branch_name
stringclasses
22 values
content
stringlengths
18
81.8M
directory_id
stringlengths
40
40
languages
sequencelengths
1
36
num_files
int64
1
7.38k
repo_language
stringclasses
151 values
repo_name
stringlengths
7
101
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<repo_name>cart3ch/badm_iimtrichy_18-20<file_sep>/RcmdrMarkdown.Rmd <!-- R Commander Markdown Template --> Replace with Main Title ======================= ### Your Name ### `r as.character(Sys.Date())` ```{r echo=FALSE} # include this code chunk as-is to set options knitr::opts_chunk$set(comment=NA, prompt=TRUE, out.width=750, fig.height=8, fig.width=8) library(Rcmdr) library(car) library(RcmdrMisc) ``` ```{r echo=FALSE} # include this code chunk as-is to enable 3D graphs library(rgl) knitr::knit_hooks$set(webgl = hook_webgl) ``` ```{r} Duncan <- read.table("/home/cart3ch/rwork/rprojects/badm_iimtrichy_18-20/data/Duncan.csv", header = TRUE, sep = ",", na.strings = "NA", dec = ".", strip.white = TRUE) ``` ```{r} summary(Duncan) ``` ```{r} cor(Duncan[, c("education", "income", "prestige")], use = "complete") ``` ```{r} cor(Duncan[, c("education", "income", "prestige")], use = "complete") ``` ```{r} Boxplot(~prestige, data = Duncan, id = list(method = "y")) ``` ```{r} Boxplot(prestige ~ type, data = Duncan, id = list(method = "y")) ``` ```{r} with(Duncan, Hist(prestige, groups = type, scale = "frequency", breaks = "Sturges", col = "darkgray")) ``` <file_sep>/RcmdrMarkdown.md <!-- R Commander Markdown Template --> Replace with Main Title ======================= ### Your Name ### 2019-09-17 ```r > Duncan <- read.table("/home/cart3ch/rwork/rprojects/badm_iimtrichy_18-20/data/Duncan.csv", + header = TRUE, sep = ",", na.strings = "NA", dec = ".", strip.white = TRUE) ``` ```r > summary(Duncan) ``` ``` Name type income education accountant : 1 blue-collar :21 Min. : 7.00 Min. : 7.00 architect : 1 prof,tech,manag:18 1st Qu.:21.00 1st Qu.: 26.00 author : 1 white-collar : 6 Median :42.00 Median : 45.00 auto.repairman: 1 Mean :41.87 Mean : 52.56 banker : 1 3rd Qu.:64.00 3rd Qu.: 84.00 barber : 1 Max. :81.00 Max. :100.00 (Other) :39 prestige Min. : 3.00 1st Qu.:16.00 Median :41.00 Mean :47.69 3rd Qu.:81.00 Max. :97.00 ``` ```r > cor(Duncan[, c("education", "income", "prestige")], use = "complete") ``` ``` education income prestige education 1.0000000 0.7245124 0.8519156 income 0.7245124 1.0000000 0.8378014 prestige 0.8519156 0.8378014 1.0000000 ``` ```r > cor(Duncan[, c("education", "income", "prestige")], use = "complete") ``` ``` education income prestige education 1.0000000 0.7245124 0.8519156 income 0.7245124 1.0000000 0.8378014 prestige 0.8519156 0.8378014 1.0000000 ``` ```r > Boxplot(~prestige, data = Duncan, id = list(method = "y")) ``` <img src="figure/unnamed-chunk-7-1.png" title="plot of chunk unnamed-chunk-7" alt="plot of chunk unnamed-chunk-7" width="750" /> ```r > Boxplot(prestige ~ type, data = Duncan, id = list(method = "y")) ``` <img src="figure/unnamed-chunk-8-1.png" title="plot of chunk unnamed-chunk-8" alt="plot of chunk unnamed-chunk-8" width="750" /> ``` [1] "27" "19" "24" "9" ``` ```r > with(Duncan, Hist(prestige, groups = type, scale = "frequency", breaks = "Sturges", + col = "darkgray")) ``` <img src="figure/unnamed-chunk-9-1.png" title="plot of chunk unnamed-chunk-9" alt="plot of chunk unnamed-chunk-9" width="750" />
18d3fcbb7e7f95e964d24b9e48adc12416af5439
[ "RMarkdown", "Markdown" ]
2
RMarkdown
cart3ch/badm_iimtrichy_18-20
cabc87afff7f37b1999317a9401069fff2c15c1f
54d22a8c8fafb2c09e49345d435ea09354728bc3
refs/heads/master
<repo_name>FRCayetano/Genera<file_sep>/Genera/Trigger/Pers_IngresoAgencia_Lineas_DTrig.sql SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: <COLLET, Gaëtan> -- Create date: <23/07/2015> -- Description: <Actualizar el importe total de un ingresoAgencia despues de eliminar una linea> -- ============================================= CREATE TRIGGER [dbo].[Pers_IngresoAgencia_Lineas_DTrig] ON [dbo].[Pers_IngresoAgencia_Lineas] AFTER DELETE AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON; DECLARE @IdIngresoAgencia INT DECLARE @IdIngresoAgenciaLinea INT DECLARE cursor_majImporte CURSOR FOR SELECT IdIngresoAgencia, IdIngresoAgenciaLinea FROM DELETED OPEN cursor_majImporte FETCH NEXT FROM cursor_majImporte INTO @IdIngresoAgencia, @IdIngresoAgenciaLinea WHILE @@FETCH_STATUS = 0 BEGIN IF EXISTS (SELECT * FROM Pers_IngresoAgencia_Cabecera WHERE IdIngresoAgencia = @IdIngresoAgencia) BEGIN UPDATE Pers_IngresoAgencia_Cabecera SET ImporteTotal = (SELECT ISNULL(SUM(Importe),0) FROM Pers_IngresoAgencia_Lineas WHERE IdIngresoAgencia = @IdIngresoAgencia) WHERE IdIngresoAgencia = @IdIngresoAgencia END FETCH NEXT FROM cursor_majImporte INTO @IdIngresoAgencia, @IdIngresoAgenciaLinea END CLOSE cursor_majImporte DEALLOCATE cursor_majImporte END GO <file_sep>/Genera/Stored/PPers_PPedidos_Cli_Lineas_I.sql USE [GENERA] GO /****** Object: StoredProcedure [dbo].[PPers_PPedidos_Cli_Lineas_I] Script Date: 29/06/2015 18:21:20 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER PROCEDURE [dbo].[PPers_PPedidos_Cli_Lineas_I] @IdPedido T_Id_Pedido OUTPUT, @Precio_EURO T_Precio OUTPUT, @PrecioMoneda T_Precio OUTPUT, @Descrip varchar(255) OUTPUT, @Fecha T_Fecha_Corta OUTPUT, @IdIngresoAgencia int OUTPUT --@IdIngresoAgenciaLinea int OUTPUT, --@IdProyecto T_Id_Proyecto OUTPUT AS BEGIN --DECLARE @IdPedido T_Id_Pedido --Param de la stored DECLARE @IdLinea T_Id_Linea DECLARE @IdArticulo T_Id_Articulo = 0 DECLARE @IdArticuloCli T_Id_Articulo = NULL DECLARE @IdAlmacen T_Id_Almacen = 0 DECLARE @Cantidad T_Decimal_2 = 1 DECLARE @Precio T_Precio = 0 --Param de la stored --DECLARE @Precio_EURO T_Precio = @PrecioMoneda --DECLARE @PrecioMoneda T_Precio = 0 DECLARE @Descuento T_Decimal = 0 DECLARE @IdIva T_Id_Iva = 0 DECLARE @IdEstado T_Id_Estado = 0 DECLARE @IdSituacion T_Id_Situacion = 0 DECLARE @IdEmbalaje T_Id_Articulo = NULL DECLARE @CantidadEmbalaje T_Cantidad_Embalaje = 0 DECLARE @Observaciones Varchar(255) = NULL --DECLARE @Descrip Varchar(255) = NULL --Param de la stored DECLARE @Comision T_Decimal = 0 DECLARE @IdAlbaran T_Id_Albaran = NULL DECLARE @FechaAlbaran T_Fecha_Corta = NULL DECLARE @IdFactura T_Id_Factura = NULL DECLARE @FechaFactura T_Fecha_Corta = NULL DECLARE @CantidadLotes T_Decimal_2 = NULL DECLARE @Marca T_Id_Doc = NULL DECLARE @EmbalajeFinal T_Id_Articulo = NULL DECLARE @CantidadEmbalajeFinal T_Cantidad_Embalaje = 0 DECLARE @Descrip2 Varchar(255) = NULL DECLARE @PesoNeto T_Decimal_2 = 0 DECLARE @PesoEmbalaje T_Decimal_2 = 0 DECLARE @PesoEmbalajeFinal T_Decimal_2 = 0 DECLARE @Orden int = 0 DECLARE @TotalComision T_Decimal = 0 DECLARE @Path varchar(50) = NULL DECLARE @DtoLP1 T_Decimal = 0 DECLARE @DtoLP2 T_Decimal = 0 DECLARE @DtoGD T_Decimal = 0 DECLARE @DtoMan T_Decimal = 0 DECLARE @ConjManual T_Booleano = 0 DECLARE @IdDocPadre T_Id_Doc = NULL DECLARE @IdFase T_IdFase = NULL DECLARE @IdProyecto_Produccion T_Id_Proyecto_Produccion = NULL DECLARE @CuentaArticulo T_Cuenta_Corriente = NULL DECLARE @TipoUnidadPres T_Tipo_Cantidad = NULL DECLARE @UnidadesStock T_Decimal_2 = 0 DECLARE @UnidadesPres T_Decimal_2 = 0 DECLARE @Precio_EuroPres T_Precio = 0 DECLARE @PrecioMonedaPres T_Precio = 0 DECLARE @IdOrdenCarga int = NULL DECLARE @IdOferta T_Id_Oferta = NULL DECLARE @Revision smallint = NULL DECLARE @IdOfertaLinea T_Id_Linea = NULL DECLARE @RefCliente Varchar(50) = NULL DECLARE @NumPlano Varchar(50) = NULL DECLARE @IdParte T_Id_Parte = NULL DECLARE @IdSeguimiento int = NULL DECLARE @IdConceptoCertif int = NULL DECLARE @NumBultos int = NULL DECLARE @IdTipoOperacion smallint = NULL DECLARE @IdFacturaCertif T_Id_Factura = 0 DECLARE @UdsCarga T_Decimal_2 = 0 DECLARE @IdEmbalaje_Disp T_Id_Articulo = NULL DECLARE @IdOrdenRecepcion int = NULL DECLARE @CantRecep float = 0 DECLARE @NumBultosFinal int = 0 DECLARE @DtoLP3 T_Decimal = 0 DECLARE @DtoLP4 T_Decimal = 0 DECLARE @DtoLP5 T_Decimal = 0 DECLARE @UdStockCarga T_Decimal_2 = NULL DECLARE @UdStockRecep T_Decimal_2 = NULL DECLARE @IdMaquina T_Id_Articulo = NULL DECLARE @IdDoc T_Id_Doc = NULL DECLARE @Usuario T_CEESI_Usuario = NULL DECLARE @FechaInsertUpdate T_CEESI_Fecha_Sistema = NULL BEGIN TRY exec PPedidos_Cli_Lineas_I @IdPedido OUTPUT , @IdLinea OUTPUT , @IdArticulo , @IdArticuloCli , @IdAlmacen , @Cantidad , @Precio , @Precio_EURO , @PrecioMoneda , @Descuento , @IdIva , @IdEstado , @IdSituacion , @IdEmbalaje , @CantidadEmbalaje , @Observaciones , @Descrip OUTPUT , @Comision , @IdAlbaran , @FechaAlbaran , @IdFactura , @FechaFactura , @CantidadLotes , @Marca , @EmbalajeFinal , @CantidadEmbalajeFinal , @Descrip2 , @PesoNeto , @PesoEmbalaje , @PesoEmbalajeFinal , @Orden , @TotalComision , @Path , @DtoLP1 , @DtoLP2 , @DtoGD , @DtoMan , @ConjManual , @IdDocPadre , @IdFase , @IdProyecto_Produccion , @CuentaArticulo , @TipoUnidadPres , @UnidadesStock , @UnidadesPres , @Precio_EuroPres , @PrecioMonedaPres , @IdOrdenCarga , @IdOferta , @Revision , @IdOfertaLinea , @RefCliente , @NumPlano , @IdParte , @IdSeguimiento , @IdConceptoCertif , @NumBultos , @IdTipoOperacion , @IdFacturaCertif , @UdsCarga , @IdEmbalaje_Disp , @IdOrdenRecepcion , @CantRecep , @NumBultosFinal , @DtoLP3 , @DtoLP4 , @DtoLP5 , @UdStockCarga , @UdStockRecep , @IdMaquina , @IdDoc OUTPUT , @Usuario , @FechaInsertUpdate --Añadir la fecha de imputacion del ingreso update Conf_Pedidos_Cli_Lineas set pFechaIngreso = @Fecha where IdPedido = @Idpedido and IdLinea = @IdLinea --Añadir la linea de pedido asociada a la linea de IngresoAgencia actual --update Pers_IngresoAgencia_Lineas set IdPedidoLinea = @IdLinea where IdIngresoAgencia = @IdIngresoAgencia and IdProyecto = @IdProyecto /************************************************************************************************************* Ejucatar stored para hacer el desgloce analitico *************************************************************************************************************/ DECLARE @Objeto varchar(50) = 'Pedido_Linea' Exec PPERS_DesgloceLinea_Pedidos @Objeto, @IdPedido, @IdLinea, @IdDoc, @Fecha, @Descrip RETURN -1 END TRY BEGIN CATCH IF @@TRANCOUNT >0 BEGIN ROLLBACK TRAN END DECLARE @CatchError NVARCHAR(MAX) SET @CatchError=dbo.funImprimeError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE()) RAISERROR(@CatchError,12,1) RETURN 0 END CATCH END <file_sep>/Genera/Stored/pPers_Importar_Datos_ImportGasto.sql USE [GENERA] GO /****** Object: StoredProcedure [dbo].[pPers_Importar_Datos_ImportGasto] Script Date: 25/06/2015 18:24:39 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: <<NAME>> -- Create date: <08/06/2015> -- Description: <Importar los datos de los gastos que vienen de las agencias> -- ============================================= CREATE PROCEDURE [dbo].[pPers_Importar_Datos_ImportGasto] -- Add the parameters for the stored procedure here @ClaveImportacion varchar(255), @IdProveedor T_Id_Proveedor --@Ubicacion varchar(255) AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON; DECLARE @IdLineaImportacion smallint DECLARE @IdProyectoAgencia varchar(255) DECLARE @IdProyectoERP T_Id_Proyecto DECLARE @IdGastoAgencia smallint DECLARE @Importe Real DECLARE @GastoAgenciaLinea smallint DECLARE @ImporteTotal DECIMAL BEGIN TRY DECLARE cursor_Import CURSOR FOR select IdLineaImportacion, IdGastoAgencia, IdProyectoAgencia, Importe from Pers_Log_Importacion_GastoAgencia where ClaveImportacion = @ClaveImportacion OPEN cursor_Import FETCH cursor_Import INTO @IdLineaImportacion, @IdGastoAgencia, @IdProyectoAgencia, @Importe WHILE @@FETCH_STATUS = 0 BEGIN if EXISTS (select 1 from Pers_Proyectos_Agencias_Gastos where IdProyectoAgencia = @IdProyectoAgencia and IdProveedor = @IdProveedor) BEGIN set @IdProyectoERP = (select IdProyecto from Pers_Proyectos_Agencias_Gastos where IdProyectoAgencia = @IdProyectoAgencia) set @GastoAgenciaLinea = (select isnull(max(IdGastoAgenciaLinea), 0) +1 from Pers_GastosAgencia_Lineas where IdGastoAgencia = @IdGastoAgencia) insert into Pers_GastosAgencia_Lineas(IdGastoAgencia, IdGastoAgenciaLinea, IdProyecto, IdProyectoAgencia, Importe) values (@IdGastoAgencia, @GastoAgenciaLinea, @IdProyectoERP, @IdProyectoAgencia, @Importe) END ELSE BEGIN update Pers_Log_Importacion_GastoAgencia set Texto_error = 'No existe correspondencia para el codigo de Proyecto Agencia : ' + @IdProyectoAgencia where IdLineaImportacion = @IdLineaImportacion and IdGastoAgencia = @IdGastoAgencia END FETCH cursor_Import INTO @IdLineaImportacion, @IdGastoAgencia, @IdProyectoAgencia, @Importe END CLOSE cursor_Import DEALLOCATE cursor_Import --MAJ de la fecha de importacion del excel y del importe total Set @ImporteTotal = (select sum(Importe) from Pers_GastosAgencia_Lineas where IdGastoAgencia = @IdGastoAgencia) update Pers_GastosAgencia_Cabecera set FechaImport = GETDATE() where IdGastoAgencia = @IdGastoAgencia update Pers_GastosAgencia_Cabecera set ImporteTotal = @ImporteTotal where IdGastoAgencia = @IdGastoAgencia RETURN -1 END TRY BEGIN CATCH IF @@TRANCOUNT >0 BEGIN ROLLBACK TRAN END DECLARE @CatchError NVARCHAR(MAX) SET @CatchError=dbo.funImprimeError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE()) RAISERROR(@CatchError,12,1) RETURN 0 END CATCH END GO <file_sep>/Genera/Stored/pPers_FijarIngresoMensualProyecto.sql USE [GENERA] GO /****** Object: StoredProcedure [dbo].[pPers_FijarIngresoMensualProyecto] Script Date: 25/06/2015 18:23:42 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: <NAME> -- Create date: 28/05/2015 -- Description: Fija Ingreso Mensual Proyecto -- ============================================= CREATE PROCEDURE [dbo].[pPers_FijarIngresoMensualProyecto] ( @IdPresupuesto int, @IdEquipo int, @IdProyecto int, @IngresoMensual float ) AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON; BEGIN try UPDATE Pers_Presupuestos_Equipos_Proyectos set IngresosEnero = @IngresoMensual, IngresosFebrero = @IngresoMensual, IngresosMarzo = @IngresoMensual, IngresosAbril = @IngresoMensual, IngresosMayo = @IngresoMensual, IngresosJunio = @IngresoMensual, IngresosJulio= @IngresoMensual, IngresosAgosto= @IngresoMensual, IngresosSeptiembre= @IngresoMensual, IngresosOctubre= @IngresoMensual, IngresosNoviembre= @IngresoMensual, IngresosDiciembre= @IngresoMensual where IdPresupuesto = @IdPresupuesto and IdEquipo = @IdEquipo and IdProyecto = @IdProyecto RETURN -1 END TRY BEGIN CATCH IF @@TRANCOUNT >0 BEGIN ROLLBACK TRAN END DECLARE @CatchError NVARCHAR(MAX) SET @CatchError=dbo.funImprimeError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE()) RAISERROR(@CatchError,12,1) RETURN 0 END CATCH END GO <file_sep>/Genera/Trigger/Pers_Pers_Presupuestos_Gastos_UTrig.sql USE [GENERA] GO /****** Object: Trigger [dbo].[Pers_Pers_Presupuestos_Gastos_UTrig] Script Date: 08/07/2015 14:30:10 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: <<NAME>> -- Create date: <07/07/2015> -- Description: <Impedir la modificacion de la estructura de un presupuesto cerrado> -- ============================================= CREATE TRIGGER [dbo].[Pers_Pers_Presupuestos_Gastos_UTrig] ON [dbo].[Pers_Presupuestos_Gastos] FOR UPDATE AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON; --No vale para UPDATE masivo que afecten a varios presupuestos porque el ROLLBACK se lanza si hay un presupuesto cerrado --Hay que desactivar el trigger o poner el campo cerrar de Pers_Presupuestos a 0 para modificar la estructura del presupuesto IF EXISTS (SELECT 1 FROM INSERTED i INNER JOIN Pers_Presupuestos pp ON i.IdPresupuesto = pp.IdPresupuesto AND pp.Cerrado = 1) BEGIN PRINT dbo.Traducir(32705, 'No se puede modificar la estructura o los datos de un presupuesto cerrado.') ROLLBACK TRAN RETURN END END GO <file_sep>/Genera/Stored/pPERS_Get_Cambio_DelDia_EuroDolar.sql USE [GENERA] GO /****** Object: StoredProcedure [dbo].[pPERS_Get_Cambio_DelDia_EuroDolar] Script Date: 25/06/2015 18:24:27 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: <<NAME>> -- Create date: <18/06/2015> -- Description: <Obtener el cambio del dia desde la pagina web de la European Central Bank -- Hay que tener en cuenta que el valor del cambio se refresque cada dia entre las dos y las tres de la tarde> -- ============================================= CREATE PROCEDURE [dbo].[pPERS_Get_Cambio_DelDia_EuroDolar] AS BEGIN DECLARE @URL VARCHAR(8000) SELECT @URL = 'http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml' DECLARE @Response varchar(8000) DECLARE @XML xml DECLARE @Obj int DECLARE @Result int DECLARE @HTTPStatus int DECLARE @ErrorMsg varchar(MAX) DECLARE @vXML xml DECLARE @DateCambio T_Fecha_Corta DECLARE @CodigoISO varchar(10) DECLARE @ImporteCambio DECIMAL(18,4) BEGIN TRY /* 1- Recuperar el XML que contiene los cambios del dia desde la pagina de la European Central Bank 2- Crear una tabla temporal para almacenar el XML para despues leerlo 3- Recoger los nodos Cubo del XML pero filtrar sobre el USD porque solo queremos este*/ IF OBJECT_ID('tempdb..#xml') IS NOT NULL DROP TABLE #xml CREATE TABLE #xml ( yourXML XML ) EXEC @Result = sp_OACreate 'MSXML2.XMLHttp', @Obj OUT EXEC @Result = sp_OAMethod @Obj, 'open', NULL, 'GET', @URL, false EXEC @Result = sp_OAMethod @Obj, 'setRequestHeader', NULL, 'Content-Type', 'application/x-www-form-urlencoded' EXEC @Result = sp_OAMethod @Obj, send, NULL, '' EXEC @Result = sp_OAGetProperty @Obj, 'status', @HTTPStatus OUT INSERT #xml ( yourXML ) EXEC @Result = sp_OAGetProperty @Obj, 'responseXML.xml'--, @Response OUT ;WITH XMLNAMESPACES( 'http://www.gesmes.org/xml/2002-08-01' as gesmes, DEFAULT 'http://www.ecb.int/vocabulary/2002-08-01/eurofxref' ) SELECT @DateCambio = x.Time, @CodigoISO = x.Currency, @ImporteCambio = x.Rate FROM (SELECT T.rows.value('@time', 'datetime') AS [Time], T2.rows.value('@currency', 'nvarchar(100)') AS [Currency], T2.rows.value('@rate', 'float') AS [Rate] FROM #xml CROSS APPLY yourXML.nodes('/gesmes:Envelope/Cube/*') T(rows) CROSS APPLY T.rows.nodes('Cube') as T2(rows) )x WHERE x.Currency = 'USD' /*Comprobar que la fecha de la variable @DateCambio esta la misma que la fecha del dia, si no, no hacer nada y esperar la proxima ejecucion de la stored para actualizar el cambio*/ if CONVERT (char(10), @DateCambio, 103) = CONVERT (char(10), getdate(), 103) AND NOT EXISTS (SELECT 1 FROM Moneda WHERE ValidezDesde = cast(getdate() As Date)) BEGIN update Moneda SET ImporteVenta_EURO = @ImporteCambio, ValidezDesde = @DateCambio, ValidezHasta = @DateCambio where CodigoISO = @CodigoISO END RETURN -1 END TRY BEGIN CATCH IF @@TRANCOUNT >0 BEGIN ROLLBACK TRAN END DECLARE @CatchError NVARCHAR(MAX) SET @CatchError=dbo.funImprimeError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE()) RAISERROR(@CatchError,12,1) RETURN 0 END CATCH END GO <file_sep>/Genera/Pivot table imputacion empleado.sql --C DECLARE @cols AS NVARCHAR(MAX), @query AS NVARCHAR(MAX) select @cols = STUFF((SELECT ',' + QUOTENAME(IdProyecto) from Pers_Importa_Dedicacion_Empleado_Proyecto_Lineas group by IdProyecto order by IdProyecto FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)') ,1,1,'') IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.VIEWS WHERE TABLE_NAME = 'vPers_Imputaciones_Empleado') DROP VIEW vPers_Imputaciones_Empleado set @query = N'Create view vPers_Imputaciones_Empleado as SELECT IdEmpleado, ' + @cols + N' from ( select IdEmpleado, IdProyecto, PorcentajeDedic from Pers_Importa_Dedicacion_Empleado_Proyecto_Lineas ) x pivot ( min(PorcentajeDedic) for IdProyecto in (' + @cols + N') ) p ' exec sp_executesql @query set @query = 'zpermisos vPers_Imputaciones_Empleado' exec sp_executesql @query select * from vPers_Imputaciones_Empleado<file_sep>/Genera/Scripts migracion datos/INSERT Pers_Presupuesto_Equipos_Proyectos.sql begin tran insert into Pers_Presupuestos_Equipos (IdPresupuesto, IdEquipo, PorcGastosFijos, PorcGastosEstructura,IngresosEnero, IngresosFebrero, IngresosMarzo, IngresosAbril, IngresosMayo, IngresosJunio, IngresosJulio, IngresosAgosto, IngresosSeptiembre, IngresosOctubre, IngresosNoviembre, IngresosDiciembre) select 1, IdEquipo, NULL, NULL,0,0,0,0,0,0,0,0,0,0,0,0 from Pers_Equipos where IDEquipo not in (select distinct Idequipo from Pers_Presupuestos_Equipos) and IdEquipo > 8 insert into Pers_Presupuestos_Equipos_Proyectos(IdPresupuesto, IdEquipo, IdProyecto, Porcentaje, IngresosEnero, IngresosFebrero, IngresosMarzo, IngresosAbril, IngresosMayo, IngresosJunio, IngresosJulio, IngresosAgosto, IngresosSeptiembre, IngresosOctubre, IngresosNoviembre, IngresosDiciembre) select x.Presupuesto, x.IdEquipo, x.IdProyecto, x.Porcentaje,0,0,0,0,0,0,0,0,0,0,0,0 from ( select distinct 1 as Presupuesto, IdEquipo, RIGHT('00000'+cast(IdProyecto as nvarchar(10)),4) as IdProyecto, 100 as Porcentaje from OPENROWSET('Microsoft.ACE.OLEDB.12.0', 'Excel 12.0;HDR=YES;Database=C:\TEMP\Maestro.xlsx;', 'SELECT * FROM [Definitivo$]') x where proyecto not in ('TALKING','PT CLASSIC','PT GOLD') union select distinct 1 as Presupuesto, IdEquipo, case when proyecto = 'PT CLASSIC' or proyecto = 'PT GOLD' then '0034' when proyecto = 'TALKING' then '0048' END as IdProyecto, 100 as Porcentaje from OPENROWSET('Microsoft.ACE.OLEDB.12.0', 'Excel 12.0;HDR=YES;Database=C:\TEMP\Maestro.xlsx;', 'SELECT * FROM [Definitivo$]') x where proyecto in ('TALKING','PT CLASSIC','PT GOLD') ) x order by x.IdEquipo commit tran<file_sep>/Genera/Stored/PPers_GenerarPedidoProveedor_From_Ingreso.sql USE [GENERA] GO /****** Object: StoredProcedure [dbo].[PPers_GenerarPedidoProveedor_From_Ingreso] Script Date: 29/06/2015 18:19:52 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: <<NAME>> -- Create date: <01/06/2015> -- Description: <Permite la creacion de los pedidos de proveedores (terceros) a la hora de generar los pedidos a partir de los ingresos de una agencia> -- ============================================= ALTER PROCEDURE [dbo].[PPers_GenerarPedidoProveedor_From_Ingreso] @IdEmpresa T_Id_Empresa OUTPUT ,@Fecha T_Fecha_Corta OUTPUT ,@IdEmpleado T_Id_Empleado OUTPUT ,@IdDepartamento T_Id_Departamento OUTPUT ,@IdIngresoAgencia INT OUTPUT ,@IdMoneda T_Id_Moneda AS BEGIN DECLARE @IdPedido T_Id_Pedido = 0 --DECLARE @IdEmpresa T_Id_Empresa = 0 DECLARE @AnoNum T_AñoNum = 1999 DECLARE @NumPedido T_Id_Pedido = 0 --DECLARE @Fecha T_Fecha_Corta = GETDATE() DECLARE @IdProveedor T_Id_Proveedor DECLARE @IdPedidoProv VARCHAR(50) = NULL DECLARE @IdContacto INT = NULL DECLARE @DescripcionPed VARCHAR(255) = NULL DECLARE @IdLista T_Id_Lista = 0 --DECLARE @IdEmpleado T_Id_Empleado = NULL --DECLARE @IdDepartamento T_Id_Departamento = NULL DECLARE @IdTransportista T_Id_Proveedor = NULL --DECLARE @IdMoneda T_Id_Moneda = 0 DECLARE @FormaPago T_Forma_Pago = 0 DECLARE @Descuento REAL = 0 DECLARE @ProntoPago REAL = 0 DECLARE @IdPortes T_Id_Portes = 'D' DECLARE @IdIva T_Id_Iva = 0 DECLARE @IdEstado T_Id_Estado = 0 DECLARE @IdSituacion T_Id_Situacion = 0 DECLARE @FechaEntrega T_Fecha_Corta = @Fecha DECLARE @FechaEntregaTope T_Fecha_Corta = @Fecha DECLARE @Observaciones VARCHAR(255) = NULL DECLARE @IdCentroCoste T_Id_CentroCoste = NULL DECLARE @IdCentroProd T_CentroProductivo = NULL DECLARE @IdCentroImp T_CentroImponible = NULL DECLARE @Codigo VARCHAR(50) = NULL DECLARE @Cambio T_Precio = NULL DECLARE @CambioEuros T_Precio = 1 DECLARE @CambioBloqueado T_Booleano = 0 DECLARE @Confirmado T_Booleano = 0 DECLARE @IdCentroCalidad T_CentroCalidad = NULL --DECLARE @IdProyecto T_Id_Proyecto = '1' DECLARE @Inmovilizado T_Booleano = 0 DECLARE @SeriePedido T_Serie = 0 DECLARE @Bloqueado T_Booleano = 0 DECLARE @IdMotivoBloqueo INT = NULL DECLARE @IdEmpleadoBloqueo T_Id_Empleado = NULL DECLARE @IdOrden T_Id_Orden = 0 DECLARE @IdBono T_Id_Bono = NULL DECLARE @EnvioAObra T_Booleano = 0 DECLARE @IdTipoProv T_Id_Tipo = 0 DECLARE @PorcentajeProveedor REAL DECLARE @ImporteLineaPedido T_Precio = 0 DECLARE @ImportePedido DECIMAL DECLARE @Msg_err VARCHAR(255) DECLARE @P0 NVARCHAR(1000) DECLARE @CadenaStr NVARCHAR(4000) DECLARE @TipoImport VARCHAR(255) = 'Ingreso' DECLARE @Descrip_Proyecto VARCHAR(255) DECLARE @UpFront DECIMAL DECLARE @UpFrontAcumulado DECIMAL DECLARE @GastosPendientes DECIMAL DECLARE @IdMonedaProveedor T_Id_Moneda DECLARE @CambioDelDia DECIMAL(18, 4) DECLARE @Precio_EURO T_Precio DECLARE @PrecioMoneda T_Precio /*********************************************************************************************************************** Comprobacion para ver si existe un tercero asociado a ese proyecto Si existe : continuar la creacion de pedido Si no : no hacer nada ************************************************************************************************************************/ BEGIN TRY --Declaramos el cursor para recoger todos los proyectos que tengan ingresos en el IngresoAgencia DECLARE @IdProyecto T_Id_Proyecto DECLARE @ImporteProyecto DECIMAL(18,4) DECLARE cursor_ingresoAgenciaLineas CURSOR FOR select distinct il.IdProyecto, SUM(il.Importe) from Pers_IngresoAgencia_Lineas il inner join Proyectos p on il.IdProyecto = p.IdProyecto where il.IdIngresoAgencia = @IdIngresoAgencia GROUP BY il.IdProyecto OPEN cursor_ingresoAgenciaLineas FETCH cursor_ingresoAgenciaLineas INTO @IdProyecto, @ImporteProyecto WHILE @@FETCH_STATUS = 0 BEGIN --Obtener el ID del proveedor asociado al proyecto @IdProyecto SELECT @IdProveedor = ISNULL(IdProveedor, - 1) FROM Proyectos WHERE IdProyecto = @IdProyecto IF (@IdProveedor <> - 1) BEGIN SET @IdContacto = ( SELECT IdContacto FROM Prov_Datos WHERE IdProveedor = @IdProveedor ) --Recuperacion de la propriedades del proyecto (UpFront, GastosPendiente, Porcentaje tercero...) SELECT @PorcentajeProveedor = cp.Pers_PorcentajeTercero ,@UpFront = ISNULL(cp.Pers_UpFront, 0) ,@UpFrontAcumulado = ISNULL(cp.Pers_UpFrontAcumulado, 0) ,@GastosPendientes = ISNULL(cp.Pers_GastosAcumulado, 0) ,@DescripcionPed = 'Proyecto ' + p.Descrip + ' : ' + p.IdProyecto FROM Proyectos p INNER JOIN Conf_Proyectos cp ON p.IdProyecto = cp.IdProyecto WHERE p.IdProyecto = @IdProyecto --Gestion de la moneda SET @ImporteLineaPedido = @ImporteProyecto * (@PorcentajeProveedor / 100) SET @IdMonedaProveedor = ( SELECT ISNULL(IdMoneda,1) FROM Prov_Datos_Economicos WHERE IdProveedor = @IdProveedor ) SET @CambioDelDia = ( SELECT Cambio FROM funDameCambioMoneda(2, GETDATE()) ) IF @IdMonedaProveedor > 1 BEGIN SET @Precio_EURO = 0 SET @PrecioMoneda = @ImporteLineaPedido --Si la moneda del Excel es el euro, convert el importe porque queremos crear un pedido en dolare IF @IdMoneda = 1 BEGIN SET @PrecioMoneda = (@PrecioMoneda * @CambioDelDia) END END IF @IdMonedaProveedor = 1 BEGIN --Si la moneda del excel nos viene en dolares, convertir el importe en EURO IF @IdMoneda > 1 BEGIN SET @Precio_EURO = @ImporteLineaPedido / @CambioDelDia END IF @IdMoneda = 1 BEGIN SET @Precio_EURO = @ImporteLineaPedido END SET @PrecioMoneda = @Precio_EURO END --Miramos si ya existe un pedido para ese proveedor que no sea facturado --Si un pedido existe, añadimos una linea si no creamos una nueva cabecera u despues la linea DECLARE @NbExistPedido INT SELECT @NbExistPedido = count(cab.Idpedido) FROM Pedidos_Prov_Cabecera cab INNER JOIN Pedidos_Prov_Lineas li ON cab.IdPedido = li.IdPedido WHERE cab.IdProveedor = @IdProveedor AND ( li.IdEstado BETWEEN 0 AND 6 ) DECLARE @IdLinea T_Id_Linea = 0 IF (@NbExistPedido = 0) BEGIN Set @IdPedido = 0 EXEC pPedidos_Prov_Cabecera_I @IdPedido OUTPUT ,@IdEmpresa ,@AnoNum ,@NumPedido ,@Fecha ,@IdProveedor ,@IdPedidoProv ,@IdContacto ,@DescripcionPed ,@IdLista ,@IdEmpleado ,@IdDepartamento ,@IdTransportista ,@IdMonedaProveedor ,@FormaPago ,@Descuento ,@ProntoPago ,@IdPortes ,@IdIva ,@IdEstado ,@IdSituacion ,@FechaEntrega ,@FechaEntregaTope ,@Observaciones ,@IdCentroCoste ,@IdCentroProd ,@IdCentroImp ,@Codigo ,@CambioDelDia ,@CambioDelDia ,@CambioBloqueado ,@Confirmado ,@IdCentroCalidad ,@IdProyecto ,@Inmovilizado ,@SeriePedido ,@Bloqueado ,@IdMotivoBloqueo ,@IdEmpleadoBloqueo ,@IdOrden ,@IdBono ,@EnvioAObra ,@IdTipoProv ,NULL ,NULL ,NULL EXEC PPERS_PPedidos_Prov_Lineas_I @IdPedido ,@Precio_EURO ,@PrecioMoneda ,@DescripcionPed ,@FechaEntrega ,@IdIngresoAgencia ,@TipoImport END ELSE BEGIN --Si ya existe un pedido para el tercero, recuperamos el id de este pedido y añadimos una linea al pedido SELECT @IdPedido = MIN(cab.Idpedido) FROM Pedidos_Prov_Cabecera cab INNER JOIN Pedidos_Prov_Lineas li ON cab.IdPedido = li.IdPedido WHERE cab.IdProveedor = @IdProveedor AND ( li.IdEstado BETWEEN 0 AND 6 ) EXEC PPERS_PPedidos_Prov_Lineas_I @IdPedido ,@Precio_EURO ,@PrecioMoneda ,@DescripcionPed ,@FechaEntrega ,@IdIngresoAgencia ,@TipoImport END --Recuperar el importe total del pedido para asegurarse de que, a la hora de descontar el upfront y los gastos, que no vamos a crear un pedido con un importe negativo SET @ImportePedido = ( SELECT sum(PrecioMoneda) FROM Pedidos_Prov_Lineas WHERE IdPedido = @IdPedido ) --Si existe, descontar el UpFront que el Indie recibio para desarollar el juego y actualizamos el campo UpFrontAcumulado de la tabla Conf_proyectos --Creamos una linea en el pedido proveedor con el importe negativo que vamos a descontar DECLARE @ImporteLineaDescontada DECIMAL(18,4) DECLARE @IdLineaMovimientoHistorico INT DECLARE @IdMonedaProyecto INT DECLARE @QuedaUpFront DECIMAL(18,4) SET @IdMonedaProyecto = ( SELECT ISNULL(Pers_Moneda, 1) FROM Conf_Proyectos WHERE IdProyecto = @IdProyecto ) --Entramos aqui si queda upFront a descontar para el proyecto IF @UpFront <> 0 AND @UpFrontAcumulado < @UpFront BEGIN SET @DescripcionPed = 'UpFront del proyecto : ' + @IdProyecto SET @TipoImport = '' --Si el importe del pedido esta superior al upfront restante, podemos descontar todo el upFront restante en el pedido IF @ImportePedido >= (@UpFront - @UpFrontAcumulado) BEGIN SET @ImportePedido = @ImportePedido - (@UpFront - @UpFrontAcumulado) SET @ImporteLineaDescontada = (@UpFront - @UpFrontAcumulado) * - 1 UPDATE Conf_Proyectos SET Pers_UpfrontAcumulado = Pers_UpFront WHERE IdProyecto = @IdProyecto END ELSE BEGIN -- Queda mas UpFront que el importe total del pedido, asi no se puede descontar todo el UpFront restante -- En este caso ponemos el pedido a zero y descontamos el importe del pedido al UpFront SET @ImporteLineaDescontada = @ImporteLineaPedido * - 1 SET @ImportePedido = @ImportePedido - (@ImporteLineaDescontada * - 1) UPDATE Conf_Proyectos SET Pers_UpfrontAcumulado = (@UpFrontAcumulado + (@ImporteLineaDescontada * - 1)) WHERE IdProyecto = @IdProyecto END EXEC PPERS_PPedidos_Prov_Lineas_I @IdPedido ,@ImporteLineaDescontada ,@ImporteLineaDescontada ,@DescripcionPed ,@FechaEntrega ,@IdIngresoAgencia --,@IdIngresoAgenciaLinea ,@TipoImport SET @IdLineaMovimientoHistorico = ( SELECT ISNULL(MAX(IdMovimiento), 0) FROM Pers_Historico_Mov_UpFrontGastos ) --Escribimos una linea en la tabla Pers_Historico_Mov_UpFrontGastos para seguir los movimientos de importe de UpFront y GastosPendiente INSERT INTO Pers_Historico_Mov_UpFrontGastos ( IdMovimiento ,TipoMovimiento ,Descrip ,Importe ,IdObjCabecera --,IdObjLinea ,IdProyecto ,FechaMovimiento ) VALUES ( @IdLineaMovimientoHistorico + 1 ,'UpFront' ,'Modificado tras importacion de Ingreso' ,@ImporteLineaDescontada ,@IdIngresoAgencia --,@IdIngresoAgenciaLinea ,@IdProyecto ,GETDATE() ) END --Si existe, descontar los gastos Pendientes y actualizamos el campo gastos pendientes de la tabla Conf_Proyectos IF @GastosPendientes <> 0 AND @ImportePedido > 0 BEGIN SET @DescripcionPed = 'Gastos Pendientes del proyecto : ' + @IdProyecto SET @TipoImport = '' IF @ImportePedido >= @GastosPendientes BEGIN SET @ImportePedido = @ImportePedido - @GastosPendientes SET @ImporteLineaDescontada = @GastosPendientes * - 1 UPDATE Conf_Proyectos SET Pers_GastosAcumulado = 0 WHERE IdProyecto = @IdProyecto END ELSE BEGIN SET @ImporteLineaDescontada = @ImportePedido * - 1 UPDATE Conf_Proyectos SET Pers_GastosAcumulado = (@GastosPendientes - @ImportePedido) WHERE IdProyecto = @IdProyecto SET @ImportePedido = 0 END EXEC PPERS_PPedidos_Prov_Lineas_I @IdPedido ,@ImporteLineaDescontada ,@ImporteLineaDescontada ,@DescripcionPed ,@FechaEntrega ,@IdIngresoAgencia --,@IdIngresoAgenciaLinea ,@TipoImport SET @IdLineaMovimientoHistorico = ( SELECT ISNULL(MAX(IdMovimiento), 0) FROM Pers_Historico_Mov_UpFrontGastos ) --Si existe, descontar los gastos Pendientes y actualizamos el campo gastos pendientes de la tabla Conf_Proyectos INSERT INTO Pers_Historico_Mov_UpFrontGastos ( IdMovimiento ,TipoMovimiento ,Descrip ,Importe ,IdObjCabecera --,IdObjLinea ,IdProyecto ,FechaMovimiento ) VALUES ( @IdLineaMovimientoHistorico + 1 ,'GastosPendientes' ,'Modificado tras importacion de Ingreso' ,@ImporteLineaDescontada ,@IdIngresoAgencia --,@IdIngresoAgenciaLinea ,@IdProyecto ,GETDATE() ) END END FETCH cursor_ingresoAgenciaLineas INTO @IdProyecto, @ImporteProyecto END CLOSE cursor_ingresoAgenciaLineas DEALLOCATE cursor_ingresoAgenciaLineas RETURN - 1 END TRY BEGIN CATCH IF @@TRANCOUNT > 0 BEGIN ROLLBACK TRAN END DECLARE @CatchError NVARCHAR(MAX) SET @CatchError = dbo.funImprimeError(ERROR_MESSAGE(), ERROR_NUMBER(), ERROR_PROCEDURE(), @@PROCID, ERROR_LINE()) RAISERROR ( @CatchError ,12 ,1 ) RETURN 0 END CATCH END<file_sep>/Genera/Stored/pPers_FijarGastoStaffMensual.sql USE [GENERA] GO /****** Object: StoredProcedure [dbo].[pPers_FijarGastoStaffMensual] Script Date: 25/06/2015 18:23:29 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: <NAME> -- Create date: 28/05/2015 -- Description: Fija Gasto Staff Equipo Mensual -- ============================================= CREATE PROCEDURE [dbo].[pPers_FijarGastoStaffMensual] ( @IdPresupuesto int, @IdEquipo int, @IdEquipoStaff int, @GastoMensual float ) AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON; BEGIN try UPDATE Pers_Presupuestos_Equipos_GastosStaff set GastosEnero = @GastoMensual, GastosFebrero = @GastoMensual, GastosMarzo = @GastoMensual, GastosAbril = @GastoMensual, GastosMayo = @GastoMensual, GastosJunio = @GastoMensual, GastosJulio= @GastoMensual, GastosAgosto= @GastoMensual, GastosSeptiembre= @GastoMensual, GastosOctubre= @GastoMensual, GastosNoviembre= @GastoMensual, GastosDiciembre= @GastoMensual where IdPresupuesto = @IdPresupuesto and IdEquipo = @IdEquipo and IdEquipoStaff = @IdEquipoStaff RETURN -1 END TRY BEGIN CATCH IF @@TRANCOUNT >0 BEGIN ROLLBACK TRAN END DECLARE @CatchError NVARCHAR(MAX) SET @CatchError=dbo.funImprimeError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE()) RAISERROR(@CatchError,12,1) RETURN 0 END CATCH END GO <file_sep>/Genera/VbScript ERP/Favorito Crear nuevo presupuesto.vbs Sub Initialize() gForm.Caption = "Creacion nuevo Presupuesto de gestion" End Sub Sub Show() gform.Botonera.BotonAdd "Copiar", "BotPers_Crear", , 0, True, 123 gform.Botonera.BotonAdd "Crear Presupuesto vacio", "BotPers_CrearVacio", , 0, True, 123 gform.Botonera.ActivarScripts = True gForm.Controls("Botonera").Boton("BotGuardar").Visible = False gForm.Controls("Botonera").Boton("BotNuevo").Visible = False gForm.Controls("Botonera").Boton("BotImprimir").Visible = False gForm.Controls("Botonera").Boton("BotEliminar").Visible = False lSql = "SELECT CAST(Anyo AS VARCHAR) as Anyo FROM Pers_Presupuestos UNION SELECT 'Nuevo' as Anyo" CreaCampoCombo "Pers_Anyo", gForm.Controls("panMain"), 200, 600, 3000, 300, "Copiar estructura del Año : ", 700, lSql, 600, "Anyo", 8, 0, "", 8, 1, 1, "X", "X" gForm.Width = 5000 gForm.Height = 3500 End Sub Function CreaCampoCombo(aNombre, aParent, aLeft, aTop, aWidth, aHeight, aCaption, aAnchoEtiqueta, aSQl, aAnch1, ANom1, aTD1, aAnch2, ANom2, aTD2, aNcol, aActiva, aObjOrigen, aObjPOrigen) Dim lCtrl Set lCtrl = gForm.Controls.Add("AhoraOCX.ComboUsuario", aNombre, aParent) With lCtrl .Move aLeft, aTop, aWidth, aHeight .CaptionVisible = True .CaptionWidth = aAnchoEtiqueta .CaptionControl = aCaption .C1Anchura = aAnch1 .C1Nombre = ANom1 .C1TipoDato = aTD1 .C2Anchura = aAnch2 .C2Nombre = ANom2 .C2TipoDato = aTD2 .NColumnas = aNcol .cActiva = aActiva .Descripcion = aSQL .ObjOrigen = aObjOrigen .ObjPOrigen = aObjPOrigen .CaptionWidth = 2000 .AplicaEstilo .Visible = True .Enabled = True End With End Function Sub Botonera_AfterExecute(aBotonera, aBoton) End Sub Sub Botonera_BeforeExecute(aBotonera, aBoton, aCancel) If aBoton.Name = "BotPers_Crear" Then Set lColparams = gcn.DameNewCollection IdPresupuestoNuevo = 0 If gForm.Controls("Pers_Anyo").text = "Nuevo" Then ano = 0 Else ano = CInt(gForm.Controls("Pers_Anyo").text) End If lColparams.add CInt(IdPresupuestoNuevo) lColparams.add CInt(ano) If gForm.Controls("Pers_Anyo").text = "Nuevo" Then If MsgBox("Crear una estructura de presupuesto vacia ?", vbYesNo, "Confirmacion ?") = vbNo Then aCancel = True Exit Sub End If End If If Not gcn.EjecutaStoreCol("pPers_CrearEstructuraPresupuesto", lColparams) Then MsgBox "No se ha podido crear el nuevo presupuesto" , vbCritical, "Error creando el presupuesto" Else Set nuevoPresupuesto = gCn.Obj.DameColeccion("Presupuestos_Gestion","Where IdPresupuesto = "& lColparams.item(1) &"") If Not nuevoPresupuesto Is Nothing Then nuevoPresupuesto.show End If End If End If End Sub<file_sep>/Genera/Stored/pPers_Nominas_Importar.sql USE [GENERA] GO /****** Object: StoredProcedure [dbo].[pPers_Nominas_Importar] Script Date: 13/07/2015 9:58:50 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER PROCEDURE [dbo].[pPers_Nominas_Importar] (@IdImportacion int, @Retorno varchar(400) OUTPUT) AS BEGIN TRY DECLARE @Valores TABLE (Valor varchar(100)) DECLARE @IMPORTES TABLE (IdEmpleado int, Empleado varchar(250), Importe_Bruto float, Importe_Pago float, Importe_SS float, CuentaBruto varchar(15), CuentaPago varchar(15), CuentaSS varchar(15), IdCentroCoste varchar(50), Asiento640 int, Apunte640 int, Apunte465 int, Asiento642 int) DECLARE @CC TABLE (IdEmpleado int, IdCentroCoste varchar(50), Porcentaje float) DECLARE @LOSEMPLEADOS TABLE (IdEmpleado int, IdCentroCoste varchar(50)) DECLARE @APUNTES_DESCUADRADOS TABLE (Asiento int, Apunte int, Importe float, IdDoc int) DECLARE @IdEjercicio int DECLARE @NumDigitos smallint DECLARE @CuentaBruto varchar(15) DECLARE @Cuenta_G_SS varchar(15) DECLARE @CuentaPago varchar(15) DECLARE @CuentaIRPF varchar(15) DECLARE @CuentaSS varchar(15) DECLARE @CuentaSS_EMP varchar(15) DECLARE @TRABAJADOR varchar(100) DECLARE @Importe_IRPF float DECLARE @Importe_SS_TRAB float DECLARE @Importe_SS_EMP float DECLARE @Asiento int DECLARE @Apunte int DECLARE @Fecha smalldatetime DECLARE @IdCentroCoste_Est varchar(50) --SELECT @IdCentroCoste_Est = Valor FROM Ceesi_configuracion WHERE Parametro = 'CENTROCOSTE_LINEA_GENERICO' ------------------------------------------------------------------------------------------------------------ ---- COMPROBACIONES ------------------------------------------------------------------------------------------------------------ --Miramos si el centro de coste generico esta definido --IF IsNULL(@IdCentroCoste_Est, '') = '' BEGIN -- RAISERROR ('DEBE CONFIGURAR UN CENTRO DE COSTE ESTRUCTURAL', 12, 1) --END --Miramos si la nomina que queremos contabilizar ya esta asociada a un asiento IF (SELECT Count(1) FROM Pers_Importa_Nominas WHERE IdImportacion=@IdImportacion AND (IsNULL(IdDocApunte, 0) > 0 OR IsNULL(IdDocApunte_SS, 0) > 0)) > 0 BEGIN RAISERROR ('ESTA NÓMINA ESTÁ VINCULADA A UN ASIENTO CONTABLE', 12, 1) END -- Hacemos un left join con la tabla empleado para asegurarnos que todos los NIF que tenemos pertenecen a un empleado del ERP -- Ponemos todos los NIF si empleado que encontramos en una tabla temporal que recogemos despues para sacar un mesage de error IF (SELECT Count(1) FROM Pers_Importa_Nominas_Lineas P LEFT JOIN Empleados_Datos E ON P.NIF = E.NIF WHERE P.IdImportacion=@IdImportacion AND E.IdEmpleado Is NULL) > 0 BEGIN INSERT INTO @Valores (Valor) SELECT LEFT(P.Trabajador, 100) FROM Pers_Importa_Nominas_Lineas P LEFT JOIN Empleados_Datos E ON P.NIF = E.NIF WHERE P.IdImportacion=@IdImportacion AND E.IdEmpleado Is NULL WHILE (SELECT COUNT(1) FROM @Valores) > 0 BEGIN SELECT TOP 1 @TRABAJADOR = Valor FROM @Valores IF LEN(ISNULL(@Retorno, '')) < 400 BEGIN SET @Retorno = ISNULL(@Retorno, '') + @TRABAJADOR + char(13) END DELETE FROM @Valores WHERE Valor = @TRABAJADOR END RAISERROR ('EXISTEN TRABAJADORES QUE NO COINCIDEN CON EL NIF DE EMPLEADOS.', 12, 1) END --Miramos si existen NIF repetidos en la nomina que queremos contabilizar IF (SELECT Count(1) FROM Empleados_Datos WHERE NIF IN (SELECT DISTINCT NIF FROM Pers_Importa_Nominas_Lineas WHERE IdImportacion = @IdImportacion) GROUP BY NIF HAVING Count(1) > 1) > 0 BEGIN INSERT INTO @Valores (Valor) SELECT NIF FROM Empleados_Datos WHERE NIF IN (SELECT DISTINCT NIF FROM Pers_Importa_Nominas_Lineas WHERE IdImportacion = @IdImportacion) GROUP BY NIF HAVING Count(1) > 1 WHILE (SELECT COUNT(1) FROM @Valores) > 0 BEGIN SELECT TOP 1 @TRABAJADOR = Valor FROM @Valores IF LEN(ISNULL(@Retorno, '')) < 400 BEGIN SET @Retorno = ISNULL(@Retorno, '') + @TRABAJADOR + char(13) END DELETE FROM @Valores WHERE Valor = @TRABAJADOR END RAISERROR ('EXISTEN NIF REPETIDOS EN FICHAS DE EMPLEADOS.', 12, 1) END --Esta comprobación no nos vale porque puede pasar. Hacemos el case por DNI --IF (SELECT COunt(1) FROM Empleados_Datos E -- INNER JOIN Pers_Importa_Nominas_Lineas P ON E.NIF = P.NIF AND E.IdEmpleado <> CAST(P.IdEmpleado as int) -- WHERE E.NIF <> '75381985Z' AND P.IdImportacion = @IdImportacion) > 0 BEGIN -- INSERT INTO @Valores (Valor) -- SELECT P.TRABAJADOR -- FROM Empleados_Datos E -- INNER JOIN Pers_Importa_Nominas_Lineas P ON E.NIF = P.NIF AND E.IdEmpleado <> CAST(P.IdEmpleado as int) -- WHERE E.NIF <> '75381985Z' AND P.IdImportacion = @IdImportacion -- WHILE (SELECT COUNT(1) FROM @Valores) > 0 BEGIN -- SELECT TOP 1 @TRABAJADOR = Valor FROM @Valores -- IF LEN(ISNULL(@Retorno, '')) < 400 BEGIN -- SET @Retorno = ISNULL(@Retorno, '') + @TRABAJADOR + char(13) -- END -- DELETE FROM @Valores WHERE Valor = @TRABAJADOR -- END -- RAISERROR ('EXISTEN EMPLEADOS QUE NO COINCIDE EL IDEMPLEADO DE NOMINAS CON EL DE LA ERP.', 12, 1) --END --Recuperar el ejercicio contable activo a la fecha de importacion de la nomina SET @IdEjercicio = -10000 SELECT @IdEjercicio = CE.IdEjercicio, @Fecha = P.Fecha FROM Conta_Ejercicios CE INNER JOIN Pers_Importa_Nominas P ON CE.IdEmpresa = P.IdEmpresa AND CONVERT(Varchar, P.Fecha, 112) BETWEEN CONVERT(Varchar, CE.FechaInicio, 112) AND CONVERT(Varchar, CE.FechaFin, 112) WHERE P.IdImportacion = @IdImportacion IF IsNULL(@IdEjercicio, -10000) < 0 BEGIN RAISERROR ('NO SE PUDO ACCEDER AL EJERCICIO DEL APUNTE.', 12, 1) END ------------------------------------------------------------------------------------------------------------ ---- DEFINICIÓN DE CUENTAS ------------------------------------------------------------------------------------------------------------ SELECT @NumDigitos = Digitos_SubCuenta FROM Conta_Ejercicios WHERE IdEjercicio = @IdEjercicio SET @CuentaBruto = '640' SET @Cuenta_G_SS = '642' SET @CuentaPago = '465' SET @CuentaIRPF = '4751' + REPLICATE('0', @NumDigitos - Len('4751')) SET @CuentaSS = '476' + REPLICATE('0', @NumDigitos - Len('476')) SET @CuentaSS_EMP = '476' + REPLICATE('0', @NumDigitos - Len('476')) --Las subcuentas de SS empleado y de SS empresa no estan definidas en el ERP, hay que crearlas IF (SELECT COUNT(1) FROM Conta_SubCuentas WHERE IdEjercicio = @IdEjercicio AND Subcuenta = @CuentaIRPF) = 0 BEGIN RAISERROR ('NO ESTÁ DEFINIDA LA CUENTA DE IRPF EN EL EJERCICIO CONTABLE', 12, 1) END IF (SELECT COUNT(1) FROM Conta_SubCuentas WHERE IdEjercicio = @IdEjercicio AND Subcuenta = @CuentaSS) = 0 BEGIN RAISERROR ('NO ESTÁ DEFINIDA LA CUENTA DE SEGURIDAD SOCIAL DEL EMPLEADO EN EL EJERCICIO CONTABLE', 12, 1) END IF (SELECT COUNT(1) FROM Conta_SubCuentas WHERE IdEjercicio = @IdEjercicio AND Subcuenta = @CuentaSS_EMP) = 0 BEGIN RAISERROR ('NO ESTÁ DEFINIDA LA CUENTA DE SEGURIDAD SOCIAL DE LA EMPRESA EN EL EJERCICIO CONTABLE', 12, 1) END ------------------------------------------------------------------------------------------------------------ ---- PREAPARACION DE NÓMINAS : Preparamos los importes asociados con cada subcuenta (un subcuenta por empleado) ------------------------------------------------------------------------------------------------------------ INSERT INTO @IMPORTES(IdEmpleado, Importe_Bruto, Importe_Pago, Importe_SS, Empleado, CuentaBruto, CuentaPago, CuentaSS, Apunte640) SELECT E.IdEmpleado, ROUND(ISNULL(P.Bruto, 0), 2), ROUND(ISNULL(P.Liquido, 0), 2), ROUND(ISNULL(P.Total_Coste_SS, 0), 2), P.TRABAJADOR, @CuentaBruto + RIGHT(REPLICATE('0', @NumDigitos) + CAST(E.IdEmpleado as varchar), @NumDigitos - LEn(@CuentaBruto)), @CuentaPago + RIGHT(REPLICATE('0', @NumDigitos) + CAST(E.IdEmpleado as varchar), @NumDigitos - LEn(@CuentaPago)), @Cuenta_G_SS + RIGHT(REPLICATE('0', @NumDigitos) + CAST(E.IdEmpleado as varchar), @NumDigitos - LEn(@Cuenta_G_SS)) , ROW_NUMBER() OVER (ORDER BY E.IdEmpleado) FROM Pers_Importa_Nominas_Lineas P INNER JOIN Empleados_Datos E ON P.NIF = E.NIF WHERE P.IdImportacion=@IdImportacion SELECT @Importe_IRPF = -1 * ROUND(Sum(ISNULL(P.IRPF, 0)), 2) FROM Pers_Importa_Nominas_Lineas P WHERE P.IdImportacion = @IdImportacion SELECT @Importe_SS_TRAB = - 1 * ROUND(Sum(ISNULL(P.SS_Trab, 0)), 2) FROM Pers_Importa_Nominas_Lineas P WHERE P.IdImportacion = @IdImportacion SELECT @Importe_SS_EMP = ROUND(Sum(ISNULL(P.Total_Coste_SS, 0)), 2) FROM Pers_Importa_Nominas_Lineas P WHERE P.IdImportacion = @IdImportacion BEGIN TRAN ------------------------------------------------------------------------------------------------------------ ---- CREACIÓN DE SUBCUCENTAS QUE NO EXISTEN YA ------------------------------------------------------------------------------------------------------------ INSERT INTO Conta_SubCuentas(IdEjercicio, SubCuenta, Descrip) SELECT DISTINCT @IdEjercicio, P.CuentaBruto, P.Empleado FROM @IMPORTES P LEFT JOIN Conta_SubCuentas C ON P.CuentaBruto = C.Subcuenta AND C.IdEjercicio = @IdEjercicio WHERE C.Subcuenta IS NULL INSERT INTO Conta_SubCuentas(IdEjercicio, SubCuenta, Descrip) SELECT DISTINCT @IdEjercicio, P.CuentaPago, P.Empleado FROM @IMPORTES P LEFT JOIN Conta_SubCuentas C ON P.CuentaPago = C.Subcuenta AND C.IdEjercicio = @IdEjercicio WHERE C.Subcuenta IS NULL INSERT INTO Conta_SubCuentas(IdEjercicio, SubCuenta, Descrip) SELECT DISTINCT @IdEjercicio, P.CuentaSS, P.Empleado FROM @IMPORTES P LEFT JOIN Conta_SubCuentas C ON P.CuentaSS = C.Subcuenta AND C.IdEjercicio = @IdEjercicio WHERE C.Subcuenta IS NULL SELECT @Asiento = MAX(Asiento) FROM Conta_Apuntes WHERE IdEjercicio = @IdEjercicio SET @Asiento = ISNULL(@Asiento, 0) + 1 UPDATE @IMPORTES SET Asiento640 = @Asiento ------------------------------------------------------------------------------------------------------------ ---- APUNTES CONTABLES 640 ------------------------------------------------------------------------------------------------------------ INSERT INTO Conta_Apuntes(IdEjercicio, Asiento, Apunte, SubCuenta, Concepto, Documento, Tipo_DH, Debe_Euros, Haber_Euros, Fecha) SELECT @IdEjercicio, @Asiento, P.Apunte640, P.CuentaBruto, 'IMPORTACION NÓMINA', 'Nómina mes ' + CAST(Month(@Fecha) as varchar) + ' - ' + CAST(Year(@Fecha) as varchar), CASE WHEN P.Importe_Bruto >= 0 THEN 'D' ELSE 'H' END, CASE WHEN P.Importe_Bruto >= 0 THEN P.Importe_Bruto ELSE 0 END, CASE WHEN P.Importe_Bruto >= 0 THEN 0 ELSE -1 * P.Importe_Bruto END, @Fecha FROM @IMPORTES P SELECT @Apunte = Max(Apunte) FROM Conta_Apuntes WHERE IdEjercicio = @IdEjercicio AND Asiento = @Asiento INSERT INTO Conta_Apuntes(IdEjercicio, Asiento, Apunte, SubCuenta, Concepto, Documento, Tipo_DH, Debe_Euros, Haber_Euros, Fecha) SELECT @IdEjercicio, @Asiento, @Apunte + 1, @CuentaIRPF, 'IMPORTACION NÓMINA', 'Nómina mes ' + CAST(Month(@Fecha) as varchar) + ' - ' + CAST(Year(@Fecha) as varchar), CASE WHEN @Importe_IRPF >= 0 THEN 'H' ELSE 'D' END, CASE WHEN @Importe_IRPF >= 0 THEN 0 ELSE -1 * @Importe_IRPF END, CASE WHEN @Importe_IRPF >= 0 THEN @Importe_IRPF ELSE 0 END, @Fecha FROM @IMPORTES P UNION SELECT @IdEjercicio, @Asiento, @Apunte + 2, @CuentaSS, 'IMPORTACION NÓMINA', 'Nómina mes ' + CAST(Month(@Fecha) as varchar) + ' - ' + CAST(Year(@Fecha) as varchar), CASE WHEN @Importe_SS_TRAB >= 0 THEN 'H' ELSE 'D' END, CASE WHEN @Importe_SS_TRAB >= 0 THEN 0 ELSE -1 * @Importe_SS_TRAB END, CASE WHEN @Importe_SS_TRAB >= 0 THEN @Importe_SS_TRAB ELSE 0 END, @Fecha FROM @IMPORTES P SET @Apunte = @Apunte + 2 UPDATE @IMPORTES SET Apunte465 = Apunte640 + @Apunte INSERT INTO Conta_Apuntes(IdEjercicio, Asiento, Apunte, SubCuenta, Concepto, Documento, Tipo_DH, Debe_Euros, Haber_Euros, Fecha) SELECT @IdEjercicio, @Asiento, P.Apunte465, P.CuentaPago, 'IMPORTACION NÓMINA', 'Nómina mes ' + CAST(Month(@Fecha) as varchar) + ' - ' + CAST(Year(@Fecha) as varchar), CASE WHEN P.Importe_Pago >= 0 THEN 'H' ELSE 'D' END, CASE WHEN P.Importe_Pago >= 0 THEN 0 ELSE P.Importe_Pago END, CASE WHEN P.Importe_Pago >= 0 THEN P.Importe_Pago ELSE 0 END, @Fecha FROM @IMPORTES P UPDATE Pers_Importa_Nominas SET IdDocApunte = C.IdDoc FROM Pers_Importa_Nominas P INNER JOIN Conta_Apuntes C ON C.IdEjercicio = @IdEjercicio AND C.Asiento = @Asiento AND C.Apunte = 1 WHERE P.IdImportacion = @IdImportacion SELECT @Asiento = MAX(Asiento) + 1 FROM Conta_Apuntes WHERE IdEjercicio = @IdEjercicio UPDATE @IMPORTES SET Asiento642 = @Asiento ------------------------------------------------------------------------------------------------------------ ---- APUNTES CONTABLES 642 ------------------------------------------------------------------------------------------------------------ INSERT INTO Conta_Apuntes(IdEjercicio, Asiento, Apunte, SubCuenta, Concepto, Documento, Tipo_DH, Debe_Euros, Haber_Euros, Fecha) SELECT @IdEjercicio, @Asiento, P.Apunte640, P.CuentaSS, 'IMPORTACION NÓMINA', 'Nómina mes ' + CAST(Month(@Fecha) as varchar) + ' - ' + CAST(Year(@Fecha) as varchar), CASE WHEN P.Importe_SS >= 0 THEN 'D' ELSE 'H' END, CASE WHEN P.Importe_SS >= 0 THEN P.Importe_SS ELSE 0 END, CASE WHEN P.Importe_SS >= 0 THEN 0 ELSE -1 * P.Importe_SS END, @Fecha FROM @IMPORTES P SELECT @Apunte = Max(Apunte) + 1 FROM Conta_Apuntes WHERE IdEjercicio = @IdEjercicio AND Asiento = @Asiento INSERT INTO Conta_Apuntes(IdEjercicio, Asiento, Apunte, SubCuenta, Concepto, Documento, Tipo_DH, Debe_Euros, Haber_Euros, Fecha) SELECT @IdEjercicio, @Asiento, @Apunte + 1, @CuentaSS_EMP, 'IMPORTACION NÓMINA', 'Nómina mes ' + CAST(Month(@Fecha) as varchar) + ' - ' + CAST(Year(@Fecha) as varchar), CASE WHEN @Importe_SS_EMP >= 0 THEN 'H' ELSE 'D' END, CASE WHEN @Importe_SS_EMP >= 0 THEN 0 ELSE -1 * @Importe_SS_EMP END, CASE WHEN @Importe_SS_EMP >= 0 THEN @Importe_SS_EMP ELSE 0 END, @Fecha UPDATE Pers_Importa_Nominas SET IdDocApunte_SS = C.IdDoc FROM Pers_Importa_Nominas P INNER JOIN Conta_Apuntes C ON C.IdEjercicio = @IdEjercicio AND C.Asiento = @Asiento AND C.Apunte = 1 WHERE P.IdImportacion = @IdImportacion ------------------------------------------------------------------------------------------------------------ ---- ASIGNACION CENTROS DE COSTE. ------------------------------------------------------------------------------------------------------------ /*INSERT INTO @LOSEMPLEADOS(IdEmpleado, IdCentroCoste) SELECT DISTINCT IdEmpleado, IdCentroCoste FROM vPers_Empleados_Horas_CC_Porcentajes WHERE Anyo = Year(@Fecha) AND Mes = Month(@Fecha)*/ --Miramos si la nomina que queremos contabilizar ya esta asociada a un asiento IF (SELECT Count(*) FROM vPers_Imputacion_Empleado_Nominas WHERE IdImportacion=@IdImportacion) = 0 BEGIN RAISERROR ('El EXCEL DE REPARTO DE CADA EMPLEADO A CADA PROYECTO PARA ESTE MES NO HA SIDO IMPORTADO', 12, 1) END INSERT INTO Conta_CentrosCoste (IdCentroCoste, Descrip, Bloqueado) SELECT DISTINCT I.IdCentroCoste, I.CC_Descrip, 0 FROM vPers_Imputacion_Empleado_Nominas I LEFT JOIN Conta_CentrosCoste C ON I.IdCentroCoste = C.IdCentroCoste WHERE C.IdCentroCoste IS NULL AND I.IdImportacion = @IdImportacion INSERT INTO Conta_CentrosCoste_Linea(IdEjercicio, IdAsiento, IdApunte, CentroCoste, Importe_Euros) SELECT @IdEjercicio, I.Asiento640, I.Apunte640, L.IdCentroCoste, L.Bruto_ImporteEquipo FROM @IMPORTES I INNER JOIN vPers_Imputacion_Empleado_Nominas L ON I.IdEmpleado = L.IdEmpleado WHERE L.IdImportacion = @IdImportacion /*INSERT INTO Conta_CentrosCoste_Linea(IdEjercicio, IdAsiento, IdApunte, CentroCoste, Importe_Euros) SELECT @IdEjercicio, I.Asiento640, I.Apunte640, I.IdCentroCoste, ABS(I.Importe_Bruto) FROM @IMPORTES I WHERE I.IdEmpleado Not IN (SELECT IdEmpleado FROM @LOSEMPLEADOS)*/ INSERT INTO Conta_CentrosCoste_Linea(IdEjercicio, IdAsiento, IdApunte, CentroCoste, Importe_Euros) SELECT @IdEjercicio, I.Asiento642, I.Apunte640, L.IdCentroCoste, L.Total_Coste_SS_ImporteEquipo FROM @IMPORTES I INNER JOIN vPers_Imputacion_Empleado_Nominas L ON I.IdEmpleado = L.IdEmpleado WHERE L.IdImportacion = @IdImportacion /*INSERT INTO Conta_CentrosCoste_Linea(IdEjercicio, IdAsiento, IdApunte, CentroCoste, Importe_Euros) SELECT @IdEjercicio, I.Asiento642, I.Apunte640, I.IdCentroCoste, ABS(I.Importe_SS) FROM @IMPORTES I WHERE I.IdEmpleado Not IN (SELECT IdEmpleado FROM @LOSEMPLEADOS)*/ --AJUSTO LOS DESCUADRES ENTRE CONTABILIDAD Y ANALITICA POR REDONDEO INSERT INTO @APUNTES_DESCUADRADOS (Asiento, Apunte, Importe) SELECT C.Asiento, C.APunte, ROUND(CASE WHEN C.Tipo_DH = 'D' THEN C.Debe_Euros ELSE C.Haber_Euros END, 2) - ROUND(CC.Total, 2) FROM Conta_Apuntes C INNER JOIN @IMPORTES I ON C.IdEjercicio = @IdEjercicio AND C.Asiento = I.Asiento640 AND C.Apunte = I.Apunte640 LEFT JOIN (SELECT C.IDEjercicio, C.IdAsiento, C.IdApunte, ROUND(Sum(IsNULL(C.Importe_Euros, 0)), 2) AS Total FROM Conta_CentrosCoste_Linea C GROUP BY C.IDEjercicio, C.IdAsiento, C.IdApunte) CC ON C.IdEjercicio = CC.IdEjercicio AND C.Asiento = CC.IdAsiento AND C.Apunte = CC.IdApunte WHERE ABS(ROUND(CASE WHEN C.Tipo_DH = 'D' THEN C.Debe_Euros ELSE C.Haber_Euros END, 2) - ROUND(CC.Total, 2)) <> 0 INSERT INTO @APUNTES_DESCUADRADOS (Asiento, Apunte, Importe) SELECT C.Asiento, C.APunte, ROUND(ROUND(CASE WHEN C.Tipo_DH = 'D' THEN C.Debe_Euros ELSE C.Haber_Euros END, 2) - ROUND(CC.Total, 2), 2) FROM Conta_Apuntes C INNER JOIN @IMPORTES I ON C.IdEjercicio = @IdEjercicio AND C.Asiento = I.Asiento642 AND C.Apunte = I.Apunte640 LEFT JOIN (SELECT C.IDEjercicio, C.IdAsiento, C.IdApunte, ROUND(Sum(IsNULL(C.Importe_Euros, 0)), 2) AS Total FROM Conta_CentrosCoste_Linea C GROUP BY C.IDEjercicio, C.IdAsiento, C.IdApunte) CC ON C.IdEjercicio = CC.IdEjercicio AND C.Asiento = CC.IdAsiento AND C.Apunte = CC.IdApunte WHERE ABS(ROUND(CASE WHEN C.Tipo_DH = 'D' THEN C.Debe_Euros ELSE C.Haber_Euros END, 2) - ROUND(CC.Total, 2)) <> 0 UPDATE @APUNTES_DESCUADRADOS SET IdDoc = dbo.fun_Pers_Max_CC_Importe(@IdEjercicio, Asiento, Apunte) UPDATE Conta_CentrosCoste_Linea SET Importe_Euros = ROUND(C.Importe_Euros, 2) + ROUND(A.Importe, 2) FROM Conta_CentrosCoste_Linea C INNER JOIN @APUNTES_DESCUADRADOS A ON C.IdDoc = A.IdDoc COMMIT TRAN RETURN -1 END TRY BEGIN CATCH IF @@TRANCOUNT >0 BEGIN ROLLBACK TRAN END DECLARE @CatchError NVARCHAR(MAX) SET @CatchError=dbo.funImprimeError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE()) RAISERROR(@CatchError,12,1) RETURN 0 END CATCH<file_sep>/Genera/Stored/pPers_Importar_Datos_ImportIngreso.sql USE [GENERA] GO /****** Object: StoredProcedure [dbo].[pPers_Importar_Datos_ImportIngreso] Script Date: 25/06/2015 18:24:48 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: <<NAME>> -- Create date: <05/06/2015> -- Description: <Importar los datos de los ingresos antes de importar> -- ============================================= CREATE PROCEDURE [dbo].[pPers_Importar_Datos_ImportIngreso] -- Add the parameters for the stored procedure here @ClaveImportacion varchar(255), @IdCliente T_Id_Cliente --@Ubicacion varchar(255) AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON; DECLARE @IdLineaImportacion smallint DECLARE @IdProyectoAgencia varchar(255) DECLARE @IdProyectoERP T_Id_Proyecto DECLARE @IdIngresoAgencia smallint DECLARE @Importe Real DECLARE @IngresoAgenciaLinea smallint DECLARE @ImporteTotal DECIMAL BEGIN TRY DECLARE cursor_Import CURSOR FOR select IdLineaImportacion, IdIngresoAgencia, IdProyectoAgencia, Importe from Pers_Log_Importacion_IngresoAgencia where ClaveImportacion = @ClaveImportacion OPEN cursor_Import FETCH cursor_Import INTO @IdLineaImportacion, @IdIngresoAgencia, @IdProyectoAgencia, @Importe WHILE @@FETCH_STATUS = 0 BEGIN if EXISTS (select 1 from Pers_Proyectos_Agencias_Ingresos where IdProyectoAgencia = @IdProyectoAgencia and IdCliente = @IdCliente) BEGIN set @IdProyectoERP = (select IdProyecto from Pers_Proyectos_Agencias_Ingresos where IdProyectoAgencia = @IdProyectoAgencia and IdCliente = @IdCliente) set @IngresoAgenciaLinea = (select isnull(max(IdIngresoAgenciaLinea), 0) +1 from Pers_IngresoAgencia_Lineas where IdIngresoAgencia = @IdIngresoAgencia) insert into Pers_IngresoAgencia_Lineas(IdIngresoAgencia, IdIngresoAgenciaLinea, IdProyecto, IdProyectoAgencia, Importe) values (@IdIngresoAgencia, @IngresoAgenciaLinea, @IdProyectoERP, @IdProyectoAgencia, @Importe) END ELSE BEGIN update Pers_Log_Importacion_IngresoAgencia set Texto_error = 'No existe correspondencia para el codigo de Proyecto Agencia : ' + @IdProyectoAgencia where IdLineaImportacion = @IdLineaImportacion and IdIngresoAgencia = @IdIngresoAgencia END FETCH cursor_Import INTO @IdLineaImportacion, @IdIngresoAgencia, @IdProyectoAgencia, @Importe END CLOSE cursor_Import DEALLOCATE cursor_Import --MAJ de la fecha de importacion del excel y del importe total Set @ImporteTotal = (select sum(Importe) from Pers_IngresoAgencia_Lineas where IdIngresoAgencia = @IdIngresoAgencia) update Pers_IngresoAgencia_Cabecera set FechaImport = GETDATE() where IdIngresoAgencia = @IdIngresoAgencia update Pers_IngresoAgencia_Cabecera set ImporteTotal = @ImporteTotal where IdIngresoAgencia = @IdIngresoAgencia return -1 END TRY BEGIN CATCH IF @@TRANCOUNT >0 BEGIN ROLLBACK TRAN END DECLARE @CatchError NVARCHAR(MAX) SET @CatchError=dbo.funImprimeError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE()) RAISERROR(@CatchError,12,1) RETURN 0 END CATCH END GO <file_sep>/Genera/VbScript ERP/IngresoAgencia.vbs Sub Show() gForm.Controls("cntPanel")(1).Top = 250 gForm.Controls("ComboUsuario")(1).Height = 300 gForm.Controls("TextoUsuario")(1).Height = 300 gForm.Controls("ComboUsuario")(2).Height = 300 gForm.Controls("TextoUsuario")(3).Height = 300 gForm.Controls("TextoUsuario")(4).Height = 300 If gForm.Controls("EObjeto").ObjGlobal.Propiedades("IdIngresoAgencia") = "" Then lastId = gcn.dameValorCampo("select isnull(max(IdIngresoAgencia),0) + 1 from Pers_IngresoAgencia_Cabecera") gForm.Controls("TextoUsuario")(1).text = lastId gForm.Botonera.Boton("btImportIngreso").Visible = False gForm.Botonera.Boton("btGenerarPed").Visible = False gForm.Botonera.Boton("btVerPedCli").Visible = False gForm.Botonera.Boton("btVerPedPro").Visible = False CrearGridAgenciaLineas() Else CrearGridAgenciaLineas() 'Si la cebecera de IngresoAgencia ya tiene un nuñero de pedido o si no hay lineas en las lineas del Ingreso, no mostrar el boton para Generar los pedidos' If gcn.dameValorCampo("select IdPedido from Pers_IngresoAgencia_Cabecera where IdIngresoAgencia = "&gForm.Controls("EObjeto").ObjGlobal.Propiedades("IdIngresoAgencia")&"") > 0 Or gcn.dameValorCampo("select count(IdIngresoAgenciaLinea) from Pers_IngresoAgencia_Lineas where IdIngresoAgencia = "&gForm.Controls("EObjeto").ObjGlobal.Propiedades("IdIngresoAgencia")&"") = 0 Then gForm.Botonera.Boton("btGenerarPed").Visible = False Else gForm.Botonera.Boton("btGenerarPed").Visible = True End If If gcn.dameValorCampo("select IdPedido from Pers_IngresoAgencia_Cabecera where IdIngresoAgencia = "&gForm.Controls("EObjeto").ObjGlobal.Propiedades("IdIngresoAgencia")&"") > 0 Or gcn.dameValorCampo("select count(IdPedidoProv) from Pers_Mapeo_Ingreso_PedidoProv where IdIngresoAgencia = "&gForm.Controls("EObjeto").ObjGlobal.Propiedades("IdIngresoAgencia")&"") > 0 Then gForm.Botonera.Boton("btGenerarPed").Visible = False End If If gcn.dameValorCampo("select IdPedido from Pers_IngresoAgencia_Cabecera where IdIngresoAgencia = "&gForm.Controls("EObjeto").ObjGlobal.Propiedades("IdIngresoAgencia")&"") > 0 Then gForm.Botonera.Boton("btVerPedCli").Visible = True gForm.Botonera.Boton("btImportIngreso").Visible = False Else gForm.Botonera.Boton("btVerPedCli").Visible = False End If If gcn.dameValorCampo("select count(IdPedidoProv) from Pers_Mapeo_Ingreso_PedidoProv where IdIngresoAgencia = "&gForm.Controls("EObjeto").ObjGlobal.Propiedades("IdIngresoAgencia")&"") > 0 Then gForm.Botonera.Boton("btVerPedPro").Visible = True gForm.Botonera.Boton("btImportIngreso").Visible = False Else gForm.Botonera.Boton("btVerPedPro").Visible = False End If End If gForm.Controls("TextoUsuario")(4).CaptionLink = True gForm.Controls("ComboUsuario")(1).CaptionLink = True gForm.Controls("ComboUsuario")(2).CaptionLink = True End Sub Sub Initialize() gform.Botonera.ActivarScripts = True gform.Botonera.BotonAdd " Generar pedido", "btGenerarPed", , , , 340 gform.Botonera.BotonAdd " Ver pedido Cliente", "btVerPedCli", , , , 340 gform.Botonera.BotonAdd " Ver pedido Proveedor", "btVerPedPro", , , , 340 gform.Botonera.BotonAdd " Importar Excel Ingreso", "btImportIngreso", , , , 433 gForm.Botonera.HabilitaBotones End Sub Sub CrearGridAgenciaLineas() Set lGrid = gForm.Controls.Add("AhoraOCX.cntGridUsuario", "GridAgenciaLineas",gForm.Controls("cntPanel")(2)) gForm.Controls("cntPanel")(2).ResizeInterior = True gForm.Controls("cntPanel")(2).ResizeEnabled = True lGrid.Visible = True lGrid.AplicaEstilo lGrid.Top = 500 lGrid.Width = gForm.Controls("cntPanel")(2).width lGrid.height = gForm.Controls("cntPanel")(2).height With lGrid If Not .Preparada Then '.Enabled=Not gForm.Eobjeto.ObjGlobal.Nuevo .Agregar = True .Editar = False .Eliminar = True .CargaObjetos = False .EditarPorObjeto = False .Grid.HeadLines = 2 .AgregaColumna "IdIngresoAgencia", 0, "IdIngresoAgencia",False .AgregaColumna "IdIngresoAgenciaLinea", 0, "IdIngresoAgenciaLinea",False .AgregaColumna "IdProyecto", 2000, "Codigo proyecto",False .AgregaColumna "IdProyectoAgencia", 3000, "Codigo proyecto interno a la agencia",False .AgregaColumna "Importe", 1500, "Importe",False,,,"#,##0.00" .AgregaColumna "@DescripProyecto", 5000, "Descripcion",True .FROM = "Pers_IngresoAgencia_Lineas" .where = "Where IdIngresoAgencia = "&gForm.Controls("TextoUsuario")(1).text&"" .Campo("@DescripProyecto").Sustitucion = "Select Descrip from Proyectos where IdProyecto = @IdProyecto" .campo("IdProyecto").Coleccion = "Proyectos" .campo("IdProyecto").ColeccionWhere = "Where IdProyecto = @IdProyecto" .campo("IdIngresoAgencia").default = gForm.Controls("TextoUsuario")(1).text .campo("IdIngresoAgenciaLinea").default = "Select isnull(max(IdIngresoAgenciaLinea),0) +1 from Pers_IngresoAgencia_Lineas" .ActivarScripts = True .ColumnaEscalada = "@DescripProyecto" .Refresca = True End If End With End Sub Sub GenerarPedidosProveedor() Set lColparams = gcn.DameNewCollection IdEmpresa = gcn.IdEmpresa Fecha = gForm.Controls("TextoUsuario")(4).text IdEmpleado = gcn.IdEmpleado IdDepartamento = gcn.IdDepartamento IdIngresoAgencia = gForm.Controls("TextoUsuario")(1).text IdMoneda = gForm.Controls("ComboUsuario")(2).text lColparams.add IdEmpresa lColparams.add Fecha lColparams.add IdEmpleado lColparams.add IdDepartamento lColparams.add IdIngresoAgencia lColparams.add IdMoneda If Not gcn.EjecutaStoreCol("PPers_GenerarPedidoProveedor_From_Ingreso", lColparams) Then MsgBox "No se ha podido crear el pedido proveedor asociado al proyecto numero : "&larr(i,lgrd.colindex("IdProyecto"))&"" , vbCritical, "Error creando pedido proveedor" gForm.Botonera.Boton("btImportIngreso").Visible = True Else MsgBox "Pedidos proveedores generados", vbInformation, "Informacion" gForm.Botonera.Boton("btVerPedPro").Visible = True gForm.Botonera.Boton("btGenerarPed").Visible = False gForm.Botonera.Boton("btImportIngreso").Visible = False BloquearGrid() End If End Sub Sub GenerarPedidoCliente() Set lColparams = gcn.DameNewCollection vFecha = gForm.Controls("TextoUsuario")(4).text vIdCliente = gForm.Controls("ComboUsuario")(1).text vDescripcionPed = gForm.Controls("TextoUsuario")(2).text & " / Ingreso numero : " & gForm.Controls("TextoUsuario")(1).text vIdEmpleado = gcn.IdEmpleado vIdMoneda = gForm.Controls("ComboUsuario")(2).text vIdIngreso = gForm.Controls("TextoUsuario")(1).text lColparams.add vFecha lColparams.add vIdCliente lColparams.add vDescripcionPed lColparams.add vIdEmpleado lColparams.add vIdMoneda lColparams.add vIdIngreso If Not gcn.EjecutaStoreCol("PPers_GenerarPedidoCliente_From_Ingreso", lColparams) Then MsgBox "No se ha podido crear el pedido cliente asociado al proyecto numero : "&larr(i,lgrd.colindex("IdProyecto"))&"" , vbCritical, "Error creando pedido cliente" gForm.Botonera.Boton("btImportIngreso").Visible = True Else MsgBox "Pedido cliente generado" , vbInformation, "Informacion" gForm.Botonera.Boton("btVerPedCli").Visible = True gForm.Botonera.Boton("btGenerarPed").Visible = False gForm.Botonera.Boton("btImportIngreso").Visible = False BloquearGrid() End If End Sub Sub Botonera_BeforeExecute(aBotonera, aBoton, aCancel) If aBoton.Name = "botGuardar" Then 'Comprobar que los campos obligatorios esten rellenos (da un fallo con la configuracion manual...) 'Los campos obligatorios son : Cliente, Moneda y Fecha. Si el Id ingreso no esta relleno, hay que rellenarlo automaticamente vCliente = gForm.Controls("ComboUsuario")(1).text vMoneda = gForm.Controls("ComboUsuario")(2).text vFechaIngreso = gForm.Controls("TextoUsuario")(4).text If Len(vCliente) = 0 Or Len(vMoneda) = 0 Or Len(vFechaIngreso) = 0 Then aCancel = True MsgBox "No se ha podido guardar. Los campos Cliente, Moneda y Fecha tiene que ser rellenados",vbExclamation,"Informacion" Else gForm.Botonera.Boton("btImportIngreso").Visible=True End If End If End Sub Sub Botonera_AfterExecute(aBotonera, aBoton) If aBoton.Name = "btGenerarPed" Then 'codigo para generar el pedido cliente que contenga una linea por cada proyecto presente en el la agencia GenerarPedidoCliente 'codigo para genera x pedidos proveedores que contenga una linea con el importe que va al tercero dependiente del porcentage establecido al principio del proyecto GenerarPedidosProveedor gform.Eobjeto.Refresh End If If aBoton.Name = "btImportIngreso" Then lFichero = SelectFile() Set fso = CreateObject("Scripting.FileSystemObject") If Not fso.FileExists(lFichero) Then MsgBox "Fichero " & lFichero & "no existe" Exit Sub End If ImportarExcel lFichero End If If aBoton.Name = "btVerPedCli" Then Set lColPedCli = gcn.obj.dameColeccion("Pedidos","where IdPedido in (select distinct idPedido from Pers_IngresoAgencia_Cabecera where IdIngresoAgencia = "&gForm.Controls("EObjeto").ObjGlobal.Propiedades("IdIngresoAgencia")&" )") If Not lColPedCli Is Nothing Then If lColPedCli.Count>0 Then lColPedCli.show End If End If End If If aBoton.Name = "btVerPedPro" Then Set lColPedProv = gcn.obj.dameColeccion("PedidosProv","where IdPedido in (select distinct idPedidoProv from Pers_Mapeo_Ingreso_PedidoProv where IdIngresoAgencia = "&gForm.Controls("EObjeto").ObjGlobal.Propiedades("IdIngresoAgencia")&" )") If Not lColPedProv Is Nothing Then If lColPedProv.Count>0 Then lColPedProv.show End If End If End If End Sub Sub ImportarExcel(lFichero ) 'Abrir el fichero Excel Set objExcel = CreateObject("Excel.Application") Set objWorkbook = objExcel.Workbooks.Open(lFichero) row = 2 claveImportacion = gcn.IdEmpleado & "_" & RandomString & "_" & Second(Now()) IdIngresoAgencia = gForm.Controls("TextoUsuario")(1).text 'Selecionar la primera hoja objExcel.Worksheets(1).Activate 'Comprobar que las 2 primeras columnas existen While Len("" & objExcel.ActiveSheet.Cells(row, 1)) > 0 IdProyectoAgencia = objExcel.ActiveSheet.Cells(row, 1) ImporteProyecto = Replace(objExcel.ActiveSheet.Cells(row, 2),",",".") IdLineaImport = gcn.dameValorCampo("select isnull(max(IdLineaImportacion), 1) +1 from Pers_Log_Importacion_IngresoAgencia") 'Insertar en base de datos los datos para comprobar la integridad de los datos lSql = "insert into Pers_Log_Importacion_IngresoAgencia(IdLineaImportacion, ClaveImportacion, IdIngresoAgencia, IdProyectoAgencia, Importe) values ("&IdLineaImport&",'"&claveImportacion&"',"&IdIngresoAgencia&",'"&IdProyectoAgencia&"','"&ImporteProyecto&"')" 'Si el insert falla, sacar um mensaje de error y detener la importacion If Not gcn.executeSql(CStr(lSql),,,,False) Then objworkbook.Saved = True objWorkbook.Close objExcel.Quit Set objExcel = Nothing Exit Sub End If 'Ir a la linea siguiente row = row + 1 Wend objExcel.Quit 'Despues de la importacion de las lineas, abrir un formulario de mantenimiento para ver las limeas importadas y indicar con una regla de color si existe un error o no Set params = gcn.DameNewCollection Cliente = gForm.Controls("ComboUsuario")(1).text params.Add claveImportacion params.Add Cliente If gcn.EjecutaStoreCol("pPers_Importar_Datos_ImportIngreso", params) Then gForm.Controls("GridAgenciaLineas").Refrescar If gcn.dameValorCampo("select count(IdIngresoAgenciaLinea) from Pers_IngresoAgencia_Lineas where IdIngresoAgencia = "&gForm.Controls("TextoUsuario")(1).text&"") > 0 Then gForm.Botonera.Boton("btGenerarPed").Visible=True End If If MsgBox("Importacion terminada, quereis ver el importe de la importacion del Excel ?", vbYesNo, "Confirmacion") = vbYes Then AbrirFormImportacion(claveImportacion) End If End If gform.Eobjeto.Refresh End Sub Sub AbrirFormImportacion(lClaveUser) Set lFrm = gcn.ahoraproceso ("NewFrmMantenimiento",False,gcn) lfrm.Form.NombreForm = "Pers_frmMant_Import" With lFrm.Grid("Comprobacion de los datos a importar") ' NO_TRADUCIR_TAG .Agregar = True .Editar = True .Eliminar = True .CargaObjetos = False .EditarPorObjeto = False .Grid.HeadLines = 2 .AgregaColumna "IdLineaImportacion", 0, "Id.LineaImportacion", False .AgregaColumna "ClaveImportacion", 0, "Clave importacion", False .AgregaColumna "IdIngresoAgencia", 0, "Id Ingreso Agencia", False .AgregaColumna "IdProyectoAgencia", 1000, "Id proyecto",False .AgregaColumna "Importe", 1000, "Importe",False,,,"#,##0.00" .AgregaColumna "Texto_error", 2500, "Error",True .From = "Pers_Log_Importacion_IngresoAgencia" .Where = "Where ClaveImportacion = '"&lClaveUser&"'" .ColumnaEscalada = "Texto_error" .OrdenMultiple = "IdLineaImportacion" .RefrescaSinLoad = True .Refresca = True End With lFrm.Form.Caption = "Comprobar los datos" lFrm.Carga , False, 4 End Sub Function SelectFile() Set wShell=CreateObject("WScript.Shell") Set oExec=wShell.Exec("mshta.exe ""about:<input type=file id=FILE><script>FILE.click();new ActiveXObject('Scripting.FileSystemObject').GetStandardStream(1).WriteLine(FILE.value);close();resizeTo(0,0);</script>""") sFileSelected = oExec.StdOut.ReadLine SelectFile = sFileSelected End Function Function RandomString() Dim max,min max=10000 min=1 Randomize RandomString = CStr(Int((max-min+1)*Rnd+min)) End Function 'Para Activar este evento hay que configurar la grid. Poner en el sub Initialize por ejemplo: gForm.grdLineas.ActivarScripts = True Sub Grid_BeforeDelete(aGrid,aCancel) 'If aGrid.Name = "GridAgenciaLineas" Then 'TipoObj = "IngresoAgencia" 'IdIngreso = aGrid.GetValue("IdIngresoAgencia") 'IdLinea = aGrid.GetValue("IdIngresoAgenciaLinea") 'Return = "" 'Set params = gcn.DameNewCollection 'params.Add IdIngreso 'params.Add IdLinea 'params.Add TipoObj 'params.Add Return 'If Not gcn.EjecutaStoreCol("pPers_DespuesEliminar_IngresoLinea", params) Then 'MsgBox "Fallo durante la actualizacion del importe total", vbError 'aCancel = True ' End If 'gform.Eobjeto.Refresh 'End If End Sub 'Para Activar este evento hay que configurar la grid. Poner en el sub Initialize por ejemplo: gForm.grdLineas.ActivarScripts = True Sub Grid_AfterDelete(aGrid) gform.Eobjeto.Refresh End Sub Sub BloquearGrid() Set lGrid = gForm.Controls("GridAgenciaLineas") With lGrid .Eliminar = False .Agregar = False .Editar = False End With End Sub <file_sep>/Genera/VbScript ERP/Proyectos.vbs Function CreaCampoTexto(aNombre, aParent, aLeft, aTop, aWidth, aHeight, aCaption, aAnchoEtiqueta, aMultilinea, aObjOrigen, aObjPOrigen) Dim lCtrl If aMultilinea <> 0 Then Set lCtrl = gForm.Controls.Add("AhoraOCX.TextoMultilinea", aNombre, aParent) Else Set lCtrl = gForm.Controls.Add("AhoraOCX.TextoUsuario", aNombre, aParent) End If With lCtrl .Move aLeft, aTop, aWidth, aHeight .CaptionVisible = True .CaptionWidth = aAnchoEtiqueta .CaptionControl = aCaption .ObjOrigen = aObjOrigen .ObjPOrigen = aObjPOrigen .AplicaEstilo .Visible = True .Enabled = True End With End Function Function CreaCampoCombo(aNombre, aParent, aLeft, aTop, aWidth, aHeight, aCaption, aAnchoEtiqueta, aSQl, aAnch1, ANom1, aTD1, aAnch2, ANom2, aTD2, aNcol, aActiva, aObjOrigen, aObjPOrigen) Dim lCtrl Set lCtrl = gForm.Controls.Add("AhoraOCX.ComboUsuario", aNombre, aParent) With lCtrl .Move aLeft, aTop, aWidth, aHeight .CaptionVisible = True .CaptionWidth = aAnchoEtiqueta .CaptionControl = aCaption .C1Anchura = aAnch1 .C1Nombre = ANom1 .C1TipoDato = aTD1 .C2Anchura = aAnch2 .C2Nombre = ANom2 .C2TipoDato = aTD2 .NColumnas = aNcol .cActiva = aActiva .Descripcion = aSQL .ObjOrigen = aObjOrigen .ObjPOrigen = aObjPOrigen .AplicaEstilo .Visible = True .Enabled = True End With End Function Sub Initialize() gform.TabDatos.Item(1).VisibleSeg = False gform.TabDatos.Item(2).VisibleSeg = False gform.TabDatos.Item(3).VisibleSeg = False gform.TabDatos.Item(4).VisibleSeg = False lSQL = "Select Descrip, IdProyecto from vPers_Proyectos WHERE IdProyectoPadre is null and IdProyecto <> " & gForm.Controls("EObjeto").ObjGlobal.Propiedades("IdProyecto") CreaCampoCombo "Pers_IdProyectoPadre",gForm.Controls("PnlTab")(0), 3390, 2490, 4440, 300, "Proyecto Padre:" ,1500, lSql, 3045, "Descrip", 8, 1000, "IdProyecto", 8, 2, 2, "EObjeto", "IdProyectoPadre" CreaCampoTexto "Pers_Porcentaje", gForm.Controls("PnlTab")(0), 255, 3650, 3075, 300, "Revenue Share:", 1500, 0, "EObjeto", "Pers_PorcentajeTercero" CreaCampoTexto "Pers_UpFront", gForm.Controls("PnlTab")(0), 255, 1383, 3075, 300, "UpFront:", 1500, 0, "EObjeto", "Pers_UpFront" CreaCampoTexto "Pers_FixFee", gForm.Controls("PnlTab")(0), 255, 1758, 3075, 300, "FixFee:", 1500, 0, "EObjeto", "Pers_FixFee" CreaCampoTexto "Pers_UpFrontAcumulado", gForm.Controls("PnlTab")(0), 3405, 1383, 4400, 300, "UpFront (Pte):", 1500, 0, "EObjeto", "Pers_UpFrontAcumulado" CreaCampoTexto "Pers_GastosAcumulado", gForm.Controls("PnlTab")(0), 3405, 1758, 4400, 300, "Gastos (Pte):", 1500, 0, "EObjeto", "Pers_GastosAcumulado" Set lPnl2 = gForm.Controls.Add("Threed.SSPanel", "pnlAgenciasIngresos") With lPnl2 .Object.AutoSize = 3 'ssChildToPanel .Visible = True gForm.Controls("TabDatos").InsertItem 7, "Ag. Ingresos", .Object.Hwnd, 170 'Set gForm.Controls("PnlTab").COntainer = lPnl2 End With Set lPnl3 = gForm.Controls.Add("Threed.SSPanel", "pnlAgenciasGastos") With lPnl3 .Object.AutoSize = 3 'ssChildToPanel .Visible = True gForm.Controls("TabDatos").InsertItem 8, "Ag. Gastos", .Object.Hwnd, 170 'Set gForm.Controls("PnlTab").COntainer = lPnl2 End With Set lPnl4 = gForm.Controls.Add("Threed.SSPanel", "pnlPresupuestos") With lPnl4 .Object.AutoSize = 3 'ssChildToPanel .Visible = True gForm.Controls("TabDatos").InsertItem 9, "Presupuestos", .Object.Hwnd, 170 'Set gForm.Controls("PnlTab").COntainer = lPnl2 End With 'gForm.Width = gForm.Width+500 CargaGridIngresos CargaGridGastos CargaGridPresupuestos gForm.Controls("Botonera").activarScripts = True End Sub Sub CargaGridPresupuestos() Set lGrid = gForm.Controls.Add("AhoraOCX.cntGridUsuario", "Presupuestos", gForm.Controls("pnlPresupuestos")) lGrid.AplicaEstilo With lGrid .Agregar = True .Editar = True .Eliminar = True .CargaObjetos = False .EditarPorObjeto = False .AgregaColumna "IdProyecto", 0, "IdProyecto", False .AgregaColumna "IdPresupuesto", 3000, "Presupuesto", False, "Select IdPresupuesto, Descrip from Pers_Presupuestos" .AgregaColumna "IdEquipo", 3000, "Equipo", False , "Select IdEquipo, Descrip from Pers_Equipos where staff = 0 " .AgregaColumna "Porcentaje", 1500, "%Dedicacion", False .From = "Pers_Presupuestos_Equipos_Proyectos" .TablaObjeto = "Pers_Presupuestos_Equipos_Proyectos" .Where = "WHERE IdProyecto = " & gForm.Controls("EObjeto").ObjGlobal.Propiedades("IdProyecto") .Campo("IdProyecto").Default = gForm.Controls("EObjeto").ObjGlobal.Propiedades("IdProyecto") .AplicaEstilo .Refresca = True .Visible = True .ValueItems "IdPresupuesto", "Select IdPresupuesto, Descrip from Pers_Presupuestos", False .ValueItems "IdEquipo", "Select IdEquipo, Descrip from Pers_Equipos", False .campo ("IdPresupuesto").coleccion = "Presupuestos_Gestion" .Campo ("IdPresupuesto").ColeccionWhere = "Where IdPresupuesto = @IdPresupuesto" End With End Sub Sub CargaGridIngresos() Set lGrid = gForm.Controls.Add("AhoraOCX.cntGridUsuario", "Ingresos Agencias", gForm.Controls("pnlAgenciasIngresos")) lGrid.AplicaEstilo With lGrid .Agregar = True .Editar = True .Eliminar = True .CargaObjetos = False .EditarPorObjeto = False .AgregaColumna "IdProyecto", 0, "" .AgregaColumna "IdCliente", 1800, "Agencia", False , "Select IdCliente, Cliente from Clientes_Datos " .AgregaColumna "IdProyectoAgencia", 1500, "ID Proyecto", False .AgregaColumna "UsuarioAgencia", 1500, "Usuario", False .From = "Pers_Proyectos_Agencias_Ingresos" .TablaObjeto = "Pers_Proyectos_Agencias_Ingresos" .Where = "WHERE IdProyecto = " & gForm.Controls("EObjeto").ObjGlobal.Propiedades("IdProyecto") .Campo("IdProyecto").Default = gForm.Controls("EObjeto").ObjGlobal.Propiedades("IdProyecto") .AplicaEstilo .Refresca = True .Visible = True .ValueItems "IdCliente", "Select IdCliente, Cliente from Clientes_Datos", False End With End Sub Sub CargaGridGastos() Set lGrid = gForm.Controls.Add("AhoraOCX.cntGridUsuario", "Gastos Agencias", gForm.Controls("pnlAgenciasGastos")) lGrid.AplicaEstilo With lGrid .Agregar = True .Editar = True .Eliminar = True .CargaObjetos = False .EditarPorObjeto = False .AgregaColumna "IdProyecto", 0, "" .AgregaColumna "IdProveedor", 1800, "Agencia", False , "Select IdProveedor, Proveedor from Prov_Datos " .AgregaColumna "IdProyectoAgencia", 1500, "ID Proyecto", False .AgregaColumna "UsuarioAgencia", 1500, "Usuario", False .From = "Pers_Proyectos_Agencias_Gastos" .TablaObjeto = "Pers_Proyectos_Agencias_Gastos" .Where = "WHERE IdProyecto = " & gForm.Controls("EObjeto").ObjGlobal.Propiedades("IdProyecto") .Campo("IdProyecto").Default = gForm.Controls("EObjeto").ObjGlobal.Propiedades("IdProyecto") .AplicaEstilo .Refresca = True .Visible = True .ValueItems "IdProveedor", "Select IdProveedor, Proveedor from Prov_Datos", False End With End Sub Sub Botonera_BeforeExecute(aBotonera, aBoton, aCancel) If aBoton.Name = "botGuardar" Then If gForm.Eobjeto.ObjGlobal.Propiedades("IdProyecto") <> "0" Then UpFrontPte = gForm.Controls("Pers_UpFrontAcumulado").text UpFrontPteBDD = gcn.DameValorCampo("select Pers_UpFrontAcumulado from Conf_Proyectos where IdProyecto = "&gForm.Controls("IdProyecto").text&"") GastosAcumulados = gForm.Controls("Pers_GastosAcumulado").text GastosAcumuladosBDD = gcn.DameValorCampo("select Pers_GastosAcumulado from Conf_Proyectos where IdProyecto = "&gForm.Controls("IdProyecto").text&"") IdProyecto = gForm.Controls("IdProyecto").text vDate = gcn.DameValorCampo("select GETDATE()") If CDbl(UpFrontPte) <> CDbl(UpFrontPteBDD) Then IdLineaMovimientoHistorico = gcn.DameValorCampo("select ISNULL(MAX(IdMovimiento),0) + 1 from Pers_Historico_Mov_UpFrontGastos") lSql = "insert into Pers_Historico_Mov_UpFrontGastos(IdMovimiento, TipoMovimiento, Descrip, Importe, IdObjCabecera, IdObjLinea, IdProyecto, FechaMovimiento) values ("&IdLineaMovimientoHistorico&",'UpFront', 'Modificado tras el objeto Proyectos',"&UpFrontPte&",NULL,NULL,"&IdProyecto&",'"&CDate(VDate)&"')" If Not gcn.executeSql(CStr(lSql),,,,False) Then MsgBox "Error insertando movimiento" MsgBox gcn.DameTodosLosErrores,vbcritical,"Error" Exit Sub End If End If If CDbl(GastosAcumulados) <> CDbl(GastosAcumuladosBDD) Then IdLineaMovimientoHistorico = gcn.DameValorCampo("select ISNULL(MAX(IdMovimiento),0) + 1 from Pers_Historico_Mov_UpFrontGastos") lSql = "insert into Pers_Historico_Mov_UpFrontGastos(IdMovimiento, TipoMovimiento, Descrip, Importe, IdObjCabecera, IdObjLinea, IdProyecto, FechaMovimiento) values ("&IdLineaMovimientoHistorico&",'Gastos', 'Modificado tras el objeto Proyectos',"&GastosAcumulados&",NULL,NULL,"&IdProyecto&",'"&CDate(VDate)&"')" If Not gcn.executeSql(CStr(lSql),,,,False) Then MsgBox "Error insertando movimiento" MsgBox gcn.DameTodosLosErrores,vbcritical,"Error" Exit Sub End If End If End If End If End Sub <file_sep>/Genera/Scripts migracion datos/INSERT_UPDATE Proveedores.sql begin tran INSERT INTO Prov_Datos (FechaAlta, IdProveedor, RazonSocial, Proveedor, Nif, Direccion, Web, E_Mail, NumTelefono, Notas) select GETDATE(), RIGHT('00000'+cast(IdProveedor as nvarchar(10)),5), Proveedor,Proveedor, CIF, DIRECCION, Web, Correo, Telefono, Actividad from OPENROWSET('Microsoft.ACE.OLEDB.12.0', 'Excel 12.0;HDR=YES;Database=C:\TEMP\Proveedores _Clientes.xlsx;', 'SELECT * FROM [Proveedor$]') update Prov_Datos_Economicos set FormaPago = ISNULL(x.IdFormatPago,0), IdMoneda = ISNULL(x.Moneda,1) from OPENROWSET('Microsoft.ACE.OLEDB.12.0', 'Excel 12.0;HDR=YES;Database=C:\TEMP\Proveedores _Clientes.xlsx;', 'SELECT * FROM [Proveedor$]') x where x.IdPRoveedor = Prov_Datos_Economicos.IdProveedor commit tran<file_sep>/Genera/Stored/pPers_DespuesEliminar_IngresoLinea.sql USE [GENERA] GO /****** Object: StoredProcedure [dbo].[pPers_DespuesEliminar_IngresoLinea] Script Date: 25/06/2015 18:22:42 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: <<NAME>> -- Create date: <09/06/2015> -- Description: <Si se elimina una linea de un ingresoAgencia : -- update el campo Importe total -- borrar la linea de pedido cliente que coresponde a la linea de ingreso -- borrar la linea de pedido proveedor que coresponde a la linea de ingreso> -- ============================================= CREATE PROCEDURE [dbo].[pPers_DespuesEliminar_IngresoLinea] -- Add the parameters for the stored procedure here @IdCabecera smallint, @IdLinea smallint, @TipoObj varchar(20), @Return varchar(255) OUTPUT AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON; DECLARE @IdPedido T_Id_Pedido DECLARE @IdLineaPed T_Id_Linea DECLARE @ImporteTotal DECIMAL DECLARE @IdPEdidoProv T_Id_Pedido DECLARE @IdLineaPedProv T_Id_Linea -- Insert statements for procedure here BEGIN TRY IF @TipoObj = 'IngresoAgencia' BEGIN --Definicion de las variables necesarias para identificar despues la linea de PEDIDO CLIENTE a borrar Set @IdPedido = (select IdPedido from Pers_IngresoAgencia_Cabecera where IdIngresoAgencia = @IdCabecera) Set @IdLineaPed = (select IdPedidoLinea from Pers_IngresoAgencia_Lineas where IdIngresoAgencia = @IdCabecera and IdIngresoAgenciaLinea = @IdLinea) Set @ImporteTotal = (select sum(Importe) from Pers_IngresoAgencia_Lineas where IdIngresoAgencia = @IdCabecera and IdIngresoAgenciaLinea <> @IdLinea) --Definicion de las variables necesarias para identificar despues la linea de PEDIDO PROVEEDOR a borrar Set @IdPedidoProv = (select IdPedidoProv from Pers_Mapeo_Ingreso_PedidoProv where IdIngresoAgencia = @IdCabecera and IdIngresoAgenciaLinea = @IdLinea) Set @IdLineaPedProv = (select IdLinea from Pers_Mapeo_Ingreso_PedidoProv where IdIngresoAgencia = @IdCabecera and IdIngresoAgenciaLinea = @IdLinea) --Update el campo Importe total despues de borrar una linea de IngresoAgenciaLinea update Pers_IngresoAgencia_Cabecera set ImporteTotal = @ImporteTotal where IdIngresoAgencia = @IdCabecera --BORRAR PEDIDO PROVEEDOR --------------------------------------------------------------------------------------------------------------------------------------------------------- IF EXISTS (select Idpedido from Pedidos_Prov_Lineas where Idpedido = @IdPedidoProv and IdLinea = @IdLineaPedProv) BEGIN delete from Pedidos_Prov_Lineas where Idpedido = @IdPedidoProv and IdLinea = @IdLineaPedProv END IF (select count(1) from Pedidos_Prov_Lineas where IdPedido = @IdPedidoProv) = 0 BEGIN delete from Pedidos_Prov_Cabecera where IdPedido = @IdPedidoProv END --------------------------------------------------------------------------------------------------------------------------------------------------------- --BORRAR PEDIDO CLIENTE --------------------------------------------------------------------------------------------------------------------------------------------------------- IF (select IdEstado from Pedidos_Cli_Lineas where IdPedido = @IdPedido and IdLinea = @IdLineaPed) > 0 BEGIN PRINT dbo.Traducir(14178, 'Imposible eliminar líneas de Pedido facturadas') RETURN 0 END --El pedido no tiene mas lineas, borramos IF @IdLineaPed = 0 And @IdPedido <> 0 BEGIN delete from Pedidos_Cli_Cabecera where IdPedido = @IdPedido update Pers_IngresoAgencia_Cabecera set IdPedido = 0 where IdIngresoAgencia = @IdCabecera END --El pedido tiene lineas, borramos la linea asociada a la linea del ingresoAgencia IF @IdLineaPed <> 0 And @IdPedido <> 0 BEGIN IF (select IdEstado from Pedidos_Cli_Lineas where IdPedido = @IdPedido and IdLinea = @IdLineaPed) = 0 BEGIN delete from Pedidos_Cli_Lineas where IdPEdido = @IdPedido and IdLinea = @IdLineaPed update Pers_IngresoAgencia_Lineas set IdPedidoLinea = 0 where IdIngresoAgencia = @IdCabecera and IdIngresoAgenciaLinea = @IdLinea END END --Conprobacion final para averiguar que despues de las supreciones, queda un pedido sin lineas IF (select count(IdLinea) from Pedidos_Cli_Lineas where IdPedido = @IdPedido) = 0 BEGIN delete from Pedidos_Cli_Cabecera where IdPedido = @IdPedido update Pers_IngresoAgencia_Cabecera set IdPedido = 0 where IdIngresoAgencia = @IdCabecera END --------------------------------------------------------------------------------------------------------------------------------------------------------- RETURN -1 END END TRY BEGIN CATCH IF @@TRANCOUNT >0 BEGIN ROLLBACK TRAN END DECLARE @CatchError NVARCHAR(MAX) SET @CatchError=dbo.funImprimeError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE()) RAISERROR(@CatchError,12,1) RETURN 0 END CATCH END GO <file_sep>/Genera/Stored/pPers_Importar_Imputacion_Empleado_Proyecto.sql SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER PROCEDURE [dbo].[pPers_Importar_Imputacion_Empleado_Proyecto] (@IdImportacion int, @Retorno varchar(400) OUTPUT) AS BEGIN TRY DECLARE @Valores TABLE (Valor varchar(100)) DECLARE @EMPLEADO varchar(100) IF (SELECT COUNT(*) FROM ( SELECT IdEmpleado, SUM(PorcentajeDedic) Porcent FROM Pers_Importa_Dedicacion_Empleado_Proyecto_Lineas WHERE IdImportacion = @IdImportacion GROUP BY IdEmpleado HAVING SUM(PorcentajeDedic) > 100 or SUM(PorcentajeDedic) < 100 )tbo ) > 0 BEGIN INSERT INTO @Valores (Valor) SELECT LEFT(tbo.Apellidos, 100) FROM ( SELECT l.IdEmpleado, SUM(PorcentajeDedic) Porcent, e.Apellidos FROM Pers_Importa_Dedicacion_Empleado_Proyecto_Lineas l INNER JOIN Empleados_Datos E ON E.IdEmpleado = l.IdEmpleado WHERE IdImportacion = 1 GROUP BY l.IdEmpleado, e.Apellidos HAVING SUM(PorcentajeDedic) > 100 or SUM(PorcentajeDedic) < 100 )tbo WHILE (SELECT COUNT(1) FROM @Valores) > 0 BEGIN SELECT TOP 1 @EMPLEADO = Valor FROM @Valores IF LEN(ISNULL(@Retorno, '')) < 400 BEGIN SET @Retorno = ISNULL(@Retorno, '') + @EMPLEADO + char(13) END DELETE FROM @Valores WHERE Valor = @EMPLEADO END RAISERROR ('EXISTEN TRABAJADORES CUYO LA SUMATORIA DE LOS PORCENTAJES ES DESIGUAL DE 100.', 12, 1) END END TRY BEGIN CATCH IF @@TRANCOUNT >0 BEGIN ROLLBACK TRAN END DECLARE @CatchError NVARCHAR(MAX) SET @CatchError=dbo.funImprimeError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE()) RAISERROR(@CatchError,12,1) RETURN 0 END CATCH <file_sep>/Genera/Stored/PPers_GenerarPedidoCliente_From_Ingreso.sql USE [GENERA] GO /****** Object: StoredProcedure [dbo].[PPers_GenerarPedidoCliente_From_Ingreso] Script Date: 29/06/2015 18:19:16 ******/ SET ANSI_NULLS OFF GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: <Gaetan, COLLET> -- Create date: <01/06/2015> -- Description: <Permite la creacion del pedido cliente a la hora de generar los pedidos despues de la importacion de los ingresos de una agencia> -- ============================================= ALTER PROCEDURE [dbo].[PPers_GenerarPedidoCliente_From_Ingreso] @Fecha T_Fecha_Corta OUTPUT, @IdCliente T_Id_Cliente OUTPUT, @DescripcionPed Varchar(255) OUTPUT, @IdEmpleado T_Id_Empleado , @IdMoneda T_Id_Moneda OUTPUT, @IdIngresoAgencia int AS /********************************************************************************************************************************* Declarar las variables **********************************************************************************************************************************/ BEGIN DECLARE @IdPedido T_Id_Pedido =0 DECLARE @IdEmpresa T_Id_Empresa = 0 DECLARE @AñoNum T_AñoNum = 1999 DECLARE @SeriePedido T_Serie=0 DECLARE @NumPedido T_Id_Pedido =0 DECLARE @Origen T_Origen = NULL DECLARE @IdPedidoCli Varchar(30) = 0 DECLARE @IdContacto int = (Select IdContacto from Clientes_Datos where IdCliente = @IdCliente) DECLARE @IdContactoA int = (Select IdContactoA from Clientes_Datos where IdCliente = @IdCliente) DECLARE @IdContactoF int = (Select IdContactoF from Clientes_Datos where IdCliente = @IdCliente) DECLARE @IdLista T_Id_Lista =0 DECLARE @IdListaRevision T_Revision_ =1 --DECLARE @IdEmpleado T_Id_Empleado = 0 DECLARE @IdDepartamento T_Id_Departamento =0 DECLARE @IdTransportista T_Id_Proveedor = NULL --DECLARE @IdMoneda T_Id_Moneda =1 DECLARE @FormaPago T_Forma_Pago =0 DECLARE @Descuento Real = 0 DECLARE @ProntoPago Real =0 DECLARE @IdPortes T_Id_Portes ='D' DECLARE @IdIva T_Id_Iva =0 DECLARE @IdEstado T_Id_Estado =0 DECLARE @IdSituacion T_Id_Situacion =0 DECLARE @FechaSalida T_Fecha_Corta = GETDATE() DECLARE @Observaciones Varchar(255) = '' DECLARE @Comision Real=0 DECLARE @Cambio T_Precio= (select Cambio from funDameCambioMoneda(2,gETDATE())) DECLARE @CambioEuros T_Precio= (select Cambio from funDameCambioMoneda(2,gETDATE())) DECLARE @CambioBloqueado T_Booleano=0 DECLARE @Representante T_Id_Empleado=0 DECLARE @IdCentroCoste T_Id_CentroCoste=NULL DECLARE @IdProyecto T_Id_Proyecto=NULL DECLARE @IdOferta T_Id_Oferta=NULL DECLARE @Revision smallint=NULL DECLARE @Inmovilizado T_Booleano =0 DECLARE @IdPrioridad int = 1 DECLARE @Referencia varchar(50)='0' DECLARE @RecogidaPorCli T_Booleano=0 DECLARE @ContactoLlamada varchar(255)=NULL DECLARE @Hora varchar(5)=NULL DECLARE @HoraSalida varchar(5)=NULL DECLARE @IdTipoPedido int=0 DECLARE @RecEquivalencia T_Booleano=0 DECLARE @Bloqueado T_Booleano=0 DECLARE @IdMotivoBloqueo int=NULL DECLARE @IdEmpleadoBloqueo int=NULL DECLARE @IdApertura int=NULL DECLARE @IdPedidoOrigen T_Id_Pedido=0 DECLARE @NoCalcularPromo T_Booleano=0 --Datos necesarios para generar las lineas DECLARE @IdProyectoLin T_id_proyecto DECLARE @ImporteProyecto Real DECLARE @DescripProyecto varchar(max) /********************************************************************************************************************************* Llamar a la stored estandard de creacion de cabecerra de pedido para crearla **********************************************************************************************************************************/ BEGIN TRY --Crear la cabecera del pedido pasandole el IdCliente, la moneda de la Agencia, el ultimo cambio Euros-Dolares disponible Declare @vRet int Exec @vRet = pPedidos_Cli_Cabecera_I @IdPedido output , @IdEmpresa , @AñoNum , @SeriePedido , @NumPedido , @Fecha , @IdCliente , @Origen , @IdPedidoCli , @IdContacto , @IdContactoA , @IdContactoF , @DescripcionPed , @IdLista , @IdListaRevision , @IdEmpleado , @IdDepartamento , @IdTransportista , @IdMoneda , @FormaPago , @Descuento , @ProntoPago , @IdPortes , @IdIva , @IdEstado , @IdSituacion , @FechaSalida , @Observaciones , @Comision , @Cambio , @CambioEuros , @CambioBloqueado , @Representante , @IdCentroCoste , @IdProyecto , @IdOferta , @Revision , @Inmovilizado , @Referencia , @RecogidaPorCli , @ContactoLlamada , @Hora , @HoraSalida , @IdTipoPedido , @RecEquivalencia , @Bloqueado , @IdMotivoBloqueo , @IdEmpleadoBloqueo , @IdApertura , @IdPedidoOrigen , @NoCalcularPromo , NULL,NULL,NULL --Asociar el IdPedido de la cabecera generada a la cabecera del IngresoAgencia actual. Eso para que, cuando borramos un ingresoAgencia, se borre automaticamente los pedidos asociados update Pers_IngresoAgencia_Cabecera set IdPEdido = @IdPedido where IdIngresoAgencia = @IdIngresoAgencia /********************************************************************************************************************************* Declare un cursor para recuperar todas las lineas del ingreso actual Añadimos un group by porque puede ser que varios IdProyectosAgencia hacen referencia a un solo IdProyecto en el ERP Para cada uno de los proyectos, llamamos a la stored pPers_PPedidos_Cli_Lineas_I para crear la linea de pedido **********************************************************************************************************************************/ DECLARE @PrecioMoneda T_Precio DECLARE @Precio_EURO T_Precio DECLARE @IdIngresoAgenciaLinea int DECLARE cursor_ingresoAgenciaLineas CURSOR FOR select distinct il.IdProyecto, SUM(il.Importe), 'Proyecto '+ p.Descrip +': ' + il.IdProyecto from Pers_IngresoAgencia_Lineas il inner join Proyectos p on il.IdProyecto = p.IdProyecto where il.IdIngresoAgencia = @IdIngresoAgencia GROUP BY il.IdProyecto, 'Proyecto '+ p.Descrip +': ' + il.IdProyecto OPEN cursor_ingresoAgenciaLineas FETCH cursor_ingresoAgenciaLineas INTO @IdProyectoLin, @ImporteProyecto, @DescripProyecto WHILE @@FETCH_STATUS = 0 BEGIN SET @PrecioMoneda = @ImporteProyecto SET @Precio_EURO = @ImporteProyecto --Si la moneda no es Euro, ponemos la variable Precio_Euro a 0 porque no hace falta ternerla IF @IdMoneda > 1 BEGIN SET @Precio_EURO = 0 END Exec pPers_PPedidos_Cli_Lineas_I @IdPedido, @Precio_EURO, @PrecioMoneda, @DescripProyecto, @Fecha, @IdIngresoAgencia FETCH cursor_ingresoAgenciaLineas INTO @IdProyectoLin, @ImporteProyecto, @DescripProyecto END CLOSE cursor_ingresoAgenciaLineas DEALLOCATE cursor_ingresoAgenciaLineas RETURN -1 END TRY BEGIN CATCH IF @@TRANCOUNT >0 BEGIN ROLLBACK TRAN END DECLARE @CatchError NVARCHAR(MAX) SET @CatchError=dbo.funImprimeError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE()) RAISERROR(@CatchError,12,1) RETURN 0 END CATCH END <file_sep>/Genera/Scripts migracion datos/INSERT Equipos.sql begin tran INSERT INTO Pers_Equipos (IdEquipo, Descrip, Activo, Staff) select IdEquipo, Equipo,1,0 from OPENROWSET('Microsoft.ACE.OLEDB.12.0', 'Excel 12.0;HDR=YES;Database=C:\TEMP\Maestro.xlsx;', 'SELECT * FROM [Equipo$]') where IdEquipo not in (select IdEquipo from Pers_Equipos) commit tran<file_sep>/Genera/Scripts migracion datos/INSERT Pers_Proyectos_Agencias_Ingresos.sql begin tran insert into Pers_Proyectos_Agencias_Ingresos ( IdProyecto, IdCliente, IdProyectoAgencia, NombreAPP) select RIGHT('00000'+cast(IDPROYECTO as nvarchar(10)),4) IdProyecto, RIGHT('00000'+cast(IDAGENCIA as nvarchar(10)),5) IdAgencia, CODIGOENAGENCIA, NOMBREAPP from OPENROWSET('Microsoft.ACE.OLEDB.12.0', 'Excel 12.0;HDR=YES;Database=C:\TEMP\Maestro.xlsx;', 'SELECT * FROM [Definitivo$]') x where x.IDAGENCIA is not null commit tran <file_sep>/Genera/Stored/pPers_DesgloceLinea_Pedidos.sql USE [GENERA] GO /****** Object: StoredProcedure [dbo].[pPERS_DesgloceLinea_Pedidos] Script Date: 15/07/2015 14:30:03 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: <Gaetan, COLLET> -- Create date: <10/06/2015> -- Description: <Realizar el desgloce analitico de la linea de pedido Cliente o Proveedor -- Depende del parametro @Objeto = Tipo objeto : Linea pedido cliente o linea pedido proveedor> -- ============================================= ALTER PROCEDURE [dbo].[pPERS_DesgloceLinea_Pedidos] @Objeto varchar(50) OUTPUT, @IdPedido T_Id_Pedido OUTPUT, @IdLinea T_Id_Linea OUTPUT, @IdDocObjeto T_Id_Doc OUTPUT, @FechaImputacion T_Fecha_Corta OUTPUT, @Descrip varchar(255) OUTPUT AS BEGIN DECLARE @Porcentaje T_Real124 DECLARE @IdProyecto varchar(15) DECLARE @IdEquipo int DECLARE @CentroCoste T_Id_CentroCoste -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON; -- Insert statements for procedure here --Obtener el IdProyecto a partir de la descripcion de la linea de pedido Set @IdProyecto = LTRIM(SUBSTRING(@Descrip,CHARINDEX( ':' ,@Descrip) +1,len(@Descrip))) --Averrigamos si el proyecto tiene une proyecto Padre (caso de Talking y PlayTales), si tiene, cambiamos el valor de la variable @IdProyecto con el IdProyecto del padre -- porque el desgloce analitico se hace con el IdProyecto padre SET @IdProyecto = (Select case when IdProyectoPadre is null then IdProyecto else IdProyectoPadre end from Conf_Proyectos where IdProyecto = @IdProyecto) BEGIN TRY --Declaramos el cursos para recoger todos los equipos que trabajen sobre el proyecto corriente --Tenemos en cuante la fecha de imputacion y para obtener la configuracion de los equipos correspondiente al presupuesto activo a la fecha de imputacion DECLARE cursor_desgloceAnalitico CURSOR FOR select pep.IdEquipo, pep.IdProyecto, pep.Porcentaje from Pers_Presupuestos_Equipos_Proyectos pep inner join Pers_Presupuestos p on pep.IdPresupuesto = p.IdPresupuesto where @FechaImputacion between p.Fecha_Inicio and p.Fecha_Fin and pep.IdProyecto = @IdProyecto OPEN cursor_desgloceAnalitico FETCH NEXT FROM cursor_desgloceAnalitico INTO @IdEquipo, @IdProyecto, @Porcentaje WHILE @@FETCH_STATUS = 0 BEGIN --Construimos el centro de coste de la forma siguiente : IdEquipo (2 digits) || IdProyecto (4 digits) Set @CentroCoste = (select right('00' + convert(varchar,@IdEquipo),2)) Set @CentroCoste += (select right('0000' + convert(varchar,@IdProyecto),4)) --Para arreglar un fallo durante la insercion del centro de coste para el desgloce de linea de pedido proveedor, borramos la linea existente antes de crear una nueva linea IF @Objeto = 'PedidoProv_Linea' BEGIN /*Insercion en la tabla CentrosCoste_Objetos*/ DELETE FROM [dbo].[CentrosCoste_Objetos] WHERE [Objeto] = 'PedidoProv_Linea' and [IdDocObjeto] = @IdDocObjeto and [CentroCoste] = @CentroCoste and [Porcentaje] = @Porcentaje END INSERT INTO [dbo].[CentrosCoste_Objetos] ([Objeto],[IdDocObjeto],[CentroCoste],[Porcentaje]) VALUES (@Objeto, @IdDocObjeto, @CentroCoste, @Porcentaje) FETCH NEXT FROM cursor_desgloceAnalitico INTO @IdEquipo, @IdProyecto, @Porcentaje END CLOSE cursor_desgloceAnalitico DEALLOCATE cursor_desgloceAnalitico -- Nuevo proceso despues de crear la definicion de los centros de costes en CentrosCoste_Objetos -- Tenemos que definir en Conta_CentrosCoste los centros de coste que existan en CentrosCoste_Objetos pero no en Conta_CentrosCoste -- Al final del cursor de insercion de los centros de costes en CentrosCoste_Objetos, insertamos en Conta_CentrosCoste INSERT INTO Conta_CentrosCoste(IdCentroCoste, Descrip, Bloqueado, FechaBloqueo, MotivoBloqueo) SELECT DISTINCT cc.CentroCoste, 'C.C. ' + pe.Descrip +' '+ po.Descrip, 0, NULL,NULL FROM CentrosCoste_Objetos cc INNER JOIN Pers_Equipos pe ON pe.idEquipo = LEFT(cc.CentroCoste,2) INNER JOIN Proyectos po ON po.IdProyecto = RIGHT(cc.CentroCoste, 4) WHERE cc.CentroCoste NOT IN (SELECT IdCentroCoste FROM Conta_CentrosCoste) RETURN -1 END TRY BEGIN CATCH IF @@TRANCOUNT >0 BEGIN ROLLBACK TRAN END DECLARE @CatchError NVARCHAR(MAX) SET @CatchError=dbo.funImprimeError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE()) RAISERROR(@CatchError,12,1) RETURN 0 END CATCH END<file_sep>/Genera/Trigger/Pers_Presupuestos_Equipos_Proyectos_UTrig.sql USE [GENERA] GO /****** Object: Trigger [dbo].[Pers_Presupuestos_Equipos_Proyectos_UTrig] Script Date: 08/07/2015 14:29:39 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TRIGGER [dbo].[Pers_Presupuestos_Equipos_Proyectos_UTrig] ON [dbo].[Pers_Presupuestos_Equipos_Proyectos] AFTER UPDATE AS BEGIN IF EXISTS (SELECT 1 FROM INSERTED i INNER JOIN Pers_Presupuestos pp ON i.IdPresupuesto = pp.IdPresupuesto AND pp.Cerrado = 1) BEGIN PRINT dbo.Traducir(32705, 'No se puede modificar la estructura o los datos de un presupuesto cerrado.') ROLLBACK TRAN RETURN END UPDATE PPE set IngresosEnero = t1.IngresosEnero, IngresosFebrero = t1.IngresosFebrero, IngresosMarzo = t1.IngresosMarzo, IngresosAbril = t1.IngresosAbril, IngresosMayo = t1.IngresosMayo, IngresosJunio = t1.IngresosJunio, IngresosJulio = t1.IngresosJulio, IngresosAgosto = t1.IngresosAgosto, IngresosSeptiembre = t1.IngresosSeptiembre, IngresosOctubre = t1.IngresosOctubre, IngresosNoviembre = t1.IngresosNoviembre, IngresosDiciembre = t1.IngresosDiciembre from ( SELECT PP.[IdPresupuesto] ,PP.[IdEquipo] ,SUM(PP.[IngresosEnero]) as IngresosEnero ,SUM(PP.[IngresosFebrero]) as IngresosFebrero ,SUM(PP.[IngresosMarzo]) as IngresosMarzo ,SUM(PP.[IngresosAbril]) as IngresosAbril ,SUM(PP.[IngresosMayo]) as IngresosMayo ,SUM(PP.[IngresosJunio]) as IngresosJunio ,SUM(PP.[IngresosJulio]) as IngresosJulio ,SUM(PP.[IngresosAgosto]) as IngresosAgosto ,SUM(PP.[IngresosSeptiembre]) as IngresosSeptiembre ,SUM(PP.[IngresosOctubre]) as IngresosOctubre ,SUM(PP.[IngresosNoviembre]) as IngresosNoviembre ,SUM(PP.[IngresosDiciembre]) as IngresosDiciembre FROM [Pers_Presupuestos_Equipos_Proyectos] PP inner join inserted I ON PP.IdPresupuesto = I.IdPresupuesto and PP.IdEquipo = I.IdEquipo GROUP BY PP.IdPresupuesto, PP.IdEquipo) t1 inner join Pers_Presupuestos_Equipos PPE ON t1.IdPresupuesto = PPE.IdPresupuesto and t1.IdEquipo = PPE.IdEquipo END GO <file_sep>/Genera/Scripts migracion datos/LIMPIAR Base de datos.sql --Borrar la configuracion actual delete from Pers_Presupuestos_Equipos_Gastos delete from Pers_Presupuestos_Equipos_GastosStaff delete from Pers_Presupuestos_Equipos_Proyectos delete from Pers_Presupuestos_Equipos delete from Pers_Presupuestos_Equipos_Empleados delete from Pers_Presupuestos delete from Pers_Proyectos_Agencias_Ingresos delete from Pers_Proyectos_Agencias_Gastos delete from Proyectos delete from Pers_Equipos --Borrar los Ingresos y Gastos existentes delete from Pers_IngresoAgencia_Cab delete from Pers_GastosAgencia_Cab --Desabilitar el trigger Deleted de la tabla Almacen_Hist_Mov antes de borrar disable trigger [dbo].[Almacen_Hist_Mov_DTrig] ON [dbo].[Almacen_Hist_Mov] delete from Almacen_Hist_Mov enable trigger [dbo].[Almacen_Hist_Mov_DTrig] ON [dbo].[Almacen_Hist_Mov] --Borrar cabecera de pedidos proveedores y clientes delete from Pedidos_Cli_Cabecera delete from Pedidos_Prov_Cabecera --Borrar los datos de clientes y proveedores delete from Clientes_Datos where idCliente <> 0 delete from Prov_datos where idProveedor <> 0 --A ver lo que hacemos con los equipos<file_sep>/Genera/Stored/PPers_GenerarPedidoProveedor_From_Gastos.sql USE [GENERA] GO /****** Object: StoredProcedure [dbo].[PPers_GenerarPedidoProveedor_From_Gastos] Script Date: 29/06/2015 18:19:35 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: <Gaetan, COLLET> -- Create date: <01/06/2015> -- Description: <Permite la creacion del pedido proveedor a la hora de generar el pedido despues de importar los gastos (de marketing) que vienen de una agencia> -- ============================================= ALTER PROCEDURE [dbo].[PPers_GenerarPedidoProveedor_From_Gastos] @IdEmpresa T_Id_Empresa OUTPUT , @IdProveedor T_Id_Proveedor OUTPUT , @Fecha T_Fecha_Corta OUTPUT , @IdEmpleado T_Id_Empleado OUTPUT , @IdDepartamento T_Id_Departamento OUTPUT , @IdGastoAgencia int OUTPUT , @IdMoneda int OUTPUT AS BEGIN /*********************************************************************************************************************** Declaracion de la variables y inicializacion ************************************************************************************************************************/ DECLARE @IdPedido T_Id_Pedido = 0 --DECLARE @IdEmpresa T_Id_Empresa = 0 DECLARE @AnoNum T_AñoNum = 1999 DECLARE @NumPedido T_Id_Pedido = 0 --DECLARE @Fecha T_Fecha_Corta = GETDATE() --DECLARE @IdProveedor T_Id_Proveedor DECLARE @IdPedidoProv varchar(50) = NULL DECLARE @IdContacto int = (select IdContacto from Prov_Datos where IdProveedor = @IdProveedor) DECLARE @DescripcionPed varchar(255) = NULL DECLARE @IdLista T_Id_Lista = 0 --DECLARE @IdEmpleado T_Id_Empleado = NULL --DECLARE @IdDepartamento T_Id_Departamento = NULL DECLARE @IdTransportista T_Id_Proveedor = NULL --DECLARE @IdMoneda T_Id_Moneda = 0 DECLARE @FormaPago T_Forma_Pago = 0 DECLARE @Descuento Real = 0 DECLARE @ProntoPago Real = 0 DECLARE @IdPortes T_Id_Portes = 'D' DECLARE @IdIva T_Id_Iva = 0 DECLARE @IdEstado T_Id_Estado = 0 DECLARE @IdSituacion T_Id_Situacion = 0 DECLARE @FechaEntrega T_Fecha_Corta = @Fecha DECLARE @FechaEntregaTope T_Fecha_Corta = @Fecha DECLARE @Observaciones varchar(255) = NULL DECLARE @IdCentroCoste T_Id_CentroCoste = NULL DECLARE @IdCentroProd T_CentroProductivo = NULL DECLARE @IdCentroImp T_CentroImponible = NULL DECLARE @Codigo varchar(50) = NULL DECLARE @Cambio T_Precio = NULL DECLARE @CambioEuros T_Precio = 1 DECLARE @CambioBloqueado T_Booleano = 0 DECLARE @Confirmado T_Booleano = 0 DECLARE @IdCentroCalidad T_CentroCalidad = NULL DECLARE @IdProyecto T_Id_Proyecto = NULL DECLARE @Inmovilizado T_Booleano = 0 DECLARE @SeriePedido T_Serie = 0 DECLARE @Bloqueado T_Booleano = 0 DECLARE @IdMotivoBloqueo int = NULL DECLARE @IdEmpleadoBloqueo T_Id_Empleado = NULL DECLARE @IdOrden T_Id_Orden = 0 DECLARE @IdBono T_Id_Bono = NULL DECLARE @EnvioAObra T_Booleano = 0 DECLARE @IdTipoProv T_Id_Tipo = 0 DECLARE @PorcentajeProveedor Real --Datos necesarios para generar las lineas DECLARE @IdProyectoLin T_id_proyecto DECLARE @ImporteProyecto Real DECLARE @DescripProyecto varchar(max) DECLARE @TipoImport varchar(255) = 'Gasto' DECLARE @IdGastoAgenciaLinea int DECLARE @IdMonedaProveedor T_Id_Moneda DECLARE @CambioDelDia DECIMAL(18,4) SET @CambioDelDia = ( SELECT Cambio FROM funDameCambioMoneda(2, GETDATE()) ) if(@IdContacto is null or @IdContacto = '') set @IdContacto = (Select IdContacto from Prov_Datos where IdProveedor = @IdProveedor) Set @DescripcionPed = 'Generado desde Gasto numero : '+cast(@IdGastoAgencia as varchar) Set @IdMonedaProveedor = (Select ISNULL(IdMoneda,1) from Prov_Datos_Economicos where IDProveedor = @IdProveedor) BEGIN TRY Declare @vRet int Exec @vRet = pPedidos_Prov_Cabecera_I @IdPedido OUTPUT , @IdEmpresa , @AnoNum , @NumPedido , @Fecha , @IdProveedor , @IdPedidoProv , @IdContacto , @DescripcionPed , @IdLista , @IdEmpleado , @IdDepartamento , @IdTransportista , @IdMonedaProveedor, @FormaPago , @Descuento , @ProntoPago , @IdPortes , @IdIva , @IdEstado , @IdSituacion , @FechaEntrega , @FechaEntregaTope , @Observaciones , @IdCentroCoste , @IdCentroProd , @IdCentroImp , @Codigo , @CambioDelDia , @CambioDelDia , @CambioBloqueado , @Confirmado , @IdCentroCalidad , @IdProyecto , @Inmovilizado , @SeriePedido , @Bloqueado , @IdMotivoBloqueo , @IdEmpleadoBloqueo, @IdOrden , @IdBono , @EnvioAObra , @IdTipoProv , NULL , NULL , NULL --Asignar el numero de pedido proveedor generado a la cabecera de GastoAgencia update Pers_GastosAgencia_Cabecera set IdPedidoProv = @IdPedido where IdGastoAgencia = @IdGastoAgencia /********************************************************************************************************************************* Declare un cursor para recuperar todas las lineas del ingreso actual Para cada una de las lineas, llamar a la stored pPers_PPedidos_Cli_Lineas_I para crear una linea de pedido **********************************************************************************************************************************/ --CURSOR PARA CREAR LAS LINEAS DEL PEDIDO CREADO --PARA CADA LINEA (PROYECTO) UPDATE EL CAMPO GASTOS PENDIENTES DECLARE @Old_Pers_GastosAcumulado DECIMAL DECLARE @IdTercero T_Id_Proveedor DECLARE @ImporteGastoTercero DECIMAL DECLARE @PorcentajeTercero DECIMAL DECLARE @IdLineaMovimientoHistorico INT DECLARE @IdMonedaProyecto INT DECLARE @PrecioMoneda T_Precio DECLARE @Precio_euro T_Precio DECLARE cursor_gastosAgenciaLineas CURSOR FOR select distinct il.IdProyecto, SUM(il.Importe), p.Descrip + ' : ' + p.IdProyecto from Pers_GastosAgencia_Lineas il inner join Proyectos p on il.IdProyecto = p.IdProyecto where il.IdGastoAgencia = @IdGastoAgencia group by il.IdProyecto, p.Descrip + ' : ' + p.IdProyecto OPEN cursor_gastosAgenciaLineas FETCH cursor_gastosAgenciaLineas INTO @IdProyectoLin, @ImporteProyecto, @DescripProyecto WHILE @@FETCH_STATUS = 0 BEGIN IF @IdMonedaProveedor > 1 BEGIN SET @Precio_EURO = 0 SET @PrecioMoneda = @ImporteProyecto --Si la moneda del Excel es el euro, convert el importe porque queremos crear un pedido en dolare IF @IdMoneda = 1 BEGIN SET @PrecioMoneda = (@PrecioMoneda * @CambioDelDia) END END IF @IdMonedaProveedor = 1 BEGIN --Si la moneda del excel nos viene en dolare, convert el importe en EURO IF @IdMoneda > 1 BEGIN SET @Precio_EURO = @ImporteProyecto / @CambioDelDia END IF @IdMoneda = 1 BEGIN SET @Precio_EURO = @ImporteProyecto END SET @PrecioMoneda = @Precio_EURO END Exec PPERS_PPedidos_Prov_Lineas_I @IdPedido, @Precio_EURO, @PrecioMoneda, @DescripProyecto, @Fecha, @IdGastoAgencia, @TipoImport SET @IdTercero = (SELECT IdProveedor from Proyectos where IdProyecto = @IdProyectoLin) IF @IdTercero IS NOT NULL BEGIN SELECT @Old_Pers_GastosAcumulado = ISNULL(Pers_GastosAcumulado,0), @PorcentajeTercero = Pers_PorcentajeTercero FROM Conf_Proyectos where IdProyecto = @IdProyectoLin SET @ImporteGastoTercero = @ImporteProyecto * (@PorcentajeTercero / 100) SET @IdMonedaProyecto = (SELECT ISNULL(Pers_Moneda,1) from Conf_Proyectos where IdProyecto = @IdProyectoLin) --Si la Moneda del Proyecto es diferente de la Moneda que viene del gasto, convertimos el importe el la moneda del Proyecto IF @IdMoneda <> @IdMonedaProyecto BEGIN Exec @ImporteGastoTercero = Pers_Fun_DameImporteConCambio @ImporteGastoTercero, @IdMonedaProyecto END UPDATE Conf_Proyectos SET Pers_GastosAcumulado = (@Old_Pers_GastosAcumulado + @ImporteGastoTercero) where IdProyecto = @IdProyectoLin SET @IdLineaMovimientoHistorico = (SELECT ISNULL(MAX(IdMovimiento),0) from Pers_Historico_Mov_UpFrontGastos) INSERT INTO Pers_Historico_Mov_UpFrontGastos (IdMovimiento, TipoMovimiento, Descrip, Importe, IdObjCabecera, IdObjLinea, IdProyecto, FechaMovimiento) VALUES (@IdLineaMovimientoHistorico + 1, 'GastosPendientes', 'Moficado tras importacion de gasto' , (@Old_Pers_GastosAcumulado + @ImporteGastoTercero), @IdGastoAgencia, @IdGastoAgenciaLinea, @IdProyectoLin, GETDATE()) END FETCH cursor_gastosAgenciaLineas INTO @IdProyectoLin, @ImporteProyecto, @DescripProyecto END CLOSE cursor_gastosAgenciaLineas DEALLOCATE cursor_gastosAgenciaLineas DECLARE @Objeto varchar(50) = 'PedidoProv_Linea' --CURSOR PARA INSERTAR DESGLOSE ANALITICO DECLARE @IdLinea int DECLARE @IDDocLinea int DECLARE @Descrip nvarchar(MAX) DECLARE GeneraDesgloseCursor CURSOR FOR SELECT IdPedido, IdLinea, IdDoc, Descrip FROM Pedidos_Prov_Lineas where IdPedido = @IdPedido OPEN GeneraDesgloseCursor FETCH NEXT FROM GeneraDesgloseCursor INTO @IdPedido, @IdLinea, @IdDocLinea, @Descrip WHILE @@FETCH_STATUS = 0 BEGIN Exec PPERS_DesgloceLinea_Pedidos @Objeto, @IdPedido, @IdLinea, @IdDocLinea, @Fecha, @Descrip FETCH NEXT FROM GeneraDesgloseCursor INTO @IdPedido, @IdLinea, @IdDocLinea, @Descrip END CLOSE GeneraDesgloseCursor DEALLOCATE GeneraDesgloseCursor RETURN -1 END TRY BEGIN CATCH IF @@TRANCOUNT >0 BEGIN ROLLBACK TRAN END DECLARE @CatchError NVARCHAR(MAX) SET @CatchError=dbo.funImprimeError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE()) RAISERROR(@CatchError,12,1) RETURN 0 END CATCH END<file_sep>/Genera/Scripts migracion datos/INSERT Proyectos.sql begin tran insert into Proyectos (IdProyecto, Descrip, Fecha, IdEstado, Tipo, IdSituacion, IdDepartamento, SeguimientosTareas, IdDelegacion) SELECT RIGHT('00000'+cast(IdProyecto as nvarchar(10)),4), Proyecto, GETDATE(), 0, '(Sin definir)', 0,0,0,-1 from OPENROWSET('Microsoft.ACE.OLEDB.12.0', 'Excel 12.0;HDR=YES;Database=C:\TEMP\Maestro.xlsx;', 'SELECT * FROM [Proyecto$]') where RIGHT('00000'+cast(IdProyecto as nvarchar(10)),4) not in (select IdProyecto from Proyectos) UPDATE Proyectos set IdProveedor = RIGHT('00000'+cast(x.IdTercero as nvarchar(10)),5) from OPENROWSET('Microsoft.ACE.OLEDB.12.0', 'Excel 12.0;HDR=YES;Database=C:\TEMP\Maestro.xlsx;', 'SELECT * FROM [Definitivo$]') x where Proyectos.IdProyecto = x.IdProyecto and x.IdTercero is not null and x.IdTercero <> '#N/A' and x.IdTercero <> '' update Conf_Proyectos set Pers_PorcentajeTercero = 40 where IdProyecto in (select IdProyecto from Proyectos where IdProveedor is not null) update Conf_Proyectos set IdProyectoPadre = case when x.proyecto = 'TALKING' Then '0048' when x.proyecto = 'PT GOLD' or x.proyecto = 'PT CLASSIC' Then '0034' end from OPENROWSET('Microsoft.ACE.OLEDB.12.0', 'Excel 12.0;HDR=YES;Database=C:\TEMP\Maestro.xlsx;', 'SELECT * FROM [Definitivo$]') x where Conf_Proyectos.IdProyecto = RIGHT('00000'+cast(x.IdProyecto as nvarchar(10)),4) and x.Proyecto in ('PT CLASSIC','PT GOLD','TALKING') commit tran <file_sep>/Genera/Stored/pPers_CrearEstructuraPresupuesto.sql -- ============================================= -- Author: <<NAME>> -- Create date: <07/07/2015> -- Description: <Inicializacion de un nuevo presupuesto de gestion, copiamdo la estructura del presupuesto pasado> -- ============================================= ALTER PROCEDURE [dbo].[pPers_CrearEstructuraPresupuesto] @IdPresupuestoNuevo INT OUTPUT, @Anyo INT OUTPUT AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON; ------------------------------------------------------------------------------- -- Creacion del nuevo presupuesto : Pers_Presupuesto ------------------------------------------------------------------------------- BEGIN DECLARE @IdPresupuestoPasado INT DECLARE @Fecha_inicio_N T_Fecha_Corta DECLARE @Fecha_Fin_N T_Fecha_Corta DECLARE @AnyoP INT DECLARE @AnyoN INT SELECT @IdPresupuestoNuevo = IdPresupuesto + 1, @AnyoN = anyo + 1, @Fecha_inicio_N = DATEADD(year,1,Fecha_Inicio), @Fecha_Fin_N = DATEADD(year,1,Fecha_Fin) FROM Pers_Presupuestos WHERE IdPresupuesto = (SELECT MAX(IdPresupuesto) FROM Pers_Presupuestos) --Si el parametro Anyo es superior a 0, el usuario quiere crear el nuevo presupuesto a partir de la estructura del año selecionado --Si no, el usuario solo quiere crear un presupuesto vacio asi que creamos une registro en Pers_Presupuest y salimos de la stored IF @Anyo > 0 BEGIN SET @IdPresupuestoPasado = (SELECT IdPresupuesto FROM Pers_Presupuestos WHERE Anyo = @Anyo) END ELSE BEGIN INSERT INTO Pers_Presupuestos(IdPresupuesto , Anyo , Fecha_Inicio , Fecha_Fin , Descrip , IdEjercicio , IdEstado , Cerrado , Activo) VALUES (@IdPresupuestoNuevo, @AnyoN, @Fecha_Inicio_N, @Fecha_Fin_N, 'Presupuesto ' + CAST(@AnyoN AS VARCHAR), 0,0,0,0) RETURN -1 END INSERT INTO Pers_Presupuestos(IdPresupuesto , Anyo , Fecha_Inicio , Fecha_Fin , Descrip , IdEjercicio , IdEstado , Cerrado , Activo) VALUES (@IdPresupuestoNuevo, @AnyoN, @Fecha_Inicio_N, @Fecha_Fin_N, 'Presupuesto ' + CAST(@AnyoN AS VARCHAR), 0,0,0,0) IF NOT EXISTS (SELECT 1 FROM Pers_Presupuestos WHERE IdDoc = SCOPE_IDENTITY()) BEGIN PRINT dbo.Traducir(24176, 'ERROR EN INSERCIÓN. NO SE HA PODIDO INSERTAR EN LA TABLA DE PRESUPUESTOS.') RETURN 0 END END ------------------------------------------------------------------------------- -- Creacion de la estructura de : Pers_Presupuesto_Equipos ------------------------------------------------------------------------------- BEGIN INSERT INTO Pers_Presupuestos_Equipos( IdPresupuesto, IdEquipo, PorcGastosFijos, PorcGastosEstructura, IngresosEnero, IngresosFebrero, IngresosMarzo, IngresosAbril, IngresosMayo, IngresosJunio, IngresosJulio, IngresosAgosto, IngresosSeptiembre, IngresosOctubre, IngresosNoviembre, IngresosDiciembre, GastosEnero, GastosFebrero, GastosMarzo, GastosAbril, GastosMayo, GastosJunio, GastosJulio, GastosAgosto, GastosSeptiembre, GastosOctubre, GastosNoviembre, GastosDiciembre ) SELECT @IdPresupuestoNuevo, IdEquipo, PorcGastosFijos, PorcGastosEstructura, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 FROM Pers_Presupuestos_Equipos WHERE idPresupuesto = @IdPresupuestoPasado END ------------------------------------------------------------------------------- -- Creacion de la estructura de : Pers_Presupuesto_Equipos_Gastos ------------------------------------------------------------------------------- BEGIN INSERT INTO Pers_Presupuestos_Equipos_Gastos( IdPresupuesto, IdEquipo, IdTipoGasto, GastosEnero, GastosFebrero, GastosMarzo, GastosAbril, GastosMayo, GastosJunio, GastosJulio, GastosAgosto, GastosSeptiembre, GastosOctubre, GastosNoviembre, GastosDiciembre ) SELECT @IdPresupuestoNuevo, IdEquipo, IdTipoGasto, 0,0,0,0,0,0,0,0,0,0,0,0 FROM Pers_Presupuestos_Equipos_Gastos WHERE idPresupuesto = @IdPresupuestoPasado END ------------------------------------------------------------------------------- -- Creacion de la estructura de : Pers_Presupuestos_Equipos_GastosStaff ------------------------------------------------------------------------------- BEGIN INSERT INTO Pers_Presupuestos_Equipos_GastosStaff( IdPresupuesto, IdEquipo, IdEquipoStaff, GastosEnero, GastosFebrero, GastosMarzo, GastosAbril, GastosMayo, GastosJunio, GastosJulio, GastosAgosto, GastosSeptiembre, GastosOctubre, GastosNoviembre, GastosDiciembre ) SELECT @IdPresupuestoNuevo, IdEquipo, IdEquipoStaff, 0,0,0,0,0,0,0,0,0,0,0,0 FROM Pers_Presupuestos_Equipos_GastosStaff WHERE idPresupuesto = @IdPresupuestoPasado END ------------------------------------------------------------------------------- -- Creacion de la estructura de : Pers_Presupuestos_Equipos_Proyectos ------------------------------------------------------------------------------- BEGIN INSERT INTO Pers_Presupuestos_Equipos_Proyectos( IdPresupuesto, IdEquipo, IdProyecto, Porcentaje, IngresosEnero, IngresosFebrero, IngresosMarzo, IngresosAbril, IngresosMayo, IngresosJunio, IngresosJulio, IngresosAgosto, IngresosSeptiembre, IngresosOctubre, IngresosNoviembre, IngresosDiciembre ) SELECT @IdPresupuestoNuevo, IdEquipo, IdProyecto, Porcentaje, 0,0,0,0,0,0,0,0,0,0,0,0 FROM Pers_Presupuestos_Equipos_Proyectos WHERE idPresupuesto = @IdPresupuestoPasado END ------------------------------------------------------------------------------- -- Creacion de la estructura de : Pers_Presupuestos_Equipos_Empleados ------------------------------------------------------------------------------- BEGIN INSERT INTO Pers_Presupuestos_Equipos_Empleados( IdPresupuesto, IdEquipo, IdEmpleado, PorcDedicacion, GastosEnero, GastosFebrero, GastosMarzo, GastosAbril, GastosMayo, GastosJunio, GastosJulio, GastosAgosto, GastosSeptiembre, GastosOctubre, GastosNoviembre, GastosDiciembre ) SELECT @IdPresupuestoNuevo, IdEquipo, IdEmpleado, PorcDedicacion, 0,0,0,0,0,0,0,0,0,0,0,0 FROM Pers_Presupuestos_Equipos_Empleados WHERE idPresupuesto = @IdPresupuestoPasado END RETURN -1 END <file_sep>/Genera/Trigger/Pers_GastosAgencia_Cabecera_DTrig.sql SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: <Gaetan, COLLET> -- Create date: <02-07-2015> -- Description: <Trigger para eliminar el pedido proveedor a la hora de suprimir la cabecera de GastosAgencias> -- ============================================= CREATE TRIGGER [dbo].[Pers_GastosAgencia_Cabecera_DTrig] ON [dbo].[Pers_GastosAgencia_Cabecera] AFTER DELETE AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON; DELETE FROM Pedidos_Prov_Cabecera WHERE IdPedido = (SELECT IdPedidoProv FROM DELETED) END GO <file_sep>/Genera/Tabla/Pers_IngresoAgencia_Lineas.sql USE [GENERA] GO /****** Object: Table [dbo].[Pers_IngresoAgencia_Lineas] Script Date: 01/06/2015 16:49:46 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO SET ANSI_PADDING ON GO CREATE TABLE [dbo].[Pers_IngresoAgencia_Lineas]( [IdIngresoAgencia] [smallint] NOT NULL, [IdIngresoAgenciaLinea] [smallint] NOT NULL, [IdProyecto] [dbo].[T_Id_Proyecto] NOT NULL, [IdProyectoAgencia] [dbo].[T_Id_Proyecto] NULL, [Importe] [decimal](18, 0) NULL, [IdDoc] [dbo].[T_Id_Doc] IDENTITY(1,1) NOT NULL, [InsertUpdate] [dbo].[T_CEESI_Insert_Update] NOT NULL, [Usuario] [dbo].[T_CEESI_Usuario] NOT NULL, [FechaInsertUpdate] [dbo].[T_CEESI_Fecha_Sistema] NOT NULL, CONSTRAINT [PK_Pers_IngresoAgencia_Lineas] PRIMARY KEY CLUSTERED ( [IdIngresoAgencia] ASC, [IdIngresoAgenciaLinea] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO SET ANSI_PADDING OFF GO ALTER TABLE [dbo].[Pers_IngresoAgencia_Lineas] WITH CHECK ADD CONSTRAINT [FK_Pers_IngresoAgencia_Lineas_Pers_IngresoAgencia_Cab] FOREIGN KEY([IdIngresoAgencia]) REFERENCES [dbo].[Pers_IngresoAgencia_Cab] ([IdIngresoAgencia]) GO ALTER TABLE [dbo].[Pers_IngresoAgencia_Lineas] CHECK CONSTRAINT [FK_Pers_IngresoAgencia_Lineas_Pers_IngresoAgencia_Cab] GO <file_sep>/Genera/Vista/Vista Porcentaje imputacion proyecto equipo Nominas.sql CREATE VIEW vPers_Imputacion_Empleado_Nominas AS SELECT ino.IdImportacion as IdImportacion, ino.fecha as Fecha_Imputacion, right('00' + CAST(pep.idequipo AS VARCHAR),2) + right('0000' + dl.IdProyecto,4) as IdCentroCoste, 'C.C. ' + pe.Descrip + ' ' + pr.Descrip as CC_Descrip, dl.idEmpleado as IdEmpleado, dl.PorcentajeDedic as PorcentajeDedic, ed.NIF as NIF, pep.IdEquipo as IdEquipo, pe.Descrip as DescripEquipo, pep.Porcentaje as PorcentajeReparto_Equipo, ABS(ROUND(((ABS(ROUND(((inol.Bruto * dl.PorcentajeDedic) /100.0), 2)) * pep.Porcentaje) /100.0), 2)) as Bruto_ImporteEquipo, ABS(ROUND(((ABS(ROUND(((inol.Total_Coste_SS * dl.PorcentajeDedic) /100.0), 2)) * pep.Porcentaje) /100.0), 2)) as Total_Coste_SS_ImporteEquipo FROM Pers_Importa_Nominas ino INNER JOIN Pers_Importa_Nominas_Lineas inol on ino.IdImportacion = inol.IdImportacion INNER JOIN Empleados_Datos ed on ed.NIF = inol.NIF INNER JOIN Pers_Importa_Dedicacion_Empleado_Proyecto_Lineas dl ON dl.IdEmpleado = ed.IdEmpleado INNER JOIN Pers_Presupuestos_Equipos_Proyectos pep on pep.IdProyecto = dl.IdProyecto INNER JOIN Pers_Presupuestos pp on pp.IdPresupuesto = pep.IdPresupuesto INNER JOIN Proyectos pr on pr.IdProyecto = dl.IdProyecto INNER JOIN Pers_Equipos pe on pe.IdEquipo = pep.IdEquipo WHERE YEAR(dl.Fecha) = YEAR(ino.Fecha) and MONTH(dl.Fecha) = MONTH(ino.fecha) AND dl.PorcentajeDedic > 0 AND dl.fecha between pp.Fecha_Inicio and pp.Fecha_Fin AND ed.IdEmpleado IN (SELECT IdEmpleado FROM Pers_Presupuestos_Equipos_Empleados WHERE IdEquipo <> 1) UNION select ino.IdImportacion as IdImportacion, ino.fecha as Fecha_Imputacion, C.CentroCoste, 'C.C. ' + pe.Descrip + ' Estructura' as CC_Descrip, ed.IdEmpleado, 0, ed.NIF, pe.IdEquipo, pe.Descrip, C.Porcentaje, ABS(ROUND(((inol.Bruto * C.Porcentaje) /100.0), 2)) as Bruto_ImporteEquipo, ABS(ROUND(((inol.Total_Coste_SS * C.Porcentaje) /100.0), 2)) as Total_Coste_SS_ImporteEquipo FROM Pers_Importa_Nominas ino INNER JOIN Pers_Importa_Nominas_Lineas inol on ino.IdImportacion = inol.IdImportacion INNER JOIN Empleados_Datos ed on ed.NIF = inol.NIF INNER JOIN ( select '1' as Plug, CentroCoste, Porcentaje from TiposGastos_Definiciones def INNER JOIN TiposGastos_Delegaciones del ON def.IdTipoGasto = del.IdTipoGasto INNER JOIN CentrosCoste_Objetos co ON co.IdDocObjeto = del.IdDoc WHERE del.IdTipoGasto = 31) C ON C.Plug = '1' INNER JOIN Pers_Equipos pe ON pe.IdEquipo = LEFT(C.CentroCoste,2) WHERE ed.IdEmpleado IN (SELECT IdEmpleado FROM Pers_Presupuestos_Equipos_Empleados pep INNER JOIN Pers_Presupuestos pp ON pp.IdPresupuesto = pep.IdPresupuesto WHERE pep.IdEquipo = 1 and ino.Fecha between pp.Fecha_Inicio and pp.Fecha_Fin) <file_sep>/Genera/Stored/PPERS_PPedidos_Prov_Lineas_I.sql USE [GENERA] GO /****** Object: StoredProcedure [dbo].[PPERS_PPedidos_Prov_Lineas_I] Script Date: 29/06/2015 18:21:31 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER PROCEDURE [dbo].[PPERS_PPedidos_Prov_Lineas_I] @IdPedido T_Id_Pedido OUTPUT, @Precio_EURO T_Precio OUTPUT, @PrecioMoneda T_Precio OUTPUT, @Descrip Varchar(255) OUTPUT, @FechaEntrega T_Fecha_Corta OUTPUT, @IdObjetoAgencia int OUTPUT, @TipoImport varchar(255) OUTPUT AS --DECLARE @IdPedido T_Id_Pedido = 0 DECLARE @IdLinea T_Id_Linea = 0 DECLARE @IdArticulo T_Id_Articulo = '0' DECLARE @IdArticuloProv T_Id_Articulo = Null DECLARE @IdAlmacen T_Id_Almacen = 0 DECLARE @Cantidad T_Decimal_2 = 1 DECLARE @Precio T_Precio = 0 --DECLARE @Precio_EURO T_Precio = @PrecioMoneda --DECLARE @PrecioMoneda T_Precio = 0 DECLARE @Descuento T_Decimal = 0 DECLARE @IdIva T_Id_Iva = 0 DECLARE @IdEstado T_Id_Estado = 0 DECLARE @IdSituacion T_Id_Situacion = 0 DECLARE @IdEmbalaje T_Id_Articulo = NULL DECLARE @CantidadEmbalaje T_Cantidad_Embalaje = 1 DECLARE @Observaciones varchar(255) = Null --DECLARE @Descrip varchar(255) = '(GENERICO)' DECLARE @IdAlbaran T_Id_Albaran = NULL DECLARE @FechaAlbaran T_Fecha_Corta = NULL DECLARE @IdFactura T_Id_Factura = NULL DECLARE @FechaFactura T_Fecha_Corta = NULL DECLARE @Lote T_Lote = NULL DECLARE @Marca T_Id_Doc = NULL DECLARE @CuentaArticulo T_Cuenta_Corriente = NULL DECLARE @TipoUnidadPres T_Tipo_Cantidad = NULL DECLARE @UnidadesStock T_Decimal_2 = 0 DECLARE @UnidadesPres T_Decimal_2 = 1 DECLARE @Precio_EuroPres T_Precio = 0 DECLARE @PrecioMonedaPres T_Precio = 0 DECLARE @IdProyecto_Produccion T_Id_Proyecto_Produccion = NULL DECLARE @IdFase T_IdFase = NULL DECLARE @DtoLP1 T_Decimal = 0 DECLARE @DtoLP2 T_Decimal = 0 DECLARE @DtoLP3 T_Decimal = 0 DECLARE @DtoLP4 T_Decimal = 0 DECLARE @DtoLP5 T_Decimal = 0 DECLARE @DtoMan T_Decimal = 0 --DECLARE @FechaEntrega T_Fecha_Corta = '20150528 00:0:00.000' DECLARE @FechaEntregaTope T_Fecha_Corta = @FechaEntrega DECLARE @NumPlano varchar(50) = NULL DECLARE @IdParte T_Id_Parte = NULL DECLARE @IdPacking T_Id_Packing = NULL DECLARE @IdDocPadre T_Id_Doc = NULL DECLARE @IdOrdenRecepcion int = NULL DECLARE @CantRecep T_Decimal_2 = 0 DECLARE @Numbultos int = 1 DECLARE @IdEmbalajeFinal T_Id_Articulo = NULL DECLARE @CantidadEmbalajeFinal T_Cantidad_Embalaje = 1 DECLARE @IdEmbalaje_Disp T_Id_Articulo = NULL DECLARE @NumeroDeLotes int = 0 DECLARE @CantidadLotes T_Decimal_2 = 0 DECLARE @IdOrdenCarga int = NULL DECLARE @UdsCarga T_Decimal_2 = 0 DECLARE @NumBultosFinal int = 0 DECLARE @UdStockCarga T_Decimal_2 = 0 DECLARE @UdStockRecep T_Decimal_2 = 0 DECLARE @IdMaquina T_Id_Articulo = NULL DECLARE @IdDoc T_Id_Doc = NULL DECLARE @Usuario T_CEESI_Usuario = NULL DECLARE @FechaInsertUpdate T_CEESI_Fecha_Sistema = NULL Exec PPedidos_Prov_Lineas_I @IdPedido OUTPUT, @IdLinea OUTPUT, @IdArticulo, @IdArticuloProv, @IdAlmacen, @Cantidad, @Precio, @Precio_EURO, @PrecioMoneda, @Descuento, @IdIva, @IdEstado, @IdSituacion, @IdEmbalaje, @CantidadEmbalaje, @Observaciones, @Descrip OUTPUT, @IdAlbaran, @FechaAlbaran, @IdFactura, @FechaFactura, @Lote, @Marca, @CuentaArticulo, @TipoUnidadPres, @UnidadesStock, @UnidadesPres, @Precio_EuroPres, @PrecioMonedaPres, @IdProyecto_Produccion, @IdFase, @DtoLP1, @DtoLP2, @DtoLP3, @DtoLP4, @DtoLP5, @DtoMan, @FechaEntrega, @FechaEntregaTope, @NumPlano, @IdParte, @IdPacking,@IdDocPadre, @IdOrdenRecepcion, @CantRecep, @Numbultos, @IdEmbalajeFinal, @CantidadEmbalajeFinal, @IdEmbalaje_Disp, @NumeroDeLotes, @CantidadLotes, @IdOrdenCarga, @UdsCarga, @NumBultosFinal, @UdStockCarga , @UdStockRecep, @IdMaquina, @IdDoc OUTPUT, @Usuario, @FechaInsertUpdate if @TipoImport = 'Ingreso' BEGIN update Conf_Pedidos_Prov_Lineas set pFechaGasto = @FechaEntrega where IdPedido = @IdPedido and IdLinea = @IdLinea insert into Pers_Mapeo_Ingreso_PedidoProv(IdIngresoAgencia, IdPedidoProv, IdLinea) values (@IdObjetoAgencia , @IdPedido, @IdLinea) END if @TipoImport = 'Gasto' BEGIN update Conf_Pedidos_Prov_Lineas set pFechaGasto = @FechaEntrega where IdPedido = @IdPedido and IdLinea = @IdLinea --update Pers_GastosAgencia_Lineas set IdPedidoPRovLinea = @IdPedido where IdGastoAgencia = @IdObjetoAgencia and IdGastoAgenciaLinea = @IdObjetoAgenciaLinea END if @TipoImport <> '' BEGIN EXEC PPERS_DesgloceLinea_Pedidos 'PedidoProv_Linea' ,@IdPedido ,@IdLinea ,@IdDoc ,@FechaEntrega ,@Descrip END RETURN -1 <file_sep>/Genera/Trigger/Pers_Ped_Cli_Lin_CCoste_ITrig.sql USE [GENERA] GO /****** Object: Trigger [dbo].[Pers_Ped_Cli_Lin_CCoste_ITrig] Script Date: 01/06/2015 16:48:07 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: <<NAME>> -- Create date: <01/06/2015> -- Description: <Aņadir el porcentaje correspondiente a la linea de pedido en el centro de coste> -- ============================================= CREATE TRIGGER [dbo].[Pers_Ped_Cli_Lin_CCoste_ITrig] ON [dbo].[Pedidos_Cli_Lineas] AFTER INSERT AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON; DECLARE @Objeto varchar(50) = 'Pedido_Linea' DECLARE @IdDocObjeto T_Id_Doc DECLARE @CentroCoste T_Id_CentroCoste DECLARE @Porcentaje T_Real124 DECLARE @IdProyecto varchar(15) DECLARE @Descripcion varchar(255) DECLARE @IdEquipo int Set @IdDocObjeto = (select IdDoc from inserted) Set @Descripcion = (select Descrip from inserted) /*Recuperar el IdProyecto a partir de la descripcion de la linea de pedido*/ Set @IdProyecto = LTRIM(SUBSTRING(@Descripcion,CHARINDEX( ':' ,(select Descrip from inserted)) +1,len(@Descripcion))) print @IdProyecto /*Cursor sobre la table que contiene los porcentajes de cada equipo para despues insertar una linea en CentroCoste_Objeto*/ --Calcular el codigo del centro de coste, Equipo/Proyecto DECLARE cursor_desgloceAnalitico CURSOR FOR select idproyecto, idequipo, porcentaje from Pers_EquiposPorProyectos where idProyecto = @IdProyecto OPEN cursor_desgloceAnalitico FETCH cursor_desgloceAnalitico INTO @IdProyecto, @IdEquipo, @Porcentaje WHILE @@FETCH_STATUS = 0 BEGIN Set @CentroCoste = (select right('0000' + convert(varchar,@IdEquipo),4)) Set @CentroCoste += (select right('0000' + convert(varchar,@IdProyecto),4)) /*Insercion en la tabla CentrosCoste_Objetos*/ INSERT INTO [dbo].[CentrosCoste_Objetos] ([Objeto],[IdDocObjeto],[CentroCoste],[Porcentaje]) VALUES (@Objeto, @IdDocObjeto, @CentroCoste, @Porcentaje) FETCH cursor_desgloceAnalitico INTO @IdProyecto, @IdEquipo, @Porcentaje END CLOSE cursor_desgloceAnalitico DEALLOCATE cursor_desgloceAnalitico END GO <file_sep>/Genera/Tabla/Pers_IngresoAgencia_Cab.sql USE [GENERA] GO /****** Object: Table [dbo].[Pers_IngresoAgencia_Cab] Script Date: 01/06/2015 16:49:32 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO SET ANSI_PADDING ON GO CREATE TABLE [dbo].[Pers_IngresoAgencia_Cab]( [IdIngresoAgencia] [smallint] NOT NULL, [Descrip] [varchar](100) NULL, [IdMoneda] [dbo].[T_Id_Moneda] NULL, [IdCliente] [dbo].[T_Id_Cliente] NULL, [Fichero] [varchar](500) NULL, [FechaImport] [smalldatetime] NULL, [FechaIngreso] [smalldatetime] NULL, [ImporteTotal] [decimal](18, 0) NULL, [IdDoc] [dbo].[T_Id_Doc] IDENTITY(1,1) NOT NULL, [InsertUpdate] [dbo].[T_CEESI_Insert_Update] NOT NULL, [Usuario] [dbo].[T_CEESI_Usuario] NOT NULL, [FechaInsertUpdate] [dbo].[T_CEESI_Fecha_Sistema] NOT NULL, CONSTRAINT [PK_Pers_IngresoAgencia] PRIMARY KEY CLUSTERED ( [IdIngresoAgencia] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO SET ANSI_PADDING OFF GO <file_sep>/Genera/VbScript ERP/Nominas.vbs Sub Initialize() gform.Botonera.BotonAdd "Contabilizar", "Bot_Contabiliza", , 0, True, 123 gform.Botonera.BotonAdd "Ver Asiento", "Bot_VerAsiento", , 0, True, 123 gform.Botonera.BotonAdd "Contab. Pago", "Bot_ContabilizaPago", , 0, True, 123 gform.Botonera.BotonAdd "Ver Asiento Pago", "Bot_VerAsientoPago", , 0, True, 123 gForm.Controls("Botonera").Boton("Bot_Contabiliza").Visible = False gForm.Controls("Botonera").Boton("Bot_VerAsiento").Visible = False gForm.Controls("Botonera").Boton("Bot_ContabilizaPago").Visible = False gForm.Controls("Botonera").Boton("Bot_VerAsientoPago").Visible = False End Sub Sub Show() PintaGrid() gForm.Controls("Botonera").ActivarScripts = True If gCn.DameValorCampo("SELECT Count(1) FROM Pers_Importa_Nominas WHERE IsNull(IdDocApunte, 0) = 0 AND IsNull(IdDocApunte_SS, 0)= 0 AND IdImportacion=" & gForm.Controls("EObjeto").ObjGlobal.Propiedades("IdImportacion")) > 0 Then gForm.Controls("Botonera").Boton("Bot_Contabiliza").Visible = True Else gForm.Controls("Botonera").Boton("Bot_VerAsiento").Visible = True End If If gCn.DameValorCampo("SELECT Count(1) FROM Pers_Importa_Nominas WHERE IsNull(IdDocApunte_Pago, 0) = 0 AND IdImportacion=" & gForm.Controls("EObjeto").ObjGlobal.Propiedades("IdImportacion")) > 0 Then gForm.Controls("Botonera").Boton("Bot_ContabilizaPago").Visible = True Else gForm.Controls("Botonera").Boton("Bot_VerAsientoPago").Visible = True End If End Sub Sub PintaGrid() 'Impedir la modificacion de lo textBox porque no se rellenan aqui gForm.Controls("TextoUsuario")(1).Locked = True gForm.Controls("TextoUsuario")(2).Locked = True gForm.Controls("TextoUsuario")(3).Locked = True 'Crear el panel Set lPnl = gForm.Controls.Add("Threed.SSPanel", "Pers_PanelGrid", gForm.Controls("PnlMain")) lPnl.Width = gForm.Width - 500 lPnl.Height = gForm.Height - 3000 lPnl.Top = 1500 lPnl.Left = gForm.Controls("cntPanel")(1).left lPnl.Visible= True lPnl.autosize = 3 'Crear el Grid Set lGrid = gForm.Controls.Add("AhoraOCX.cntGridUsuario", "Pers_Grid_LineasNominas", lPnl) With lGrid .ResizeEnabled = True .ResizeRestanteV = True .ResizeRestanteH = True .ResizeV = 4 .AplicaEstilo .Visible = True .Agregar = False .Editar = False .Eliminar = False .CargaObjetos = False .EditarPorObjeto = False .AgregaColumna "Fecha", 0, "Fecha", False .AgregaColumna "Trabajador", 3000, "Trabajador",False .AgregaColumna "SalarioBase", 1200, "Salario base",,,,"#,##0.00", True .AgregaColumna "Bruto", 1200, "Bruto",,,,"#,##0.00", True .AgregaColumna "IRPF", 1200, "IRPF",,,,"#,##0.00", True .AgregaColumna "SS_Trab", 1200, "SS Trabajador",,,,"#,##0.00", True .AgregaColumna "Liquido", 1200, "Liquido",,,,"#,##0.00", True .AgregaColumna "SS", 1200, "SS Empresa",,,,"#,##0.00", True .AgregaColumna "ACC", 1200, "ACC",,,,"#,##0.00", True .AgregaColumna "Total_Coste_SS", 1200, "Total coste SS",,,,"#,##0.00", True .AgregaColumna "NIF", 0, "NIF",False .From = "Pers_Importa_Nominas_Lineas" .Where = "Where IdImportacion = "& gForm.Controls("TextoUsuario")(1).text& "" .campo ("Trabajador").Coleccion = "Empleados" .campo ("Trabajador").ColeccionWhere = "Where NIF = @NIF" .OrdenMultiple = "Trabajador" .RefrescaSinLoad = True .Refresca = True End With End Sub Sub Botonera_AfterExecute(aBotonera, aBoton) If aBoton.Name = "Bot_Contabiliza" Then Set lColParam = gcn.dameNewCollection lColParam.Add gForm.Controls("EObjeto").ObjGlobal.Propiedades("IdImportacion") lColParam.Add "" If gCn.EjecutaStoreCol("pPers_Nominas_Importar",lColParam) = True Then gForm.Controls("Botonera").Boton("Bot_Contabiliza").Visible = False gForm.Controls("Botonera").Boton("Bot_VerAsiento").Visible = True gForm.Controls("EObjeto").Refresh MsgBox "Nómina generada correctamente" Else On Error Resume Next If Len("" & CStr(lColParam.Item(2))) > 0 Then MsgBox "Error generando asiento. Los valores afectados son:" & vbcrlf & CStr(lColParam.Item(2)) End If End If End If If aBoton.Name = "Bot_VerAsiento" Then Dim lAsiento1 Dim lAsiento2 Dim lIdEjercicio Dim lAsiento lAsiento1 = gCn.DameValorCampo("SELECT Asiento FROM Conta_Apuntes WHERE IdDoc = " & gForm.Controls("EObjeto").ObjGlobal.Propiedades("IdDocApunte")) lAsiento2 = gCn.DameValorCampo("SELECT Asiento FROM Conta_Apuntes WHERE IdDoc = " & gForm.Controls("EObjeto").ObjGlobal.Propiedades("IdDocApunte_SS")) On Error Resume Next If Len("" & lAsiento1) > 0 Then lIdEjercicio = gCn.DameValorCampo("SELECT IdEjercicio FROM Conta_Apuntes WHERE IdDoc = " & gForm.Controls("EObjeto").ObjGlobal.Propiedades("IdDocApunte")) Else If Len("" & lAsiento2) > 0 Then lIdEjercicio = gCn.DameValorCampo("SELECT IdEjercicio FROM Conta_Apuntes WHERE IdDoc = " & gForm.Controls("EObjeto").ObjGlobal.Propiedades("IdDocApunte_SS")) End If End If lAsiento = "" If Len("" & lAsiento1) > 0 Then lAsiento = lAsiento1 If Len("" & lAsiento2) > 0 Then lAsiento = lAsiento & ", " & lAsiento2 End If Else If Len("" & lAsiento2) > 0 Then lAsiento = lAsiento2 End If End If If Len("" & lAsiento) > 0 Then Set lFrm = gcn.ahoraproceso("ObjFormConta_Apuntes",False) ' lFrm.carga_extracto CLng(lIdEjercicio), 0, Nothing, CStr(lAsiento) , True lFrm.carga_extracto CLng(lIdEjercicio), 0, Nothing, CStr(lAsiento) , True Else MsgBox "No se pudo acceder a los asientos generados" End If End If End Sub <file_sep>/Genera/Trigger/Pers_GastoAgencia_Lineas_DTrig.sql SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: <COLLET, Gaëtan> -- Create date: <23/07/2015> -- Description: <Actualizar el importe total de un GastosAgencia despues de eliminar una linea> -- ============================================= CREATE TRIGGER [dbo].[Pers_GastoAgencia_Lineas_DTrig] ON [dbo].[Pers_GastosAgencia_Lineas] AFTER DELETE AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON; DECLARE @IdGastoAgencia INT DECLARE @IdGastoAgenciaLinea INT DECLARE cursor_majImporte CURSOR FOR SELECT IdGastoAgencia, IdGastoAgenciaLinea FROM DELETED OPEN cursor_majImporte FETCH NEXT FROM cursor_majImporte INTO @IdGastoAgencia, @IdGastoAgenciaLinea WHILE @@FETCH_STATUS = 0 BEGIN IF EXISTS (SELECT * FROM Pers_GastosAgencia_Cabecera WHERE IdGastoAgencia = @IdGastoAgencia) BEGIN UPDATE Pers_GastosAgencia_Cabecera SET ImporteTotal = (SELECT ISNULL(SUM(Importe),0) FROM Pers_GastosAgencia_Lineas WHERE IdGastoAgencia = @IdGastoAgencia) WHERE IdGastoAgencia = @IdGastoAgencia END FETCH NEXT FROM cursor_majImporte INTO @IdGastoAgencia, @IdGastoAgenciaLinea END CLOSE cursor_majImporte DEALLOCATE cursor_majImporte END GO <file_sep>/Genera/VbScript ERP/GastoAgencia.vbs Sub Show() gForm.Controls("ComboUsuario")(2).Height = 300 gForm.Controls("TextoUsuario")(2).Height = 300 gForm.Controls("ComboUsuario")(1).Height = 300 gForm.Controls("TextoUsuario")(4).Height = 300 gForm.Controls("TextoUsuario")(5).Height = 300 If gForm.Controls("EObjeto").ObjGlobal.Propiedades("IdGastoAgencia") = "" Then lastId = gcn.dameValorCampo("select isnull(max(IdGastoAgencia),0) + 1 from Pers_GastosAgencia_Cabecera") gForm.Controls("TextoUsuario")(2).text = lastId gForm.Botonera.Boton("btImportGasto").Visible = False gForm.Botonera.Boton("btGenerarPed").Visible = False gForm.Botonera.Boton("btVerPed").Visible = False CrearGridAgenciaLineas Else CrearGridAgenciaLineas If gcn.dameValorCampo("select IdPedidoProv from Pers_GastosAgencia_Cabecera where IdGastoAgencia = "&gForm.Controls("TextoUsuario")(2).text&"") > 0 Then gForm.Botonera.Boton("btVerPed").Visible = True gForm.Botonera.Boton("btImportGasto").Visible = False gForm.Botonera.Boton("btGenerarPed").Visible = False BloquearGrid() Else gForm.Botonera.Boton("btVerPed").Visible = False gForm.Botonera.Boton("btImportGasto").Visible = True gForm.Botonera.Boton("btGenerarPed").Visible = True End If If gcn.dameValorCampo("select count(*) from Pers_GastosAgencia_Lineas where IdGastoAgencia = "&gForm.Controls("TextoUsuario")(2).text&"") < 1 Then gForm.Botonera.Boton("btGenerarPed").Visible = False End If End If gForm.Controls("TextoUsuario")(5).CaptionLink = True gForm.Controls("ComboUsuario")(1).CaptionLink = True gForm.Controls("ComboUsuario")(2).CaptionLink = True End Sub Sub Initialize() gform.Botonera.ActivarScripts = True gform.Botonera.BotonAdd " Generar pedido", "btGenerarPed", , , , 340 gform.Botonera.BotonAdd " Ver pedido", "btVerPed", , , , 340 gform.Botonera.BotonAdd " Importar Excel Gasto", "btImportGasto", , , , 433 gForm.Botonera.HabilitaBotones End Sub Sub CrearGridAgenciaLineas() Set lGrid = gForm.Controls.Add("AhoraOCX.cntGridUsuario", "GridAgenciaLineas",gForm.Controls("cntPanel")(2)) gForm.Controls("cntPanel")(2).ResizeInterior = True gForm.Controls("cntPanel")(2).ResizeEnabled = True lGrid.Visible = True lGrid.AplicaEstilo lGrid.Top = 500 lGrid.Width = gForm.Controls("cntPanel")(2).width lGrid.height = gForm.Controls("cntPanel")(2).height With lGrid If Not .Preparada Then '.Enabled=Not gForm.Eobjeto.ObjGlobal.Nuevo .Agregar = True .Editar = False .Eliminar = True .CargaObjetos = False .EditarPorObjeto = False .Grid.HeadLines = 2 .ActivarScripts = True .AgregaColumna "IdGastoAgencia", 0, "IdGastoAgencia",False .AgregaColumna "IdGastoAgenciaLinea", 0, "IdGastoAgenciaLinea",False .AgregaColumna "IdProyecto", 2000, "Codigo proyecto",False .AgregaColumna "IdProyectoAgencia", 3000, "Codigo proyecto interno a la agencia",False .AgregaColumna "Importe", 1500, "Importe",False,,,"#,##0.00" .AgregaColumna "@DescripProyecto", 5000, "Descripcion",True .FROM = "Pers_GastosAgencia_Lineas" .where = "Where IdGastoAgencia = '"&gForm.Controls("TextoUsuario")(2).text&"'" .Campo("@DescripProyecto").Sustitucion = "Select Descrip from Proyectos where IdProyecto = @IdProyecto" .campo("IdProyecto").Coleccion = "Proyectos" .campo("IdProyecto").ColeccionWhere = "Where IdProyecto = @IdProyecto" .campo("IdGastoAgencia").default = gForm.Controls("EObjeto").ObjGlobal.Propiedades("IdGastoAgencia") .campo("IdGastoAgenciaLinea").default = "Select isnull(max(IdGastoAgenciaLinea),0) +1 from Pers_GastosAgencia_Lineas" .ColumnaEscalada = "@DescripProyecto" .Refresca = True End If End With End Sub Sub GenerarPedidosProveedor() Set lColparams = gcn.DameNewCollection IdEmpresa = gcn.IdEmpresa IdProveedor = gForm.Controls("ComboUsuario")(2).text Fecha = gForm.Controls("TextoUsuario")(5).text IdEmpleado = gcn.idEmpleado IdDepartamento = gcn.idDepartamento IdGastoAgencia = gForm.Controls("EObjeto").ObjGlobal.Propiedades("IdGastoAgencia") IdMoneda = gForm.Controls("ComboUsuario")(1).text lColparams.add IdEmpresa lColparams.add IdProveedor lColparams.add Fecha lColparams.add IdEmpleado lColparams.add IdDepartamento lColparams.add IdGastoAgencia lColparams.add IdMoneda If Not gcn.EjecutaStoreCol("PPers_GenerarPedidoProveedor_From_Gastos", lColparams) Then MsgBox "No se ha podido crear el pedido proveedor asociado al proyecto numero : "&larr(i,lgrd.colindex("IdProyecto"))&"" , vbCritical, "Error creando pedido cliente" gForm.Botonera.Boton("btImportGasto").Visible = True Else MsgBox "Pedido proveedor generado" , vbInformation, "Informacion" gForm.Botonera.Boton("btGenerarPed").Visible = False gForm.Botonera.Boton("btVerPed").Visible = True gForm.Botonera.Boton("btImportGasto").Visible = False BloquearGrid() End If End Sub Sub Botonera_BeforeExecute(aBotonera, aBoton, aCancel) If aBoton.Name = "botGuardar" Then 'Comprobar que los campos obligatorios esten rellenos (da un fallo con la configuracion manual...) 'Los campos obligatorios son : Cliente, Moneda y Fecha. Si el Id ingreso no esta relleno, hay que rellenarlo automaticamente vProveedor = gForm.Controls("ComboUsuario")(2).text vMoneda = gForm.Controls("ComboUsuario")(1).text vFechaIngreso = gForm.Controls("TextoUsuario")(5).text If Len(vProveedor) = 0 Or Len(vMoneda) = 0 Or Len(vFechaIngreso) = 0 Then aCancel = True MsgBox "No se ha podido guardar. Los campos Proveedor, Moneda y Fecha tiene que ser rellenados",vbExclamation,"Informacion" Else gForm.Botonera.Boton("btImportGasto").Visible=True End If End If End Sub Sub Botonera_AfterExecute(aBotonera, aBoton) If aBoton.Name = "btGenerarPed" Then 'codigo para genera x pedidos proveedores que contenga una linea con el importe que va al tercero dependiente del porcentage establecido al principio del proyecto GenerarPedidosProveedor End If If aBoton.Name = "btImportGasto" Then lFichero = SelectFile() Set fso = CreateObject("Scripting.FileSystemObject") If Not fso.FileExists(lFichero) Then MsgBox "Fichero " & lFichero & " no existente" Exit Sub End If ImportarExcel lFichero End If If aBoton.Name = "btVerPed" Then Set lColPedProv = gcn.obj.dameColeccion("PedidosProv","Where IdPedido in (select distinct IdPedidoProv from Pers_GastosAgencia_Cabecera where IdGastoAgencia = "&gForm.Controls("EObjeto").ObjGlobal.Propiedades("IdGastoAgencia")&" )") If Not lColPedProv Is Nothing Then If lColPedProv.Count>0 Then lColPedProv.show End If End If End If End Sub Sub ImportarExcel(lFichero ) 'Abrir el fichero Excel Set objExcel = CreateObject("Excel.Application") Set objWorkbook = objExcel.Workbooks.Open(lFichero) row = 2 claveImportacion = gcn.IdEmpleado & "_" & RandomString IdProveedor = gForm.Controls("ComboUsuario")(2).text IdGastoAgencia = gForm.Controls("TextoUsuario")(2).text 'Selecionar la primera hoja objExcel.Worksheets(1).Activate 'Comprobar que las 2 primeras columnas existen While Len("" & objExcel.ActiveSheet.Cells(row, 1)) > 0 IdProyectoAgencia = objExcel.ActiveSheet.Cells(row, 1) ImporteGasto = Replace(objExcel.ActiveSheet.Cells(row, 2),",",".") IdLineaImport = gcn.dameValorCampo("select isnull(max(IdLineaImportacion), 1) +1 from Pers_Log_Importacion_GastoAgencia") 'Insertar en base de datos los datos para comprobar la integridad de los datos lSql = "insert into Pers_Log_Importacion_GastoAgencia(IdLineaImportacion, ClaveImportacion, IdGastoAgencia, IdProyectoAgencia, Importe) values ("&IdLineaImport&",'"&claveImportacion&"',"&IdGastoAgencia&",'"&IdProyectoAgencia&"',"&ImporteGasto&")" 'Si el insert falla, sacar um mensaje de error y detener la importacion If Not gcn.executeSql(CStr(lSql),,,,False) Then objworkbook.Saved = True objWorkbook.Close objExcel.Quit Set objExcel = Nothing Exit Sub End If 'Ir a la linea siguiente row = row + 1 Wend objExcel.Quit 'Despues de la importacion de las lineas, abrir un formulario de mantenimiento para ver las limeas importadas y indicar con una regla de color si existe un error o no Set params = gcn.DameNewCollection params.Add claveImportacion params.Add IdProveedor If gcn.EjecutaStoreCol("pPers_Importar_Datos_ImportGasto", params) Then gForm.Controls("GridAgenciaLineas").Refrescar If gcn.dameValorCampo("select count(IdGastoAgenciaLinea) from Pers_GastosAgencia_Lineas where IdGastoAgencia = "&gForm.Controls("TextoUsuario")(2).text&"") > 0 Then gForm.Botonera.Boton("btGenerarPed").Visible = True End If If MsgBox("Importacion terminada, quereis ver el importe de inportacion ?", vbYesNo, "Confirmacion") = vbYes Then AbrirFormImportacion(claveImportacion) End If End If gForm.Controls("GridAgenciaLineas").Refrescar gform.Eobjeto.Refresh End Sub Sub AbrirFormImportacion(lClaveUser) Set lFrm = gcn.ahoraproceso ("NewFrmMantenimiento",False,gcn) lfrm.Form.NombreForm = "Pers_frmMant_Import" With lFrm.Grid("Comprobacion de los datos a importar") ' NO_TRADUCIR_TAG .Agregar = True .Editar = True .Eliminar = True .CargaObjetos = False .EditarPorObjeto = False .Grid.HeadLines = 2 .AgregaColumna "IdLineaImportacion", 0, "Id.LineaImportacion", False .AgregaColumna "ClaveImportacion", 0, "Clave importacion", False .AgregaColumna "IdGastoAgencia", 0, "Id Gasto Agencia", False .AgregaColumna "IdProyectoAgencia", 1000, "Id proyecto",False .AgregaColumna "Importe", 1000, "Importe",False,,,"#,##0.00" .AgregaColumna "Texto_error", 2500, "Error",True .From = "Pers_Log_Importacion_GastoAgencia" .Where = "Where ClaveImportacion = '"&lClaveUser&"'" .ColumnaEscalada = "Texto_error" .OrdenMultiple = "IdLineaImportacion" .RefrescaSinLoad = True .Refresca = True End With lFrm.Form.Caption = "Comprobar los datos" lFrm.Carga , False, 4 End Sub Function SelectFile() Set wShell=CreateObject("WScript.Shell") Set oExec=wShell.Exec("mshta.exe ""about:<input type=file id=FILE><script>FILE.click();new ActiveXObject('Scripting.FileSystemObject').GetStandardStream(1).WriteLine(FILE.value);close();resizeTo(0,0);</script>""") sFileSelected = oExec.StdOut.ReadLine SelectFile = sFileSelected End Function Function RandomString() Dim max,min max=10000 min=1 Randomize RandomString = CStr(Int((max-min+1)*Rnd+min)) End Function Sub BloquearGrid() Set lGrid = gForm.Controls("GridAgenciaLineas") With lGrid .Eliminar = False .Agregar = False .Editar = False End With End Sub 'Para Activar este evento hay que configurar la grid. Poner en el sub Initialize por ejemplo: gForm.grdLineas.ActivarScripts = True Sub Grid_AfterDelete(aGrid) gform.Eobjeto.Refresh If gcn.dameValorCampo("select count(*) from Pers_GastosAgencia_Lineas where IdGastoAgencia = "&gForm.Controls("TextoUsuario")(2).text&"") < 1 Then gForm.Botonera.Boton("btGenerarPed").Visible = False End If End Sub <file_sep>/Genera/Project-Genera.sublime-project { "folders": [ { "path": "Scripts migracion datos" }, { "path": "Stored" }, { "path": "Tabla" }, { "path": "Trigger" }, { "path": "VbScript ERP" } ] } <file_sep>/Genera/Scripts migracion datos/INSERT_UPDATE Clientes.sql /* * Si queremos hacer la migracion de los datos a partir de un entorno aue no tenga Office 2007 o superior, tenemos que cambiar la version de Excel en el OpenRowSet : Excel 12.0 */ begin tran INSERT INTO Clientes_Datos (FechaAlta, IdCliente, RazonSocial, Cliente, Nif, Direccion, Web, NumTelefono) select GETDATE(), RIGHT('00000'+cast(IdCliente as nvarchar(10)),5),Cliente, Cliente, CIF, DIRECCION, Correo, Telefono from OPENROWSET('Microsoft.ACE.OLEDB.12.0', 'Excel 12.0;HDR=YES;Database=C:\TEMP\Proveedores _Clientes.xlsx;', 'SELECT * FROM [Cliente$]') update Clientes_Datos_Economicos set IdMoneda = t1.Moneda from OPENROWSET('Microsoft.ACE.OLEDB.12.0', 'Excel 12.0;HDR=YES;Database=C:\TEMP\Proveedores _Clientes.xlsx;', 'SELECT * FROM [Cliente$]') t1 where Clientes_Datos_Economicos.IdCliente = RIGHT('00000'+cast(t1.IdCliente as nvarchar(10)),5) and t1.Moneda is not null commit tran
5fefe7a91b93f46ea36b1838f2f6949dc692589b
[ "JSON with Comments", "TSQL", "SQL", "VBScript" ]
38
JSON with Comments
FRCayetano/Genera
f3614564348012d6ae6101c38f62096765019fd1
f1e300552186121eda7a5c945a00eb7883e94600
refs/heads/master
<repo_name>stevemolloy/toga_sandpit_for_duvet<file_sep>/make_a_window.py # noinspection PyUnresolvedReferences import toga from colosseum import CSS class MyApp(toga.App): def startup(self): main_window = toga.MainWindow(self.name) main_window.app = self main_box = toga.Box() main_box.add(self.make_toolbar()) main_box.add(self.make_maincontent()) main_window.content = main_box main_window.show() @staticmethod def make_toolbar(): toolbar_box = toga.Box(style=CSS( flex_direction='row', justify_content='space-between', padding=5, )) refresh_btn = toga.Button('Refresh') summary_label = toga.Label('???%', alignment=toga.RIGHT_ALIGNED) toolbar_box.add(refresh_btn) toolbar_box.add(summary_label) return toolbar_box @staticmethod def make_maincontent(): split = toga.SplitContainer(style=CSS(flex=1)) left_container = toga.Box() tree = toga.Tree(['Fake File Navigator']) root1 = tree.insert(None, None, 'root1') tree.insert(root1, None, 'root1.1') root1_2 = tree.insert(root1, None, 'root1.2') tree.insert(root1_2, None, 'root1.2.1') tree.insert(root1_2, None, 'root1.2.2') tree.insert(root1_2, None, 'root1.2.3') codebox = MyApp.make_codebox() split.content = [tree, codebox] return split @staticmethod def make_codebox(): code_box = toga.Box(style=CSS(flex=1)) with open('make_a_window.py') as f: code_text = toga.MultilineTextInput( initial=f.read(), readonly = True, style=CSS(flex=1), ) code_box.add(code_text) return code_box if __name__ == '__main__': app = MyApp('Duvet', 'org.pybee.duvet') app.main_loop()
a729adccf2d8c4837cf731a8b2e4d0491149bbdf
[ "Python" ]
1
Python
stevemolloy/toga_sandpit_for_duvet
3b39bd95369e1c70e9eb56aad2c6509b31c3bb12
5a0f7e451f58018e4f61150f941b4dba4fa02c32
refs/heads/main
<file_sep>"""You are a cashier whose goal is to give customers their correct change while using asfew total coins as possible. The input is the set of available coin denominations as integersx1, . . . , xn; and the amount of change that is due, an integer W. The output is the fewestnumber of total coins that add up to W. """ import array as arr def __coinDenomination_greedy__ (denomination, w): print ("Input\n \tdenominations" + str(denomination) + "weight: " + str(w) ) #sort coin denominations denomination.sort(reverse = True) print(denomination) count = 0 frequency = {} #Keep subtracting the larget denominations which satisfies the condition w[i] < remaining weight for i in denomination: count = count + w//i frequency[i] = w//i w = w%i print(count) #print the number of coins used per denominaiton print(frequency) def __coinDenomination_dynamic__ (denomination, w): print ("Input\n \tDenominations:" + str(denomination) + "Weight: " + str(w)) #W[0] =0 weight = [0]*(w+ 1) trace = [0]*(w+ 1) weight[0] = 0 for i in range(1,w+1): min_denominations = 99999 trace[i] = 0 for j in denomination: if (i - j >=0): if (min_denominations > weight[i-j]): min_denominations = weight[i-j] + 1 trace[i] = j if (min_denominations == 99999): weight[i] = 99999 else : weight[i] = min_denominations print("total coins used :",weight[w]) i = w while trace[i] !=0: print (trace[i], end= " ") i = i - trace[i] def __main__ (): print("this is main") denomination1 = [1,7,15,33,51,99] denomination2 = [1, 5, 10, 25, 50, 100] weight1 = 72 weight2 = 2919 #Greedy __coinDenomination_greedy__(denomination1, weight1) __coinDenomination_greedy__(denomination1, weight2) __coinDenomination_greedy__(denomination2, weight1) __coinDenomination_greedy__(denomination2, weight2) #using dynamic solution approch __coinDenomination_dynamic__(denomination1, weight1) __coinDenomination_dynamic__(denomination1, weight2) __coinDenomination_dynamic__(denomination2, weight1) __coinDenomination_dynamic__(denomination2, weight2) __main__()<file_sep>""" The edit distance between two strings (i.e. lists of characters) is the smallest number of transformations needed to convert one string into the other. The allowable transformations are: • Substitute one character for any character. • Insert a new character anywhere. • Delete any existing character. Note this is symmetric: If we can get from string X to Y in a series of transformations, we can get back in the same number of steps by reversing them. """ def edit_distance(string1, string2): E = [[0 for i in range(0, len(string1)+1)] for j in range(0, len(string2)+1)] for i in range(0,len(string2) + 1): E[i][0] = i # for the all deletion case. for j in range(0,len(string1) + 1): E[0][j] = j # for all insertion case. for i in range(1,len(string2) + 1): for j in range(1,len(string1) + 1): a = E[i-1][j] + 1 b = E[i][j-1] + 1 if (string2[i-1] == string1[j-1]): c = E[i-1][j-1] else : c = E[i-1][j-1] + 1 E[i][j] = min(a,b,c) print(E[len(string2)][len(string1)]) def __main__(): string1 = "HELLO" string2 = "HELL" edit_distance(string1, string2) __main__() <file_sep>''' Spanning trees: Given a connected undirected graphG= (V,E), aspanning treeis asubgraphT= (V,E′) that is a tree (connected graph with no cycles). Note thatTcontainsall vertices ofGand, becauseTis a tree, it has exactly|V|−1 edges. SupposeGhas nonnegative edge weightsw(e). Theweightof a spanning treeT= (V,E′)is the total weight of all its edges, i.e.∑e∈E′w(e). Aminimum spanning treeis a spanningtree of smallest weight. As you may know, there are greedy algorithms such as Prim’s andKruskal’s that find minimum spanning trees very efficiently. '''<file_sep>""" A contiguous subsequence of a list S is a subsequence made up of consecutive elements of S. For instance, if S is 5, 15, −30, 10, −5, 40, 10, then 15, −30, 10 is a contiguous subsequence but 5, 15, 40 is not. Give a linear-time algorithm for the following task: Input: A list of numbers, a1, a2, . . . , an. Output: The contiguous subsequence of maximum sum (a subsequence of length zero has sum zero). For the preceding example, the answer would be 10, −5, 40, 10, with a sum of 55. (Hint: For each j ∈ {1, 2, . . . , n}, consider contiguous subsequences ending exactly at position j.) """ def max_sum_continues_susequence (): print("")<file_sep>""" proble statement: The longest increasing subsequence (LIS) problem is: • Input: a nonempty list of integers. • Output: the length of its longest subsequence that is weakly increasing eg: 1) input : 1,2,3,4,5,6,7,8 output: 1,2,3,4,5,6,7,8. 2) input : 1, 5, 6, 3, 4, 8 output:1, 3, 4, 8 with a length of 4 elements. """ """ Algorithm 1 Longest Increasing Subsequence 1: Input: List A of integers, length n. 2: Create array L and set L[1] = 1. 3: for j = 2, . . . , n do 4: Set L[j] = 1. 5: for i = 1, . . . , j − 1 do 6: if A[i] ≤ A[j] and L[j] < L[i] + 1 then 7: Set L[j] = L[i] + 1. 8: end if 9: end for 10: end for 11: Return maxj L[j]""" def __LongestIncreasingSubsequence__(input_array): L = [] previous_selection = [] max = 1 for j in input_array: L[j] = 1 for i in j-1: if input_array[i] <= input_array[j] and L[j] < L[j] + 1: L[j] = L[i] +1 if max < L[j]: max = L[j] print("Length of longest increasing sequence:" + max) print("Runnig time for this algorithm is O(n^2)") def __main__ (): print("this is main") __main__()<file_sep>"""Longest Common Substringproblem, the input consists of two strings,XandY. Theoutput should be the length of the longest string that is a substring of bothXandY. A substring must be consecutive. For example, ifX=ALGORIT HMandY=RHY T HM, thenT HMis a substring of both, butRT HMis not a substring of either (eventhough it is a “subsequence”). """ def __longestSubSrtring__(string1, string2): max = 0 max_i = 0 max_j =0 C = [[0 for i in range(0, len(string2)+1)] for j in range(0, len(string1)+1)] for i in range(0, len(string1)): for j in range(0, len(string2)): if (i == 0 | j == 0): C[i][j] = 0 elif string1[i] == string2[j]: C[i][j] = C[i-1][j-1] +1 if(max < C[i][j]): max = C[i][j] max_i = i max_j =j else: C[i][j] = 0 print("Length of Longest sub string is :", max) print("Longest sub string is:", end=" ") temp_max_i = max_i - max +1 while C[max_i][max_j] >0: #print("temp i is ",temp_max_i) print( string1[temp_max_i], end=" ") max_i = max_i -1 max_j = max_j -1 temp_max_i = temp_max_i +1 def __main__ (): string1 = 'ALGORITHM' string2 = 'RHYTHM' __longestSubSrtring__(string1, string2) __main__()
617a17f779ee2de7d32578087b6c1aadeb6db082
[ "Python" ]
6
Python
sureshnnayak/Algorithms
431a3555e40342178ddc70494e7efec849913fb1
4cacc6d51aebe4b47419a5e6e1757ccc6ee301a7
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TreeHeight { public class BaszoTree { Bogyo root; public BaszoTree(Bogyo root) { this.root = root; } public int GetDepth() { return 0; } public void Add(int cucc) { root.Recursive(root, cucc); Console.WriteLine(root.Value); } public bool CheckRecursive(Bogyo bogyo, int cucc) { if(bogyo!=null) { if(root.Value == cucc) { return true; } else { if(CheckRecursive(bogyo.Left, cucc)) { return true; } if(CheckRecursive(bogyo.Right, cucc)) { return true; } } } return false; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TreeHeight { public class Program { static void Main(string[] args) { Bogyo root = new Bogyo(0); BaszoTree tree = new BaszoTree(root); tree.Add(10); tree.Add(1); tree.Add(15); tree.Add(16); tree.Add(111); tree.Add(4); Console.WriteLine(tree.CheckRecursive(root, 16)); Console.ReadKey(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TreeHeight { public class Bogyo { int value; Bogyo left; Bogyo right; public Bogyo(int value) { this.value = value; left = null; right = null; } public int Value { get; set; } public Bogyo Left { get; set; } public Bogyo Right { get; set; } public Bogyo Recursive(Bogyo bogyo, int value) { if(bogyo == null) { return new Bogyo(value); } else if(value >= bogyo.Value){ return Recursive(bogyo.right, value); } else if(value < bogyo.value) { return Recursive(bogyo.left, value); } } } }
2a054fef9576a8a5cecd650c5f497fc8c74c0be0
[ "C#" ]
3
C#
gaboroneSzabo/BinaryTree
59e0bf30a155f1f8444e7edfd92eb66b091a67be
59bf3a8ba695e4aa14962b180a84aa7668100709
refs/heads/master
<file_sep># HelloWorld Buat Coba coba aja Testing Update
42bbb5274074a08f059a3ed8ac6cc585d12b06b3
[ "Markdown" ]
1
Markdown
skayv13/HelloWorld
3d935f9ee1c2ddc40f8c7a17db7c7bb1c5664ad1
ef36269cf6fee7c9025367013801410a2376924a
refs/heads/master
<repo_name>ankit-jain-erpanderp/test-ldap-git<file_sep>/src/main/java/org/modules/LDAPClient.java package org.modules; import com.sun.jndi.ldap.LdapCtx; import javax.naming.Context; import javax.naming.NamingException; import javax.naming.directory.Attributes; import javax.naming.directory.DirContext; import javax.naming.directory.InitialDirContext; import java.util.Hashtable; public class LDAPClient { public static String suffix = "dc=mulesoft,dc=local"; public static Hashtable<String, String> environment; private static DirContext ctx; private static final String url = "ldap://172.17.0.3"; private static final String connectionType = "simple"; private static final String adminDN = "cn=admin,"+suffix; private static final String password = "<PASSWORD>"; public LDAPClient() { environment = new Hashtable<String, String>(); environment.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); environment.put(Context.PROVIDER_URL, url); environment.put(Context.OBJECT_FACTORIES, "java.naming.factory.object"); environment.put(Context.SECURITY_AUTHENTICATION, connectionType); environment.put(Context.SECURITY_PRINCIPAL, adminDN); environment.put(Context.SECURITY_CREDENTIALS, password); environment.put("com.sun.jndi.ldap.connect.pool", "true"); //This property is a system property environment.put("com.sun.jndi.ldap.connect.pool.initsize", "5"); } public void connection() { try { ctx = new InitialDirContext(environment); System.out.println("Connection is created"); } catch (NamingException exc) { System.out.println(exc.getResolvedName().toString()); System.err.println(exc.getMessage().toString()); } } /*simple lookup operation using JNDI */ public void lookUp(String lookupDn) { try { Object obj = ctx.lookup(lookupDn); LdapCtx ldapctx = (LdapCtx) ctx.lookup(lookupDn); System.out.println(obj.getClass()); System.out.println(obj.toString()); System.out.println("entry exist in server"); } catch (NamingException exc) { System.out.println(exc.getResolvedName().toString()); System.err.println(exc.getMessage().toString()); } } /* creating simple user entry to the LDAP server * EntryDn is the Dn and is of String Type * Attributes we have to add when creating an Entry*/ public void createUserEntry(String entryDN, Attributes attributes) { try { ctx.createSubcontext(entryDN, attributes); } catch (NamingException exc) { System.out.println(exc.getResolvedName().toString()); System.err.println(exc.getMessage().toString()); } } } <file_sep>/pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>s3sample</groupId> <artifactId>basic-access</artifactId> <version>1.0-SNAPSHOT</version> <packaging>jar</packaging> <name>Basic Access</name> <url>http://none.none</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <!-- https://mvnrepository.com/artifact/com.amazonaws/aws-java-sdk-core --> <dependency> <groupId>com.amazonaws</groupId> <artifactId>aws-java-sdk-core</artifactId> <version>1.11.79</version> </dependency> <!-- https://mvnrepository.com/artifact/com.amazonaws/aws-java-sdk-sqs --> <dependency> <groupId>com.amazonaws</groupId> <artifactId>aws-java-sdk-s3</artifactId> <version>1.11.79</version> </dependency> <!-- https://mvnrepository.com/artifact/com.amazonaws/aws-java-sdk-sqs --> <dependency> <groupId>com.amazonaws</groupId> <artifactId>aws-java-sdk-sqs</artifactId> <version>1.11.79</version> </dependency> <dependency> <groupId>com.amazonaws</groupId> <artifactId>aws-java-sdk-sts</artifactId> <version>1.11.98</version> </dependency> <dependency> <groupId>org.springframework.ldap</groupId> <artifactId>spring-ldap-ldif-core</artifactId> <version>2.0.4.RELEASE</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>exec-maven-plugin</artifactId> <version>1.1.1</version> <executions> <execution> <phase>test</phase> <goals> <goal>java</goal> </goals> <configuration> <mainClass>App</mainClass> <arguments> <argument>arg0</argument> <argument>arg1</argument> </arguments> </configuration> </execution> </executions> </plugin> </plugins> </build> </project>
92e2ab539a71e874bf3f7405e0c4f80669305b50
[ "Java", "Maven POM" ]
2
Java
ankit-jain-erpanderp/test-ldap-git
e4a426aeb89a990cd41569b8fd860968c6f801fc
1446089f3fa9e15d8b73ad4d490ca80c265ce31b
refs/heads/master
<file_sep>#include <iostream> #include <string> #include <locale> #include "stdio.h" using namespace std; void duffCopy(char* to, int size, char* from) { int n = (size + 7) / 8; switch (size % 8) { case 0: do { *to++ = *from++; case 7: *to++ = *from++; case 6: *to++ = *from++; case 5: *to++ = *from++; case 4: *to++ = *from++; case 3: *to++ = *from++; case 2: *to++ = *from++; case 1: *to++ = *from++; } while (--n > 0); } } void testDuffCopy() { int size = 100; char* from = new char[size]; for (int i = 0; i < size; i++) { int c = 97 + i % 26; from[i] = c; } char* to = new char[size]; duffCopy(to, size, from); for (int i = 0; i < size; i++) { printf("%c\r\n", to[i]); } } char *ptr = new char[1000]; int index = 0; int maxSize = 0; int running = 1; int startLoopCount = 0; void parseSingleInput(char in) { switch (in) { case 62: ++index; break; case 60: if (index < 1) { printf("Runtime error - index moved out of bounds\n"); } else --index; break; case 43: ++ptr[index]; break; case 45: --ptr[index]; break; case 46: putchar(ptr[index]); break; case 44: //input is handled separately //ptr[index]=getchar(); break; case 91: //loop endpoints are handled separately break; case 93: //loop endpoints are handled separately break; default: printf("Syntax error - invalid BF symbol: '%c'\n", in); break; } if (index >= maxSize) maxSize = index + 1; } void printState() { printf("\n\n"); printf("=============PROGRAM STATE=============\n"); printf("VALUES:\t"); for (int i = 0; i < maxSize; i++) printf("%d\t", (int)(ptr[i])); printf("\nindex:\t"); for (int i = 0; i < maxSize; i++) printf("%d\t", i); printf("\nPTR:\t"); for (int i = 0; i < index; i++) printf("\t"); printf("^\n"); } void printHelp() { printf("Valid BF syntax: \n"); printf("\t>\tIncrement data pointer\n"); printf("\t<\tDecrement data pointer\n"); printf("\t+\tIncrement data pointee\n"); printf("\t-\tDecrement data pointee\n"); printf("\t.\tOutput data pointee byte\n"); printf("\t,\tStore input as data pointee byte\n"); printf("\t[\tLoop opener\n"); printf("\t]\tIf data pointee == 0, jump to '['\n\n"); printf("\"clear\" to clear program state\n"); printf("\"exit\" to exit\n\n"); printState(); } void init() { for (int i = 0; i < 1000; i++) ptr[i] = 0; index = 0; maxSize = 1; running = 1; printf("\n=============STATE CLEARED=============\n"); printState(); } int findLoopEnd(string line, int start) { int openCount = 0; for (int i = start + 1; i < line.length(); i++) { if (line[i] == '[') openCount++; if (line[i] == ']') { if (openCount) openCount--; else return i; } } return -1; } void queryInput() { printf("input: "); cin >> ptr[index]; } int parseLine(string line) { if (line.compare("help") == 0) printHelp(); else if (line.compare("exit") == 0) running = 0; else if (line.compare("clear") == 0) init(); else { //CAN'T DO IT THIS WAY //DOESN'T SUPPORT MULTIPLE LOOPS for (int i = 0; i < (int)(line.length()); i++) { if (line[i] == '[') { int loopEnd = findLoopEnd(line, i); if (i > loopEnd) printf("Syntax error - loop end before loop start: ']' at position %d; '[' at position %d\n", loopEnd, i); string insideLoop = line.substr(i + 1, loopEnd - i - 1); parseLine(insideLoop); while (ptr[index]) parseLine(insideLoop); i = loopEnd; } else { if (line[i] == ',') queryInput(); else parseSingleInput(line[i]); //printState(); } } return 1; } return 0; } string getLine() { string input; getline(cin, input); return input; } void BFIDEMain() { init(); printf("Enter BF code or type \"help\" for help.\n"); while (running) { string input = getLine(); if (parseLine(input)) printState(); } printf("Goodbye :)\n"); } int main(void) { BFIDEMain(); // don't let the terminal window go away until we want it to /* char in; std::cin >> in; */ return 0; } <file_sep>random ====== Short, stupid, random stuff
4aca82f95744cd9ff604ac5f17749540d607734a
[ "Markdown", "C++" ]
2
Markdown
pwteneyck/random
6c2c76ffa7f010ccee4bc60c8a407a39fadc0a24
8b69075982a9244341d122491405e4f5656bdd73
refs/heads/master
<repo_name>LilacTree/partner-gifter<file_sep>/gifts.js module.exports = [ /** * You can add more gifts to this list if the gift you want to use is not listed below * * id: item id, can be found using the in-game command "/8 partnergifter find" * name: name of the item * cd: cooldown of the item (in seconds) * */ { id: 206049, name: "<NAME>", cd: 2, }, ]<file_sep>/README.MD # partner-gifter TERA-proxy module for TERA Online that automatically gives gift to your partner to keep them happy! ## Commands List of in-game commands (use in /proxy or /8 channel): - `partnergifter` - Toggles module (default: true) - `partnergifter notice` - Toggles notice (default: false) - `partnergifter find` - Finds out the Item ID of the gift ## Installation - Move files in `defs` into the `node_modules\tera-data\protocol\` folder - Add opcodes for your region in the `node_modules\tera-data\map\` folder ## Notes - If there are no opcodes for your region, get them yourself using https://github.com/SoliaRdi/PacketsLogger - Modify the config file to customize settings - Modify the gifts file to customize which gifts to use - Module only works for gifting partners and not regular pets ## Opcodes for NA (protocol.353337.map) S_UPDATE_SERVANT_INFO = 57591
7302252d826b60f155d81611a10a14ae099a09e3
[ "Markdown", "JavaScript" ]
2
Markdown
LilacTree/partner-gifter
6982f610d264bfd2093fee68d198e07a70569dee
d74b0c6deb727a09a30fba7feaf2eecb419989aa
refs/heads/master
<repo_name>cchaos/curiouschaos<file_sep>/client/assets/scss/site/pages/_rmb-page.scss $rmb-primary: #467c84; #rmb-page { .header_video_image { position: relative; .the_video { position: absolute; left: 0; bottom: 0; } } } #rmb-screenshot { &, .screenshot { // allow image's dropshadow to extend bounds overflow: visible; } img { border-radius: 5px; box-shadow: 0 4px 4px rgba(0, 0, 0, .1), 0 8px 8px rgba(0, 0, 0, .1), 0 8px 54px 9px rgba(0, 0, 0, .1);; } } #rmb-iphone-aside { padding: 0; margin-bottom: 0; .image img { max-height: 20rem; width: 100%; object-fit: cover; } aside { background-color: $rmb-primary; padding: 2rem; text-align: center; h4 { margin-top: 1rem; color: $white-smoke !important; margin-bottom: 2rem; } .button { font-weight: $font-weight-bold; } } @include breakpoint(large) { display: flex; > * { flex-basis: 50%; } .image img { max-height: none; width: auto; } aside { display: flex; flex-direction: column; justify-content: center; } } } <file_sep>/test.md ## YO!<file_sep>/client/assets/scss/site/components/_slick.scss $slick-font-path: ""; $slick-font-family: $paragraph-font-family; $slick-loader-path: "./" !default; $slick-arrow-color: $primary-color; $slick-dot-color: $oil; $slick-dot-color-active: $primary-color; $slick-prev-character: ""; $slick-next-character: ""; $slick-dot-character: "•" !default; $slick-dot-size: rem-calc(36); $slick-opacity-default: 0.75 !default; $slick-opacity-on-hover: 0.5; $slick-opacity-not-active: 0.25 !default; $slick-background: $smoke; $slick-arrow-icon-color: str-replace($slick-arrow-color, '#', '%23'); @import "../../../bower_components/slick-carousel/slick/slick-theme.scss"; @mixin change-slick-active-colors($color) { .slick-next { background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='#{$color}' width='105' height='105' viewBox='0 0 105 105'%3E%3Cpath d='M52.5 0A52.5 52.5 0 1 0 105 52.5 52.56 52.56 0 0 0 52.5 0zm0 100A47.5 47.5 0 1 1 100 52.5 47.55 47.55 0 0 1 52.5 100z'/%3E%3Cpath d='M60.15 30.73a2.5 2.5 0 0 0-3.54 3.54L72.36 50H26.62a2.5 2.5 0 0 0 0 5h45.73L56.6 70.73a2.5 2.5 0 1 0 3.55 3.54l20-20a2.5 2.5 0 0 0 0-3.54z'/%3E%3C/svg%3E"); } .slick-prev { background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='#{$color}' width='105' height='105' viewBox='0 0 105 105'%3E%3Cpath d='M52.5 105A52.5 52.5 0 1 0 0 52.5 52.56 52.56 0 0 0 52.5 105zm0-100A47.5 47.5 0 1 1 5 52.5 47.55 47.55 0 0 1 52.5 5z'/%3E%3Cpath d='M44.85 74.27a2.5 2.5 0 0 0 3.54-3.54L32.64 55h45.73a2.5 2.5 0 0 0 0-5H32.65L48.4 34.27a2.5 2.5 0 1 0-3.55-3.54l-20 20a2.5 2.5 0 0 0 0 3.54z'/%3E%3C/svg%3E"); } .slick-dots li.slick-active button:before { color: $color; } } .slick-slider { padding: $global-padding 0 $global-padding*3; background: $slick-background; margin-bottom: 0; .slick-next, .slick-prev { display: none !important; width: rem-calc(48); height: rem-calc(48); background-repeat: no-repeat; background-position: center center; background-size: 50% 50%; } @include change-slick-active-colors($slick-arrow-icon-color); .slick-next { right: 0; } .slick-prev { left: 0; } @include breakpoint(medium) { padding: $global-padding*2 $global-padding*2 $global-padding*4; .slick-next, .slick-prev { margin-top: -3rem; display: block !important; } .slick-next { right: -.75rem; } .slick-prev { left: -.75rem; } } // dots on top instead of bottom &.reverse { padding: $global-padding*3 0 $global-padding; .slick-dots { bottom: auto; top: $global-padding*.4; } .slick-next, .slick-prev { top: auto; bottom: 50%; margin-top: 0; margin-bottom: -$global-padding*2; } @include breakpoint(large) { padding: $global-padding*4 $global-padding*2 $global-padding*2; .slick-dots { top: $global-padding*1; } } } } .slick-dots { bottom: $global-padding*.8; left: 0; margin: 0; li button:before { transition: opacity .2s; } @include breakpoint(large) { bottom: $global-padding*1.6; } } @mixin slick-change-colors($color) { .slick-prev:before, .slick-next:before { color: $color; } .slick-dots li.slick-active button:before { color: $color; } } <file_sep>/client/assets/scss/site/pages/_cinario-page.scss $cinario-primary: #37474F; #cinario-page { } #cinario-personas { overflow: visible; background: $slick-background; padding-top: 2rem; > div, > div > * { overflow: visible; } .card { background: white; padding: 1rem; border-radius: 3px; box-shadow: 0 4px 4px rgba(0, 0, 0, .1), 0 8px 8px rgba(0, 0, 0, .1), 0 16px 16px rgba(0, 0, 0, .1); margin-bottom: 2rem; } .caption { padding-left: 2rem; padding-right: 2rem; font-style: italic; text-align: center; font-size: $small-font-size; } @include breakpoint(medium) { .grid-content:first-child { padding-left: 0; } .grid-content:last-child { padding-right: 0; } } } #cinario-mvp { .content { padding-top: 2rem; } .slick-slider { background: transparent; } @include breakpoint(large) { display: flex; .content { width: 30%; margin-right: 5%; padding-top: 6%; } .mvp-slick { width: 65%; align-self: center; } } } #cinario-styleguide { @extend .clearfix; background: $slick-background; padding-top: 2rem; img { max-width: calc(50% - .5rem); float: left; margin-bottom: 1rem; &:nth-child(odd) { margin-right: 1rem; } } @include breakpoint($horizontal) { img { max-width: calc(50% - 1rem); margin-bottom: 2rem; &:nth-child(odd) { margin-right: 2rem; } } } } #cinario-final-images { text-align: center; font-size: 0; img { max-width: 27%; position: relative; &:not(:first-child) { margin-left: -10%; } &:nth-child(1), &:nth-child(5) { z-index: 1; } &:nth-child(2), &:nth-child(4) { z-index: 2; box-shadow: 0 4px 4px rgba(0, 0, 0, .1), 0 8px 8px rgba(0, 0, 0, .1); } &:nth-child(3) { z-index: 3; box-shadow: 0 4px 4px rgba(0, 0, 0, .1), 0 8px 8px rgba(0, 0, 0, .1), 0 16px 16px rgba(0, 0, 0, .1); } } }<file_sep>/client/templates/about.html --- name: about url: /about animationIn: slideInUp --- <section id="about-page" class=""> <div> <div class="inner first"> <p class="text-center"> <img src="assets/img/Process_dark.svg" alt="4 step process diagrammed"> </p> </div> <div class="inner"> <p><b>I love to problem solve</b>; whether it's finding intuitive yet innovative solutions to usability difficulties; or developing ways to implement those solutions in the somewhat limiting world of front-end technologies and accessibility. And, while my process can be chaotic, I am an organizer through and through. Just ask my sock drawer.</p> <p>I surround myself with design. My office walls are covered in posters, vinyl album covers and antique cameras. I love to travel, hunt for rare brews, and photographing my journeys.</p> </div> <!-- <div class="inner"> <h4>MY PROCESS</h4> <p>As Senior UX Engineer, I am constantly practicing the fundamentals of graphic, interface and interaction design, user experience, and usability. Perpetual communication and collaboration are a large part of my daily life not just within my team but with clients as well.</p> <p>I always start by <strong>identifying</strong> the client’s goals and the users’ needs. Finding where they intersect, I <strong>strategize</strong> to find creative and intuitive solutions. I consider user stories and possible user flows; always referencing back to the first step to make sure my concepts align. I start the <strong>creation</strong> process with wireframes and work up to high-fidelity mockups. I make sure the information is organized effectively and the interface design is compelling. I <strong>implement</strong> the design utilizing progressive enhancement when using the newest technology. I make sure it’s mobile-<em>friendly</em> not just responsive. I also consider accessibility and backwards compatibility.</p> </div> --> <div class="inner"> <h4 class="cheers">Cheers, <img src="assets/img/me2.jpg" alt="Photo of me" width="100" class="thumb round"></h4> </div> <hr> <div class="inner text-center"> <h3>Want to get in touch?</h3> <a class="button" href="mailto:<EMAIL>?subject=Contact from CuriousChaos.com">Email Me</a> <a class="button" href="http://www.linkedin.com/in/curiouschaos">Connect on LinkedIn</a> <a class="button" href="https://dribbble.com/curiouschaos">Check out my Dribbble</a> </div> </div> </section> <file_sep>/client/assets/scss/site/_global.scss $horizontal: xlarge; $sidebar-width: rem-calc(260); $sidebar-min-height: rem-calc(500); // Prettify type rendering body { -webkit-font-smoothing: antialiased; text-rendering: optimizeLegibility; background: $primary-color url('../img/pattern3.png') right top repeat-y; background-size: 100% auto; background-position-y: rem-calc(340); @include breakpoint(large) { } @include breakpoint($horizontal) { overflow: hidden; //background-size: calc(100% - (#{$sidebar-width + 2rem})) auto; } @include breakpoint(95rem) { //background-size: calc(80% - 2rem); } } %main-padding { padding: 0 $global-padding; } main { //background: $primary-color url('../img/pattern3.png') left top no-repeat; //background-size: 100% auto; > * { max-width: $container-width; margin-right: auto; margin-left: auto; } @include breakpoint(large) { background: none; > * { padding: 1rem; } } @include breakpoint($horizontal) { background: none; padding-left: $sidebar-width; height: 100vh; overflow-y: auto; > * { padding: 1rem 1rem 1rem 2rem; } } @include breakpoint(95rem) { padding-left: 20%; } } // disable pointer events except for on links so scrolling can happen over top-banner @include breakpoint($horizontal) { #top-banner, footer { //pointer-events: none; a { //pointer-events: all; // ie fix for no pointer-events position: relative; z-index: 20; } } } // Reset margin and padding on figure element figure { margin: 0; padding: 0; } // Add some basic styling for figcaption element figcaption { margin-bottom: rem-calc(20); margin-top: rem-calc(10); color: $monsoon; } blockquote { font-family: $font-family-serif; //font-style: $font-style-italic; cite { padding-left: 40%; } } // TYPOGRAPHY // Specific font families for headers sizes a { transition: color .15s, background .15s; } h1, h2 { //font-family: $font-family-headline; //text-align: center; font-weight: 900; } h1 { text-transform: uppercase; color: currentColor; } h2 { //margin-bottom: 2.5rem; } h3 { text-transform: uppercase; color: $primary-color; } h4 { font-weight: $font-weight-bold; } h5.subheader { text-align: center; max-width: 48rem; margin: 0 auto 2.5rem; } $paragraph-ideal: 33rem; p.ideal { max-width: $paragraph-ideal; &.text-center { margin-left: auto; margin-right: auto; } } video { max-width: 100%; } // LAYOUT // Section paddings and such $section-padding: 5rem; @mixin make-section($padding: $section-padding) { padding-top: $padding/1.5; padding-bottom: $padding/1.5; @include breakpoint(medium) { padding-top: $padding; padding-bottom: $padding; } & > :last-child { margin-bottom: 0; } } section.layout { @include make-section(); } // BUTTONS .button.secondary { color: $steel; } .button { transition: all .2s ease-in; } .button:hover, .button:focus, .button:active { box-shadow: 0 4px 4px rgba(0, 0, 0, .1), 0 8px 8px rgba(0, 0, 0, .1), 0 16px 16px rgba(0, 0, 0, .1); } // CUSTOM MIXINS // --------------------- // force the wrapping of long links/emails/etc. @mixin force-wrap() { overflow-wrap: break-word; word-wrap: break-word; -ms-word-break: break-all; /* This is the dangerous one in WebKit, as it breaks things wherever */ word-break: break-all; /* Instead use this non-standard one: */ word-break: break-word; } @mixin force-truncate($width: 100%) { width: $width; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } // FOOTER $footer-height: rem-calc(80); footer { padding-top: $global-padding; height: $footer-height; ul.inline-list, p { text-align: center; margin-left: 0; margin-bottom: .5rem; } li, p { font-size: $small-font-size*.8; } ul { display: flex; justify-content: center; } .inline-list li { margin: 0; text-transform: uppercase; letter-spacing: .05em; } a { padding: 1rem .5rem; &, &:hover, &:focus { color: $white; } } p { color: rgba($white, .5); } @include breakpoint($horizontal) { position: fixed; left: 0; bottom: 0; width: $sidebar-width; } @include breakpoint(95rem) { width: 20%; } @media screen and (max-height: $sidebar-min-height) { bottom: auto; top: $sidebar-min-height - $footer-height; } } .slideInUp, .fadeIn { &.ng-enter-active, &.ng-leave-active { position: relative !important; } } .thumb.round { border-radius: 50%; } img[src*="clicky"] { display: none; } <file_sep>/client/assets/scss/site/template/_project.scss // PAGE // .project { width: 100%; max-width: $container-width; margin: 0 auto; article { background: $white; max-width: none; } @include breakpoint(large) { article { box-shadow: 0 4px 4px rgba(0, 0, 0, .1), 0 8px 8px rgba(0, 0, 0, .1), 0 16px 16px rgba(0, 0, 0, .1), 0 32px 32px rgba(0, 0, 0, .15), 0 64px 64px rgba(0, 0, 0, .15); } } } // HEADER // .project header { @extend %main-padding; padding-top: $global-padding; padding-bottom: $global-padding*2; .entry-title { line-height: 1.1; margin-bottom: 1rem; @include breakpoint(large) { font-size: $h2-font-size*1.2; } } .categories { margin-bottom: $global-padding*2; > li { margin-left: .5rem; margin-right: .5rem; } } p.lead { max-width: $paragraph-ideal*1.2; margin-left: auto; margin-right: auto; } + hr { width: 20%; margin: 0 auto $global-padding*3; } @include breakpoint(small only) { p.lead { font-size: rem-calc(15); padding: 0; } } @include breakpoint(large) { padding-top: $global-padding*2; padding-bottom: $global-padding*3; + hr { margin-bottom: $global-padding*4; } } } // OVERALL CONTENT // .entry-content { @extend %main-padding; margin-bottom: 2rem; &.new-section { margin-top: $global-padding; } p { max-width: $paragraph-ideal; &.text-center { margin-left: auto; margin-right: auto; } } @include breakpoint(small only) { .text-center p, p.text-center, h3.text-center { text-align: left !important; } } @include breakpoint(large) { p { margin-bottom: 2rem; } } @include breakpoint($horizontal) { padding-left: 2rem; padding-right: 2rem; &.new-section { margin-top: $global-padding*4; } } } // TYPES OF CONTENT // .screenshot { //margin-top: 3rem; text-align: center; } .description { margin-top: 2rem; } @include breakpoint($horizontal) { .screenshot { //margin-top: 5rem; //margin-bottom: 5rem; } .description { margin-top: 8rem; } } // NAVIGATION // .posts_navigation { border-top: 1px solid $iron; ul { margin: 0; @extend .clearfix; font-size: 0; } li { margin-left: 0; padding: 0; list-style: none; margin: 0; display: inline-block; width: 50%; &:last-child { float: right; } } a { @extend .button; @extend .secondary; background-color: transparent !important; margin: 0; font-weight: bold; transition: color .25s; &:hover, &:active, &:focus { color: $primary-color; box-shadow: none; } margin-bottom: 0; padding-top: 1.5rem; padding-bottom: 1.5rem; background-repeat: no-repeat !important; background-size: 40px auto !important; width: 100%; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } li:only-child { width: 100%; } li a[rel="prev"] { text-align: left; background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='#{$slick-arrow-icon-color}' width='105' height='105' viewBox='0 0 105 105'%3E%3Cpath d='M44.85 74.27a2.5 2.5 0 0 0 3.54-3.54L32.64 55h45.73a2.5 2.5 0 0 0 0-5H32.65L48.4 34.27a2.5 2.5 0 1 0-3.55-3.54l-20 20a2.5 2.5 0 0 0 0 3.54z'/%3E%3C/svg%3E"); background-position: left 10px center !important; padding-left: 70px; } li:not(:only-child) a[rel="prev"] { border-right: 1px solid $iron; } li a[rel="next"] { text-align: right; background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='#{$slick-arrow-icon-color}' width='105' height='105' viewBox='0 0 105 105'%3E%3Cpath d='M60.15 30.73a2.5 2.5 0 0 0-3.54 3.54L72.36 50H26.62a2.5 2.5 0 0 0 0 5h45.73L56.6 70.73a2.5 2.5 0 1 0 3.55 3.54l20-20a2.5 2.5 0 0 0 0-3.54z'/%3E%3C/svg%3E"); background-position: right 10px center !important; padding-right: 70px; } }
31d6087ea761a72019f61eabafaf1d3dbd337fae
[ "Markdown", "SCSS", "HTML" ]
7
Markdown
cchaos/curiouschaos
b90d92f252607220895d9d3c55d584cffabaae6a
1e778cc41dfbf0bd49c81e262a6ce3459fc7b36e
refs/heads/master
<repo_name>Chikoumi/Simplex-UI<file_sep>/website/js/general.js //Pop-Up code jQuery(function($){ //Lorsque vous cliquez sur un lien de la classe pop-me $('a.pop-me').on('click', function() { var popID = $(this).data('rel'); //Recupération de la valeur data-rel var popWidth = $(this).data('width'); //Récupération de la valeur date-width //Apparition de la popup et génération du lien de fermeture $('#' + popID).fadeIn().css({ 'width': popWidth}).prepend('<a href="#" class="close">X</a>'); //Récupération du margin var popMargTop = ($('#' + popID).height() + 50) / 2; var popMargLeft = ($('#' + popID).width() + 80) / 2; //Application des marges $('#' + popID).css({ 'margin-top' : -popMargTop, 'margin-left' : -popMargLeft }); //Apparition du fond & compatibilité avec ancienne version d'IE $('body').append('<div id="fade"></div>'); $('#fade').css({'filter' : 'alpha(opacity=80)'}).fadeIn(); return false; }); $('body').on('click', 'a.close, #fade, #cancel', function() { //Fermeture de la Pop-Up $('#fade , .popup').fadeOut(function() { $('#fade, a.close').remove(); //Fermeture du fade. }); return false; }); }); //Scrabble change letter $('.scrabble').each(function() { var letters = $(this).text().split(''), $container = $(this).empty(); $.each(letters, function(_, letter) { $('<span>', {text: letter}).appendTo($container); }); });<file_sep>/website/demo.php <?php $titre ="Demo"; include("include/header.php");?> <div class="article"> <div class="header"> <h1>Article header h1</h1> <p>Text header : Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam sodales urna non odio egestas tempor. Nunc vel vehicula ante. Etiam bibendum iaculis libero, eget molestie nisl pharetra in. In semper consequat est, eu porta velit mollis nec.</p> </div> <h2>Features :</h2> <h3 class="separate">Navigation Bar</h3> See top-page. You can change color using menu on left. Possibility to have fixed-top navbar, just add top-nav to &lt;div class="page"&gt; like &lt;div class="page top-nav"&gt;, with this way Navbar will be fixed on top when you scroll down, you can activate "sticky-header" with left demo menu. <h3 class="separate">Buttons :</h3> <h5>Small format</h5> <a class="button button-default button-small">Small</a> <a class="button button-green button-small">Small</a> <a class="button button-yellow button-small">Small</a> <a class="button button-blue button-small">Small</a> <a class="button button-red button-small">Small</a> <br> <h5>Default format</h5> <a class="button button-default">Default</a> <a class="button button-green">Default</a> <a class="button button-yellow">Default</a> <a class="button button-blue">Default</a> <a class="button button-red">Default</a> <br> <h5>Big format</h5> <a class="button button-default button-big">Big one</a> <a class="button button-green button-big">Big one</a> <a class="button button-yellow button-big">Big one</a> <a class="button button-blue button-big">Big one</a> <a class="button button-red button-big">Big one</a> <br> <h5>Specials buttons</h5> <a class="button button-default button-big button-dsbl" disabled>button-dsbl</a> <a class="button button-default button-blue button-big button-ico">button-ico <i class="fa fa-cogs"></i></a><br> <a class="button button-blue button-big button-block">Block button</a> <h5>Buttons-group</h5> <div class="button-group"> <a class="button button-green">Button</a> <a class="button button-blue">Button</a> <a class="button button-red">Button</a> <a class="button button-green">Button</a> </div> <h3 class="separate">Labels</h3> <span class="lbl default">Lorem</span> <span class="lbl green">Lorem</span> <span class="lbl blue">Lorem</span> <span class="lbl yellow">Lorem</span> <span class="lbl red">Lorem</span> <h3 class="separate">Code :</h3> Lorem ipsum dolor <code>cd /home</code> sed do eiusmod tempor incididunt, <code>wget "https://github.com/Chikoumi/Ioncube-Autoinstall/archive/master.zip" && unzip master.zip" && cd Ioncube-Autoinstall && chmod +x fr_ioncube.sh && ./fr_ioncube.sh</code> consectetur adipiscing elit. <h3 class="separate">Bash console</h3> <div class="console"> <div class="console-head"> <h3>Bash console</h3> </div> <div class="console-body"> root@chk:/# ls <br> bin dev home lib64 media opt reboot run selinux sys usr <br> boot etc lib lost+found mnt proc root sbin srv tmp var <br> root@chk:/# uptime <br> 03:40:48 up 11 days, 4:44, 0 users, load average: 0.00, 0.00, 0.00 <br> root@chk:/# service teamspeak start <br> root@chk:/# TeamSpeak 3 server started, for details please view the log file<br> root@chk:/# </div> </div> <h3 class="separate">Message</h3> <div class="message msg-default"> Lorem ipsum dolor sit amet, <strong>consectetur</strong> adipisicing elit. </div> <div class="message msg-green"> Lorem ipsum dolor sit amet, <strong>consectetur</strong> adipisicing elit. </div> <div class="message msg-blue"> Lorem ipsum dolor sit amet, <strong>consectetur</strong> adipisicing elit. </div> <div class="message msg-yellow"> Lorem ipsum dolor sit amet, <strong>consectetur</strong> adipisicing elit. </div> <div class="message msg-red"> Lorem ipsum dolor sit amet, <strong>consectetur</strong> adipisicing elit. </div> <h3 class="separate">Card message</h3> <div class="card card-default"> <div class="card-head"> <h3>Exceptur sint occaecat</h3> </div> <div class="card-body"> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod </div> </div> <div class="card card-green"> <div class="card-head"> <h3>Exceptur sint occaecat</h3> </div> <div class="card-body"> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod </div> </div> <div class="card card-blue"> <div class="card-head"> <h3>Exceptur sint occaecat</h3> </div> <div class="card-body"> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod </div> </div> <div class="card card-yellow"> <div class="card-head"> <h3>Exceptur sint occaecat</h3> </div> <div class="card-body"> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod </div> </div> <div class="card card-red"> <div class="card-head"> <h3>Exceptur sint occaecat</h3> </div> <div class="card-body"> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod </div> </div> <H3>Progress Bar</H3> <h5>One line progress bar</h5> <div class="progress"> <div class="bar" style="width: 60%;"></div> </div> <div class="progress"> <div class="bar bar-green" style="width: 20%;"></div> </div> <div class="progress"> <div class="bar bar-blue" style="width: 80%;"></div> </div> <div class="progress"> <div class="bar bar-yellow" style="width: 65%;"></div> </div> <div class="progress"> <div class="bar bar-red" style="width: 90%;"></div> </div> <h3 class="separate">Highlight paragraph</h3> <p class="hl">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam.</p> <p class="hl-green">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam.</p> <p class="hl-blue">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam.</p> <p class="hl-yellow">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam.</p> <p class="hl-red">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam.</p> <h3 class="separate">Blockquote</h3> <blockquote class="quote-left"> Delenda cartago est, <br> Il faut détruire Carthage. <span class="copy">Caton </span> </blockquote> <blockquote class="quote-right"> Delenda cartago est, <br> Il faut détruire Carthage. <span class="copy">Caton </span> </blockquote> <h3 class="separate">Hint on hover</h3> <a class="button button-default tips">Hover-me <span class="tips-hint">Hint message</span></a> <p class="tips">Hover-me <span class="tips-hint">Hint Tips</span></p> <h3 class="separate">Tables</h3> <h5>Blue</h5> <table class="blue"> <thead> <tr> <th>ID</th> <th>First Name</th> <th>Last Name</th> <th>Email</th> </tr> </thead> <tbody> <tr> <td>#1121</td> <td>Bob</td> <td>Sponge</td> <td><EMAIL>-</td> </tr> <tr> <td>#7120</td> <td>Jacob</td> <td>Matador</td> <td><EMAIL></td> </tr> <tr> <td>#9981</td> <td>Ben</td> <td>Scott</td> <td><EMAIL></td> </tr> </tbody> </table> <h5>Red</h5> <table class="red"> <thead> <tr> <th>ID</th> <th>First Name</th> <th>Last Name</th> <th>Email</th> </tr> </thead> <tbody> <tr> <td>#1121</td> <td>Bob</td> <td>Sponge</td> <td><EMAIL>-</td> </tr> <tr> <td>#7120</td> <td>Jacob</td> <td>Matador</td> <td><EMAIL></td> </tr> <tr> <td>#9981</td> <td>Ben</td> <td>Scott</td> <td><EMAIL></td> </tr> </tbody> </table> <h5>Green</h5> <table class="green"> <thead> <tr> <th>ID</th> <th>First Name</th> <th>Last Name</th> <th>Email</th> </tr> </thead> <tbody> <tr> <td>#1121</td> <td>Bob</td> <td>Sponge</td> <td><EMAIL>-</td> </tr> <tr> <td>#7120</td> <td>Jacob</td> <td>Matador</td> <td><EMAIL></td> </tr> <tr> <td>#9981</td> <td>Ben</td> <td>Scott</td> <td><EMAIL></td> </tr> </tbody> </table> <h5>Yellow</h5> <table class="yellow"> <thead> <tr> <th>ID</th> <th>First Name</th> <th>Last Name</th> <th>Email</th> </tr> </thead> <tbody> <tr> <td>#1121</td> <td>Bob</td> <td>Sponge</td> <td><EMAIL>-</td> </tr> <tr> <td>#7120</td> <td>Jacob</td> <td>Matador</td> <td><EMAIL></td> </tr> <tr> <td>#9981</td> <td>Ben</td> <td>Scott</td> <td><EMAIL></td> </tr> </tbody> </table> <h5>Default</h5> <table> <thead> <tr> <th>ID</th> <th>First Name</th> <th>Last Name</th> <th>Email</th> </tr> </thead> <tbody> <tr> <td>#1121</td> <td>Bob</td> <td>Sponge</td> <td><EMAIL>-</td> </tr> <tr> <td>#7120</td> <td>Jacob</td> <td>Matador</td> <td><EMAIL></td> </tr> <tr> <td>#9981</td> <td>Ben</td> <td>Scott</td> <td><EMAIL></td> </tr> </tbody> </table> <h3 class="separate">Scrabble</h3> <span class="scrabble">Lorem</span> <h3 class="separate">Pop-up</h3> <a href="" data-width="500" data-rel="popup1" class="pop-me button button-big button-default">Clic me</a> <div id="popup1" class="popup default"> <div class="header"><h2>Default one Pop-up</h2></div> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo </p> <div class="btn"> <a class="button button-green">I agree</a> <a class="button button-red" id="cancel">I disagree</a> <!-- Just add #cancel to button if it should close pop-up --> </div> </div> <a href="" data-width="500" data-rel="popup2" class="pop-me button button-big button-green">Clic me</a> <div id="popup2" class="popup green"> <div class ="header"><h2>Green one Pop-up</h2></div> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo </p> <div class="btn"> <a class="button button-green">I agree</a> <a class="button button-red" id="cancel">I disagree</a> <!-- Just add #cancel to button if it should close pop-up --> </div> </div> <a href="" data-width="500" data-rel="popup3" class="pop-me button button-big button-blue">Clic me</a> <div id="popup3" class="popup blue"> <div class ="header"><h2>Blue one Pop-up</h2></div> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo </p> <div class="btn"> <a class="button button-green">I agree</a> <a class="button button-red" id="cancel">I disagree</a> <!-- Just add #cancel to button if it should close pop-up --> </div> </div> <a href="" data-width="500" data-rel="popup4" class="pop-me button button-big button-yellow">Clic me</a> <div id="popup4" class="popup yellow"> <div class ="header"><h2>Yellow one Pop-up</h2></div> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo </p> <div class="btn"> <a class="button button-green">I agree</a> <a class="button button-red" id="cancel">I disagree</a> <!-- Just add #cancel to button if it should close pop-up --> </div> </div> <a href="" data-width="500" data-rel="popup5" class="pop-me button button-big button-red">Clic me</a> <div id="popup5" class="popup red"> <div class ="header"><h2>Red one Pop-up</h2></div> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo </p> <div class="btn"> <a class="button button-green">I agree</a> <a class="button button-red" id="cancel">I disagree</a> <!-- Just add #cancel to button if it should close pop-up --> </div> </div> <h3 class="separate">Price-List</h3> <div class="plist-container"> <div class="plist red"> <div class="price">$100</div> <div class="type">Article</div> <ul class="options"> <li><strong>Nice</strong> features</li> <li><strong>Nice</strong> features</li> <li><strong>Nice</strong> features</li> </ul> <a class="button">J'achète</a> </div> <div class="plist better yellow"> <div class="price">$150</div> <div class="type">Best Offer</div> <ul class="options"> <li><strong>Nice</strong> features</li> <li><strong>Nice</strong> features</li> <li><strong>Nice</strong> features</li> </ul> <a class="button">J'achète</a> </div> <div class="plist blue"> <div class="price">$9000</div> <div class="type">Another article</div> <ul class="options"> <li><strong>Nice</strong> features</li> <li><strong>Nice</strong> features</li> <li><strong>Nice</strong> features</li> </ul> <a class="button">J'achète</a> </div> </div> <div class="plist-container"> <div class="plist green"> <div class="price">$100</div> <div class="type">Article</div> <ul class="options"> <li><strong>Nice</strong> features</li> <li><strong>Nice</strong> features</li> <li><strong>Nice</strong> features</li> </ul> <a class="button">J'achète</a> </div> <div class="plist red"> <div class="price">$150</div> <div class="type">Another Article</div> <ul class="options"> <li><strong>Nice</strong> features</li> <li><strong>Nice</strong> features</li> <li><strong>Nice</strong> features</li> </ul> <a class="button">J'achète</a> </div> <div class="plist better"> <div class="price">$9000</div> <div class="type">Best Offer</div> <ul class="options"> <li><strong>Nice</strong> features</li> <li><strong>Nice</strong> features</li> <li><strong>Nice</strong> features</li> </ul> <a class="button">J'achète</a> </div> </div> <h3 class="separate">Status icon</h3> <ul> <li>Server status: <div class="status"></div></li> <li>Server status: <div class="status off"></div></li> </ul> <h3 class="separate">Grid-System</h3> <div class="grid"> <h3>3 Collums</h3> <div class="col_1"> <h5>Col_1</h5> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam sodales urna non odio egestas tempor. Nunc vel vehicula ante. Etiam bibendum iaculis libero. </div> <div class="col_1"> <h5>Col_1</h5> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam sodales urna non odio egestas tempor. Nunc vel vehicula ante. Etiam bibendum iaculis libero. </div> <div class="col_1"> <h5>Col_1</h5> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam sodales urna non odio egestas tempor. Nunc vel vehicula ante. Etiam bibendum iaculis libero. </div> <h3>2 Collums</h3> <div class="col_2"> <h5>Col_2</h5> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam sodales urna non odio egestas tempor. Nunc vel vehicula ante. Etiam bibendum iaculis libero. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam sodales urna non odio egestas tempor. Nunc vel vehicula ante. Etiam bibendum iaculis libero. </div> <div class="col_1"> <h5>Col_1</h5> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam sodales urna non odio egestas tempor. Nunc vel vehicula ante. </div> </div> <h3>3 Collums with img</h3> <div class="grid index"> <div class="col_1"> <h5>Col_1</h5> <img src="img/many.png"></img> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam sodales urna non odio egestas tempor. Nunc vel vehicula ante. Etiam bibendum iaculis libero. </div> <div class="col_1"> <h5>Col_1</h5> <img src="img/many.png"></img> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam sodales urna non odio egestas tempor. Nunc vel vehicula ante. Etiam bibendum iaculis libero. </div> <div class="col_1"> <h5>Col_1</h5> <img src="img/many.png"></img> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam sodales urna non odio egestas tempor. Nunc vel vehicula ante. Etiam bibendum iaculis libero. </div> </div> <h2>article h2</h2> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam sodales urna non odio egestas tempor. Nunc vel vehicula ante. Etiam bibendum iaculis libero, eget molestie nisl pharetra in. In semper consequat est, eu porta velit mollis nec. Curabitur posuere enim eget turpis feugiat tempor. Etiam ullamcorper lorem dapibus velit suscipit ultrices. Proin in est sed erat facilisis pharetra.</p> </div> </div> <!-- End-main --> </div> <!-- End-main-container --> </div><!-- End-Page --> <?php include("include/footer.php"); ?> <file_sep>/website/include/header.php <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <title>Simplex-UI | <?php echo $titre;?></title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- favicon invocation --> <link rel="shortcut icon" href="/img/favicon.ico" type="image/x-icon"> <link rel="icon" href="/img/favicon.ico" type="image/x-icon"> <!-- End favicon invocation --> <link rel="stylesheet" type="text/css" href="css/reset.css"> <!-- call reset css--> <link rel="stylesheet" type="text/css" href="css/main.css"> <!-- call main css (require) --> <link rel="stylesheet" type="text/css" href="css/col.css"> <!-- call colonne system (require)--> <?php if ($titre == "Demo") { echo '<link rel="stylesheet" type="text/css" href="demo-files/demo.css"> <!-- Juste here for demo-->';} ?> <?php if ($titre == "How to use") { echo '<link rel="stylesheet" type="text/css" href="demo-files/demo.css"><link rel="stylesheet" type="text/css" href="demo-files/prism.css">';} ?> </head> <body class="red"> <!-- Just apply color to body wich modify footer & navbar color : default, red, yellow, blue, green && --> <!-- Page --> <div class="page *top-nav"> <!-- remove * before top-bar to enable fixed navbar on top --> <div class="header-container"> <header class="wrapper clearfix"> <div class="brand"> <img src="img/brand.png"><h1>Simplex-UI</h1> </div> <nav> <ul> <li><a href="/"><i class="fa fa-home"></i> Home</a></li> <li><a href="/demo"><i class="fa fa-paw"></i> Demo</a></li> <li><a><i class="fa fa-plus"></i> Tools</a> <ul><!-- DropDown --> <li><a href="/download"><i class="fa fa-slark"></i> Download</a></li> <li><a href="/use"><i class="fa fa-slark"></i> How to use</a></li> <li><a target="_blank" href="https://github.com/Chikoumi/Simplex-UI"><i class="fa fa-slark"></i> Github</a></li> </ul><!-- End DropDown --> </li> </ul> </nav> </header> </div> <?php if ($titre == "Demo") { echo '<div class="color-container"> <a>Themes :</a><br> <span onclick="colors(\'blue\')" class="color-change blue"> </span> <span onclick="colors(\'red\')" class="color-change red"> </span> <span onclick="colors(\'green\')" class="color-change green"> </span> <span onclick="colors(\'yellow\')" class="color-change yellow"> </span> <span onclick="colors(\'default\')" class="color-change default"> </span><br> <a>Sidebar :</a><br> <span onclick="sidebar(\'sidebar left\')" class="lbl blue">Left</span> <span onclick="sidebar(\'sidebar right\')" class="lbl blue">Right</span><br> <a>Sticky Header:</a><br> <span onclick="navbar(\'page top-nav\')" class="lbl green">On</span> <span onclick="navbar(\'page *top-nav\')" class="lbl red">Off</span> </div>';} ?> <?php if ($titre == "How to use") { echo ' <div class="color-container"> <h5>Navigation:</h5> <ul> <li><a href="#navbar">Navbar</a></li> <li><a href="#btn">Buttons</a></li> <li><a href="#lbl">Labels</a></li> <li><a href="#code">Code</a></li> <li><a href="#bash">Bash Console</a></li> <li><a href="#msg">Messages</a></li> <li><a href="#card">Cards Message</a></li> <li><a href="#progress">Progress-Bar</a></li> <li><a href="#hl">Highlight &lt;p&gt;</a></li> <li><a href="#blockquote">Blockquote</a></li> <li><a href="#hint">Hint Tips</a></li> <li><a href="#table">Tables</a></li> <li><a href="#scrabble">Scrabble</a></li> <li><a href="#pop-up">Pop-up</a></li> <li><a href="#plist">Price-List</a></li> <li><a href="#grid">Grid System</a></li> </ul> </div>';} ?> <!-- main-container --> <div class="main-container"> <!-- main --> <div class="main wrapper clearfix"> <div class="showcase"> <h1>Free HTML Starter Kit</h1> If you want to start your site with a starter kit, this is the right place. I propose you a kit to be able to start in the web world. This kit does not pretend to be turnkey, you will subsequently create a site to your image. The use of the kit has been made as easy as possible. </div> <div class="sidebar right"><!-- Just write Right or left to choose sidebar version --> <h3>About Version</h3> <h5>Actual:</h5> <p class="hl-red">Current version is 1.1</p> <h5>Alpha Version</h5> <p class="hl-blue">She was released on June 2014. <br>Aborted, go to beta version.</p> <h5>Beta Version</h5> <p class="hl-blue">She was released on July 2014. <br>Many bugs corrected, add lot of things.</p> </div><file_sep>/website/demo-files/demo.js function colors(color) { document.body.className = color; } function navbar(top) { $(".page").removeClass().addClass(top); } function sidebar(position) { $(".sidebar").removeClass().addClass(position); }<file_sep>/README.md [Simplex-UI](http://chikoumi.github.io/Simplex-UI/) ========== My own Html/Css template, easy to use to start your own website. Welcome on Simplex-UI Website. If you want to start your site with a starter kit, this is the right place. I propose you a kit to be able to start in the web world. This kit does not pretend to be turnkey, you will subsequently create a site to your image. The use of the kit has been made as easy as possible. Responsive ------------ Your website can be viewed on a mobile phone or on a screen and will be automatically adapted. Without JS, just with css, because of an old or incompatblie browser. Simple Tag ----------- Just with an css tag you can change design color, or fix the navbar or fixed sidebar on left, on right. Very simple to use and easy to understand. Lots of features ---------------- Many tools are offered to you : tables, labels, buttons, code, card message, stylized p and message, Progress-bar, hint on hover, pop-up, price-list... <file_sep>/website/use.php <?php $titre ="How to use"; include("include/header.php");?> <div class="article"> <div class="header"> <h1>How to use Simplex-UI</h1> <p>If you don't want to search code to made something, here you can get it.</p> </div> <h3 class="separate">Made with prism.js</h3> <p>This page is provide by <a href="http://prismjs.com">Prism.js</a>, it is an extensible syntax highlighter, built with modern web standards.</p> <h3 id="navbar" class="separate">Navigation Bar</h3> See top-page. You can change color using menu on left. Possibility to have fixed-top navbar, just add top-nav to &lt;div class="page"&gt; like &lt;div class="page top-nav"&gt;, with this way Navbar will be fixed on top when you scroll down, you can activate "sticky-header" with left demo menu. <h6>HTML code:</h6><pre><code class="language-markup">&lt;div class="page *top-nav"> &lt;!-- remove * before top-bar to enable fixed navbar on top --> &lt;div class="header-container"> &lt;header class="wrapper clearfix"> &lt;div class="brand"> &lt;img src="img/brand.png">&lt;h1>Simplex-UI&lt;/h1> &lt;/div> &lt;nav> &lt;ul> &lt;li>&lt;a href="/">&lt;i class="fa fa-home">&lt;/i> Home&lt;/a>&lt;/li> &lt;li>&lt;a href="/demo">&lt;i class="fa fa-paw">&lt;/i> Demo&lt;/a>&lt;/li> &lt;li>&lt;a>&lt;i class="fa fa-plus">&lt;/i> Tools&lt;/a> &lt;ul>&lt;!-- DropDown --> &lt;li>&lt;a href="/download">&lt;i class="fa fa-slark">&lt;/i> Download&lt;/a>&lt;/li> &lt;li>&lt;a href="/use">&lt;i class="fa fa-slark">&lt;/i> How to use&lt;/a>&lt;/li> &lt;li>&lt;a target="_blank" href="https://github.com/Chikoumi/Simplex-UI">&lt;i class="fa fa-slark">&lt;/i> Github&lt;/a>&lt;/li> &lt;/ul>&lt;!-- End DropDown --> &lt;/li> &lt;/ul> &lt;/nav> &lt;/header> &lt;/div></code></pre> <h3 id="btn" class="separate">Buttons :</h3> <h5>Small format</h5> <a class="button button-default button-small">Small</a> <a class="button button-green button-small">Small</a> <a class="button button-yellow button-small">Small</a> <a class="button button-blue button-small">Small</a> <a class="button button-red button-small">Small</a> <br> <h6>HTML code:</h6><pre><code class="language-markup">&lt;a class="button button-default button-small">Small&lt;/a> &lt;a class="button button-green button-small">Small&lt;/a> &lt;a class="button button-yellow button-small">Small&lt;/a> &lt;a class="button button-blue button-small">Small&lt;/a> &lt;a class="button button-red button-small">Small&lt;/a></code></pre> <h5>Default format</h5> <a class="button button-default">Default</a> <a class="button button-green">Default</a> <a class="button button-yellow">Default</a> <a class="button button-blue">Default</a> <a class="button button-red">Default</a> <br> <h6>HTML code:</h6><pre><code class="language-markup">&lt;a class="button button-default">Default&lt;/a> &lt;a class="button button-green">Default&lt;/a> &lt;a class="button button-yellow">Default&lt;/a> &lt;a class="button button-blue">Default&lt;/a> &lt;a class="button button-red">Default&lt;/a></code></pre> <h5>Big format</h5> <a class="button button-default button-big">Big one</a> <a class="button button-green button-big">Big one</a> <a class="button button-yellow button-big">Big one</a> <a class="button button-blue button-big">Big one</a> <a class="button button-red button-big">Big one</a> <br> <h6>HTML code:</h6><pre><code class="language-markup">&lt;a class="button button-default button-big">Big one&lt;/a> &lt;a class="button button-green button-big">Big one&lt;/a> &lt;a class="button button-yellow button-big">Big one&lt;/a> &lt;a class="button button-blue button-big">Big one&lt;/a> &lt;a class="button button-red button-big">Big one&lt;/a></code></pre> <h5>Specials buttons</h5> <a class="button button-default button-big button-dsbl" disabled>button-dsbl</a> <a class="button button-default button-blue button-big button-ico">button-ico <i class="fa fa-cogs"></i></a><br> <a class="button button-blue button-big button-block">Block button</a> <br> <h6>HTML code:</h6><pre><code class="language-markup">&lt;a class="button button-default button-big button-dsbl" disabled>button-dsbl&lt;/a> &lt;a class="button button-default button-blue button-big button-ico">button-ico &lt;i class="fa fa-cogs">&lt;/i>&lt;/a>&lt;br> &lt;a class="button button-blue button-big button-block">Block button&lt;/a></code></pre> <h5>Buttons-group</h5> <div class="button-group"> <a class="button button-green">Button</a> <a class="button button-blue">Button</a> <a class="button button-red">Button</a> <a class="button button-green">Button</a> </div> <br> <h6>HTML code:</h6><pre><code class="language-markup">&lt;div class="button-group"> &lt;a class="button button-green">Button&lt;/a> &lt;a class="button button-blue">Button&lt;/a> &lt;a class="button button-red">Button&lt;/a> &lt;a class="button button-green">Button&lt;/a> &lt;/div></code></pre> <h3 id="lbl" class="separate">Labels</h3> <span class="lbl default">Lorem</span> <span class="lbl green">Lorem</span> <span class="lbl blue">Lorem</span> <span class="lbl yellow">Lorem</span> <span class="lbl red">Lorem</span><br> <h6>HTML code:</h6><pre><code class="language-markup">&lt;span class="lbl default">Lorem&lt;/span> &lt;span class="lbl green">Lorem&lt;/span> &lt;span class="lbl blue">Lorem&lt;/span> &lt;span class="lbl yellow">Lorem&lt;/span> &lt;span class="lbl red">Lorem&lt;/span></code></pre> <h3 id="code" class="separate">Code :</h3> Lorem ipsum dolor <code>cd /home</code> sed do eiusmod tempor incididunt, <code>wget "https://github.com/Chikoumi/Ioncube-Autoinstall/archive/master.zip" && unzip master.zip" && cd Ioncube-Autoinstall && chmod +x fr_ioncube.sh && ./fr_ioncube.sh</code> consectetur adipiscing elit. <h6>HTML code:</h6><pre><code class="language-markup">Lorem ipsum dolor &lt;code>cd /home&lt;/code> sed do eiusmod tempor incididunt, &lt;code>wget "https://github.com/Chikoumi/Ioncube-Autoinstall/archive/master.zip" && unzip master.zip" && cd Ioncube-Autoinstall && chmod +x fr_ioncube.sh && ./fr_ioncube.sh&lt;/code> consectetur adipiscing elit. </code></pre> <h3 id="bash" class="separate">Bash console</h3> <div class="console"> <div class="console-head"> <h3>Bash console</h3> </div> <div class="console-body"> root@chk:/# ls <br> bin dev home lib64 media opt reboot run selinux sys usr <br> boot etc lib lost+found mnt proc root sbin srv tmp var <br> root@chk:/# uptime <br> 03:40:48 up 11 days, 4:44, 0 users, load average: 0.00, 0.00, 0.00 <br> root@chk:/# service teamspeak start <br> root@chk:/# TeamSpeak 3 server started, for details please view the log file<br> root@chk:/# </div> </div> <h6>HTML code:</h6><pre><code class="language-markup">&lt;div class="console"> &lt;div class="console-head"> &lt;h3>Bash console&lt;/h3> &lt;/div> &lt;div class="console-body"> root@chk:/# ls &lt;br> bin dev home lib64 media opt reboot run selinux sys usr &lt;br> boot etc lib lost+found mnt proc root sbin srv tmp var &lt;br> root@chk:/# uptime &lt;br> 03:40:48 up 11 days, 4:44, 0 users, load average: 0.00, 0.00, 0.00 &lt;br> root@chk:/# service teamspeak start &lt;br> root@chk:/# TeamSpeak 3 server started, for details please view the log file&lt;br> root@chk:/# &lt;/div> &lt;/div></code></pre> <h3 id="msg" class="separate">Message</h3> <div class="message msg-default"> Lorem ipsum dolor sit amet, <strong>consectetur</strong> adipisicing elit. </div> <div class="message msg-green"> Lorem ipsum dolor sit amet, <strong>consectetur</strong> adipisicing elit. </div> <div class="message msg-blue"> Lorem ipsum dolor sit amet, <strong>consectetur</strong> adipisicing elit. </div> <div class="message msg-yellow"> Lorem ipsum dolor sit amet, <strong>consectetur</strong> adipisicing elit. </div> <div class="message msg-red"> Lorem ipsum dolor sit amet, <strong>consectetur</strong> adipisicing elit. </div> <h6>HTML code:</h6><pre><code class="language-markup">&lt;div class="message msg-default"> Lorem ipsum dolor sit amet, &lt;strong>consectetur&lt;/strong> adipisicing elit. &lt;/div> &lt;div class="message msg-green"> Lorem ipsum dolor sit amet, &lt;strong>consectetur&lt;/strong> adipisicing elit. &lt;/div> &lt;div class="message msg-blue"> Lorem ipsum dolor sit amet, &lt;strong>consectetur&lt;/strong> adipisicing elit. &lt;/div> &lt;div class="message msg-yellow"> Lorem ipsum dolor sit amet, &lt;strong>consectetur&lt;/strong> adipisicing elit. &lt;/div> &lt;div class="message msg-red"> Lorem ipsum dolor sit amet, &lt;strong>consectetur&lt;/strong> adipisicing elit. &lt;/div></code></pre> <h3 id="card" class="separate">Card message</h3> <div class="card card-default"> <div class="card-head"> <h3>Exceptur sint occaecat</h3> </div> <div class="card-body"> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod </div> </div> <div class="card card-green"> <div class="card-head"> <h3>Exceptur sint occaecat</h3> </div> <div class="card-body"> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod </div> </div> <div class="card card-blue"> <div class="card-head"> <h3>Exceptur sint occaecat</h3> </div> <div class="card-body"> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod </div> </div> <div class="card card-yellow"> <div class="card-head"> <h3>Exceptur sint occaecat</h3> </div> <div class="card-body"> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod </div> </div> <div class="card card-red"> <div class="card-head"> <h3>Exceptur sint occaecat</h3> </div> <div class="card-body"> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod </div> </div> <h6>HTML code:</h6><pre><code class="language-markup">&lt;div class="card card-default"> &lt;div class="card-head"> &lt;h3>Exceptur sint occaecat&lt;/h3> &lt;/div> &lt;div class="card-body"> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod &lt;/div> &lt;/div> &lt;div class="card card-green"> &lt;div class="card-head"> &lt;h3>Exceptur sint occaecat&lt;/h3> &lt;/div> &lt;div class="card-body"> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod &lt;/div> &lt;/div> &lt;div class="card card-blue"> &lt;div class="card-head"> &lt;h3>Exceptur sint occaecat&lt;/h3> &lt;/div> &lt;div class="card-body"> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod &lt;/div> &lt;/div> &lt;div class="card card-yellow"> &lt;div class="card-head"> &lt;h3>Exceptur sint occaecat&lt;/h3> &lt;/div> &lt;div class="card-body"> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod &lt;/div> &lt;/div> &lt;div class="card card-red"> &lt;div class="card-head"> &lt;h3>Exceptur sint occaecat&lt;/h3> &lt;/div> &lt;div class="card-body"> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod &lt;/div> &lt;/div></code></pre> <H3 id="progress" class="separate">Progress Bar</H3> <h5>One line progress bar</h5> <div class="progress"> <div class="bar" style="width: 60%;"></div> </div> <div class="progress"> <div class="bar bar-green" style="width: 20%;"></div> </div> <div class="progress"> <div class="bar bar-blue" style="width: 80%;"></div> </div> <div class="progress"> <div class="bar bar-yellow" style="width: 65%;"></div> </div> <div class="progress"> <div class="bar bar-red" style="width: 90%;"></div> </div> <h6>HTML code:</h6><pre><code class="language-markup">&lt;div class="progress"> &lt;div class="bar" style="width: 60%;">&lt;/div> &lt;/div> &lt;div class="progress"> &lt;div class="bar bar-green" style="width: 20%;">&lt;/div> &lt;/div> &lt;div class="progress"> &lt;div class="bar bar-blue" style="width: 80%;">&lt;/div> &lt;/div> &lt;div class="progress"> &lt;div class="bar bar-yellow" style="width: 65%;">&lt;/div> &lt;/div> &lt;div class="progress"> &lt;div class="bar bar-red" style="width: 90%;">&lt;/div> &lt;/div></code></pre> <h3 id="hl" class="separate">Highlight paragraph</h3> <p class="hl">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam.</p> <p class="hl-green">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam.</p> <p class="hl-blue">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam.</p> <p class="hl-yellow">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam.</p> <p class="hl-red">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam.</p> <h6>HTML code:</h6><pre><code class="language-markup">&lt;p class="hl">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam.&lt;/p> &lt;p class="hl-green">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam.&lt;/p> &lt;p class="hl-blue">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam.&lt;/p> &lt;p class="hl-yellow">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam.&lt;/p> &lt;p class="hl-red">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam.&lt;/p></code></pre> <h3 id="blockquote" class="separate">Blockquote</h3> <blockquote class="quote-left"> Delenda cartago est, <br> Il faut détruire Carthage. <span class="copy">Caton </span> </blockquote> <blockquote class="quote-right"> Delenda cartago est, <br> Il faut détruire Carthage. <span class="copy">Caton </span> </blockquote> <h6>HTML code:</h6><pre><code class="language-markup">&lt;blockquote class="quote-left"> Delenda cartago est, &lt;br> Il faut détruire Carthage. &lt;span class="copy">Caton &lt;/span> &lt;/blockquote> &lt;blockquote class="quote-right"> Delenda cartago est, &lt;br> Il faut détruire Carthage. &lt;span class="copy">Caton &lt;/span> &lt;/blockquote></code></pre> <h3 id="hint" class="separate">Hint on hover</h3> <a class="button button-default tips">Hover-me <span class="tips-hint">Hint message</span></a> <p class="tips">Hover-me <span class="tips-hint">Hint Tips</span></p> <h6>HTML code:</h6><pre><code class="language-markup">&lt;a class="button button-default tips">Hover-me &lt;span class="tips-hint">Hint message&lt;/span>&lt;/a> &lt;p class="tips">Hover-me &lt;span class="tips-hint">Hint Tips&lt;/span>&lt;/p> </code></pre> <h3 id="table" class="separate">Tables</h3> <h5>Blue</h5> <table class="blue"> <thead> <tr> <th>ID</th> <th>First Name</th> <th>Last Name</th> <th>Email</th> </tr> </thead> <tbody> <tr> <td>#1121</td> <td>Bob</td> <td>Sponge</td> <td><EMAIL>-</td> </tr> <tr> <td>#7120</td> <td>Jacob</td> <td>Matador</td> <td><EMAIL></td> </tr> <tr> <td>#9981</td> <td>Ben</td> <td>Scott</td> <td><EMAIL></td> </tr> </tbody> </table> <h5>Red</h5> <table class="red"> <thead> <tr> <th>ID</th> <th>First Name</th> <th>Last Name</th> <th>Email</th> </tr> </thead> <tbody> <tr> <td>#1121</td> <td>Bob</td> <td>Sponge</td> <td><EMAIL>-</td> </tr> <tr> <td>#7120</td> <td>Jacob</td> <td>Matador</td> <td><EMAIL></td> </tr> <tr> <td>#9981</td> <td>Ben</td> <td>Scott</td> <td><EMAIL></td> </tr> </tbody> </table> <h5>Green</h5> <table class="green"> <thead> <tr> <th>ID</th> <th>First Name</th> <th>Last Name</th> <th>Email</th> </tr> </thead> <tbody> <tr> <td>#1121</td> <td>Bob</td> <td>Sponge</td> <td><EMAIL>-</td> </tr> <tr> <td>#7120</td> <td>Jacob</td> <td>Matador</td> <td><EMAIL></td> </tr> <tr> <td>#9981</td> <td>Ben</td> <td>Scott</td> <td><EMAIL></td> </tr> </tbody> </table> <h5>Yellow</h5> <table class="yellow"> <thead> <tr> <th>ID</th> <th>First Name</th> <th>Last Name</th> <th>Email</th> </tr> </thead> <tbody> <tr> <td>#1121</td> <td>Bob</td> <td>Sponge</td> <td><EMAIL>-</td> </tr> <tr> <td>#7120</td> <td>Jacob</td> <td>Matador</td> <td><EMAIL></td> </tr> <tr> <td>#9981</td> <td>Ben</td> <td>Scott</td> <td><EMAIL></td> </tr> </tbody> </table> <h5>Default</h5> <table> <thead> <tr> <th>ID</th> <th>First Name</th> <th>Last Name</th> <th>Email</th> </tr> </thead> <tbody> <tr> <td>#1121</td> <td>Bob</td> <td>Sponge</td> <td><EMAIL>-</td> </tr> <tr> <td>#7120</td> <td>Jacob</td> <td>Matador</td> <td><EMAIL></td> </tr> <tr> <td>#9981</td> <td>Ben</td> <td>Scott</td> <td><EMAIL></td> </tr> </tbody> </table> <h6>HTML code:</h6><pre><code class="language-markup">&lt;h5>Blue&lt;/h5> &lt;table class="blue"> &lt;thead> &lt;tr> &lt;th>ID&lt;/th> &lt;th>First Name&lt;/th> &lt;th>Last Name&lt;/th> &lt;th>Email&lt;/th> &lt;/tr> &lt;/thead> &lt;tbody> &lt;tr> &lt;td>#1121&lt;/td> &lt;td>Bob&lt;/td> &lt;td>Sponge&lt;/td> &lt;td><EMAIL>-&lt;/td> &lt;/tr> &lt;tr> &lt;td>#7120&lt;/td> &lt;td>Jacob&lt;/td> &lt;td>Matador&lt;/td> &lt;td><EMAIL>&lt;/td> &lt;/tr> &lt;tr> &lt;td>#9981&lt;/td> &lt;td>Ben&lt;/td> &lt;td>Scott&lt;/td> &lt;td><EMAIL>&lt;/td> &lt;/tr> &lt;/tbody> &lt;/table> &lt;h5>Red&lt;/h5> &lt;table class="red"> &lt;thead> &lt;tr> &lt;th>ID&lt;/th> &lt;th>First Name&lt;/th> &lt;th>Last Name&lt;/th> &lt;th>Email&lt;/th> &lt;/tr> &lt;/thead> &lt;tbody> &lt;tr> &lt;td>#1121&lt;/td> &lt;td>Bob&lt;/td> &lt;td>Sponge&lt;/td> &lt;td><EMAIL>-&lt;/td> &lt;/tr> &lt;tr> &lt;td>#7120&lt;/td> &lt;td>Jacob&lt;/td> &lt;td>Matador&lt;/td> &lt;td><EMAIL>&lt;/td> &lt;/tr> &lt;tr> &lt;td>#9981&lt;/td> &lt;td>Ben&lt;/td> &lt;td>Scott&lt;/td> &lt;td><EMAIL>&lt;/td> &lt;/tr> &lt;/tbody> &lt;/table> &lt;h5>Green&lt;/h5> &lt;table class="green"> &lt;thead> &lt;tr> &lt;th>ID&lt;/th> &lt;th>First Name&lt;/th> &lt;th>Last Name&lt;/th> &lt;th>Email&lt;/th> &lt;/tr> &lt;/thead> &lt;tbody> &lt;tr> &lt;td>#1121&lt;/td> &lt;td>Bob&lt;/td> &lt;td>Sponge&lt;/td> &lt;td><EMAIL>-&lt;/td> &lt;/tr> &lt;tr> &lt;td>#7120&lt;/td> &lt;td>Jacob&lt;/td> &lt;td>Matador&lt;/td> &lt;td><EMAIL>&lt;/td> &lt;/tr> &lt;tr> &lt;td>#9981&lt;/td> &lt;td>Ben&lt;/td> &lt;td>Scott&lt;/td> &lt;td><EMAIL>&lt;/td> &lt;/tr> &lt;/tbody> &lt;/table> &lt;h5>Yellow&lt;/h5> &lt;table class="yellow"> &lt;thead> &lt;tr> &lt;th>ID&lt;/th> &lt;th>First Name&lt;/th> &lt;th>Last Name&lt;/th> &lt;th>Email&lt;/th> &lt;/tr> &lt;/thead> &lt;tbody> &lt;tr> &lt;td>#1121&lt;/td> &lt;td>Bob&lt;/td> &lt;td>Sponge&lt;/td> &lt;td><EMAIL>-&lt;/td> &lt;/tr> &lt;tr> &lt;td>#7120&lt;/td> &lt;td>Jacob&lt;/td> &lt;td>Matador&lt;/td> &lt;td><EMAIL>&lt;/td> &lt;/tr> &lt;tr> &lt;td>#9981&lt;/td> &lt;td>Ben&lt;/td> &lt;td>Scott&lt;/td> &lt;td><EMAIL>&lt;/td> &lt;/tr> &lt;/tbody> &lt;/table> &lt;h5>Default&lt;/h5> &lt;table> &lt;thead> &lt;tr> &lt;th>ID&lt;/th> &lt;th>First Name&lt;/th> &lt;th>Last Name&lt;/th> &lt;th>Email&lt;/th> &lt;/tr> &lt;/thead> &lt;tbody> &lt;tr> &lt;td>#1121&lt;/td> &lt;td>Bob&lt;/td> &lt;td>Sponge&lt;/td> &lt;td><EMAIL>-&lt;/td> &lt;/tr> &lt;tr> &lt;td>#7120&lt;/td> &lt;td>Jacob&lt;/td> &lt;td>Matador&lt;/td> &lt;td><EMAIL>&lt;/td> &lt;/tr> &lt;tr> &lt;td>#9981&lt;/td> &lt;td>Ben&lt;/td> &lt;td>Scott&lt;/td> &lt;td><EMAIL>&lt;/td> &lt;/tr> &lt;/tbody> &lt;/table></code></pre> <h3 id="scrabble" class="separate">Scrabble</h3> <span class="scrabble">Lorem</span> <h6>HTML code:</h6><pre><code class="language-markup">&lt;span class="scrabble">Lorem&lt;/span> &lt;!-- JS automatically transform letters--></code></pre> <h3 id="pop-up" class="separate">Pop-up</h3> <a href="" data-width="500" data-rel="popup1" class="pop-me button button-big button-default">Clic me</a> <div id="popup1" class="popup default"> <div class="header"><h2>Default one Pop-up</h2></div> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo </p> <div class="btn"> <a class="button button-green">I agree</a> <a class="button button-red" id="cancel">I disagree</a> <!-- Just add #cancel to button if it should close pop-up --> </div> </div> <a href="" data-width="500" data-rel="popup2" class="pop-me button button-big button-green">Clic me</a> <div id="popup2" class="popup green"> <div class ="header"><h2>Green one Pop-up</h2></div> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo </p> <div class="btn"> <a class="button button-green">I agree</a> <a class="button button-red" id="cancel">I disagree</a> <!-- Just add #cancel to button if it should close pop-up --> </div> </div> <a href="" data-width="500" data-rel="popup3" class="pop-me button button-big button-blue">Clic me</a> <div id="popup3" class="popup blue"> <div class ="header"><h2>Blue one Pop-up</h2></div> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo </p> <div class="btn"> <a class="button button-green">I agree</a> <a class="button button-red" id="cancel">I disagree</a> <!-- Just add #cancel to button if it should close pop-up --> </div> </div> <a href="" data-width="500" data-rel="popup4" class="pop-me button button-big button-yellow">Clic me</a> <div id="popup4" class="popup yellow"> <div class ="header"><h2>Yellow one Pop-up</h2></div> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo </p> <div class="btn"> <a class="button button-green">I agree</a> <a class="button button-red" id="cancel">I disagree</a> <!-- Just add #cancel to button if it should close pop-up --> </div> </div> <a href="" data-width="500" data-rel="popup5" class="pop-me button button-big button-red">Clic me</a> <div id="popup5" class="popup red"> <div class ="header"><h2>Red one Pop-up</h2></div> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo </p> <div class="btn"> <a class="button button-green">I agree</a> <a class="button button-red" id="cancel">I disagree</a> <!-- Just add #cancel to button if it should close pop-up --> </div> </div> <h6>HTML code:</h6><pre><code class="language-markup"> &lt;a href="" data-width="500" data-rel="popup1" class="pop-me button button-big button-default">Clic me&lt;/a> &lt;div id="popup1" class="popup default"> &lt;div class="header">&lt;h2>Default one Pop-up&lt;/h2>&lt;/div> &lt;p> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo &lt;/p> &lt;div class="btn"> &lt;a class="button button-green">I agree&lt;/a> &lt;a class="button button-red" id="cancel">I disagree&lt;/a> &lt;!-- Just add #cancel to button if it should close pop-up --> &lt;/div> &lt;/div> &lt;a href="" data-width="500" data-rel="popup2" class="pop-me button button-big button-green">Clic me&lt;/a> &lt;div id="popup2" class="popup green"> &lt;div class ="header">&lt;h2>Green one Pop-up&lt;/h2>&lt;/div> &lt;p> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo &lt;/p> &lt;div class="btn"> &lt;a class="button button-green">I agree&lt;/a> &lt;a class="button button-red" id="cancel">I disagree&lt;/a> &lt;!-- Just add #cancel to button if it should close pop-up --> &lt;/div> &lt;/div> &lt;a href="" data-width="500" data-rel="popup3" class="pop-me button button-big button-blue">Clic me&lt;/a> &lt;div id="popup3" class="popup blue"> &lt;div class ="header">&lt;h2>Blue one Pop-up&lt;/h2>&lt;/div> &lt;p> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo &lt;/p> &lt;div class="btn"> &lt;a class="button button-green">I agree&lt;/a> &lt;a class="button button-red" id="cancel">I disagree&lt;/a> &lt;!-- Just add #cancel to button if it should close pop-up --> &lt;/div> &lt;/div> &lt;a href="" data-width="500" data-rel="popup4" class="pop-me button button-big button-yellow">Clic me&lt;/a> &lt;div id="popup4" class="popup yellow"> &lt;div class ="header">&lt;h2>Yellow one Pop-up&lt;/h2>&lt;/div> &lt;p> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo &lt;/p> &lt;div class="btn"> &lt;a class="button button-green">I agree&lt;/a> &lt;a class="button button-red" id="cancel">I disagree&lt;/a> &lt;!-- Just add #cancel to button if it should close pop-up --> &lt;/div> &lt;/div> &lt;a href="" data-width="500" data-rel="popup5" class="pop-me button button-big button-red">Clic me&lt;/a> &lt;div id="popup5" class="popup red"> &lt;div class ="header">&lt;h2>Red one Pop-up&lt;/h2>&lt;/div> &lt;p> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo &lt;/p> &lt;div class="btn"> &lt;a class="button button-green">I agree&lt;/a> &lt;a class="button button-red" id="cancel">I disagree&lt;/a> &lt;!-- Just add #cancel to button if it should close pop-up --> &lt;/div> &lt;/div></code></pre> <h3 id="plist" class="separate">Price-List</h3> <div class="plist-container"> <div class="plist red"> <div class="price">$100</div> <div class="type">Article</div> <ul class="options"> <li><strong>Nice</strong> features</li> <li><strong>Nice</strong> features</li> <li><strong>Nice</strong> features</li> </ul> <a class="button">J'achète</a> </div> <div class="plist better yellow"> <div class="price">$150</div> <div class="type">Best Offer</div> <ul class="options"> <li><strong>Nice</strong> features</li> <li><strong>Nice</strong> features</li> <li><strong>Nice</strong> features</li> </ul> <a class="button">J'achète</a> </div> <div class="plist blue"> <div class="price">$9000</div> <div class="type">Another article</div> <ul class="options"> <li><strong>Nice</strong> features</li> <li><strong>Nice</strong> features</li> <li><strong>Nice</strong> features</li> </ul> <a class="button">J'achète</a> </div> </div> <div class="plist-container"> <div class="plist green"> <div class="price">$100</div> <div class="type">Article</div> <ul class="options"> <li><strong>Nice</strong> features</li> <li><strong>Nice</strong> features</li> <li><strong>Nice</strong> features</li> </ul> <a class="button">J'achète</a> </div> <div class="plist red"> <div class="price">$150</div> <div class="type">Another Article</div> <ul class="options"> <li><strong>Nice</strong> features</li> <li><strong>Nice</strong> features</li> <li><strong>Nice</strong> features</li> </ul> <a class="button">J'achète</a> </div> <div class="plist better"> <div class="price">$9000</div> <div class="type">Best Offer</div> <ul class="options"> <li><strong>Nice</strong> features</li> <li><strong>Nice</strong> features</li> <li><strong>Nice</strong> features</li> </ul> <a class="button">J'achète</a> </div> </div> <h6>HTML code:</h6><pre><code class="language-markup">&lt;div class="plist-container"> &lt;div class="plist red"> &lt;div class="price">$100&lt;/div> &lt;div class="type">Article&lt;/div> &lt;ul class="options"> &lt;li>&lt;strong>Nice&lt;/strong> features&lt;/li> &lt;li>&lt;strong>Nice&lt;/strong> features&lt;/li> &lt;li>&lt;strong>Nice&lt;/strong> features&lt;/li> &lt;/ul> &lt;a class="button">J'achète&lt;/a> &lt;/div> &lt;div class="plist better yellow"> &lt;div class="price">$150&lt;/div> &lt;div class="type">Best Offer&lt;/div> &lt;ul class="options"> &lt;li>&lt;strong>Nice&lt;/strong> features&lt;/li> &lt;li>&lt;strong>Nice&lt;/strong> features&lt;/li> &lt;li>&lt;strong>Nice&lt;/strong> features&lt;/li> &lt;/ul> &lt;a class="button">J'achète&lt;/a> &lt;/div> &lt;div class="plist blue"> &lt;div class="price">$9000&lt;/div> &lt;div class="type">Another article&lt;/div> &lt;ul class="options"> &lt;li>&lt;strong>Nice&lt;/strong> features&lt;/li> &lt;li>&lt;strong>Nice&lt;/strong> features&lt;/li> &lt;li>&lt;strong>Nice&lt;/strong> features&lt;/li> &lt;/ul> &lt;a class="button">J'achète&lt;/a> &lt;/div> &lt;/div> &lt;div class="plist-container"> &lt;div class="plist green"> &lt;div class="price">$100&lt;/div> &lt;div class="type">Article&lt;/div> &lt;ul class="options"> &lt;li>&lt;strong>Nice&lt;/strong> features&lt;/li> &lt;li>&lt;strong>Nice&lt;/strong> features&lt;/li> &lt;li>&lt;strong>Nice&lt;/strong> features&lt;/li> &lt;/ul> &lt;a class="button">J'achète&lt;/a> &lt;/div> &lt;div class="plist red"> &lt;div class="price">$150&lt;/div> &lt;div class="type">Another Article&lt;/div> &lt;ul class="options"> &lt;li>&lt;strong>Nice&lt;/strong> features&lt;/li> &lt;li>&lt;strong>Nice&lt;/strong> features&lt;/li> &lt;li>&lt;strong>Nice&lt;/strong> features&lt;/li> &lt;/ul> &lt;a class="button">J'achète&lt;/a> &lt;/div> &lt;div class="plist better"> &lt;div class="price">$9000&lt;/div> &lt;div class="type">Best Offer&lt;/div> &lt;ul class="options"> &lt;li>&lt;strong>Nice&lt;/strong> features&lt;/li> &lt;li>&lt;strong>Nice&lt;/strong> features&lt;/li> &lt;li>&lt;strong>Nice&lt;/strong> features&lt;/li> &lt;/ul> &lt;a class="button">J'achète&lt;/a> &lt;/div> &lt;/div></code></pre> <h3 id="status" class="separate">Status icon</h3> <ul> <li>Server status: <div class="status"></div></li> <li>Server status: <div class="status off"></div></li> </ul> <h6>HTML code:</h6><pre><code class="language-markup">&lt;ul> &lt;li>Server status: &lt;div class="status">&lt;/div>&lt;/li> &lt;li>Server status: &lt;div class="status off">&lt;/div>&lt;/li> &lt;/ul> &lt;!-- &lt;ul> and &lt;li> are optional just add the class Status && off --></code></pre> <h3 id="grid" class="separate">Grid-System</h3> <div class="grid"> <h3>3 Collums</h3> <div class="col_1"> <h5>Col_1</h5> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam sodales urna non odio egestas tempor. Nunc vel vehicula ante. Etiam bibendum iaculis libero. </div> <div class="col_1"> <h5>Col_1</h5> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam sodales urna non odio egestas tempor. Nunc vel vehicula ante. Etiam bibendum iaculis libero. </div> <div class="col_1"> <h5>Col_1</h5> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam sodales urna non odio egestas tempor. Nunc vel vehicula ante. Etiam bibendum iaculis libero. </div> </div> <br> <h6>HTML code:</h6><pre><code class="language-markup">&lt;div class="grid"> &lt;h3>3 Collums&lt;/h3> &lt;div class="col_1"> &lt;h5>Col_1&lt;/h5> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam sodales urna non odio egestas tempor. Nunc vel vehicula ante. Etiam bibendum iaculis libero. &lt;/div> &lt;div class="col_1"> &lt;h5>Col_1&lt;/h5> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam sodales urna non odio egestas tempor. Nunc vel vehicula ante. Etiam bibendum iaculis libero. &lt;/div> &lt;div class="col_1"> &lt;h5>Col_1&lt;/h5> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam sodales urna non odio egestas tempor. Nunc vel vehicula ante. Etiam bibendum iaculis libero. &lt;/div> &lt;/div></code></pre> <div class="grid"> <h3>2 Collums</h3> <div class="col_2"> <h5>Col_2</h5> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam sodales urna non odio egestas tempor. Nunc vel vehicula ante. Etiam bibendum iaculis libero. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam sodales urna non odio egestas tempor. Nunc vel vehicula ante. Etiam bibendum iaculis libero. </div> <div class="col_1"> <h5>Col_1</h5> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam sodales urna non odio egestas tempor. Nunc vel vehicula ante. </div> </div> <h6>HTML code:</h6><pre><code class="language-markup">&lt;div class="grid"> &lt;h3>2 Collums&lt;/h3> &lt;div class="col_2"> &lt;h5>Col_2&lt;/h5> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam sodales urna non odio egestas tempor. Nunc vel vehicula ante. Etiam bibendum iaculis libero. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam sodales urna non odio egestas tempor. Nunc vel vehicula ante. Etiam bibendum iaculis libero. &lt;/div> &lt;div class="col_1"> &lt;h5>Col_1&lt;/h5> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam sodales urna non odio egestas tempor. Nunc vel vehicula ante. &lt;/div> &lt;/div></code></pre> <div class="grid index"> <h3>3 Collums with img</h3> <div class="col_1"> <h5>Col_1</h5> <img src="img/many.png"></img> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam sodales urna non odio egestas tempor. Nunc vel vehicula ante. Etiam bibendum iaculis libero. </div> <div class="col_1"> <h5>Col_1</h5> <img src="img/many.png"></img> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam sodales urna non odio egestas tempor. Nunc vel vehicula ante. Etiam bibendum iaculis libero. </div> <div class="col_1"> <h5>Col_1</h5> <img src="img/many.png"></img> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam sodales urna non odio egestas tempor. Nunc vel vehicula ante. Etiam bibendum iaculis libero. </div> </div> <br> <h6>HTML code:</h6><pre><code class="language-markup">&lt;div class="grid index"> &lt;h3>3 Collums&lt;/h3> &lt;div class="col_1"> &lt;h5>Col_1&lt;/h5> &lt;img src="img/many.png">&lt;/img> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam sodales urna non odio egestas tempor. Nunc vel vehicula ante. Etiam bibendum iaculis libero. &lt;/div> &lt;div class="col_1"> &lt;h5>Col_1&lt;/h5> &lt;img src="img/many.png">&lt;/img> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam sodales urna non odio egestas tempor. Nunc vel vehicula ante. Etiam bibendum iaculis libero. &lt;/div> &lt;div class="col_1"> &lt;h5>Col_1&lt;/h5> &lt;img src="img/many.png">&lt;/img> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam sodales urna non odio egestas tempor. Nunc vel vehicula ante. Etiam bibendum iaculis libero. &lt;/div> &lt;/div></code></pre> </div> </div> <!-- End-main --> </div> <!-- End-main-container --> </div><!-- End-Page --> <?php include("include/footer.php"); ?> <file_sep>/website/download.php <?php $titre ="Download"; include("include/header.php");?> <div class="article"> <div class="header"> <h1>Download page</h1> <p>Here you can download Simplex-UI</p> </div> <h3 class="separate">Just download and try it ! :)</h3> <h4>Master Version <small>(From Github)</small> :</h4> <p class="hl-green">This version include Current version of simplex, with website, website use php include, in a way you can be very fast in your work if you use it.</p> <a href="https://github.com/Chikoumi/Simplex-UI/archive/master.zip" target="_blank" class="button button-green button-big button-block">Download master.zip</a> <h4>Just Simplex-ui ZIP <small>(Without Website)</small> :</h4> <p class="hl-yellow">If you download this zip, you will just have version 1.1 of simplex, website aren't include.</p> <a href="https://raw.githubusercontent.com/Chikoumi/Simplex-UI/master/version_1.1.zip " target="_blank" class="button button-yellow button-big button-block">Download Version 1.1</a> </div> </div> <!-- End-main --> </div> <!-- End-main-container --> </div><!-- End-Page --> <?php include("include/footer.php"); ?> <file_sep>/website/include/footer.php <!-- Please do not put code between page and footer to prevent sticky-footer / Ne pas placer de code ici pour ne pas supprimer le sticky-footer--> <div class="footer-print">&copy; 2014 | Company name</div> <!-- This footer will replace next footer on print --> <!-- sticky-footer --> <div class="footer-container"> <footer class="wrapper"> <center><h1>Simplex-UI <br><small>Free CSS Starter Kit</small></h1></center> <div class="grid"> <div class="col-3"> <h3>About Simplex</h3> Simplex is born on 2014, I've the idea to create my own CSS template and to share it with other webmaster, Simplex must to be simple to use, he must be without js as for as I can, he is fully responsive and in a way mobile-ready. I've added a lot of themes, they are easy to change with a CSS tag. </div> <div class="col-3"> <h3>About Author</h3> Simplex-UI is provide by Chk (Chikoumi), i'm a french guys who really love to create website, i can use php, html, css, js and a lot of langage related to linux. I'm a member of Harmony-Hosting's support who sell VPS. If you want to know more about me, you can read <a target="_blank" href="http://chikoumi.com" class="lbl yellow">my website</a> </div> <div class="col-3"> <h3>Simplex-UI</h3> If you want to know more about Simplex-ui's use you can read the <br> <a class="button button-blue button-big button-block" href="/use">Usage page</a> <br>If you just to download it, you should go to : <br> <a class="button button-green button-big button-block" href="/download">Download Page</a> </div> </div> <p class="copy">&copy; <a target="_blank" href="http://chikoumi.com">Chk</a> | 2014 | Simplex-UI</p> </footer> </div> <!-- End-sticky-footer --> <script type="text/javascript"></script> <!-- JS-invocation --> <script src="js/jquery-1.11.0.min.js"></script> <script src="js/general.js"></script> <!-- JS GENERAL code --> <!-- end-JS-invocation --> <?php if ($titre == "Demo") { echo '<script src="demo-files/demo.js"></script>';} ?> <?php if ($titre == "How to use") { echo '<script src="demo-files/prism.js"></script>';} ?> </body> </html><file_sep>/website/index.php <?php $titre ="Home"; include("include/header.php");?> <div class="article"> <div class="header"> <h1>Home</h1> <p>Welcome on Simplex-UI Website. If you want to start your site with a starter kit, this is the right place. I propose you a kit to be able to start in the web world. This kit does not pretend to be turnkey, you will subsequently create a site to your image. The use of the kit has been made as easy as possible.</p> </div> </style> <h3 class="separate">Simply to use, for everyone</h3> <div class="grid index"> <div class="col_1"> <h5>Responsive</h5> <img src="img/responsive.png"></img> Your website can be viewed on a mobile phone or on a screen and will be automatically adapted. Without JS, just with css, because of an old or incompatblie browser. </div> <div class="col_1"> <h5>Simple Tag</h5> <img src="img/simple.png"></img> Just with an css tag you can change design color, or fix the navbar or fixed sidebar on left, on right. Very simple to use and easy to understand. </div> <div class="col_1"> <h5>Lots of features</h5> <img src="img/many.png"></img> Many tools are offered to you : tables, labels, buttons, code, card message, stylized <i>p</i> and message, Progress-bar, hint on hover, pop-up, price-list... </div> </div> </div> </div> <!-- End-main --> </div> <!-- End-main-container --> </div><!-- End-Page --> <?php include("include/footer.php"); ?>
2bf73f2eb1e83f91d49b5813fd8968d4fe1e32f8
[ "Markdown", "JavaScript", "PHP" ]
9
Markdown
Chikoumi/Simplex-UI
2fc58b61132dca45bff7325268a9061f48b77955
c5d1f9c9a2367c87357b0ba32e96febc9b2990d8
refs/heads/master
<repo_name>mit4351/myapp<file_sep>/app/views/user_sessions/new.html.erb <%= form_for @user, url: users_path do |f| %> <fieldset> <legend>Sign up</legend> <p> <%= f.label :name %> <%= f.text_field :name %> </p> <p> <%= f.label :empno %> <%= f.text_field :empno %> </p> <p> <%= f.label :password %> <%= f.password_field :password %> </p> <p> <%= f.label :password_confirmation %> <%= f.password_field :password_confirmation %> </p> <%= f.submit "sign up", class: "btn btn-primary" %> </fieldset> <% end %><file_sep>/app/models/user.rb class User < ApplicationRecord # for authlogic acts_as_authentic do |c| c.login_field = :email end end <file_sep>/app/controllers/user_sessions_controller.rb class UserSessionsController < ApplicationController skip_before_filter :require_login, only: [:new, :create] # GET /login def new @user_session = UserSession.new end # POST /user_session def create @user_session = UserSession.new(params[:user_session]) if @user_session.save redirect_to root_url else render action: :new end end # DELETE /logout def destroy current_user_session.destroy redirect_to login_url end end
77026ddc794a7d6219bc141b09f7e03db856ad74
[ "HTML+ERB", "Ruby" ]
3
HTML+ERB
mit4351/myapp
4de4379086526b279758fa5aa49b471239cc44cb
d5080670545d5b376c1f79d4233ca7d2524568dd
refs/heads/master
<repo_name>RyuKimura/JRPG<file_sep>/JRPG/objects/playerClass/Draw_0.gml /// @description Insert description here // You can write your code in this editor spr = character + "_spr"; spr_ind = asset_get_index(spr); draw_sprite_ext(spr_ind,0,x,y,1,1,0,c_white,1); //draw_text(x-8,y-32,"(" + string(xstart) + "," + string(ystart) + ")"); if(dead == true) { draw_sprite(dead_spr,0,x,y); }<file_sep>/JRPG/scripts/useItem/useItem.gml var type = argument0; switch(type){ case "money": //add moeny break; case "exp": //add exp break; case "item": // add randomm item break; case "enemy": //spawn enemy break; case "heal": //heal all plauyers break; } <file_sep>/JRPG/scripts/enemyGen/enemyGen.gml ///enemyGen(array, enenmyFrequency, maxEnemy) randomize(); var enemyMax = 0; for(i = 0; i <= ds_list_size(argument0); i++){ if(enemyMax >= argument2) break; if(floor(random(100)) <= argument1){ var temp = argument0[|i]; if(abs(point_distance(entrance.x,entrance.y,temp.x,temp.y)) > 150) { var enem = instance_create_depth(temp.x,temp.y,-6,skullEnemy); enemyMax++; } } }<file_sep>/JRPG/objects/gameManager/KeyPress_16.gml /// @description Insert description here // You can write your code in this editor currentNum += 1;<file_sep>/JRPG/objects/gameManager/Create_0.gml /// @description Insert description here // You can write your code in this editor // declare globals randomise(); globalvar player, enemy, playerPartySize, enemyPartySize, totalPartySize, currentNum, turnOrder; // Player Start Positions startPositionPlayerX[1] = 240; startPositionPlayerY[1] = 240; startPositionPlayerX[2] = 320; startPositionPlayerY[2] = 360; startPositionPlayerX[3] = 240; startPositionPlayerY[3] = 480; // Enemy Start Positions startPositionEnemyX[1] = 240*3; startPositionEnemyY[1] = 240; startPositionEnemyX[2] = 320*2; startPositionEnemyY[2] = 320; startPositionEnemyX[3] = 320*2; startPositionEnemyY[3] = 400; startPositionEnemyX[4] = 240*3; startPositionEnemyY[4] = 480; playerPartySize = 3; enemyPartySize = irandom_range(1,4); totalPartySize = playerPartySize + enemyPartySize; currentNum = 1; for(i = 1; i <= playerPartySize; i++) { player[i] = instance_create_depth(startPositionPlayerX[i],startPositionPlayerY[i],100,idiot_obj); player[i].name = "Player " + string(i); player[i].number = i; fighters[i] = player[i]; } for(i = 1; i <= enemyPartySize; i++) { enemy[i] = instance_create_depth(startPositionEnemyX[i],startPositionEnemyY[i],100,rock_obj); enemy[i].name = "Enemy " + string(i); fighters[(i + playerPartySize)] = enemy[i]; } // Turn Order for(ii = totalPartySize+1; ii >= 1; ii-=1) { turnOrder[ii] = noone; } for(i = 1; i <= totalPartySize; i++) { for(ii = totalPartySize; ii >= 1; ii-=1) { if(turnOrder[ii] != noone) { if(turnOrder[ii] != fighters[i]) { if(fighters[i].agi > turnOrder[ii].agi) { tempOrder = turnOrder[ii]; turnOrder[ii] = fighters[i]; turnOrder[ii+1] = tempOrder; } } } else { turnOrder[ii] = fighters[i]; turnOrder[ii+1] = noone; } } } active = true; instance_create_depth(x,y,100,battleManager);<file_sep>/JRPG/objects/gameManager/Draw_0.gml /// @description Insert description here // You can write your code in this editor if(active == true) { for(i = 1; i <= totalPartySize; i++) { if(turnOrder[i] != noone) { draw_text(320,32+(32*i),"Turn " + string(i) + ": " + string(turnOrder[i].name) + " - Agility: " + string(turnOrder[i].agi)); } else { draw_text(320,32+(32*i),"Turn " + string(i) + ": noone"); } } }<file_sep>/JRPG/scripts/ItemGeneration/ItemGeneration.gml ///ItemGeneration(array, itemFrequency, itemMaxItems) randomize(); var itemMax = 0; for(i = 0; i <= ds_list_size(argument0); i++){ if(itemMax >= argument2) break; if(floor(random(100)) <= argument1){ var temp = argument0[|i]; if(!position_meeting(temp.x,temp.y,entrance) && !position_meeting(temp.x,temp.y,goal)){ instance_create_depth(temp.x,temp.y,-6,Item); itemMax++; } } }<file_sep>/JRPG/objects/overworldParty/Collision_d90a439b-44aa-4dd1-a4c4-09e18c6dd40c.gml /// @description Insert description here // You can write your code in this editor if(show_question("Move to next dungeon?")){ MapGeneration(Wall,200,4,Generation.array, 1, 5, 10, 5); } else{ x = xprevious; y = yprevious; }<file_sep>/JRPG/scripts/MapGeneration/MapGeneration.gml ///MapGeneration(wallObject,numTunnels,maxTunnelLength,array, ItemFrequency, maxItems, enemyFreq, maxEnemy) randomize(); var first = true; var existingGoal; if(instance_exists(goal)) { first = false; existingGoal = goal; } ds_list_clear(argument3); instance_destroy(Item); instance_destroy(skullEnemy); instance_destroy(Wall); instance_destroy(entrance); instance_destroy(blockade); var gap = sprite_get_width(Sprite_Wall); var strt; var randX; var randY; //if this is the first time creating a map //find a random place for an entrance if(first){ randX = floor(random(room_width/gap)) * gap; randY = floor(random(room_height/gap))* gap; while(true){ var c = 0; var cc = 0; if(randX <= 0 || randX >= room_width - gap) { randX = floor(random(room_width/gap)) * gap; } else c = 1; if(randY <= 0 || randY >= room_height - gap){ randY = floor(random(room_height/gap))* gap; } else cc = 1; if(c == 1 && cc == 1) break; } strt = instance_create_depth(randX, randY, 0 , argument0); instance_create_depth(randX, randY, -6 , entrance); }else { randX = existingGoal.x; randY = existingGoal.y; strt = instance_create_depth(randX, randY, 0 , argument0); instance_create_depth(randX, randY, -6 , entrance); } ds_list_add(argument3,strt); //continue to make tunnels of paths while(argument1 != 0){ var len = floor(random_range(1,argument2)); var dir = choose(0,1,2,3); // 0 = up 1 = down 2 = left 3 = right for(i = len; i != 0; i--){ switch(dir){ case 0: if((randY - gap) <= 0) break else randY -= gap break; case 1: if((randY + gap) >= room_height - gap) break else randY += gap break; case 2: if((randX - gap) <= 0) break else randX -= gap break; case 3: if((randX + gap) >= room_width - gap) break else randX += gap break; default: break; } if(!position_meeting(randX,randY,argument0)){ var temp = instance_create_depth(randX, randY, 0 , argument0); ds_list_add(argument3,temp); } else{ var randPos = argument3[| floor(random(ds_list_size(argument3)))]; randX = randPos.x; randY = randPos.y; continue; } } argument1--; } //create the goal instance_destroy(goal); var randPos = argument3[| floor(random(ds_list_size(argument3)))]; var finish = instance_create_depth(randPos.x, randPos.y, -5 , goal); //make sure its not overlapping with the entrance while(true){ if(position_meeting(finish.x,finish.y,entrance)){ randPos = argument3[| floor(random(ds_list_size(argument3)))]; finish.x = randPos.x; finish.y = randPos.y; } else break; } for(i = 0; i != ds_list_size(argument3); i++){ var kk = argument3[|i]; if(position_empty(kk.x + gap, kk.y)) instance_create_depth(kk.x + gap, kk.y, -10, blockade); if(position_empty(kk.x - gap, kk.y)) instance_create_depth(kk.x - gap, kk.y, -10, blockade); if(position_empty(kk.x, kk.y + gap)) instance_create_depth(kk.x, kk.y + gap, -10, blockade); if(position_empty(kk.x, kk.y - gap)) instance_create_depth(kk.x, kk.y - gap, -10, blockade); } ItemGeneration(argument3,argument4, argument5); enemyGen(argument3,argument6,argument7);<file_sep>/JRPG/objects/Generation/KeyPress_32.gml //MapGeneration(Wall,200,4,array, 1, 5, 10, 5);<file_sep>/JRPG/objects/playerClass/Create_0.gml /// @description Insert description here // You can write your code in this editor // Stats name = "Player"; type = "player"; dead = false; hp = irandom_range(75,150); mp = irandom_range(30,60); atk = irandom_range(10,30); def = irandom_range(5,15); // Attributes str = irandom_range(1,10); agi = irandom_range(1,10); int = irandom_range(1,10); luck = irandom_range(1,10); /// @description Insert description here // You can write your code in this editor maxSpells = 5; spell[0,0] = "Agi"; spell[1,0] = "Zio"; spell[2,0] = "Garu"; spell[3,0] = "Bufu"; spell[4,0] = "Dia"; spell[0,1] = 5; spell[1,1] = 3; spell[2,1] = 2; spell[3,1] = 1; spell[4,1] = 1;<file_sep>/JRPG/objects/goal/Draw_0.gml /// @description Insert description here // You can write your code in this editor draw_circle_color(x,y,5,c_blue,c_blue,0);<file_sep>/JRPG/objects/skullEnemy/Step_0.gml /// @description Insert description here // You can write your code in this editor switch(AIState){ case "moving": if(mp_potential_step_object(destination.x,destination.y,1,blockade)) { destination = mapData.array[| floor(random(ds_list_size(mapData.array)))]; } break; case "chase": break; default: break; }<file_sep>/JRPG/objects/dmgNum/Create_0.gml /// @description Insert description here // You can write your code in this editor speed = 0.5; direction = 90; time = 30; int = 0; type = "nothing";<file_sep>/JRPG/objects/dmgNum/Draw_0.gml /// @description Insert description here // You can write your code in this editor switch(type) { case "damage": draw_text_color(x,y,string(int),c_red,c_red,c_red,c_red,1); break; case "heal": draw_text_color(x,y,string(int),c_green,c_green,c_green,c_green,1); break; }<file_sep>/JRPG/objects/Item/Create_0.gml /// @description Insert description here // You can write your code in this editor type = choose("money", "exp","item","enemy","heal");<file_sep>/JRPG/objects/idiot_obj/Create_0.gml /// @description Insert description here // You can write your code in this editor // Character Presets character = "explorer"; event_inherited();<file_sep>/JRPG/objects/Generation/Create_0.gml /// @description Insert description here // You can write your code in this editor array = ds_list_create(); MapGeneration(Wall,200,4,array, 1, 5, 10, 5);<file_sep>/JRPG/objects/skullEnemy/Draw_0.gml /// @description Insert description here // You can write your code in this editor draw_self(); //draw_line(x,y,destination.x,destination.y);<file_sep>/JRPG/objects/battleManager/Draw_0.gml /// @description Insert description here // You can write your code in this editor draw_set_alpha(1); squareDist = 52; if(current != noone) { if(actionType == "nothing") { if(current.dead == false) { draw_sprite_ext(point_spr,0,current.x-48,current.y+16,1,1,90,c_white,1); } } if(actionType == "target") { if(currentSelect != noone) { if(currentSelect.dead == false) { draw_sprite_ext(point_spr,0,currentSelect.x-16,currentSelect.y-64,1,1,0,c_white,1); } } } } if(actionTarget == "enemy") { //draw_text(32,256,"Damage = " + string(dmg)); } if(actionTarget == "friend") { //draw_text(32,256,"Heal = " + string(heal)); draw_rectangle_color(190+(num*200),588,360+(num*200),670,c_green,c_green,c_green,c_green,true); } //draw_text(32,32,"Menu Count - " + string(menuMax)); draw_text(32,32,"Turn = " + string(turn)); draw_text(32,128,"Selected Action - " + string(action)); draw_text(32,160,"Target Type - " + string(actionTarget)); draw_text(32,192,"Turn Number = " + string(turnNumber)); draw_text(32,224,"Num = " + string(num)); draw_text(32,256,"turnTimer = " + string(turnTimer) + " / " + string(turnTimerMax)); if(turn == "player") { draw_rectangle_color(190+(current.number*200),588,360+(current.number*200),670,c_yellow,c_yellow,c_yellow,c_yellow,true); } draw_rectangle(32,480-32,128+extraRoom,room_height-32,true); for(i = 0; i < menuMax; i++) { i_x = ((128)/2)+16; i_y = (480+(squareDist*(i+1))-48); draw_circle(i_x,i_y,24,true); //draw_sprite(select_icon_spr,0,i_x,i_y); sprIcon = menu[menuType,i] + "_icon_spr"; sprIconInd = asset_get_index(sprIcon); if(sprIconInd != -1) { draw_set_alpha(1); draw_sprite_ext(sprIconInd,0,i_x,i_y,0.75,0.75,0,c_white,1); } switch(menuType) { case 2: draw_text(i_x+32,i_y,"x" + string(item[i,1])); break; case 1: if(current != noone) { draw_text(i_x+32,i_y,string(current.spell[i,1]) + "mp"); } break; } menuIconX[i] = i_x; menuIconY[i] = i_y; } if(menuNum >= 0 and menuNum < menuMax) { draw_text(32,64,"Menu = " + string(menuType)); draw_text(32,96,"Action = " + string(menu[menuType,menuNum])); draw_set_alpha(0.25); draw_circle_color(menuIconX[menuNum],menuIconY[menuNum],24,c_yellow,c_yellow,false); } // Party UI if(drawAction == true) { draw_text((room_width/2)-32,128,string(action)); } for(i = 1; i <= playerPartySize; i++) { draw_set_alpha(1); draw_set_color(c_white); draw_text(200+(i*200),598,"Name: " + string(player[i].name)); draw_text(200+(i*200),620,"HP: " + string(player[i].hp)); draw_text(200+(i*200),642,"MP: " + string(player[i].mp)); } draw_sprite_ext(point_spr,0,290,64+(32*turnNumber),1,1,90,c_white,1);<file_sep>/JRPG/objects/enemyClass/Create_0.gml /// @description Insert description here // You can write your code in this editor // Stats name = "Enemy"; type = "enemy"; hp = irandom_range(75,150); mp = irandom_range(30,60); atk = irandom_range(10,30); def = irandom_range(5,15); // Attributes str = irandom_range(1,10); agi = irandom_range(1,10); int = irandom_range(1,10); luck = irandom_range(1,10); dead = false;<file_sep>/JRPG/objects/battleManager/Step_0.gml /// @description Insert description here // You can write your code in this editor if(currentEnemyAlive <= 0) { room_goto(room0); } if(currentPartyAlive <= 0) { room_goto(room0); } menuMax = array_length_2d(menu,0); switch(menuNum) { case -1: menuNum = menuMax-1; break; case menuMax: menuNum = 0; break; } turnNumber = currentNum; while(current == noone) { if(current == noone) { turnNumber += 1*dir; } if(turnNumber > totalPartySize) { turnNumber = 1; } if(turnNumber < 1) { turnNumber = totalPartySize; } current = turnOrder[turnNumber]; } if(current != noone) { //while(current.dead == true) //{ //if(currentEnemyAlive > 0 && currentPartyAlive > 0) //{ //turnNumber += 1; if(turnNumber > totalPartySize) { turnNumber = 1; } if(turnNumber < 1) { turnNumber = totalPartySize; } //current = turnOrder[turnNumber]; //} //} current = turnOrder[turnNumber]; } turn = current.type; if(turn == "player") { // Menu Buttons // MenuButtons(); // Item Update for(i = 0; i < maxItems; i++) { menu[2,i] = item[i,0]; } if(current != noone) { for(i = 0; i < current.maxSpells; i++) { menu[1,i] = current.spell[i,0]; } } partySize = playerPartySize; // Targeting PlayerTargeting(); } if(turn == "enemy") { partySize = enemyPartySize; while(current == noone) { current = enemy[num]; if(current == noone) { num += 1; } if(num > partySize) { num = 1; } } if(turnTimer <= turnTimerMax) { turnTimer += 1; if(turnTimer >= turnTimerMax) { EnemyTargeting(); drawAction = true; turnTimer = 0; nextTurn(); } } //currentNum += 1; } <file_sep>/JRPG/scripts/EnemyTargeting/EnemyTargeting.gml enemyAction = irandom(2); switch(enemyAction) { case 0: case 1: case 2: target = irandom_range(1,playerPartySize); while(player[target].dead == true) { target = irandom_range(1,playerPartySize); } if(player[target].dead != true) { currentSelect = player[target]; int = current.atk; moveType = "damage"; actionExecute(); //nextTurn(); } break; default: //nextTurn(); break; }<file_sep>/JRPG/objects/overworldParty/Step_0.gml /// @description Insert description here // You can write your code in this editor vkLeft = -keyboard_check(vk_left); vkRight = keyboard_check(vk_right); vkUp = -keyboard_check(vk_up); vkDown = keyboard_check(vk_down); hspd = vkRight + vkLeft; vspd = vkDown + vkUp; x += hspd*spd y += vspd*spd; enemy = instance_nearest(x,y,skullEnemy) if(distance_to_object(enemy) <= 8) { instance_destroy(enemy); room_goto(playtest_room); }<file_sep>/JRPG/objects/entrance/Draw_0.gml /// @description Insert description here // You can write your code in this editor draw_circle_color(x,y,5,c_red,c_red,0); //draw_circle(x,y,150,1);<file_sep>/JRPG/objects/gameManager/Step_0.gml /// @description Insert description here // You can write your code in this editor if(currentNum > totalPartySize) { currentNum = 1; }<file_sep>/JRPG/scripts/nextTurn/nextTurn.gml int = 0; menuType = 0; menuNum = 0; actionType = "nothing"; actionTarget = "nothing"; action = "nothing"; currentNum += 1;<file_sep>/JRPG/objects/dmgNum/Step_0.gml /// @description Insert description here // You can write your code in this editor time -= 1; if(time <= 0) { instance_destroy(); }<file_sep>/JRPG/scripts/MenuButtons/MenuButtons.gml if(actionTarget == "nothing") { if(keyboard_check_pressed(vk_up)) { menuNum -= 1 } if(keyboard_check_pressed(vk_down)) { menuNum += 1 } } if(actionType == "target") { if(keyboard_check_pressed(vk_left)) { dir = -1; num += 1*dir } if(keyboard_check_pressed(vk_right)) { dir = 1; num += 1*dir } } switch(actionType) { case "target": switch(menuType) { case 0: if(keyboard_check_pressed(vk_space)) { int = current.atk; moveType = "damage"; actionExecute(); nextTurn(); } break; case 1: if(keyboard_check_pressed(vk_space)) { SpellList(); actionExecute(); nextTurn(); } break; } break; case "nothing": switch(menuType) { case 0: if(keyboard_check_pressed(vk_space)) { switch(menu[0,menuNum]) { case "Spells": case "Items": extraRoom = 32; lastMenuPos = menuNum; menuType = menuNum; menuNum = 0; break; case "Attack": actionType = "target"; actionTarget = "enemy"; action = menu[menuType,menuNum]; break; } } break; case 1: if(keyboard_check_pressed(vk_space)) { SpellDirectory(); action = menu[menuType,menuNum]; } break; case 2: if(keyboard_check_pressed(vk_space)) { switch(menu[2,menuNum]) { case "Attack": actionType = "target"; actionTarget = "enemy"; action = menu[menuType,menuNum]; break; } } break; } break; } if(keyboard_check_pressed(vk_backspace)) { switch(menuType) { case 1: case 2: switch(actionType) { case "target": actionType = "nothing"; actionTarget = "nothing"; action = "nothing"; dmg = 0; heal = 0; break; case "nothing": extraRoom = 0; menuType = 0; menuNum = lastMenuPos; break; } break; case 0: actionType = "nothing"; actionTarget = "nothing"; action = "nothing"; dmg = 0; break; } } <file_sep>/JRPG/scripts/actionExecute/actionExecute.gml numberStats = instance_create_depth(currentSelect.x,currentSelect.y-32,-100,dmgNum); numberStats.int = int; numberStats.type = moveType; switch(moveType) { case "damage": currentSelect.hp -= int; break; case "heal": currentSelect.hp += int; break; }<file_sep>/JRPG/objects/enemyClass/Step_0.gml /// @description Insert description here // You can write your code in this editor if(dead != true) { if(hp <= 0) { currentEnemyAlive -= 1; dead = true; } }<file_sep>/JRPG/objects/inventoryManager/Create_0.gml /// @description Insert description here // You can write your code in this editor globalvar item, maxItems; maxItems = 5; item[0,0] = "Health Potion"; item[1,0] = "Mana Potion"; item[2,0] = "Revive Potion"; item[3,0] = "Farcaster"; item[4,0] = "Large Barrel Bomb"; item[0,1] = 5; item[1,1] = 3; item[2,1] = 2; item[3,1] = 1; item[4,1] = 1;<file_sep>/JRPG/scripts/SpellList/SpellList.gml switch(menu[1,menuNum]) { case "Agi": case "Zio": case "Garu": case "Bufu": int = round((10*current.int)*0.75); moveType = "damage"; break; case "Dia": int = round((15*current.int)*0.25); moveType = "heal"; break; }<file_sep>/JRPG/scripts/SpellDirectory/SpellDirectory.gml actionType = "target"; switch(menu[1,menuNum]) { case "Agi": case "Bufu": case "Garu": case "Zio": actionTarget = "enemy"; break; case "Dia": actionTarget = "friend"; break; }<file_sep>/JRPG/objects/battleManager/Create_0.gml /// @description Insert description here // You can write your code in this editor globalvar currentEnemyAlive, currentPartyAlive; current = turnOrder[1]; currentSelect = noone; turn = "nothing"; turnNumber = 1; num = 1; dir = 1; chooseNum = 1; actionType = "nothing"; actionTarget = "nothing"; action = "nothing" dmg = 0; turnTimerMax = 60; turnTimer = 0; heal = 0; currentPartyAlive = playerPartySize; currentEnemyAlive = enemyPartySize; // Action Menu menuMax = 0; menuNum = 0; lastMenuPos = 0; extraRoom = 0; drawAction = false; // Menu Types // /* Base - 0 Spell - 1 Item - 2 */ menuType = 0; menu[0,0] = "Attack"; menu[0,1] = "Spells"; menu[0,2] = "Items"; menu[0,3] = "Block"; menu[0,4] = "Flee"; /* menu[1,0] = "Fire Spell"; menu[1,1] = "Water Spell"; menu[1,2] = "Air Spell"; menu[1,3] = "Earth Spell"; menu[1,4] = "Heal Spell"; */ /* menu[2,0] = "Health Potion"; menu[2,1] = "Mana Potion"; menu[2,2] = "Revive Potion"; menu[2,3] = "Farcaster"; menu[2,4] = "Large Barrel Bomb"; */ <file_sep>/JRPG/objects/entrance/Create_0.gml /// @description Insert description here // You can write your code in this editor if(!instance_exists(overworldParty)){ instance_create_depth(x,y,-100,overworldParty); }else { overworldParty.x = x; overworldParty.y = y; }<file_sep>/JRPG/objects/skullEnemy/Create_0.gml /// @description Insert description here // You can write your code in this editor destination = mapData.array[| floor(random(ds_list_size(mapData.array)))];<file_sep>/JRPG/scripts/PlayerTargeting/PlayerTargeting.gml switch(actionTarget) { case "enemy": targetPartySize = enemyPartySize; while(currentSelect == noone) { if(currentSelect == noone) { num += 1*dir; } if(num > targetPartySize) { num = 1; } if(num < 1) { num = targetPartySize; } currentSelect = enemy[num]; } if(currentSelect != noone) { if(currentSelect.dead = true) { num += 1*dir; } if(num > targetPartySize) { num = 1; } if(num < 1) { num = targetPartySize; } if(instance_exists(enemy[num]) == true) { currentSelect = enemy[num]; } else { currentSelect = noone; } } break; case "friend": targetPartySize = playerPartySize; while(currentSelect == noone) { if(currentSelect == noone) { num += 1*dir; } if(num > targetPartySize) { num = 1; } if(num < 1) { num = targetPartySize; } currentSelect = player[num]; } if(currentSelect != noone) { if(num > targetPartySize) { num = 1; } if(num < 1) { num = targetPartySize; } currentSelect = player[num]; } break; case "nothing": /* while(current == noone) { if(current == noone) { currentNum += 1*dir; } if(currentNum > partySize) { currentNum = 1; } if(currentNum < 1) { currentNum = partySize; } current = player[currentNum]; } if(current != noone) { if(currentNum > partySize) { currentNum = 1; } if(currentNum < 1) { currentNum = partySize; } current = player[currentNum]; } */ break; }
2c42ceed881e68a7db402b027b53c5929922f7aa
[ "Game Maker Language" ]
38
Game Maker Language
RyuKimura/JRPG
93fb6e131ff0b030bd126bbec251bb4d0b5dc5db
219f7bc209951517b9184506d623ea4a97e19201
refs/heads/master
<file_sep>#!/usr/bin/env python # coding: utf-8 # # Example of performing linear least squares fitting # ### First we import numpy and matplotlib as usual # In[ ]: get_ipython().run_line_magic('matplotlib', 'inline') import matplotlib.pyplot as plt import numpy as np # ## Now let's generate some random data about a trend line # In[ ]: #Set a random number seed np.random.seed(119) #Set number of data points npoints = 50 #Set x x = np.linspace(0,10.,npoints) #Set slope, intercept, and scatter rms m = 2.0 b = 1.0 sigma = 2.0 #Generate y points y = m*x + b + np.random.normal(scale=sigma, size=npoints) #scale=sigma is the rms value of a gaussian, so we're generating gaussian noise y_err = np.full(npoints, sigma) #This means there are 50 two values to fill the array(?) # ### Let's just plot the data first to make sure the plot works # In[ ]: f = plt.figure(figsize=(7,7)) plt.errorbar(x,y,sigma,fmt='o') plt.xlabel('x') plt.ylabel('y') # ### Method #1, polyfit() # In[ ]: m_fit, b_fit = np.poly1d(np.polyfit(x, y, 1, w = 1./y_err)) #weight with uncertainties print(m_fit, b_fit) y_fit = m_fit * x * b_fit # ### Plot result # In[ ]: f = plt.figure(figsize=(7,7)) plt.errorbar(x,y, yerr=y_err, fmt='o', label='data') plt.plot(x,y_fit,label='fit') plt.xlabel('x') plt.ylabel('y') plt.legend(loc=2, frameon=False) # In[ ]: <file_sep>#!/usr/bin/env python # coding: utf-8 # In[ ]: get_ipython().run_line_magic('matplotlib', 'inline') import numpy as np import matplotlib.pyplot as plt # In[ ]: x = np.arange(0, 5, 0.1) #create x = [0..5] in 0.1 increments y = np.sin(x) #y = sin(x) plt.plot(x,y) #make a plot plt.xlabel('x') #label x axis plt.ylabel('sin(x)') #label y axis plt.show() #show the plot on the screen # In[ ]: #Save an image as png x = np.arange(0, 5, 0.1) #create x = [0..5] in 0.1 increments y = np.sin(x) #y = sin(x) plt.plot(x,y) #make a plot plt.xlabel('x') #label x axis plt.ylabel('sin(x)') #label y axis plt.savefig('sinx.png', bbox_inches="tight", dpi=600) #Save figure as png # In[ ]: #Save an image as pdf x = np.arange(0, 5, 0.1) #create x = [0..5] in 0.1 increments y = np.sin(x) #y = sin(x) plt.plot(x,y) #make a plot plt.xlabel('x') #label x axis plt.ylabel('sin(x)') #label y axis plt.savefig('sinx.pdf', bbox_inches="tight", dpi=600) #Save figure as png #can change to .pdf # In[ ]: get_ipython().run_line_magic('matplotlib', 'inline') import numpy as np import matplotlib.pyplot as plt # In[ ]: #Make a multipanel plot with matplotlib x = np.linspace(0,2*np.pi,100) print(x[-1],2*np.pi) y = np.sin(x) <file_sep># astr-119-session-6 Class session 6 on 10/16/18 <file_sep>#!/usr/bin/env python # coding: utf-8 # ## Making multipanel plots with matplotlib # ### First we import numpy and matplotlib as per usjj # In[ ]: get_ipython().run_line_magic('matplotlib', 'inline') import numpy as np import matplotlib.pyplot as plt # ### Then we define an array of angles, and their sines and cosines using numpy. This time we will use linspace # In[2]: x = np.linspace(0,2*np.pi,100) print(x[-1],2*np.pi) y = np.sin(x) z = np.cos(x) w = np.sin(4*x) v = np.cos(4*x) # ### Now let's make a two panel plot side-by-side # In[3]: #Call subplots to generate a mltipanel figure. this means 1 row, 2 #columns of figures f, axarr = plt.subplots(1,2) #Treat axarr as an array from left to right #First panel axarr[0].plot(x,y) axarr[0].set_xlabel('x') axarr[0].set_ylabel('sin(x)') axarr[0].set_title(r'$\sin(x)$') #Second panel axarr[1].plot(x,z) axarr[1].set_xlabel('x') axarr[1].set_ylabel('cos(x)') axarr[1].set_title(r'$\cos(x)$') # ### The panels are too close together above. # ### We can adjust that using the subplots_adjust() function. # In[4]: #Call subplots to generate a mltipanel figure. this means 1 row, 2 #columns of figures f, axarr = plt.subplots(1,2) #Treat axarr as an array from left to right #First panel axarr[0].plot(x,y) axarr[0].set_xlabel('x') axarr[0].set_ylabel('sin(x)') axarr[0].set_title(r'$\sin(x)$') #Second panel axarr[1].plot(x,z) axarr[1].set_xlabel('x') axarr[1].set_ylabel('cos(x)') axarr[1].set_title(r'$\cos(x)$') #Add more space between the figures f.subplots_adjust(wspace=0.4) # ### The axis ratios are all squished, let's fix that too. # ### We can use set_aspect() to change the axis ratio # In[5]: #Call subplots to generate a mltipanel figure. this means 1 row, 2 #columns of figures f, axarr = plt.subplots(1,2) #Treat axarr as an array from left to right #First panel axarr[0].plot(x,y) axarr[0].set_xlabel('x') axarr[0].set_ylabel('sin(x)') axarr[0].set_title(r'$\sin(x)$') #Second panel axarr[1].plot(x,z) axarr[1].set_xlabel('x') axarr[1].set_ylabel('cos(x)') axarr[1].set_title(r'$\cos(x)$') #Add more space between the figures f.subplots_adjust(wspace=0.4) #Fic the axis ratio #Here are two possible options axarr[0].set_aspect('equal') #make the ratio of the tick units equal, #a bit counter-intuitive axarr[1].set_aspect(np.pi) #make a square by setting the aspect to #to be the ratio of the tick unit range # ### Alright, let's keep the square figurem merge them into one, remove the titles and add legends # In[11]: #Adjust the size of the figure fig = plt.figure(figsize=(6,6)) plt.plot(x, y, label=r'$y = \sin(x)$') #add a label to the line plt.plot(x, z, label=r'$y = \cos(x)$') #add a label to the second line plt.plot(x, w, label=r'$y = \sin(4x)$') #add a label to the third line plt.plot(x, v, label=r'$y = \cos(4x)$') #add a label to the fourth line plt.xlabel(r'$x$') #note set_xlabel vs. xlabel plt.ylabel(r'$f(x)$') #note set_ylabel vs. ylabel plt.xlim([0,2*np.pi]) #note set_xlim vs. xlim plt.ylim([-1.2,1.2]) #note set_ylim vs. ylim plt.legend(loc=1, framealpha=0.95) #add a legend with semi-transparent frame in the upper RH corner #Fix the axis ratio plt.gca().set_aspect(np.pi/1.2) #Use "gca" to get current axis # In[ ]:
67ffdfa0cbef5b038908726c737b3cb4bdfba5a9
[ "Markdown", "Python" ]
4
Markdown
abanda97/astr-119-session-6
b60cd3f2274acd3206d0a86ae80c57b5e0105c75
f7f469eb7706e5445313f885341c1604496246f6
refs/heads/master
<file_sep>CREATE TABLE `anställd` ( `id` int, `namn` varchar, `lön` int, `avdelning-id` int, PRIMARY KEY (`id`), `avdelning-id` int FOREIGN KEY REFERENCES `avdelning` (id) ); CREATE TABLE `avdelning` ( `id` int, `namn` varchar, `nummer` int, `anställd-chef-id` int, PRIMARY KEY (`id`), `anställd-chef-id` int FOREIGN KEY REFERENCES `anställd` (id) ); CREATE TABLE `vara` ( `id` int, `namn` varchar, `nummer` int, `avdelning-id` int, `leverantör-id` int, PRIMARY KEY (`id`), `avdelning-id` int FOREIGN KEY REFERENCES `avdelning` (id), `leverantör-id` int FOREIGN KEY REFERENCES `leverantör` (id) ); CREATE TABLE `leverantör` ( `id` int, `namn` varchar, `adress` varchar, PRIMARY KEY (`id`) ); CREATE TABLE `kund` ( `id` int, `namn` varchar, `adress` varchar, PRIMARY KEY (`id`) ); CREATE TABLE `order` ( `id` int, `order-nummer` int, `order-datum` date, `kund-id` int, `vara-id` int, PRIMARY KEY (`id`), `kund-id` int FOREIGN KEY REFERENCES `kund` (id), `vara-id` int FOREIGN KEY REFERENCES `vara` (id) KEY `FK` (`kund-id`, `vara-id`) ); <file_sep># ER-DIAGRAM<br/> ## ER DIAGRAMÖVNINGAR ### Tips: #### 1:Om det inte finns någon unik nyckel i en entitetstyp, så kan man skapa ett särskilt unikt identitetsnummer bara för användning i databasen. #### 2:Det är ofta klokt att skapa ett unikt identitetsnummer även om det redan finns en unik nyckel, om den nyckeln är en textsträng eller olämplig av andra skäl. #### 3:Man behöver inte använda arv eller svaga entitetstyper i dom här uppgifterna. ## Kom ihåg: #### 1 Finns det saker i rutan ovan som är svåra eller omöjliga att rita i ER-diagrammet? Hur gör man då? #### 2 Fattas det information som egentligen skulle behövas för att rita ER-diagrammet? Hur gör man då? ## Gör det här: Skapa ett entity-relationship-schema för att skapa databasen i varje uppgift, ni behöver inte ange datatypen (domänen) för varje attribut, men ni bör ange primär- och främmande- nycklar. # Övning 1: Gamingsoft: Multi User Dungeon Game Det finns en klass av dataspel som kallas massively multiplayer online role-playing games, eller MMORPG. Det är spel där man spelar en rollfigur, till exempel en riddare, som går runt i en simulerad värld och slåss med monster, samlar skatter eller bara pratar med andra spelare som spelar samma spel och går runt i samma simulerade värld. Ett par kända såna spel är EverQuestoch World of Warcraft.<br/> Redan på sjuttiotalet fanns det textbaserade liknande spel, där man (precis som i de moderna MMORPG-spelen) spelar en rollfigur, går runt i en simulerad värld, och interagerar med andra spelare. En klass av såna textbaserade spel kallas Multi-user dungeon, eller MUD. Man styrde sin rollfigur med kommandon som "gå norrut", "ta upp väskan" och "anfall björnen".I den här uppgiften ska vi skapa en databas som kan användas för lagring av data i ett MUD.<br/> <br/> De saker som ska lagras i databasen är följande:<br/> 1 Spelare. En "spelare" är egentligen inte en representation av själva spelaren, utan av den rollfigur som spelaren spelar i spelet. Spelaren (dvs rollfiguren) har ett unikt namn, en (inte nödvändigtvis unik) beskrivning, och några "stats", dvs värden som beskriver rollfigurens egenskaper: styrka, skicklighet, friskhet och hur många poäng som spelaren samlat ihop. Spelarna måste finnas kvar i databasen även när de loggar ut. En spelare som dör i spelet försvinner inte, utan förlorar bara sina saker och en del av sina poäng.<br/> 2 Monster. Ett "monster" behöver inte vara grönt och ha många tänder, utan alla figurer i spelet som styrs av datorn och inte av en spelare kallas för monster. Ett monster har, precis som en spelare, ett namn, en beskrivning och dessutom samma "stats" som spelarna. En skillnad är att namnet inte behöver vara unikt, utan det kan till exempel finnas många grodor som allihop heter Groda. Ett monster som dör i spelet försvinner.<br/> 3 Rum eller platser. Det här är de platser som spelarna och monstren kan gå omkring i. Varje spelare som är inloggad i spelet befinner sig i ett visst rum. Spelare som inte är inloggade, befinner sig inte i något rum. En del rum kan vara tomma. Varje rum har ett unikt nummer, ett (inte nödvändigtvis unikt) namn och en (inte nödvändigtvis unik) beskrivning.<br/> 4 Saker. Det här är de saker som finns i spelet, förutom rum, spelare och monster. Det kan till exempel vara stenar, guldmynt, svärd och tulpaner. Sakerna kan ligga och skräpa i rummen, och dessutom kan både spelarna och monstren plocka upp sakerna och bära omkring på dem. Varje sak befinner sig antingen i ett visst rum, eller på en viss spelare eller monster. Varje sak har ett (inte nödvändigtvis unikt) namn och en (inte nödvändigtvis unik) beskrivning.<br/> 5 Servrar. Spelvärlden är så stor att den inte kan hanteras av en enda dator, utan den är uppdelad på ett antal olika datorer, eller servrar. Varje rum hör till en viss server. Spelarna och monstren kan däremot flytta sig mellan servrarna. Varje server har ett IP-nummer (dvs dess Internet-adress), som kan ändras ibland men som är unikt vid varje tillfälle.De flesta mudden var ganska små, och kördes på en enda server. De innehöll kanske tio tusen rum eller platser, och några tiotal samtidiga spelare. Men nu tänker vi oss att vi ska konkurrera med EverQuest och World of Warcraft, så vi vill kunna hantera hundratalas servrar, miljoner rum, och tiotusentals spelare. # Övning 2: The Universitetet <br/> Antag att universitetet behöver ett databassystem för att hålla rätt på studenter som går kurser, vem som ger vilka kurser och var de personerna är anställda (vilken institution).<br/> ### De saker som ska lagras i databasen är följande:<br/> För att representera studenter behöver vi lagra namn (förnamn och efternamn skiljs så att man enkelt kan sortera på efternamn), personnummer för att få ett unikt id, kontonamn och lösenord. Kurser har kurskoder, namn, ges en viss period och ägs (ansvaras för) av en viss institution. De ger ett visst antal poäng och hålls av någon som är anställd på högskolan. Olika år kan en viss kurs ges olika läs-perioder och av olika personer (dock max en gång per år). Om en kurs byter namn eller omfattning i poäng, eller flyttas till annan institution måste den också byta kurskod, dvs formellt blir det en ny kurs. Institutionen som ansvarar för kurserna är inte nödvändigtvis samma institution som läraren är anställd på.<br/> ### The extra mile: Antag att rektor utlyser pengar för pedagogiska projekt, som institutionerna kan arrangera. Man vill kunna söka efter alla olika projekten, kolla deras tidsplaner och budgetar. Projekten identifieras med namn, MEN man kan inte anta att namnen är helt unika. Inom varje institution finns en kontroll att namnen är unika, men institutionerna pratar inte med varandra.<br/> # Övning 3: That Företaget Antag att ett företag med s.k. matrisorganisation (personalen är anställd på avdelningar, som har avdelningschefer, men arbetet organiseras i projekt där man plockar in folk från olika avdelningar efter behov) behöver hjälp att hantera information om sina anställda för lönehantering och arbetsplanering, samt att hantera de löneförmåner i form av familjeförsäkringar som de anställda har. Avdelningschefers lön är delvis beroende av hur länge de varit chefer för sina avdelningar.<br/> ### De saker som ska lagras i databasen är följande: Företaget består av ett antal avdelningar. Varje avdelning har ett namn, ett nummer, en chef och ett antal anställda. Startdatum för varje avdelningschef registreras. En avdelning kan ha flera lokaler. Lokaler identifieras endast med sina namn. Varje avdelning finansierar ett antal projekt. Varje projekt har ett namn, ett nummer och en lokal där man arbetar. För varje anställd lagras följande information: namn, personnummer, adress, lön och kön. En anställd jobbar för endast en avdelning men kan jobba med flera projekt som kan tillhöra olika avdelningar. Information om antalet timmar (per vecka) som en anställd planeras jobba med ett projekt lagras. Facket har drivit igenom ett krav på att ingen får beläggas mer än 40 timmar i veckan. Information gällande den anställdes avdelningschef behöver också finnas. För varje anställd lagras information om familjen av försäkringsskäl. För varje familjemedlem lagras förnamn, födelsedatum, kön samt typ av relation till den anställde (make/maka resp barn). Man kan inte anta att informationen om familjemedlemmarna är unik. Man antar att anställda inte är gifta med varandra (vilket problem skulle kunna uppstå om vi inte antog detta). ### Man ska kunna svara på följande frågor (med SQL) : <NAME> är sjuk idag, sök ut alla projekt där hon jobbar så att man kan skriva på lokalens whiteboard att hon är sjuk. De anställda som har barn under 12 år ska få ett erbjudande om barnförsäkring (lista anställda med barn under 12) Projekt X har drabbats av förseningar och behöver komma ikapp. Deltagarna behöver kunna lägga mer tid på projektet under den närmaste månaden. De avdelningschefer som har folk som jobbar på projekt X ska sammankallas för förhandlingar. # Övning 4: Check the Varuhuset Antag att ett större varuhus-företag med butiker över hela landet behöver hålla rätt på personalen och varorna, samt kunder som får hemleveranser. Man behöver hålla rätt på personalens löner och för varorna gäller det lagersaldo och leveranser från olika leverantörer (en viss vara kan levereras av olika leverantörer). <br/> ### De saker som ska lagras i databasen är följande: Varuhusföretaget har anställda, med namn och lön, som arbetar på varuhusets olika avdelningar (namn och nummer), där man säljer olika varor (namn och nummer). Varje avdelning har en chef, som är en av de anställda. Varorna levereras av olika leverantörer (namn och adress), och flera leverantör kan leverera samma varor, men till olika priser, som också kan variera från gång till gång. Varuhuset har hemkörningsservice. Kunder som har konto hos varuhuset och anmält en adress för leveranser kan beställa varor och få dem levererade hem. Varje sådan beställning har ett ordernummer och ett orderdatum, utöver listan av ingående varor (naturligtvis kan man beställa mer än en av varje vara vid ett visst tillfälle).<br/> # Övning 5: Sjukhusets förlossningsavdelning Man dokumenterar förlossningar, varje förlossning involverar en mor och ett barn som föds (som inte kan identifieras med något personnummer ännu, utan identifieras med hjälp av modern och vilken tid förlossningen startade). Flerbarnsfödslar dokumenteras som olika förlossningar med olika tidpunkter (förlossningen för en yngre tvilling anses starta då den första tvillingen är ute). Personalen som medverkar är alltid en ansvarig barnmorska och minst en men oftast flera andra sköterskor. Det finns också alltid en ansvarig förlossningsläkare, men vid en normal förlossning blir denna aldrig involverad. All personal identifieras med anställnings-ID, och man lagrar namnet och arbetspasset (dag/kväll/natt) som arbetats. Barnmorskor och läkare har också personsökare, vars nummer man lagrar. Man vill för varje förlossning veta vilken personal som var involverad och vilket barnets status på APGARskalan var. Förlossningsförloppet dokumenteras i kvinnans journal men om förlossningsläkaren ingriper skriver denne dessutom i sin egen dokumentation, där varje inlägg tidsstämplas men annars inte särbehandlas (dvs det är ett enda dokument som tillhör läkaren). # Övning 6: Värsta Mäklarfirman Antag att en mäklarfirma behöver hjälp att hålla ordning på sina försäljningsobjekt, kunder och budgivning. Man vill också hålla ordning på de banker kunderna har kontakt med. ### De saker som ska lagras i databasen är följande: För varje objekt (fastighet) lagrar man adress, område, beskrivning, bild, boyta samt vilken typ av fastighet det är (lägenhet, villa, kedjehus). En viss mäklare (en av de anställda) är huvudansvarig för varje objekt. Varje objekt tilldelas en unik kod. Information om ägarna lagras också. Varje mäklare har ett unikt ID, ett kontor och ett mobilnummer, och namn. Varje mäklare ansvarar för ett antal försäljningsobjekt. Man lagrar också information om lånegivande banker/institut. För varje långivare (som har unika namn men också ges ett ID) har man en kontaktperson och mobilnummer till den personen, samt ett centralt telefonnumret till företaget. Man behöver ibland kontakta dessa långivare för att bekräfta bud. Varje kund registreras med namn, adress och mobilnummer, samt hemtelefon och arbetstelefon. Man registrerar också alternativa kontaktpersoner (t.ex maka/make) med telefonnummer. En kund ges ett kundnummer för att kunna identifieras unikt. Ett bud på ett objekt har ett visst belopp och läggs vid en viss tidpunkt, som markeras av en unik tidsstämpel för att säkert kunna visa i vilken ordning buden lagts på ett visst objekt. Ett bud på ett objekt kan inte vara lägre än ett tidigare bud. Ett bud läggs av en viss kund via en mäklare och stöds av en lånegivare. Ett bud måste förmedlas via en mäklare, men det behöver inte vara den mäklare som har huvudansvaret för försäljningsobjektet. Ett bud har oftast, men behöver inte ha, en stödjande lånegivare (ifall kunden inte behöver ta lån).
d71455ce7840343f3970ffe7d97125f0bd823703
[ "Markdown", "SQL" ]
2
Markdown
pedramamiri/ER-DIAGRAM
6fb5340a780dad652af3cb47d9e4d34105baf8eb
237fe41b256ce570bd20f0c620db6fc0aacca6ae
refs/heads/master
<repo_name>gapoorva/microservice-tutorial<file_sep>/README.md # microservice-tutorial This repository is a reference and tutorial with code examples to understand and utilize microservices. In this tutorial, we will cover: * What are microservices? * What is docker? * How can you use docker to build effective microservices? * What is golang? * How can you use golang with docker? * How do you make a small microservice in golang? * What is a URL shortener? * How do you test microservices? We will explore the above in stages. Each stage will have it's own `README.md`. Be sure to reach each to understand what covered in each stage. We will build upon previous stages to develop a full URL shortening microservice. Please let me know if you have any questions - feel free to open github issues on this repo. <file_sep>/stage2-sol/replace.sh #!/bin/bash echo $1 | sed "s/$2/$3/g"<file_sep>/stage1/README.md # microservice-tutorial: Stage 1 In this stage, we'll talk a bit about what a microservice is and how it's used in software engineering. We won't be actually writing any code in this part of the tutorial, this stage purely conceptual. ## What's a mircoservice? A microservice is a small, focused, and maintainable unit of a system. A system that is designed using microservices has high "cohesion" but low "coupling". When systems are designed in this way, the major benefit is ability to maintain, debug, deploy and develop individual components with a relatively low cost as opposed to a more coupled system. ### Cohesion Cohesion is a measure of how well related logic is kept in one place. If related logic is spread all over a system, the system can suffer performance impacts of communication across logical component boundaries. Often this means that related state is duplicated everywhere the related logic exists. When we go to make changes to how the logic works, we might end up "cascading" the effects of the changes across our system. This is especially concerning in systems that use a shared component in many unrelated places. When that's the case, it's difficult to make changes to the behavior of the shared component. If a certain application of the component necessitates a change in the interface of the component, you have to be careful that this interface change is compatible with other uses! Let's use an example to demonstrate - you are working on a project with 4 other people, except the people on your team are spread across the globe. Your communication suffers because it takes a full day or longer for your teammates to reply to your emails due to the time difference. If your team agreed to equally divide up the project so that everyone gives input on every part of the project, your team will have poor cohesion. It seems counter-intuitive, since the team is doing *everything* together, but that model also requires a lot of communication and real time collaboration which is highly expensive when everyone has to work remotely. To make the team more cohesive, it actually makes more sense to split project into individual subproblems that can be solved more or less independently. Then, your team could divide up the subproblems. Since the sub-problems don't require a lot of collaboration to solve, your team can reduce the expensive cross-globe communication to when it's really necessary. Similarly, in software systems it makes more sense for components to be as self sufficient and singularly focused as possible - solving a focused subproblem in one component makes the system overall more efficient and modular. ### Coupling Coupling is a measure of how much components depend on each other. Some coupling is inevitable between components of a system, since separating out functionality into smaller components requires these components to work together for the system to function. Microservices aim to reduce coupling between system components as much as possible by taking all the parts of the system that have high cohesion (see the section above) and bundling them together. The resulting components will depend less on each other. While these interfaces can't be completely elminated, reducing them as much as possible makes a system much easier to maintain. It's useful to have low coupling between components since it makes it easier to replace the part of the system with a different implementation or process without requiring complementing changes in other components. In highly coupled systems it can be difficult to even change a component since components can depend on each other in strange ways. Fixing a bug can then require changes in multiple parts of the system. Let's use a warehouse analogy to demonstrate coupling. Let's say two employees need to load a truck. One employee (selector) decides the highest priority packages to load in the truck, retrives them, and then hands it to the second employee (loader). The loader is responsible for loading the package into the truck in a way that consumes the least amount of space. The two employee system has high coupling since the selector can't select the next package until the loader takes it off her hands, and the loader can't load more packages until the selector hands it to her. If we were to replace either employee with a high-tech robot arm, we would then have to train that employee to work with the robot which can be more expensive than we can afford. To fix the coupling, we can add a conveyor belt to the system. The selector places packages on the conveyer belt, and the loader picks them off to load them. In this scenario, the loader and selector don't need to pay attention to each other, they can both pick up/place packages at will. An additional benefit of this solution is that we can now replace one or both employees with a robot arm without having to train the other employee, since their workflow won't be impacted. ### Coupling & Cohesion in Microservices A microservice-oriented architecture allows a software system to attain low coupling and high cohesion. This means that components are better at performing one focused function, and don't rely heavily on other systems to do their work. Moreover, when we decide to change something about a microservice - or replace it entirely - we don't need to make sweeping changes across the system since the related logic and functionality is scoped to the component itself. Proper application of microservices is very similar to the core computer science concepts of encapsulation and abstraction. Both of the mechanisms allow us to create systems that are inexpensive to build and maintain, and that are flexible enough to evolve and improve over time as the needs of your users change. ## When should I use microservices? Just because we've been talking about all the benefits of microservices doesn't mean that they are always the right tool for the job. Microservices can be expensive to build and maintain, since deploying several fragmented components can often introduce a lot of unwanted overhead. For example, in cloud computing, each microservice typically represents an individual web server. Each microservice will then require it's own deployment pipeline, need to be to be tested separately, and might need to repeat a lot of common functionality like boiler-plate to authenticate a user session. ### A case for the Monolith Often, microservices aren't the starting point for a software organization. Many large software companies today started out with a single application that handled all functions, which are typically referred to as a **Monolith**. Monoliths will often have bad code cohesion and a high amount of coupling - these properties will make it harder and harder to make changes over time as more functionality is added, since small changes have the potential for widespread impact in behavior. At the same time, Monolithic applications side-step a lot of the overhead issues related to microservices. With one application, you only need to deploy one application before your users can realize the functionality of your software. There's typically one (or a few) codebases to maintain, and a lot of common functionality can be shared within the application leading to less repeated code. As a result, it's often the case that starting with a monolithic app is a **good** move for an engineering organization. It helps engineers work faster to deliver more features without taking on the overhead of microservices. ### Scale with microservices When would we make the transition over to microservices? This really depends from project to project, but a good indication is when coupling within the system erodes cohesion to the point where it starts impact feature development. This slows down the delivery of features that users find valuable, as engineers struggle with what's called **technical debt**. It's the cost of adding coupling and decreasing cohesion in order to deliver features quickly. When it piles up, it prevents the codebase from scaling. **Scaling** is somewhat of a buzzword in the software world, but it is a core part of software engineering, since we're always thinking about how our systems perform as we add more users, more data, and more functionality into the mix. More users will naturally result in a larger volume of transactions in a system. More data requires computing resources to both compute on and store the data. More functionalities make the system ever more complicated. A combination of these factors along with a monolithic code base cause real problems. The application might function correctly for the first 1,000 users supported on the system, but at 10,000, the system slows to the point where it's unusable. Some stragies like multiple instances of the application can help split traffic, but ultimately this extremely expensive - linearly scaling the number of computing resources with the number of users or data your system can handle is unsustainable, especially since the added cost (financial or otherwise) doesn't ensure greater profits. Microservices can help this scenario by splitting up traffic and logic in a way that scales properly. To understand how scaling works let's visualize an example - Imagine a restaurant that serves 10 different items. 9 of these items are quick and easy to produce, but 1 of these items are expensive. For all 10 items, the same groceries are bought, the same kitchen is used, and the same staff works on them. However that 1 item is hard to do right, takes a lot of space in the kitchen and requires multiple cooks to prepare. Assuming each of the items is equally popular, the restaurant can only serve a certain amount of customers until they simply can't keep up with orders - there's not enough space, dishes or staff to cook every order. As a result the restaurant can't serve more customers, and therefore can't make more profits. To help this restaurant scale, one thing the owner can do is to split off that 1 expensive item into it's very own food truck. With this food truck focusing on just this one item, it's much easier to plan and prepare that item. The restaurant can then drop that item of the menu, and continue to serve the 9 cheaper items. When this is done, a lot of resources get freeded up in the kitchen and the restaurant is suddenly able to handle way more orders, which means more customers and more profits! Meanwhile loyal patrons can still get the expensive item from the foodtruck, which can specially configured to produce that one item. Similarly, sometimes in software it makes sense to split large applications into focused microservices that are specialized to specific task at hand. Microservices can lead the operational benefits within software organizations as well, since these organizations can naturally split up into teams dedicated to a set of microservices. This is a great way to scale the number of *engineers* working on the project as well! ## Further Reading For the purposes of this tutorial, the above will be enough context about microservices to understand how build them and when to use them. If you'd like to do further reading I recommend picking up copy of [*Building Microservices* by <NAME>, Published by O'Reily Media Inc.](https://www.amazon.com/Building-Microservices-Designing-Fine-Grained-Systems/dp/1491950358) from which the above content was also partly adopted. <file_sep>/stage2/README.md # microservice-tutorial: Stage 2 **Note**: Working code examples for this stage can be found in the [`stage2-sol`](https://github.com/gapoorva/microservice-tutorial/stage2-sol) folder. In this stage, we'll start talking about [docker](https://www.docker.com), a popular linux container system that can run on most operating systems, and why it helps us implement microservices. We'll be adding docker to our local system, "pulling down" some images and running containers to get an understanding for what docker can do. ## What is Docker? Docker calls itself a "container platform". It allows you to run [docker containers](https://www.docker.com/resources/what-container) on what's called the [docker engine](https://www.docker.com/products/docker-engine). Before understanding all these terms, let's briefly explore the core problem docker is trying to solve. When running an application that serves real users, it's important to make sure the application works as intended. Often, the environment an application is developed in is different from the one it is run in. For example, most cloud applications run on linux servers, since these environments have strong software engineering communities and tools built on top of them. However, a developer may prefer to use a Windows or MacOS operating system to develop his or her software. Colloquially, this is known as the "works on my machine" problem. Even if you develop an application on the same operating system as it runs on in "production", you can still run into problems if all the depencies of an application, like special files or SSL certificates, or networking setups are different. Historically, software engineers have solved this problem by using virtual machines. In a virtual machine, an entire operating system and file system is emulated on the host computer. Virtual machines can still be expensive to run, since your application runs on several layers of abstraction. If virtual machine stops working, it's expensive to create a new one, since the machine images are huge. Finally, every VM needs to be setup independently - you can't send a VM to your teammate and have them run it without some required setup. Docker aims to solve these problems using docker **images** and docker **containers**. Docker images are *composable descriptions* of a file system and system tools/libraries needed to run you application. You can define this file system with code, like you would any other program. Docker containers are *instances* of the images you define, and like virtual machines can be started or stopped. Unlike VMs however, containers only include what is needed to run your app, so they are very small and less resource intensive. You can also save docker images and store them in a repository so that other developers can retrieve them and run them in the exact same environment. In fact, docker images can run on any machine that has the docker engine installed - including the linux server that hosts your application to users! ## Installing Docker Let's get started using docker. Below are instructions for installing docker on 3 popular operating systems. For more operating systems, see the [Docker installation guide](https://docs.docker.com/v17.12/install/). * [MacOS](https://docs.docker.com/v17.12/docker-for-mac/install/) * [Windows 10](https://docs.docker.com/v17.12/docker-for-windows/install/) * [Ubuntu](https://docs.docker.com/v17.12/install/linux/docker-ce/ubuntu/#os-requirements) We won't need to install other softwares for this tutorial - docker will allow us to use any tool we want! From this point on, since we'll be running utilities in the same environment, we won't need to make special exceptions for operating systems anymore :) ## Pulling your first Docker image Let's start with the `hello-world` image. This is an image made by the creators of docker that will run a simple binary, print some output, and then exit. Ensure docker is available from your command line: ``` $ docker -v Docker version 18.06.0-ce, build 0ffa825 ``` Then, let's directly run: ``` $ docker run hello-world ``` This will cause the docker engine to check locally for the `hello-world` **image**. Since it doesn't find it locally, it pulls from the docker registry - which is a public, shared registry. Once the image is downloaded, it will attempt to run it by creating a new **container**. That container is then executed, and the output is sent to the terminal. After the process ends, the container stops and becomes dormant. To see your dormant container run: ``` $ docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 71f02a8bbf42 hello-world "/hello" 3 minutes ago Exited (0) 3 minutes ago stoic_stallman ``` This will show you containers on your system. The `-a` flag makes docker show you both stopped *and* running containers. Ommitting it will show you only running containers. For this reason, think of containers like individual processes on your machine like your web browser or a text editor. Once they stop, the life of the process is over. As you continue using docker you will accumulate stopped containers and unused images. It's a good idea so prune your images and containers periodically. Just run the following commands (agreeing to any questions): ``` $ docker container prune $ docker image prune ``` ## Running a docker image interactively We can run docker images interactively by specifying a few special arguments to docker run, which will set up some configurations and make it appear as if we have `ssh`'d inside a VM. Quick overview of options: * `--rm` Removes the container after running it, so you don't collect extra containers * `-it` Attaches an interactive TTY to the container so that you can send and receive signals to the container Try it with an ubuntu image: ``` $ docker run --rm -it ubuntu ``` Docker will first pull the image `ubuntu` if it's unable to find it locally. Then it will start up the container and then execute the default entrypoint for this image, which is `bash`. ### Other useful options You can pass environment variables using `-e`: ``` $ docker run --rm -it -e "FOO=BAR" ubuntu root # echo $FOO BAR ``` You can change the command that is run when the container is started: ``` $ docker run --rm -it ubuntu ls bin dev home lib64 mnt proc run srv tmp var boot etc lib media opt root sbin sys usr ``` You can change the working directory: ``` $ docker run --rm -it -w "/home" ubuntu pwd /home ``` ## The Dockerfile Until now, we've worked with two different images. One was the `hello-world` image, and the other was the `ubuntu` image. Docker gives us the ability to define our own images that have all the pieces we need to run our apps. We can use a `Dockerfile` to define an image. This allows us to set up a lot of the environment for our app. This can include: * Installing binaries such as node, python, php, etc... * Adding in source code files * Adding in configuration files * Setting up a working directory * Changing the user to boot the machine with * Setting up port forwarding * Setting up a default "entrypoint" * Setting up a default command on the entrypoint. We can use this to build our image and ship it like an "executable". As an example, let's use this small bash script and dockerize it. **replace.sh** ```bash #!/bin/bash echo $1 | sed "s/$2/$3/g" ``` This is a small (and trivial) wrapper around the sed command that accepts content as `$1`, a search regex as `$2` and a replacement string as `$3`. Below is example usage: ``` $ ./replace.sh "my cat ate a bat and then a hat" "[c|b|h]at" warble my warble ate a warble and then a warble ``` We can use a dockerfile to build a docker image whose sole purpose will be to run this command, in a consistent, ubuntu environment. No matter which host OS this image is run on, thanks to docker it will behave the same. First, let's create a dockerfile: **Dockerfile** ```Dockerfile # FROM specifies which image to inherit from - this helps reduce the number of things we'd need to potentially redefine/install in order to have a working ubuntu environment. FROM ubuntu # COPY command copies files in from the "build context" to the image. This would be used to copy in source files and configuration files. # # Here, we're copying replace.sh from the "build context" directory to the "/home" directory within the image. COPY ./replace.sh /home # WORKDIR changes which directory is considered the "working directory" inside the image. The last setting will then be the default location in the file system when the image is run. WORKDIR /home # RUN executes a command in the shell. This is the way we can run executables to have side effects like installing dependencies or compiling code. The command is run within the last WORKDIR setting. Here, we're making sure that `replace.sh` is executable. RUN chmod +x replace.sh # ENTRYPOINT sets up the executable that should be run inside the docker container. This can't be overriden by the user when running `docker run`, essentially making this command the single focus of this image. ENTRYPOINT ["/bin/bash", "/home/replace.sh"] # CMD sets what the default command arguments should be, and is passed to the ENTRYPOINT as a set of default arguments when none is provided by the user. This is why CMD is an array. In our case, there isn't a good default for the replace command so we will omit this from the Dockerfile. # # If we were to uncomment the line below, by default the container would print "jello" and then exit when run without any parameters. # CMD ["hello", "h", "j"] ``` This Dockerfile _codifies_ the environment that we want to set up, so we can be sure that our image works the same way every single time. We can use the Dockerfile and the `docker build` command to build our new image: ``` $ docker build -t replace-executable:1.0.0 -f ./Dockerfile . # a bunch of output .... Successfully built 609bf6c49a23 Successfully tagged replace-executable:1.0.0 ``` **Explanation of options**: * `-t replace-executable:1.0.0` aliases our image as "replace-executable" in addition to the SHA that docker generates. In the above example, that's `609bf6c49a23`. We can add an additional (optional) qualifier to the name as a "tag" - in practice this is often used to specifiy a version and when omitted, docker assumes that tag should be `latest`. * `-f ./Dockerfile` specifies a path to the Dockerfile that `docker build` should use. When the path is `./*.Dockerfile`, you can actually omit the `-f` option, `docker` automatically searches for a `*.Dockerfile` in your current working directory. * Notice at the end of the `docker build` command is a `.`. Very subtle, the dot is important because that argument is specifying the **build context**. This is how `docker` knows where to grab your source code from. You can of course run the `docker build` command using a different build context than your current working directory. **Explanation of output** What's happened here is that `docker` executed the commands in our Dockerfile in sequence to arrive at our new image. As it builds, it spits out SHA tags like `---> cd6d8154f1e1`. These are the SHA identifiers of "layers". Each command in the Dockerfile causes `docker` to build a new "layer" using the previous layer as a starting point and then adding the changes from the command. The resulting filesystem is hashed and the layer is given that ID. This way, when we go to rebuild the image after changing some source code, we only have to re-run the steps starting with the step that copies in source code. Layers before then don't have to change and therefore don't have to be re-computed. This saves a bunch of time when developing on docker. If any command in the Dockerfile results in an error, `docker build` will spit out an error and stop building. This way `docker build` is almost like a compiler for your environment. We now have our first custom docker image! Hooray! We can confirm that our docker image really does exist by running `docker images`: ``` $ docker images REPOSITORY TAG IMAGE ID CREATED SIZE replace-executable 1.0.0 96b92c6cddc6 2 minutes ago 84.1MB # Potentially more images also listed ... ``` Now, just like the `hello-world` and `ubuntu` images, we can run our `replace-executable` image as well! ``` $ docker run --rm replace-executable "my cat ate a bat and then a hat" "[c|b|h]at" warble my warble ate a warble and then a warble ``` What we've done is made an executable out of our docker image - one that is very good at replacing text in strings. There's a slight downside in that it takes a bit more typing, but it's nothing a small bash script or a bash `alias` couldn't cure :). As an added benefit, you can now run your image anywhere, including a new terminal window, different working directory or as we'll see below on you friend's computer! ## Sharing your images Going back to the beginning of this stage, our goal with learning `docker` was to solve the "works on my machine" problem. So it's important to learn how you can share and distribute your docker images. With this ability you can send your docker images to your teammates, run it on a raspberry pie, or transfer it to your cloud machine so that you can expose your app to the wider internet audience. ### Docker Hub method One way you can share your docker images is by using a **docker registry**. This is basically a remote server that can manage image uploads and downloads so that anyone with access to the internet (and your images) can publish new versions of an image and pull latest versions. It works a lot like cloud SCM services like Github or BitBucket. You could host your own private registry - and most serous software organizations will consider doing this to save money and secure their technology - but for small and open source projects, the public docker registry called "docker hub" should work great. First head over to [hub.docker.com](https://hub.docker.com) to create an account with docker. Then, login to your local docker agent: ``` $ docker login -u <username> ``` You will be prompted for your password, after which you should be authenticated to your docker agent. You can now push images to the docker hub under your account. To publish your docker image, you need namespace your image under your username. To do this, let's build another version of `replace-executable` but under your username namespace. ``` $ docker build -t "<your_username>/replace-executable" -f ./Dockerfile . ``` You can now publish the docker file to your docker hub account: ``` $ docker push <your_username>/replace-executable ``` After some pushing... tada! You have published your first image to the docker hub. You can use the UI on [hub.docker.com](https://hub.docker.com) to manage access control rights and collaborators who can push to your docker repo using the same name. Now, your friend can run this image locally with just one command (as long as they too have docker installed): ``` $ docker run --rm <your_username>/replace-executable "my cat ate a bat and then a hat" "[c|b|h]at" warble my warble ate a warble and then a warble ``` It doesn't matter which environment you developed your app on, it doesn't matter which environment you need to run your app in. As long as both have `docker`, you can run any kind of tech stack. With nothing but a favorite text editor and `docker` you can build most every software application you can think of. ## Further Reading For our tutorial, this was a fairly thorough overview of docker. There are plenty of tools we didn't cover, and the best place to read about them is the [docs.docker.com documentation](https://docs.docker.com).<file_sep>/stage2-sol/Dockerfile # FROM specifies which image to inherit from - this helps reduce the number of things we'd need to potentially redefine/install in order to have a working ubuntu environment. FROM ubuntu # COPY command copies files in from the "build context" to the image. This would be used to copy in source files and configuration files. # # Here, we're copying replace.sh from the "build context" directory to the "/home" directory within the image. COPY ./replace.sh /home # WORKDIR changes which directory is considered the "working directory" inside the image. The last setting will then be the default location in the file system when the image is run. WORKDIR /home # RUN executes a command in the shell. This is the way we can run executables to have side effects like installing dependencies or compiling code. The command is run within the last WORKDIR setting. Here, we're making sure that `replace.sh` is executable. RUN chmod +x replace.sh # ENTRYPOINT sets up the executable that should be run inside the docker container. This can't be overriden by the user when running `docker run`, essentially making this command the single focus of this image. ENTRYPOINT ["/bin/bash", "/home/replace.sh"] # CMD sets what the default command arguments should be, and is passed to the ENTRYPOINT as a set of default arguments when none is provided by the user. This is why CMD is an array. In our case, there isn't a good default for the replace command so we will omit this from the Dockerfile. # # If we were to uncomment the line below, by default the container would print "jello" and then exit when run without any parameters. # CMD ["hello", "h", "j"]
832dd8819abef904a0944107b12370bfa14df82e
[ "Markdown", "Shell", "Dockerfile" ]
5
Markdown
gapoorva/microservice-tutorial
cd583fa5829475dc17f5da60e875cc1b53e3a035
dc16d0bbe1d4b069bbd842213aa7beba79e514c0
refs/heads/master
<file_sep>import React, {Component} from "react" import { FaTwitter, FaGithub, FaLinkedin, FaEnvelope, FaItchIo } from "react-icons/fa"; import { IconContext } from "react-icons"; import "../styles/links.scss" class Links extends Component { render() { return ( <div className="links-container"> <IconContext.Provider value={{ className: 'react-icons', size: '1.4em', style: {color: this.props.color}}}> <a href="https://twitter.com/shuttlefrog"> <FaTwitter /> </a> <a href="https://github.com/tpeng3"> <FaGithub /> </a> <a href="https://shuttlefrog.itch.io/"> <FaItchIo /> </a> <a href="https://linkedin.com/in/tpeng3"> <FaLinkedin /> </a> <a href="mailto:<EMAIL>"> <FaEnvelope /> </a> </IconContext.Provider> </div> ) } }; export default Links;<file_sep>const gameData = [ { id: 10, name: "Cafe in the Clouds", date: "March 2020​, October 2020 - Present", description: `UX and Gameplay Programmer, Writer, and Sound Designer for a point and click adventure visual novel starring two lovely dreameaters who investigate and eat away their client's troubles. Made with two other friends during the 2020 NaNoReNo Game Jam!`, addText: "Has 6000+ downloads and won the Visual Arts Award at the 2020 UCSC Games Showcase.", imageURL: 'https://img.itch.zone/aW1hZ2UvNjA4MTY1LzMyMzgxMTUucG5n/original/e9QPsX.png', altText: 'Cafe in the Clouds Screenshot', built: "RenPy, Clip Studio Paint", links: {"Game Page": "https://cafe-nemo.itch.io/cafe-in-the-clouds", "Github": "https://github.com/tpeng3/bakubaker"}, tag: ["art", "game", "programming", "featured"] }, { id: 1, name: "<NAME>", date: "Fall 2018 - Summer 2019", description: 'Art Director, Co-Producer, and Pixel Artist/Animator in a 12-member team for a slash and skewer adventure game about a robot feeding food to Eldritch Gods. I also designed and coded the public website!', addText: "Won both the Visual Arts and Worldbuilding Award at the 2019 UCSC Games Showcase.", imageURL: 'https://shuttlefrog.weebly.com/uploads/2/8/6/2/28624773/marsh1_orig.png', altText: "Savor Saber Screenshot", built: "Unity, Aseprite", links: {"Website": "https://savorsaber.com/", "Game Page": "https://shuttlefrog.itch.io/savor-saber", "Twitter": "https://twitter.com/SAVORSABER"}, tag: ["art", "game", "web", "programming", "featured"] }, { id: 2, name: 'Typocrypha', date: "Summer 2018 - Present​", description: 'One of the artists for an experimental Typing JRPG Visual Novel about social and cultural alienation. I draw backgrounds, clean up visual novel sprites and design various characters and enemies!', imageURL: 'https://imgur.com/Of0x19l.png', altText: "Savor Saber Screenshot", built: "Unity, Clip Studio Paint", links: {"Website": "https://typocrypha.com/", "Game Page": "https://typocrypha.itch.io/demonstration-i", "Twitter": "https://twitter.com/typocrypha"}, tag: ["art", "game", "featured"] }, { id: 3, name: "Null Metal Detective: Tactical Schedule Management", date: "Spring 2018​", description: "Artist, Programmer and Writer working with two others for a time management visual novel about an incompetent detective. It also doubles as a bullet hell game.", addText: "Featured in the 2018 Sammy Showcase.", built: "Phaser, Javascript", imageURL: 'https://shuttlefrog.weebly.com/uploads/2/8/6/2/28624773/nmd-screencap_orig.png', altText: 'Typocrypha Screenshot', links: {"Game Page": "https://hanmori.itch.io/harold", "Github": "https://github.com/tpeng3/Endless-Runner", "Dev Video": "Available upon request."}, tag: ["programming", "art", "game"] }, { id: 4, name: "Harold, they're Lesbians", date: "Spring 2018​", description: "Solo project. Programmer and Artist for a short endless runner about a phantom thief and police detective.", addText: "Nominated for Sonic '06 Best Runner 2018 (in-class joke award)", imageURL: "https://shuttlefrog.weebly.com/uploads/2/8/6/2/28624773/screenshot1_orig.png", altText: 'Harold Screenshot', built: "Phaser, Javascript", links: {"Game Page": "https://hanmori.itch.io/harold", "Github": "https://github.com/tpeng3/Endless-Runner", "Dev Video": "https://youtu.be/JAerYD-Mx7Y"}, tag: ["art", "game"] }, { id: 5, name: "<NAME>", date: "Fall 2016", description: "Lead Artist, Programmer and Designer collaborating with one other friend for a college kitchen simulator. Based off real-life experiences (aka that one time I accidentally set frozen peas on fire).", addText: "Featured in the 2017 Sammy Showcase", built: "Twine, Renpy", imageURL: 'https://shuttlefrog.weebly.com/uploads/2/8/6/2/28624773/published/mainmenu3.png?1521269196', altText: 'Boneapp Screenshot', links: {"Game Page": "https://appletea.itch.io/boneapp"}, tag: ["game", "art"] }, { id: 6, name: "<NAME>", date: "Fall 2015 - On Hold", description: "Solo personal project. A murder mystery visual novel about what one college student and five other girls face when they wake up trapped in an empty mansion.", addText: "​There's currently an hour of gameplay that has been beta tested.", built: "Renpy, Sai2, Photoshop, Affinity Designer", imageURL: 'https://shuttlefrog.weebly.com/uploads/2/8/6/2/28624773/editor/399139231_1.png', altText: 'ONM Screenshot', links: null, tag: ["game", "art", "programming"] }, { id: 7, name: "<NAME>", date: "Summer 2018 - On Hold​", description: "Programmer and Designer for an escape room game about two witches stuck in a hotel room. Started as a game jam project but there are plans to continue when my two friends and I have more time. Title is tentative!", built: "Renpy", imageURL: 'https://shuttlefrog.weebly.com/uploads/2/8/6/2/28624773/leika_1.png', altText: 'Roomba Screenshot', links: null, tag: ["game", "art", "programming"] }, { id: 8, name: "<NAME>", date: "January 2019", description: "One of the Artists and Animation Programmer for a cozy game about a tiny girl named Thimble trying to fish up her friends (Tetris-styled) after a giant flood.", addText: "An entry for the Global Game Jam where the theme was Home.", built: "Unity, Sai2", imageURL: 'https://shuttlefrog.weebly.com/uploads/2/8/6/2/28624773/e7c65294d05cb19872d0bf85ba390c43_orig.png', altText: 'thelittlethings Screenshot', links: {"Game Page": "https://globalgamejam.org/2019/games/little-things"}, tag: ["game", "art"] }, { id: 9, name: "<NAME>", date: "October 2018", description: "An Artist and Designer for a card game where 4 players (playing as super-villains) work together to make the most evil dinner possible! The goal is to grab and combine ingredient cards to create cursed recipes, scoring Evil Points as a result. But if all else fails, just make some Soup.", built: "the magic of paper and markers", addText: "​An entry for the Garden Game Jam where the theme was Better Together.", imageURL: 'https://shuttlefrog.weebly.com/uploads/2/8/6/2/28624773/chaos_orig.jpg', altText: 'ChaosCooking Screenshot', links: null, tag: ["game", "art"] } ]; export default gameData;<file_sep>import React from "react" import Layout from "../components/layout" import Project from "../components/project" import webData from "../data/webData.js" import {Container} from 'react-bootstrap' import Fade from 'react-reveal/Fade'; export default () => ( <Layout childKey="webdev"> <Container> <Fade> {webData.map(project => <Project info={project} key={project.id} /> ) } </Fade> </Container> </Layout> )<file_sep>import React from "react" import Layout from "../components/layout" import Slideshow from "../components/slideshow" import slideshowData from "../data/slideshowData.js" // import "../styles/art.scss" export default () => ( <Layout childKey="art"> <div id="art"> <div className="slideshow-container"> <Slideshow data={slideshowData} /> </div> </div> </Layout> )<file_sep>import React, {Component} from "react" // import Img from "gatsby-image"; import {Row, Col, Image, Button} from 'react-bootstrap' class Project extends Component { render() { const { name, date, description, built, imageURL, altText} = this.props.info; const addText = this.props.info.addText; const links = this.props.info.links; const linkStyle = { display: "flex", listStyle: "none", marginTop: "2em", marginBottom: "4em", }; const btnStyle = { borderRadius: "10", marginRight: "1.2em", }; return ( <Row> <Col md={6}> <div className="pb-3"> <Image src={imageURL} alt={altText} thumbnail width="600" /> </div> </Col> <Col md={6}> <div className="px-2"> <h2>{name}</h2> <h3>{date}</h3> <p>{description}</p> <p>{addText}</p> <p>Made with: {built}</p> { links ? ( <div style={linkStyle}> { Object.entries(links).map( ([key, value]) => <Button key={key} href={value} style={btnStyle} className="d-flex align-items-center" variant="outline-info">{key}</Button> ) } </div> ) : ( <div></div>) } </div> </Col> </Row> ); } }; export default Project;<file_sep>import React from "react" import Layout from "../components/layout" import Fade from 'react-reveal/Fade'; export default () => ( <Layout childKey={"404"}> <Fade> <div className="text-center py-4"> <h2>Page not found</h2> <h3>Whoops! It looks like this page doesn't exist... yet.</h3> </div> </Fade> </Layout> )<file_sep>import React from "react" import Layout from "../components/layout" import Links from "../components/links" import {Container, Row, Col, Button} from 'react-bootstrap' import Slideshow from "../components/slideshow" import webData from "../data/webData.js" import gameData from "../data/gameData.js" import Fade from 'react-reveal/Fade'; const introStyle = { backgroundColor: "#73DFCB", width: "100%", textAlign: "center" } const btnStyle = { margin: "1em" } const webPrev = webData.slice(0, 3); const gamePrev = gameData.slice(0, 3); export default () => ( <Layout childKey="index"> <Fade> <div style={introStyle}> <Container> <div className="intro-text mx-auto py-5"> <h1><NAME></h1> <h3>Web Developer, Game Designer, Digital Artist</h3> <p>Hello! This is a personal website to showcase my projects and work.</p> <Links color="#fff"></Links> </div> </Container> </div> <Container> <Row className="text-center my-3"> <Col sm={6} className="py-3"> <Button href="/webdev" style={btnStyle} variant="info">Web Dev</Button> <Slideshow data={webPrev} /> </Col> <Col sm={6} className="py-3"> <Button href="/gamedev" style={btnStyle} variant="info">Game Dev</Button> <Slideshow data={gamePrev} /> </Col> </Row> </Container> </Fade> </Layout> )<file_sep>.carousel-indicators { visibility: hidden } .carousel-control-next-icon, .carousel-control-prev-icon { margin: 2em; border-radius: 20%; background-color: #73DFCB; } .carousel img { height: auto; max-width: 100%; }<file_sep>const webData = [ { id: 7, name: "<NAME>", date: "June 2020", description: "I use Twitter a lot to record my thoughts so I made a webtool to grab my data and organize them with tags. It's purely meant for personal scrapbooking purposes.", built: "Gatsby, React, Redux, Bootstrap, GraphQL", imageURL: 'https://imgur.com/a5vu79E.png', altText: "Archiver Screenshot", links: {"Github": "https://github.com/tpeng3/penguinhut"}, tag: ["web", "programming"] }, { id: 1, name: "this website!", date: "Summer 2019", description: "I used to host my portfolio on Weebly, but I decided to rebuild all the components with React as a learning project.", built: "Gatsby, React, Bootstrap", imageURL: 'https://imgur.com/SHPaSDi.png', altText: "Website Screenshot", links: {"Weebly Site": "https://shuttlefrog.weebly.com"}, tag: ["web", "programming"] }, { id: 2, name: "<NAME>", date: "Fall 2018 - Present​", description: 'Art Director, Producer, and Pixel Artist/Animator for a slash and skewer adventure game about a robot feeding food to Eldritch Gods. I also designed and coded the public website!', addText: "Won both the Visual Arts and Worldbuilding Award at the 2019 UCSC Showcase.", imageURL: "https://imgur.com/iXvlb6J.png", altText: "Savor Saber Screenshot", built: "HTML5, Bootstrap", links: {"Website": "https://savorsaber.com/", "Game Page": "https://shuttlefrog.itch.io/savor-saber", "Twitter": "https://twitter.com/SAVORSABER"}, tag: ["art", "game", "web", "programming", "featured"] }, { id: 3, name: 'Okinawa Memory Initiative', date: "Fall 2018​", description: "Front-end Lead Programmer for a website hosting documents and articles related to Okinawan history during American military occupation. This is side website to the Gail Project.", built: "React, Bootstrap, Django, SQLite", imageURL: 'https://shuttlefrog.weebly.com/uploads/2/8/6/2/28624773/fdfdg_3.png', altText: 'OMI Screenshot', links: {"Github": "https://github.com/tpeng3/Okinawa-Initiative", "Gail Project Site": "https://gailproject.ucsc.edu/"}, tag: ["web", "programming"] }, { id: 4, name: "Null Metal Detective: Tactical Schedule Management", date: "Spring 2018​", description: "Artist, Programmer and Writer for a time management visual novel about an incompetent detective. It also doubles as a bullet hell game.", addText: "Featured in the 2018 Sammy Showcase.", built: "Phaser, Javascript", imageURL: 'https://shuttlefrog.weebly.com/uploads/2/8/6/2/28624773/nmd-screencap_orig.png', altText: 'Typocrypha Screenshot', links: {"Game Page": "https://hanmori.itch.io/harold", "Github": "https://github.com/tpeng3/Endless-Runner", "Dev Video": "Available upon request."}, tag: ["programming", "art", "game"] }, { id: 5, name: "Harold, they're Lesbians", date: "Spring 2018​", description: "Solo project. Programmer and Artist for a short endless runner about a phantom thief and police detective.", addText: "Nominated for Sonic '06 Best Runner 2018 (in-class joke award)", imageURL: "https://shuttlefrog.weebly.com/uploads/2/8/6/2/28624773/screenshot1_orig.png", altText: 'Harold Screenshot', built: "Phaser, Javascript", links: {"Game Page": "https://hanmori.itch.io/harold", "Github": "https://github.com/tpeng3/Endless-Runner", "Dev Video": "https://youtu.be/JAerYD-Mx7Y"}, tag: ["art", "game"] }, { id: 6, name: "Rubik's Cube Teacher as AI", date: "Fall 2017", description: "Lead Programmer for an AI program that gives the players tips on how to solve a Rubik's cube, using behavior trees.", built: "HTML5, Javascript", imageURL: 'https://shuttlefrog.weebly.com/uploads/2/8/6/2/28624773/294260296_1_orig.jpg', altText: 'Rubiks Screenshot', links: {"Demo Video": "https://www.youtube.com/watch?v=n9YwXZanT5o", "Github": "https://github.com/mmmayr/cube-destroyers"}, tag: ["programming"] } ]; export default webData;<file_sep>.links-container { margin-top: 1em; margin-bottom: 1.2em; } .react-icons { width: 2.4em; } .react-icons:hover { color: #3c3c3c !important; } <file_sep>import React from "react" import { Link } from "gatsby" import "../styles/global.scss" function Layout (props) { const ListLink = props => ( <li> <Link to={props.to} className="header-links" activeStyle={{ color: '#333' }}> {props.children} </Link> </li> ) return ( <div id="page-container"> <div id="content-wrap"> <div className="title"><img src="https://imgur.com/YzY5UEZ.png" alt="Icon"></img></div> <div className="header-links-container"> <nav> <ul> <ListLink index={0} to="/">HOME</ListLink> <ListLink index={1} to="/about">ABOUT</ListLink> <ListLink index={2} to="/webdev/">WEBDEV</ListLink> <ListLink index={3} to="/gamedev/">GAMEDEV</ListLink> </ul> </nav> </div> <div> {/* <div key={props.childKey? props.childKey : "test"} id={props.childKey}> */} {props.children} </div> </div> <footer id="footer">© 2019 <NAME></footer> </div> ) } export default Layout;
59e1c4ae16175c5817ac69e736a3fb4966dec735
[ "SCSS", "JavaScript" ]
11
SCSS
tpeng3/personal-website
3861f93436cb511b0c206bbc05f76e0b2062bf7b
31ade2ef8bcd145df0a243b53adad887f359db18
refs/heads/master
<repo_name>JamyGolden/eslint-mocha-no-only<file_sep>/lib/rules/mocha-no-only.js /** * @fileoverview Warns or throws an error if a .only function is present on describes, contexts and its * @author <NAME> */ 'use strict'; module.exports = function(context) { return { "Identifier": function(node) { if (node.name == 'only' && node.parent.object) { var parent_name = node.parent.object.name; if(parent_name == 'describe' || parent_name == 'context' || parent_name == 'it') { context.report({ node: node, message: 'Unexpected "only" method called on a mocha test keyword' }); } } } }; }; module.exports.fixable = 'code'; module.exports.schema = [];
ec02cab2360876d79d156b524038d683eeca6d47
[ "JavaScript" ]
1
JavaScript
JamyGolden/eslint-mocha-no-only
3cf75b88c38c8eabfcbd5beec5f680bad99f1003
f09ca57bf0d3a16a091aba19efe734b2e7956130
refs/heads/main
<file_sep># dep-proj foo, test
5f6afc445cfcdd8c875ce7764a58aaa1d28ea0c1
[ "Markdown" ]
1
Markdown
gh-jwhite/dep-proj
86c72320036e76af43bf6c1c536f1c94d42bd907
3003b272aa510885d117394d9faa755b6ea607f0
refs/heads/main
<file_sep># TileThingie Tile based 2d game created with unity. <file_sep>using System; using System.Collections; using UnityEngine; using UnityEngine.SceneManagement; public class WinLevel : MonoBehaviour { [SerializeField] float levelLoadDelay = 2f; [SerializeField] float levelSlowmo = 0.2f; private void OnTriggerEnter2D(Collider2D other) { StartCoroutine(LoadNextLevel()); } IEnumerator LoadNextLevel() { Time.timeScale = levelSlowmo; yield return new WaitForSecondsRealtime(levelLoadDelay); Time.timeScale = 1f; var currSceneIdx = SceneManager.GetActiveScene().buildIndex; SceneManager.LoadScene(currSceneIdx + 1); } } <file_sep>using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class Player : MonoBehaviour { // Config [SerializeField] float runSpeed = 5f; [SerializeField] float jumpSpeed = 10f; [SerializeField] float climbSpeed = 10f; [SerializeField] Vector2 deathKick = new Vector2(-10f, 15f); // State bool isAlive = true; // Caching Rigidbody2D myRigidbody; Animator myAnimator; CapsuleCollider2D myBodyCollider; BoxCollider2D myFeet; float startingGravity; // Messages then methods void Start() { myRigidbody = GetComponent<Rigidbody2D>(); myAnimator = GetComponent<Animator>(); myBodyCollider = GetComponent<CapsuleCollider2D>(); myFeet = GetComponent<BoxCollider2D>(); startingGravity = myRigidbody.gravityScale; } // Update is called once per frame void Update() { if (isAlive) { Run(); Jump(); Climb(); FlipMe(); Die(); } } private void Run() { float controlThrow = Input.GetAxis("Horizontal"); Vector2 playerVelocity = new Vector2(controlThrow * runSpeed, myRigidbody.velocity.y); myRigidbody.velocity = playerVelocity; bool hasHorizontalSpeed = Mathf.Abs(myRigidbody.velocity.x) > Mathf.Epsilon; myAnimator.SetBool("isRunning", hasHorizontalSpeed); } private void Jump() { bool canJump = myFeet.IsTouchingLayers(LayerMask.GetMask("Ground")); if (Input.GetButtonDown("Jump") && canJump) { Vector2 jumpVelocityToAdd = new Vector2(0f, jumpSpeed); myRigidbody.velocity += jumpVelocityToAdd; } } private void Climb() { bool canClimb = myFeet.IsTouchingLayers(LayerMask.GetMask("Ladder")); if (!canClimb) { myRigidbody.gravityScale = startingGravity; myAnimator.SetBool("isClimbing", false); return; } myRigidbody.gravityScale = 0; float controlThrow = Input.GetAxis("Vertical"); Vector2 playerVelocity = new Vector2(myRigidbody.velocity.x, controlThrow * climbSpeed); myRigidbody.velocity = playerVelocity; bool hasVerticalSpeed = Mathf.Abs(myRigidbody.velocity.y) > Mathf.Epsilon; myAnimator.SetBool("isClimbing", hasVerticalSpeed); } private void FlipMe() { bool hasHorizontalSpeed = Mathf.Abs(myRigidbody.velocity.x) > Mathf.Epsilon; if (hasHorizontalSpeed) { transform.localScale = new Vector2(Mathf.Sign(myRigidbody.velocity.x), 1f); } } private void Die() { if (myBodyCollider.IsTouchingLayers(LayerMask.GetMask("Enemy", "Hazzards"))) { myAnimator.SetTrigger("Die"); isAlive = false; myRigidbody.velocity = deathKick; FindObjectOfType<GameSession>().ProcessPlayerDeath(); } } }
1cb9e48b204857c28af21ec2426e7270e44477b8
[ "C#", "Markdown" ]
3
C#
igor-trbic/TileThingie
2c1df96eaf62d2dd981aff6a8ad7b30bbe0534de
379af2ea40987dbb30e3cff9f93bc920799be43a
refs/heads/master
<file_sep>from flask import Flask, request, jsonify import search_word app = Flask(__name__) from flask_cors import CORS, cross_origin CORS(app) @app.route('/search/<word>') def search(word): definition_list = search_word.getDefinition(word) definition = '' for defi in definition_list: definition += ',' + defi if len(definition) != 0: definition = definition[1:] return jsonify({'definition': definition}) if __name__ == "__main__": app.run(port=5050) <file_sep>from urllib.request import urlopen from bs4 import BeautifulSoup def getHtml(url): html = urlopen(url) bsObject = BeautifulSoup(html, 'html.parser') return bsObject def getDefinition(word): url = 'https://dic.daum.net/search.do?q=' + word + '&dic=eng' # url = 'https://dic.daum.net/search.do?q=test&dic=eng' # url = 'https://dic.daum.net/search.do?q=hello&dic=eng' html = getHtml(url) temp = html.find_all(class_='list_search') definition_list = [] if temp: temp = temp[0].find_all(class_='txt_search') for key_tag in temp: definition_list.append(key_tag.text) else: meta = html.head.find_all('meta') url = 'https://dic.daum.net' + meta[3].get('content').split('URL=')[1] html = getHtml(url) temp = html.find_all(class_='list_mean')[0].find_all(class_='txt_mean') for key_tag in temp: definition_list.append(key_tag.text) return definition_list # if __name__ == '__main__': # definition_list = getDefinition('ambiguous') # print(definition_list)
f3704306469420cee37d8943dc23d4c56145cf74
[ "Python" ]
2
Python
Junwon6/dictionary_api_server
1a3f8f5bf31683df6f5a6ae31c61531698992083
a4e840c58f2b0228610bc435a01a921f5f1159e6
refs/heads/master
<file_sep><?php echo "Welcome to PHP World!" ?>
acd4ed2f992308690e908412830691620b9d7e5e
[ "PHP" ]
1
PHP
ETACloudOS/web-php-simple
a592be0c2ebfe302173b7dc78bacc6cc4efe44d8
414e27a5babb9a21d997d2da9317321810bea410
refs/heads/master
<repo_name>limitlis/scribble<file_sep>/README.md #scribble Turn a canvas element into a scribble pad that supports bouth mouse and touch. ##Installation ###Bower `bower install scribble` ###Manual Download - [Development]() - [Production]() ##Usage In order to initialize the module, you'll need to target either a `canvas` or a `div`. The module will wrap the `canvas` with a `div` or create a `canvas` inside the supplied `div`. Finally, you need to just call `scribble` on top of the jQuery element: $('#myAwesomeCanvas').scribble(); And that's it! Well, I lied a little. You have some methods and options available! ### Available options | Option | Explanation | Default | | ----------------- |:---------------------------------------:|:-----------:| | `color` | Color in which you'll draw | `#000000` | | `size` | Size of the stroke | `2` | | `readMode` | Sets whether the canvas is in read mode | `false` | | `tool` | Selected tool at beginning | `pencil` | | `stopDrawingTime` | Time to debounce stop drawing | `500` | | `cssClasses` | Object that holds css classes to style | *See below* | `cssClasses` have this configurable properties: * `canvas-holder` : Class for the `div` that wraps the canvas. (*Default*: `scribble-canvas-holder`) * `main-canvas` : Class for the main `canvas`. (*Default*: `scribble-main-canvas`) * `shadow-canvas` : Class for the auxiliar canvas used. (*Default*: `scribble-main-canvas`) **Note**: Aside from `cssClases`, all the options can be change with methods after initialization. ### Available methods Several methods are exposed through Fidel for you to use that allows you to do fancy things. #### `changeColor(color)` With this method you can… change the stroke color. What did you expect? There is no validation performed on plugin side so you should be sure you're passing a good value. #### `changeSize(size)` Changes the size of the stroke. Size has to be an integer. #### `changeReadMode(mode)` Changes the read mode to whatever value you pass. If you pass `true`, you'll enable read mode and `false` will disable it. #### `undo` This method will undo the latest drawing. #### `redo` This method will redo the latest undone action. #### `clear` This method will clear the drawing canvas. #### `changeTool(tool)` This method allows you to change "drawing" tool. Currently there are only two possible values. Plugin will yell if you pass something which is not implemented. * `pencil` : This is the default value and is what you expect. * `eraser` : This is what you expect too… It will erase as you draw. ### Fired events #### `drawing.changed` Whenever the user finished drawing, this event will fire. It's *debounced* so it won't fire until the time defined on the option `stopDrawingTime` passess without any more alike events. #### Export methods There are 2 exports methods with their counterpart that will import as well: * `toJSON` : It returns an object literall with all the points. * `loadJSON` : It loads that object and draws everything back. * `toDataURL` : Converts the canvas to base64 string * `loadDataUrl` : Loads the canvas from a base64 string ##Development ###Requirements - node and npm - bower `npm install -g bower` - grunt `npm install -g grunt-cli` ###Setup - `npm install` - `bower install` ###Run `grunt dev` or for just running tests on file changes: `grunt ci` ###Tests `grunt mocha` <file_sep>/HISTORY.md 0.3.0 / 2014-05-30 ================== * Adding retina canvas support * New fullSteps feature that reduces the size of the points saved. Great if you are not changing tools, size and color on your scribble. * The loadDataURL method now uses asynchronous loading of the image which solves an issue of images not loading on some browsers 0.2.0 / 2014-04-02 ================== * Removing console from test * Updating mocks to reflect new behaviour * Taking offset into account on touch devices and avoiding saving too many points * Updating jQuery to point to the new location 0.1.0 / 2013-09-21 ================== * Fixes #5 0.0.1 / 2013-09-09 ================== * Fixes #4 * Improve test coverage & fixes * Fix #3 * Fixes #2 * Adding Readme and some tests * First commit * project setup <file_sep>/dist/fidel.scribble.js /*! * scribble - Turn a canvas element into a scribble pad * v0.3.0 * https://github.com/firstandthird/scribble * copyright First + Third 2016 * MIT License */ (function($){ function capitalize (string) { return string.charAt(0).toUpperCase() + string.slice(1); } $.declare('scribble',{ defaults : { color : '#000000', size : 2, readMode : false, stopDrawingTime : 500, fullSteps : true, tool : 'pencil', cssClasses : { 'canvas-holder' : 'scribble-canvas-holder', 'main-canvas' : 'scribble-main-canvas', 'shadow-canvas' : 'scribble-shadow-canvas' } }, tools : [ 'pencil','eraser' ], _isCanvas : function () { var htmlNode = this.el[0], result = true; if (htmlNode.nodeType !== 1 || htmlNode.nodeName.toLowerCase() !== 'canvas'){ result = false; } return result; }, _createCanvas : function(){ var canvas = $('<canvas>'); canvas.appendTo(this.el); this.canvasHolder = this.el; this.el = canvas; }, _getId : function() { var i = 0,id = null, auxID; while (id === null) { auxID = 'fidel_scribble_' + i; if ($('#' + auxID).length === 0){ id = auxID; } else { i++; } } return id; }, _createWrapper : function(){ var div = $('<div>'); div.insertBefore(this.el); this.el.appendTo(div); this.canvasHolder = div; }, _applyClasses : function(){ this.canvasHolder.addClass(this.cssClasses['canvas-holder']); this.el.addClass(this.cssClasses['main-canvas']); this.shadowCanvas.addClass(this.cssClasses['shadow-canvas']); var computedStyle = getComputedStyle(this.canvasHolder[0]); this.el[0].width = parseInt(computedStyle.width,10); this.el[0].height = parseInt(computedStyle.height,10); this.shadowCanvas[0].width = parseInt(computedStyle.width,10); this.shadowCanvas[0].height = parseInt(computedStyle.height,10); }, _getContexts : function(){ this.shadowContext = this.shadowCanvas[0].getContext('2d'); this.context = this.el[0].getContext('2d'); }, _createShadowCanvas : function(){ this.shadowCanvas = $('<canvas>'); this.shadowCanvas[0].id = this._getId(); this.shadowCanvas.insertAfter(this.el); }, _bindEvents: function () { this.shadowCanvas.on('mousemove touchmove', this.proxy(this._saveMouse,this)); this.shadowCanvas.on('mousedown touchstart', this.proxy(this._startDrawing,this)); this.shadowCanvas.on('mouseup touchend', this.proxy(this._stopDrawing,this)); $('body').on('mouseup touchend', this.proxy(this._stopDrawing,this)); }, _unbindEvents : function(){ this.shadowCanvas.off('mousemove touchmove', this.proxy(this._saveMouse,this)); this.shadowCanvas.off('mousedown touchstart', this.proxy(this._startDrawing,this)); this.shadowCanvas.off('mouseup touchend', this.proxy(this._stopDrawing,this)); $('body').off('mouseup', this.proxy(this._stopDrawing,this)); }, _startDrawing : function(e){ e.stopPropagation(); e.preventDefault(); if(e.handled !== true) { this.shadowCanvas.on('mousemove touchmove', this.proxy(this._draw, this)); this.drawing = true; this._saveMouse(e); this._draw(); e.handled = true; } else { return false; } }, _savePoint : function(){ var point = { x : this.mousePosition.x, y : this.mousePosition.y }; if (this.fullSteps){ point.size = this.size; point.color = this.color; point.tool = this.tool; } this.points.push(point); }, _saveMouse : function(e){ if (e.type === 'touchmove'){ e.preventDefault(); } var position = this._getXY(e); this.mousePosition.x = position.x; this.mousePosition.y = position.y; if (this.drawing){ this._savePoint(); } }, _saveStep : function(){ var aux = { points: this.points.splice(0) }; this.doneSteps.push(aux); }, _stopDrawing : function(e){ if (this.drawing){ e.stopImmediatePropagation(); this.shadowCanvas.off('mousemove touchmove', this.proxy(this._draw,this)); this._copyShadowToReal(); this.drawing = false; this._emitDrawingChanged(); } }, _emitDrawingChanged : function(){ if (this.stopTimer){ clearTimeout(this.stopTimer); } var self = this; this.stopTimer = setTimeout(function(){ self.emit('drawing.changed'); }, this.stopDrawingTime); }, _copyShadowToReal : function(){ this.context.drawImage(this.shadowCanvas[0],0,0); this._clearCanvas(this.shadowCanvas,this.shadowContext); if (this.drawing){ this._saveStep(); } this.points = []; }, _getXY : function(e){ var x, y, touchEvent = { pageX : 0, pageY : 0}; if (typeof e.changedTouches !== 'undefined'){ touchEvent = e.changedTouches[0]; } else if ( typeof e.originalEvent !== 'undefined' && typeof e.originalEvent.changedTouches !== 'undefined'){ touchEvent = e.originalEvent.changedTouches[0]; } x = e.offsetX || e.layerX || touchEvent.pageX; y = e.offsetY || e.layerY || touchEvent.pageY; if (e.type.indexOf('touch') !== -1){ var offset = this.shadowCanvas.offset(); x -= offset.left; y -= offset.top; } return { x : x, y : y }; }, _draw : function(){ var length = this.points.length, aux = this.points[0], erasing = aux.tool === 'eraser', context = erasing ? this.context : this.shadowContext, previousTool = '', revertTool = false; if (this.tool !== aux.tool && typeof aux.tool != "undefined"){ revertTool = true; previousTool = this.tool; this.changeTool(aux.tool); } context.lineWidth = aux.size || this.size; context.strokeStyle = aux.color || this.color; context.fillStyle = aux.color || this.color; if (length !== 0){ if (length < 3){ context.beginPath(); context.arc(aux.x,aux.y, context.lineWidth / 2, 0, Math.PI * 2, true); context.fill(); context.closePath(); } else { if (!erasing){ this._clearCanvas(this.shadowCanvas,this.shadowContext); } context.beginPath(); context.moveTo(this.points[0].x,this.points[0].y); for (var i = 1; i < length -2; i++){ var x = (this.points[i].x + this.points[i+1].x) / 2, y = (this.points[i].y + this.points[i+1].y) / 2; context.quadraticCurveTo(this.points[i].x,this.points[i].y,x,y); } context.quadraticCurveTo(this.points[i].x,this.points[i].y,this.points[i+1].x,this.points[i+1].y); context.stroke(); } } // Only used in undo / redo return { 'toolUsed' : aux.tool, 'previousTool' : previousTool, 'revertTool' : revertTool }; }, _drawFromSteps : function(actions){ if (actions){ this.clear(true); for (var i = 0, len = actions.length; i < len; i++) { if (actions[i].points) { this.points = actions[i].points; var result = this._draw(); if (result.toolUsed !== 'eraser'){ this._copyShadowToReal(); } if (result.revertTool){ this.changeTool(result.previousTool); } } else if (actions[i].rects) { for (var r = 0; r < actions[i].rects.length; r++) { // should this be extracted to lower level function this.context.drawImage(actions[i].rects[r].image, actions[i].rects[r].x, actions[i].rects[r].y, actions[i].rects[r].width, actions[i].rects[r].height); } } } } }, init : function(){ if (!this._isCanvas()){ this._createCanvas(); } else { this._createWrapper(); } this._createShadowCanvas(); this._applyClasses(); this._getContexts(); this.shadowContext.lineJoin = 'round'; this.body = $('body'); this.mousePosition = { x : 0, y : 0 }; this.points = []; this.drawing = false; this.unDoneSteps = []; this.doneSteps = []; this.clear(true); if (!this.readMode){ this._bindEvents(); } this.oldColor = this.color; this.changeTool(this.tool); }, changeColor: function(color){ this.color = color; this.shadowContext.strokeStyle = this.color; }, changeSize : function(size){ this.size = size; this.shadowContext.lineWidth = this.size; }, changeReadMode : function(mode){ if (mode){ this._bindEvents(); } else { this._unbindEvents(); } this.readMode = mode; }, toJSON : function(){ return this.doneSteps; }, loadJSON : function(obj){ this._drawFromSteps(obj); this.doneSteps = obj; }, toDataURL : function(){ return this.el[0].toDataURL(); }, loadDataURL : function(dataurl){ var image = new Image(), context = this.context, canvasEl = this.el, self = this; image.onload = function() { context.drawImage(this, 0, 0, parseInt(canvasEl.attr('width'), 10), parseInt(canvasEl.attr('height'), 10)); self.doneSteps.push({ rects: [ { x: 0, y: 0, width: parseInt(canvasEl.attr('width'), 10), height: parseInt(canvasEl.attr('height'), 10), image: this, url: dataurl.toString(), tool: 'stamp' } ] }); self._emitDrawingChanged(); }; image.src = dataurl.toString(); }, undo : function(){ if (this.doneSteps.length){ var lastStep = this.doneSteps.pop(); this.unDoneSteps.push(lastStep); this._drawFromSteps(this.doneSteps); this._emitDrawingChanged(); } }, redo : function(){ if (this.unDoneSteps.length){ var lastUndone = this.unDoneSteps.pop(); this.doneSteps.push(lastUndone); this._drawFromSteps(this.doneSteps); this._emitDrawingChanged(); } }, _setPencil : function(){ this.context.globalCompositeOperation = 'source-over'; this.color = this.oldColor; }, _setEraser : function(){ this.context.globalCompositeOperation = 'destination-out'; this.oldColor = this.color; this.color = 'rgba(0,0,0,1)'; }, changeTool : function(tool){ if (this.tools.indexOf(tool) !== -1){ var method = '_set' + capitalize(tool); this[method].call(this); this.tool = tool; } else { console.error(tool + ' is not implemented'); } }, _clearCanvas : function(canvas, context){ context.clearRect(0,0,canvas[0].width,canvas[0].height); }, clear : function(intern){ intern = intern || false; this._clearCanvas(this.el,this.context); if (!intern){ this.emit('clear'); this.doneSteps = []; } } }); })(jQuery); <file_sep>/test/scribble.test.js function cleanMess(){ $('#fixture').empty().html('<canvas id="testCanvas"></canvas><div id="testDiv"></div>'); } function startDrawing(fidel,x,y){ var down = $.Event('mousedown'); down.layerX = x; down.layerY = y; movePoint(fidel,x,y); fidel.shadowCanvas.trigger(down); } function stopDrawing(fidel){ var up = $.Event('mouseup'); fidel.shadowCanvas.trigger(up); } function drawLine1(fidel){ startDrawing(fidel,0,0); for (var i = 1; i < 5; i++){ movePoint(fidel,i,i); } stopDrawing(fidel); return fidel.toJSON(); } function movePoint(fidel,x,y){ var move = $.Event('mousemove'); move.layerX = x; move.layerY = y; fidel.shadowCanvas.trigger(move); } suite('scribble', function() { var canvas, div, canvasFidel, scribble; var line1Mock = [{"points":[{"x":0,"y":0,"size":2,"color":"#000000","tool":"pencil"},{"x":1,"y":1,"size":2,"color":"#000000","tool":"pencil"},{"x":2,"y":2,"size":2,"color":"#000000","tool":"pencil"},{"x":3,"y":3,"size":2,"color":"#000000","tool":"pencil"},{"x":4,"y":4,"size":2,"color":"#000000","tool":"pencil"}]}]; setup(function(){ cleanMess(); canvas = $('#testCanvas'); div = $('#testDiv'); canvas.scribble(); canvasFidel = canvas.data('scribble'); div.scribble(); }); suite('init',function(){ test('scribble should exists in jQuery\'s namespace', function(){ assert.equal(typeof $().scribble, 'function'); }); suite('structure creating',function(){ suite('canvas attributes',function(){ test('main canvas should have id attribute',function(){ assert.notEqual(div.find('canvas').first().attr('id'),''); }); test('last canvas should have id attribute',function(){ assert.notEqual(div.find('canvas').last().attr('id'),''); }); test('main canvas should have width attribute',function(){ assert.notEqual(div.find('canvas').first().attr('width'),''); }); test('last canvas should have width attribute',function(){ assert.notEqual(div.find('canvas').last().attr('width'),''); }); test('main canvas should have height attribute',function(){ assert.notEqual(div.find('canvas').first().attr('height'),''); }); test('last canvas should have height attribute',function(){ assert.notEqual(div.find('canvas').last().attr('height'),''); }); }); suite('canvas target',function(){ test('scribble should create a wrapper div', function(){ assert.ok(canvas.parent().hasClass(canvasFidel.cssClasses['canvas-holder'])); }); test('scribble should create a shadow canvas next to the target one', function(){ assert.ok(canvas.next().hasClass(canvasFidel.cssClasses['shadow-canvas'])); }); test('scribble should assign the correct class to the canvas',function(){ assert.ok(canvas.hasClass(canvasFidel.cssClasses['main-canvas'])); }); }); suite('div target',function(){ test('scribble should two canvas inside', function(){ assert.equal(div.find('canvas').length,2); }); test('scribble should add class to div', function(){ assert.ok(div.hasClass(canvasFidel.cssClasses['canvas-holder'])); }); test('scribble should create a shadow canvas next to the target one', function(){ assert.equal(div.find('canvas.' +canvasFidel.cssClasses['shadow-canvas']).length,1); }); test('scribble should assign the correct class to the canvas',function(){ assert.equal(div.find('canvas.' +canvasFidel.cssClasses['main-canvas']).length,1); }); }); }); }); suite('feature',function(){ setup(function(){ cleanMess(); canvas = $('#testCanvas'); div = $('#testDiv'); canvas.scribble(); canvasFidel = canvas.data('scribble'); div.scribble(); }); suite('drawing',function(){ setup(function(){ cleanMess(); canvas = $('#testCanvas'); scribble = canvas.scribble(); canvasFidel = canvas.data('scribble'); drawLine1(canvasFidel); }); test('scribble should draw a line when user tries to',function(){ assert.deepEqual(canvasFidel.toJSON(),line1Mock); }); test('scribble should undo the drawing when calling undo',function(){ canvasFidel.undo(); assert.deepEqual(canvasFidel.toJSON(),[]); }); test('scribble should redo the drawing when calling redo',function(){ canvasFidel.undo(); canvasFidel.redo(); assert.deepEqual(canvasFidel.toJSON(),line1Mock); }); test('scribble should empty the canvas on clear',function(){ canvasFidel.clear(); assert.deepEqual(canvasFidel.toJSON(),[]); }); test('scribble should fire an event when line was drawn', function(done){ scribble.on('drawing.changed',function(){ done(); }); }); test('scribble should save simpler points if fullSteps is false', function () { cleanMess(); canvas = $('#testCanvas'); scribble = canvas.scribble({ fullSteps : false }); canvasFidel = canvas.data('scribble'); drawLine1(canvasFidel); var firstPoint = canvasFidel.toJSON()[0].points[0]; assert.ok(typeof firstPoint.color === "undefined"); assert.ok(typeof firstPoint.size === "undefined"); assert.ok(typeof firstPoint.tool === "undefined"); assert.ok(typeof firstPoint.x !== "undefined"); assert.ok(typeof firstPoint.y !== "undefined"); }); }); suite('exporting',function(){ setup(function(){ cleanMess(); canvas = $('#testCanvas'); canvas.scribble(); canvasFidel = canvas.data('scribble'); drawLine1(canvasFidel); }); test('scribble should export drawing to JSON',function(){ assert.deepEqual(canvasFidel.toJSON(),line1Mock); }); test('scribble should export drawing to base64',function(){ assert.ok(canvasFidel.toDataURL().indexOf('data:image/png;base64') !== -1); }); }); suite('importing',function(){ setup(function(){ cleanMess(); canvas = $('#testCanvas'); canvas.scribble(); canvasFidel = canvas.data('scribble'); }); test('scribble should import drawing from JSON',function(){ canvasFidel.loadJSON(line1Mock); assert.deepEqual(canvasFidel.toJSON(),line1Mock); }); }); }); }); <file_sep>/dist/scribble.js /*! * scribble - Turn a canvas element into a scribble pad * v0.3.0 * https://github.com/firstandthird/scribble * copyright First + Third 2016 * MIT License */ /*! * fidel - a ui view controller * v2.2.5 * https://github.com/jgallen23/fidel * copyright <NAME> 2014 * MIT License */ (function(w, $) { var _id = 0; var Fidel = function(obj) { this.obj = obj; }; Fidel.prototype.__init = function(options) { $.extend(this, this.obj); this.id = _id++; this.namespace = '.fidel' + this.id; this.obj.defaults = this.obj.defaults || {}; $.extend(this, this.obj.defaults, options); $('body').trigger('FidelPreInit', this); this.setElement(this.el || $('<div/>')); if (this.init) { this.init(); } $('body').trigger('FidelPostInit', this); }; Fidel.prototype.eventSplitter = /^(\w+)\s*(.*)$/; Fidel.prototype.setElement = function(el) { this.el = el; this.getElements(); this.dataElements(); this.delegateEvents(); this.delegateActions(); }; Fidel.prototype.find = function(selector) { return this.el.find(selector); }; Fidel.prototype.proxy = function(func) { return $.proxy(func, this); }; Fidel.prototype.getElements = function() { if (!this.elements) return; for (var selector in this.elements) { var elemName = this.elements[selector]; this[elemName] = this.find(selector); } }; Fidel.prototype.dataElements = function() { var self = this; this.find('[data-element]').each(function(index, item) { var el = $(item); var name = el.data('element'); self[name] = el; }); }; Fidel.prototype.delegateEvents = function() { if (!this.events) return; for (var key in this.events) { var methodName = this.events[key]; var match = key.match(this.eventSplitter); var eventName = match[1], selector = match[2]; var method = this.proxy(this[methodName]); if (selector === '') { this.el.on(eventName + this.namespace, method); } else { if (this[selector] && typeof this[selector] != 'function') { this[selector].on(eventName + this.namespace, method); } else { this.el.on(eventName + this.namespace, selector, method); } } } }; Fidel.prototype.delegateActions = function() { var self = this; self.el.on('click'+this.namespace, '[data-action]', function(e) { var el = $(this); var action = el.attr('data-action'); if (self[action]) { self[action](e, el); } }); }; Fidel.prototype.on = function(eventName, cb) { this.el.on(eventName+this.namespace, cb); }; Fidel.prototype.one = function(eventName, cb) { this.el.one(eventName+this.namespace, cb); }; Fidel.prototype.emit = function(eventName, data, namespaced) { var ns = (namespaced) ? this.namespace : ''; this.el.trigger(eventName+ns, data); }; Fidel.prototype.hide = function() { if (this.views) { for (var key in this.views) { this.views[key].hide(); } } this.el.hide(); }; Fidel.prototype.show = function() { if (this.views) { for (var key in this.views) { this.views[key].show(); } } this.el.show(); }; Fidel.prototype.destroy = function() { this.el.empty(); this.emit('destroy'); this.el.unbind(this.namespace); }; Fidel.declare = function(obj) { var FidelModule = function(el, options) { this.__init(el, options); }; FidelModule.prototype = new Fidel(obj); return FidelModule; }; //for plugins Fidel.onPreInit = function(fn) { $('body').on('FidelPreInit', function(e, obj) { fn.call(obj); }); }; Fidel.onPostInit = function(fn) { $('body').on('FidelPostInit', function(e, obj) { fn.call(obj); }); }; w.Fidel = Fidel; })(window, window.jQuery || window.Zepto); (function($) { $.declare = function(name, obj) { $.fn[name] = function() { var args = Array.prototype.slice.call(arguments); var options = args.shift(); var methodValue; var els; els = this.each(function() { var $this = $(this); var data = $this.data(name); if (!data) { var View = Fidel.declare(obj); var opts = $.extend({}, options, { el: $this }); data = new View(opts); $this.data(name, data); } if (typeof options === 'string') { methodValue = data[options].apply(data, args); } }); return (typeof methodValue !== 'undefined') ? methodValue : els; }; $.fn[name].defaults = obj.defaults || {}; }; $.Fidel = window.Fidel; })(jQuery); /** * HiDPI Canvas Polyfill (1.0.10) * * Author: <NAME> (http://jondavidjohn.com) * Homepage: https://github.com/jondavidjohn/hidpi-canvas-polyfill * Issue Tracker: https://github.com/jondavidjohn/hidpi-canvas-polyfill/issues * License: Apache-2.0 */ (function(prototype) { var pixelRatio = (function() { var canvas = document.createElement('canvas'), context = canvas.getContext('2d'), backingStore = context.backingStorePixelRatio || context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1; return (window.devicePixelRatio || 1) / backingStore; })(), forEach = function(obj, func) { for (var p in obj) { if (obj.hasOwnProperty(p)) { func(obj[p], p); } } }, ratioArgs = { 'fillRect': 'all', 'clearRect': 'all', 'strokeRect': 'all', 'moveTo': 'all', 'lineTo': 'all', 'arc': [0,1,2], 'arcTo': 'all', 'bezierCurveTo': 'all', 'isPointinPath': 'all', 'isPointinStroke': 'all', 'quadraticCurveTo': 'all', 'rect': 'all', 'translate': 'all', 'createRadialGradient': 'all', 'createLinearGradient': 'all' }; if (pixelRatio === 1) return; forEach(ratioArgs, function(value, key) { prototype[key] = (function(_super) { return function() { var i, len, args = Array.prototype.slice.call(arguments); if (value === 'all') { args = args.map(function(a) { return a * pixelRatio; }); } else if (Array.isArray(value)) { for (i = 0, len = value.length; i < len; i++) { args[value[i]] *= pixelRatio; } } return _super.apply(this, args); }; })(prototype[key]); }); // Stroke lineWidth adjustment prototype.stroke = (function(_super) { return function() { this.lineWidth *= pixelRatio; _super.apply(this, arguments); this.lineWidth /= pixelRatio; }; })(prototype.stroke); // Text // prototype.fillText = (function(_super) { return function() { var args = Array.prototype.slice.call(arguments); args[1] *= pixelRatio; // x args[2] *= pixelRatio; // y this.font = this.font.replace( /(\d+)(px|em|rem|pt)/g, function(w, m, u) { return (m * pixelRatio) + u; } ); _super.apply(this, args); this.font = this.font.replace( /(\d+)(px|em|rem|pt)/g, function(w, m, u) { return (m / pixelRatio) + u; } ); }; })(prototype.fillText); prototype.strokeText = (function(_super) { return function() { var args = Array.prototype.slice.call(arguments); args[1] *= pixelRatio; // x args[2] *= pixelRatio; // y this.font = this.font.replace( /(\d+)(px|em|rem|pt)/g, function(w, m, u) { return (m * pixelRatio) + u; } ); _super.apply(this, args); this.font = this.font.replace( /(\d+)(px|em|rem|pt)/g, function(w, m, u) { return (m / pixelRatio) + u; } ); }; })(prototype.strokeText); })(CanvasRenderingContext2D.prototype); ;(function(prototype) { prototype.getContext = (function(_super) { return function(type) { var backingStore, ratio, context = _super.call(this, type); if (type === '2d') { backingStore = context.backingStorePixelRatio || context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1; ratio = (window.devicePixelRatio || 1) / backingStore; if (ratio > 1) { this.style.height = this.height + 'px'; this.style.width = this.width + 'px'; this.width *= ratio; this.height *= ratio; } } return context; }; })(prototype.getContext); })(HTMLCanvasElement.prototype); /** * HiDPI Canvas Polyfill (1.0.10) * * Author: <NAME> (http://jondavidjohn.com) * Homepage: https://github.com/jondavidjohn/hidpi-canvas-polyfill * Issue Tracker: https://github.com/jondavidjohn/hidpi-canvas-polyfill/issues * License: Apache-2.0 */ (function(prototype) { var pixelRatio = (function() { var canvas = document.createElement('canvas'), context = canvas.getContext('2d'), backingStore = context.backingStorePixelRatio || context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1; return (window.devicePixelRatio || 1) / backingStore; })(), forEach = function(obj, func) { for (var p in obj) { if (obj.hasOwnProperty(p)) { func(obj[p], p); } } }, ratioArgs = { 'fillRect': 'all', 'clearRect': 'all', 'strokeRect': 'all', 'moveTo': 'all', 'lineTo': 'all', 'arc': [0,1,2], 'arcTo': 'all', 'bezierCurveTo': 'all', 'isPointinPath': 'all', 'isPointinStroke': 'all', 'quadraticCurveTo': 'all', 'rect': 'all', 'translate': 'all', 'createRadialGradient': 'all', 'createLinearGradient': 'all' }; if (pixelRatio === 1) return; forEach(ratioArgs, function(value, key) { prototype[key] = (function(_super) { return function() { var i, len, args = Array.prototype.slice.call(arguments); if (value === 'all') { args = args.map(function(a) { return a * pixelRatio; }); } else if (Array.isArray(value)) { for (i = 0, len = value.length; i < len; i++) { args[value[i]] *= pixelRatio; } } return _super.apply(this, args); }; })(prototype[key]); }); // Stroke lineWidth adjustment prototype.stroke = (function(_super) { return function() { this.lineWidth *= pixelRatio; _super.apply(this, arguments); this.lineWidth /= pixelRatio; }; })(prototype.stroke); // Text // prototype.fillText = (function(_super) { return function() { var args = Array.prototype.slice.call(arguments); args[1] *= pixelRatio; // x args[2] *= pixelRatio; // y this.font = this.font.replace( /(\d+)(px|em|rem|pt)/g, function(w, m, u) { return (m * pixelRatio) + u; } ); _super.apply(this, args); this.font = this.font.replace( /(\d+)(px|em|rem|pt)/g, function(w, m, u) { return (m / pixelRatio) + u; } ); }; })(prototype.fillText); prototype.strokeText = (function(_super) { return function() { var args = Array.prototype.slice.call(arguments); args[1] *= pixelRatio; // x args[2] *= pixelRatio; // y this.font = this.font.replace( /(\d+)(px|em|rem|pt)/g, function(w, m, u) { return (m * pixelRatio) + u; } ); _super.apply(this, args); this.font = this.font.replace( /(\d+)(px|em|rem|pt)/g, function(w, m, u) { return (m / pixelRatio) + u; } ); }; })(prototype.strokeText); })(CanvasRenderingContext2D.prototype); ;(function(prototype) { prototype.getContext = (function(_super) { return function(type) { var backingStore, ratio, context = _super.call(this, type); if (type === '2d') { backingStore = context.backingStorePixelRatio || context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1; ratio = (window.devicePixelRatio || 1) / backingStore; if (ratio > 1) { this.style.height = this.height + 'px'; this.style.width = this.width + 'px'; this.width *= ratio; this.height *= ratio; } } return context; }; })(prototype.getContext); })(HTMLCanvasElement.prototype); (function($){ function capitalize (string) { return string.charAt(0).toUpperCase() + string.slice(1); } $.declare('scribble',{ defaults : { color : '#000000', size : 2, readMode : false, stopDrawingTime : 500, fullSteps : true, tool : 'pencil', cssClasses : { 'canvas-holder' : 'scribble-canvas-holder', 'main-canvas' : 'scribble-main-canvas', 'shadow-canvas' : 'scribble-shadow-canvas' } }, tools : [ 'pencil','eraser' ], _isCanvas : function () { var htmlNode = this.el[0], result = true; if (htmlNode.nodeType !== 1 || htmlNode.nodeName.toLowerCase() !== 'canvas'){ result = false; } return result; }, _createCanvas : function(){ var canvas = $('<canvas>'); canvas.appendTo(this.el); this.canvasHolder = this.el; this.el = canvas; }, _getId : function() { var i = 0,id = null, auxID; while (id === null) { auxID = 'fidel_scribble_' + i; if ($('#' + auxID).length === 0){ id = auxID; } else { i++; } } return id; }, _createWrapper : function(){ var div = $('<div>'); div.insertBefore(this.el); this.el.appendTo(div); this.canvasHolder = div; }, _applyClasses : function(){ this.canvasHolder.addClass(this.cssClasses['canvas-holder']); this.el.addClass(this.cssClasses['main-canvas']); this.shadowCanvas.addClass(this.cssClasses['shadow-canvas']); var computedStyle = getComputedStyle(this.canvasHolder[0]); this.el[0].width = parseInt(computedStyle.width,10); this.el[0].height = parseInt(computedStyle.height,10); this.shadowCanvas[0].width = parseInt(computedStyle.width,10); this.shadowCanvas[0].height = parseInt(computedStyle.height,10); }, _getContexts : function(){ this.shadowContext = this.shadowCanvas[0].getContext('2d'); this.context = this.el[0].getContext('2d'); }, _createShadowCanvas : function(){ this.shadowCanvas = $('<canvas>'); this.shadowCanvas[0].id = this._getId(); this.shadowCanvas.insertAfter(this.el); }, _bindEvents: function () { this.shadowCanvas.on('mousemove touchmove', this.proxy(this._saveMouse,this)); this.shadowCanvas.on('mousedown touchstart', this.proxy(this._startDrawing,this)); this.shadowCanvas.on('mouseup touchend', this.proxy(this._stopDrawing,this)); $('body').on('mouseup touchend', this.proxy(this._stopDrawing,this)); }, _unbindEvents : function(){ this.shadowCanvas.off('mousemove touchmove', this.proxy(this._saveMouse,this)); this.shadowCanvas.off('mousedown touchstart', this.proxy(this._startDrawing,this)); this.shadowCanvas.off('mouseup touchend', this.proxy(this._stopDrawing,this)); $('body').off('mouseup', this.proxy(this._stopDrawing,this)); }, _startDrawing : function(e){ e.stopPropagation(); e.preventDefault(); if(e.handled !== true) { this.shadowCanvas.on('mousemove touchmove', this.proxy(this._draw, this)); this.drawing = true; this._saveMouse(e); this._draw(); e.handled = true; } else { return false; } }, _savePoint : function(){ var point = { x : this.mousePosition.x, y : this.mousePosition.y }; if (this.fullSteps){ point.size = this.size; point.color = this.color; point.tool = this.tool; } this.points.push(point); }, _saveMouse : function(e){ if (e.type === 'touchmove'){ e.preventDefault(); } var position = this._getXY(e); this.mousePosition.x = position.x; this.mousePosition.y = position.y; if (this.drawing){ this._savePoint(); } }, _saveStep : function(){ var aux = { points: this.points.splice(0) }; this.doneSteps.push(aux); }, _stopDrawing : function(e){ if (this.drawing){ e.stopImmediatePropagation(); this.shadowCanvas.off('mousemove touchmove', this.proxy(this._draw,this)); this._copyShadowToReal(); this.drawing = false; this._emitDrawingChanged(); } }, _emitDrawingChanged : function(){ if (this.stopTimer){ clearTimeout(this.stopTimer); } var self = this; this.stopTimer = setTimeout(function(){ self.emit('drawing.changed'); }, this.stopDrawingTime); }, _copyShadowToReal : function(){ this.context.drawImage(this.shadowCanvas[0],0,0); this._clearCanvas(this.shadowCanvas,this.shadowContext); if (this.drawing){ this._saveStep(); } this.points = []; }, _getXY : function(e){ var x, y, touchEvent = { pageX : 0, pageY : 0}; if (typeof e.changedTouches !== 'undefined'){ touchEvent = e.changedTouches[0]; } else if ( typeof e.originalEvent !== 'undefined' && typeof e.originalEvent.changedTouches !== 'undefined'){ touchEvent = e.originalEvent.changedTouches[0]; } x = e.offsetX || e.layerX || touchEvent.pageX; y = e.offsetY || e.layerY || touchEvent.pageY; if (e.type.indexOf('touch') !== -1){ var offset = this.shadowCanvas.offset(); x -= offset.left; y -= offset.top; } return { x : x, y : y }; }, _draw : function(){ var length = this.points.length, aux = this.points[0], erasing = aux.tool === 'eraser', context = erasing ? this.context : this.shadowContext, previousTool = '', revertTool = false; if (this.tool !== aux.tool && typeof aux.tool != "undefined"){ revertTool = true; previousTool = this.tool; this.changeTool(aux.tool); } context.lineWidth = aux.size || this.size; context.strokeStyle = aux.color || this.color; context.fillStyle = aux.color || this.color; if (length !== 0){ if (length < 3){ context.beginPath(); context.arc(aux.x,aux.y, context.lineWidth / 2, 0, Math.PI * 2, true); context.fill(); context.closePath(); } else { if (!erasing){ this._clearCanvas(this.shadowCanvas,this.shadowContext); } context.beginPath(); context.moveTo(this.points[0].x,this.points[0].y); for (var i = 1; i < length -2; i++){ var x = (this.points[i].x + this.points[i+1].x) / 2, y = (this.points[i].y + this.points[i+1].y) / 2; context.quadraticCurveTo(this.points[i].x,this.points[i].y,x,y); } context.quadraticCurveTo(this.points[i].x,this.points[i].y,this.points[i+1].x,this.points[i+1].y); context.stroke(); } } // Only used in undo / redo return { 'toolUsed' : aux.tool, 'previousTool' : previousTool, 'revertTool' : revertTool }; }, _drawFromSteps : function(actions){ if (actions){ this.clear(true); for (var i = 0, len = actions.length; i < len; i++) { if (actions[i].points) { this.points = actions[i].points; var result = this._draw(); if (result.toolUsed !== 'eraser'){ this._copyShadowToReal(); } if (result.revertTool){ this.changeTool(result.previousTool); } } else if (actions[i].rects) { for (var r = 0; r < actions[i].rects.length; r++) { // should this be extracted to lower level function this.context.drawImage(actions[i].rects[r].image, actions[i].rects[r].x, actions[i].rects[r].y, actions[i].rects[r].width, actions[i].rects[r].height); } } } } }, init : function(){ if (!this._isCanvas()){ this._createCanvas(); } else { this._createWrapper(); } this._createShadowCanvas(); this._applyClasses(); this._getContexts(); this.shadowContext.lineJoin = 'round'; this.body = $('body'); this.mousePosition = { x : 0, y : 0 }; this.points = []; this.drawing = false; this.unDoneSteps = []; this.doneSteps = []; this.clear(true); if (!this.readMode){ this._bindEvents(); } this.oldColor = this.color; this.changeTool(this.tool); }, changeColor: function(color){ this.color = color; this.shadowContext.strokeStyle = this.color; }, changeSize : function(size){ this.size = size; this.shadowContext.lineWidth = this.size; }, changeReadMode : function(mode){ if (mode){ this._bindEvents(); } else { this._unbindEvents(); } this.readMode = mode; }, toJSON : function(){ return this.doneSteps; }, loadJSON : function(obj){ this._drawFromSteps(obj); this.doneSteps = obj; }, toDataURL : function(){ return this.el[0].toDataURL(); }, loadDataURL : function(dataurl){ var image = new Image(), context = this.context, canvasEl = this.el, self = this; image.onload = function() { context.drawImage(this, 0, 0, parseInt(canvasEl.attr('width'), 10), parseInt(canvasEl.attr('height'), 10)); self.doneSteps.push({ rects: [ { x: 0, y: 0, width: parseInt(canvasEl.attr('width'), 10), height: parseInt(canvasEl.attr('height'), 10), image: this, url: dataurl.toString(), tool: 'stamp' } ] }); self._emitDrawingChanged(); }; image.src = dataurl.toString(); }, undo : function(){ if (this.doneSteps.length){ var lastStep = this.doneSteps.pop(); this.unDoneSteps.push(lastStep); this._drawFromSteps(this.doneSteps); this._emitDrawingChanged(); } }, redo : function(){ if (this.unDoneSteps.length){ var lastUndone = this.unDoneSteps.pop(); this.doneSteps.push(lastUndone); this._drawFromSteps(this.doneSteps); this._emitDrawingChanged(); } }, _setPencil : function(){ this.context.globalCompositeOperation = 'source-over'; this.color = this.oldColor; }, _setEraser : function(){ this.context.globalCompositeOperation = 'destination-out'; this.oldColor = this.color; this.color = 'rgba(0,0,0,1)'; }, changeTool : function(tool){ if (this.tools.indexOf(tool) !== -1){ var method = '_set' + capitalize(tool); this[method].call(this); this.tool = tool; } else { console.error(tool + ' is not implemented'); } }, _clearCanvas : function(canvas, context){ context.clearRect(0,0,canvas[0].width,canvas[0].height); }, clear : function(intern){ intern = intern || false; this._clearCanvas(this.el,this.context); if (!intern){ this.emit('clear'); this.doneSteps = []; } } }); })(jQuery);
041fc9d376be43b70ac36a0a4eb5d8fcfc3c67f0
[ "Markdown", "JavaScript" ]
5
Markdown
limitlis/scribble
eee476374a0fb63b5f6ec3a07e6fda22a2c64c5b
1b58914678b60ce603dfff7e5e6f90addf4aed57
refs/heads/master
<repo_name>ELCHE16/G5-E-Commerce-DH<file_sep>/DER e-Commerce/e_commerce/e-commerce_facturas.sql CREATE DATABASE IF NOT EXISTS `e-commerce` /*!40100 DEFAULT CHARACTER SET utf8mb4 */; USE `e-commerce`; -- MySQL dump 10.13 Distrib 5.6.17, for Win32 (x86) -- -- Host: 127.0.0.1 Database: e-commerce -- ------------------------------------------------------ -- Server version 5.5.5-10.4.8-MariaDB /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; /*!40103 SET TIME_ZONE='+00:00' */; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; -- -- Table structure for table `facturas` -- DROP TABLE IF EXISTS `facturas`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `facturas` ( `id_factura` int(11) NOT NULL AUTO_INCREMENT, `id_usuariof` int(11) NOT NULL, `id_tipo_factura` int(11) NOT NULL, `fecha` datetime NOT NULL, `id_direccionf` int(11) NOT NULL, `id_tarjetaf` int(11) NOT NULL, `id_enviosf` int(11) DEFAULT NULL, `numero_factura` varchar(45) NOT NULL, `total` float NOT NULL, PRIMARY KEY (`id_factura`), UNIQUE KEY `id_factura_UNIQUE` (`id_factura`), KEY `id_tipo_factura_idx` (`id_tipo_factura`), KEY `id_direccionf_idx` (`id_direccionf`), KEY `id_usuariof_idx` (`id_usuariof`), KEY `id_tarjetaf_idx` (`id_tarjetaf`), KEY `id_enviosf_idx` (`id_enviosf`), CONSTRAINT `id_direccionf` FOREIGN KEY (`id_direccionf`) REFERENCES `direcciones` (`id_direccion`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `id_enviosf` FOREIGN KEY (`id_enviosf`) REFERENCES `envios` (`id_envio`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `id_tarjetaf` FOREIGN KEY (`id_tarjetaf`) REFERENCES `tarjetas` (`id_tarjeta`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `id_tipo_factura` FOREIGN KEY (`id_tipo_factura`) REFERENCES `tipo_factura` (`id_tipo_factura`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `id_usuariof` FOREIGN KEY (`id_usuariof`) REFERENCES `usuarios` (`id_usuario`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `facturas` -- LOCK TABLES `facturas` WRITE; /*!40000 ALTER TABLE `facturas` DISABLE KEYS */; /*!40000 ALTER TABLE `facturas` ENABLE KEYS */; UNLOCK TABLES; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!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 */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; -- Dump completed on 2020-01-29 20:49:59 <file_sep>/clases/Categoria.php <?php class Categoria { private $id_categoria; private $categoria; public function listarcategorias() { $link = Conexion::conectar(); try { $sql = "SELECT id_categoria, categoria FROM categorias"; $stmt = $link->prepare($sql); $stmt->execute(); $resultado = $stmt->fetchAll(PDO::FETCH_ASSOC); $stmt->closeCursor(); return $resultado; } catch (\Exception $e) { echo "Error al obtener Lista de Categorias"; $e->getMessage(); } } public function verCategoriaPorID($id_categoria) { try{ $link = Conexion::conectar(); $sql = "SELECT * FROM categorias WHERE id_categoria='$id_categoria'"; $stmt = $link->prepare($sql); $stmt->execute(); $resultado = $stmt->fetch(PDO::FETCH_ASSOC); return $resultado; } catch(\PDOException $e){ return null; } catch(\PDOStatement $e){ return null; } catch (\Exception $e) { die($e->getMessage()); return null; } } public function agregarCategoria() { $categoria = $_POST['categoria']; $link = Conexion::conectar(); $sql = "INSERT INTO categorias VALUES ( default, :categoria )"; $stmt = $link->prepare($sql); $stmt->bindParam(':categoria', $categoria, PDO::PARAM_STR); if( $stmt->execute() ){ $this->setId_categoria($link->lastInsertId()); $this->setCategoria($categoria); return true; } return false; } public function modificarCategoria() { $id = $_POST['id_categoria']; $categoria = $_POST['categoria']; $link = Conexion::conectar(); $sql = "UPDATE categorias SET categoria='$categoria' WHERE id_categoria='$id'"; $stmt = $link->prepare($sql); if( $stmt->execute() ){ $this->setid_categoria($link->lastInsertId()); $this->setcategoria($categoria); return true; } return false; } public function eliminarCategoria() { try { $id = $_REQUEST['id']; $link = Conexion::conectar(); $sql = "DELETE FROM categorias WHERE id_Categoria=?"; $stmt = $link->prepare($sql); if( $stmt->execute(array($id)) ){ // $this->setid_Categoria($link->lastInsertId()); // $this->setCategoria($Categoria); } }catch(\PDOException $e){ return False; } catch(\PDOStatement $e){ return False; } catch (\Exception $e) { die($e->getMessage()); return false; } return true; } /** * @return mixed */ public function getId__categoria() { return $this->id_categoria; } /** * @param mixed $id_categoria */ public function setId_categoria($id_categoria) { $this->id_categoria = $id_categoria; } /** * @return mixed */ public function getCategoria() { return $this->categoria; } /** * @param mixed $categoria */ public function setCategoria($categoria) { $this->categoria = $categoria; } }<file_sep>/home.php <?php session_start(); $pagina="Home"; include_once("includes/funciones.php"); include_once("includes/baseDeDatos.php"); if(isset($_SESSION["activeUser"]) && !is_null($_SESSION["activeUser"])){ if($_SESSION["activeUser"]["fotoPerfil"]==""){ $_SESSION["activeUser"]["fotoPerfil"]=(isset($imagenUsuario))?$imagenUsuario:"img/perfil.png"; } $activeUser=$_SESSION["activeUser"]; } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <link rel="stylesheet" href="css/styles.css"> <title>E-commerce</title> <link rel="shortcut icon" href="favicon.ico"/> </head> <body class="main-perfil"> <!--Comienza el header--> <header class="container-fluir fixed-top"> <?php include_once("includes/headerPerfil.php"); ?> </header> <!--Fin el header--> <main> <div class="inner-main" id="home"> <div class="welcome"> <div class="inner-welcome"> <div class="img"> <img src="img/e-com1.png" alt=""> </div> <div class="text"> <h1> ¡Bienvenid@ a E-commerce! </h1> <p> El lugar donde encontrarás todo lo que buscas y al mejor precio. </p> </div> </div> </div> <div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel"> <ol class="carousel-indicators"> <li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li> <li data-target="#carouselExampleIndicators" data-slide-to="1"></li> <li data-target="#carouselExampleIndicators" data-slide-to="2"></li> </ol> <div class="carousel-inner"> <div class="carousel-item active"> <img class="d-block w-100" src="img/carousel/2.png" alt="First slide"> </div> <div class="carousel-item"> <img class="d-block w-100" src="img/carousel/3.png" alt="Second slide"> </div> <div class="carousel-item"> <img class="d-block w-100" src="img/carousel/1.png" alt="Third slide"> </div> </div> <a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> <div class="categorias"> <div class="categoria"> <div class="icono"> <img src="img/categorias/autopng.png" alt=""> </div> <div class="titulo"> Vehículos </div> </div> <a href="lista-productos.php" class="irDescripcion"><!--Saque el onclick por que pertenece a javascript---> <div class="categoria"> <div class="icono"> <img src="img/categorias/tel.png" alt=""> </div> <div class="titulo"> Smarthphones </div> </div> </a> <div class="categoria"> <div class="icono"> <img src="img/categorias/casa.png" alt=""> </div> <div class="titulo"> Hogar </div> </div> <div class="categoria"> <div class="icono"> <img src="img/categorias/ropa.png" alt=""> </div> <div class="titulo"> Ropa </div> </div> <div class="categoria"> <div class="icono"> <img src="img/categorias/guitarra.png" alt=""> </div> <div class="titulo"> Música </div> </div> <div class="categoria"> <div class="icono"> <img src="img/categorias/pc.png" alt=""> </div> <div class="titulo"> Computación </div> </div> <div class="categoria"> <div class="icono"> <img src="img/categorias/servicios.png" alt=""> </div> <div class="titulo"> Servicios </div> </div> <div class="categoria"> <div class="icono"> <img src="img/categorias/mas.png" alt=""> </div> <div class="titulo"> Otras categorías </div> </div> </div> </div> </main> <!-- MainBody End ============================= --> <!-- footer --> <?php include_once("includes/footer.php"); ?> <!-- fin footer --> <!-- Modal --> <?php include_once("includes/modal.php"); ?> <!-- Fin modal --> <?php include_once("includes/scriptBootstrap.php"); ?> <script src="https://kit.fontawesome.com/67f61afa3e.js" crossorigin="anonymous"></script> </body> </html> <file_sep>/seguridad.php <?php session_start(); include_once("includes/funciones.php"); include_once("includes/baseDeDatos.php"); $pagina="Seguridad"; if(isset($_SESSION["activeUser"]) && !is_null($_SESSION["activeUser"])){ $activeUser=$_SESSION["activeUser"]; }else{ header("Location: login.php");exit; } $errores=null; if(isset($_POST["enviarClave"])&& $_POST){ $cambios= [ "claveActual"=>trim($_POST["claveActual"]), "claveNueva"=>trim($_POST["claveNueva"]), "claveNuevaRepetir"=>trim($_POST["claveNuevaRepetir"]) ]; $requisitos = [ "claveActual"=>[ CLAVE ], "claveNueva"=>[ CLAVE ], "claveNuevaRepetir"=>[ CLAVE ] ]; $errores = hacerValidaciones($cambios,$requisitos); //dd($_POST); //dd($activeUser); //dd($cambios); if(!$errores){ if(!password_verify($cambios["claveActual"],$activeUser["clave"])){ $errores["claveActual"]="clave incorrecta"; }else { //dd($cambios); if($cambios["claveNueva"]!=$cambios["claveNuevaRepetir"]){ $errores["claveNueva"]="clave incorrecta"; $errores["claveNuevaRepetir"]="clave incorrecta"; //dd($errores); }else{ if(!$errores){ $activeUser["clave"]=password_hash($cambios["claveNueva"],PASSWORD_DEFAULT); $_SESSION["activeUser"]=$activeUser; $arrayUsuarios=getObjectsFromFile("data/usuarios.json"); //$arrayUsuarios=leerJsonYpasaArray(Direccion); $arrayUsuarios[$activeUser["email"]]=$activeUser; guardarArrayYpasarAJson("data/usuarios.json",$arrayUsuarios); header("Location:logOut.php");exit; }else{ //dd("hola"); } } } } } if(isset($_POST["cambiosEmail"])&& $_POST){ $cambiosMail= [ "nuevoMail"=>trim($_POST["nuevoMail"]), "claveActualMail"=>trim($_POST["claveActualMail"]) ]; $requisitos = [ "nuevoMail"=>[ CORREO ], "claveActualMail"=>[ CLAVE ] ]; $errores = hacerValidaciones($cambiosMail,$requisitos); if(!$errores){ if(!password_verify($cambiosMail["claveActualMail"],$activeUser["clave"])){ $errores["claveActualMail"][]="clave incorrecta"; } if(!$errores){ $arrayUsuarios=getObjectsFromFile("data/usuarios.json"); if( isset($arrayUsuarios[$cambiosMail["nuevoMail"]]) ){ $errores["nuevoMail"][]="utilize otro email"; } if(!$errores){ unset($arrayUsuarios[$activeUser["email"]]); //-------------- $arrayUM=getObjectsFromFile("data/user_email.json"); $arrayUM[$activeUser["usuario"]]=$cambiosMail["nuevoMail"]; guardarArrayYpasarAJson("data/user_email.json",$arrayUM); //-------------- $activeUser["email"]=$cambiosMail["nuevoMail"]; $_SESSION["activeUser"]=$activeUser; $arrayUsuarios[$activeUser["email"]]=$activeUser; unlink("data/usuarios.json"); guardarArrayYpasarAJson("data/usuarios.json",$arrayUsuarios); } //header("Location:logOut.php");exit; }else{ //dd("hola"); } } } ?> <!DOCTYPE html> <html lang="en"> <head> <?php include_once("includes/headPerfil.php") ?> <link rel="stylesheet" href="css/stylePerfilSeguridadResumen.css"> <title>E-commerce</title> </head> <body class="main-perfil"> <!--Comienza el header--> <header class="container-fluir fixed-top"> <?php include_once("includes/headerPerfil.php"); ?> </header> <!--Fin el header--> <main class="mx-xl-auto" > <div class="container contenedor"> <div class="row"> <!--ubicacion--> <?php include_once("includes/ubicacionPerfil.php"); ?> <!--ubicacion--> <!--menu izquierdo--> <?php include_once("includes/menuIzquierdoPerfil.php"); ?> <!--menu izquierdo--> <!-----Seguridad--------------------------------> <div class="col-12 col-sm-12 col-md-9 col-lg-9 mb-4 resumen seguridad"> <h1 class="d-block mt-2">Seguridad</h1> <!--comienzo del Cambio de E-mail---> <h2 class="col-12 my-4">Cambio de E-mail</h2> <div class="informacion"> <h5 class="">Recomendaciones de seguridad</h5> <p class="">Ingrese un E-mail valido.</br> Se le enviara un correo de confirmacion.</p> </div> <form class="my-3 px-4 col-10 form-mail" name="formCambioMail" method="post" action=""> <div class="form-group" > <label for="viejoMail">Email </label> <input type="email" class="form-control" id="viejoMail" name="viejoMail" aria-describedby="emailHelp" value="<?=$activeUser["email"]; ?>" readonly> <small class="text-muted">E-mail Actual</small> </div> <div class="form-group" > <label for="nuevoMail">Nuevo Email</label> <input type="email" class="form-control" id="nuevoMail" name="nuevoMail" aria-describedby="emailHelp" placeholder="Ingrese Nuevo email" title="Ingresar el nuevo e-mail" required> <small class="text-muted">Ingrese el Nuevo E-mail</small> <small class="text-danger"><?=(isset($errores))?mostrarErroresPerfil($errores,"nuevoMail"):""; ?></small> </div> <div class="form-group" > <label for="claveActualMail" class="">Clave Actual</label> <input type="password" class="form-control" id="claveActualMail" name="claveActualMail" placeholder="Clave Actual" title="Ingresa la clave actual para cambiar el e-mail" minlength="6" maxlength="20" autocomplete="off" required> <small class="text-muted">Ingrese la Clave Actual para guardar los cambios</small> <small class="text-danger"><?=(isset($errores))?mostrarErroresPerfil($errores,"claveActualMail"):""; ?></small> </div> <button type="submit" class="btn btn-secondary ml-md-auto boton-efecto" name="cambiosEmail" >Guardar Cambios</button> </form> <!--Fin Cambio de Email--> <!-----Comienzo de Cambio de Clave------------------------------------------------------------------------------> <h2 class="col-12 text-left my-4">Cambio de Clave</h2> <div class="informacion"> <h5 class="">Recomendaciones de seguridad</h5> <p class="">Ingresá entre 6 y 20 caracteres.</br> No usés la misma clave de otro sitio.</p> </div> <form class="my-3 px-4 col-10 form-clave" name="formCambioClave" method="post" action=""> <div class="form-group"> <label for="claveActual" class="col-form-label">Clave Actual</label> <input type="password" class="form-control" id="claveActual" name="claveActual" placeholder="Clave Actual" title="Ingresa la clave actual" minlength="6" maxlength="20" autocomplete="off" required> <small class="text-muted">Ingrese la Clave Actual para Cambiar la Clave</small> <small class="text-danger"><?=(isset($errores))?mostrarErroresPerfil($errores,"clave"):""; ?></small> </div> <div class="form-group "> <label for="claveNueva" class="">Nueva Clave</label> <input type="password" class="form-control" id="claveNueva" name="claveNueva" placeholder="Ingresa la Nueva Clave" title="Ingresa la Nueva clave " minlength="6" maxlength="20" autocomplete="off" required> <small class="text-muted">Su contraseña debe tener entre 8 y 20 caracteres, contener letras y números, y no debe contener espacios, caracteres especiales o emoji.</small> <small class="text-danger"><?=(isset($errores))?mostrarErroresPerfil($errores,"claveNueva"):""; ?></small> </div> <div class="form-group "> <label for="claveNuevaRepetir" class="">Repetir Nueva Clave </label> <input type="password" class="form-control" id="claveNuevaRepetir" name="claveNuevaRepetir" placeholder="Repetir la Nueva Clave" title="Repita la Nueva clave" minlength="6" maxlength="20" autocomplete="off" required> <small class="text-muted">Repita la Nueva Clave</small> <small class="text-danger"><?=(isset($errores))?mostrarErroresPerfil($errores,"claveNuevaRepetir"):""; ?></small> </div> <button type="submit" class="btn btn-secondary ml-md-auto boton-efecto" name="enviarClave">Guardar Cambios</button> </form> <!--fin Cambio de Clave------------------------------- --> </div> <!-----Fin Seguridad--------------------------------> </div> </div> <!-- MainBody End ============================= --> </main> <!-- Footer ================================================================== --> <?php include_once("includes/footer.php"); ?> <!-- Footer End================================================================== --> <!-- Modal --> <?php include_once("includes/modal.php"); ?> <!-- Fin modal --> <?php include_once("includes/scriptBootstrap.php") ?> <script src="https://kit.fontawesome.com/67f61afa3e.js" crossorigin="anonymous"></script> </body> </html><file_sep>/DER e-Commerce/e_commerce/e-commerce_usuarios.sql CREATE DATABASE IF NOT EXISTS `e-commerce` /*!40100 DEFAULT CHARACTER SET utf8mb4 */; USE `e-commerce`; -- MySQL dump 10.13 Distrib 5.6.17, for Win32 (x86) -- -- Host: 127.0.0.1 Database: e-commerce -- ------------------------------------------------------ -- Server version 5.5.5-10.4.8-MariaDB /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; /*!40103 SET TIME_ZONE='+00:00' */; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; -- -- Table structure for table `usuarios` -- DROP TABLE IF EXISTS `usuarios`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `usuarios` ( `id_usuario` int(11) NOT NULL AUTO_INCREMENT, `nombre` varchar(45) NOT NULL, `apellido` varchar(45) NOT NULL, `user` varchar(45) NOT NULL, `contrasenia` varchar(1000) NOT NULL, `email` varchar(100) NOT NULL, `img` varchar(10000) NOT NULL DEFAULT 'img/defaul.png', `id_tipo_de_usuario` int(11) NOT NULL, `id_sexo` int(11) DEFAULT NULL, `id_direccion` int(11) DEFAULT NULL, `id_tarjeta` int(11) DEFAULT NULL, `id_carrito` int(11) DEFAULT NULL, `id_estado` int(11) NOT NULL, `fecha_nacimiento` date DEFAULT NULL, PRIMARY KEY (`id_usuario`), UNIQUE KEY `id_usuario_UNIQUE` (`id_usuario`), UNIQUE KEY `user_UNIQUE` (`user`), UNIQUE KEY `email_UNIQUE` (`email`), KEY `id_sexo_idx` (`id_sexo`), KEY `id_direccion_idx` (`id_direccion`), KEY `id_tipo_de_usuario_idx` (`id_tipo_de_usuario`), KEY `id_carrito_idx` (`id_carrito`), KEY `id_tarjeta_idx` (`id_tarjeta`), KEY `id_estado_idx` (`id_estado`), CONSTRAINT `id_carrito` FOREIGN KEY (`id_carrito`) REFERENCES `carritos` (`id_carrito`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `id_direccion` FOREIGN KEY (`id_direccion`) REFERENCES `direcciones` (`id_direccion`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `id_estado` FOREIGN KEY (`id_estado`) REFERENCES `estados` (`id_estado`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `id_sexo` FOREIGN KEY (`id_sexo`) REFERENCES `sexos` (`id_sexo`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `id_tarjeta` FOREIGN KEY (`id_tarjeta`) REFERENCES `tarjetas` (`id_tarjeta`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `id_tipo_de_usuario` FOREIGN KEY (`id_tipo_de_usuario`) REFERENCES `tipo_usuario` (`id_tipo_cliente`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `usuarios` -- LOCK TABLES `usuarios` WRITE; /*!40000 ALTER TABLE `usuarios` DISABLE KEYS */; /*!40000 ALTER TABLE `usuarios` ENABLE KEYS */; UNLOCK TABLES; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!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 */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; -- Dump completed on 2020-01-29 20:49:58 <file_sep>/includes/baseDeDatos.php <?php function guardarArrayYpasarAJson($direccion,$miArray){ $miJsonUsuarios=json_encode($miArray); file_put_contents($direccion,$miJsonUsuarios); } function activarDesactivarInput($valor=true){ if($valor){ echo "disabled"; }else{ echo ""; } }<file_sep>/admin.php <?php session_start(); $_SESSION["msj"]=""; ?> <!DOCTYPE html> <html lang="en" dir="ltr"> <?php include 'includes/head.php';?> <title>ABM Productos</title> <! -- body --> <?php include 'includes/headerAdm.php'; ?> <main class="container "> <h1>Administración</h1> <div class="list-group"> <a class="list-group-item list-group-item-action" href="abmMarca.php"> Panel de administración de Marcas </a> <a class="list-group-item list-group-item-action" href="abmCategoria.php"> Panel de administración de Categorías </a> <a class="list-group-item list-group-item-action" href="abmProducto.php"> Panel de administración de Productos </a> <a class="list-group-item list-group-item-action" href="adminUsuarios.php"> Panel de administración de Usuarios </a> </div> </main> <?php include 'includes/footer.php'; include 'includes/scriptBootstrap.php'; ?> <! -- /body --> </html> <file_sep>/adminUsuarios.php <?php //require_once ('includes/pdo.php'); require_once 'clases/Conexion.php'; require_once "clases/Usuario.php"; require_once "clases/Administrador.php"; $administrador = new Administrador(); $variable=$administrador->obtenerListaAdministradores(); //var_dump($variable); if ($_POST) { // var_dump($_POST); // exit; if (isset($_POST["btnBorrar"])) { $id = $_POST["id"]; $administrador->borrarAdministrador($id); } } ?> <!DOCTYPE html> <html lang="en" dir="ltr"> <?php include 'includes/head.php';?> <title>ABM administradors</title> <body> <?php include 'includes/headerAdm.php'; ?> <main> <div class="container-fluir my-3"> <div id="accordion"> <div class="card"> <div class="card-header " id="headingFour"> <h5 class="mb-0 d-flex justify-content-between"> <button class="btn btn-link mr-3 collapsed" data-toggle="collapse" data-target="#collapseFour" aria-expanded="false" aria-controls="collapseFour"> Lista de Administradores </button> <a href="agregaradministrador.php" class="btn btn-primary ml-3 ">Agregar</a> <a href="admin.php" class="btn btn-primary ml-3">Volver a principal</a> </h5> </div> <div id="collapseFour" class="collapse carrito-resumen" aria-labelledby="headingFour" data-parent="#accordion"> <ul class="list-group"> <li class="list-group-item"> <div class="card-body form-inline d-flex justify-content-between px-0"> <div class="form-group mb-1 col-1 px-1" > <span class="form-control-plaintext text-center">Id</span> </div> <div class="form-group mb-1 col-2 px-1" > <span class="form-control-plaintext text-center">Usuario</span> </div> <div class="form-group mb-1 col-2 px-1" > <span class="form-control-plaintext text-center">Nombre</span> </div> <div class="form-group mb-1 col-2 " > <span class="form-control-plaintext text-center">Apellido</span> </div> <div class="form-group mb-1 col-3 px-1" > <span class="form-control-plaintext text-center">Email</span> </div> <div class="form-group mb-1 col-2 px-1" > <span class="form-control-plaintext text-center">Estado</span> </div> </div> </li> <?php foreach ($variable as $key => $value) { ?> <li class="list-group-item"> <div class="card-body px-0"> <form class="form-inline" action="modificaradministrador.php" method="post" class="d-flex justify-content-between"> <div class="form-group mb-1 col-1 px-1" > <input type="text" readonly class="form-control-plaintext text-center" id="id" value="<?=$value->getId();?>" name="id"> </div> <div class="form-group mb-2 col-2 px-1 d-block"> <span class="form-control-plaintext text-center " ><?=$value->getUsuario();?></span> </div> <div class="form-group mb-2 col-2 px-1"> <span class="form-control-plaintext text-center " >$ <?=$value->getNombre();?></span> </div> <div class="form-group mb-2 col-2 px-1"> <span class="form-control-plaintext text-center " ><?=$value->getApellido();?></span> </div> <div class="form-group mb-2 col-3 px-1"> <span class="form-control-plaintext text-center " ><?=$value->getEmail();?></span> </div> <div class="form-group mb-2 col-2 px-1"> <span class="form-control-plaintext text-center " ><?=$value->getEstado();?></span> </div> <div class="form-group mb-2 col-12 text-center"> <button type="submit" class="btn btn-primary mx-2 mb-1 " name="modificar_l" value="<?=$value->getId();?>">Modificar</button> <!-- Button trigger modal --> <button type="button" class="btn btn-primary mx-2 mb-1 " name="eliminar_l" value="<?=$value->getId();?>" data-toggle="modal" data-target="#eliminar<?=$value->getId();?>Modal"> Eliminar </button> <!-- Modal --> <div class="modal fade" id="eliminar<?=$value->getId();?>Modal" tabindex="-1" role="dialog" aria-labelledby="eliminar<?=$value->getId();?>ModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content text-center"> <div class="modal-header"> <h5 class="modal-title" id="eliminar<?=$value->getId();?>ModalLabel">Desea eliminar este administrador?</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body d-flex justify-content-between flex-wrap"> <div class="form-group mb-2 col-2 px-1 d-block"> <span class="form-control-plaintext text-center " ><?=$value->getUsuario();?></span> </div> <div class="form-group mb-2 col-2 px-1"> <span class="form-control-plaintext text-center " >$ <?=$value->getNombre();?></span> </div> <div class="form-group mb-2 col-2 px-1"> <span class="form-control-plaintext text-center " ><?=$value->getApellido();?></span> </div> <div class="form-group mb-2 col-4 px-1"> <span class="form-control-plaintext text-center " ><?=$value->getEmail();?></span> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancelar</button> <button type="submit" class="btn btn-primary mx-2 mb-1 " name="btnBorrar" value="<?=$value->getId();?>">Eliminar</button> </div> </div> </div> </div> </div> </form> </div> </li> <?php } ?> </ul> </div> </div> </div> </div> </main> <?php include 'includes/footer.php'; include 'includes/scriptBootstrap.php'; ?> </body> </html><file_sep>/abmMarca.php <?php require_once 'clases/Conexion.php'; require 'clases/Marca.php'; $objMarca = new Marca; $marcas = $objMarca->listarMarcas(); include 'includes/head.php'; include 'includes/headerAdm.php'; ?> <!DOCTYPE html> <html lang="en" dir="ltr"> <title>ABM Marcas</title> <body> <! -- include 'includes/headerAdm.php'; --> <main class="container"> <h1>Administracion de Marcas</h1> <a href="admin.php" class="btn btn-outline-secondary m-3">Volver a principal</a> <table class="table table-stripped table-bordered table-hover bg-white"> <thead class="thead-dark"> <tr> <th>id</th> <th>Marca</th> <th colspan="2"> <a href="formAgregarMarca.php" class="btn btn-dark"> agregar </a> </th> </tr> </thead> <tbody> <?php foreach ( $marcas as $marca ){ ?> <tr> <td><?= $marca['id_marca']; ?></td> <td><?= $marca['marca']; ?></td> <td> <a href="formModificarMarca.php?id=<?php echo $marca['id_marca']; ?>" class="btn btn-outline-secondary"> modificar </a> </td> <td> <!-- Button trigger modal --> <button type="button" class="btn btn-outline-secondary" name="eliminar_l" value="<?=$marca["id_marca"];?>" data-toggle="modal" data-target="#eliminar<?=$marca["id_marca"];?>Modal"> Eliminar </button> <!-- Modal --> <div class="modal fade" id="eliminar<?=$marca["id_marca"];?>Modal" tabindex="-1" role="dialog" aria-labelledby="eliminar<?=$marca["id_marca"];?>ModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content text-center"> <div class="modal-header"> <h5 class="modal-title" id="eliminar<?=$marca["id_marca"];?>ModalLabel">Desea eliminar este Marca?</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body d-flex align-items-center justify-content-center flex-wrap"> <div class="form-group mb-2 col-10 px-1 "> <span class="form-control-plaintext " ><?=$marca["marca"];?></span> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancelar</button> <a href="eliminarMarca.php?id=<?php echo $marca['id_marca']; ?>" class="btn btn-outline-secondary"> eliminar </a> </div> </div> </div> </div> </td> </tr> <?php } ?> </tbody> </table> <a href="admin.php" class="btn btn-outline-secondary m-3">Administracion principal</a> </main> <?php include 'includes/footer.php'; include 'includes/scriptBootstrap.php'; ?> </body> </html><file_sep>/includes/pdo.php <?php $dsn = "mysql:host=localhost;dbname=e-commerce"; $user = "root"; $pass = ""; try { $db = new PDO($dsn, $user,$pass); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $db->exec('SET CHARACTER SET utf8'); } catch (\Exception $e) { $e->getMessage(); echo "Error al conectar la base de datos"; } ?> <file_sep>/includes/menuIzquierdoPerfil.php <div class="col-12 col-sm-12 col-md-3 col-lg-3 mb-4 menu-left"> <ul class="list-group"> <li class="list-group-item "><a href="resumen.php" class="">Resumen</a></li> <li class="list-group-item conf" > <a data-toggle="collapse" href="#collapseExample" role="button" aria-expanded="false" aria-controls="collapseExample">Configuracion</a> <div class="collapse" id="collapseExample"> <ul class="card card-header"> <li > <a href="perfil.php" class="">Mis Datos</a> </li> <li > <a href="seguridad.php" class="">Seguridad</a> </li> </ul> </div> </li> </ul> </div><file_sep>/formModificarMarca.php <?php require_once 'clases/Conexion.php'; include 'includes/head.php'; include 'includes/headerAdm.php'; require 'clases/Marca.php'; if(isset($_REQUEST['id'])) { $objMarca = new Marca; $id_marca=$_REQUEST['id']; $marca=$objMarca->verMarcaPorID($id_marca); //var_dump($marca); } ?> <main class="container"> <h1> Actualizacion de una marca</h1> <form action="modificarMarca.php" method="post"> Marca: <input type="hidden" name="id_marca" value="<?php echo $marca['id_marca'];?>" /> <br> <input type="text" name="marca" value="<?php echo $marca['marca'];?>" class="form-control" required> <br> <input type="submit" value="Modificar Marca" class="btn btn-secondary"> <a href="abmMarca.php" class="btn btn-light">Volver a admin de marcas</a> </form> </main> <?php include 'includes/footer.php'; ?><file_sep>/clases/Domicilio.php <?php class Domicilio{ private $id; private $pais; private $provincia; private $ciudad; private $direccion; private $cod_postal; /** * Get the value of id */ public function getId() { return $this->id; } /** * Set the value of id * * @return self */ public function setId($id) { $this->id = $id; return $this; } /** * Get the value of pais */ public function getPais() { return $this->pais; } /** * Set the value of pais * * @return self */ public function setPais($pais) { $this->pais = $pais; return $this; } /** * Get the value of provincia */ public function getProvincia() { return $this->provincia; } /** * Set the value of provincia * * @return self */ public function setProvincia($provincia) { $this->provincia = $provincia; return $this; } /** * Get the value of ciudad */ public function getCiudad() { return $this->ciudad; } /** * Set the value of ciudad * * @return self */ public function setCiudad($ciudad) { $this->ciudad = $ciudad; return $this; } /** * Get the value of direccion */ public function getDireccion() { return $this->direccion; } /** * Set the value of direccion * * @return self */ public function setDireccion($direccion) { $this->direccion = $direccion; return $this; } /** * Get the value of cod_postal */ public function getCod_postal() { return $this->cod_postal; } /** * Set the value of cod_postal * * @return self */ public function setCod_postal($cod_postal) { $this->cod_postal = $cod_postal; return $this; } } ?><file_sep>/includes/fileManager.php <?php // creo que tira error si el archivo no tiene ningún objeto function leerFile($path){ return file_get_contents($path); } function escribirFile($path, $content){ return file_put_contents($path, $content); } function agregarToFile($path, $content, $cut = ""){ return file_put_contents($path, $cut . $content, FILE_APPEND); } function getObjectsFromFile($path, $likeArray = true){ $content = file_get_contents($path); $object = json_decode($content, $likeArray); return $object; } function getObjectFromFile($path, $key, $likeArray = true){ $content = file_get_contents($path); $object = json_decode($content, $likeArray); if($likeArray){ return $object[$key] ?? false; } else{ return $object ?? false; } } function mergeObjectToFile($path, $nuevo){ $todo = getObjectsFromFile($path); $todo = array_merge($todo, $nuevo); escribirFile($path, json_encode($todo)); } function removeObjectFromFile($path, $key){ $objects = getObjectsFromFile($path); unset($objects[$key]); escribirFile($path, json_encode($objects)); } function existsKeyOnFile($path, $key){ $todo = getObjectsFromFile($path); if(!$todo){ return false; } return in_array($key, array_keys($todo)); } // // TESTING ---------------------------------------------- // $arr = []; // $arr["a"] = 1; // $arr["b"] = 2; // $path = "datos.json"; // escribirFile($path, json_encode($arr)); // $nuevo = ["c" => 3]; // mergeObjectToFile($path, $nuevo); // echo "<br>"; // echo leerFile($path); // echo "<br>"; // if(existsKeyOnFile($path, "b")){ // echo "Está seteado 'b'"; // }else{ // echo "No está seteado 'b'"; // } // echo "<br>"; // if(existsKeyOnFile($path, "z")){ // echo "Está seteado 'z'"; // }else{ // echo "No está seteado 'z'"; // } // echo "<br>"; // echo getObjectsFromFile($path)["b"]; // echo "<br>"; // echo getObjectFromFile("datos.json", "a"); // echo "<br>"; // agregarToFile($path, "Texto random agregado", PHP_EOL); // echo leerFile($path); // // END TESTING ---------------------------------------------------------------- ?><file_sep>/login.php <?php session_start(); $pagina="Login"; //session_destroy(); require_once "./includes/funciones.php"; if(isset($_SESSION["activeUser"])){ header("Location: perfil.php"); } else{ $errores = null; if($_POST){ $user = $_POST["usuario"]; $pass = $_POST["pass"]; $requisitos = [ "usuario" => [ MINSIZE => 4, MAXSIZE => 155 ], "pass" => [ CLAVE ] ]; $errores = hacerValidaciones($_POST, $requisitos); if(!$errores){ // setcookies if(findUserByEmail($_POST["usuario"])){ $activeUser = findUserByEmail($_POST["usuario"]); if(password_verify($_POST["pass"], $activeUser["clave"])){ $_SESSION["activeUser"] = $activeUser; if($_POST["recordame"]="on"){ setcookie("usuario",$activeUser["usuario"],time()+60*60); setcookie("clave",$activeUser["clave"],time()+60*60); setcookie("email",$activeUser["email"],time()+60*60); } header("Location: perfil.php");exit; }else{ $errores["soloTexto"] = ["Los datos ingresados son inválidos"]; } }else if(findUserByUserName($_POST["usuario"])){ $activeUser = findUserByUserName($_POST["usuario"]); if(password_verify($_POST["pass"], $activeUser["clave"])){ $_SESSION["activeUser"] = $activeUser; if($_POST["recordame"]="on"){ setcookie("usuario",$activeUser["usuario"],time()+60*60); setcookie("clave",$activeUser["clave"],time()+60*60); setcookie("email",$activeUser["email"],time()+60*60); } header("Location: perfil.php");exit; }else{ $errores["soloTexto"] = ["Los datos ingresados son inválidos"]; } }else{ $errores["soloTexto"] = ["Los datos ingresados son inválidos"]; } } }else{ $user = ""; $pass = ""; } } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="https://fonts.googleapis.com/css?family=Roboto+Condensed:400,700|Roboto:400,500,700&display=swap" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600|Roboto:500,700&display=swap" rel="stylesheet"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <link rel="stylesheet" href="css/styles.css"> <title>Login</title> <link rel="shortcut icon" href="favicon.ico"/> </head> <body class="main-login"> <!--Comienza el header--> <header class="container-fluir fixed-top"> <?php include_once("includes/headerPerfil.php"); ?> </header> <!--Fin el header--> <main class=" container mb-4 main-inicio"> <ul class="breadcrumb col-12"> <li><a href="home.html">Home</a> <span class="divider">/</span></li> <li>Cuenta <span class="divider">/</span></li> <li class="active">Ingreso</li> </ul> <section class=" mb-2"> <!--<h2>Inicio de Seccion</h2> --> <form class="col-10 col-sm-6 col-md-6 col-lg-6 mx-auto" action="" method="post"> <!--<form action="iniciar sesion.php" metodo="post" class="form">--> <h2 class="form-titulo">INICIO DE SESION</h2> <div class="contenedor-inputs"> <h3>Hola! Ingresa tu e-mail o usuario</h3> <input type="text" name="usuario" id="usuario" value="" placeholder="E-mail o usuario" class="input-100" required> </br> <h3>Ahora, tu clave</h3> <input type="password" name="pass" id="pass" value="" placeholder="<PASSWORD>" class="input-100" required> </br> <?php if(isset($errores)) echo imprimirErrores($errores) ?> <div> <label class="input-100 px-1" for="recordar"><input type="checkbox" name="recordar" class="col-ms-1 mx-1" checked>Recodar</label> </div> <input type="submit" value="Ingresar" class="btn-enviar"> </div> </form> </section> </main> <!-- footer --> <?php include_once("includes/footer.php"); ?> <!-- fin footer --> <!-- Modal --> <?php include_once("includes/modal.php"); ?> <!-- Fin modal --> <?php include_once("includes/scriptBootstrap.php"); ?> <script src="https://kit.fontawesome.com/67f61afa3e.js" crossorigin="anonymous"></script> </body> </html> <file_sep>/clases/EstadoUsuario.php <?php class EstadoUsuario{ private $id; private $estado; public function obtenerListaEstadoUsuario(){ $db=Conexion::conectar(); try { $sql = "SELECT id_estado as id,estado as estado FROM estados"; $stmt = $db->prepare($sql); $stmt->execute(); //$variable = $stmt->fetchAll(PDO::FETCH_ASSOC);//array asociado $variable = $stmt->fetchAll(PDO::FETCH_CLASS,"EstadoUsuario");//objeto $stmt->closeCursor(); return $variable; } catch (\Exception $e) { echo "Error al obtener Lista de Sexos"; $e->getMessage(); return false; } } /** * Get the value of id */ public function getId() { return $this->id; } /** * Set the value of id * * @return self */ public function setId($id) { $this->id = $id; return $this; } /** * Get the value of estado */ public function getEstado() { return $this->estado; } /** * Set the value of estado * * @return self */ public function setEstado($estado) { $this->estado = $estado; return $this; } } ?><file_sep>/modificarProducto.php <?php require_once 'clases/Conexion.php'; require_once 'clases/Marca.php'; require_once 'clases/Categoria.php'; require_once 'clases/Producto.php'; include_once("includes/funciones.php"); include_once("includes/baseDeDatos.php"); $producto = new Producto(); $marca=new Marca(); $categoria=new Categoria(); session_start(); $msj=""; if(isset($_POST["id"]) && isset($_POST["modificar_l"])){ $id=(int)$_POST["modificar_l"]; $unProducto=$producto->buscarPorId($id); $_SESSION["unProducto"]=$unProducto; if(!$unProducto){ $msj="warning"; } } /** *echo "<pre>"; *echo"post"; *var_dump($_POST); *echo"secion"; *var_dump($_SESSION); *echo"producto"; *var_dump($unProducto); *echo "</pre>"; */ var_dump($_SESSION["unProducto"]); if (isset($_POST["modificar_id"])&& $_POST ){ /** * */ $datos=[ "id"=>trim($_POST["id"]), "nombre" =>trim($_POST["nombre"]), "descripcion" =>trim($_POST["descripcion"]), "precio" =>trim($_POST["precio"]), "stock" =>trim($_POST["stock"]), "marca" =>trim($_POST["marca"]), "categoria" =>trim($_POST["categoria"]), "descuento" =>trim($_POST["descuento"]) ]; /*** * */ $requisitos = [ "id"=>[ MINSIZE=>1, SOLONUMEROS, Positivo, PRODUCTO ], "nombre"=>[ MINSIZE=>2, MAXSIZE => 30 ], "descripcion" => [ MAXSIZE => 10000 ], "precio" => [ MINSIZE => 1, PositivoFloat ], "stock" => [ MINSIZE => 1, SOLONUMEROS, Positivo, ], "marca" => [ MINSIZE => 1, SOLONUMEROS, Positivo, Marca ], "categoria" => [ MINSIZE => 1, SOLONUMEROS, Positivo, Categoria ], "descuento" => [ MINSIZE => 1, Descuento ] ]; /** * * */ if($_FILES){ $errorArchivo=( validarArchivo($_FILES["img"]) ); } /** * */ $errores = hacerValidaciones($datos, $requisitos); if($errorArchivo){ $errores["img"]=$errorArchivo; }else{ if($_FILES["img"]["name"]!="" && $_FILES){ $img=Producto::guardarArchivo($_FILES["img"],$_POST["nombre"]); }else{ $img=$_POST["imagenActual"]; } } /** * */ //var_dump($_POST); //var_dump($_FILES); /** * */ if(!$errores){ $producto->modificarProducto($datos["id"],$img,$datos); $unProducto=new Producto(); $unProducto=$producto->buscarPorId($datos["id"]); $msj="success"; }else{ $datos["img"]=$img; //var_dump($datos); foreach ($datos as $key => $value) { $valorPersistencia[$key]=persistirDatoGeneral($errores,$key,$datos); } $unProducto=new Producto(); $unProducto->setId($valorPersistencia["id"]); $unProducto->setNombre($valorPersistencia["nombre"]); $unProducto->setDescripcion($valorPersistencia["descripcion"]); $unProducto->setPrecio($valorPersistencia["precio"]); $unProducto->setStock($valorPersistencia["stock"]); $unProducto->setMarca($valorPersistencia["marca"]); $unProducto->setCategoria($valorPersistencia["categoria"]); $unProducto->setDescuento($valorPersistencia["descuento"]); $unProducto->setImg($valorPersistencia["img"]); //var_dump($valorPersistencia); $msj="danger"; } /** * */ /** * esta aqui nuevo */ $id= ((int)$_POST["id"]);//de alguna manera le tiene que llegar un id //$producto->modificarProducto($id,$img,$datos); //$msj="success"; //$unProducto=$producto->buscarPorId($id); } ?> <!DOCTYPE html> <html lang="en" dir="ltr"> <?php include 'includes/head.php';?> <title>ABM Productos</title> <body> <?php include 'includes/headerAdm.php'; ?> <main> <div class="container-fluir my-3"> <div id="accordion"> <div class="card"> <div class="card-header " id="headingFour"> <h5 class=" mb-0 d-flex justify-content-between align-items-center"> <button class="btn btn-link mr-3 collapsed" data-toggle="collapse" data-target="#collapseFour" aria-expanded="false" aria-controls="collapseFour"> Modificar Producto </button> <p class="btn alert alert-<?=$msj;?>" role="alert"> <?php if($msj=="success"){ echo("Producto se agregada correctamente."); } if($msj=="danger"){ echo("No se pudo modificar el Producto"); } if($msj=="warning"){ echo("No se encuentra el Producto a Eliminar"); } ?> </p> <a href="abmProducto.php" class=" btn btn-primary ml-3 ">Volver a principal</a> </h5> </div> <div id="collapseFour" class="collapse carrito-resumen" aria-labelledby="headingFour" data-parent="#accordion"> <div class="card-body "> <form class="modificarProducto" action="" method="post" enctype="multipart/form-data"> <input type="number" class="form-control" id="id" name="id" value="<?=$unProducto->getId();?>" readonly hidden> <div class="form-group"> <label for="nombre">Nombre</label> <input type="text" class="form-control" id="nombre" name="nombre" value="<?=$unProducto->getNombre();?>"> <small class="text-danger"><?=(isset($errores))?mostrarErroresPerfil($errores,"nombre"):""; ?></small> </div> <div class="form-group"> <label for="descripcion">Descripcion</label> <pre> <textarea class="form-control" id="descripcion" rows="8" cols="80" name="descripcion" ><?=$unProducto->getDescripcion();?></textarea> </pre> <small class="text-danger"><?=(isset($errores))?mostrarErroresPerfil($errores,"descripcion"):""; ?></small> </div> <div class="form-group"> <label for="precio">Precio:</label> <input type="text" class="form-control" id="precio" name="precio" value="<?=$unProducto->getPrecio();?>"> <small class="text-danger"><?=(isset($errores))?mostrarErroresPerfil($errores,"precio"):""; ?></small> </div> <div class="form-group"> <label for="stock">stock</label> <input type="number" class="form-control" id="stock" name="stock" min="1" value="<?=$unProducto->getStock();?>"> <small class="text-danger"><?=(isset($errores))?mostrarErroresPerfil($errores,"stock"):""; ?></small> </div> <div class="form-group"> <label for="marca">Marca</label> <select class="form-control" id="marca" name="marca"> <?php $marcas=$marca->listarMarcas(); foreach ($marcas as $key => $value) { ?> <?php if ($unProducto->getMarca()==$value["marca"]) {?> <option value="<?=$value["id_marca"];?>" selected><?=$value["marca"];?></option> <?php }else{?> <option value="<?=$value["id_marca"];?>"><?=$value["marca"];?></option> <?php } ?> <?php } ?> </select> <small class="text-danger"><?=(isset($errores))?mostrarErroresPerfil($errores,"marca"):""; ?></small> </div> <div class="form-group"> <label for="categoria">Categoria</label> <select class="form-control" id="categoria" name="categoria"> <?php $categorias=$categoria->listarcategorias(); foreach ($categorias as $key => $value) { ?> <?php if($unProducto->getCategoria()==$value["categoria"]){ ?> <option value="<?=$value["id_categoria"];?>" selected><?=$value["categoria"];?></option> <?php }else{ ?> <option value="<?=$value["id_categoria"];?>" ><?=$value["categoria"];?></option> <?php } ?> <?php } ?> </select> <small class="text-danger"><?=(isset($errores))?mostrarErroresPerfil($errores,"categoria"):""; ?></small> </div> <div class="form-group"> <label for="descuento">descuento</label> <input type="text" class="form-control" id="descuento" name="descuento" min="1" max="100" value="<?=$unProducto->getDescuento();?>"> <small class="text-danger"><?=(isset($errores))?mostrarErroresPerfil($errores,"descuento"):""; ?></small> </div> <div class="form-group text-center"> <label for="img" class="col-12">Imagen</label> <img src="<?=$unProducto->getImg();?>" alt="" sizes="" width="80%" class="col-3" height=""> <input type="text" name="imagenActual" value="<?=$unProducto->getImg();?>" readonly hidden> <label for="img" class="text-left col-12">Cambiar</label> <input type="file" class="form-control-file" id="img" name="img" class=""> <small class="text-danger"><?=(isset($errores))?mostrarErroresPerfil($errores,"img"):""; ?></small> </div> <button type="submit" class="btn btn-primary mb-2" name="modificar_id" value="">Modificar</button> </form> </div> </div> </div> </div> </div> </main> <?php include 'includes/footer.php'; include 'includes/scriptBootstrap.php'; ?> </body> </html> <file_sep>/DER e-Commerce/e_commerce/e-commerce_detalle_de_productos.sql CREATE DATABASE IF NOT EXISTS `e-commerce` /*!40100 DEFAULT CHARACTER SET utf8mb4 */; USE `e-commerce`; -- MySQL dump 10.13 Distrib 5.6.17, for Win32 (x86) -- -- Host: 127.0.0.1 Database: e-commerce -- ------------------------------------------------------ -- Server version 5.5.5-10.4.8-MariaDB /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; /*!40103 SET TIME_ZONE='+00:00' */; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; -- -- Table structure for table `detalle_de_productos` -- DROP TABLE IF EXISTS `detalle_de_productos`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `detalle_de_productos` ( `id_detalle_de_Producto` int(11) NOT NULL AUTO_INCREMENT, `idcarrito` int(11) NOT NULL, `idproducto` int(11) NOT NULL, `id_estado_producto` int(11) NOT NULL, `cantidad` int(11) NOT NULL, PRIMARY KEY (`id_detalle_de_Producto`), UNIQUE KEY `id_detalle_de_Producto_UNIQUE` (`id_detalle_de_Producto`), KEY `idcarrito_idx` (`idcarrito`), KEY `idproducto_idx` (`idproducto`), KEY `id_estado_producto_idx` (`id_estado_producto`), CONSTRAINT `id_estado_producto` FOREIGN KEY (`id_estado_producto`) REFERENCES `estado_producto` (`id_estado_producto`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `idcarrito` FOREIGN KEY (`idcarrito`) REFERENCES `carritos` (`id_carrito`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `idproducto` FOREIGN KEY (`idproducto`) REFERENCES `productos` (`id_producto`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `detalle_de_productos` -- LOCK TABLES `detalle_de_productos` WRITE; /*!40000 ALTER TABLE `detalle_de_productos` DISABLE KEYS */; /*!40000 ALTER TABLE `detalle_de_productos` ENABLE KEYS */; UNLOCK TABLES; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!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 */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; -- Dump completed on 2020-01-29 20:50:00 <file_sep>/clases/Marca.php <?php class Marca { private $id_marca; private $marca; public function listarMarcas() { $link = Conexion::conectar(); try{ $sql = "SELECT id_marca, marca FROM marcas"; $stmt = $link->prepare($sql); $stmt->execute(); $resultado = $stmt->fetchAll(PDO::FETCH_ASSOC); return $resultado; } catch (\Exception $e) { echo "Error al obtener Lista de Marcas"; $e->getMessage(); } } public function verMarcaPorID($id_marca) { try{ $link = Conexion::conectar(); $sql = "SELECT * FROM marcas WHERE id_marca='$id_marca'"; $stmt = $link->prepare($sql); $stmt->execute(); $resultado = $stmt->fetch(PDO::FETCH_ASSOC); return $resultado; } catch(\PDOException $e){ return null; } catch(\PDOStatement $e){ return null; } catch (\Exception $e) { die($e->getMessage()); return null; } } public function agregarMarca() { $marca = $_POST['marca']; $link = Conexion::conectar(); $sql = "INSERT INTO marcas VALUES ( default, :marca )"; $stmt = $link->prepare($sql); $stmt->bindParam(':marca', $marca, PDO::PARAM_STR); if( $stmt->execute() ){ $this->setid_marca($link->lastInsertId()); $this->setmarca($marca); return true; } return false; } public function modificarMarca() { $id = $_POST['id_marca']; $marca = $_POST['marca']; $link = Conexion::conectar(); $sql = "UPDATE marcas SET marca='$marca' WHERE id_marca='$id'"; $stmt = $link->prepare($sql); if( $stmt->execute() ){ $this->setid_marca($link->lastInsertId()); $this->setmarca($marca); return true; } return false; } public function eliminarMarca() { try { $id = $_REQUEST['id']; $link = Conexion::conectar(); $sql = "DELETE FROM marcas WHERE id_marca=?"; $stmt = $link->prepare($sql); if( $stmt->execute(array($id)) ){ // $this->setid_marca($link->lastInsertId()); // $this->setmarca($marca); } } catch(\PDOException $e){ return False; } catch(\PDOStatement $e){ return False; } catch (\Exception $e) { die($e->getMessage()); return false; } return true; } /** * @return mixed */ public function getId_marca() { return $this->id_marca; } /** * @param mixed $id_marca */ public function setId_marca($id_marca) { $this->id_marca = $id_marca; } /** * @return mixed */ public function getMarca() { return $this->marca; } /** * @param mixed $marca */ public function setMarca($marca) { $this->marca = $marca; } } <file_sep>/clases/Usuario.php <?php class Usuario{ protected $id; protected $usuario; protected $nombre; protected $apellido; protected $email; protected $contrasenia; protected $estado; public function cambiarEmail(){ } public function cambiarContraseña(){ } /** * Get the value of id */ public function getId():int { return $this->id; } /** * Set the value of id * * @return self */ public function setId($id) { $this->id = $id; return $this; } /** * Get the value of usuario */ public function getUsuario():string { return $this->usuario; } /** * Set the value of usuario * * @return self */ public function setUsuario($usuario) { $this->usuario = $usuario; return $this; } /** * Get the value of nombre */ public function getNombre():string { return $this->nombre; } /** * Set the value of nombre * * @return self */ public function setNombre($nombre) { $this->nombre = $nombre; return $this; } /** * Get the value of apellido */ public function getApellido():string { return $this->apellido; } /** * Set the value of apellido * * @return self */ public function setApellido($apellido) { $this->apellido = $apellido; return $this; } /** * Get the value of email */ public function getEmail():string { return $this->email; } /** * Get the value of estado */ public function getEstado():string { return $this->estado; } /** * Set the value of estado * * @return self */ public function setEstado($estado) { $this->estado = $estado; return $this; } } ?><file_sep>/modificarCategoria.php <?php require_once('clases/Conexion.php'); require 'clases/Categoria.php'; $objCategoria= new Categoria; if(isset($_REQUEST['id_categoria'])){ $chequeo = $objCategoria->modificarCategoria(); } include 'includes/head.php'; include 'includes/headerAdm.php'; ?> <main class="container"> <h1>Actualizacion de una Categoria</h1> <?php $mensaje = 'No se pudo actualizar la Categoria'; $class = 'danger'; if( $chequeo ){ $mensaje = 'Categoria: '.$objCategoria->getCategoria(); $mensaje .= ' se actualizo!.'; $class = 'success'; } ?> <div class="alert alert-<?= $class; ?>"> <?= $mensaje; ?> </div> <a href="abmCategoria.php" class="btn btn-light">Volver a admin de Categorias</a> </main> <?php include 'includes/footer.php'; ?><file_sep>/includes/navBar.php <div class="row"> <div class="col-12"> <ul class="breadcrumb"> <li><a href="home.html">Home</a> <span class="divider">/</span></li> <li><a href="products.html">Products</a> <span class="divider">/</span></li> <li class="active">Product Details</li> </ul> </div> </div> <file_sep>/clases/Producto.php <?php /** * */ class Producto { private $id; private $nombre; private $descripcion; private $precio; private $stock; private $marca; private $categoria; private $descuento; private $img; public function altaProducto(string $img,$array=null) { if(is_null($array)){ $array=$_POST; } $db=Conexion::conectar(); $nombre = $array["nombre"]; $desc = $array["descripcion"]; $precio= $array["precio"]; $stock = $array["stock"]; $marca = $array["marca"]; $categoria = $array["categoria"]; $descuento = $array["descuento"]; try{ $statement = $db->prepare("INSERT into productos(id_marca,id_categoria,nombre,descripcion,precio,cantidad,img,descuento) VALUES ( :idMarca, :idCategoria,:nombre, :descripcion, :precio, :cantidad, :img,:descuento)"); $statement->bindValue(':idMarca', $marca,PDO::PARAM_INT); $statement->bindValue(":idCategoria", $categoria,PDO::PARAM_INT); $statement->bindValue(":nombre", $nombre,PDO::PARAM_STR); $statement->bindValue(":descripcion", $desc,PDO::PARAM_STR); $statement->bindValue(":precio", $precio); $statement->bindValue(":cantidad", $stock,PDO::PARAM_INT); $statement->bindValue(":img", $img,PDO::PARAM_STR); $statement->bindValue(":descuento", $descuento); $statement->execute(); $statement->closeCursor(); }catch (\Exception $e) { echo "Error al cargar poducto"; $e->getMessage(); } } public function modificarProducto(int $id,string $img,$array=null) { if(is_null($array)){ $array=$_POST; } try { $db=Conexion::conectar(); $nombre = $array["nombre"]; $desc = $array["descripcion"]; $precio= $array["precio"]; $stock = $array["stock"]; $marca = $array["marca"]; $categoria = $array["categoria"]; $descuento = $array["descuento"]; $sql="UPDATE productos SET nombre=:nombre, descripcion=:descripcion, precio=:precio, cantidad=:cantidad, img=:img, descuento=:descuento, id_marca=:idMarca, id_categoria=:idCategoria WHERE id_producto =:id"; $statement = $db->prepare($sql); $statement->bindValue(":nombre", $nombre,PDO::PARAM_STR); $statement->bindValue(":descripcion", $desc); $statement->bindValue(":precio", $precio); $statement->bindValue(":cantidad", $stock,PDO::PARAM_INT); $statement->bindValue(":img", $img,PDO::PARAM_STR); $statement->bindValue(":descuento", $descuento); $statement->bindValue(':idMarca', $marca,PDO::PARAM_INT); $statement->bindValue(":idCategoria", $categoria,PDO::PARAM_INT); $statement->bindValue(':id', $id,PDO::PARAM_INT); $statement->execute(); } catch(\PDOException $e){ die($e->getMessage()); return False; } catch (\Exception $e) { die($e->getMessage()); return false; } return true; } public function borrarProducto($id) { $db=Conexion::conectar(); try { $statement = $db->prepare("DELETE FROM productos WHERE id_producto = :id"); $statement->bindValue(":id", $id); $statement->execute(); } catch(\PDOException $e){ return False; } catch (\Exception $e) { die($e->getMessage()); return false; } return true; } static function guardarArchivo($file,$nombre="text"){ if($file["name"]!=""){ $nombreArchivo=$file["name"]; $archivo=$file["tmp_name"]; $ext=pathinfo($nombreArchivo,PATHINFO_EXTENSION); $miArchivo="img/productos/".$nombre; //ruta actual $nombre="phone".uniqid(); if (!file_exists($miArchivo)) { mkdir($miArchivo, 0777, true); } $directorio = opendir($miArchivo); $cont=0; $archivoEliminar=""; while ($archivoDir = readdir($directorio)) //obtenemos un archivo y luego otro sucesivamente { if (!is_dir($archivoDir))//verificamos si es o no un directorio { //var_dump ($archivoDir ); if(preg_match("/phone/i" ,$archivoDir)){//encuentra un archivo que coincida con el patron $cont++; $archivoEliminar=$archivoDir; } } } if($cont>1){ unlink($miArchivo."/".$archivoEliminar); } $miArchivo=$miArchivo."/".$nombre.".".$ext; move_uploaded_file($archivo,$miArchivo); return $miArchivo; } return null; } public function buscarPorId(int $id){ $db=Conexion::conectar(); if(isset($_POST["id"])){ $id=(int)$_POST["id"]; } try { $sql = "SELECT id_producto as id,nombre,descripcion,precio,cantidad as stock,marca,categoria,descuento,img FROM productos as p inner join categorias as c on p.id_categoria=c.id_categoria inner join marcas as m on p.id_marca=m.id_marca WHERE id_producto= :id"; $seleccionado=$db->prepare($sql); $seleccionado->bindValue(":id", $id,PDO::PARAM_INT); $seleccionado->execute(); $variable = $seleccionado->fetchObject("Producto");//objeto }catch(\PDOException $e){ die($e->getMessage()); return null; } catch (\Exception $e) { $e->getMessage(); return null; } return $variable; } public function obtenerListaProductos(){ $db=Conexion::conectar(); try { $sql = "SELECT id_producto as id,nombre,descripcion,precio,cantidad as stock,marca,categoria,descuento,img FROM productos as p inner join categorias as c on p.id_categoria=c.id_categoria inner join marcas as m on p.id_marca=m.id_marca"; $stmt = $db->prepare($sql); $stmt->execute(); //$variable = $stmt->fetchAll(PDO::FETCH_ASSOC);//array asociado $variable = $stmt->fetchAll(PDO::FETCH_CLASS,"Producto");//objeto $stmt->closeCursor(); return $variable; } catch (\Exception $e) { echo "Error al obtener Lista de Productos"; $e->getMessage(); return false; } } function buscarMarca(PDO $db) { $nombre="%".$_GET["buscador"]."%"; try { $statement = $db->prepare("SELECT nombre FROM marcas WHERE nombre LIKE :nombre"); $statement->bindValue(":nombre",$nombre); $statement->execute(); $variable=$statement->fetchAll(PDO::FETCH_ASSOC); return $variable; } catch (\Exception $e) { $e->getMessage(); return false; } } /** * Get the value of id */ public function getId():int { return $this->id; } /** * Set the value of id * * @return self */ public function setId($id) { $this->id = $id; return $this; } /** * Get the value of nombre */ public function getNombre():string { return $this->nombre; } /** * Set the value of nombre * * @return self */ public function setNombre($nombre) { $this->nombre = $nombre; return $this; } /** * Get the value of descripcion */ public function getDescripcion():string { return $this->descripcion; } /** * Set the value of descripcion * * @return self */ public function setDescripcion($descripcion) { $this->descripcion = $descripcion; return $this; } /** * Get the value of stock */ public function getStock():int { return $this->stock; } /** * Set the value of stock * * @return self */ public function setStock($stock) { $this->stock = $stock; return $this; } /** * Get the value of marca */ public function getMarca():string { return $this->marca; } /** * Set the value of marca * * @return self */ public function setMarca($marca) { $this->marca = $marca; return $this; } /** * Get the value of categoria */ public function getCategoria():string { return $this->categoria; } /** * Set the value of categoria * * @return self */ public function setCategoria($categoria) { $this->categoria = $categoria; return $this; } /** * Get the value of descuento */ public function getDescuento():float { return $this->descuento; } /** * Set the value of descuento * * @return self */ public function setDescuento($descuento) { $this->descuento =(float)$descuento; return $this; } /** * Get the value of img */ public function getImg():string { return $this->img; } /** * Set the value of img * * @return self */ public function setImg($img) { $this->img = $img; return $this; } /** * Get the value of precio */ public function getPrecio():float { return $this->precio; } /** * Set the value of precio * * @return self */ public function setPrecio($precio) { $this->precio =(float) $precio; return $this; } } ?> <file_sep>/includes/header.php <!--Comienzo del header--> <header class="container-fluir fixed-top"> <!--Comienza el nav--> <nav class="navbar navbar-expand-lg navbar-dark bg-dark barra"> <!--Comienza el nombre de la empresa--> <a class="navbar-brand" href="home.php"> <img src="img/e-com1.png" width="30" height="30" class="d-inline-block align-top logo" alt=""> <span>E-commerce</span> </a> <!--Fin el nombre de la empresa--> <!--Comienza el buscador--> <form class=" d-md-inline-block form-inline mx-auto my-2 my-md-0"> <div class="input-group"> <input type="text" class="form-control" placeholder="Buscar producto...." aria-label="Search" aria-describedby="basic-addon2"> <div class="input-group-append"> <button class="btn btn-primary" type="button"> <img src="img/lupa.png" width="20" height="20" class="d-inline-block align-top" alt=""> </button> </div> </div> </form> <!--fin el buscador--> <!--Comienza del menu comprimido--> <button class="navbar-toggler col-12 col-sm-3" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span>Menu</span> <span class="navbar-toggler-icon"></span> </button> <!--Comienza el menu descomprimido--> <div class="collapse navbar-collapse " id="navbarNav"> <ul class="navbar-nav ml-md-auto"> <li class="nav-item "> <a class="nav-link" href="home.php">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <!--Comienza el categoria--> <div class="dropdown"> <a class="nav-link dropdown-toggle " href="#" role="button" id="dropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Celulares </a> <!--Comienza el menu desplegable de categoria--> <div class="dropdown-menu bg-dark py-0 mt-2 sub-menu-categoria" aria-labelledby="dropdownMenuLink"> <ul class="px-0"> <li class="py-0 px-0 dropdown-item li-marca "><a class=" ml-md-auto text-decoration-none d-block py-2 px-2 marca" href="#">Motorola</a></li> <li class="py-0 px-0 dropdown-item li-marca "><a class=" ml-md-auto text-decoration-none d-block py-2 px-2 marca" href="#">Samsung</a></li> <li class="py-0 px-0 dropdown-item li-marca "><a class=" ml-md-auto text-decoration-none d-block py-2 px-2 marca" href="#">LG</a></li> <li class="py-0 px-0 dropdown-item li-marca "><a class=" ml-md-auto text-decoration-none d-block py-2 px-2 marca" href="#">Apple</a></li> <li class="py-0 px-0 dropdown-item li-marca "><a class=" ml-md-auto text-decoration-none d-block py-2 px-2 marca" href="#">Nokia</a></li> </ul> </div> <!--fin el menu desplegable de categoria--> </div> <!--Fin categoria--> </li> <li class="nav-item"> <a class="nav-link btn btn-primary" href="login.php">ingresar</a> </li> <li class="nav-item"> <a class="nav-link" href="registro.php">registrarse</a> </li> <li class="nav-item"> <a class="nav-link" href="faq.php">ayuda</a> </li> <li class="nav-item"> <!-- Trigger modal --> <a class="nav-link" href="#summary" role="button" data-toggle="modal" data-target="#exampleModalScrollable"> <span>carrito</span> <img src="img/car.png" width="20" height="20" class="d-inline-block align-top " alt=""> </a> </li> </ul> </div> <!--fin el menu descomprimido--> <!--Comienza del menu comprimido--> </nav> </header> <!--Fin del header--> <file_sep>/modificarMarca.php <?php require 'clases/Conexion.php'; require 'clases/Marca.php'; $objMarca = new Marca; if(isset($_REQUEST['id_marca'])){ $chequeo = $objMarca->modificarMarca(); } include 'includes/head.php'; include 'includes/headerAdm.php'; ?> <main class="container"> <h1>Actualizacion de una Marca</h1> <?php $mensaje = 'No se pudo actualizar la Marca'; $class = 'danger'; if( $chequeo ){ $mensaje = 'Marca: '.$objMarca->getMarca(); $mensaje .= ' se actualizo!.'; $class = 'success'; } ?> <div class="alert alert-<?= $class; ?>"> <?= $mensaje; ?> </div> <a href="abmMarca.php" class="btn btn-light">Volver a admin de marcas</a> </main> <?php include 'includes/footer.php'; ?><file_sep>/clases/Factura.php <?php class Factura{ private $id; private $tipoFactura; private $direccion; private $tarjeta; private $envios; private $nroFactura; private $fecha; private $productos; private $total; private $usuario; /** * Get the value of id */ public function getId() { return $this->id; } /** * Set the value of id * * @return self */ public function setId($id) { $this->id = $id; return $this; } /** * Get the value of nroFactura */ public function getNroFactura() { return $this->nroFactura; } /** * Set the value of nroFactura * * @return self */ public function setNroFactura($nroFactura) { $this->nroFactura = $nroFactura; return $this; } /** * Get the value of fecha */ public function getFecha() { return $this->fecha; } /** * Set the value of fecha * * @return self */ public function setFecha($fecha) { $this->fecha = $fecha; return $this; } /** * Get the value of productos */ public function getProductos() { return $this->productos; } /** * Set the value of productos * * @return self */ public function setProductos($productos) { $this->productos = $productos; return $this; } /** * Get the value of total */ public function getTotal() { return $this->total; } /** * Set the value of total * * @return self */ public function setTotal($total) { $this->total = $total; return $this; } /** * Get the value of tipoFactura */ public function getTipoFactura() { return $this->tipoFactura; } /** * Set the value of tipoFactura * * @return self */ public function setTipoFactura($tipoFactura) { $this->tipoFactura = $tipoFactura; return $this; } /** * Get the value of direccion */ public function getDireccion() { return $this->direccion; } /** * Set the value of direccion * * @return self */ public function setDireccion($direccion) { $this->direccion = $direccion; return $this; } /** * Get the value of tarjeta */ public function getTarjeta() { return $this->tarjeta; } /** * Set the value of tarjeta * * @return self */ public function setTarjeta($tarjeta) { $this->tarjeta = $tarjeta; return $this; } /** * Get the value of envios */ public function getEnvios() { return $this->envios; } /** * Set the value of envios * * @return self */ public function setEnvios($envios) { $this->envios = $envios; return $this; } /** * Get the value of usuario */ public function getUsuario() { return $this->usuario; } /** * Set the value of usuario * * @return self */ public function setUsuario($usuario) { $this->usuario = $usuario; return $this; } } ?><file_sep>/logOut.php <?php session_start(); session_destroy(); setcookie("usuario",null,time()-1); setcookie("clave",null,time()-1); setcookie("email",null,time()-1); header("Location: login.php");exit; ?><file_sep>/css/stylePerfilSeguridadResumen.css @import "body.css"; @import "header.css"; @import "footer.css"; /* .main-perfil, main{ */ body{ display: flex; flex-direction: column; align-content: space-between; justify-content: space-between; } .main-perfil{ background-size: initial; } footer{ width: 100% !important; align-self:flex-end !important; } .img-perfil .contenedor-perfil { border-radius: 100%; height: inherit; } .img-perfil .contenedor-perfil img { height: inherit; width: 100%; border-radius: 100%; border: 2px solid silver; } .usuario{ background-color: #FFFFFF; border-radius: 20px; border: 1px solid rgba(0, 0, 0, 0.3); /* box-shadow:0px 6px 30px 10px dimgray inset; transform: rotate(7deg);*/ } .menu-left ul{ box-shadow: 0px 6px 10px #021422; transition: all .6s; } .menu-left ul:hover{ position: relative; bottom:5px; } .menu-left li{ padding: 0; } .menu-left ul li a{ padding: .75rem 1.25rem; display: block; text-decoration: none; } .menu-left ul li a:hover{ border-left: solid blue 4px; } .conf div ul{ padding: 0; margin-top:5px; } .conf div ul li{ list-style: none; } .conf div ul li a{ display: block; text-decoration:none; padding: .75rem 1.25rem; margin-bottom: -1px; background-color: #fff; border-top: 1px solid rgba(0,0,0,.125); border-bottom: 1px solid rgba(0,0,0,.125); } .img-perfil{ width: 300px; height: 300px; position: relative; } .img-perfil a{ background-color: rgba(0,0,0,45%); color: snow; text-align: center; position:absolute; top: auto; z-index: 1000; text-decoration: none; } .boton-efecto{ margin-left:4vw; margin-right: 4vw; background-image: linear-gradient(to top,rgb(134, 131, 131,0.2),rgba(7, 5, 5, 0.637)); box-shadow: 0px 6px 10px #01070c; transition: all .6s; } .boton-efecto:hover,.boton-efecto:focus{ position: relative; bottom: 2px; } .resumen{ background-color: #FFFFFF; border-radius: 20px; border: 1px solid rgba(0, 0, 0, 0.3); } .carrito-resumen{ padding: 5px; height:500px; border: 1px solid rgba(0, 0, 0, 0.3); overflow: scroll; } .resumen .factura{ overflow: scroll; display: flex; flex-direction: row; justify-content: space-around; flex-wrap: wrap; height:200px; } .resumen .factura div{ display: flex; flex-direction: row; justify-content: space-around; flex-wrap: wrap; } .resumen .factura div div{ border-bottom: solid black 1px; } .factura{ border: black solid 1px; padding:0px; } .seguridad{ padding: 20px; } .seguridad .informacion{ padding: 10px 30px; } .form-clave , .form-mail{ margin-left: 20px; margin-right: 20px; padding:12px; border-radius:2px; border: rgba(76, 72, 72, 0.747) solid 1px; } .form-mail .form-group span,.form-clave .form-group span{ margin-top: 10px; } .form-clave{ } .irDescripcion{ text-decoration: none; color: inherit; } .irDescripcion:hover{ text-decoration-line: none; color: inherit; } .zoom{ /* Aumentamos la anchura y altura durante 2 segundos */ transition: width 2s, height 2s, transform 2s; -moz-transition: width 2s, height 2s, -moz-transform 2s; -webkit-transition: width 2s, height 2s, -webkit-transform 2s; -o-transition: width 2s, height 2s,-o-transform 2s; } .zoom:hover{ /* tranformamos el elemento al pasar el mouse por encima al doble de su tamaño con scale(2). */ transform : scale(2); -moz-transform : scale(2); /* Firefox */ -webkit-transform : scale(2); /* Chrome - Safari */ -o-transform : scale(2); /* Opera */ } @media (max-width: 470.98px) { .container{ margin-top: 16vh; } .resumen .factura{ overflow: scroll; display: flex; flex-direction: column; justify-content: space-around; flex-wrap: wrap; height:200px; } .resumen .factura div{ padding: 5px auto; border: #343a40 solid 1px; } .resumen .factura div div{ padding: 6px; border-bottom: solid black 1px; } .resumen .factura div div p{ margin: 0; } } @media (max-width: 457.8px) { .container{ margin-top: 160px; } .resumen .factura div{ border: #343a40 solid 1px; } .resumen .factura{ overflow: scroll; display: flex; justify-content: stretch; align-items: stretch; flex-wrap: wrap; height:240px; } .resumen .factura div{ width: 300px; padding: 0; display: flex; flex-direction: column; justify-content: space-around; flex-wrap: wrap; border: #343a40 solid 1px; } .resumen .factura div div{ padding: 6px 0; text-align: center; border-bottom: solid black 1px; } .resumen .factura div div:last-child{ height: 70px; } } @media (min-width: 458px) and (max-width: 599.98px) { .container{ margin-top: 158px; } .resumen .factura div{ border: #343a40 solid 1px; } .resumen .factura{ overflow: scroll; display: flex; flex-direction: column; justify-content: stretch; align-items: stretch; flex-wrap: wrap; height:240px; } .resumen .factura div{ display: flex; flex-direction: column; justify-content: space-around; flex-wrap: wrap; } .resumen .factura div div{ padding: 6px 0; text-align: center; border-bottom: solid black 1px; } .resumen .factura div div:last-child{ height: 70px; } } @media (min-width: 600px) and (max-width: 767.98px) { .container{ margin-top: 119px; } } @media (min-width: 768px) and (max-width: 991.98px) { .container{ margin-top: 70px; } } @media (min-width: 992px) and (max-width:1199.98px) { .container{ margin-top: 72px; } } @media(min-height:900px){ body{ } } @media(min-width: 1200px){ body{ height:100vh; } .main-perfil{ background-size: cover; } .container{ margin-top:70px; min-width: 70vw !important; max-width: 80vw !important; align-self: center; } main{ min-width: 80vw !important; max-width: 90vw !important; align-self: center; } }<file_sep>/includes/headPerfil.php <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600|Roboto:500,700&display=swap" rel="stylesheet"> <link rel="shortcut icon" href="favicon.ico"/> <!--Iconos de pestania--> <link rel="apple-touch-icon" sizes="180x180" href="img/pestania-ico/apple-touch-icon.png"> <link rel="icon" type="image/png" sizes="32x32" href="img/pestania-ico/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="16x16" href="img/pestania-ico/favicon-16x16.png"> <link rel="manifest" href="img/pestania-ico/site.webmanifest"> <link rel="mask-icon" href="img/pestania-ico/safari-pinned-tab.svg" color="#5bbad5"> <meta name="msapplication-TileColor" content="#da532c"> <!--Iconos de pestania--> <!--cambia la barra de pestaña de moviles de androi--> <meta name="theme-color" content="#4285f4"> <!--cambia la barra de pestaña de moviles de androi--> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"><file_sep>/includes/funciones.php <?php require_once "./includes/validaciones.php"; require_once "./includes/fileManager.php"; require_once "./includes/userManager.php"; ?><file_sep>/faq.php <?php session_start(); include_once("includes/funciones.php"); include_once("includes/baseDeDatos.php"); $pagina="Descriccion de Producto"; //$pagina_anterior=$_SERVER['HTTP_REFERER'];//pagina anterior if(isset($_SESSION["activeUser"]) && !is_null($_SESSION["activeUser"])){ if($_SESSION["activeUser"]["fotoPerfil"]==""){ $_SESSION["activeUser"]["fotoPerfil"]=(isset($imagenUsuario))?$imagenUsuario:"img/perfil.png"; } $activeUser=$_SESSION["activeUser"]; } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <link rel="stylesheet" href="css/styles.css"> <title>E-commerce</title> <link rel="shortcut icon" href="favicon.ico"/> </head> <body class="main-perfil"> <!--Comienza el header--> <header class="container-fluir fixed-top"> <?php include_once("includes/headerPerfil.php"); ?> </header> <!--Fin el header--> <main class=""> <div class="inner-main"> <?php include_once "includes/navBar.php" ?> <h1 class="faq-h1">Preguntas frecuentes</h1> <div class="accordion" id="accordionFaq"> <div class="card"> <div class="card-header" id="headingOne"> <h2 class="mb-0"> <button class="btn btn-link" type="button" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne"> Cómo devolver un producto </button> </h2> </div> <div id="collapseOne" class="collapse" aria-labelledby="headingOne" data-parent="#accordionFaq"> <div class="card-body"> <div class="content__data"><h2>1. Pedí la devolución del producto</h2> <p dir="ltr">Para devolver un producto, <strong>buscá la opción “Devolver o cambiar gratis”</strong> que aparece en el menú de la compra que ya no querés y seguí los pasos. Te vamos a dar una etiqueta de devolución gratis para que envíes el producto de vuelta. Según la información que tengamos sobre la devolución, a veces te vamos a pedir que hables con el vendedor antes de tener la etiqueta.</p> <p dir="ltr">También vas a tener que hablar con el vendedor si al comprar acordaste la entrega con él. Sin embargo, en esos casos no te vamos a dar una etiqueta, sino que tendrán que ponerse de acuerdo sobre cómo continuar.</p> <h2 dir="ltr">2. Prepará el paquete para enviarlo</h2> <p dir="ltr">Antes de preparar el paquete, revisá que el producto esté en las mismas condiciones que lo recibiste, sin usar y con todos sus accesorios y etiquetas.</p> <ul> <li dir="ltr"> <p dir="ltr">Guardá el producto en su envoltorio original o en uno alternativo si no lo tenés.&nbsp;</p> </li> <li dir="ltr"> <p dir="ltr">Embalá el producto. Si es frágil, utilizá un embalaje seguro que lo proteja.&nbsp;</p> </li> <li dir="ltr"> <p dir="ltr">Imprimí la etiqueta de devolución y pegala en el paquete.</p> </li> <li dir="ltr"> <p dir="ltr">Entregá el paquete al correo.</p> </li> </ul> <p dir="ltr">Si compraste más de una unidad del mismo producto, tenés que devolver todos los artículos para recuperar tu dinero.</p> <h2 dir="ltr">3. Recibí el reembolso del dinero</h2> <p dir="ltr">En la mayoría de los casos, <strong>hacemos los reembolsos cuando el correo nos avisa que entregaste el producto</strong>.&nbsp;</p> <p dir="ltr">Sin embargo, <strong>a veces hacemos el reembolso después de que el paquete le llega al vendedor</strong> y nos confirma que está bien, para asegurarnos de que no hubo ningún problema.&nbsp;</p> <p dir="ltr">Si querés saber cuánto tardará en acreditarse tu reembolso, podés consultar <a href="https://www.mercadolibre.com.ar/ayuda/5266">los tiempos de acreditación de cada medio de pago</a>.</p></div> </div> </div> </div> <div class="card"> <div class="card-header" id="headingOne2"> <h2 class="mb-0"> <button class="btn btn-link" type="button" data-toggle="collapse" data-target="#collapseOne2" aria-expanded="true" aria-controls="collapseOne2"> Cómo vender de manera segura </button> </h2> </div> <div id="collapseOne2" class="collapse" aria-labelledby="headingOne2" data-parent="#accordionFaq"> <div class="card-body"> <div class="content__data"><div class="wrap-content"> <p>¿Tuviste tu primera venta? Te damos algunos consejos para tener en cuenta si ya recibiste una oferta en tu publicación.</p> <h3>Presta atención si se comporta raro</h3> <p>Estate atento si:</p> <ul> <li>Está apurado o te pide que le envíes el producto antes de pagarte.</li> <li>Quiere llevarse cualquier producto si ya no tienes stock del que compró.</li> <li>Cambia de dirección o modo de envío.</li> <li>No te da un teléfono fijo donde puedas contactarlo.</li> <li>Los datos que te dio no coinciden con los que tiene en el sitio.</li> </ul> <h3>Toma la iniciativa</h3> <p>Si pasan unos días y no te contacta, llámalo tú para encaminar la venta.</p> </div></div> </div> </div> </div> <div class="card"> <div class="card-header" id="headingTwo"> <h2 class="mb-0"> <button class="btn btn-link collapsed" type="button" data-toggle="collapse" data-target="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo"> Cómo pagar tu compra </button> </h2> </div> <div id="collapseTwo" class="collapse" aria-labelledby="headingTwo" data-parent="#accordionFaq"> <div class="card-body"> <div id="cxMainContent" class="cx-main--content cx-main--content__grow ui-list__shadow-wrapper"><div class="content__data"><div class="wrap-content"> <p><strong>Pagá con Mercado Pago</strong> y tu compra <a href="https://www.mercadolibre.com.ar/ayuda/Compra_Protegida_986">va a estar 100% protegida</a>, si el producto no es lo que esperabas te devolvemos el dinero.</p> <p>Las reservas de vehículos y las contrataciones de servicios también se pagan con Mercado Pago. Así protegemos tu dinero hasta que nos confirmes que ya te entregaron el vehículo o te brindaron el servicio.</p> <p>Elegí&nbsp;entre cualquiera de estos medios de pago:</p> </div> <div class="wrap-content"> <div class="responsive-table"> <div class="column-fixed"> <table class="ch-datagrid table" summary="Cómo pagar tu compra"> <tbody> <tr> <td class="responsive-table-listing"> <ul> <li class="paymentmethod-visa">Visa</li> <li class="paymentmethod-master">Mastercard</li> <li class="paymentmethod-amex">American Express</li> <li class="paymentmethod-mercadopago_cc">Mercado Pago + Banco Patagonia</li> <li class="paymentmethod-naranja">Naranja</li> <li class="paymentmethod-argencard">Argencard</li> <li class="paymentmethod-cabal">Cabal</li> <li class="paymentmethod-cencosud">Cencosud</li> <li class="paymentmethod-nativa">Nativa</li> <li class="paymentmethod-tarshop">Tarjeta Shopping</li> <li class="paymentmethod-cordobesa">Cordobesa</li> <li class="paymentmethod-cmr">CMR</li> <li class="paymentmethod-cordial">Cordial</li> </ul> <p><strong>Tarjeta de crédito</strong>.</p> </td> <td class="responsive-table-exposition">Hasta <strong>12 cuotas sin interés</strong> con <a href="http://www.mercadolibre.com.ar/gz/promociones-bancos">promociones bancarias</a> <p><a title="Conoce los bancos o tarjetas con promoción de cuotas sin interés para pagar en Mercado Libre." href="http://ayuda.mercadolibre.com.ar/ayuda/Costos-de-financiaci-n-por-pag-ml_2955" target="_blank">Costo de financiación para pagos con tarjetas de crédito</a></p> </td> <td class="responsive-table-exposition">Se acredita instantáneamente</td> </tr> <tr> <td class="responsive-table-listing"> <ul class="payment-method-list"> <li class="paymentmethod-visa">Visa</li> <li class="paymentmethod-maestro">Maestro</li> <li class="paymentmethod-debcabal">Cabal</li> </ul> <p><strong>Tarjeta</strong> <strong>de </strong><strong>débito.</strong></p> </td> <td class="responsive-table-exposition">1 pago</td> <td class="responsive-table-exposition">Se acredita instantáneamente</td> </tr> <tr> <td class="responsive-table-listing"> <ul class="payment-method-list"> <li class="paymentmethod-rapipago">Rapipago</li> <li class="paymentmethod-pagofacil">Pago Fácil</li> <li class="paymentmethod-cargavirtual">Carga Virtual</li> </ul> <p><strong>En</strong> <strong>efectivo </strong>con<strong> Rapipago</strong>,<strong> Pago Fácil</strong> y<strong> Carga Virtual</strong>: te&nbsp;damos un número para pagar.</p> </td> <td class="responsive-table-exposition">1 pago</td> <td class="responsive-table-exposition">Se acredita instantáneamente</td> </tr> <tr> <td class="responsive-table-listing"> <ul> <li class="paymentmethod-bapropagos">BaproPagos</li> </ul> <p><strong>En efectivo </strong>con<strong>&nbsp;Provincia NET</strong>:&nbsp;imprimí tu factura y acercate&nbsp;a pagar.</p> </td> <td class="responsive-table-exposition">1 pago.</td> <td class="responsive-table-exposition">Pagás, y se acredita <strong>en 1 día hábil</strong></td> </tr> <tr> <td class="responsive-table-listing"> <ul class="payment-method-list"> <li class="paymentmethod-account_money">Dinero en cuenta MercadoPago</li> </ul> <p><strong>Dinero en tu cuenta</strong>: tu dinero disponible en Mercado Pago se transfiere al instante a la cuenta del receptor.</p> </td> <td class="responsive-table-exposition">1 pago</td> <td class="responsive-table-exposition">Se acredita instantáneamente</td> </tr> </tbody> </table> <p class="helpTip"><br>* No disponible para reventa de entradas.</p> </div> </div> </div> <p>En publicaciones de subastas también&nbsp;podés elegir acordar el pago con el vendedor. Si pagás de esta forma, te recomendamos:</p> <ul> <li>Evitar usar servicios de transferencia de dinero que no permitan verificar la identidad de tu contraparte.</li> <li>Asegurarte de que el titular de la cuenta bancaria en la que vayas a depositar coincida con los datos de contacto del vendedor.</li> <li>Guardar los comprobantes de pago.</li> <li>No pagar una factura enviada por un vendedor. Al terminar la compra&nbsp;podés imprimir tu propia factura.</li> </ul> <p>&nbsp;</p> <div> <p><a class="ch-btn" href="https://www.mercadolibre.com.ar/ayuda/purchases">Tengo un problema con un pago</a></p> </div></div><div class="cx-main--content__effectivitySurvey"><div class="cx-effectivity__content"><h3>¿Te ayudó la información?</h3><div class="cx-effectivity__icons"><div role="presentation" class="cx-effectivity__positive cx-effectivity__icons-circle"><div class="cx-effectivity__icons-yes"></div></div><div role="presentation" class="cx-effectivity__negative cx-effectivity__icons-circle"><div class="cx-effectivity__icons-no"></div></div></div></div></div></div> </div> </div> </div> <div class="card"> <div class="card-header" id="headingThree"> <h2 class="mb-0"> <button class="btn btn-link collapsed" type="button" data-toggle="collapse" data-target="#collapseThree" aria-expanded="false" aria-controls="collapseThree"> Agregar stock, pausar, eliminar y reactivar una publicación </button> </h2> </div> <div id="collapseThree" class="collapse" aria-labelledby="headingThree" data-parent="#accordionFaq"> <div class="card-body"> <div class="wrap-content"> <h2>Agregar stock</h2> <p>Si publicás productos nuevos en Clásica, quedarán inactivas automáticamente cuando te quedes sin stock. Si querés reactivar tu publicación, podrás hacerlo de forma individual, o masivamente, desde el <a href="https:/www.mercadolibre.com.ar/publicaciones/editor-masivo/#label=paused">editor masivo.</a></p> <p>Si, en cambio, vendés productos usados, tus publicaciones&nbsp;van a finalizar automáticamente cuando no tengas más stock. Si&nbsp;querés volver a activarlas&nbsp;tenés que crear una nueva publicación.</p> </div> <div class="wrap-content"> <h2>Pausar</h2> <p>Si&nbsp;querés pausar tu publicación tené en cuenta que:</p> <ul> <li>El tiempo de exposición de tu publicación Gratuita seguirá corriendo, aunque no aparezca en los listados.</li> <li>Tu producto publicado en Clásica no se&nbsp;va a ver en los listados, hasta que lo reactives nuevamente.</li> </ul> </div> <div class="wrap-content"> <h2>Eliminar</h2> <p>Podés eliminar una publicación siempre que esté inactiva. Tené en cuenta que una vez eliminada, no vas a poder recuperarla.</p> </div> <div class="wrap-content"> <h2>Republicar un producto</h2> <p>Podés&nbsp;republicar sin cambios o modificar la publicación antes de hacerlo.</p> <p>Si está inactiva y queres reactivarla, asegurate de hacerlo antes de que pasen 60 días, de esta forma vas a mantener&nbsp;las ventas, visitas y preguntas pendientes. Tené en cuenta que si editás el título lo consideraremos una publicación nueva, y&nbsp;va a perder la cantidad de ventas y visitas acumuladas.</p> </div> <div class="wrap-content"> <h2>Republicar en Clasificados</h2> <p>Si republicás un vehículo, inmueble o servicio dentro de los 60 días,&nbsp;mantenés las visitas.</p> <p>Pero además, los inmuebles se pueden republicar gratis dentro de los 30 días, aunque sin exposición en las páginas principales.</p> <p>&nbsp;</p> </div></div> </div> </div> </div> </div> </div> </main> <!-- footer --> <?php include_once("includes/footer.php"); ?> <!-- fin footer --> <!-- Modal --> <?php include_once("includes/modal.php"); ?> <!-- Fin modal --> <?php include_once("includes/scriptBootstrap.php"); ?> <script src="https://kit.fontawesome.com/67f61afa3e.js" crossorigin="anonymous"></script> </body> </html> <file_sep>/clases/Carrito.php <?php class Carrito{ private $id; private $productos; private $total; /** * Get the value of id */ public function getId() { return $this->id; } /** * Set the value of id * * @return self */ public function setId($id) { $this->id = $id; return $this; } /** * Get the value of productos */ public function getProductos() { return $this->productos; } /** * Set the value of productos * * @return self */ public function setProductos($productos) { $this->productos = $productos; return $this; } /** * Get the value of total */ public function getTotal() { return $this->total; } /** * Set the value of total * * @return self */ public function setTotal($total) { $this->total = $total; return $this; } } ?><file_sep>/registro.php <!DOCTYPE html> <?php session_start(); $pagina="Registro"; require_once "./includes/funciones.php"; $errores=null; if($_POST /*|| true*/){ // $_POST["nombre"] = "test"; // $_POST["apellido"] = "test"; // $_POST["correo"] = "test"; // $_POST["usuario"] = "test"; // $_POST["clave"] ="test"; // $_POST["telefono"] = "test"; $nombre = $_POST["nombre"]; $apellido = $_POST["apellido"] ; $correo = $_POST["correo"] ; $usuario = $_POST["usuario"] ; $clave = $_POST["clave"]; $telefono = $_POST["telefono"]; $requisitos = [ "nombre" => [ MINSIZE => 4, MAXSIZE => 15 ], "apellido" => [ MINSIZE => 4, MAXSIZE => 15 ], "correo" => [ CORREO ], "usuario" => [ MINSIZE => 4, MAXSIZE => 15 ], "clave" => [ CLAVE ], "telefono" => [ MINSIZE => 8, TELEFONO ] ]; $errores = hacerValidaciones($_POST, $requisitos); if(!$errores){ // setcookies $user = [ "email" => $correo, "nombre" => $nombre, "apellido" => $apellido, "usuario" => $usuario, "clave" => password_hash($clave, PASSWORD_DEFAULT), "telefono" => $telefono, "fechaNacimiento"=>"", "direccion"=>"", "ciudad"=>"", "provincia"=>"", "pais"=>"", "codigoPostal"=>"", "sexo"=>"", "nombreTitular"=>"", "numeroTarjeta"=>"", "tipoDeTarjeta"=>"", "fechaVencimiento"=>"", "cvc"=>"", "fotoPerfil"=>"" ]; if(!existsUser($user)){ mergeUser($user); $_SESSION["activeUser"] = $user; // echo json_encode($user); exit; // $_SESSION["usuario"]=$usuario; // $_SESSION["nombre"]=$nombre; // $_SESSION["apellido"]=$apellido; // $_SESSION["email"]=$correo; header("Location: perfil.php");exit; }else{ $errores["email"] = ["... <b style='font-size: 1.2em'>LA CUENTA YA ESTÁ REGISTRADA!!!</b> <a href='#' style='color: blue'>Recuperar contraseña</a>"]; } } } else{ $nombre = ""; $apellido = ""; $correo = ""; $usuario = ""; $clave = ""; $telefono = "" ; } ?> <html lang="en"> <head> <?php include_once("includes/headPerfil.php"); ?> <link rel="stylesheet" href="css/styleAnto.css"> <title>registro</title> </head> <body class="main-login"> <!--Comienza el header--> <header class="container-fluir fixed-top"> <?php include_once("includes/headerPerfil.php"); ?> </header> <!--Fin el header--> <main class=" container mb-4 main-inicio"> <?php include_once("includes/ubicacionPerfil.php") ?> <section class=" mb-2"> <!--<h2>Inicio de Seccion</h2> --> <form class="col-10 col-sm-6 col-md-6 col-lg-6 mx-auto" action="" method="post"> <!-- <form action="registrar.php" metodo="post" class="form"> --> <h2 class="form-titulo">CREA UNA CUENTA</h2> <div class="contenedor-inputs"> <input type="text" name="nombre" placeholder="Nombre" class="input-48" required value="<?=$nombre?>"> <input type="text" name="apellido" placeholder="Apellido" class="input-48" required value="<?=$apellido?>"> <input type="email" name="correo" placeholder="Correo" class="input-100" required value="<?=$correo?>"> <input type="text" name="usuario" placeholder="Usuario" class="input-48" required value="<?=$usuario?>"> <input type="password" name="clave" placeholder="<PASSWORD>" class="input-48" required value=""> <input type="text" name="telefono" placeholder="Telefono" class="input-100" required value="<?=$telefono?>"> <?php if(isset($errores)) echo imprimirErrores($errores) ?> <input type="submit" value="Registrar" class="btn-enviar"> <p class="form__link">¿Ya tienes una cuenta?<a href="login.html">Ingresa aqui</a></p> </div> </form> </section> </main> <!-- footer --> <?php include_once("includes/footer.php"); ?> <!-- fin footer --> <?php include_once("includes/scriptBootstrap.php"); ?> <script src="https://kit.fontawesome.com/67f61afa3e.js" crossorigin="anonymous"></script> </body> </html> <file_sep>/includes/userManager.php <?php require_once "fileManager.php"; /* COMO MODIFICAR USUARIOS: 1) $_SESSION["activeUser"]["<atributo>"] = "<valor>"; 2) mergeUser($_SESSION["activeUser"]); ** NO PERMITIR CAMBIOS DE EMAIL NI USERNAME */ define("USERS_BBDD_PATH", dirname(__FILE__) . "\..\data\usuarios.json"); define("USER_EMAIL", dirname(__FILE__) . "\..\data\user_email.json"); if(!file_exists(USERS_BBDD_PATH)){ file_put_contents(USERS_BBDD_PATH, "{}"); } if(!file_exists(USER_EMAIL)){ file_put_contents(USER_EMAIL, "{}"); } function mergeUser($user){ $u = []; $u[$user["email"]] = $user; mergeObjectToFile(USERS_BBDD_PATH, $u); foreach($u as $theUser){ $userEmail[$theUser["usuario"]] = $theUser["email"]; mergeObjectToFile(USER_EMAIL, $userEmail); } } function existsUser($user){ if( existsKeyOnFile(USERS_BBDD_PATH, $user["email"]) || existsKeyOnFile(USER_EMAIL, $user["usuario"]) ){ return true; } return false; } function existsUserName($userName){ return existsKeyOnFile(USER_EMAIL, $user["usuario"]); } function existsUserEmail($userEmail){ return existsKeyOnFile(USERS_BBDD_PATH, $user["email"]); } function findUserByEmail($email){ return getObjectFromFile(USERS_BBDD_PATH, $email); } function findUserByUserName($userName){ $email = getObjectFromFile(USER_EMAIL, $userName); return findUserByEmail($email); } function getUsers(){ return getObjectsFromFile(USERS_BBDD_PATH); } function removeUser($user){ $users = getUsers(); removeObjectFromFile(USERS_BBDD_PATH, $user["email"]); removeObjectFromFile(USER_EMAIL, $user["usuario"]); } function updateUserEmail($new, $old){ if(existsUserEmail($new)) return false; $user = findUserByEmail($old); removeUser($user); $user["email"] = $new; mergeUser($user); } function updateUserName($new, $old){ if(existsUserName($new)) return false; $user = findUserByUserName($old); // innecesario removeUser($user); $user["usuario"] = $new; mergeUser($user); } ?><file_sep>/includes/validacionDeFecha.php <?php function validarFeha($fecha){ $valores = explode('-', $fecha); if(count($valores) != 3 || !checkdate($valores[2], $valores[1], $valores[0])){ return false; } return true; } ?><file_sep>/agregarProducto.php <?php //require_once ('includes/pdo.php'); require_once 'clases/Conexion.php'; require_once 'clases/Marca.php'; require_once 'clases/Categoria.php'; require_once 'clases/Producto.php'; include_once("includes/funciones.php"); include_once("includes/baseDeDatos.php"); $producto = new Producto(); $msj=""; $img=""; $errores=null; if (isset($_POST["btnCargar"])&& $_POST ){ /** * */ $datos=[ "nombre" =>trim($_POST["nombre"]), "descripcion" =>trim($_POST["descripcion"]), "precio" =>trim($_POST["precio"]), "stock" =>trim($_POST["stock"]), "marca" =>trim($_POST["marca"]), "categoria" =>trim($_POST["categoria"]), "descuento" =>trim($_POST["descuento"]) ]; /*** * */ $requisitos = [ "nombre"=>[ MINSIZE=>2, MAXSIZE => 30 ], "descripcion" => [ MAXSIZE => 10000 ], "precio" => [ MINSIZE => 1, PositivoFloat ], "stock" => [ MINSIZE => 1, SOLONUMEROS, Positivo, ], "marca" => [ MINSIZE => 1, SOLONUMEROS, Positivo, Marca ], "categoria" => [ MINSIZE => 1, SOLONUMEROS, Positivo, Categoria ], "descuento" => [ MINSIZE => 1, Descuento ] ]; /** * * */ if($_FILES){ $errorArchivo=( validarArchivo($_FILES["img"]) ); } /** * */ $errores = hacerValidaciones($datos, $requisitos); if($errorArchivo){ $errores["img"]=$errorArchivo; }else{ if($_FILES["img"]["name"]!="" && $_FILES){ $img=Producto::guardarArchivo($_FILES["img"],$_POST["nombre"]); }else{ $img=$_POST["imagenActual"]; } } /** * */ //var_dump($_POST); //var_dump($_FILES); /** * */ if(!$errores){ $producto->altaProducto($img,$datos); $msj="success"; }else{ $datos["img"]=$img; //var_dump($datos); foreach ($datos as $key => $value) { $valorPersistencia[$key]=persistirDatoGeneral($errores,$key,$datos); } //var_dump($valorPersistencia); $msj="danger"; } /** * */ $nombre = $_POST["nombre"]; $descripcion = $_POST["descripcion"]; $precio= $_POST["precio"]; $stock = $_POST["stock"]; $marca = $_POST["marca"]; $categoria = $_POST["categoria"]; $descuento = $_POST["descuento"]; } ?> <!DOCTYPE html> <html lang="en" dir="ltr"> <?php include 'includes/head.php';?> <title>ABM Productos</title> <body> <?php include 'includes/headerAdm.php'; ?> <main> <div class="container-fluir my-3"> <div id="accordion"> <div class="card"> <div class="card-header " id="headingFour"> <h5 class="mb-0 d-flex justify-content-between align-items-center"> <button class="btn btn-link mr-3 collapsed" data-toggle="collapse" data-target="#collapseFour" aria-expanded="false" aria-controls="collapseFour"> Agregar Producto </button> <p class="btn alert alert-<?=$msj;?>" role="alert"> <?php if($msj=="success"){ echo("Producto se agregada correctamente."); } if($msj=="danger"){ echo("No se pudo agregar el Producto"); } ?> </p> <a href="abmProducto.php" class=" btn btn-primary ml-3">Volver a principal</a> </h5> </div> <div id="collapseFour" class="collapse carrito-resumen" aria-labelledby="headingFour" data-parent="#accordion"> <div class="card-body "> <form class="altaProducto" action="" method="post" enctype="multipart/form-data"> <div class="form-group"> <label for="nombre">Nombre</label> <input type="text" class="form-control" id="nombre" name="nombre" value="<?=(isset($valorPersistencia["nombre"]))?$valorPersistencia["nombre"]:"" ;?>" require> <small class="text-danger"><?=(isset($errores))?mostrarErroresPerfil($errores,"nombre"):""; ?></small> </div> <div class="form-group"> <label for="descripcion">Descripcion</label> <textarea class="form-control" id="descripcion" rows="8" cols="80" name="descripcion" ><?=( isset($valorPersistencia["descripcion"]))?$valorPersistencia["descripcion"]:"" ;?></textarea> <small class="text-danger"><?=(isset($errores))?mostrarErroresPerfil($errores,"descripcion"):""; ?></small> </div> <div class="form-group"> <label for="precio">Precio:</label> <input type="text" class="form-control " id="precio" name="precio" min="1" value="<?=(isset($valorPersistencia["precio"]))?$valorPersistencia["precio"]:"0" ;?>" require > <small class="text-danger"><?=(isset($errores))?mostrarErroresPerfil($errores,"precio"):""; ?></small> </div> <div class="form-group"> <label for="stock">stock</label> <input type="text" class="form-control" id="stock" name="stock" min="1" value="<?=(isset($valorPersistencia["stock"]))?$valorPersistencia["stock"]:"0" ;?>" require> <small class="text-danger"><?=(isset($errores))?mostrarErroresPerfil($errores,"stock"):""; ?></small> </div> <div class="form-group"> <label for="marca">Marca</label> <select class="form-control" id="marca" name="marca"> <option value="0" >Seleccionar</option> <?php $marca=new Marca(); $marcas=$marca->listarMarcas(); $marcaElegida=(isset($valorPersistencia["marca"]))?$valorPersistencia["marca"]:"" ; foreach ($marcas as $key => $value) { if($value["id_marca"]==$marcaElegida){ ?> <option value="<?=$value["id_marca"];?>" selected><?=$value["marca"];?></option> <?php }else{ ?> <option value="<?=$value["id_marca"];?>"><?=$value["marca"];?></option> <?php } ?> <?php } ?> </select> <small class="text-danger"><?=(isset($errores))?mostrarErroresPerfil($errores,"marca"):""; ?></small> </div> <div class="form-group"> <label for="categoria">Categoria</label> <select class="form-control" id="categoria" name="categoria"> <option value="0" >Seleccionar</option> <?php $categoria=new Categoria(); $categorias=$categoria->listarcategorias(); $categoriaElegida=(isset($valorPersistencia["categoria"]))?$valorPersistencia["categoria"]:"" ; foreach ($categorias as $key => $value) { if($value["id_categoria"]==$categoriaElegida){ ?> <option value="<?=$value["id_categoria"];?>" selected><?=$value["categoria"];?></option> <?php }else{ ?> <option value="<?=$value["id_categoria"];?>"><?=$value["categoria"];?></option> <?php } ?> <?php } ?> </select> <small class="text-danger"><?=(isset($errores))?mostrarErroresPerfil($errores,"categoria"):""; ?></small> </div> <div class="form-group"> <label for="descuento">descuento</label> <input type="text" class="form-control" id="descuento" name="descuento" pattern="(^0?|^[1-9]{1}+[0-9]{1})+([\.]([0-9]){1,2})?$" value="<?=( isset($valorPersistencia["descuento"]))?$valorPersistencia["descuento"]:"0" ;?>" > <small class="text-danger"><?=(isset($errores))?mostrarErroresPerfil($errores,"descuento"):""; ?></small> </div> <div class="form-group text-center"> <label for="" class="col-12">Imagen</label> <input type="text" name="imagenActual" value="<?=(isset($valorPersistencia["img"]))?$valorPersistencia["img"]:"img/Productos/phone.png";?>" readonly hidden> <img src="<?=(isset($valorPersistencia["img"]))?$valorPersistencia["img"]:"img/Productos/phone.png" ;?>" alt="" sizes="" width="" class="" height="300px"> <label for="img" class="text-left col-12">Cambiar</label> <input type="file" class="form-control-file" id="img" name="img" class=""> <small class="text-danger"><?=(isset($errores))?mostrarErroresPerfil($errores,"img"):""; ?></small> </div> <button type="submit" class="btn btn-primary mb-2" name="btnCargar" value="cargar">Cargar</button> </form> </div> </div> </div> </div> </div> </main> <?php include 'includes/footer.php'; include 'includes/scriptBootstrap.php'; ?> </body> </html><file_sep>/agregarCategoria.php <?php require_once 'clases/Conexion.php'; require 'clases/Categoria.php'; $objCategoria = new Categoria; $chequeo = $objCategoria->agregarCategoria(); // include 'includes/header.html'; // include 'includes/nav.php'; include 'includes/head.php'; include 'includes/headerAdm.php'; ?> <main class="container"> <h1>Alta de una nueva Categoria</h1> <?php $mensaje = 'No se pudo agregar la Categoria'; $class = 'danger'; if( $chequeo ){ $mensaje = 'Categoria '.$objCategoria->getCategoria(); $mensaje .= ' agregada correctamente.'; $class = 'success'; } ?> <div class="alert alert-<?= $class; ?>"> <?= $mensaje; ?> </div> <a href="abmCategoria.php" class="btn btn-light">Volver a admin de categorias</a> </main> <?php include 'includes/footer.php'; ?><file_sep>/formAgregarMarca.php <?php require_once 'clases/Conexion.php'; include 'includes/head.php'; include 'includes/headerAdm.php'; ?> <main class="container"> <h1>Alta de una marca</h1> <form action="agregarMarca.php" method="post"> Marca: <br> <input type="text" name="marca" class="form-control" required> <br> <input type="submit" value="Agregar Marca" class="btn btn-secondary"> <a href="abmMarca.php" class="btn btn-light">Volver a admin de marcas</a> </form> </main> <?php include 'includes/footer.php'; ?><file_sep>/productoDetalle.php <?php session_start(); include_once("includes/funciones.php"); include_once("includes/baseDeDatos.php"); $pagina="Descriccion de Producto"; //$pagina_anterior=$_SERVER['HTTP_REFERER'];//pagina anterior if(isset($_SESSION["activeUser"]) && !is_null($_SESSION["activeUser"])){ if($_SESSION["activeUser"]["fotoPerfil"]==""){ $_SESSION["activeUser"]["fotoPerfil"]=(isset($imagenUsuario))?$imagenUsuario:"img/perfil.png"; } $activeUser=$_SESSION["activeUser"]; } ?> <!DOCTYPE html> <html lang="en"> <?php include_once "includes/head.php" ?> <body> <!--Comienza el header--> <header class="container-fluir fixed-top"> <?php include_once("includes/headerPerfil.php"); ?> </header> <!--Fin el header--> <?php include_once "includes/modal.php" ?> <!--Main--> <main> <div class="container" id="mainContainer"> <?php include_once "includes/navBar.php" ?> <hr> <div class="row" id = "seccionProducto"> <div class="col-xl-6 col-lg-6 col-md-6 col-sm-12" id="imagenProducto"> <a href="img/phone.jpg" title="Phone example"> <img src="img/phone.jpg" style="width:100%" alt="Phone example"/> </a> </div> <div class="col-xl-6 col-lg-6 col-md-6 col-sm-12" id="descProducto"> <h3>Phone example</h3> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> <form class="form-horizontal qtyFrm"> <div class="control-group"> <label class="control-label"><span>$222.00</span></label> <div class="controls"> <input class="cantidad" type="number" name="numero" value="1" min="1" max="50" placeholder="Cantidad"/> <button type="submit" class="btn btn-large btn-primary pull-right"> Add to cart <i class="fas fa-shopping-cart"></i></button> </div> </div> </form> <form class="form-horizontal qtyFrm pull-right"> <div class="control-group"> <label class="control-label"><span>Color</span></label> <div class="controls"> <select> <option>Black</option> <option>Red</option> <option>Blue</option> <option>Brown</option> </select> </div> </div> </form> <br> <h4>Métodos de pago</h4> <img src="img/payment_methods.png" alt="payment_methods.png"> </div> </div> <hr> <div class="row" id="seccionInfoProducto"> <div class="col-12"> <h4>Product Information</h4> <table class="table table-bordered"> <tbody> <tr class="techSpecRow"><th colspan="2">Product Details</th></tr> <tr class="techSpecRow"><td class="techSpecTD1">Brand: </td><td class="techSpecTD2">Fujifilm</td></tr> <tr class="techSpecRow"><td class="techSpecTD1">Model:</td><td class="techSpecTD2">FinePix S2950HD</td></tr> <tr class="techSpecRow"><td class="techSpecTD1">Released on:</td><td class="techSpecTD2"> 2011-01-28</td></tr> <tr class="techSpecRow"><td class="techSpecTD1">Dimensions:</td><td class="techSpecTD2"> 5.50" h x 5.50" w x 2.00" l, .75 pounds</td></tr> <tr class="techSpecRow"><td class="techSpecTD1">Display size:</td><td class="techSpecTD2">3</td></tr> </tbody> </table> </div> <div class="col-12"> <h5>Features</h5> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </p> <h4>Editorial Reviews</h4> <h5>Manufacturer's Description </h5> <p> With a generous 18x Fujinon optical zoom lens, the S2950 really packs a punch, especially when matched with its 14 megapixel sensor, large 3.0" LCD screen and 720p HD (30fps) movie capture. </p> <h5>Electric powered Fujinon 18x zoom lens</h5> <p> The S2950 sports an impressive 28mm – 504mm* high precision Fujinon optical zoom lens. Simple to operate with an electric powered zoom lever, the huge zoom range means that you can capture all the detail, even when you're at a considerable distance away. You can even operate the zoom during video shooting. Unlike a bulky D-SLR, bridge cameras allow you great versatility of zoom, without the hassle of carrying a bag of lenses. </p> <h5>Impressive panoramas</h5> <p> With its easy to use Panoramic shooting mode you can get creative on the S2950, however basic your skills, and rest assured that you will not risk shooting uneven landscapes or shaky horizons. The camera enables you to take three successive shots with a helpful tool which automatically releases the shutter once the images are fully aligned to seamlessly stitch the shots together in-camera. It's so easy and the results are impressive. </p> <h5>Sharp, clear shots</h5> <p> Even at the longest zoom settings or in the most challenging of lighting conditions, the S2950 is able to produce crisp, clean results. With its mechanically stabilised 1/2 3", 14 megapixel CCD sensor, and high ISO sensitivity settings, Fujifilm's Dual Image Stabilisation technology combines to reduce the blurring effects of both hand-shake and subject movement to provide superb pictures. </p> </div> </div> <hr> </div> </main> <!--End main--> <?php include_once "includes/footer.php" ?> <?php include_once "includes/scriptBootstrap.php" ?> </body> </html> <file_sep>/perfil.php <?php session_start(); include_once("includes/funciones.php"); include_once("includes/baseDeDatos.php"); $pagina="Datos de Usuario"; //$pagina_anterior=$_SERVER['HTTP_REFERER'];//pagina anterior if(isset($_SESSION["activeUser"]) && !is_null($_SESSION["activeUser"])){ if($_SESSION["activeUser"]["fotoPerfil"]==""){ $_SESSION["activeUser"]["fotoPerfil"]=(isset($imagenUsuario))?$imagenUsuario:"img/perfil.png"; } $activeUser=$_SESSION["activeUser"]; }else{ header("Location: login.php");exit; } $pagina="Datos de Usuario"; $arraySexo=["Hombre","Mujer","Otro"]; $arrayTiposDeTarjetas=["Mastercad"=>"img/mastercard.png","Visa"=>"img/visa.png","Discover"=>"img/discover.png","America Express"=>"img/americanExpress.png"]; $jsonProvincias=file_get_contents("json/doc/provincias.json"); $arrayProvincias=json_decode($jsonProvincias,true); $jsonPaises=file_get_contents("json/doc/paises.json"); $arrayPaises=json_decode($jsonPaises,true); $errores=null; $input=true; if(isset($_POST["guardar"])&& $_POST){ $usuarioTemporar=[ "usuario"=>$activeUser["usuario"], "email"=>$activeUser["email"], "clave"=>$activeUser["clave"], "nombre" =>trim($_POST["nombre"]), "apellido" =>trim($_POST["apellido"]), "telefono" =>trim($_POST["telefono"]), "fechaNacimiento"=>trim($_POST["fechaNacimiento"]), "direccion"=>trim($_POST["direccion"]), "ciudad"=>trim($_POST["ciudad"]), "provincia"=>trim($_POST["provincia"]), "pais"=>trim($_POST["pais"]), "codigoPostal"=>trim($_POST["codigoPostal"]), "sexo"=>trim($_POST["sexo"]), "nombreTitular"=>trim($_POST["nombreTitular"]), "numeroTarjeta"=>trim($_POST["numeroTarjeta"]), "tipoDeTarjeta"=>trim($_POST["tipoDeTarjeta"]), "fechaVencimiento"=>trim($_POST["fechaVencimiento"]), "cvc"=>trim($_POST["cvc"]), "fotoPerfil"=>$activeUser["fotoPerfil"] ]; //dd($_FILES); $requisitos = [ "usuario"=>[ MINSIZE=>2, ], "nombre" => [ MINSIZE => 2, MAXSIZE => 30 ], "apellido" => [ MINSIZE => 2, MAXSIZE => 30 ], "telefono" => [ MINSIZE => 8, TELEFONO ], "fechaNacimiento"=>[ FECHA ], "direccion"=>[ MINSIZE => 4, MAXSIZE => 30 ], "ciudad"=>[ MINSIZE => 4, MAXSIZE => 30 ], "provincia"=>[ MINSIZE => 4, MAXSIZE => 30 ], "pais"=>[ MINSIZE => 4, MAXSIZE => 30 ], "codigoPostal"=>[ MINSIZE => 2, MAXSIZE => 30 ], "sexo"=>[ SEXO=>$arraySexo ], "nombreTitular"=>[ MINSIZE => 2, MAXSIZE => 30 ], "numeroTarjeta"=>[ MINSIZE => 12, MAXSIZE => 30, TIPODETARJETANUM ], "tipoDeTarjeta"=>[ MINSIZE => 3, MAXSIZE => 10, TIPODETARJETA=>$usuarioTemporar["numeroTarjeta"] ], "fechaVencimiento"=>[ FECHAVENCIMIENTOTARJETA ], "cvc"=>[ SOLONUMEROS, MINSIZE => 3, MAXSIZE => 10 ] ]; //dd($_FILES); if($_FILES){ $errorArchivo=( validarArchivo($_FILES["adjunto"]) ); } $errores = hacerValidaciones($_POST, $requisitos); if($errorArchivo){ $errores["archivo"]=$errorArchivo; }else{ if($_FILES["adjunto"]["name"]!=""){ $imagenUsuario=guardarArchivo($_FILES["adjunto"],$activeUser["usuario"]); $usuarioTemporar["fotoPerfil"]=$imagenUsuario; }else { $imagenUsuario=$usuarioTemporar["fotoPerfil"]; } } if(!$errores){ $input=true; $miUsuario=$usuarioTemporar; $_SESSION["activeUser"]=$miUsuario; $arrayUsuarios=getObjectsFromFile("data/usuarios.json"); //$arrayUsuarios=leerJsonYpasaArray(Direccion); $arrayUsuarios[$miUsuario["email"]]=$miUsuario; guardarArrayYpasarAJson("data/usuarios.json",$arrayUsuarios); }else{ foreach ($_SESSION["activeUser"] as $key => $value) { $valorPersistencia=persistirDato($errores,$key); if($key!="fotoPerfil" && $key!="email" && $key!="clave"){ $_SESSION["activeUser"][$key]=($valorPersistencia=="")?$value:$valorPersistencia; }else{ if($key=="fotoPerfil" && $_SESSION["activeUser"][$key]==""){ $_SESSION["activeUser"][$key]=(isset($imagenUsuario))?$imagenUsuario:"img/perfil.png"; } } } $input=false; //dd($_SESSION["activeUser"]); } // dd($errores); } if(isset($_POST["editar"]) && $_POST){ $input=false; } if(!($_POST)){ } ?> <!DOCTYPE html> <html lang="en"> <head> <?php include_once("includes/headPerfil.php"); ?> <link rel="stylesheet" href="css/stylePerfilSeguridadResumen.css"> <title>E-commerce</title> </head> <body class="main-perfil"> <!--Comienza el header--> <header class="container-fluir fixed-top"> <?php include_once("includes/headerPerfil.php"); ?> </header> <!--Fin el header--> <main class="mx-xl-auto" > <div class="container contenedor mb-4"> <div class="row"> <!--ubicacion--> <?php include_once("includes/ubicacionPerfil.php"); ?> <!--ubicacion--> <!--menu izquierdo--> <?php include_once("includes/menuIzquierdoPerfil.php"); ?> <!--menu izquierdo--> <!--contenido derecho--> <div class="col-12 col-sm-12 col-md-9 col-lg-9 usuario"> <h1>Perfil</h1> <div class=" col-lg-12 mb-4"> <h2>Datos:</h2> <div class="col-12"> <!--Formulario--> <form class="container-fluir" method="post" action="" name="datosUsuario" enctype="multipart/form-data" autocomplete="on" > <!--imagen--> <div class="d-flex flex-wrap mx-auto my-4 img-perfil img-fluid"> <div class="contenedor-perfil" > <img src="<?=(isset($_SESSION["activeUser"]["fotoPerfil"]))?$_SESSION["activeUser"]["fotoPerfil"]:"" ;?>" alt="imagen de perfil" class=" img-hola "> <!-- Button trigger modal --> <a href="" class=" fixed-bottom btn-link py-2" data-toggle="modal" data-target="#exampleModalCenter">editar</a> <!-- Modal --> <div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalCenterTitle">Subir Foto</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <div class="container-fluid"> <div class="row"> <div class="col-md-6 mx-auto my-2 bg-secondary"> <img src="img/pngocean.com(1).png" class="img-fluid rounded mx-auto d-block" alt="..." max-width="100%" height="auto"> </div> </div> <div class="row"> <div class="col-md-12 col-lg-12 mx-auto"> <!-- Campo de selección de archivo --> <input type="file" name="adjunto" accept=".jpg,.png" class="examinar col-md-12 col-lg-12 mx-auto" <?=activarDesactivarInput($input) ; ?> > </div> </div> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Cerrar</button> </div> </div> </div> </div> </div> <small class="text-danger"><?=(isset($errores))?mostrarErroresPerfil($errores,"archivo"):""; ?></small> </div> <!--imagen--> <div class="form-group" > <label for="usuario">Usuario</label> <input type="text" class="form-control" id="usuario" name="usuario" placeholder="usuario" value="<?=(isset($_SESSION["activeUser"]["usuario"]))?$_SESSION["activeUser"]["usuario"]:"" ;?>" readonly required> <small class="text-danger"><?=(isset($errores))?mostrarErroresPerfil($errores,"usuario"):""; ?></small> </div> <div class="form-row my-1"> <div class="col"> <label for="nombre">Nombre</label> <input id="nombre" type="text" class="form-control" placeholder="ej:Juan" name="nombre" value="<?=(isset($_SESSION["activeUser"]["nombre"]))?$_SESSION["activeUser"]["nombre"]:"" ;?>" <?=activarDesactivarInput($input) ; ?> required> <small class="text-danger"><?=(isset($errores))?mostrarErroresPerfil($errores,"nombre"):""; ?></small> </div> <div class="col"> <label for="apellido">Apellido</label> <input id="apellido" type="text" class="form-control" placeholder="ej:Lopez" name="apellido" value="<?=(isset($_SESSION["activeUser"]["apellido"]))?$_SESSION["activeUser"]["apellido"]:"" ;?>" <?=activarDesactivarInput($input) ; ?> required> <small class="text-danger"><?=(isset($errores))?mostrarErroresPerfil($errores,"apellido"):""; ?></small> </div> </div> <div class="form-group"> <label for="telefono">Telefono</label> <input type="tel" class="form-control" id="telefono" name="telefono" placeholder="1564582635" value="<?=(isset($_SESSION["activeUser"]["telefono"]))?$_SESSION["activeUser"]["telefono"]:"" ;?>" <?=activarDesactivarInput($input) ; ?> required> <small class="text-danger"><?=(isset($errores))?mostrarErroresPerfil($errores,"telefono"):""; ?></small> </div> <div class="form-group my-2"> <label for="fechaNacimiento ">Fecha de Nacimiento</label> <input type="date" class="form-control" id="fechaNacimiento" placeholder="dd-mm-yyyy" name="fechaNacimiento" value="<?=(isset($_SESSION["activeUser"]["fechaNacimiento"]))?$_SESSION["activeUser"]["fechaNacimiento"]:"" ;?>" <?=activarDesactivarInput($input) ; ?> required> <small class="text-danger"><?=(isset($errores))?mostrarErroresPerfil($errores,"fechaNacimiento"):""; ?></small> </div> <div class="form-group"> <label for="inputAddress">Direccion</label> <input type="text" class="form-control" id="inputAddress" name="direccion" placeholder="calle altura ej:av.rivadavia 4302" value="<?=(isset($_SESSION["activeUser"]["direccion"]))?$_SESSION["activeUser"]["direccion"]:"" ;?>" <?=activarDesactivarInput($input) ; ?> required> <small class="text-danger"><?=(isset($errores))?mostrarErroresPerfil($errores,"direccion"):""; ?></small> </div> <div class="form-row"> <div class="form-group col-md-5"> <label for="inputCity">Ciudad</label> <input type="text" class="form-control" id="inputCity" value="<?=(isset($_SESSION["activeUser"]["ciudad"]))?$_SESSION["activeUser"]["ciudad"]:"" ;?>" placeholder="Caseros" name="ciudad" <?=activarDesactivarInput($input) ; ?> required> <small class="text-danger"><?=(isset($errores))?mostrarErroresPerfil($errores,"ciudad"):""; ?></small> </div> <div class="form-group col-md-4"> <label for="inputState">Provincia</label> <select id="inputState" class="form-control" name="provincia" <?=activarDesactivarInput($input) ; ?> required > <option value="" >Seleccionar</option> <?php $valorProvincia=(isset($_SESSION["activeUser"]["provincia"]))?$_SESSION["activeUser"]["provincia"]:"" ; for ($i=0; $i <count($arrayProvincias) ; $i++) { $valor=$arrayProvincias[$i]["nombre"]; if($valorProvincia==$valor){ echo "<option value='$valor' selected>$valor</option>"; }else{ echo "<option value='$valor' >$valor</option>"; } } ?> </select> <small class="text-danger"><?=(isset($errores))?mostrarErroresPerfil($errores,"provincia"):""; ?></small> </div> <div class="form-group col-md-4"> <label for="inputState">Pais</label> <select id="inputState" class="form-control" name="pais" <?=activarDesactivarInput($input) ; ?> required > <option value="" >Seleccionar</option> <?php $valorPais=(isset($_SESSION["activeUser"]["pais"]))?$_SESSION["activeUser"]["pais"]:"" ; for ($i=0; $i <count($arrayPaises) ; $i++) { $valor=$arrayPaises[$i]; if($valorPais==$valor){ echo "<option value='$valor' selected >$valor</option>"; }else{ echo "<option value='$valor' >$valor</option>"; } } ?> </select> <small class="text-danger"><?=(isset($errores))?mostrarErroresPerfil($errores,"pais"):""; ?></small> </div> <div class="form-group col-md-3"> <label for="inputZip">Codigo Postal</label> <input type="text" class="form-control" id="inputZip" placeholder="codigo postal" value="<?=(isset($_SESSION["activeUser"]["codigoPostal"]))?$_SESSION["activeUser"]["codigoPostal"]:"" ;?>" <?=activarDesactivarInput($input) ; ?> name="codigoPostal" required> <small class="text-danger"><?=(isset($errores))?mostrarErroresPerfil($errores,"codigoPostal"):""; ?></small> </div> </div> <fieldset class="form-group"> <div class="row"> <legend class="col-form-label col-sm-2 pt-0">Sexo </legend> <div class="col-sm-10"> <?php $valorSexo=(isset($_SESSION["activeUser"]["sexo"]))?$_SESSION["activeUser"]["sexo"]:"" ; ?> <?php foreach ($arraySexo as $value): ?> <div class="form-check"> <?php if($valorSexo==$value){ ?> <input class="form-check-input" type="radio" name="sexo" id="<?=$value ; ?>" value="<?=$value;?>" checked <?=activarDesactivarInput($input) ; ?> required> <label class="form-check-label" for="<?=$value ; ?>"> <?=$value; ?> </label> <?php }else{ ?> <input class="form-check-input" type="radio" name="sexo" id="<?=$value ; ?>" value="<?=$value;?>" <?=activarDesactivarInput($input) ; ?> required> <label class="form-check-label" for="<?=$value ; ?>"> <?=$value; ?> </label> <?php } ?> </div> <?php endforeach ?> </div> </div> <small class="text-danger"><?=(isset($errores))?mostrarErroresPerfil($errores,"sexo"):""; ?></small> </fieldset> <label for="datoDeTarjeta"><h5>Datos de Tarjeta</h5></label> <div class="form-group"> <label for="NombreTarjeta">Nombre Completo del Titular</label> <input type="text" class="form-control" id="NombreTarjeta" name="nombreTitular" value="<?=(isset($_SESSION["activeUser"]["nombreTitular"]))?$_SESSION["activeUser"]["nombreTitular"]:"" ;?>" placeholder="Nombre del titular" <?=activarDesactivarInput($input) ; ?> required> <small class="text-danger"><?=(isset($errores))?mostrarErroresPerfil($errores,"nombreTitular"):""; ?></small> </div> <div class="form-group" id="datoDeTarjeta"> <label for="Numerotarjeta">Numero de tarjeta</label> <input type="text" class="form-control" id="Numerotarjeta" name="numeroTarjeta" value="<?=(isset($_SESSION["activeUser"]["numeroTarjeta"]))?$_SESSION["activeUser"]["numeroTarjeta"]:"" ;?>" placeholder="ingrese el numero sin guiones(-) ej 5119101838103698" <?=activarDesactivarInput($input) ; ?> required> <small class="text-danger"><?=(isset($errores))?mostrarErroresPerfil($errores,"numeroTarjeta"):""; ?></small> </div> <fieldset class="form-group"> <div class="row"> <legend class="col-form-label col-sm-4 pt-0">Tipo de pago </legend> <div class="col-sm-10"> <?php $valorTP=(isset($_SESSION["activeUser"]["tipoDeTarjeta"]))?$_SESSION["activeUser"]["tipoDeTarjeta"]:"" ; ?> <?php foreach ($arrayTiposDeTarjetas as $key => $value): ?> <div class="form-check col-4 form-check-inline"> <?php if($valorTP==$key){ ?> <input class="form-check-input" type="radio" name="tipoDeTarjeta" id="<?=$key; ?>" value="<?=$key; ?>" checked <?=activarDesactivarInput($input) ; ?> required> <label class="form-check-label" for="<?=$key; ?>"> <img src="<?=$value; ?>" alt="<?=$key; ?>" width="60"> </label> <?php }else{ ?> <input class="form-check-input" type="radio" name="tipoDeTarjeta" id="<?=$key; ?>" value="<?=$key; ?>" <?=activarDesactivarInput($input) ; ?> required> <label class="form-check-label" for="<?=$key; ?>"> <img src="<?=$value; ?>" alt="<?=$key; ?>" width="60"> </label> <?php } ?> </div> <?php endforeach ?> </div> </div> <small class="text-danger"><?=(isset($errores))?mostrarErroresPerfil($errores,"tipoDeTarjeta"):""; ?></small> </fieldset> <div class="form-group" > <label for="fechaVencimiento col-6">Fecha de Vencimiento</label> <input type="text" class="form-control col-6" id="fechaVencimiento" name="fechaVencimiento" value="<?=(isset($_SESSION["activeUser"]["fechaVencimiento"]))?$_SESSION["activeUser"]["fechaVencimiento"]:"" ;?>" <?=activarDesactivarInput($input) ; ?> placeholder="mm/yyyy" required> <small class="text-danger"><?=(isset($errores))?mostrarErroresPerfil($errores,"fechaVencimiento"):""; ?></small> </div> <div class="form-group" > <label for="cvc" class="col-sm-4 px-0">CVC</label> <input type="text" class="form-control col-sm-6" id="cvc" name="cvc" value="<?=(isset($_SESSION["activeUser"]["cvc"]))?$_SESSION["activeUser"]["cvc"]:"" ;?>" placeholder="ingrese el cvc" <?=activarDesactivarInput($input) ; ?> required> <small class="text-danger"><?=(isset($errores))?mostrarErroresPerfil($errores,"cvc"):""; ?></small> </div> <button type="submit" class="btn btn-secondary ml-md-auto boton-efecto my-2" name="editar">Editar</button> <button type="submit" class="btn btn-secondary ml-md-auto boton-efecto my-2" name="guardar">guardar</button> </form> <!--Formulario--> </div> </div> </div> <!--contenido derecho--> </div> </div> </main> <!-- footer --> <?php include_once("includes/footer.php"); ?> <!-- fin footer --> <!-- Modal --> <?php include_once("includes/modal.php"); ?> <!-- Fin modal --> <?php include_once("includes/scriptBootstrap.php"); ?> <script src="https://kit.fontawesome.com/67f61afa3e.js" crossorigin="anonymous"></script> </body> </html> <file_sep>/clases/Tarjeta.php <?php class Tarjeta{ private $id_tarjeta; private $id_tipo_tarjeta; private $nombre; private $numeroTarjeta; private $tipoTarjeta; private $cvc; private $fecha_vencimiento; /** * Get the value of id_tarjeta */ public function getId_tarjeta() { return $this->id_tarjeta; } /** * Set the value of id_tarjeta * * @return self */ public function setId_tarjeta($id_tarjeta) { $this->id_tarjeta = $id_tarjeta; return $this; } /** * Get the value of id_tipo_tarjeta */ public function getId_tipo_tarjeta() { return $this->id_tipo_tarjeta; } /** * Set the value of id_tipo_tarjeta * * @return self */ public function setId_tipo_tarjeta($id_tipo_tarjeta) { $this->id_tipo_tarjeta = $id_tipo_tarjeta; return $this; } /** * Get the value of nombre */ public function getNombre() { return $this->nombre; } /** * Set the value of nombre * * @return self */ public function setNombre($nombre) { $this->nombre = $nombre; return $this; } /** * Get the value of numeroTarjeta */ public function getNumeroTarjeta() { return $this->numeroTarjeta; } /** * Set the value of numeroTarjeta * * @return self */ public function setNumeroTarjeta($numeroTarjeta) { $this->numeroTarjeta = $numeroTarjeta; return $this; } /** * Get the value of tipoTarjeta */ public function getTipoTarjeta() { return $this->tipoTarjeta; } /** * Set the value of tipoTarjeta * * @return self */ public function setTipoTarjeta($tipoTarjeta) { $this->tipoTarjeta = $tipoTarjeta; return $this; } /** * Get the value of cvc */ public function getCvc() { return $this->cvc; } /** * Set the value of cvc * * @return self */ public function setCvc($cvc) { $this->cvc = $cvc; return $this; } /** * Get the value of fecha_vencimiento */ public function getFecha_vencimiento() { return $this->fecha_vencimiento; } /** * Set the value of fecha_vencimiento * * @return self */ public function setFecha_vencimiento($fecha_vencimiento) { $this->fecha_vencimiento = $fecha_vencimiento; return $this; } } ?><file_sep>/contacto.php <?php session_start(); include_once("includes/funciones.php"); include_once("includes/baseDeDatos.php"); $pagina="Datos de Usuario"; //$pagina_anterior=$_SERVER['HTTP_REFERER'];//pagina anterior if(isset($_SESSION["activeUser"]) && !is_null($_SESSION["activeUser"])){ if($_SESSION["activeUser"]["fotoPerfil"]==""){ $_SESSION["activeUser"]["fotoPerfil"]=(isset($imagenUsuario))?$imagenUsuario:"img/perfil.png"; } $activeUser=$_SESSION["activeUser"]; } $pagina="Contacto"; ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="https://fonts.googleapis.com/css?family=Roboto+Condensed:400,700|Roboto:400,500,700&display=swap" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600|Roboto:500,700&display=swap" rel="stylesheet"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <link rel="stylesheet" href="css/styles.css"> <title>Contacto</title> <link rel="shortcut icon" href="favicon.ico"/> </head> <body class="main-login"> <!--Comienza el header--> <header class="container-fluir fixed-top"> <?php include_once("includes/headerPerfil.php"); ?> </header> <!--Fin el header--> <main class=" container mb-4 main-inicio"> <ul class="breadcrumb col-12"> <li><a href="home.html">Home</a> <span class="divider">/</span></li> <li>Informacion<span class="divider">/</span></li> <li class="active">Contacto</li> </ul> <section class=" mb-2"> <!--<h2>Inicio de Seccion</h2> --> <form class="col-10 col-sm-6 col-md-6 col-lg-6 mx-auto" action="" method="post"> <!-- <form action="contactar.php" metodo="post" class="form">--> <h2 class="form-titulo">CONTACTO</h2> <div class="contenedor-inputs"> <input type="text" name="nombre" placeholder="Nombre" class="input-100" required> <input type="email" name="correo" placeholder="Correo" class="input-100" required> <input type="text" name="telefono" placeholder="Telefono" class="input-100" required> <textarea name="mensaje" placeholder="escriba aqui su mensaje" required class="border border-secondary"></textarea> <input type="submit" value="ENVIAR" class="btn-enviar"> </div> </form> </section> </main> <!-- footer --> <?php include_once("includes/footer.php"); ?> <!-- fin footer --> <!-- Modal --> <?php include_once("includes/modal.php"); ?> <!-- Fin modal --> <?php include_once("includes/scriptBootstrap.php"); ?> <script src="https://kit.fontawesome.com/67f61afa3e.js" crossorigin="anonymous"></script> </body> </html> <file_sep>/clases/Sexo.php <?php class Sexo{ private $id_sexo; private $sexo; public function altaProducto(string $img) { $db=Conexion::conectar(); $nombre = $_POST["nombre"]; $desc = $_POST["descripcion"]; $precio= $_POST["precio"]; $stock = $_POST["stock"]; $marca = $_POST["marca"]; $categoria = $_POST["categoria"]; $descuento = $_POST["descuento"]; try{ $statement = $db->prepare("INSERT into productos(id_marca,id_categoria,nombre,descripcion,precio,cantidad,img,descuento) VALUES ( :idMarca, :idCategoria,:nombre, :descripcion, :precio, :cantidad, :img,:descuento)"); $statement->bindValue(':idMarca', $marca,PDO::PARAM_INT); $statement->bindValue(":idCategoria", $categoria,PDO::PARAM_INT); $statement->bindValue(":nombre", $nombre,PDO::PARAM_STR); $statement->bindValue(":descripcion", $desc,PDO::PARAM_STR); $statement->bindValue(":precio", $precio); $statement->bindValue(":cantidad", $stock,PDO::PARAM_INT); $statement->bindValue(":img", $img,PDO::PARAM_STR); $statement->bindValue(":descuento", $descuento); $statement->execute(); $statement->closeCursor(); }catch (\Exception $e) { echo "Error al cargar poducto"; $e->getMessage(); } } public function modificarProducto(int $id,string $img) { $db=Conexion::conectar(); $nombre = $_POST["nombre"]; $desc = $_POST["descripcion"]; $precio= $_POST["precio"]; $stock = $_POST["stock"]; $marca = $_POST["marca"]; $categoria = $_POST["categoria"]; $descuento = $_POST["descuento"]; $sql="UPDATE productos SET nombre=:nombre, descripcion=:descripcion, precio=:precio, cantidad=:cantidad, img=:img, descuento=:descuento, id_marca=:idMarca, id_categoria=:idCategoria WHERE id_producto =:id"; $statement = $db->prepare($sql); $statement->bindValue(":nombre", $nombre,PDO::PARAM_STR); $statement->bindValue(":descripcion", $desc); $statement->bindValue(":precio", $precio); $statement->bindValue(":cantidad", $stock,PDO::PARAM_INT); $statement->bindValue(":img", $img,PDO::PARAM_STR); $statement->bindValue(":descuento", $descuento); $statement->bindValue(':idMarca', $marca,PDO::PARAM_INT); $statement->bindValue(":idCategoria", $categoria,PDO::PARAM_INT); $statement->bindValue(':id', $id,PDO::PARAM_INT); $statement->execute(); } public function borrarProducto($id) { $db=Conexion::conectar(); try { $statement = $db->prepare("DELETE FROM productos WHERE id_producto = :id"); $statement->bindValue(":id", $id); $statement->execute(); } catch (\Exception $e) { echo "Error al borrar producto"; $e->getMessage(); } } public function buscarPorId(int $id){ $db=Conexion::conectar(); if(isset($_POST["id"])){ $id=(int)$_POST["id"]; } try { $sql = "SELECT id_producto as id,nombre,descripcion,precio,cantidad as stock,marca,categoria,descuento,img FROM productos as p inner join categorias as c on p.id_categoria=c.id_categoria inner join marcas as m on p.id_marca=m.id_marca WHERE id_producto= :id"; $seleccionado=$db->prepare($sql); $seleccionado->bindValue(":id", $id,PDO::PARAM_INT); $seleccionado->execute(); $variable = $seleccionado->fetchObject("Producto");//objeto return $variable; } catch (\Exception $e) { $e->getMessage(); return false; } } public function obtenerListaSexo(){ $db=Conexion::conectar(); try { $sql = "SELECT id_sexo,sexo FROM sexos"; $stmt = $db->prepare($sql); $stmt->execute(); //$variable = $stmt->fetchAll(PDO::FETCH_ASSOC);//array asociado $variable = $stmt->fetchAll(PDO::FETCH_CLASS,"Sexo");//objeto $stmt->closeCursor(); return $variable; } catch (\Exception $e) { echo "Error al obtener Lista de Sexos"; $e->getMessage(); return false; } } /** * Get the value of id_sexo */ public function getId_sexo() { return $this->id_sexo; } /** * Set the value of id_sexo * * @return self */ public function setId_sexo($id_sexo) { $this->id_sexo = $id_sexo; return $this; } /** * Get the value of sexo */ public function getSexo() { return $this->sexo; } /** * Set the value of sexo * * @return self */ public function setSexo($sexo) { $this->sexo = $sexo; return $this; } } ?><file_sep>/abmProducto.php <?php //require_once ('includes/pdo.php'); require_once 'clases/Conexion.php'; require_once 'clases/Marca.php'; require_once 'clases/Categoria.php'; require_once 'clases/Producto.php'; include_once("includes/funciones.php"); include_once("includes/baseDeDatos.php"); session_start(); $producto = new Producto(); $msj=""; $variable=$producto->obtenerListaProductos(); //var_dump($variable); if ($_POST) { // var_dump($_POST); // exit; if (isset($_POST["btnBorrar"])) { $id =$_POST["btnBorrar"]; $producto->borrarProducto($id); if($producto){ $_SESSION["msj"]="Eliminado Producto de ID: $id"; }else { $_SESSION["msj"]="Error en eliminado Producto de ID: $id"; } $archivoActual = $_SERVER['PHP_SELF']; header("refresh:1;url=$archivoActual"); exit; } } ?> <!DOCTYPE html> <html lang="en" dir="ltr"> <?php include 'includes/head.php';?> <title>Productos</title> <body> <?php include 'includes/headerAdm.php'; ?> <main> <div class="container-fluir my-3"> <?php //if(isset($_SESSION["msj"])){ if($_SESSION["msj"]!=""){ ?> <div class="alert alert-success"> <h5><?=$_SESSION["msj"];?></h5> </div> <?php $_SESSION["msj"]=""; //} } ?> <div id="accordion"> <div class="card"> <div class="card-header " id="headingFour"> <h5 class="mb-0 d-flex justify-content-between"> <button class="btn btn-link mr-3 collapsed" data-toggle="collapse" data-target="#collapseFour" aria-expanded="false" aria-controls="collapseFour"> Lista de Productos </button> <a href="agregarProducto.php" class="btn btn-primary ml-3 ">Agregar</a> <a href="admin.php" class="btn btn-primary ml-3">Volver a principal</a> </h5> </div> <div id="collapseFour" class="collapse carrito-resumen" aria-labelledby="headingFour" data-parent="#accordion"> <ul class="list-group"> <li class="list-group-item"> <div class="card-body form-inline d-flex justify-content-between px-0"> <div class="form-group mb-1 col-1 px-1" > <span class="form-control-plaintext text-center">Id</span> </div> <div class="form-group mb-1 col-2 px-1" > <span class="form-control-plaintext text-center">Nombre</span> </div> <div class="form-group mb-1 col-1 px-0" > <span class="form-control-plaintext text-center">Descripcion</span> </div> <div class="form-group mb-1 col-1 " > <span class="form-control-plaintext text-center">Precio</span> </div> <div class="form-group mb-1 col-1 px-1" > <span class="form-control-plaintext text-center">Stock</span> </div> <div class="form-group mb-1 col-2 px-1" > <span class="form-control-plaintext text-center">Marca</span> </div> <div class="form-group mb-1 col-1 px-1" > <span class="form-control-plaintext text-center">Categoria</span> </div> <div class="form-group mb-1 col-1 px-1" > <span class="d-block form-control-plaintext text-center">Descuento</span> </div> <div class="form-group mb-1 col-2 px-1" > <span class="d-block text-center form-control-plaintext text-center ">Imagen</span> </div> </div> </li> <?php $i=0; foreach ($variable as $key => $value) { $i+=1; ?> <li class="list-group-item"> <div class="card-body px-0"> <form class="form-inline d-flex justify-content-between " action="modificarProducto.php" method="post"> <div class="form-group mb-1 col-1 px-1" > <input type="text" readonly class="form-control-plaintext text-center" id="idF" value="<?=$i;?>" name="idF" > <input type="text" readonly class="form-control-plaintext text-center" id="id" value="<?=$value->getId();?>" name="id" readonly hidden> </div> <div class="form-group mb-2 col-2 px-1"> <span class="form-control-plaintext text-center" ><?=$value->getNombre();?></span> </div> <div class="form-group mb-2 col-1"> <span class="form-control-plaintext text-center" > <button type="button" class="btn btn-link" data-toggle="modal" data-target="#exampleModalCenter"> Ver </button> </span> </div> <!--modal de descripcion --> <div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalCenterTitle">Descripcion</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <!-- <p> <pre> <?=$value->getDescripcion();?> </pre> </p> --> <?php $array=explode(PHP_EOL,$value->getDescripcion()); foreach ($array as $key => $caracteristica) {?> <ul type="circle"> <li > <?=$caracteristica;?> </li> </ul> <?php } ?> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> </div> </div> </div> </div> <!--modal de descripcion --> <div class="form-group mb-2 col-1"> <span class="form-control-plaintext text-center" >$ <?=$value->getPrecio();?></span> </div> <div class="form-group mb-2 col-1 px-1"> <span class="form-control-plaintext text-center" ><?=$value->getStock();?></span> </div> <div class="form-group mb-2 col-2 px-1"> <span class="form-control-plaintext text-center" ><?=$value->getMarca();?></span> </div> <div class="form-group mb-2 col-1 px-1"> <span class="form-control-plaintext text-center d-block" ><?=$value->getCategoria();?></span> </div> <div class="form-group mb-2 col-1 px-1"> <span class="form-control-plaintext text-center d-block" ><?=$value->getDescuento();?>%</span> </div> <div class="form-group mb-2 col-2 text-center"> <img src="<?=$value->getImg();?>" alt="" sizes="" width="80%" class="zoom"> </div> <div class="form-group mb-2 col-12 text-center"> <button type="submit" class="btn btn-primary mx-2 mb-1 " name="modificar_l" value="<?=$value->getId();?>">Modificar</button> <!-- Button trigger modal --> <button type="button" class="btn btn-primary mx-2 mb-1 " name="eliminar_l" value="<?=$value->getId();?>" data-toggle="modal" data-target="#eliminar<?=$value->getId();?>Modal"> Eliminar </button> </form> <form class="form-inline d-flex justify-content-between " action="" method="post"> <!-- Modal --> <div class="modal fade" id="eliminar<?=$value->getId();?>Modal" tabindex="-1" role="dialog" aria-labelledby="eliminar<?=$value->getId();?>ModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content text-center"> <div class="modal-header"> <h5 class="modal-title" id="eliminar<?=$value->getId();?>ModalLabel">Desea eliminar este producto?</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body d-flex align-items-center justify-content-center flex-wrap"> <div class="form-group mb-2 col-10 px-1 "> <span class="form-control-plaintext " ><?=$value->getNombre();?></span> </div> <div class="form-group mb-2 col-5 text-center"> <img src="<?=$value->getImg();?>" alt="" sizes="" width="80%" class=""> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancelar</button> <button type="submit" class="btn btn-primary mx-2 mb-1 " name="btnBorrar" value="<?=$value->getId();?>">Eliminar</button> </div> </div> </div> </div> </form> </div> </div> </li> <?php } ?> </ul> </div> </div> </div> </div> </main> <?php include 'includes/footer.php'; include 'includes/scriptBootstrap.php'; ?> </body> </html> <file_sep>/resumen.php <?php session_start(); include_once("includes/funciones.php"); include_once("includes/baseDeDatos.php"); if(isset($_SESSION["activeUser"]) && !is_null($_SESSION["activeUser"])){ if($_SESSION["activeUser"]["fotoPerfil"]==""){ $_SESSION["activeUser"]["fotoPerfil"]=(isset($imagenUsuario))?$imagenUsuario:"img/perfil.png"; } $activeUser=$_SESSION["activeUser"]; }else{ header("Location: login.php");exit; } $pagina="Resumen"; ?> <!DOCTYPE html> <html lang="en"> <head> <?php include_once("includes/headPerfil.php") ?> <link rel="stylesheet" href="css/stylePerfilSeguridadResumen.css"> <title>E-commerce</title> </head> <body class="main-perfil"> <!--Comienza el header--> <header class="container-fluir fixed-top"> <?php include_once("includes/headerPerfil.php"); ?> </header> <!--Fin el header--> <main class="mx-xl-auto" > <div class="container contenedor"> <div class="row"> <!--ubicacion--> <?php include_once("includes/ubicacionPerfil.php"); ?> <!--ubicacion--> <!--menu izquierdo--> <?php include_once("includes/menuIzquierdoPerfil.php"); ?> <!--menu izquierdo--> <!-----Resumen--------------------------------> <div class="col-12 col-sm-12 col-md-9 col-lg-9 mb-4 resumen"> <h1 class="d-block">Resumen</h1> <!--comienzo del carrito actual---> <h2 class="col-12 my-4" id="summary">Carrito de Compras</h2> <div class="carrito-resumen" > <table class="table table-bordered"> <thead> <!--Fila de detalle de cada producto--> <tr> <th>Product</th> <th>Description</th> <th>Quantity/Update</th> <th>Price</th> </tr> </thead> <tbody> <!--Filas y columnas--> <tr> <td> <img width="60" src="img/phone.jpg" alt="phone.jpg"/></td> <td>MASSA AST<br/>Color : black, Material : metal</td> <td> <div class="input-append"> <input class="span1" style="max-width:34px" placeholder="1" id="appendedInputButtons" size="16" type="text"> <button class="btn" type="button"> <i class="fas fa-minus"></i> </button> <button class="btn" type="button"> <i class="fas fa-plus"></i> </button> <button class="btn btn-danger" type="button"> <i class="far fa-times-circle"></i> </button> </div> </td> <td>$120.00</td> </tr> <tr> <td> <img width="60" src="img/phone.jpg" alt="phone.jpg"/></td> <td>MASSA AST<br/>Color : black, Material : metal</td> <td> <div class="input-append"> <input class="span1" style="max-width:34px" placeholder="1" size="16" type="text"> <button class="btn" type="button"> <i class="fas fa-minus"></i> </button> <button class="btn" type="button"> <i class="fas fa-plus"></i> </button> <button class="btn btn-danger" type="button"> <i class="far fa-times-circle"></i> </button> </div> </td> <td>$7.00</td> </tr> <tr> <td> <img width="60" src="img/phone.jpg" alt="phone.jpg"/></td> <td>MASSA AST<br/>Color : black, Material : metal</td> <td> <div class="input-append"> <input class="span1" style="max-width:34px" placeholder="1" size="16" type="text"> <button class="btn" type="button"> <i class="fas fa-minus"></i> </button> <button class="btn" type="button"> <i class="fas fa-plus"></i> </button> <button class="btn btn-danger" type="button"> <i class="far fa-times-circle"></i> </button> </div> </td> <td>$120.00</td> </tr> <!--Fila que muestra el total del carrito--> <tr> <td colspan="3" style="text-align:right">Total Price: </td> <td> $228.00</td> </tr> <tr> <td colspan="3" style="text-align:right">Total Discount: </td> <td> $50.00</td> </tr> <tr> <td colspan="3" style="text-align:right">Total Tax: </td> <td> $31.00</td> </tr> <tr> <td colspan="3" style="text-align:right"><strong>TOTAL ($228 - $50 + $31) =</strong></td> <td class="label label-important" style="display:block"> <strong> $155.00 </strong></td> </tr> </tbody> </table> <p><button type="button" class="btn btn-secondary ml-md-auto boton-efecto">Vaciar Carrito</button><button type="button" class="btn btn-secondary ml-md-auto boton-efecto">Comprar</button></p> </div> <!-- Fin modal --> <!-----factura------------------------------------------------------------------------------> <h2 class="col-12 text-left my-4">Mis Factura</h2> <div class="factura my-4"> <!--Fila --> <div class=" col-sm-12 col-md-12 col-lg-12"> <div class="col-sm-12 col-md-2 col-lg-2"> <p>Comprobante</p> </div> <div class=" col-sm-12 col-md-3 col-lg-3"> <p>Numero de Factura</p> </div> <div class=" col-sm-12 col-md-3 col-lg-3 "> <p>Fecha</p> </div> <div class=" col-sm-12 col-md-2 col-lg-2"> <p>Importe</p> </div> <div class=" col-sm-12 col-md-2 col-lg-2"> <p>Ver factura</p> </div> </div> <!--fin Fila --> <!--Fila --> <div class="col-sm-12 col-md-12 col-lg-12"> <div class=" col-sm-12 col-md-2 col-lg-2"> <p>Factura A</p> </div> <div class=" col-sm-12 col-md-3 col-lg-3"> <p>NumeroFactura</p> </div> <div class=" col-sm-12 col-md-3 col-lg-3"> <p>dd-mm-yyyy</p> </div> <div class=" col-sm-12 col-md-2 col-lg-2"> <p>$15215.25</p> </div> <div class=" col-sm-12 col-md-2 col-lg-2"> <a href="factura/factura-ejemplo.pdf" download="factura-ejemplo.pdf" class="d-block"><p><img src="img/pdf.png" alt=""></p></a> </div> </div> <!--fin Fila --> <!--Fila --> <div class="col-sm-12 col-md-12 col-lg-12"> <div class=" col-sm-12 col-md-2 col-lg-2"> <p>Factura A</p> </div> <div class=" col-sm-12 col-md-3 col-lg-3"> <p>NumeroFactura</p> </div> <div class=" col-sm-12 col-md-3 col-lg-3"> <p>dd-mm-yyyy</p> </div> <div class=" col-sm-12 col-md-2 col-lg-2"> <p>$15215.25</p> </div> <div class=" col-sm-12 col-md-2 col-lg-2"> <a href="descargar.html" class="d-block"><p><img src="img/pdf.png" alt=""></p></a> </div> </div> <!--fin Fila --> <!--Fila --> <div class=" col-sm-12 col-md-12 col-lg-12"> <div class=" col-sm-12 col-md-2 col-lg-2"> <p>Factura A</p> </div> <div class=" col-sm-12 col-md-3 col-lg-3"> <p>NumeroFactura</p> </div> <div class=" col-sm-12 col-md-3 col-lg-3"> <p>dd-mm-yyyy</p> </div> <div class=" col-sm-12 col-md-2 col-lg-2"> <p>$15215.25</p> </div> <div class=" col-sm-12 col-md-2 col-lg-2"> <a href="descargar.html" class="d-block"><p><img src="img/pdf.png" alt=""></p></a> </div> </div> <!--fin Fila --> </div> <!--fin Facturas------------------------------- --> </div> <!-----Fin Resumen--------------------------------> </div> </div> <!-- MainBody End ============================= --> </main> <!-- Footer ================================================================== --> <?php include_once("includes/footer.php"); ?> <!-- Footer End================================================================== --> <?php include_once("includes/scriptBootstrap.php") ?> <script src="https://kit.fontawesome.com/67f61afa3e.js" crossorigin="anonymous"></script> </body> </html> <file_sep>/clases/TipoEnvio.php <?php class TipoEnvio{ private $id; private $tipo_envio; public function obtenerListaTipoEnvio(){ $db=Conexion::conectar(); try { $sql = "SELECT id_tipo_envio as id,tipo as tipo_envio FROM tipo_envios"; $stmt = $db->prepare($sql); $stmt->execute(); //$variable = $stmt->fetchAll(PDO::FETCH_ASSOC);//array asociado $variable = $stmt->fetchAll(PDO::FETCH_CLASS,"TipoEnvio");//objeto $stmt->closeCursor(); return $variable; } catch (\Exception $e) { echo "Error al obtener Lista de Sexos"; $e->getMessage(); return false; } } /** * Get the value of id */ public function getId() { return $this->id; } /** * Set the value of id * * @return self */ public function setId($id) { $this->id = $id; return $this; } /** * Get the value of tipo_envio */ public function getTipo_envio() { return $this->tipo_envio; } /** * Set the value of tipo_envio * * @return self */ public function setTipo_envio($tipo_envio) { $this->tipo_envio = $tipo_envio; return $this; } } ?><file_sep>/clases/Administrador.php <?php class Administrador extends Usuario{ public function obtenerListaAdministradores(){ $db=Conexion::conectar(); //try { $sql = "SELECT id_usuario as id,user as usuario,nombre,apellido,email,contrasenia as contrasenia,estado as estado FROM usuarios as u inner join estados as e on u.id_estado=e.id_estado " //where id_tipo_de_usuario= 1 " ; $stmt = $db->prepare($sql); $stmt->execute(); //$variable = $stmt->fetchAll(PDO::FETCH_ASSOC);//array asociado $variable = $stmt->fetchAll(PDO::FETCH_CLASS,"Administrador");//objeto return $variable; //} catch (\Exception $e) { // echo "Error al obtener Lista de Administradores"; // $e->getMessage(); // return false; //} } public function borrarAdministrador($id) { $db=Conexion::conectar(); try { $statement = $db->prepare("DELETE FROM usuarios WHERE id_producto = :id"); $statement->bindValue(":id", $id); $statement->execute(); } catch (\Exception $e) { echo "Error al borrar producto"; $e->getMessage(); } } public function agregarAlListado(){ return false; } public function eliminarUsuario(){ return false; } public function modificarProducto(){} } ?><file_sep>/eliminarCategoria.php <?php require_once 'clases/Conexion.php'; require 'clases/Categoria.php'; include 'includes/head.php'; include 'includes/headerAdm.php'; $objCategoria = new Categoria; isset($_REQUEST['id']); $chequeo = $objCategoria->eliminarCategoria(); ?> <main class="container"> <h1>Dar de baja una Categoria</h1> <?php $mensaje=''; // $mensaje = 'No se pudo eliminar la Categoria'; $class = 'danger'; if( $chequeo){ // $mensaje = 'Categoria: '.$objCategoria->getCategoria(); $mensaje .= '<br>La categoria con ID: '.$_REQUEST['id'];//La idea era mostrar el nombre de la categoria ///eliminada $mensaje .= ' fue eliminada con exito!'; $class = 'success'; }else{ // $mensaje = 'Marca: '.$objMarca->getMarca(); $mensaje .= '<br>La categoria con ID: '.$_REQUEST['id'];//La idea era mostrar el nombre de la marca ///eliminada $mensaje .= ' no se puede eliminar!.'; } ?> <div class="alert alert-<?= $class; ?>"> <?= $mensaje; ?> </div> <a href="abmCategoria.php" class="btn btn-light">Volver a admin de categorias</a> </main> <?php include 'includes/footer.php'; ?><file_sep>/tests/bye.php <?php session_start(); session_destroy(); echo "Estás deslogueado."; // require "../includes/userManager.php"; // removeUser(findUserByEmail("<EMAIL>")); ?><file_sep>/abmCategoria.php <?php require_once 'clases/Conexion.php'; require 'clases/Categoria.php'; $objCategoria = new Categoria; $categorias = $objCategoria->listarCategorias(); include 'includes/head.php'; include 'includes/headerAdm.php'; ?> <!DOCTYPE html> <html lang="en" dir="ltr"> <title>ABM Categorias</title> <body> <! -- include 'includes/headerAdm.php'; --> <main class="container"> <h1>Administracion de Categorias</h1> <a href="admin.php" class="btn btn-outline-secondary m-3">Administracion principal</a> <table class="table table-stripped table-bordered table-hover bg-white"> <thead class="thead-dark"> <tr> <th>id</th> <th>Categoria</th> <th colspan="2"> <a href="formAgregarCategoria.php" class="btn btn-dark"> agregar </a> </th> </tr> </thead> <tbody> <?php foreach ( $categorias as $categoria ){ ?> <tr> <td><?= $categoria['id_categoria']; ?></td> <td><?= $categoria['categoria']; ?></td> <td> <a href="formModificarCategoria.php?id=<?php echo $categoria['id_categoria']; ?>" class="btn btn-outline-secondary"> modificar </a> </td> <td> <!-- Button trigger modal --> <button type="button" class="btn btn-outline-secondary" name="eliminar_l" value="<?=$categoria["id_categoria"];?>" data-toggle="modal" data-target="#eliminar<?=$categoria["id_categoria"];?>Modal"> Eliminar </button> <!-- Modal --> <div class="modal fade" id="eliminar<?=$categoria["id_categoria"];?>Modal" tabindex="-1" role="dialog" aria-labelledby="eliminar<?=$categoria["id_categoria"];?>ModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content text-center"> <div class="modal-header"> <h5 class="modal-title" id="eliminar<?=$categoria["id_categoria"];?>ModalLabel">Desea eliminar este Categoria?</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body d-flex align-items-center justify-content-center flex-wrap"> <div class="form-group mb-2 col-10 px-1 "> <span class="form-control-plaintext " ><?=$categoria["categoria"];?></span> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancelar</button> <a href="eliminarCategoria.php?id=<?php echo $categoria["id_categoria"]; ?>" class="btn btn-outline-secondary"> eliminar </a> </div> </div> </div> </div> </td> </tr> <?php } ?> </tbody> </table> <a href="admin.php" class="btn btn-outline-secondary m-3">Administracion principal</a> </main> <?php include 'includes/footer.php'; include 'includes/scriptBootstrap.php'; ?> </body> </html><file_sep>/tests/testing.php <?php require "../includes/fileManager.php"; $arr = []; $arr["key"] = "valor"; // Cambiar "null" por "{}" en el archivo que crea y ya funciona. Después lo corrijo mergeObjectToFile("fileName.json", $arr); ?><file_sep>/includes/validaciones.php <?php /* ----------------- USO ------------------ 0) require_once "validaciones.php"; 1) Crear arreglo asociativo $requisitos a) Las claves deben ser las de la variable $_POST/GET que se quieran validar. b) Los valores van dentro de un arreglo. EJ: $requisitos = [ "postKey" => [ MINSIZE => 5, CORREO ] ]; ------------------ 2) Enviarle $_POST/GET y $requisitos a "hacerValidaciones()" y almacenar el retorno en una variable. EJ: $errores = hacerValidaciones($_POST, $requisitos); ------------------- 3) Mostrar los errores enviándole los errores a la funcion "mostrarErrores()" EJ: <?php if(isset($errores)) echo mostrarErrores($errores) ?> CONSTANTES ----------- MINSIZE => n MAXSIZE => n CORREO CLAVE SCAPE --------------------- -------- EJEMPLO COMPLETO --------- Se recibe por $_POST["name","email" y "pass"]. $requisitos = [ "name" => [ MINSIZE => 5, MAXSIZE => 20 ], "email" => [ CORREO ], "pass" => [ CLAVE ] ]; $errores = hacerValidaciones($_POST, $requisitos); <html> <?php if(isset($errores)) echo mostrarErrores($errores) ?> </html> ---------------------------------------- */ define("CLAVE", "asdfasdfavr"); define("CORREO", "34vq3vfvzxv"); define("MINSIZE", "asdy6we6ar66"); define("MAXSIZE", "asdf444322d"); define("SCAPE", "asdf422f1fds"); define("TELEFONO", "fddf4534ka"); define("FECHA","7d"); define("SEXO","8d"); define("TIPODETARJETANUM","9d"); define("TIPODETARJETA","10d"); define("FECHAVENCIMIENTOTARJETA","11d"); define("SOLONUMEROS","d12"); define("Marca","d13"); define("Categoria","d14"); define("Positivo","d15"); define("PositivoFloat","d16"); define("Descuento","d17"); define("PRODUCTO","d18"); function hacerValidaciones($arr, $requisitos){ $errores = []; foreach($arr as $key => $val){ if(isset($requisitos[$key])){ $errs = validar($val, $requisitos[$key]); if($errs){ $errores[$key] = []; foreach($errs as $err){ $errores[$key][] = $err; } } } } return $errores; } function validar($value, $requisitos){ $ret = []; $errs = []; if(in_array(CLAVE, $requisitos) || isset($requisitos[CLAVE])){ $errs[] = validarClave($value, $requisitos); } if(in_array(CORREO, $requisitos) || isset($requisitos[CORREO])){ $errs[] = validarCorreo($value); } if(in_array(TELEFONO, $requisitos) || isset($requisitos[TELEFONO])){ $errs[] = validarTelefono($value, $requisitos); } if(isset($requisitos[MINSIZE]) || isset($requisitos[MAXSIZE])){ $errs[] = validarSize($value, $requisitos); } if(in_array(FECHA, $requisitos) || isset($requisitos[FECHA])){ $errs[] = validarFecha($value); } if(isset($requisitos[SEXO])){ $errs[] = validarSexo($value,$requisitos[SEXO]); } if(isset($requisitos[TIPODETARJETANUM]) || in_array(TIPODETARJETANUM, $requisitos)){ $errs[] = validarNumeroDeTarjeta($value); } if(isset($requisitos[TIPODETARJETA])){ $errs[] = validarTipoDeTarjeta($value,$requisitos[TIPODETARJETA]); } if(isset($requisitos[FECHAVENCIMIENTOTARJETA])|| in_array(FECHAVENCIMIENTOTARJETA, $requisitos)){ $errs[] = validarFechaDeVencimiento($value); } if(isset($requisitos[SOLONUMEROS])|| in_array(SOLONUMEROS, $requisitos)){ $errs[] = validarSoloNumeros($value); } if(isset($requisitos[Positivo])|| in_array(Positivo, $requisitos)){ $errs[] = validarPositivo($value); } if(isset($requisitos[PositivoFloat])|| in_array(PositivoFloat, $requisitos)){ $errs[] = validarPositivoFloat($value); } if(isset($requisitos[Marca])|| in_array(Marca, $requisitos)){ $errs[] = validarMarca($value); } if(isset($requisitos[Categoria])|| in_array(Categoria, $requisitos)){ $errs[] = validarCategoria($value); } if(isset($requisitos[Descuento])|| in_array(Descuento, $requisitos)){ $errs[] = validarDescuento($value); } if(isset($requisitos[PRODUCTO])|| in_array(PRODUCTO, $requisitos)){ $errs[] = validarProducto($value); } foreach($errs as $err){ $ret = array_merge($ret, $err); } return $ret; } function validarSize($value, $requisitos){ // unset($requisitos[MINSIZE]) $errores = []; foreach($requisitos as $key => $val){ if( $key === MINSIZE && strlen($value) < $val ){ $errores[] = "al menos $val caracteres"; } else if( $key === MAXSIZE && strlen($value) > $val ){ $errores[] = "menos de $val caracteres"; } } return $errores; } function validarClave($value, $requisitos){ $ret = []; if(strlen($value) < 8){ $ret[] = "al menos ocho caracteres"; } if (!preg_match('`[a-z]`',$value)){ $ret[] = "al menos una letra minúscula"; } if (!preg_match('`[A-Z]`',$value)){ $ret[] = "al menos una letra mayúscula"; } if (!preg_match('`[0-9]`',$value)){ $ret[] = "al menos un caracter numérico"; } return $ret; } function validarCorreo($value){ $ret = []; if(!filter_var($value, FILTER_VALIDATE_EMAIL)){ $ret[] = "un formato válido"; } return $ret; } function validarTelefono($value, $requisitos){ $ret = []; if (preg_match('`[^0-9]`',$value)){ $ret[] = "sólo caracteres numéricos"; } return $ret; } //agregado function pre($valor){ echo "<pre>"; var_dump($valor); echo "<pre/>"; } function dd($valor){ pre($valor); exit; } //agregado //agregado function validarFecha($fecha){ $ret=[]; $fecha=preg_replace("/[\-\/.]/","/", $fecha); $valores = explode('/', $fecha); if(empty($fecha)){ $ret[]="Debe llenar este campo"; }elseif(count($valores) != 3 || !( checkdate($valores[1], $valores[2], $valores[0]) xor checkdate($valores[0], $valores[1], $valores[2]) xor checkdate($valores[1], $valores[0], $valores[2]) ) ){ $ret[]="un formato válido"; } return $ret; } function validarSexo($sexo,$requisitos){ $ret=[]; $msj=null; if(empty($sexo)){ $ret[]="Debe llenar este campo"; }elseif(!in_array($sexo, $requisitos)){ $msj="Seleccione una de las opciones: "; foreach ($requisitos as $value) { $msj.=" - ".$value." "; } $ret[]=$msj; } return $ret; } function validarNumeroDeTarjeta($numeroDeTarjeta){ $ret=[]; if(empty($numeroDeTarjeta)){ $ret[]="Debe llenar este campo"; }elseif( !( preg_match('/^6(?:011|5[0-9]{2})[0-9]{12}$/',$numeroDeTarjeta) || preg_match('/^3[47][0-9]{13}$/',$numeroDeTarjeta) || preg_match('/^5[1-5][0-9]{14}$/',$numeroDeTarjeta) || preg_match('/^4[0-9]{15}$/',$numeroDeTarjeta) ) ){ $ret[]="Numero de Tarjeta Invalida"; } return $ret; } function validarTipoDeTarjeta($tipoDeTarjeta,$numeroDeTarjeta){ $arrayTarjeta=[3=>"America Express",4=>"Visa",5=>"Mastercad",6=>"Discover"]; $resultado=validarNumeroDeTarjeta($numeroDeTarjeta); if(!$resultado){ $valor=trim($numeroDeTarjeta); $valor=substr($valor,0,1); if(!($arrayTarjeta[$valor]==$tipoDeTarjeta)){ $resultado[]="Seleccion Incorrecta de Tipo de Tarjeta"; } } return $resultado; } function validarFechaDeVencimiento($mesYAnio){ $ret=[]; //pre("es "); //pre(preg_replace("/^[\-\/.]$/","/^[\/]$/", $mesYAnio)); //dd(preg_match("/^(0[1-9]|1[012])[\-\/.](1|2)\d\d\d$/",$mesYAnio)); //dd(preg_match("/^(0[1-9]|1[0-2])\/[0-9]{4}$/",$mesYAnio)); //checkdate($valores[2], $valores[1], $valores[0]); //$valores = explode('/', $mesYAnio); if(empty($mesYAnio)){ $ret[]="Debe llenar este campo"; }else{ if(preg_match("/^(0[1-9]|1[012])[\-\/.](1|2)\d\d\d$/",$mesYAnio)>0){ $mesYAnio=preg_replace("/[\-\/.]/","/",$mesYAnio); //$valores = explode('/', $mesYAnio); $fecha_actual = date("d-m-Y"); $diff = ( strtotime("01/".$mesYAnio) - strtotime($fecha_actual) ); $years = floor($diff / (365*60*60*24)); $months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24)); if($years<=0 && $months<=0){ $ret[]="La tarjeta esta vencida"; } //preg_match("/^(1|2)\d\d\d[\-\/.](0[1-9]|1[012])[\-\/.](0[1-9]|[12][0-9]|3[01])$/",$mesYAnio); verifica el yyyy-mm-dd //$fecha_actual = date("d-m-Y"); //dd(date("d-m-Y",strtotime($fecha_actual."- ".$valores[0]." month"."- ".$valores[1]." year")) ); }else{ $ret[]="un formato válido"; } } return $ret; } function validarArchivo($archivo){ $ret=[]; if( !($archivo["error"]===UPLOAD_ERR_NO_FILE && $archivo["name"]=="") ){ if($archivo["error"]!==UPLOAD_ERR_OK){ $ret[]="El archivo subido fue sólo parcialmente cargado"; switch ($archivo["error"]) { case UPLOAD_ERR_INI_SIZE: $ret[] = "El archivo cargado supera la directiva upload_max_filesize en php.ini"; break; case UPLOAD_ERR_FORM_SIZE: $ret[] = "El archivo cargado excede la directiva MAX_FILE_SIZE que se especificó en el formulario HTML"; break; case UPLOAD_ERR_PARTIAL: $ret[] = "El archivo cargado solo se cargó parcialmente"; break; case UPLOAD_ERR_NO_FILE: $ret[] = "No se cargó ningún archivo"; break; case UPLOAD_ERR_NO_TMP_DIR: $ret[] = "Falta una carpeta temporal"; break; case UPLOAD_ERR_CANT_WRITE: $ret[] = "Error al escribir el archivo en el disco"; break; case UPLOAD_ERR_EXTENSION: $ret[] = "Carga de archivo detenida por extensión"; break; default: $ret[] = "Error de carga desconocido"; break; } }else{ if($archivo["size"]>10000000){ $ret[]="No puede superar los 10MB"; }else{ $nombre=$archivo["name"]; $ext=pathinfo($nombre,PATHINFO_EXTENSION); if($ext!="jpg" && $ext!="png"){ $ret[]="Subir una imagen de tipo jpg o png"; } } } } return $ret; } function guardarArchivo($file,$nombre="text"){ if($file["name"]!=""){ $nombreArchivo=$file["name"]; $archivo=$file["tmp_name"]; $ext=pathinfo($nombreArchivo,PATHINFO_EXTENSION); $miArchivo="img/Usuario/".$nombre; //ruta actual $nombre="avatar".uniqid(); if (!file_exists($miArchivo)) { mkdir($miArchivo, 0777, true); } $directorio = opendir($miArchivo); $cont=0; $archivoEliminar=""; while ($archivoDir = readdir($directorio)) //obtenemos un archivo y luego otro sucesivamente { if (!is_dir($archivoDir))//verificamos si es o no un directorio { //var_dump ($archivoDir ); if(preg_match("/avatar/i" ,$archivoDir)){//encuentra un archivo que coincida con el patron $cont++; $archivoEliminar=$archivoDir; } } } if($cont>1){ unlink($miArchivo."/".$archivoEliminar); } $miArchivo=$miArchivo."/".$nombre.".".$ext; move_uploaded_file($archivo,$miArchivo); return $miArchivo; } return null; } function persistirDato($arrayE, $string) { if(isset($arrayE[$string])) { return ""; } else { if(isset($_POST[$string])) { return $_POST[$string]; } } return ""; } function mostrarErroresPerfil($arrayError,$nombre){ if(isset($arrayError[$nombre])){ echo"<ul class='text-decoration-none'>"; foreach ($arrayError[$nombre] as $key => $value) { echo "<li>$value</li>"; } echo"</ul>"; } } function validarSoloNumeros($value){ $ret = []; //if(preg_match("/^0$|^[-]?[1-9][0-9]*$/",$value)){//prueba if (preg_match('`[^0-9]`',$value)){//original $ret[] = "sólo caracteres numéricos"; } return $ret; } /** * */ function is_digit($digit) { if(is_int($digit)) { return true; } elseif(is_string($digit)) { return ctype_digit($digit); } else { // booleans, floats and others return false; } } function new_is_unsigned_float($val) { $val=str_replace(" ","",trim($val)); //$prueba=str_replace(".","",$val); //return preg_match("/^([0-9])+([\.|,]([0-9])*)?$/",$val);//original return preg_match("/(^0?|^[1-9]+[0-9]*)+([\.]([0-9])*)?$/",$val);//prueba } function descuentoVerficar($val) { $val=str_replace(" ","",trim($val)); //$prueba=str_replace(".","",$val); //return preg_match("/^([0-9])+([\.|,]([0-9])*)?$/",$val);//original return preg_match("/(^0?|^[1-9]{1}+[0-9]{1})+([\.]([0-9]){1,2})?$/",$val);//prueba } /** * */ function validarDescuento($value){ $ret=[]; if(preg_match('`[^0-9]`',$value) && strlen($value)==1){ $ret[] = "sólo caracteres numéricos 0 al 9"; }elseif (!descuentoVerficar($value) && strlen($value)>1) { $ret[] = "sólo caracteres numéricos positivos decimales con punto"; } return $ret; } /** * */ function validarPositivoFloat($value){ $ret=[]; if(preg_match('`[^0-9]`',$value) && strlen($value)==1){ $ret[] = "sólo caracteres numéricos 0 al 9"; }elseif (!new_is_unsigned_float($value) && strlen($value)>1) { $ret[] = "sólo caracteres numéricos positivos decimales con punto"; } return $ret; } /** * */ function validarPositivo($value){ $ret=[]; if(!is_digit($value) && strlen($value)==1){ $ret[] = "sólo caracteres numéricos 0 al 9"; }elseif (!preg_match("/^0$|^[-]?[1-9][0-9]*$/",$value) && strlen($value)>1) { $ret[] = "sólo caracteres numéricos positivos sin ceros a la izquierda"; } return $ret; } /*** * */ function validarMarca($value){ $ret=[]; $marca=new Marca(); if(is_digit($value) && $value!="0" &&strlen($value)==1){ if(is_null($marca->verMarcaPorID($value))){ $ret[] = "Debe eligir una Marca"; } }elseif (preg_match("/^0$|^[-]?[1-9][0-9]*$/",$value) && strlen($value)>1) { if(!$marca->verMarcaPorID($value)){ $ret[] = "Debe eligir una Marca"; } }else{ $ret[] = "Debe eligir una Marca Existente"; } return $ret; } /** * */ function validarCategoria($value){ $ret=[]; $categoria=new Categoria(); if(is_digit($value) && $value!="0" &&strlen($value)==1){ if(is_null($categoria->verCategoriaPorID($value))){ $ret[] = "Debe eligir una Categoria "; } }elseif (preg_match("/^0$|^[-]?[1-9][0-9]*$/",$value) && strlen($value)>1) { if(!$categoria->verCategoriaPorID($value)){ $ret[] = "Debe eligir una Categoria "; } }else{ $ret[] = "Debe eligir una Categoria Existente"; } return $ret; } /** * */ function validarProducto($value){ $ret=[]; $producto=new Producto(); if(is_digit($value) && $value!="0" &&strlen($value)==1){ if(is_null($producto->buscarPorId($value))){ $ret[] = "Debe eligir una Producto "; } }elseif (preg_match("/^0$|^[-]?[1-9][0-9]*$/",$value) && strlen($value)>1) { if(!$producto->buscarPorId($value)){ $ret[] = "Debe eligir una Producto "; } }else{ $ret[] = "Debe eligir una Producto Existente"; } return $ret; } /** * */ function persistirDatoGeneral($arrayErrores, $campo,$verificar) { if(isset($arrayErrores[$campo])) { return ""; } else { if(isset($verificar[$campo])) { return $verificar[$campo]; } } return ""; } /** * */ //agregado // Si se envía la clave "soloTexto" no imprime ..el campo tal bla bla bla. function imprimirErrores($errores){ if($_POST){ echo "<ul class='errores col-12'>"; foreach($errores as $key => $errores){ $coma = ""; $return = "<li>El campo <u style='color:black'>$key</u> debe tener "; foreach($errores as $error){ $return .= "$coma $error"; if(!$coma) $coma = ","; } echo $return .".</li>"; } echo '</ul>'; } } ?><file_sep>/includes/modal.php <!-- Modal --> <div class="modal fade" id="exampleModalScrollable" tabindex="-1" role="dialog" aria-labelledby="exampleModalScrollableTitle" aria-hidden="true"> <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalScrollableTitle">Carrito</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <table class="table table-bordered"> <thead> <!--Fila de detalle de cada producto--> <tr> <th>Product</th> <th>Description</th> <th>Quantity/Update</th> <th>Price</th> </tr> </thead> <tbody> <!--Filas y columnas--> <tr> <td> <img width="60" src="img/phone.jpg" alt="phone.jpg"/></td> <td>MASSA AST<br/>Color : black, Material : metal</td> <td> <div class="input-append"> <input class="span1" style="max-width:34px" placeholder="1" id="appendedInputButtons" size="16" type="text"> <button class="btn" type="button"> <i class="fas fa-minus"></i> </button> <button class="btn" type="button"> <i class="fas fa-plus"></i> </button> <button class="btn btn-danger" type="button"> <i class="far fa-times-circle"></i> </button> </div> </td> <td>$120.00</td> </tr> <tr> <td> <img width="60" src="img/phone.jpg" alt="phone.jpg"/></td> <td>MASSA AST<br/>Color : black, Material : metal</td> <td> <div class="input-append"> <input class="span1" style="max-width:34px" placeholder="1" size="16" type="text"> <button class="btn" type="button"> <i class="fas fa-minus"></i> </button> <button class="btn" type="button"> <i class="fas fa-plus"></i> </button> <button class="btn btn-danger" type="button"> <i class="far fa-times-circle"></i> </button> </div> </td> <td>$7.00</td> </tr> <tr> <td> <img width="60" src="img/phone.jpg" alt="phone.jpg"/></td> <td>MASSA AST<br/>Color : black, Material : metal</td> <td> <div class="input-append"> <input class="span1" style="max-width:34px" placeholder="1" size="16" type="text"> <button class="btn" type="button"> <i class="fas fa-minus"></i> </button> <button class="btn" type="button"> <i class="fas fa-plus"></i> </button> <button class="btn btn-danger" type="button"> <i class="far fa-times-circle"></i> </button> </div> </td> <td>$120.00</td> </tr> <!--Fila que muestra el total del carrito--> <tr> <td colspan="3" style="text-align:right">Total Price: </td> <td> $228.00</td> </tr> <tr> <td colspan="3" style="text-align:right">Total Discount: </td> <td> $50.00</td> </tr> <tr> <td colspan="3" style="text-align:right">Total Tax: </td> <td> $31.00</td> </tr> <tr> <td colspan="3" style="text-align:right"><strong>TOTAL ($228 - $50 + $31) =</strong></td> <td class="label label-important" style="display:block"> <strong> $155.00 </strong></td> </tr> </tbody> </table> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> </div> </div> </div> </div> <!-- Fin modal --> <file_sep>/lista-productos.php <?php session_start(); include_once("includes/funciones.php"); include_once("includes/baseDeDatos.php"); $pagina="Lista de Productos"; //$pagina_anterior=$_SERVER['HTTP_REFERER'];//pagina anterior if(isset($_SESSION["activeUser"]) && !is_null($_SESSION["activeUser"])){ if($_SESSION["activeUser"]["fotoPerfil"]==""){ $_SESSION["activeUser"]["fotoPerfil"]=(isset($imagenUsuario))?$imagenUsuario:"img/perfil.png"; } $activeUser=$_SESSION["activeUser"]; } $pagina="Datos de Usuario"; ?> <!DOCTYPE html> <html lang="es"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <link rel="shortcut icon" href="favicon.ico"/> <link href="https://fonts.googleapis.com/css?family=Roboto+Condensed:400,700|Roboto:400,500,700&display=swap" rel="stylesheet"> <link rel="stylesheet" href="css/lista-productos.css"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <link rel="stylesheet" href="css/styles.css"> <link rel="stylesheet" href="css/mainListaProductos.css"> </head> <body class="main-perfil"> <!--Comienza el header--> <header class="container-fluir fixed-top"> <?php include_once("includes/headerPerfil.php"); ?> </header> <!--Fin el header--> <main class="container mb-4"> <div class="inner-main" id="lista-productos"> <aside> <div class="tags"> <span class="tag"> <span>Nuevo ✖ </span> <!-- <i class="material-icons">&#xe14c;</i> --> </span> <span class="tag"> <span>Motorola ✖</span> <!-- <i class="material-icons">&#xe14c;</i> --> </span> </div> <dl> <dt> Linea </dt> <dd> <a href="#"> <span class="filter-name">Moto</span> <span class="filter-result-qty">(123)</span> </a> </dd> <dd> <a href="#"> <span class="filter-name">RAZR</span> <span class="filter-result-qty">(65)</span> </a> </dd> <dd> <a href="#"> <span class="filter-name">One</span> <span class="filter-result-qty">(70)</span> </a> </dd> <dd> <a href="#"> Ver todos </a> </dd> </dl> <dl> <dt> Modelo </dt> <dd> <a href="#"> <span class="filter-name">IRONROCK</span> <span class="filter-result-qty">(36)</span> </a> </dd> <dd> <a href="#"> <span class="filter-name">i867</span> <span class="filter-result-qty">(22)</span> </a> </dd> <dd> <a href="#"> <span class="filter-name">G7 Power</span> <span class="filter-result-qty">(17)</span> </a> </dd> <dd> <a href="#"> Ver todos </a> </dd> </dl> </aside> <section clas="productos"> <a href="productoDetalle.php" class="irDescripcion"><!--Saque el onclick por que pertenece a javascript---> <article > <div class="img-container"> <img src="img/phone.jpg" alt=""> </div> <div class="descripcion"> <div class="price"> <span class="price-symbol">$</span> <span class="price-value">948</span> </div> <div class="descripcion-text"> Descripción </div> <div class="vendedor"> Vendedor </div> <div class="cantidad-vendidos"> 206 </div> </div> </article> </a> <a href="productoDetalle.php" class="irDescripcion"> <article > <div class="img-container"> <img src="img/phone.jpg" alt=""> </div> <div class="descripcion"> <div class="price"> <span class="price-symbol">$</span> <span class="price-value">948</span> </div> <div class="descripcion-text"> Descripción </div> <div class="vendedor"> Vendedor </div> <div class="cantidad-vendidos"> 206 </div> </div> </article> </a> <a href="productoDetalle.php" class="irDescripcion"> <article > <div class="img-container"> <img src="img/phone.jpg" alt=""> </div> <div class="descripcion"> <div class="price"> <span class="price-symbol">$</span> <span class="price-value">948</span> </div> <div class="descripcion-text"> Descripción </div> <div class="vendedor"> Vendedor </div> <div class="cantidad-vendidos"> 206 </div> </div> </article> </a> <a href="productoDetalle.php" class="irDescripcion"> <article > <div class="img-container"> <img src="img/phone.jpg" alt=""> </div> <div class="descripcion"> <div class="price"> <span class="price-symbol">$</span> <span class="price-value">948</span> </div> <div class="descripcion-text"> Descripción </div> <div class="vendedor"> Vendedor </div> <div class="cantidad-vendidos"> 206 </div> </div> </article> </a> <a href="productoDetalle.php" class="irDescripcion"> <article > <div class="img-container"> <img src="img/phone.jpg" alt=""> </div> <div class="descripcion"> <div class="price"> <span class="price-symbol">$</span> <span class="price-value">948</span> </div> <div class="descripcion-text"> Descripción </div> <div class="vendedor"> Vendedor </div> <div class="cantidad-vendidos"> 206 </div> </div> </article> </a> <a href="productoDetalle.php" class="irDescripcion"> <article > <div class="img-container"> <img src="img/phone.jpg" alt=""> </div> <div class="descripcion"> <div class="price"> <span class="price-symbol">$</span> <span class="price-value">948</span> </div> <div class="descripcion-text"> Descripción </div> <div class="vendedor"> Vendedor </div> <div class="cantidad-vendidos"> 206 </div> </div> </article> </a> <a href="productoDetalle.php" class="irDescripcion"> <article > <div class="img-container"> <img src="img/phone.jpg" alt=""> </div> <div class="descripcion"> <div class="price"> <span class="price-symbol">$</span> <span class="price-value">948</span> </div> <div class="descripcion-text"> Descripción </div> <div class="vendedor"> Vendedor </div> <div class="cantidad-vendidos"> 206 </div> </div> </article> </a> <a href="productoDetalle.php" class="irDescripcion"> <article > <div class="img-container"> <img src="img/phone.jpg" alt=""> </div> <div class="descripcion"> <div class="price"> <span class="price-symbol">$</span> <span class="price-value">948</span> </div> <div class="descripcion-text"> Descripción </div> <div class="vendedor"> Vendedor </div> <div class="cantidad-vendidos"> 206 </div> </div> </article> </a> <div class="pagination-container"> <ul> <li><a href=""><i class='fas'>&#xf104;</i> Anterior</a></li> <li><a href="">1</a></li> <li><a href="">2</a></li> <li><a href="">3</a></li> <li><a href="">4</a></li> <li><a href="">5</a></li> <li><a href="">6</a></li> <li><a href="">7</a></li> <li><a href="">8</a></li> <li><a href="">9</a></li> <li><a href="">10</a></li> <li><a href="">Siguiente <i class='fas'>&#xf105;</i></a></li> </ul> </div> </section> </div> </main> <!-- MainBody End ============================= --> <!-- Modal --> <div class="modal fade" id="exampleModalScrollable" tabindex="-1" role="dialog" aria-labelledby="exampleModalScrollableTitle" aria-hidden="true"> <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalScrollableTitle">Carrito</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <table class="table table-bordered"> <thead> <!--Fila de detalle de cada producto--> <tr> <th>Product</th> <th>Description</th> <th>Quantity/Update</th> <th>Price</th> </tr> </thead> <tbody> <!--Filas y columnas--> <tr> <td> <img width="60" src="img/phone.jpg" alt="phone.jpg"/></td> <td>MASSA AST<br/>Color : black, Material : metal</td> <td> <div class="input-append"> <input class="span1" style="max-width:34px" placeholder="1" id="appendedInputButtons" size="16" type="text"> <button class="btn" type="button"> <i class="fas fa-minus"></i> </button> <button class="btn" type="button"> <i class="fas fa-plus"></i> </button> <button class="btn btn-danger" type="button"> <i class="far fa-times-circle"></i> </button> </div> </td> <td>$120.00</td> </tr> <tr> <td> <img width="60" src="img/phone.jpg" alt="phone.jpg"/></td> <td>MASSA AST<br/>Color : black, Material : metal</td> <td> <div class="input-append"> <input class="span1" style="max-width:34px" placeholder="1" size="16" type="text"> <button class="btn" type="button"> <i class="fas fa-minus"></i> </button> <button class="btn" type="button"> <i class="fas fa-plus"></i> </button> <button class="btn btn-danger" type="button"> <i class="far fa-times-circle"></i> </button> </div> </td> <td>$7.00</td> </tr> <tr> <td> <img width="60" src="img/phone.jpg" alt="phone.jpg"/></td> <td>MASSA AST<br/>Color : black, Material : metal</td> <td> <div class="input-append"> <input class="span1" style="max-width:34px" placeholder="1" size="16" type="text"> <button class="btn" type="button"> <i class="fas fa-minus"></i> </button> <button class="btn" type="button"> <i class="fas fa-plus"></i> </button> <button class="btn btn-danger" type="button"> <i class="far fa-times-circle"></i> </button> </div> </td> <td>$120.00</td> </tr> <!--Fila que muestra el total del carrito--> <tr> <td colspan="3" style="text-align:right">Total Price: </td> <td> $228.00</td> </tr> <tr> <td colspan="3" style="text-align:right">Total Discount: </td> <td> $50.00</td> </tr> <tr> <td colspan="3" style="text-align:right">Total Tax: </td> <td> $31.00</td> </tr> <tr> <td colspan="3" style="text-align:right"><strong>TOTAL ($228 - $50 + $31) =</strong></td> <td class="label label-important" style="display:block"> <strong> $155.00 </strong></td> </tr> </tbody> </table> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> </div> </div> </div> </div> <!-- Fin modal --> <!-- Footer ================================================================== --> <?php include_once("includes/footer.php"); ?> <!-- Footer End================================================================== --> <?php include_once("includes/scriptBootstrap.php") ?> <script src="https://kit.fontawesome.com/a076d05399.js"></script> </body> </html> <file_sep>/includes/footer.php <footer class="container-fluid bg-dark px-auto py-4 footer-cambiado "> <!-- Footer ================================================================== --> <div class="row d-flex justify-content-between"> <div class="col-12 col-sm-4 col-md-4 col-lg-4 col-xd-4"> <h5>ACCOUNT</h5> <a href="login.php" class="">YOUR ACCOUNT</a> <a href="login.php">PERSONAL INFORMATION</a> <a href="login.php">ADDRESSES</a> <a href="login.php">DISCOUNT</a> <a href="login.php">ORDER HISTORY</a> </div> <div class="col-12 col-sm-4 col-md-4 col-lg-4 col-xd-4"> <h5>INFORMATION</h5> <a href="contacto.php">CONTACT</a> <a href="registro.php">REGISTRATION</a> <a href="legal_notice.html">LEGAL NOTICE</a> <a href="tac.html">TERMS AND CONDITIONS</a> <a href="faq.php">FAQ</a> </div> <div id="" class="col-12 col-sm-4 col-md-4 col-lg-4 col-xd-4 social text-center"> <h5 class="social">SOCIAL MEDIA </h5> <a href="#" class="social"><img width="60" height="60" src="https://live.staticflickr.com/65535/49093342407_45310a774c_o.png" title="facebook" alt=""/></a> <a href="#" class="social"><img width="60" height="60" src="https://live.staticflickr.com/65535/49092642883_c0782ddd4d_o.png" title="twitter" alt=""/></a> <a href="#" class="social"><img width="60" height="60" src="https://live.staticflickr.com/65535/49092641488_040001d127_o.png" title="youtube" alt=""/></a> </div> </div> <p class="mx-auto text-center my-2 py-2">Copyright &copy; Your Website 2019</p> <!-- Container End --> <!-- Footer End================================================================== --> </footer><file_sep>/includes/headerAdm.php <!--Comienza el nav--> <nav class="navbar navbar-expand-lg navbar-dark bg-dark barra"> <!--Comienza el nombre de la empresa--> <a class="navbar-brand" href="home.php"> <img src="img/e-com1.png" width="30" height="30" class="d-inline-block align-top logo" alt=""> <span>E-commerce</span> </a> <!--Fin el nombre de la empresa--> <!--Comienza el buscador--> <form class=" d-md-inline-block form-inline mx-auto my-2 my-md-0"> <div class="input-group"> <input type="text" class="form-control" placeholder="Buscar producto...." aria-label="Search" aria-describedby="basic-addon2"> <div class="input-group-append"> <button class="btn btn-primary" type="button"> <img src="img/lupa.png" width="20" height="20" class="d-inline-block align-top" alt=""> </button> </div> </div> </form> <!--fin el buscador--> <!--Comienza del menu complimido--> <!--Comienza el icono de complimido--> <button class="navbar-toggler col-12 col-sm-3" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span>Menu</span> <span class="navbar-toggler-icon"></span> </button> <!--fin el icono de complimido--> <!--Comienza el menu descomplimido--> <div class="collapse navbar-collapse " id="navbarNav"> <ul class="navbar-nav ml-md-auto"> <li class="nav-item "> <a class="nav-link" href="home.php">Home <span class="sr-only">(current)</span></a> </li> <?php if (isset($_SESSION["activeUser"]) && $pagina!="Registro" && $pagina!="Login" ): ?> <li class="nav-item"> <a class="nav-link text-primary" href="resumen.php"><?=(isset($_SESSION["activeUser"]["usuario"]))?$_SESSION["activeUser"]["usuario"]:"usuario";?></a> </li> <li class="nav-item"> <a class="nav-link text-primary" href="logOut.php">Cerrar Sesion</a> </li> <?php else: ?> <li class="nav-item"> <a class="nav-link text-primary" href="login.php">Iniciar Sesion</a> </li> <li class="nav-item"> <a class="nav-link text-primary" href="registro.php">Registrarse</a> </li> <?php endif ?> <li class="nav-item"> <a class="nav-link" href="faq.php">Ayuda <img src="img/pregunta.png" width="25" height="25" class="d-inline-block align-top ml-auto logo" alt=""></a> </li> </ul> </div> <!--fin el menu descomplimido--> <!--Comienza del menu complimido--> </nav> <file_sep>/css/faq.less main{ margin-top: 70px; min-height: 80vh; .inner-main{ max-width: 1100px; margin: 0 auto; #accordionFaq{ .ch-datagrid.table{ td{ border: 1px solid #0004; } } } } }<file_sep>/css/home.less .inner-main#home{ padding: 70px 10px; min-height: 700px; #carouselExampleIndicators{ background-color: white; margin: 0 auto; max-width: 600px; .carousel-inner{ .carousel-item{ img{ } } } } .welcome{ width: 100%; border-radius: 5px; padding: 5px; .inner-welcome{ display: flex; justify-content: center; border-radius: 5px; width: 100%; .img{ img{ height: 70px; } } .text{ text-align: center; color: #0000; background-image: linear-gradient(to top, #fdc, #ccd, #fec); background-clip: text; } } } .categorias{ padding: 40px 0; display: grid; gap: 1px; width: 50%; margin: 0 auto; grid-template-columns: 150px 150px 150px 150px; justify-content: center; .categoria{ background-image: radial-gradient( #fff, rgb(240, 239, 232)); display: flex; flex-direction: column; justify-content: space-around; &:hover{ background-image: none; filter: invert(0.9); cursor: pointer; } .icono{ margin: 0 auto; display: flex; align-content: center; justify-content: center; img{ width: 70%; } } .titulo{ text-align: center; font-weight: bold; } } } } @media (max-width: 620px) { .inner-main#home{ padding-top: 120px; } .categorias{ grid-template-columns: 150px 150px 150px; } } @media (max-width: 480px) { .inner-main#home{ padding-top: 180px; } .categorias{ grid-template-columns: 150px 150px; } }<file_sep>/index.php <?php // require_once "home.html"; header("Location: home.php"); ?><file_sep>/includes/ubicacionPerfil.php <ul class="breadcrumb col-12"> <li><a href="home.html">Home</a><span class="divider">/</span></li> <li>Cuenta<span class="divider">/</span></li> <li class="active"><?=$pagina; ?></li> </ul><file_sep>/formAgregarCategoria.php <?php require_once 'clases/Conexion.php'; include 'includes/head.php'; include 'includes/headerAdm.php'; ?> <main class="container"> <h1>Alta de una categoria</h1> <form action="agregarCategoria.php" method="post"> Categoria: <br> <input type="text" name="categoria" class="form-control" required> <br> <input type="submit" value="Agregar Categoria" class="btn btn-secondary"> <a href="abmCategoria.php" class="btn btn-light">Volver a admin de categorias</a> </form> </main> <?php include 'includes/footer.php'; ?><file_sep>/clases/UsuarioComun.php <?php class UsuarioComun{ private $sexo; private $telefono; private $dni; private $fechaNacimiento; private $tarjeta; private $domicilio; private $carrito; private $facturas; private $foto; /** * Get the value of sexo */ public function getSexo() { return $this->sexo; } /** * Set the value of sexo * * @return self */ public function setSexo($sexo) { $this->sexo = $sexo; return $this; } /** * Get the value of telefono */ public function getTelefono() { return $this->telefono; } /** * Set the value of telefono * * @return self */ public function setTelefono($telefono) { $this->telefono = $telefono; return $this; } /** * Get the value of dni */ public function getDni() { return $this->dni; } /** * Set the value of dni * * @return self */ public function setDni($dni) { $this->dni = $dni; return $this; } /** * Get the value of fechaNacimiento */ public function getFechaNacimiento() { return $this->fechaNacimiento; } /** * Set the value of fechaNacimiento * * @return self */ public function setFechaNacimiento($fechaNacimiento) { $this->fechaNacimiento = $fechaNacimiento; return $this; } /** * Get the value of tarjeta */ public function getTarjeta() { return $this->tarjeta; } /** * Set the value of tarjeta * * @return self */ public function setTarjeta($tarjeta) { $this->tarjeta = $tarjeta; return $this; } /** * Get the value of domicilio */ public function getDomicilio() { return $this->domicilio; } /** * Set the value of domicilio * * @return self */ public function setDomicilio($domicilio) { $this->domicilio = $domicilio; return $this; } /** * Get the value of carrito */ public function getCarrito() { return $this->carrito; } /** * Set the value of carrito * * @return self */ public function setCarrito($carrito) { $this->carrito = $carrito; return $this; } /** * Get the value of facturas */ public function getFacturas() { return $this->facturas; } /** * Set the value of facturas * * @return self */ public function setFacturas($facturas) { $this->facturas = $facturas; return $this; } /** * Get the value of foto */ public function getFoto() { return $this->foto; } /** * Set the value of foto * * @return self */ public function setFoto($foto) { $this->foto = $foto; return $this; } } ?><file_sep>/clases/TipoUsuario.php <?php class TipoUsuario{ private $id; private $tipo_usuario; public function obtenerListaTipoUsuario(){ $db=Conexion::conectar(); try { $sql = "SELECT id_tipo_cliente as id,nombre as tipo_usuario FROM tipo_usuario"; $stmt = $db->prepare($sql); $stmt->execute(); //$variable = $stmt->fetchAll(PDO::FETCH_ASSOC);//array asociado $variable = $stmt->fetchAll(PDO::FETCH_CLASS,"TipoUsuario");//objeto $stmt->closeCursor(); return $variable; } catch (\Exception $e) { echo "Error al obtener Lista de Sexos"; $e->getMessage(); return false; } } /** * Get the value of id */ public function getId() { return $this->id; } /** * Set the value of id * * @return self */ public function setId($id) { $this->id = $id; return $this; } /** * Get the value of tipo_usuario */ public function getTipo_usuario() { return $this->tipo_usuario; } /** * Set the value of tipo_usuario * * @return self */ public function setTipo_usuario($tipo_usuario) { $this->tipo_usuario = $tipo_usuario; return $this; } } ?><file_sep>/formModificarCategoria.php <?php require_once 'clases/Conexion.php'; include 'includes/head.php'; include 'includes/headerAdm.php'; require 'clases/Categoria.php'; if(isset($_REQUEST['id'])) { $objCategoria = new Categoria; $id_categoria=$_REQUEST['id']; $categoria=$objCategoria->verCategoriaPorID($id_categoria); //var_dump($Categoria); } ?> <main class="container"> <h1> Actualizacion de una Categoria</h1> <form action="modificarCategoria.php" method="post"> Categoria: <input type="hidden" name="id_categoria" value="<?php echo $categoria['id_categoria'];?>" /> <br> <input type="text" name="categoria" value="<?php echo $categoria['categoria'];?>" class="form-control" required> <br> <input type="submit" value="Modificar Categoria" class="btn btn-secondary"> <a href="abmCategoria.php" class="btn btn-light">Volver a admin de categorias</a> </form> </main> <?php include 'includes/footer.php'; ?><file_sep>/includes/head.php <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <!--Fon awesome--> <script src="https://kit.fontawesome.com/67f61afa3e.js" crossorigin="anonymous"></script> <!--Google fonts--> <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600|Roboto:500,700&display=swap" rel="stylesheet"> <link rel="shortcut icon" href="favicon.ico"/> <!-- Bootstrap style responsive --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <link rel="stylesheet" href="css/styles.css"> </head>
508f6b1e075c11489c7d81ef4634b3171c5879b7
[ "Hack", "SQL", "PHP", "Less", "CSS" ]
65
Hack
ELCHE16/G5-E-Commerce-DH
71ef1d22d9a708c044307c9cd4620630957e29da
2779a8159ece78437637069de5ee87fa20921fd7
refs/heads/master
<repo_name>yakovlevavaleria/-alculator<file_sep>/example/CMakeLists.txt cmake_minimum_required(VERSION 2.8) project (-alculator_example) set(SOURCES main.cpp) add_executable (${PROJECT_NAME} ${SOURCES}) target_link_libraries(${PROJECT_NAME} -alculator) <file_sep>/include/calculator.hpp double sumary(double a, double b); double differense(double a, double b); double multiplication(double a, double b); double quotient(double a, double b); double power(double a, int c); double squareroot(double a); double absolut(double a); double roundp(double a); <file_sep>/README.md # -alcular [![Build Status](https://travis-ci.org/yakovlevavaleria/-alculator.svg?branch=master)](https://travis-ci.org/yakovlevavaleria/-alculator) <file_sep>/sources/calculator.cpp double sum(double a, double b) { return a + b; } double subtraction(double a, double b) { return a - b; } double multiplication(double a, double b) { return a*b; } double division(double a, double b) { return a / b; } double power(double a, double b) { double c = 1; if (b>0) for (int i = 0; i < b; i++) c = c*a; if (b<0) for (int i = 0; i < (-b); i++) c = c / a; return c; } double squareroot(double a) { double i = 0; while (i*i < a) i = i + 0.000001; return i; } double absolut(double a) { return ((a >= 0) ? a : -a); } double roundp(double a) { if (a < 0) a = -absolut(a); return a; } <file_sep>/tests/source/init.cpp #include <calculator.hpp> #include <catch.hpp> SCENARIO("calculator summary", "[summary]") { float a = 2.0; float b = 5.0; float rv = summary(a,b); REQUIRE( rv == 7.0); } SCENARIO("calculator sub", "[sub]") { float a = 5.0; float b = 2.0; float rv = sub(a,b); REQUIRE (rv ==3.0); } SCENARIO("calculator multiplication", "[multiplication]") { float a = 5.0; float b = 2.0; float rv = multiplication(a,b); REQUIRE (rv ==10.0); } SCENARIO("calculator division", "[division]") { float a = 5.0; float b = 2.0; float rv = division(a,b); REQUIRE (rv ==2.5); } SCENARIO("calculator involution", "[involution]") { float a = 5.0; float b = 2.0; float rv = involution(a,b); REQUIRE (rv ==25.0); } SCENARIO ("calculator square-root", "[square_root]"){ float x = 0.25; double long rv = square_root (x); REQUIRE ( rv == 0.5 ); } <file_sep>/example/main.cpp #include "stdafx.h" #include <iostream> using namespace std; double sum(double a, double b) { return a + b; } double subtraction(double a, double b) { return a - b; } double multiplication(double a, double b) { return a*b; } double division(double a, double b) { return a / b; } double power(double a, double b) { double c = 1; if (b>0) for (int i = 0; i < b; i++) c = c*a; if (b<0) for (int i = 0; i < (-b); i++) c = c / a; return c; } double squareroot(double a) { double i = 0; while (i*i < a) i = i + 0.000001; return i; } double absolut(double a) { return ((a >= 0) ? a : -a); } double roundp(double a) { if (a < 0) a = -absolut(a); return a; } int main() { int a, b, c; setlocale(LC_ALL, "rus"); cout << "Введите число a="; cin >> a; cout << "Введите число b="; cin >> b; cout << "Введите число c="; cin >> c; cout << "Сумма чисел a+b= " << roundp(sum(a, b)) << endl; cout << "Разность чисел a-b= " << roundp(subtraction(a, b)) << endl; cout << "Произведение чисел a*b= " << roundp(multiplication(a, b)) << endl; cout << "Честное чисел a/b= " << roundp(division(a, b)) << endl; cout << "Возведение в степень a^b= " << roundp(power(a, b)) << endl; if (a >= 0) cout << "Корень из a " << squareroot(a) << endl; else cout << "Корень извлечь нельзя" << endl; system("pause"); }
c8d714fa41fd52223602e3f7ff72be1f1eceab90
[ "Markdown", "C++", "CMake" ]
6
Markdown
yakovlevavaleria/-alculator
516e9f016e6f3a2d617ea5b9484be2a2ada9cbf6
70310e261167cd77d4dec3b2a9d39d33e1bbe64b
refs/heads/master
<repo_name>tagenasec/go-assumerole<file_sep>/Makefile all: go build -o go-assumerole main.go cp -a go-assumerole ../org/go-assumerole <file_sep>/assumerole/config.go package assumerole import ( "context" "github.com/apex/log" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/service/sts" ) type AssumeRole struct { cfg aws.Config stsSvc *sts.Client } func NewAssumeRoleFromProfileName(profileName string) (*AssumeRole, error) { log.WithField("profile", profileName).Info("Configuring using profile name") awsConfig, err := config.LoadDefaultConfig(context.TODO(), config.WithSharedConfigProfile(profileName)) if err != nil { log.WithField("profile", profileName).WithError(err).Error("Unable to load AWS config from profile name") return nil, err } awsConfig.Region = "us-east-1" return &AssumeRole{ cfg: awsConfig, stsSvc: sts.NewFromConfig(awsConfig), }, nil } <file_sep>/go.mod module github.com/tagenasec/go-assumerole go 1.16 require ( github.com/apex/log v1.9.0 github.com/aws/aws-sdk-go-v2 v1.8.1 // indirect github.com/aws/aws-sdk-go-v2/config v1.6.1 github.com/aws/aws-sdk-go-v2/credentials v1.3.3 // indirect github.com/aws/aws-sdk-go-v2/service/iam v1.8.1 github.com/aws/aws-sdk-go-v2/service/sts v1.6.2 // indirect github.com/pkg/errors v0.9.1 // indirect github.com/spf13/cobra v1.2.1 ) <file_sep>/assumerole/rolearn.go package assumerole import ( "context" "fmt" "github.com/apex/log" "github.com/aws/aws-sdk-go-v2/service/sts" ) func RoleArnFromAccountAndRoleName(accountId string, roleName string) string { return fmt.Sprintf("arn:aws:iam::%s:role/%s", accountId, roleName) } func (self *AssumeRole) RoleArnFromRoleNameInThisAccount(roleName string) (string, error) { callerIdentity, err := self.stsSvc.GetCallerIdentity(context.TODO(), &sts.GetCallerIdentityInput{}) if err != nil { log.WithError(err).Error("Unable to get caller identity") return "", err } return RoleArnFromAccountAndRoleName(*callerIdentity.Account, roleName), nil } <file_sep>/assumerole/environment.go package assumerole import ( "os" "github.com/apex/log" "github.com/aws/aws-sdk-go-v2/service/sts" ) func SetEnvironmentForAssumedRole(assumedRole *sts.AssumeRoleOutput) error { os.Unsetenv("AWS_PROFILE") err := os.Setenv("AWS_ACCESS_KEY_ID", *assumedRole.Credentials.AccessKeyId) if err != nil { log.WithError(err).Error("Unable to set environment") return err } os.Setenv("AWS_SECRET_ACCESS_KEY", *assumedRole.Credentials.SecretAccessKey) if err != nil { log.WithError(err).Error("Unable to set environment") return err } os.Setenv("AWS_SESSION_TOKEN", *assumedRole.Credentials.SessionToken) if err != nil { log.WithError(err).Error("Unable to set environment") return err } return nil } func (self *AssumeRole) AssumeRoleAndOpenShell(roleArn string) error { credentials, err := self.AssumeRoleArn(roleArn) if err != nil { log.WithError(err).Error("Unable to assume role") return err } err = SetEnvironmentForAssumedRole(credentials) if err != nil { log.WithError(err).Error("Unable to set environment") return err } shell := os.Getenv("SHELL") err = doExec(shell, []string{}, map[string]string{}) if err != nil { log.WithField("shell", shell).WithError(err).Error("Unable to exec SHELL") return err } return nil } <file_sep>/assumerole/doexec.go package assumerole import ( "os" "os/exec" "syscall" "github.com/apex/log" ) func doExec(executable string, args []string, environ map[string]string) error { absoluteExecutable, err := exec.LookPath(executable) if err != nil { log.WithField("args", args).WithError(err).WithField("executable", executable).Fatal("Unable to find executable") return err } realArgs := []string{executable} realArgs = append(realArgs, args...) finalEnviron := append([]string{}, os.Environ()...) for key, value := range environ { finalEnviron = append(finalEnviron, key+"="+value) } err = syscall.Exec(absoluteExecutable, realArgs, finalEnviron) if err != nil { log.WithField("args", args).WithError(err).WithField("executable", absoluteExecutable).Fatal("Unable to exec") return err } return nil } <file_sep>/main.go package main import ( "os" "strings" "github.com/apex/log" "github.com/pkg/errors" "github.com/spf13/cobra" "github.com/tagenasec/go-assumerole/assumerole" ) func main() { log.SetLevel(log.DebugLevel) role := "" profile := "" rootCmd := &cobra.Command{ Use: "assumerole [options]", Short: "Open a new shell with aws environment variables for an assumed role", RunE: func(cmd *cobra.Command, args []string) error { if role == "" { return errors.Errorf("Must specify -r (or --role)") } if profile == "" { profile = "default" } assumeRole, err := assumerole.NewAssumeRoleFromProfileName(profile) if err != nil { log.WithError(err).Error("Unable to create assume role object") return err } if !strings.HasPrefix(role, "arn:") { roleArn, err := assumeRole.RoleArnFromRoleNameInThisAccount(role) if err != nil { log.WithError(err).Error("Unable to get role arn") return err } role = roleArn } err = assumeRole.AssumeRoleAndOpenShell(role) if err != nil { log.WithError(err).Error("Assume operation failed") return err } return nil }, } rootCmd.PersistentFlags().StringVarP(&role, "role", "r", "", "role name to assume to") rootCmd.PersistentFlags().StringVarP(&profile, "profile", "p", os.Getenv("AWS_PROFILE"), "aws profile to assume from") if err := rootCmd.Execute(); err != nil { os.Exit(1) } os.Exit(0) } <file_sep>/assumerole/assumerole.go package assumerole import ( "context" "fmt" "strings" "github.com/apex/log" "github.com/aws/aws-sdk-go-v2/credentials/stscreds" "github.com/aws/aws-sdk-go-v2/service/iam" "github.com/aws/aws-sdk-go-v2/service/sts" ) func (self *AssumeRole) AssumeRoleArn(targetRoleArn string) (*sts.AssumeRoleOutput, error) { log.Info("Attempting to assume role") callerIdentity, err := self.stsSvc.GetCallerIdentity(context.TODO(), nil) if err != nil { log.WithError(err).Error("Unable to get caller identity") return nil, err } userName := strings.Split(*callerIdentity.Arn, "/")[1] iamSvc := iam.NewFromConfig(self.cfg) mfaDevicesList, err := iamSvc.ListMFADevices(context.TODO(), &iam.ListMFADevicesInput{ UserName: &userName, }) if err != nil { log.WithError(err).Error("Unable to fetch mfa devices") return nil, err } if len(mfaDevicesList.MFADevices) == 0 { log.Error("User has no mfa devices") return nil, fmt.Errorf("User has no mfa devices") } if len(mfaDevicesList.MFADevices) > 1 { log.Error("User has more than one MFA device") return nil, fmt.Errorf("User has more than one MFA device") } serialNumber := mfaDevicesList.MFADevices[0].SerialNumber token, err := stscreds.StdinTokenProvider() if err != nil { log.WithError(err).Error("Unable to get Token from user") return nil, err } roleSessionName := fmt.Sprintf("cli-by-%s", userName) credentials, err := self.stsSvc.AssumeRole(context.TODO(), &sts.AssumeRoleInput{ RoleArn: &targetRoleArn, RoleSessionName: &roleSessionName, SerialNumber: serialNumber, TokenCode: &token, }) if err != nil { log.WithError(err).Error("Unable to assume role") return nil, err } log.Info("Successfully assumed role") return credentials, nil }
226226ffdb5fe24d67c111efd3b6bcade0b50a17
[ "Makefile", "Go Module", "Go" ]
8
Makefile
tagenasec/go-assumerole
65c5cb010f4a73e4972a5a56409cba75c4b2ea83
2b6131e411b8b4535a1cdad00892d051ed50d371
refs/heads/master
<repo_name>Soneritics/Twinfield.API<file_sep>/Api/Exceptions/TokenExpiredException.cs using System; using System.Runtime.Serialization; namespace Api.Exceptions { public class TokenExpiredException : Exception { public TokenExpiredException() { } protected TokenExpiredException(SerializationInfo info, StreamingContext context) : base(info, context) { } public TokenExpiredException(string message) : base(message) { } public TokenExpiredException(string message, Exception innerException) : base(message, innerException) { } } } <file_sep>/Demo/KeyVaultDemo.cs using System; using System.Threading.Tasks; using Api; using Api.Dto.OAuth; using Api.Exceptions; using Azure; using Azure.Identity; using Azure.Security.KeyVault.Secrets; using Newtonsoft.Json; namespace Demo { /// <summary> /// This demo shows how to store the key in KeyVault, so it /// can be used for background processes. /// </summary> public static class KeyVaultDemo { // OAuth settings private static OAuthClientSettings oauthClientSettings = new OAuthClientSettings() { Id = "", Secret = "" }; // This URL should catch the 'code' from the JSON which is POSTed after a successful user login private static string redirectUrl = "https://..."; // Keyvault URL private static string keyVaultUrl = "https://{keyVaultName}.vault.azure.net"; private static string keyVaultSecretName = "TwinfieldAccessToken"; public static async Task Run() { Console.WriteLine("Choose 1 or 2:\n\t1. Authorize (only needed once)\n\t2. Load the token from KeyVault and access Twinfield"); var program = Console.ReadLine(); switch (program) { case "1": await AuthorizeAndSaveTokenAsync(); break; case "2": await LoadTokenFromKeyVaultandRunDemoAsync(); break; default: Console.WriteLine("Invalid input."); break; } } private static async Task AuthorizeAndSaveTokenAsync() { // Create the TwinfieldApi var twinfieldApi = new TwinfieldApi(oauthClientSettings); // First get the authorization URL Console.WriteLine("Send the user to the following URL:"); Console.WriteLine(twinfieldApi.GetAuthorizationUrl(redirectUrl)); // Catch the authorization code in your own program, and paste it here Console.Write("\n\nEnter the code: "); var authenticationCode = Console.ReadLine(); // Get the access token await twinfieldApi .SetAccessTokenByAuthorizationCodeAsync(authenticationCode, redirectUrl); // Store the access token in KeyVault var accessToken = twinfieldApi.Token; Console.WriteLine("Saving access token to KeyVault.."); await StoreAccesstokenInKeyVaultAsync(accessToken); Console.WriteLine("Done."); } private static async Task LoadTokenFromKeyVaultandRunDemoAsync(bool canRetry = true) { // Create the TwinfieldApi var twinfieldApi = new TwinfieldApi(oauthClientSettings) { Token = await GetAccessTokenFromKeyVaultAsync() }; // Check if the token should be refreshed if (twinfieldApi.Token.IsExpired()) { Console.WriteLine("Token expired, refreshing.."); await twinfieldApi.RefreshTokenAsync(); await StoreAccesstokenInKeyVaultAsync(twinfieldApi.Token); } try { // The token should be good, make some calls to Twinfield now var officeList = await twinfieldApi.ServiceFactory.ProcessXmlDataService.GetOfficeList(); Console.WriteLine($"List of all {officeList.Count} offices:"); foreach (var o in officeList) { Console.WriteLine("{0,10} {1,20} {2}", o.Code, o.ShortName, o.Name); } // And place the rest of your logic here, including extra calls to Twinfield //... //... //... } catch (TokenExpiredException) { if (canRetry) { // Refresh the token await twinfieldApi.RefreshTokenAsync(); await StoreAccesstokenInKeyVaultAsync(twinfieldApi.Token); // Retry (once) await LoadTokenFromKeyVaultandRunDemoAsync(false); } else { // Token could not be refreshed. Throw exception and quit. throw; } } } private static async Task StoreAccesstokenInKeyVaultAsync(OAuthToken accessToken) { var client = new SecretClient( new Uri(keyVaultUrl), new DefaultAzureCredential() ); var jsonToken = JsonConvert.SerializeObject(accessToken); var secret = new KeyVaultSecret(keyVaultSecretName, jsonToken); await client.SetSecretAsync(secret); } private static async Task<OAuthToken> GetAccessTokenFromKeyVaultAsync() { try { var client = new SecretClient( new Uri(keyVaultUrl), new DefaultAzureCredential() ); var secret = await client.GetSecretAsync(keyVaultSecretName); var jsonToken = secret.Value.Value; return JsonConvert.DeserializeObject<OAuthToken>(jsonToken); } catch (RequestFailedException) { Console.WriteLine($"Key not found in KeyVault: {keyVaultSecretName}"); throw; } } } }<file_sep>/Api/Services/Data/IService.cs namespace Api.Services.Data { public interface IService { string ServiceEndpoint { get; } } } <file_sep>/Api/Dto/OAuth/OAuthSoapHeader.cs using System.Threading.Tasks; namespace Api.Dto.OAuth { public class OAuthSoapHeader : ISoapHeader { private readonly OAuthToken _oauthToken; public string ClusterUri { get; set; } = "https://api.accounting.twinfield.com"; public string Company { get; set; } public OAuthSoapHeader(OAuthToken oauthToken) { _oauthToken = oauthToken; } public async Task<TwinfieldFinderService.Header> GetHeaderAsync(TwinfieldFinderService.Header header) { header.AccessToken = _oauthToken.Accesstoken; if (!string.IsNullOrEmpty(Company)) header.CompanyCode = Company; return header; } public async Task<TwinfieldProcessXmlService.Header> GetHeaderAsync(TwinfieldProcessXmlService.Header header) { header.AccessToken = _oauthToken.Accesstoken; if (!string.IsNullOrEmpty(Company)) header.CompanyCode = Company; return header; } } } <file_sep>/Api/Services/Auth/AuthServiceBase.cs using System; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; using Api.Dto.OAuth; using Newtonsoft.Json; namespace Api.Services.Auth { public abstract class AuthServiceBase { public string LastError { get; protected set; } public HttpStatusCode LastRequestStatus { get; protected set; } protected readonly HttpClient HttpClient; protected AuthServiceBase(HttpClient httpClient) { HttpClient = httpClient; } public async Task<TResult> GetApiResult<TResult>( HttpMethod httpMethod, string endPoint, OAuthClientSettings credentials = null, List<KeyValuePair<string, string>> post = null) { var request = credentials == default ? await GetHttpRequestMessage(httpMethod, endPoint, post) : await GetAuthenticatedHttpRequestMessage(httpMethod, endPoint, credentials, post); var apiResult = await HttpClient.SendAsync(request); ProcessHttpHeaders(apiResult); return await GetProcessedResult<TResult>(apiResult); } protected virtual async Task<HttpRequestMessage> GetHttpRequestMessage( HttpMethod httpMethod, string endPoint, List<KeyValuePair<string, string>> post = null) { return await Task.Run(() => { var result = new HttpRequestMessage(httpMethod, endPoint); result.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); if (post != null) { result.Content = new FormUrlEncodedContent(post); result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded"); } return result; }); } protected async Task<HttpRequestMessage> GetAuthenticatedHttpRequestMessage( HttpMethod httpMethod, string endPoint, OAuthClientSettings credentials, List<KeyValuePair<string, string>> post = null) { var result = await GetHttpRequestMessage(httpMethod, endPoint, post); result.Headers.Authorization = new AuthenticationHeaderValue( "Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes($"{credentials.Id}:{credentials.Secret}")) ); return result; } /// <summary> /// Processes the HTTP headers. /// </summary> /// <param name="httpResponseMessage">The HTTP response message.</param> protected virtual void ProcessHttpHeaders(HttpResponseMessage httpResponseMessage) { LastRequestStatus = httpResponseMessage.StatusCode; } /// <summary> /// Gets the processed (deserialized) result. /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="httpResponseMessage">The HTTP response message.</param> /// <returns></returns> protected async Task<TResult> GetProcessedResult<TResult>(HttpResponseMessage httpResponseMessage) { if (!httpResponseMessage.IsSuccessStatusCode) throw await GetHttpException(httpResponseMessage); return await GetDeserializedResponse<TResult>(httpResponseMessage); } /// <summary> /// Gets the HTTP exception. /// </summary> /// <param name="httpResponseMessage">The HTTP response message.</param> /// <returns></returns> protected async Task<Exception> GetHttpException(HttpResponseMessage httpResponseMessage) { // First set the error message so it can be retrieved LastError = await httpResponseMessage.Content.ReadAsStringAsync(); // Throw exception with information try { httpResponseMessage.EnsureSuccessStatusCode(); } catch (Exception e) { return e; } // This should not happen return new Exception($"HttpRequestException occured with message: '{LastError}'"); } /// <summary> /// Gets the deserialized response from the API. /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="httpResponseMessage">The HTTP response message.</param> /// <returns></returns> protected async Task<TResult> GetDeserializedResponse<TResult>(HttpResponseMessage httpResponseMessage) { var msgString = await httpResponseMessage.Content.ReadAsStringAsync(); try { return JsonConvert.DeserializeObject<TResult>(msgString); } catch { return default; } } } }<file_sep>/Demo/Program.cs using System; using System.Threading.Tasks; namespace Demo { class Program { static async Task Main(string[] args) { Console.Write("Type 1 to run the full demo, 2 to run the KeyVault demo: "); var program = Console.ReadLine(); switch (program) { case "1": await FullDemo.Run(); break; case "2": await KeyVaultDemo.Run(); break; default: Console.WriteLine("Invalid input."); await Main(default); break; } } } }<file_sep>/Demo/FullDemo.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Api; using Api.Dto.OAuth; using Api.Dto.ProcessXml; using Api.Exceptions; using Api.Helpers; using Api.Utilities; namespace Demo { public static class FullDemo { // OAuth settings private static OAuthClientSettings oauthClientSettings = new OAuthClientSettings() { Id = "", Secret = "" }; // This URL should catch the 'code' from the JSON which is POSTed after a successful user login private static string redirectUrl = "https://..."; // In Example 1, this is read from the command line. // You can choose to fill it manually, so you don't need to go over the authorization flow. private static OAuthToken accessToken; // Determine what data to show private static string company = ""; private static int fromMonth = 0; private static int fromYear = DateTime.Now.Year; private static int toMonth = 2; private static int toYear = DateTime.Now.Year; #region Properties private static TwinfieldApi twinfieldApi; #endregion public static async Task Run() { // Create the TwinfieldApi twinfieldApi = new TwinfieldApi(oauthClientSettings); // You can also provide an HttpClient: // twinfieldApi = new TwinfieldApi(httpClient, oauthClientSettings); // Authorization flow await Example1(); Console.WriteLine($"Auth code: {accessToken.Accesstoken}"); // Instead of authenticating, you can also set the access token twinfieldApi.Token = accessToken; // Check if the token should be refreshed await Example2(); Console.WriteLine($"Auth code: {accessToken.Accesstoken}"); // Always try to catch a TokenExpiredException when calling the API try { // Get offices list and select the first await Example3(); // Get the fields for the balance sheet await Example4(); // Get the fields for profit and loss await Example5(); // Example 6: Get the general ledger request options // Example 7: Get a valid request, including range // Example 9: Reading data from the general ledger var requestOptions = await Example6(); var minimalRequestOptions = Example7(requestOptions); await Example9(minimalRequestOptions); // Example 8: Narrowing down the result of Example #6 even more // Example 9: Reading data from the general ledger minimalRequestOptions = Example8(requestOptions); await Example9(minimalRequestOptions); // Read data from the general ledger, based on the minimum request options. await Example10(); } catch (TokenExpiredException) { // Refresh the token and retry } } #region Examples /// <summary> /// Authorization flow. /// </summary> static async Task Example1() { // First get the authorization URL Console.WriteLine("Send the user to the following URL:"); Console.WriteLine(twinfieldApi.GetAuthorizationUrl(redirectUrl)); // Catch the authorization code in your own program, and paste it here Console.Write("\n\nEnter the code: "); var authenticationCode = Console.ReadLine(); // Get the access token await twinfieldApi .SetAccessTokenByAuthorizationCodeAsync(authenticationCode, redirectUrl); accessToken = twinfieldApi.Token; } /// <summary> /// Check if the token should be refreshed. /// </summary> static async Task Example2() { if (twinfieldApi.Token.IsExpired()) { Console.WriteLine("Token expired, refreshing.."); } else { Console.WriteLine("Token is not expired. Still refreshing :-)"); await Task.Delay(2000); } await twinfieldApi.RefreshTokenAsync(); accessToken = twinfieldApi.Token; // You should save the refreshed token, so you // can use it to call the Twinfield API the next time } /// <summary> /// Get offices list. /// </summary> static async Task Example3() { var officeList = await twinfieldApi.ServiceFactory.ProcessXmlDataService.GetOfficeList(); Console.WriteLine($"List of all {officeList.Count} offices:"); foreach (var o in officeList) { Console.WriteLine("{0,10} {1,20} {2}", o.Code, o.ShortName, o.Name); } var firstOffice = officeList.First(); Console.WriteLine($"Selecting office `{firstOffice.Name}` ({firstOffice.Code})"); twinfieldApi.SetCompany(firstOffice.Code); } /// <summary> /// Get the fields for the balance sheet. /// </summary> static async Task Example4() { var balanceSheetFields = await twinfieldApi .ServiceFactory .FinderDataService .GetBalanceSheetFields(company); Console.WriteLine("Balance sheet fields:"); foreach (var field in balanceSheetFields) { Console.WriteLine("{0,10} {1}", field.Key, field.Value); } } /// <summary> /// Get the fields for profit and loss. /// </summary> static async Task Example5() { var pnlFields = await twinfieldApi .ServiceFactory .FinderDataService .GetProfitAndLossFields(company); Console.WriteLine("Profit & Loss fields:"); foreach (var field in pnlFields) { Console.WriteLine("{0,10} {1}", field.Key, field.Value); } } /// <summary> /// Get the general ledger request options. /// </summary> /// <returns></returns> static async Task<List<GeneralLedgerRequestOption>> Example6() { var data = await twinfieldApi .ServiceFactory .ProcessXmlDataService .GetGeneralLedgerRequestOptions(company); Console.WriteLine("General Ledger request options:"); foreach (var d in data) { Console.WriteLine("{0,10} {1,35} {2,10} {3,10} {4,10} {5}", d.Id, d.Field, d.Operator, d.Ask, d.Visible, d.Label); } return data; } /// <summary> /// Get a valid request, including range. /// </summary> /// <param name="list">The list.</param> /// <returns></returns> static List<GeneralLedgerRequestOption> Example7(List<GeneralLedgerRequestOption> list) { var data = GeneralLedgerRequestOptionsHelper .GetRequestList(list, fromYear, fromMonth, toYear, toMonth); Console.WriteLine("General Ledger request:"); foreach (var d in data) { Console.WriteLine("{0,10} {1,35} {2,10} {3,10}", d.Id, d.Field, d.From, d.To); } return data; } /// <summary> /// Narrowing down the result of Example #6 even more. /// </summary> /// <param name="list">The list.</param> /// <returns></returns> static List<GeneralLedgerRequestOption> Example8(List<GeneralLedgerRequestOption> list) { var data = GeneralLedgerRequestOptionsHelper .GetRequestList( list, fromYear, fromMonth, toYear, toMonth, GeneralLedgerRequestOptionsLists.MinimalList ); Console.WriteLine("General Ledger request with minimum fields:"); foreach (var d in data) { Console.WriteLine("{0,10} {1,35} {2,10} {3,10}", d.Id, d.Field, d.From, d.To); } return data; } /// <summary> /// Reading data from the general ledger /// </summary> /// <param name="list">The list.</param> static async Task Example9(List<GeneralLedgerRequestOption> list) { var glData = await twinfieldApi .ServiceFactory .ProcessXmlDataService .GetGeneralLedgerData(list); Console.WriteLine("General Ledger data headers:"); foreach (var h in glData.Headers) { Console.WriteLine($"\t{h.Value.Label} ({h.Value.ValueType})"); } Console.WriteLine("General Ledger data lines (max 10 lines):"); foreach (var h in glData.Data.Where(d => d.FirstOrDefault(i => i.Field == "fin.trs.line.dim1type")?.Value.ToString() == "PNL")/*.Take(10)*/) { Console.WriteLine("{"); foreach (var r in h) { Console.WriteLine("\t{0,35} {1,25} {2}", r.Field, r.Label, r.Value); } Console.WriteLine("}"); } Console.WriteLine("{...}"); } /// <summary> /// Read data from the general ledger, based on the minimum request options. /// </summary> static async Task Example10() { var list = GeneralLedgerRequestOptionsLists.GetMinimumRequestOptionsList(fromYear, fromMonth, toYear, toMonth); await Example9(list); } #endregion } } <file_sep>/Api/Exceptions/UnknownValueTypeException.cs using System; using System.Runtime.Serialization; namespace Api.Exceptions { class UnknownValueTypeException : Exception { public UnknownValueTypeException() { } protected UnknownValueTypeException(SerializationInfo info, StreamingContext context) : base(info, context) { } public UnknownValueTypeException(string message) : base(message) { } public UnknownValueTypeException(string message, Exception innerException) : base(message, innerException) { } } } <file_sep>/Api/Services/Auth/AuthenticationService.cs using System; using System.Collections.Generic; using System.Net.Http; using System.Threading.Tasks; using Api.Dto.OAuth; namespace Api.Services.Auth { public class AuthenticationService : AuthServiceBase { private readonly OAuthClientSettings _oAuthClientSettings; public AuthenticationService(OAuthClientSettings oAuthClientSettings, HttpClient httpClient) : base(httpClient) { _oAuthClientSettings = oAuthClientSettings; } public string GetAuthorizationUrl(string redirectUrl, string state, string nonce) { return "https://login.twinfield.com/auth/authentication/connect/authorize" + $"?client_id={_oAuthClientSettings.Id}" + "&response_type=code&scope=openid+twf.organisationUser+twf.user+twf.organisation+offline_access" + $"&redirect_uri={redirectUrl}&state={state}&nonce={nonce}"; } public string GetAuthorizationUrl(string redirectUrl) { return GetAuthorizationUrl( redirectUrl, Guid.NewGuid().ToString(), Guid.NewGuid().ToString() ); } public async Task<OAuthToken> GetAccessTokenByAuthorizationCodeAsync(string authorizationCode, string redirectUrl) { var postObject = new List<KeyValuePair<string, string>> { new KeyValuePair<string, string>("grant_type", "authorization_code"), new KeyValuePair<string, string>("code", authorizationCode), new KeyValuePair<string, string>("redirect_uri", redirectUrl) }; var rawToken = await GetApiResult<RawToken>( HttpMethod.Post, "https://login.twinfield.com/auth/authentication/connect/token", _oAuthClientSettings, postObject ); return new OAuthToken() { Accesstoken = rawToken.Accesstoken, RefreshToken = rawToken.RefreshToken, ExpiresIn = rawToken.ExpiresIn }; } } } <file_sep>/Api/Extensions/XmlExtensions.cs using System.Xml; namespace Api.Extensions { /// <summary> /// Extensions for working with XML. /// </summary> internal static class XmlExtensions { /// <summary> /// Converts a string to an XmlNode. /// </summary> /// <param name="contents">The contents.</param> /// <returns></returns> public static XmlNode ToXmlNode(this string contents) { var xmlDoc = new XmlDocument(); xmlDoc.LoadXml(contents); return xmlDoc; } } } <file_sep>/Api/Services/Data/ProcessXmlDataService.cs using System.Collections.Generic; using System.Threading.Tasks; using System.Xml; using Api.Dto; using Api.Dto.ProcessXml; using Api.Dto.ProcessXml.GeneralLedgerData; using Api.Extensions; using Api.Helpers; using TwinfieldProcessXmlService; namespace Api.Services.Data { /// <summary> /// ProcessXmlDataService, uses the Twinfield ProcessXml API. /// </summary> /// <seealso cref="ProcessXmlSoapClient" /> public class ProcessXmlDataService : AbstractDataService<ProcessXmlSoapClient> { /// <summary> /// Gets or sets the soapHeader. /// </summary> /// <value> /// The soapHeader. /// </value> public ISoapHeader SoapHeader { get; set; } /// <summary> /// Gets the service endpoint. /// </summary> /// <value> /// The service endpoint. /// </value> public override string ServiceEndpoint { get; } = "/webservices/processxml.asmx"; /// <summary> /// Initializes a new instance of the <see cref="ProcessXmlDataService"/> class. /// Uses the SoapHeader object to authorize against the service. /// </summary> /// <param name="soapHeader">The soapHeader.</param> public ProcessXmlDataService(ISoapHeader soapHeader) : base(soapHeader.ClusterUri) { SoapHeader = soapHeader; SoapClient = new ProcessXmlSoapClient(GetServiceBinding(), GetEndpoint()); } /// <summary> /// Gets the office list from Twinfield. /// </summary> /// <returns></returns> public async Task<List<Office>> GetOfficeList() { var document = "<list><type>offices</type></list>"; var officeListResult = await SoapClient.ProcessXmlDocumentAsync( await SoapHeader.GetHeaderAsync(new Header()), document.ToXmlNode() ); var result = new List<Office>(); foreach (XmlNode node in officeListResult.ProcessXmlDocumentResult.ChildNodes) { result.Add(new Office() { Code = node.InnerText, Name = node.Attributes["name"]?.Value, ShortName = node.Attributes["shortname"]?.Value }); } return result; } /// <summary> /// Gets the general ledger request options. /// </summary> /// <param name="companyCode">The company code.</param> /// <returns></returns> public async Task<List<GeneralLedgerRequestOption>> GetGeneralLedgerRequestOptions(string companyCode) { var document = $"<read><type>browse</type><code>030_2</code><office>{companyCode}</office></read>"; var dataRequestOptions = await SoapClient.ProcessXmlDocumentAsync( await SoapHeader.GetHeaderAsync(new Header()), document.ToXmlNode() ); var result = new List<GeneralLedgerRequestOption>(); foreach (XmlNode node in dataRequestOptions.ProcessXmlDocumentResult.LastChild.ChildNodes) { var glro = new GeneralLedgerRequestOption() { Id = node.Attributes["id"]?.Value }; foreach (XmlNode childElement in node.ChildNodes) { switch (childElement.Name) { case "label": glro.Label = childElement.InnerText; break; case "field": glro.Field = childElement.InnerText; break; case "operator": glro.Operator = childElement.InnerText; break; case "visible": glro.Visible = childElement.InnerText.Equals("true"); break; case "ask": glro.Ask = childElement.InnerText.Equals("true"); break; } } result.Add(glro); } return result; } /// <summary> /// Read data from the the general ledger. /// </summary> /// <param name="requestOptions">The request options.</param> /// <returns></returns> public async Task<GeneralLedgerData> GetGeneralLedgerData(List<GeneralLedgerRequestOption> requestOptions) { var requestString = GeneralLedgerRequestOptionsParser.Parse(requestOptions); var balanceSheetDataResult = await SoapClient.ProcessXmlDocumentAsync( await SoapHeader.GetHeaderAsync(new Header()), requestString.ToXmlNode() ); var balanceSheetHeaders = new Dictionary<string, TwinfieldDataLineHeader>(); var balanceSheetDataList = new List<List<TwinfieldDataLine>>(); var firstNode = true; foreach (XmlNode row in balanceSheetDataResult.ProcessXmlDocumentResult) { if (firstNode) { foreach (XmlNode el in row.ChildNodes) { if (el.Name.Equals("td")) { balanceSheetHeaders[el.InnerText] = new TwinfieldDataLineHeader() { ValueType = el.Attributes["type"]?.Value, Label = el.Attributes["label"]?.Value }; } } firstNode = false; } else { var rowData = new List<TwinfieldDataLine>(); foreach (XmlNode el in row) { if (el.Name.Equals("td")) { rowData.Add(new TwinfieldDataLine() { Field = el.Attributes["field"]?.Value, Label = balanceSheetHeaders[el.Attributes["field"]?.Value]?.Label, Value = new TwinfieldValue(balanceSheetHeaders[el.Attributes["field"]?.Value]?.ValueType, el.InnerText) }); } } balanceSheetDataList.Add(rowData); } } return new GeneralLedgerData() { Headers = balanceSheetHeaders, Data = balanceSheetDataList }; } /// <summary> /// Releases unmanaged and - optionally - managed resources. /// </summary> /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> protected override void Dispose(bool disposing) { if (disposing) { SoapClient.CloseAsync(); } } } } <file_sep>/Api/Dto/ProcessXml/Office.cs namespace Api.Dto.ProcessXml { /// <summary> /// Office class /// </summary> public class Office { /// <summary> /// Gets or sets the office code. /// </summary> /// <value> /// The office code. /// </value> public string Code { get; set; } /// <summary> /// Gets or sets the office name. /// </summary> /// <value> /// The office name. /// </value> public string Name { get; set; } /// <summary> /// Gets or sets the office's short name. /// </summary> /// <value> /// The office's short name. /// </value> public string ShortName { get; set; } } } <file_sep>/Api/Dto/ProcessXml/GeneralLedgerRequestOption.cs namespace Api.Dto.ProcessXml { /// <summary> /// General ledger request option /// </summary> public class GeneralLedgerRequestOption { /// <summary> /// Gets or sets the identifier. /// </summary> /// <value> /// The identifier. /// </value> public string Id { get; set; } /// <summary> /// Gets or sets the label. /// </summary> /// <value> /// The label. /// </value> public string Label { get; set; } /// <summary> /// Gets or sets the field. /// </summary> /// <value> /// The field. /// </value> public string Field { get; set; } /// <summary> /// Gets or sets a value indicating whether this <see cref="GeneralLedgerRequestOption"/> is visible. /// </summary> /// <value> /// <c>true</c> if visible; otherwise, <c>false</c>. /// </value> public bool Visible { get; set; } /// <summary> /// Gets or sets a value indicating whether this <see cref="GeneralLedgerRequestOption"/> is ask. /// </summary> /// <value> /// <c>true</c> if ask; otherwise, <c>false</c>. /// </value> public bool Ask { get; set; } /// <summary> /// Gets or sets the operator. /// </summary> /// <value> /// The operator. /// </value> public string Operator { get; set; } /// <summary> /// Gets or sets from. /// </summary> /// <value> /// From. /// </value> public string From { get; set; } /// <summary> /// Gets or sets to. /// </summary> /// <value> /// To. /// </value> public string To { get; set; } } } <file_sep>/Api/TwinfieldApi.cs using System; using System.Net.Http; using System.Threading.Tasks; using Api.Dto.OAuth; using Api.Exceptions; using Api.Services; using Api.Services.Auth; namespace Api { public class TwinfieldApi { private readonly HttpClient _httpClient; private readonly OAuthClientSettings _oAuthClientSettings; private OAuthSoapHeader _soapHeader; #region Field private async Task<OAuthSoapHeader> GetSoapHeader() { return _soapHeader ??= new OAuthSoapHeader(Token) { ClusterUri = await AuthorizationService.GetClusterUrlAsync() }; } private OAuthToken _token; public OAuthToken Token { get => _token; set { _soapHeader = default; _token = value; } } protected AuthenticationService AuthenticationService => new AuthenticationService(_oAuthClientSettings, _httpClient); protected AuthorizationService AuthorizationService => new AuthorizationService(_oAuthClientSettings, Token, _httpClient); public ServiceFactory ServiceFactory { get { if (Token == default) { throw new MissingFieldException("Field `Token` has not been set"); } if (Token?.IsExpired() == true) { throw new TokenExpiredException(); } return new ServiceFactory(GetSoapHeader().GetAwaiter().GetResult()); } } #endregion public TwinfieldApi(HttpClient httpClient, OAuthClientSettings oAuthClientSettings) { _httpClient = httpClient; _oAuthClientSettings = oAuthClientSettings; } public TwinfieldApi(OAuthClientSettings oAuthClientSettings) : this(new HttpClient(), oAuthClientSettings) { } #region Authentication public string GetAuthorizationUrl(string redirectUrl, string state, string nonce) { return AuthenticationService .GetAuthorizationUrl(redirectUrl, state, nonce); } public string GetAuthorizationUrl(string redirectUrl) { return AuthenticationService .GetAuthorizationUrl(redirectUrl); } public async Task SetAccessTokenByAuthorizationCodeAsync(string authorizationCode, string redirectUrl) { Token = await AuthenticationService .GetAccessTokenByAuthorizationCodeAsync(authorizationCode, redirectUrl); } #endregion public async Task RefreshTokenAsync() { Token = await AuthorizationService.GetRefreshTokenAsync(); await GetSoapHeader(); } public async Task RefreshTokenAsync(string refreshToken) { Token = new OAuthToken() { RefreshToken = refreshToken }; await RefreshTokenAsync(); } public void SetCompany(string companyCode) { _soapHeader.Company = companyCode; } } } <file_sep>/azure-pipelines.yml trigger: - master pool: vmImage: 'windows-latest' variables: buildConfiguration: 'Release' steps: - task: DotNetCoreCLI@2 displayName: 'dotnet build' inputs: command: 'build' arguments: '--configuration $(buildConfiguration)' projects: '**/Api.csproj' - task: DotNetCoreCLI@2 displayName: "dotnet pack" inputs: command: 'pack' arguments: '--configuration $(buildConfiguration)' projects: '**/ApiI.csproj' - task: NuGetCommand@2 inputs: command: 'push' packagesToPush: '$(Build.ArtifactStagingDirectory)/**/*.nupkg;!$(Build.ArtifactStagingDirectory)/**/*.symbols.nupkg' nuGetFeedType: 'external' publishFeedCredentials: 'NuGet' packagesToPack: '**/Api.csproj' nobuild: true versioningScheme: 'off' <file_sep>/Api/Dto/ProcessXml/GeneralLedgerData/TwinfieldDataLine.cs namespace Api.Dto.ProcessXml.GeneralLedgerData { /// <summary> /// TwinfieldDataLine, contains a line of General Ledger data. /// </summary> public class TwinfieldDataLine { /// <summary> /// Gets or sets the field. /// </summary> /// <value> /// The field. /// </value> public string Field { get; set; } /// <summary> /// Gets or sets the label. /// </summary> /// <value> /// The label. /// </value> public string Label { get; set; } /// <summary> /// Gets or sets the value. /// </summary> /// <value> /// The value. /// </value> public TwinfieldValue Value { get; set; } } } <file_sep>/Api/Dto/ISoapHeader.cs using System.Threading.Tasks; namespace Api.Dto { public interface ISoapHeader { string ClusterUri { get; set; } Task<TwinfieldFinderService.Header> GetHeaderAsync(TwinfieldFinderService.Header header); Task<TwinfieldProcessXmlService.Header> GetHeaderAsync(TwinfieldProcessXmlService.Header header); } } <file_sep>/Api/Dto/ProcessXml/GeneralLedgerData/GeneralLedgerData.cs using System.Collections.Generic; namespace Api.Dto.ProcessXml.GeneralLedgerData { /// <summary> /// Data from the General Ledger. /// </summary> public class GeneralLedgerData { /// <summary> /// Gets or sets the headers. /// </summary> /// <value> /// The headers. /// </value> public Dictionary<string, TwinfieldDataLineHeader> Headers { get; set; } /// <summary> /// Gets or sets the data. /// </summary> /// <value> /// The data. /// </value> public List<List<TwinfieldDataLine>> Data { get; set; } } } <file_sep>/Api/Services/Data/FinderDataService.cs using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Api.Dto; using Api.Dto.Financial; using TwinfieldFinderService; namespace Api.Services.Data { /// <summary> /// FinderDataService, uses the Twinfield Finder API. /// </summary> /// <seealso cref="FinderSoapClient" /> public class FinderDataService : AbstractDataService<FinderSoapClient> { /// <summary> /// Gets or sets the soapHeader. /// </summary> /// <value> /// The soapHeader. /// </value> public ISoapHeader SoapHeader { get; set; } /// <summary> /// Gets the service endpoint. /// </summary> /// <value> /// The service endpoint. /// </value> public override string ServiceEndpoint { get; } = "/webservices/finder.asmx"; /// <summary> /// Initializes a new instance of the <see cref="FinderDataService"/> class. /// Uses the SoapHeader object to authorize against the service. /// </summary> /// <param name="soapHeader">The soapHeader.</param> public FinderDataService(ISoapHeader soapHeader) : base(soapHeader.ClusterUri) { SoapHeader = soapHeader; SoapClient = new FinderSoapClient(GetServiceBinding(), GetEndpoint()); } /// <summary> /// Gets the balance sheet fields (code & name). /// </summary> /// <param name="companyCode">The company code.</param> /// <returns></returns> public async Task<Dictionary<string, string>> GetBalanceSheetFields(string companyCode) { return await GetFields(companyCode, FinancialType.BalanceSheet); } /// <summary> /// Gets the profit and loss fields (code & name). /// </summary> /// <param name="companyCode">The company code.</param> /// <returns></returns> public async Task<Dictionary<string, string>> GetProfitAndLossFields(string companyCode) { return await GetFields(companyCode, FinancialType.ProfitAndLoss); } /// <summary> /// Gets the fields for either a Balance Sheet or Profit and Loss. /// </summary> /// <param name="companyCode">The company code.</param> /// <param name="financialType">Type of the dim. BAS for Balance Sheet, PNL for Profit and Loss</param> /// <returns></returns> private async Task<Dictionary<string, string>> GetFields(string companyCode, string financialType) { var searchRequest = new SearchRequest() { Header = await SoapHeader.GetHeaderAsync(new Header()), type = "DIM", pattern = "*", field = 0, firstRow = 1, maxRows = int.MaxValue, options = new[] { new [] { "section", "financials" }, new [] { "dimtype", financialType }, new [] { "office", companyCode } } }; var searchResults = await SoapClient.SearchAsync(searchRequest); return searchResults.data.Items .Select(s => new { Code = s[0], Name = s[1] }) .ToDictionary(d => d.Code, d => d.Name); } /// <summary> /// Releases unmanaged and - optionally - managed resources. /// </summary> /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> protected override void Dispose(bool disposing) { if (disposing) { SoapClient.CloseAsync(); } } } } <file_sep>/README.md [![Build Status](https://soneritics.visualstudio.com/Twinfield%20API/_apis/build/status/Soneritics.Twinfield.API?branchName=master)](https://soneritics.visualstudio.com/Twinfield%20API/_build/latest?definitionId=1&branchName=master) # Introduction This project contains an API for [Twinfield](https://twinfield.com/). The API is based on the [Twinfield API specification](https://c3.twinfield.com/webservices/documentation/#/GettingStarted/WebServicesOverview). # NuGet The package is available via NuGet.org: Twinfield.API.TwinfieldAPI # Remarks * For now it's used primarily to get the data to show a balance sheet and profit & loss overview. * Not all Twinfield API functionality is provided by this API. Only the functionalities that I need for my projects. * BankBookService API is not included at all. # How to use There is a complete documentation in the code (Demo project). An quick example of how to use below. ``` c# // Create the TwinfieldApi twinfieldApi = new TwinfieldApi(oauthClientSettings); // First get the authorization URL Console.WriteLine("Send the user to the following URL:"); Console.WriteLine(twinfieldApi.GetAuthorizationUrl(redirectUrl)); // Catch the authorization code in your own program, and paste it here Console.Write("\n\nEnter the code: "); var authenticationCode = Console.ReadLine(); // Get the access token await twinfieldApi .SetAccessTokenByAuthorizationCodeAsync(authenticationCode, redirectUrl); accessToken = twinfieldApi.Token; if (twinfieldApi.Token.IsExpired()) { Console.WriteLine("Token expired, refreshing.."); } else { Console.WriteLine("Token is not expired. Still refreshing :-)"); await Task.Delay(2000); } await twinfieldApi.RefreshTokenAsync(); accessToken = twinfieldApi.Token; // You should save the refreshed token, so you // can use it to call the Twinfield API the next time // Office list var officeList = await twinfieldApi.ServiceFactory.ProcessXmlDataService.GetOfficeList(); // Balance sheet fields var balanceSheetFields = await twinfieldApi .ServiceFactory .FinderDataService .GetBalanceSheetFields(company); // General ledger data var data = GeneralLedgerRequestOptionsHelper .GetRequestList( list, fromYear, fromMonth, toYear, toMonth, GeneralLedgerRequestOptionsLists.MinimalList ); // More examples in PRogram.cs :-) ``` # Contribute Feel free to contribute to the project.<file_sep>/Api/Utilities/GeneralLedgerRequestOptionsLists.cs using System; using System.Collections.Generic; using System.Linq; using Api.Dto.ProcessXml; namespace Api.Utilities { /// <summary> /// Utility class for default request options. /// </summary> public static class GeneralLedgerRequestOptionsLists { /// <summary> /// The minimum request options list. /// </summary> public static List<GeneralLedgerRequestOption> MinimumRequestOptionsList = new List<GeneralLedgerRequestOption>() { new GeneralLedgerRequestOption() { Field = "fin.trs.head.yearperiod", Label = "Jaar/periode (JJJJ/PP)", Visible = false, Ask = true, Operator = "between" }, new GeneralLedgerRequestOption() { Field = "fin.trs.line.dim1group1name", Label = "Groepnaam 1", Visible = true, Ask = false, Operator = "none" }, new GeneralLedgerRequestOption() { Field = "fin.trs.line.dim1", Label = "Grootboekrek.", Visible = true, Ask = true, Operator = "between" }, new GeneralLedgerRequestOption() { Field = "fin.trs.line.dim1name", Label = "Grootboekrek.naam", Visible = true, Ask = false, Operator = "none" }, new GeneralLedgerRequestOption() { Field = "fin.trs.line.dim1type", Label = "Dimensietype 1", Visible = true, Ask = false, Operator = "none" }, new GeneralLedgerRequestOption() { Field = "fin.trs.line.valuesigned", Label = "Bedrag", Visible = true, Ask = false, Operator = "none" }, new GeneralLedgerRequestOption() { Field = "fin.trs.line.debitcredit", Label = "D/C", Visible = true, Ask = false, Operator = "none" }, new GeneralLedgerRequestOption() { Field = "fin.trs.line.dim1group1", Label = "Groep 1", Visible = true, Ask = false, Operator = "none" }, new GeneralLedgerRequestOption() { Field = "fin.trs.line.dim2name", Label = "Kpl./rel.", Visible = true, Ask = true, Operator = "between" }, new GeneralLedgerRequestOption() { Ask = true, Field = "fin.trs.head.status", Label = "Status", Operator = "equal", Visible = true } }; /// <summary> /// The minimal list of fields. /// </summary> public static List<string> MinimalList => MinimumRequestOptionsList.Select(l => l.Field).ToList(); /// <summary> /// Gets the minimum request options list. /// </summary> /// <param name="fromYear">From year.</param> /// <param name="fromMonth">From month.</param> /// <param name="toYear">To year.</param> /// <param name="toMonth">To month.</param> /// <returns></returns> /// <exception cref="ArgumentException">The field 'fin.trs.head.yearperiod' must be included in the includeFields parameter.</exception> public static List<GeneralLedgerRequestOption> GetMinimumRequestOptionsList(int fromYear, int fromMonth, int toYear, int toMonth) { var list = new List<GeneralLedgerRequestOption>(); list.AddRange(MinimumRequestOptionsList); var first = list.FirstOrDefault(o => o.Field == "fin.trs.head.yearperiod"); if (first == null) throw new ArgumentException("The field 'fin.trs.head.yearperiod' must be included in the includeFields parameter."); PeriodValidator.Validate(fromYear, fromMonth, toYear, toMonth); first.From = $"{fromYear}/{fromMonth.ToString().PadLeft(2, '0')}"; first.To = $"{toYear}/{toMonth.ToString().PadLeft(2, '0')}"; return list; } } } <file_sep>/Api/Utilities/PeriodValidator.cs using System; namespace Api.Utilities { /// <summary> /// Validator class for periods. /// </summary> public static class PeriodValidator { /// <summary> /// Validates the specified period. /// </summary> /// <param name="fromYear">From year.</param> /// <param name="fromMonth">From month.</param> /// <param name="toYear">To year.</param> /// <param name="toMonth">To month.</param> /// <exception cref="ArgumentException"> /// The 'fromYear' parameter must be a 4-digit, valid year. /// or /// The 'toYear' parameter must be a 4-digit, valid year. /// or /// The 'fromMonth' parameter must be a valid month (0-12) /// or /// The 'toMonth' parameter must be a valid month (0-12) /// </exception> public static void Validate(int fromYear, int fromMonth, int toYear, int toMonth) { if (fromYear < 1000 || fromYear > 2100) throw new ArgumentException("The 'fromYear' parameter must be a 4-digit, valid year."); if (toYear < 1000 || toYear > 2100) throw new ArgumentException("The 'toYear' parameter must be a 4-digit, valid year."); if (fromMonth < 0 || fromMonth > 12) // Yes, 0 is actually valid throw new ArgumentException("The 'fromMonth' parameter must be a valid month (0-12)"); if (toMonth < 0 || toMonth > 12) // Yes, 0 is actually valid throw new ArgumentException("The 'toMonth' parameter must be a valid month (0-12)"); } } } <file_sep>/Api/Services/Data/AbstractDataService.cs using System; using System.ServiceModel; namespace Api.Services.Data { public abstract class AbstractDataService<T> : IService, IDisposable where T : class { public abstract string ServiceEndpoint { get; } protected T SoapClient { get; set; } private readonly string _clusterUri; protected AbstractDataService(string clusterUri) { _clusterUri = clusterUri; } protected BasicHttpBinding GetServiceBinding() { return new BasicHttpBinding(BasicHttpSecurityMode.Transport) { MaxReceivedMessageSize = int.MaxValue, SendTimeout = new TimeSpan(0, 0, 900) }; } protected EndpointAddress GetEndpoint() { return new EndpointAddress($"{_clusterUri}{ServiceEndpoint}"); } protected abstract void Dispose(bool disposing); public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } } } <file_sep>/Api/Dto/ProcessXml/GeneralLedgerData/TwinfieldDataLineHeader.cs namespace Api.Dto.ProcessXml.GeneralLedgerData { /// <summary> /// Header line for the General Ledger data. /// </summary> public class TwinfieldDataLineHeader { /// <summary> /// Gets or sets the type of the value. /// </summary> /// <value> /// The type of the value. /// </value> public string ValueType { get; set; } /// <summary> /// Gets or sets the label. /// </summary> /// <value> /// The label. /// </value> public string Label { get; set; } } } <file_sep>/Api/Dto/ProcessXml/GeneralLedgerData/ITwinfieldValue.cs using System; namespace Api.Dto.ProcessXml.GeneralLedgerData { /// <summary> /// Interface for the TwinfieldValue class. /// Contains holders for all the possible values, of which only one will be filled. /// </summary> public interface ITwinfieldValue { /// <summary> /// Gets the string. /// </summary> /// <returns></returns> string GetString(); /// <summary> /// Gets the number. /// </summary> /// <returns></returns> int GetNumber(); /// <summary> /// Gets the decimal. /// </summary> /// <returns></returns> decimal GetDecimal(); /// <summary> /// Gets the value. /// </summary> /// <returns></returns> decimal GetValue(); /// <summary> /// Gets the date time. /// </summary> /// <returns></returns> DateTime GetDateTime(); /// <summary> /// Gets the date. /// </summary> /// <returns></returns> DateTime GetDate(); /// <summary> /// Converts to string. /// </summary> /// <returns> /// A <see cref="System.String" /> that represents this instance. /// </returns> string ToString(); } } <file_sep>/Api/Dto/OAuth/OAuthToken.cs using System; namespace Api.Dto.OAuth { public class OAuthToken { public string Accesstoken { get; set; } public string RefreshToken { get; set; } private int _expiresIn; public int ExpiresIn { get => _expiresIn; set { _expiresIn = value; ExpiresAt = Created.AddSeconds(_expiresIn); } } public DateTime Created { get; } = DateTime.Now; public DateTime ExpiresAt { get; private set; } = DateTime.Now; public bool IsExpired() { return ExpiresAt <= DateTime.Now.Subtract(new TimeSpan(0, 1, 0)); } } } <file_sep>/Api/Services/Auth/AuthorizationService.cs using System.Collections.Generic; using System.Net.Http; using System.Threading.Tasks; using Api.Dto.OAuth; namespace Api.Services.Auth { public class AuthorizationService : AuthServiceBase { private readonly OAuthClientSettings _oAuthClientSettings; private readonly OAuthToken _token; public AuthorizationService( OAuthClientSettings oAuthClientSettings, OAuthToken token, HttpClient httpClient ) : base(httpClient) { _oAuthClientSettings = oAuthClientSettings; _token = token; } public async Task<OAuthToken> GetRefreshTokenAsync() { var postObject = new List<KeyValuePair<string, string>> { new KeyValuePair<string, string>("grant_type", "refresh_token"), new KeyValuePair<string, string>("refresh_token", _token.RefreshToken) }; var rawToken = await GetApiResult<RawToken>( HttpMethod.Post, "https://login.twinfield.com/auth/authentication/connect/token", _oAuthClientSettings, postObject ); return new OAuthToken() { Accesstoken = rawToken.Accesstoken, RefreshToken = rawToken.RefreshToken, ExpiresIn = rawToken.ExpiresIn }; } public async Task<string> GetClusterUrlAsync() { var response = await GetApiResult<ClusterUriResponse>( HttpMethod.Get, $"https://login.twinfield.com/auth/authentication/connect/accesstokenvalidation?token={_token.Accesstoken}" ); return response.ClusterUrl; } } } <file_sep>/Api/Helpers/GeneralLedgerRequestOptionsParser.cs using System.Collections.Generic; using System.Text; using Api.Dto.ProcessXml; namespace Api.Helpers { /// <summary> /// Parser class for the request options. Parses an object to XML. /// </summary> internal static class GeneralLedgerRequestOptionsParser { /// <summary> /// Parses the specified list. /// </summary> /// <param name="list">The list.</param> /// <returns></returns> public static string Parse(List<GeneralLedgerRequestOption> list) { var balanceSheetDataRequest = new StringBuilder(); balanceSheetDataRequest.Append($"<columns code=\"030_2\">"); foreach (var item in list) { var visibility = item.Visible ? "true" : "false"; if (item.Operator == "between" && !string.IsNullOrEmpty(item.From) && !string.IsNullOrEmpty(item.To)) balanceSheetDataRequest.Append($"<column><field>{item.Field}</field><label>{item.Label}</label><visible>{visibility}</visible><operator>{item.Operator}</operator><from>{item.From}</from><to>{item.To}</to></column>"); else balanceSheetDataRequest.Append($"<column><field>{item.Field}</field><label>{item.Label}</label><visible>{visibility}</visible></column>"); } balanceSheetDataRequest.Append($"</columns>"); return balanceSheetDataRequest.ToString(); } } } <file_sep>/Api/Dto/OAuth/ClusterUriResponse.cs using Newtonsoft.Json; namespace Api.Dto.OAuth { public class ClusterUriResponse { [JsonProperty("twf.clusterUrl")] public string ClusterUrl { get; set; } } }<file_sep>/Api/Dto/OAuth/OAuthClientSettings.cs namespace Api.Dto.OAuth { public class OAuthClientSettings { public string Id { get; set; } public string Secret { get; set; } } } <file_sep>/Api/Services/ServiceFactory.cs using Api.Dto; using Api.Services.Data; namespace Api.Services { /// <summary> /// Factory class for creating clients to call the Twinfield services. /// </summary> public class ServiceFactory { /// <summary> /// The soapHeader /// </summary> private readonly ISoapHeader _soapHeader; /// <summary> /// The process XML service /// </summary> private ProcessXmlDataService _processXmlDataService; /// <summary> /// Gets the process XML service. /// </summary> /// <value> /// The process XML service. /// </value> public ProcessXmlDataService ProcessXmlDataService => _processXmlDataService ??= new ProcessXmlDataService(_soapHeader); /// <summary> /// The finder service /// </summary> private FinderDataService _finderDataService; /// <summary> /// Gets the finder service. /// </summary> /// <value> /// The finder service. /// </value> public FinderDataService FinderDataService => _finderDataService ??= new FinderDataService(_soapHeader); /// <summary> /// Initializes a new instance of the <see cref="ServiceFactory"/> class. /// Requires a soapHeader, as all of the services created by this factory require a logged in user. /// </summary> /// <param name="soapHeader">The soapHeader.</param> public ServiceFactory(ISoapHeader soapHeader) { _soapHeader = soapHeader; } } } <file_sep>/Api/Dto/ProcessXml/GeneralLedgerData/TwinfieldValue.cs using System; using System.Globalization; using Api.Exceptions; namespace Api.Dto.ProcessXml.GeneralLedgerData { /// <summary> /// TwinfieldValue class, contains the value of a General Ledger data row. /// </summary> /// <seealso cref="ITwinfieldValue" /> public class TwinfieldValue : ITwinfieldValue { /// <summary> /// Gets the type of the value. /// </summary> /// <value> /// The type of the value. /// </value> public string ValueType { get; } /// <summary> /// The string value /// </summary> private readonly string _stringValue; /// <summary> /// The number value /// </summary> private readonly int _numberValue; /// <summary> /// The decimal value /// </summary> private readonly decimal _decimalValue; /// <summary> /// The value value /// </summary> private readonly decimal _valueValue; /// <summary> /// The datetime value /// </summary> private readonly DateTime _datetimeValue; /// <summary> /// The date value /// </summary> private readonly DateTime _dateValue; /// <summary> /// Initializes a new instance of the <see cref="TwinfieldValue"/> class. /// Sets the value based on the Value Type. /// </summary> /// <param name="valueType">Type of the value.</param> /// <param name="value">The value.</param> /// <exception cref="UnknownValueTypeException">Unknown value type {valueType}</exception> public TwinfieldValue(string valueType, string value) { ValueType = valueType; switch (valueType.ToLower()) { case "string": _stringValue = value; break; case "number": _numberValue = string.IsNullOrEmpty(value) ? 0 : int.Parse(value); break; case "decimal": _decimalValue = string.IsNullOrEmpty(value) ? 0 : decimal.Parse(value, CultureInfo.InvariantCulture); break; case "value": _valueValue = string.IsNullOrEmpty(value) ? 0 : decimal.Parse(value, CultureInfo.InvariantCulture); break; case "datetime": var dateTime = $"{value.Substring(0, 4)}-{value.Substring(4, 2)}-{value.Substring(6, 2)} {value.Substring(8, 2)}:{value.Substring(10, 2)}:{value.Substring(12, 2)}"; _datetimeValue = DateTime.Parse(dateTime); break; case "date": var date = $"{value.Substring(0, 4)}-{value.Substring(4, 2)}-{value.Substring(6, 2)} 10:00:00"; _dateValue = DateTime.Parse(date); break; default: throw new UnknownValueTypeException($"Unknown value type {valueType}"); } } /// <summary> /// Converts to string. /// </summary> /// <returns> /// A <see cref="System.String" /> that represents this instance. /// </returns> /// <exception cref="Exception">No value set</exception> public override string ToString() { switch (ValueType.ToLower()) { case "string": return _stringValue; case "number": return _numberValue.ToString(); case "decimal": return _decimalValue.ToString(CultureInfo.InvariantCulture); case "value": return _valueValue.ToString(CultureInfo.InvariantCulture); case "datetime": return _datetimeValue.ToString(CultureInfo.InvariantCulture); case "date": return _dateValue.ToString(CultureInfo.InvariantCulture); default: throw new Exception("No value set"); } } /// <summary> /// Gets the string. /// </summary> /// <returns></returns> public string GetString() { return _stringValue; } /// <summary> /// Gets the number. /// </summary> /// <returns></returns> public int GetNumber() { return _numberValue; } /// <summary> /// Gets the decimal. /// </summary> /// <returns></returns> public decimal GetDecimal() { return _decimalValue; } /// <summary> /// Gets the value. /// </summary> /// <returns></returns> public decimal GetValue() { return _valueValue; } /// <summary> /// Gets the date time. /// </summary> /// <returns></returns> public DateTime GetDateTime() { return _datetimeValue; } /// <summary> /// Gets the date. /// </summary> /// <returns></returns> public DateTime GetDate() { return _dateValue; } } } <file_sep>/Api/Dto/Financial/FinancialType.cs namespace Api.Dto.Financial { /// <summary> /// Financial type, as used within Twinfield. /// </summary> public class FinancialType { /// <summary> /// The balance sheet /// </summary> public const string BalanceSheet = "BAS"; /// <summary> /// The profit & loss /// </summary> public const string ProfitAndLoss = "PNL"; // @todo: Not sure what the names of these types are, but can be included as constants as well // DEB CRD KPL PRJ AST ACT } } <file_sep>/Api/Helpers/GeneralLedgerRequestOptionsHelper.cs using System; using System.Collections.Generic; using System.Linq; using Api.Dto.ProcessXml; using Api.Utilities; namespace Api.Helpers { /// <summary> /// Helper class to help with the /// </summary> public static class GeneralLedgerRequestOptionsHelper { /// <summary> /// Gets a valid request list from the full set. Also providing methods to help with date ranges. /// </summary> /// <param name="optionsList">The options list.</param> /// <param name="fromYear">From year.</param> /// <param name="fromMonth">From month.</param> /// <param name="toYear">To year.</param> /// <param name="toMonth">To month.</param> /// <returns></returns> /// <exception cref="Exception">dunno..</exception> public static List<GeneralLedgerRequestOption> GetRequestList(List<GeneralLedgerRequestOption> optionsList, int fromYear, int fromMonth, int toYear, int toMonth) { var includeFields = optionsList.Where(i => i.Visible).Select(i => i.Field).ToList(); includeFields.Add("fin.trs.head.yearperiod"); return GetRequestList(optionsList, fromYear, fromMonth, toYear, toMonth, includeFields); } /// <summary> /// Gets the request list, based on a list of items that need to be included. /// </summary> /// <param name="optionsList">The options list.</param> /// <param name="fromYear">From year.</param> /// <param name="fromMonth">From month.</param> /// <param name="toYear">To year.</param> /// <param name="toMonth">To month.</param> /// <param name="includeFields">The include fields.</param> /// <returns></returns> /// <exception cref="ArgumentException">The field 'fin.trs.head.yearperiod' must be included in the includeFields parameter.</exception> public static List<GeneralLedgerRequestOption> GetRequestList(List<GeneralLedgerRequestOption> optionsList, int fromYear, int fromMonth, int toYear, int toMonth, List<string> includeFields) { var minimalList = optionsList.Where(o => includeFields.Contains(o.Field)).ToList(); var first = minimalList.FirstOrDefault(o => o.Field == "fin.trs.head.yearperiod"); if (first == null) throw new ArgumentException("The field 'fin.trs.head.yearperiod' must be included in the includeFields parameter."); PeriodValidator.Validate(fromYear, fromMonth, toYear, toMonth); first.From = $"{fromYear}/{fromMonth.ToString().PadLeft(2, '0')}"; first.To = $"{toYear}/{toMonth.ToString().PadLeft(2, '0')}"; return minimalList; } } }
008fbc76b9fad2e0e6137ef16cf8f6c3117e1926
[ "C#", "Markdown", "YAML" ]
34
C#
Soneritics/Twinfield.API
6620a6e6b5d7081035ea1959b02f7b45f903fa84
898d3deb7f9227c3ed1d7d57430e396cb45d0a73
refs/heads/master
<repo_name>sicet7/faro-core-old<file_sep>/src/ModuleLoader.php <?php namespace Sicet7\Faro; use DI\ContainerBuilder; use Psr\Container\ContainerInterface; use Sicet7\Faro\Exception\ModuleLoaderException; class ModuleLoader { /** * @var string */ private string $moduleFqn; /** * @var ModuleContainer */ private ModuleContainer $moduleContainer; /** * @var bool */ private bool $loaded = false; /** * @var bool */ private bool $setup = false; /** * @var bool */ private bool $enabled = false; /** * @var string[] */ private array $dependencyNames = []; /** * @var ModuleLoader[] */ private array $dependencyLoaders = []; /** * @var string */ private string $name; /** * @var array */ private array $definitions = []; /** * ModuleLoader constructor. * @param string $moduleFqn * @param ModuleContainer $moduleContainer * @throws ModuleLoaderException */ public function __construct( string $moduleFqn, ModuleContainer $moduleContainer ) { $this->moduleFqn = '\\' . ltrim($moduleFqn, '\\'); $this->moduleContainer = $moduleContainer; $this->init(); } /** * @throws ModuleLoaderException */ private function init() { if (!is_subclass_of($this->getModuleFqn(), AbstractModule::class)) { throw new ModuleLoaderException( "Invalid module class. \"{$this->getModuleFqn()}\" must be an instance of " . '"' . AbstractModule::class . '".' ); } $enabled = $this->moduleRead('isEnabled'); if (!is_bool($enabled)) { throw new ModuleLoaderException( "Invalid \"isEnabled\" state on module: \"{$this->getModuleFqn()}\"" ); } $this->enabled = $enabled; /* F*** the rest if we ain't enabled :-) */ if (!$this->isEnabled()) { return; } $dependencies = $this->moduleRead('getDependencies'); if (!is_array($dependencies)) { throw new ModuleLoaderException( "Unknown dependency type on module: \"{$this->getModuleFqn()}\"" ); } $this->dependencyNames = $dependencies; $name = $this->moduleRead('getName'); if (!is_string($name) || empty($name)) { throw new ModuleLoaderException( "The module name of {$this->getModuleFqn()} must be a non empty string value." ); } $this->name = $name; $definitions = $this->moduleRead('getDefinitions'); if (!is_array($definitions)) { throw new ModuleLoaderException( "Invalid definitions type on module: \"{$this->getModuleFqn()}\"." ); } $this->definitions = $definitions; } /** * @param string $method * @return mixed */ private function moduleRead(string $method) { return call_user_func([$this->getModuleFqn(), $method]); } /** * @return bool */ private function findDependencyModuleLoaders(): bool { if (empty($this->dependencyNames)) { return true; } foreach ($this->moduleContainer->getList() as $moduleLoader) { if (!isset($this->dependencyLoaders[$moduleLoader->getName()]) && in_array($moduleLoader->getName(), $this->dependencyNames)) { $this->dependencyLoaders[$moduleLoader->getName()] = $moduleLoader; } } if (count($this->dependencyNames) == count($this->dependencyLoaders)) { return true; } return false; } /** * @return bool */ private function isDependenciesLoaded(): bool { if (empty($this->dependencyNames)) { return true; } if (!$this->findDependencyModuleLoaders()) { return false; } foreach ($this->dependencyLoaders as $loader) { if (!$loader->isEnabled() || !$loader->isLoaded()) { return false; } } return true; } /** * @return bool */ private function isDependenciesSetup(): bool { if (empty($this->dependencyNames)) { return true; } if (!$this->findDependencyModuleLoaders()) { return false; } foreach ($this->dependencyLoaders as $loader) { if (!$loader->isEnabled() || !$loader->isSetup()) { return false; } } return true; } /** * @return ModuleContainer */ protected function getModuleContainer(): ModuleContainer { return $this->moduleContainer; } /** * @return string */ public function getModuleFqn(): string { return $this->moduleFqn; } /** * @return bool */ public function isLoaded(): bool { return $this->loaded; } /** * @return bool */ public function isSetup(): bool { return $this->setup; } /** * @return bool */ public function isEnabled(): bool { return $this->enabled; } /** * @return string */ public function getName(): string { return $this->name; } /** * @return array */ public function getDefinitions(): array { return $this->definitions; } /** * @return bool */ public function load(): bool { if ($this->isLoaded() || !$this->isEnabled() || !$this->isDependenciesLoaded()) { return false; } $this->getModuleContainer() ->getContainerBuilder() ->addDefinitions($this->getDefinitions()); $this->loaded = true; return true; } /** * @param ContainerInterface $container * @return bool */ public function setup(ContainerInterface $container): bool { if ($this->isSetup() || !$this->isEnabled() || !$this->isDependenciesSetup()) { return false; } call_user_func([$this->getModuleFqn(), 'setup'], $container); $this->setup = true; return true; } }<file_sep>/src/Exception/ModuleLoaderException.php <?php declare(strict_types=1); namespace Sicet7\Faro\Exception; class ModuleLoaderException extends \Exception { }<file_sep>/src/ModuleContainer.php <?php namespace Sicet7\Faro; use DI\Container; use DI\ContainerBuilder; use Psr\Container\ContainerInterface; use Sicet7\Faro\Exception\ModuleLoaderException; class ModuleContainer { private static ?ModuleContainer $instance = null; /** * @return ModuleContainer */ public final static function getInstance(): ModuleContainer { if (!(static::$instance instanceof ModuleContainer)) { static::$instance = new static(); } return static::$instance; } /** * @param string $moduleFqn * @throws ModuleLoaderException */ public final static function registerModule(string $moduleFqn): void { static::getInstance()->addModule($moduleFqn); } /** * @return string[] */ public final static function getModuleList(): array { return static::getInstance()->getList(); } /** * Should be a class which the ContainerBuilder * * @var string */ protected string $containerClass = Container::class; /** * @var ContainerBuilder */ private ContainerBuilder $containerBuilder; /** * @var ModuleLoader[] */ private array $moduleList = []; public function __construct() { $this->containerBuilder = new ContainerBuilder($this->containerClass); $this->containerBuilder->useAutowiring(false); $this->containerBuilder->useAnnotations(false); $extensionDefinitions = $this->definitions(); if (!empty($extensionDefinitions)) { $this->containerBuilder->addDefinitions($extensionDefinitions); } } /** * @return ContainerBuilder */ public function getContainerBuilder(): ContainerBuilder { return $this->containerBuilder; } /** * @throws ModuleLoaderException */ protected function loadDefinitions() { do { $loadCount = 0; foreach ($this->getList() as $loader) { if (!$loader->isEnabled()) { continue; } if (!$loader->isLoaded() && $loader->load()) { $loadCount++; } } } while($loadCount !== 0); foreach ($this->getList() as $loader) { if ($loader->isEnabled() && !$loader->isLoaded()){ throw new ModuleLoaderException("Failed to load module: {$loader->getModuleFqn()}"); } } } /** * @param ContainerInterface $container * @throws ModuleLoaderException */ protected function setupModules(ContainerInterface $container) { do { $setupCount = 0; foreach ($this->getList() as $loader) { if (!$loader->isEnabled()) { continue; } if (!$loader->isSetup() && $loader->setup($container)) { $setupCount++; } } } while($setupCount !== 0); foreach ($this->getList() as $loader) { if ($loader->isEnabled() && !$loader->isSetup()) { throw new ModuleLoaderException("Module setup failed for module: {$loader->getModuleFqn()}"); } } } /** * @param string $moduleFqn * @throws ModuleLoaderException */ public function addModule(string $moduleFqn): void { $moduleLoader = $this->createLoader($moduleFqn); if ($moduleLoader->isEnabled()) { $this->moduleList[$moduleLoader->getName()] = $moduleLoader; } } /** * @return ModuleLoader[] */ public function getList(): array { return $this->moduleList; } /** * @return ContainerInterface * @throws ModuleLoaderException */ public function buildContainer(): ContainerInterface { try { $this->loadDefinitions(); $container = $this->getContainerBuilder()->build(); $this->setupModules($container); return $container; } catch (\Exception $exception) { throw new ModuleLoaderException($exception, $exception->getCode(), $exception); } } /** * Creates the loader for the modules. * * @param string $moduleFqn * @return ModuleLoader * @throws ModuleLoaderException */ protected function createLoader(string $moduleFqn): ModuleLoader { return new ModuleLoader($moduleFqn, $this); } /** * This function is to allow sub classes to define their custom definitions * * @return array */ protected function definitions(): array { return []; } }
5bf0940d3fe3c53db59e57c4ffa478fa5c6084c6
[ "PHP" ]
3
PHP
sicet7/faro-core-old
468aebbbf9ff11ec726a88c77d3655253b7ae1d9
28256d4abfbff5dcb91fc9ae8163a764f0cbd191
refs/heads/master
<file_sep># SKA SA Homebrew Tap This contains extra formulas useful for radio astronomy in general and the MeerKAT project in particular that are not distributed by Homebrew. For information on Homebrew itself, see http://mxcl.github.com/homebrew/ To use the formulas specified here, use the tap subcommand to pull them in: ``` $ brew tap ska-sa/tap ``` If you no longer want to track this repository, use ``` $ brew untap ska-sa/tap ``` <file_sep>class Pyrap < Formula desc 'Python bindings for casacore, a library used in radio astronomy' homepage 'https://casacore.github.io/python-casacore/' stable do url 'https://pyrap.googlecode.com/files/pyrap-1.1.0.tar.bz2' sha256 "4ca7fa080d31de64680a78425f0ea02f36a1d8f019febf7e595234055e7e2d54" # Patch to disable explicit linking to system Python framework in order to support brew Python (and other non-system versions) patch do url 'https://gist.github.com/ludwigschwardt/5195760/raw/0dbf63fba7b4caed537c84eb26c42afc7db0ec23/patch5.diff' sha256 "8f8b78809b42bfe3e49f1be02be69f604c71e51af57ac9329c5901daa089b7c7" end # Fix C++11 issue (space between string and literal) patch do url "https://gist.github.com/ludwigschwardt/5195760/raw/296b0ec87ceffc5a006138a0e9263cd97b553897/patch10.diff" sha256 "707744a2c115171a85ea882982a21775c569056f996fad6c11f2821dddbaba84" end # Enable C++11 both for libpyrap and the python extensions for clang patch do url "https://gist.github.com/ludwigschwardt/5195760/raw/c8fc9ce1a65d7e198a2013d1a828fae738fa147e/patch11.diff" sha256 "a89e080babe6e63222d0898f6c75276530afbd9efc7767dfebf037b4e903d393" end # CASA components library has been dropped from 2.0.0 patch do url "https://gist.github.com/ludwigschwardt/5195760/raw/11b648371df7d17f1264ef67d7b782eaa31bef54/patch12.diff" sha256 "5b1291336822107f007db99ea4804e32cb7e71ccc68758134ac69453f8457bfe" end end head do url 'https://github.com/casacore/python-casacore.git' # Patch to support compilation on Mac OS 10.7+ (Lion and up) by ignoring sysroot patch do url 'https://gist.github.com/ludwigschwardt/5195760/raw/c0981d0c27b3086cb7378cf4442b2754abc8a42d/patch2.diff' sha256 '2d5f315ffdbbcab7ae428e7418a22fe89b8067e09e5ea3cee250fa28b253a1c9' end # Patch to ignore fortran to c library (aka libgfortran) patch do url 'https://gist.github.com/ludwigschwardt/5195760/raw/5bdd5e6ab42e9551750128c441a775dffaa3feea/patch4.diff' sha256 '8bb39b4d9436818a6b579a9d536b849d4417b553dbe686c6b455e54d52a88c89' end # Patch to disable explicit linking to system Python framework in order to support brew Python (and other non-system versions) patch do url 'https://gist.github.com/ludwigschwardt/5195760/raw/a270c600a5870523192a791c6a4459bbddc293b3/patch6.diff' sha256 'c204c14f0864d3cc7668354b0129c6f70b9ad6630543b688a75a499eca85d6af' end # Fix C++11 issue (space between string and literal) patch do url "https://gist.github.com/ludwigschwardt/5195760/raw/e13d6971f7647591572a9a0faf7e393f032cb488/patch7.diff" sha256 '6ea089c5d7ba59b6f2e535929304d14ba26d12ffcc205c3c5a51c3b849d15ec3' end # Enable C++11 both for libpyrap and the python extensions for clang patch do url "https://gist.github.com/ludwigschwardt/5195760/raw/3e32d83f58a4abdd15d7530583a659feaa39c15a/patch8.diff" sha256 "e7781da938d509809e62f40dace1361ad2b6de43f452c51f5e259932bc504936" end # CASA components library has been dropped from 2.0.0 patch do url "https://gist.github.com/ludwigschwardt/5195760/raw/ecfe7c62cab531599b096e6e9db962468735d203/patch9.diff" sha256 "2f0111c117b5c715843e5559dba8ed4779123ce7550d47d3e8c81469e126fa31" end end depends_on 'scons' => :build depends_on 'boost-python' depends_on 'casacore' depends_on 'python@2' depends_on 'numpy' # Patch to support compilation on Mac OS 10.7+ (Lion and up) by ignoring sysroot patch do url 'https://gist.github.com/ludwigschwardt/5195760/raw/da9264e50c244b84cd92e180b207e13928f7ff93/patch1.diff' sha256 'aa4ccbf03fce7a136bbeda47c625fe0e61d119a3aa1ef3315ce86ae2a0aa8fa7' end # Patch to ignore fortran to c library (aka libgfortran) patch do url 'https://gist.github.com/ludwigschwardt/5195760/raw/0bda200fb5c8f743c488077e94195c786ecb2486/patch3.diff' sha256 '3ffb0226a509633eec1adcdae4f2e60c5013b6524a02ba4b506e0f6c784154d0' end def install if build.head? build_cmd = 'batchbuild-trunk.py' else build_cmd = 'batchbuild.py' end # Obtain information on Python installation python_xy = "python" + %x(python -c 'import sys;print(sys.version[:3])').chomp python_site_packages = lib + "#{python_xy}/site-packages" system "python", build_cmd, "--boost-root=#{HOMEBREW_PREFIX}", "--boost-lib=boost_python-mt", "--enable-hdf5", "--prefix=#{prefix}", "--python-prefix=#{python_site_packages}", "--universal=x86_64" # Get rid of horrible eggs as they trample on other packages via site.py and easy-install.pth cd "#{python_site_packages}" rm_f ['easy-install.pth', 'site.py', 'site.pyc'] mkdir 'pyrap' touch 'pyrap/__init__.py' Dir['pyrap.*.egg'].each do |egg| Dir.foreach("#{egg}/pyrap") do |item| next if ['.', '..', '__init__.py', '__init__.pyc'].include? item mv "#{egg}/pyrap/#{item}", 'pyrap/' end rm_rf egg end end end <file_sep>class Tempo2 < Formula desc 'A pulsar timing package' homepage "http://www.atnf.csiro.au/research/pulsar/tempo2/" url "https://downloads.sourceforge.net/tempo2/tempo2-2013.9.1.tar.gz" sha256 "79dede8fcb4deb66789d6acffa775cfc27ed33412eb795c93aad4dbe054cd933" depends_on "libx11" => :recommended depends_on "gcc" depends_on "pgplot" depends_on "fftw" depends_on "cfitsio" depends_on "gsl" def install share.install "T2runtime" system "./configure", "--disable-dependency-tracking", "--disable-silent-rules", "--prefix=#{prefix}", "--with-tempo2-plug-dir=#{share}/T2runtime/plugins" system "make", "install" system "make", "plugins-install" end def caveats s = <<-EOS.undent Please set the TEMPO2 environment variable to: export TEMPO2=#{share}/T2runtime EOS s end test do system "TEMPO2=#{share}/T2runtime", bin/"tempo2", "-h", "||", "[", "$?", "==", "1", "]" end end <file_sep>class Tigger < Formula desc 'A FITS viewer and sky model management tool (part of MeqTrees)' homepage 'https://github.com/ska-sa/meqtrees/wiki/Tigger' url 'https://svn.astron.nl/Tigger/release/Tigger/release-1.2.2' head 'https://svn.astron.nl/Tigger/trunk/Tigger' depends_on 'python@2' depends_on 'numpy' depends_on 'scipy' depends_on 'purr' # Missing dependencies: pyfits, pyqwt, astLib if not build.head? # Ignore setAllowX11ColorNames attribute on non-X11 Mac platform (fixed in HEAD) patch do url 'https://gist.github.com/raw/4565060/3a11913eff383b188a7dc887d560140b2b2b3500/patch1.diff' end # Fix imports to be absolute (fixed in HEAD) patch do url 'https://gist.github.com/raw/4565060/b42096bf9569b60a11f99a7432826e6235be5c4b/patch2.diff' end # Nuke matplotlib differently (dummy_module clashes with pkg_resources) (fixed in HEAD) patch do url 'https://gist.github.com/raw/4565060/95dc15b776855ed4273c79d18e1c99177ea8b41a/patch4.diff' end end # p << 'https://gist.github.com/raw/4565060/2bc9f42182180401adb52b8be065d1c70d39fe37/patch3.diff' if build.head? def install # Obtain information on Python installation python_xy = "python" + %x(python -c 'import sys;print(sys.version[:3])').chomp python_site_packages = lib + "#{python_xy}/site-packages" tigger = "#{python_site_packages}/Tigger" mkdir_p ["#{tigger}", "#{share}/doc", "#{share}/meqtrees"] cp_r '.', "#{tigger}/" rm_rf ["#{tigger}/bin", "#{tigger}/doc", "#{tigger}/icons"] cp_r 'bin', "#{bin}" rm_f "#{bin}/tigger" ln_s "#{tigger}/tigger", "#{bin}/tigger" cp_r 'doc', "#{share}/doc/tigger" cp_r 'icons', "#{share}/meqtrees/" end test do if system "python -c 'import Tigger'" then onoe 'Tigger FAILED' else ohai 'Tigger OK' end end end <file_sep>class Purr < Formula desc 'A GUI tool for auto-generating descriptive data processing logs' homepage 'https://github.com/ska-sa/meqtrees/wiki/Purr-Introduction' url 'https://svn.astron.nl/Purr/release/Purr/release-1.2.0' head 'https://github.com/ska-sa/purr.git' depends_on 'python@2' depends_on 'pyqt' # Missing dependencies: pyfits if not build.head? # First look for icons in meqtrees share directory (fixed in HEAD) patch do url 'https://gist.github.com/raw/4705954/bdcfe30b6f63a4d634f33fcfa4334ea7760cd69d/patch1.diff' end # Provide alternatives for Linux-only 'cp -u' and 'mv -u' (fixed in HEAD) patch do url 'https://gist.github.com/raw/4705954/95942b16e28c387b89ff64baf986b141c037d422/patch2.diff' end # Escape spaces in paths sent to pychart to produce histograms (fixed in HEAD) patch do url 'https://gist.github.com/raw/4705954/fef3b6a3386a3b8c8ec512099fc14b2bcb680e47/patch3.diff' end end def install # Obtain information on Python installation python_xy = "python" + %x(python -c 'import sys;print(sys.version[:3])').chomp python_site_packages = lib + "#{python_xy}/site-packages" bin.install 'Purr/purr.py', 'Purr/purr' mkdir_p "#{python_site_packages}" cp_r ['Purr', 'Kittens'], "#{python_site_packages}/" mkdir_p "#{share}/meqtrees" cp_r 'icons', "#{share}/meqtrees/" end test do if system "python -c 'import Purr'" then onoe 'Purr FAILED' else ohai 'Purr OK' end end end <file_sep>class SofaC < Formula desc "Standards of Fundamental Astronomy routines (ANSI C version)" homepage "http://www.iausofa.org/" url "http://www.iausofa.org/2018_0130_C/sofa_c-20180130.tar.gz" sha256 "de09807198c977e1c58ea1d0c79c40bdafef84f2072eab586a7ac246334796db" def install cd "#{version}/c/src" system "make", "install", "INSTALL_DIR=#{prefix}" end end <file_sep>class Xpra < Formula desc 'Multi-platform screen and application forwarding system: "screen for X11"' homepage "http://xpra.org" url "https://www.xpra.org/src/xpra-0.17.6.tar.bz2" sha256 "d08a68802f86183e69c7bcb2b6c42dc93fce60d2d017beb9a1b18f581f8902d2" head "http://xpra.org/svn/Xpra/trunk/src/", :using => :svn # We want pkg-config env :userpaths depends_on 'python@2' depends_on "Cython" # PyObjC is used for AppKit - install core first to avoid recompilation # Missing dependencies: objc # PyOpenGL is only required if pygtkglext is to be used depends_on "OpenGL" if build.with? "pygtkglext" depends_on "OpenGL_accelerate" if build.with? "pygtkglext" depends_on "libx11" => :recommended depends_on "pygtk" depends_on "pygtkglext" => :recommended depends_on "gtk-mac-integration" depends_on "ffmpeg" depends_on "libvpx" depends_on "webp" # extras: rencode cryptography lzo lz4 # 1) Use AppKit NSBeep instead of Carbon.Snd.SysBeep for system bell. # 2) Fix icon directory. patch :DATA def install inreplace "xpra/platform/paths.py", "sys.prefix", '"#{prefix}"' system "python", "setup.py", "install", "--prefix=#{prefix}" end test do system "#{bin}/xpra", "showconfig" end end __END__ diff --git a/xpra/platform/darwin/gui.py b/xpra/platform/darwin/gui.py index 52f0c6b..05fd0ec 100644 --- a/xpra/platform/darwin/gui.py +++ b/xpra/platform/darwin/gui.py @@ -39,9 +39,13 @@ def get_OSXApplication(): return macapp try: - from Carbon import Snd #@UnresolvedImport + from AppKit import NSBeep #@UnresolvedImport except: - Snd = None + NSBeep = None + try: + from Carbon.Snd import SysBeep #@UnresolvedImport + except: + SysBeep = None def do_init(): @@ -75,10 +81,13 @@ def get_native_tray_classes(): return [OSXTray] def system_bell(*args): - if Snd is None: - return False - Snd.SysBeep(1) - return True + if NSBeep is not None: + NSBeep() + return True + if SysBeep is not None: + SysBeep(1) + return True + return False #if there is an easier way of doing this, I couldn't find it: try: diff --git a/xpra/platform/darwin/paths.py b/xpra/platform/darwin/paths.py index 0f7137d..67990f3 100644 --- a/xpra/platform/darwin/paths.py +++ b/xpra/platform/darwin/paths.py @@ -18,7 +18,7 @@ def do_get_resources_dir(): RESOURCES = "/Resources/" #FUGLY warning: importing gtkosx_application causes the dock to appear, #and in some cases we don't want that.. so use the env var XPRA_SKIP_UI as workaround for such cases: - if os.environ.get("XPRA_SKIP_UI", "0")=="0": + if os.environ.get("XPRA_SKIP_UI", "1")=="0": try: import gtkosx_application #@UnresolvedImport try: diff --git a/xpra/platform/darwin/paths.py b/xpra/platform/darwin/paths.py index f9ac98e..0f7137d 100644 --- a/xpra/platform/darwin/paths.py +++ b/xpra/platform/darwin/paths.py @@ -61,7 +61,13 @@ def do_get_app_dir(): def do_get_icon_dir(): from xpra.platform.paths import get_resources_dir - i = os.path.join(get_resources_dir(), "share", "xpra", "icons") + rsc = get_resources_dir() + head, tail = os.path.split(rsc) + headhead, headtail = os.path.split(head) + if headtail == "share" and tail == "xpra": + i = os.path.join(rsc, "icons") + else: + i = os.path.join(rsc, "share", "xpra", "icons") debug("get_icon_dir()=%s", i) return i <file_sep>class Leo < Formula desc 'A full-featured outliner, IDE and data manager written in Python' homepage 'http://leoeditor.com/' url 'https://downloads.sourceforge.net/projects/leo/files/Leo/4.10%20final/Leo-4.10-final.zip' sha256 '3c27d28e8127094aee9a9dba3d4b5093275e5f35af1b2d3ea1e8b76e5a9f7c7b' head 'https://github.com/leo-editor/leo-editor.git' depends_on 'pyqt' depends_on 'enchant' => :recommended def install # Obtain information on Python installation python_xy = "python" + %x(python -c 'import sys;print(sys.version[:3])').chomp python_site_packages = lib + "#{python_xy}/site-packages" python_site_packages.install 'leo' bin.install ['launchLeo.py', 'profileLeo.py'] ln_s "#{bin}/launchLeo.py", "#{bin}/leo" end test do if system "python -c 'import leo'" then onoe 'Leo FAILED' else ohai 'Leo OK' end end end <file_sep>class Rpfits < Formula desc 'Library to access ATCA visibility data in RPFITS format' homepage 'http://www.atnf.csiro.au/computing/software/rpfits.html' url 'ftp://ftp.atnf.csiro.au/pub/software/rpfits/rpfits-2.23.tar.gz' sha256 '7fbed9951b16146ee8d02b09f447adb1706e812c33a1026e004b7feb63f221a0' depends_on "gcc" def install ENV.deparallelize ENV['RPARCH'] = "darwin" system "make -f GNUmakefile" lib.install ['librpfits.a'] bin.install ['rpfex','rpfhdr'] include.install ['code/RPFITS.h'] end end <file_sep>class Psrchive < Formula desc 'A C++ development library for the analysis of pulsar astronomical data' homepage "https://psrchive.sourceforge.io/" stable do url "https://downloads.sourceforge.net/psrchive/psrchive-2012-12.tar.gz" sha256 "0ca685b644eae34cac6dcbbc56b3729f58d334cee94322b38ec98d26c8b9bb71" # 1. Add missing include for mem_fun and bind2nd # 2. Use 'template' keyword to treat 'get' as a dependent template name # 3 - 6. Fix unqualified lookup in templates for overloaded operators # 7. Put default arguments in function declaration only patch :DATA end head do url "git://git.code.sf.net/p/psrchive/code" depends_on "autoconf" => :build depends_on "automake" => :build depends_on "libtool" => :build patch :DATA end option "with-x11", "Experimental: build with x11 support" if build.with? "x11" depends_on "libx11" => :recommended end depends_on "gcc" depends_on "pgplot" depends_on "fftw" depends_on "cfitsio" def install ENV.deparallelize # Force clang to use the old standard library for now (solves issue with mutex type) ENV.append "CXXFLAGS", "-stdlib=libstdc++" if ENV.compiler == :clang system "./bootstrap" if build.head? system "./configure", "--disable-dependency-tracking", "--disable-silent-rules", "--prefix=#{prefix}" system "make", "install" end test do system bin/"psrchive", "--version" end end # diff --git a/Util/genutil/templates.h b/Util/genutil/templates.h # index 88ce0fc..a8e2952 100644 # --- a/Util/genutil/templates.h # +++ b/Util/genutil/templates.h # @@ -11,6 +11,7 @@ # #include <algorithm> # +#include <functional> # #include <iterator> # #include <vector> # # #include <assert.h> # #include <string.h> # --- a/Base/Formats/PSRFITS/setup_profiles.h # +++ b/Base/Formats/PSRFITS/setup_profiles.h # @@ -32,7 +32,7 @@ void setup_profiles_dat (I subint, P& profiles) # template<class E, typename I, typename P> # void setup_profiles (I subint, P& profiles) # { # - E* ext = subint->get_Profile(0,0)->Pulsar::Profile::get<E>(); # + E* ext = subint->get_Profile(0,0)->template get<E>(); # if (!ext) # throw Error (InvalidState, "setup_profiles<Extension>", # "first profile is missing required Extension"); # @@ -44,7 +44,7 @@ void setup_profiles (I subint, P& profiles) # # for (unsigned ichan=0; ichan<nchan; ichan++) # { # - ext = subint->get_Profile(0,ichan)->Pulsar::Profile::get<E>(); # + ext = subint->get_Profile(0,ichan)->template get<E>(); # if (!ext) # throw Error (InvalidState, "setup_profiles<Extension>", # "profile[%u] is missing required Extension", ichan); __END__ diff --git a/Util/genutil/Types.h b/Util/genutil/Types.h index 78a0154..13f10dd 100644 --- a/Util/genutil/Types.h +++ b/Util/genutil/Types.h @@ -123,16 +123,16 @@ namespace Signal { //! Returns the state resulting from a pscrunch operation State pscrunch (State state); -} + std::ostream& operator<< (std::ostream& ostr, Signal::Source source); + std::istream& operator>> (std::istream& is, Signal::Source& source); -std::ostream& operator << (std::ostream& ostr, Signal::Source source); -std::istream& operator >> (std::istream& is, Signal::Source& source); + std::ostream& operator<< (std::ostream& ostr, Signal::State state); + std::istream& operator>> (std::istream& is, Signal::State& state); -std::ostream& operator << (std::ostream& ostr, Signal::State state); -std::istream& operator >> (std::istream& is, Signal::State& state); + std::ostream& operator<< (std::ostream& ostr, Signal::Scale scale); + std::istream& operator>> (std::istream& is, Signal::Scale& scale); -std::ostream& operator << (std::ostream& ostr, Signal::Scale scale); -std::istream& operator >> (std::istream& is, Signal::Scale& scale); +} /* note that Basis extraction and insertion operators are defined in Conventions.h */ diff --git a/Util/genutil/Types.C b/Util/genutil/Types.C index 682c29e..470d8ba 100644 --- a/Util/genutil/Types.C +++ b/Util/genutil/Types.C @@ -232,12 +232,12 @@ Signal::State Signal::string2State (const string& ss) "Unknown state '" + ss + "'"); } -std::ostream& operator<< (std::ostream& ostr, Signal::State state) +std::ostream& Signal::operator << (std::ostream& ostr, Signal::State state) { return ostr << State2string(state); } -std::istream& operator >> (std::istream& is, Signal::State& state) +std::istream& Signal::operator >> (std::istream& is, Signal::State& state) { return extraction (is, state, Signal::string2State); } @@ -294,12 +294,12 @@ Signal::Source Signal::string2Source (const string& ss) "Unknown source '" + ss + "'"); } -std::ostream& operator<< (std::ostream& ostr, Signal::Source source) +std::ostream& Signal::operator << (std::ostream& ostr, Signal::Source source) { return ostr << Source2string(source); } -std::istream& operator >> (std::istream& is, Signal::Source& source) +std::istream& Signal::operator >> (std::istream& is, Signal::Source& source) { return extraction (is, source, Signal::string2Source); } @@ -353,12 +353,12 @@ Signal::Scale Signal::string2Scale (const string& ss) "Unknown scale '" + ss + "'"); } -std::ostream& operator<< (std::ostream& ostr, Signal::Scale scale) +std::ostream& Signal::operator << (std::ostream& ostr, Signal::Scale scale) { return ostr << Scale2string(scale); } -std::istream& operator >> (std::istream& is, Signal::Scale& scale) +std::istream& Signal::operator >> (std::istream& is, Signal::Scale& scale) { return extraction (is, scale, Signal::string2Scale); } diff --git a/Util/tempo/Pulsar/Predictor.h b/Util/tempo/Pulsar/Predictor.h index 7e774ee..c0cd789 100644 --- a/Util/tempo/Pulsar/Predictor.h +++ b/Util/tempo/Pulsar/Predictor.h @@ -99,10 +99,10 @@ namespace Pulsar { }; -} + std::ostream& operator<< (std::ostream& ostr, Pulsar::Predictor::Policy p); -std::ostream& operator<< (std::ostream& ostr, Pulsar::Predictor::Policy p); + std::istream& operator>> (std::istream& istr, Pulsar::Predictor::Policy& p); -std::istream& operator>> (std::istream& istr, Pulsar::Predictor::Policy& p); +} #endif diff --git a/Util/resources/Generator_default.C b/Util/resources/Generator_default.C index 3df6f76..33117b8 100644 --- a/Util/resources/Generator_default.C +++ b/Util/resources/Generator_default.C @@ -13,7 +13,7 @@ using namespace std; -std::ostream& operator<< (std::ostream& ostr, Pulsar::Predictor::Policy p) +std::ostream& Pulsar::operator<< (std::ostream& ostr, Pulsar::Predictor::Policy p) { if (p == Pulsar::Predictor::Input) return ostr << "input"; @@ -27,7 +27,7 @@ std::ostream& operator<< (std::ostream& ostr, Pulsar::Predictor::Policy p) return ostr; } -std::istream& operator>> (std::istream& istr, Pulsar::Predictor::Policy& p) +std::istream& Pulsar::operator>> (std::istream& istr, Pulsar::Predictor::Policy& p) { std::string policy; istr >> policy; diff --git a/Base/Formats/PSRFITS/setup_profiles.h b/Base/Formats/PSRFITS/setup_profiles.h index 29fa2f2..f6bdaae 100644 diff --git a/Util/genutil/RobustStats.h b/Util/genutil/RobustStats.h index 6be7634..cd5424a 100644 --- a/Util/genutil/RobustStats.h +++ b/Util/genutil/RobustStats.h @@ -126,7 +126,7 @@ T f_pseudosigma ( T f_spread ) * @param[in] Tukey_tune is the tuning constant for the influence function (Tukey's biweight in this case). This affects the efficiency of the estimator. The optimal value is 6.0 (i.e. include data up to 4 sigma away from the mean (Data analysis and regression, Mosteller and Tukey 1977) */ template<typename T> -T robust_stddev ( T * data, unsigned size, T initial_guess, T initial_guess_scale = 1.4826, T Tukey_tune = 6.0 ) +T robust_stddev ( T * data, unsigned size, T initial_guess, T initial_guess_scale, T Tukey_tune ) { vector<T> input; input.resize ( size ); <file_sep>class Sofa < Formula desc "Standards of Fundamental Astronomy routines (Fortran 77 version)" homepage "http://www.iausofa.org/" url "http://www.iausofa.org/2018_0130_F/sofa_f-20180130.tar.gz" sha256 "175cb39a6b65bd1e5506ed2ea57220e81defab9b4e766e215f6f245458e93d90" depends_on "gcc" def install cd "#{version}/f77/src" system "make", "install", "INSTALL_DIR=#{prefix}" end end <file_sep>class ZtarDownloadStrategy < CurlDownloadStrategy def stage(&block) UnpackStrategy::Tar.new(cached_location).extract(basename: basename, verbose: verbose?) chdir(&block) end end class CasacoreData < Formula desc "Ephemerides and geodetic data for casacore measures (via Astron)" homepage "https://github.com/casacore/casacore" head "ftp://ftp.astron.nl/outgoing/Measures/WSRT_Measures.ztar", :using => ZtarDownloadStrategy deprecated_option "use-casapy" => "with-casapy" option "with-casapy", "Use Mac CASA.App (aka casapy) data directory if found" APP_DIR = Pathname.new "/Applications" CASAPY_APP_NAME = "CASA.app" CASAPY_APP_DIR = APP_DIR / CASAPY_APP_NAME CASAPY_DATA = CASAPY_APP_DIR / "Contents/data" def install if build.with? "casapy" if !Dir.exists? CASAPY_APP_DIR odie "--with-casapy was specified, but #{CASAPY_APP_NAME} was not found in #{APP_DIR}" elsif !Dir.exists? CASAPY_DATA odie "--with-casapy was specified, but data directory not found at #{CASAPY_DATA}" end prefix.install_symlink CASAPY_DATA else (prefix / CASAPY_DATA.basename).install Dir["*"] end end test do Dir.exists? (prefix / CASAPY_DATA.basename / "ephemerides") Dir.exists? (prefix / CASAPY_DATA.basename / "geodetic") end def caveats data_dir = prefix / CASAPY_DATA.basename if File.symlink? data_dir "Linked to CASA data directory (#{CASAPY_DATA}) from #{data_dir}" else "Installed latest Astron WSRT_Measures tarball to #{data_dir}" end end end <file_sep>class Bnmin1 < Formula desc "<NAME> minimisation and statistical inference library" homepage "https://www.mrao.cam.ac.uk/~bn204/oof/bnmin1.html" url "https://www.mrao.cam.ac.uk/~bn204/soft/bnmin1-1.11.tar.bz2" sha256 "e2367190a4d6439e122cc2d78ad8224dcd9690fbc201f36a2a87fec149a39540" depends_on "swig" => :build depends_on "boost" depends_on "gcc" depends_on "gsl@1" # Patch 1: Allow the use of SWIG 2.x for Python bindings # Patch 2: Fix naming of static library # Patch 3: Make fprior_t struct public as it is referenced in public priorlist_t patch :DATA def install ENV.deparallelize # Avoid arithmetic overflow in pda_d1mach.f ENV["FFLAGS"] = "-fno-range-check" # Workaround to get fortran and C++ to play together (see Homebrew issue #20173) ENV.append "LDFLAGS", "-L/usr/lib -lstdc++" system "./configure", "--disable-debug", "--disable-dependency-tracking", "--prefix=#{prefix}", "--enable-static" system "make", "install" end test do system "#{bin}/t_unit" end end __END__ diff --git a/pybind/configure b/pybind/configure index 828ea58..0d06394 100755 --- a/pybind/configure +++ b/pybind/configure @@ -15462,9 +15462,9 @@ $as_echo "$swig_version" >&6; } if test -z "$available_patch" ; then available_patch=0 fi - if test $available_major -ne $required_major \ - -o $available_minor -ne $required_minor \ - -o $available_patch -lt $required_patch ; then + if test $available_major -lt $required_major \ + -o $available_major -eq $required_major -a $available_minor -lt $required_minor \ + -o $available_major -eq $required_major -a $available_minor -eq $required_minor -a $available_patch -lt $required_patch ; then { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: SWIG version >= 1.3.31 is required. You have $swig_version. You should look at http://www.swig.org" >&5 $as_echo "$as_me: WARNING: SWIG version >= 1.3.31 is required. You have $swig_version. You should look at http://www.swig.org" >&2;} SWIG='echo "Error: SWIG version >= 1.3.31 is required. You have '"$swig_version"'. You should look at http://www.swig.org" ; false' diff --git a/bnmin1.pc.in b/bnmin1.pc.in index 792bc60..f0f6f91 100644 --- a/bnmin1.pc.in +++ b/bnmin1.pc.in @@ -6,5 +6,5 @@ includedir=@includedir@ Name: BNMin1 Description: <NAME>'s minimisation library Version: @VERSION@ -Libs: -L${libdir} ${libdir}/libbnmin1.la +Libs: -L${libdir} -lbnmin1 Cflags: -I${includedir} diff --git a/src/priors.hxx b/src/priors.hxx index 424c9c2..0ebdff0 100644 --- a/src/priors.hxx +++ b/src/priors.hxx @@ -89,6 +89,7 @@ namespace Minim { std::vector< Minim::DParamCtr > _mpars; + public: struct fprior_t { const double * p; @@ -96,7 +97,6 @@ namespace Minim { double pmax; }; - public: typedef std::list<fprior_t> priorlist_t; private: <file_sep>class Wsclean < Formula desc "Fast widefield interferometric imager based on w-stacking" homepage "https://sourceforge.net/projects/wsclean/" url "https://downloads.sourceforge.net/projects/wsclean/files/wsclean-1.7/wsclean-1.7.tar.bz2" sha256 "05de05728ace42c3f7cba38e6c0182534d0be5d00b4563501970a9b77a70cd54" depends_on "cmake" => :build depends_on "casacore" depends_on "cfitsio" depends_on "fftw" depends_on "boost" depends_on "gsl" # 1. Add <algorithm> for std::min and std::max # 2. Change C++0x to C++11 for clang # 3. Explicitly define M_PIl (GNU extension) for clang # 4. Replace sincos with __sincos (clang extension) but not sincosf and sincosl # 5. Replace exp10 with __exp10 (clang extension) # 6. Correctly calculate memory size on OS X patch :DATA def install system "cmake", ".", *std_cmake_args system "make", "install" end test do system "#{bin}/wsclean", "-version" end end __END__ diff --git a/aocommon/uvector.h b/aocommon/uvector.h index 73e25d0..cdb9a23 100644 --- a/aocommon/uvector.h +++ b/aocommon/uvector.h @@ -6,6 +6,7 @@ #include <memory> #include <utility> #include <stdexcept> +#include <algorithm> /** * @file uvector.h diff --git a/aocommon/uvector_03.h b/aocommon/uvector_03.h index d83f0db..ae6cf90 100644 --- a/aocommon/uvector_03.h +++ b/aocommon/uvector_03.h @@ -6,6 +6,7 @@ #include <memory> #include <utility> #include <stdexcept> +#include <algorithm> /** * @file uvector.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 7b041a7..b16a6f5 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -62,7 +62,7 @@ IF("${isSystemDir}" STREQUAL "-1") SET(CMAKE_INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/lib") ENDIF("${isSystemDir}" STREQUAL "-1") -set(CMAKE_REQUIRED_FLAGS "-std=c++0x") +set(CMAKE_REQUIRED_FLAGS "-std=c++11") include(CheckCXXSourceCompiles) check_cxx_source_compiles( "#include \"${CMAKE_CURRENT_SOURCE_DIR}/aocommon/uvector.h\" @@ -107,7 +107,7 @@ ENDIF("${isSystemDir}" STREQUAL "-1") add_executable(wsclean wscleanmain.cpp wsclean.cpp casamaskreader.cpp dftpredictionalgorithm.cpp fftconvolver.cpp fftresampler.cpp fitsiochecker.cpp fitsreader.cpp fitswriter.cpp imageweights.cpp layeredimager.cpp nlplfitter.cpp modelrenderer.cpp progressbar.cpp stopwatch.cpp wsinversion.cpp cleanalgorithms/cleanalgorithm.cpp cleanalgorithms/joinedclean.cpp cleanalgorithms/moresane.cpp cleanalgorithms/multiscaleclean.cpp cleanalgorithms/simpleclean.cpp model/model.cpp msproviders/contiguousms.cpp msproviders/msprovider.cpp msproviders/partitionedms.cpp ${LBEAM_FILES}) -set_target_properties(wsclean PROPERTIES COMPILE_FLAGS "-std=c++0x") +set_target_properties(wsclean PROPERTIES COMPILE_FLAGS "-std=c++11") target_link_libraries(wsclean ${CASA_LIBS} ${FFTW3_LIB} ${Boost_FILESYSTEM_LIBRARY} ${Boost_THREAD_LIBRARY} ${Boost_SYSTEM_LIBRARY} ${FITSIO_LIB} ${GSL_LIB} ${CBLAS_LIB} ${PTHREAD_LIB} ${LBEAM_LIBS}) diff --git a/radeccoord.h b/radeccoord.h index 7400d96..f07c5de 100644 --- a/radeccoord.h +++ b/radeccoord.h @@ -7,6 +7,9 @@ #include <cstdlib> #include <cmath> +// Specifically for clang +# define M_PIl 3.1415926535897932384626433832795029L /* pi */ + class RaDecCoord { private: diff --git a/dftpredictionalgorithm.cpp b/dftpredictionalgorithm.cpp index e2dfec7..7b72cd0 100644 --- a/dftpredictionalgorithm.cpp +++ b/dftpredictionalgorithm.cpp @@ -265,7 +265,7 @@ void DFTPredictionAlgorithm::predict(MC2x2& dest, double u, double v, double w, double l = component.L(), m = component.M(), lmsqrt = component.LMSqrt(); double angle = 2.0*M_PI*(u*l + v*m + w*(lmsqrt-1.0)); double sinangleOverLMS, cosangleOverLMS; - sincos(angle, &sinangleOverLMS, &cosangleOverLMS); + __sincos(angle, &sinangleOverLMS, &cosangleOverLMS); sinangleOverLMS /= lmsqrt; cosangleOverLMS /= lmsqrt; MC2x2 temp, appFlux; diff --git a/dftpredictionalgorithm.h b/dftpredictionalgorithm.h index 9cd2aab..c0297a3 100644 --- a/dftpredictionalgorithm.h +++ b/dftpredictionalgorithm.h @@ -99,7 +99,7 @@ private: // Position angle is angle from North: // (TODO this and next statements can be optimized to remove add) double paSin, paCos; - sincos(positionAngle+0.5*M_PI, &paSin, &paCos); + __sincos(positionAngle+0.5*M_PI, &paSin, &paCos); // Make rotation matrix long double transf[4]; transf[0] = paCos; diff --git a/layeredimager.cpp b/layeredimager.cpp index 3e5566c..ce3f840 100644 --- a/layeredimager.cpp +++ b/layeredimager.cpp @@ -651,7 +651,7 @@ void LayeredImager::projectOnImageAndCorrect(const std::complex<double> *source, double rad = twoPiW * *sqrtLMIter; double s, c; - sincos(rad, &s, &c); + __sincos(rad, &s, &c); /*std::complex<double> val = std::complex<double>( source->real() * c - source->imag() * s, source->real() * s + source->imag() * c @@ -725,7 +725,7 @@ void LayeredImager::copyImageToLayerAndInverseCorrect(std::complex<double> *dest double rad = twoPiW * *sqrtLMIter; double s, c; - sincos(rad, &s, &c); + __sincos(rad, &s, &c); double realVal = dataReal[xDest + yDest*_width]; if(IsComplex) { diff --git a/imagecoordinates.h b/imagecoordinates.h index bbfcf04..4ccb770 100644 --- a/imagecoordinates.h +++ b/imagecoordinates.h @@ -130,13 +130,19 @@ class ImageCoordinates } private: static void SinCos(double angle, double* sinAngle, double* cosAngle) - { sincos(angle, sinAngle, cosAngle); } + { __sincos(angle, sinAngle, cosAngle); } static void SinCos(long double angle, long double* sinAngle, long double* cosAngle) - { sincosl(angle, sinAngle, cosAngle); } + { + *sinAngle = sin(angle); + *cosAngle = cos(angle); + } static void SinCos(float angle, float* sinAngle, float* cosAngle) - { sincosf(angle, sinAngle, cosAngle); } + { + *sinAngle = sin(angle); + *cosAngle = cos(angle); + } ImageCoordinates(); }; diff --git a/matrix2x2.h b/matrix2x2.h index 66f4b2a..41db86c 100644 --- a/matrix2x2.h +++ b/matrix2x2.h @@ -262,7 +262,7 @@ public: static void RotationMatrix(std::complex<T>* matrix, double alpha) { T cosAlpha, sinAlpha; - sincos(alpha, &sinAlpha, &cosAlpha); + __sincos(alpha, &sinAlpha, &cosAlpha); matrix[0] = cosAlpha; matrix[1] = -sinAlpha; matrix[2] = sinAlpha; matrix[3] = cosAlpha; } diff --git a/wsinversion.cpp b/wsinversion.cpp index 3b5d9ad..aff3ec7 100644 --- a/wsinversion.cpp +++ b/wsinversion.cpp @@ -719,7 +719,7 @@ void WSInversion::rotateVisibilities(const BandData &bandData, double shiftFacto { const double wShiftRad = shiftFactor / bandData.ChannelWavelength(ch); double rotSinD, rotCosD; - sincos(wShiftRad, &rotSinD, &rotCosD); + __sincos(wShiftRad, &rotSinD, &rotCosD); float rotSin = rotSinD * multFactor, rotCos = rotCosD * multFactor; std::complex<float> v = *dataIter; *dataIter = std::complex<float>( diff --git a/modelrenderer.cpp b/modelrenderer.cpp index c284e3e..cc138b1 100644 --- a/modelrenderer.cpp +++ b/modelrenderer.cpp @@ -87,7 +87,8 @@ void ModelRenderer::Restore(NumType* imageData, size_t imageWidth, size_t imageH // Make rotation matrix long double transf[4]; // Position angle is angle from North: - sincosl(beamPA+0.5*M_PI, &transf[2], &transf[0]); + transf[2] = sin(beamPA+0.5*M_PI); + transf[0] = cos(beamPA+0.5*M_PI); transf[1] = -transf[2]; transf[3] = transf[0]; double sigmaMax = std::max(std::fabs(sigmaMaj * transf[0]), std::fabs(sigmaMaj * transf[1])); @@ -170,7 +171,8 @@ void ModelRenderer::Restore(NumType* imageData, NumType* modelData, size_t image // Make rotation matrix long double transf[4]; // Position angle is angle from North: - sincosl(beamPA+0.5*M_PI, &transf[2], &transf[0]); + transf[2] = sin(beamPA+0.5*M_PI); + transf[0] = cos(beamPA+0.5*M_PI); transf[1] = -transf[2]; transf[3] = transf[0]; double sigmaMax = std::max(std::fabs(sigmaMaj * transf[0]), std::fabs(sigmaMaj * transf[1])); diff --git a/imageweights.cpp b/imageweights.cpp index fc3676f..446e3cd 100644 --- a/imageweights.cpp +++ b/imageweights.cpp @@ -212,7 +212,7 @@ void ImageWeights::FinishGridding() for(ao::uvector<double>::const_iterator i=_grid.begin(); i!=_grid.end(); ++i) avgW += *i * *i; avgW /= _totalSum; - double numeratorSqrt = 5.0 * exp10(-_weightMode.BriggsRobustness()); + double numeratorSqrt = 5.0 * __exp10(-_weightMode.BriggsRobustness()); double sSq = numeratorSqrt*numeratorSqrt / avgW; for(ao::uvector<double>::iterator i=_grid.begin(); i!=_grid.end(); ++i) { diff --git a/nlplfitter.cpp b/nlplfitter.cpp index f67eaba..8a027c7 100644 --- a/nlplfitter.cpp +++ b/nlplfitter.cpp @@ -146,7 +146,7 @@ public: fity = a_j + fity * lg; } //std::cout << x << ':' << fity << " / \n"; - gsl_vector_set(f, i, exp10(fity) - y); + gsl_vector_set(f, i, __exp10(fity) - y); } return GSL_SUCCESS; @@ -171,7 +171,7 @@ public: const double a_j = gsl_vector_get(xvec, j); fity = a_j + fity * lg; } - fity = exp10(fity); + fity = __exp10(fity); // dY/da_i = e^[ a_0...a_i-1,a_i+1...a_n] * (e^[a_i {log x}^i]) {log x}^i gsl_matrix_set(J, i, 0, fity); @@ -453,5 +453,5 @@ double NonLinearPowerLawFitter::Evaluate(double x, const std::vector<double>& te size_t j = terms.size()-k-1; y = y * lg + terms[j]; } - return exp10(y); + return __exp10(y); } diff --git a/nlplfitter.h b/nlplfitter.h index 27d26ec..756f557 100644 --- a/nlplfitter.h +++ b/nlplfitter.h @@ -39,7 +39,7 @@ public: static double Term0ToFactor(double term0, double term1) { - return exp10(term0); // + term1*log(NLPLFact)); + return __exp10(term0); // + term1*log(NLPLFact)); } static double FactorToTerm0(double factor, double term1) diff --git a/wsinversion.cpp b/wsinversion.cpp index aff3ec7..0fd3b72 100644 --- a/wsinversion.cpp +++ b/wsinversion.cpp @@ -22,6 +22,11 @@ #include <boost/thread/thread.hpp> +#ifdef __APPLE__ +#include <sys/types.h> +#include <sys/sysctl.h> +#endif /* __APPLE__ */ + WSInversion::MSData::MSData() : matchingRows(0), totalRowsProcessed(0) { } @@ -30,8 +35,14 @@ WSInversion::MSData::~MSData() WSInversion::WSInversion(ImageBufferAllocator<double>* imageAllocator, size_t threadCount, double memFraction, double absMemLimit) : InversionAlgorithm(), _phaseCentreRA(0.0), _phaseCentreDec(0.0), _phaseCentreDL(0.0), _phaseCentreDM(0.0), _denormalPhaseCentre(false), _hasFrequencies(false), _freqHigh(0.0), _freqLow(0.0), _bandStart(0.0), _bandEnd(0.0), _beamSize(0.0), _totalWeight(0.0), _startTime(0.0), _gridMode(LayeredImager::NearestNeighbour), _cpuCount(threadCount), _laneBufferSize(_cpuCount*2), _imageBufferAllocator(imageAllocator) { - long int pageCount = sysconf(_SC_PHYS_PAGES), pageSize = sysconf(_SC_PAGE_SIZE); - _memSize = (int64_t) pageCount * (int64_t) pageSize; +#ifdef __APPLE__ + size_t len = sizeof(_memSize); + int ret = sysctlbyname("hw.memsize", &_memSize, &len, NULL, 0); +#else + long int pageCount = sysconf(_SC_PHYS_PAGES), pageSize = sysconf(_SC_PAGE_SIZE); + _memSize = (int64_t) pageCount * (int64_t) pageSize; +#endif /* __APPLE__ */ + double memSizeInGB = (double) _memSize / (1024.0*1024.0*1024.0); if(memFraction == 1.0 && absMemLimit == 0.0) { std::cout << "Detected " << round(memSizeInGB*10.0)/10.0 << " GB of system memory, usage not limited.\n"; @@ -46,7 +57,7 @@ WSInversion::WSInversion(ImageBufferAllocator<double>* imageAllocator, size_t th else std::cout << "limit=" << round(absMemLimit*10.0)/10.0 << "GB)\n"; - _memSize = int64_t((double) pageCount * (double) pageSize * memFraction); + _memSize = int64_t((double) _memSize * memFraction); if(absMemLimit!=0.0 && double(_memSize) > double(1024.0*1024.0*1024.0) * absMemLimit) _memSize = int64_t(double(absMemLimit) * double(1024.0*1024.0*1024.0)); } <file_sep>class Libmodbus2 < Formula desc 'A library to send/receive data according to the Modbus protocol' homepage 'http://libmodbus.org' url 'https://github.com/downloads/stephane/libmodbus/libmodbus-2.0.4.tar.gz' sha256 '408b314cbfd2bc494a8c4059db29a5d514d8a102a73519eda44517492aeffaf0' def install system "./configure", "--disable-dependency-tracking", "--prefix=#{prefix}" system "make", "install" end end <file_sep>class Makems < Formula desc 'Make CASA MeasurementSets from scratch' homepage 'https://github.com/ska-sa/meqtrees/wiki/BuildingMakeMs' url 'https://svn.astron.nl/makems/release/makems/release-1.2.0' head 'https://svn.astron.nl/makems/trunk/makems' depends_on 'cmake' => :build depends_on 'casacore' # Darwin does not have /usr/include/malloc.h # Darwin already defines 'union semun' in sys/sem.h patch :DATA def install # To get a build type besides "gnu_opt" we need to change from superenv to std env first build_type = 'gnu_opt' mkdir_p "LOFAR/build/#{build_type}" cd "LOFAR/build/#{build_type}" cmake_args = std_cmake_args cmake_args.delete '-DCMAKE_BUILD_TYPE=None' cmake_args << "-DCMAKE_BUILD_TYPE=#{build_type}" cmake_args << "-DCMAKE_MODULE_PATH:PATH=#{Dir.pwd}/../../../LOFAR/CMake" cmake_args << '-DUSE_LOG4CPLUS=OFF' << '-DBUILD_TESTING=OFF' system 'cmake', '../..', *cmake_args system 'make' bin.install 'CEP/MS/src/makems' cd '../../../doc' doc.install 'makems.pdf', 'examples', 'mkant' bin.install "#{doc}/mkant/mkant.py" end test do mktemp do # Create MS and convert to FITS to verify file structure cp_r ["#{doc}/examples/WSRT_ANTENNA", "#{doc}/examples/makems.cfg"], '.' system '#{bin}/makems makems.cfg' system '#{bin}/ms2uvfits in=test.MS_p0 out=test.fits writesyscal=F' if File.exists? 'test.fits' then ohai 'makems OK' else onoe 'makems FAILED' end end end end __END__ diff --git a/LOFAR/LCS/Common/src/CMakeLists.txt b/LOFAR/LCS/Common/src/CMakeLists.txt index 8ab0297..c4badbc 100644 --- a/LOFAR/LCS/Common/src/CMakeLists.txt +++ b/LOFAR/LCS/Common/src/CMakeLists.txt @@ -73,8 +73,7 @@ if(HAVE_SHMEM) -DMORECORE=shmbrk -DMORECORE_CONTIGUOUS=0 -DMORECORE_CANNOT_TRIM=1 - -DSHMEM_ALLOC - -DHAVE_USR_INCLUDE_MALLOC_H) + -DSHMEM_ALLOC) join_arguments(shmem_COMPILE_FLAGS) set_source_files_properties(${shmem_LIB_SRCS} PROPERTIES COMPILE_FLAGS ${shmem_COMPILE_FLAGS}) diff --git a/LOFAR/LCS/Common/src/shmem/Makefile.am b/LOFAR/LCS/Common/src/shmem/Makefile.am index fa7fe72..9ae2060 100644 --- a/LOFAR/LCS/Common/src/shmem/Makefile.am +++ b/LOFAR/LCS/Common/src/shmem/Makefile.am @@ -13,8 +13,7 @@ AM_CPPFLAGS = \ -DMORECORE=shmbrk \ -DMORECORE_CONTIGUOUS=0 \ -DMORECORE_CANNOT_TRIM=1 \ - -DSHMEM_ALLOC \ - -DHAVE_USR_INCLUDE_MALLOC_H + -DSHMEM_ALLOC libshmem_la_SOURCES = \ $(DOCHDRS) \ diff --git a/LOFAR/LCS/Common/src/shmem/shmem_alloc.cc b/LOFAR/LCS/Common/src/shmem/shmem_alloc.cc index fefc086..9ca31e0 100644 --- a/LOFAR/LCS/Common/src/shmem/shmem_alloc.cc +++ b/LOFAR/LCS/Common/src/shmem/shmem_alloc.cc @@ -41,10 +41,10 @@ using LOFAR::map; -// needs to be defined -union semun { - int val; -}; +// already defined in <sys/sem.h> +// union semun { +// int val; +// }; /* definitions */ #define SHMID_REGISTRY_INITIAL_SIZE 32 <file_sep>class Casacore < Formula desc "Suite of C++ libraries for radio astronomy data processing" homepage "https://github.com/casacore/casacore" url "https://github.com/casacore/casacore/archive/v3.4.0.tar.gz" sha256 "31f02ad2e26f29bab4a47a2a69e049d7bc511084a0b8263360e6157356f92ae1" head "https://github.com/casacore/casacore.git" depends_on "cmake" => :build depends_on "fftw" depends_on "hdf5" depends_on "cfitsio" depends_on "wcslib" depends_on "gcc" # for gfortran depends_on "readline" depends_on "casacore-data" option "with-python", "Build Python bindings" patch :DATA if build.with?("python") depends_on "python3" depends_on "numpy" depends_on "boost-python3" end def install casacore_data = HOMEBREW_PREFIX / "opt/casacore-data/data" if !casacore_data.exist? opoo "casacore data not found at #{casacore_data}" end # To get a build type besides "release" we need to change from superenv to std env first build_type = "release" mkdir "build/#{build_type}" do cmake_args = std_cmake_args cmake_args.delete "-DCMAKE_BUILD_TYPE=None" cmake_args << "-DCMAKE_BUILD_TYPE=#{build_type}" cmake_args << "-DBUILD_PYTHON=OFF" cmake_args << "-DBUILD_PYTHON3=#{(build.with? "python") ? "ON" : "OFF"}" cmake_args << "-DUSE_OPENMP=OFF" cmake_args << "-DUSE_FFTW3=ON" << "-DFFTW3_ROOT_DIR=#{HOMEBREW_PREFIX}" cmake_args << "-DUSE_HDF5=ON" << "-DHDF5_ROOT_DIR=#{HOMEBREW_PREFIX}" cmake_args << "-DBoost_NO_BOOST_CMAKE=True" cmake_args << "-DDATA_DIR=#{HOMEBREW_PREFIX / "opt/casacore-data/data"}" system "cmake", "../..", *cmake_args system "make", "install" end end test do system bin / "findmeastable", "IGRF" system bin / "findmeastable", "DE405" end end __END__ diff --git a/python/Converters/test/CMakeLists.txt b/python/Converters/test/CMakeLists.txt index 32214a8..321c98b 100644 --- a/python/Converters/test/CMakeLists.txt +++ b/python/Converters/test/CMakeLists.txt @@ -1,6 +1,6 @@ include_directories ("..") add_library(tConvert MODULE tConvert.cc) SET_TARGET_PROPERTIES(tConvert PROPERTIES PREFIX "_") -target_link_libraries (tConvert casa_python ${PYTHON_LIBRARIES}) +target_link_libraries (tConvert casa_python) add_test (tConvert ${CMAKE_SOURCE_DIR}/cmake/cmake_assay ./tConvert) add_dependencies(check tConvert) <file_sep>class Cattery < Formula desc 'MeqTrees-based frameworks for interferometer simulation and calibration' homepage 'http://meqtrees.net' url 'https://svn.astron.nl/MeqTrees/release/Cattery/release-1.2.0' head 'https://github.com/ska-sa/meqtrees-cattery.git' def install # Obtain information on Python installation python_xy = "python" + %x(python -c 'import sys;print(sys.version[:3])').chomp python_site_packages = lib + "#{python_xy}/site-packages" mkdir_p "#{python_site_packages}" rm_f 'Meow/LSM0' cp_r 'LSM', 'Meow/LSM0' cp_r ['Calico', 'LSM', 'Lions', 'Meow', 'Siamese', 'qt.py'], "#{python_site_packages}/" if build.head? cp_r 'Scripter', "#{python_site_packages}/" end mkdir_p "#{share}/meqtrees" cp_r 'test', "#{share}/meqtrees/" end end <file_sep>class Owlcat < Formula desc 'Miscellaneous scripts for manipulating radio interferometry data' homepage 'http://www.astron.nl/meqwiki-data/users/oms/Owlcat-plotms-tutorial.purrlog/' # Waiting for next release after 1.2.0 to be supported on Mac # url 'https://svn.astron.nl/Owlcat/release/Owlcat/release-1.2.0' # Repository after 8761 contains both Pyxis dir and pyxis script which clash on HFS+ head 'https://svn.astron.nl/Owlcat/trunk/Owlcat', :revision => '8761' depends_on 'python@2' depends_on 'numpy' depends_on 'pyrap' depends_on 'cattery' # Missing dependencies: matplotlib, pyfits def install # Obtain information on Python installation python_xy = "python" + %x(python -c 'import sys;print(sys.version[:3])').chomp python_site_packages = lib + "#{python_xy}/site-packages" inreplace 'owlcat.sh', 'dir=`dirname $(readlink -f $0)`', "dir='#{libexec}'" bin.install 'owlcat.sh' mv "#{bin}/owlcat.sh", "#{bin}/owlcat" mkdir_p "#{python_site_packages}" # Since Cattery while be installed in the usual path, we don't need to look for it inreplace 'Owlcat/__init__.py', '"Cattery"', '' cp_r 'Owlcat', "#{python_site_packages}/" libexec.install Dir['*.py'], Dir['*.sh'], 'commands.list' doc.install 'tutorial/Owlcat-plotms-tutorial.purrlog' doc.install 'README', 'imager.conf.example', 'owlcat-logo.jpg' end end <file_sep>class Meqtrees < Formula desc 'A system for implementing and solving arbitrary Measurement Equations' homepage 'http://meqtrees.net/' url 'https://svn.astron.nl/MeqTrees/release/Timba/release-1.2.1' head 'https://github.com/ska-sa/meqtrees-timba.git' option 'enable-debug', 'Enable debug build of MeqTrees as well as debugging symbols' option 'without-symbols', 'Remove debugging symbols' # Since MeqTrees is still quite experimental we want debug symbols # included, which are aggressively stripped out in superenv. env :std depends_on 'cmake' => :build depends_on 'casacore' depends_on 'pyrap' depends_on 'casarest' depends_on 'cfitsio' depends_on 'fftw' depends_on 'blitz' depends_on 'qdbm' depends_on 'python@2' depends_on 'numpy' # Missing dependencies: pyqwt pyfits PIL # The following packages are strictly optional but by including them # it is easy to install the whole MeqTrees suite in one go # (and it allows testing the whole suite via Batchtest) depends_on 'purr' depends_on 'tigger' depends_on 'cattery' depends_on 'owlcat' depends_on 'makems' if not build.head? # Added explicit template instantiation and corrected constness (fixed in HEAD) patch do url 'https://gist.github.com/raw/4568292/e187cef9d60d4b89293f2d6b93ad9940ccd9c5aa/patch1.diff' end # Use correct version of strerror_r on the Mac (fixed in HEAD) patch do url 'https://gist.github.com/raw/4568292/21ebb9fd3094b18c37555ef1288915036c623c03/patch2.diff' end # Fixed bug in thread map index (fixed in HEAD) patch do url 'https://gist.github.com/raw/4568292/058d009cd7e90f9578d90494b508b96968dddd13/patch3.diff' end # Disambiguate Mutex::Lock class (fixed in HEAD) patch do url 'https://gist.github.com/raw/4568292/38983609880a37d0a93d626628d31fbba76accd2/patch5.diff' end # Use file-based Unix sockets on the Mac as abstract sockets are Linux-only (fixed in HEAD) patch do url 'https://gist.github.com/raw/4568292/c7cb2091dc7b63b55dbe6f810b5a11bd75856be5/patch7.diff' end end # Add support for Blitz++ 0.10 patch do url 'https://gist.github.com/raw/4568292/76627df1f718eceef29fa3e224d2bfee90c3ce06/patch4.diff' end # Suppress compiler warning by using correct format specifier # 'https://gist.github.com/raw/4568292/f978679da33f843a6260d4c7a36f4c021174d32c/patch6.diff' if build.head? # Provide link to Siamese and Calico packages instead of Cattery to get it included in sidebars of GUI file dialogs patch do url 'https://gist.github.com/ludwigschwardt/4568292/raw/abd9de4a07380e296e7b5e592313c8494fae9bb1/patch8.diff' end def install # Obtain information on Python installation python_xy = "python" + %x(python -c 'import sys;print(sys.version[:3])').chomp python_site_packages = lib + "#{python_xy}/site-packages" # If semi-standard Python script not included in MeqTrees repository, download it (Python version 2.7) if not File.exists? 'Tools/Build/h2py.py' system 'curl -o Tools/Build/h2py.py http://hg.python.org/cpython/raw-file/1cfe0f50fd0c/Tools/scripts/h2py.py' end if build.include? 'enable-debug' build_type = 'debug' elsif build.without? 'symbols' build_type = 'release' else build_type = 'relwithdebinfo' end mkdir_p "build/#{build_type}" cd "build/#{build_type}" cmake_args = std_cmake_args cmake_args.delete '-DCMAKE_BUILD_TYPE=None' cmake_args << "-DCMAKE_BUILD_TYPE=#{build_type}" cmake_args << "-DCMAKE_SHARED_LINKER_FLAGS='-undefined dynamic_lookup'" system 'cmake', '../..', *cmake_args system "make" ohai "make install" # The debug symlink tree is the most complete - use as template for all build types cd "../../install/symlinked-debug/bin" Dir.foreach('.') do |item| next if ['.', '..', 'purr.py', 'trut'].include? item # Preserve local links but dereference proper links item = if (File.symlink? item) and (File.readlink(item).start_with? '../') then File.readlink(item) else item end item.sub! '/debug/', "/#{build_type}/" bin.install item if File.exists? item end cd "../lib" Dir.foreach('.') do |item| next if not item.start_with? 'lib' # Preserve local links but dereference proper links item = if (File.symlink? item) and (File.readlink(item).start_with? '../') then File.readlink(item) else item end item.sub! '/debug/', "/#{build_type}/" item.sub! '.so', '.dylib' lib.install item if File.exists? item end cd '../libexec/python/Timba' timba = "#{python_site_packages}/Timba" mkdir_p timba # Create DLFCN.py for our system quiet_system 'python', '../../../../../Tools/Build/h2py.py /usr/include/dlfcn.h' Dir.foreach('.') do |item| next if ['.', '..'].include? item # Preserve local links but dereference proper links item = if (File.symlink? item) and (File.readlink(item).start_with? '../') then File.readlink(item) else item end item.sub! '/debug/', "/#{build_type}/" if File.exists? item if item.end_with? '.dylib' # Move Python extensions to main library directory (as executables also link to them) # and symlink them back to module directory with desired .so extension lib.install item libname = File.basename(item, '.dylib') ln_s "#{lib}/#{libname}.dylib", "#{timba}/#{libname}.so" else cp_r item, timba+'/' end end end cd '../icons' mkdir_p "#{share}/meqtrees/icons" icons = 'treebrowser' icons = if File.symlink? icons then File.readlink(icons) else icons end cp_r icons, "#{share}/meqtrees/icons/" if File.exists? icons # Assemble debug symbol (*.dSYM) files if the build type requires it if build_type != 'release' cd "#{lib}" Dir.foreach('.') do |item| next if not item.end_with? '.dylib' safe_system 'dsymutil', item end end end end <file_sep>class Casarest < Formula desc 'The light-weight imager (lwimager) for radio astronomy' homepage 'https://github.com/ska-sa/meqtrees/wiki/LinkingWithCasaCore' url 'https://svn.astron.nl/casarest/release/casarest/release-1.2.1' head 'https://svn.astron.nl/casarest/trunk/casarest' depends_on 'cmake' => :build depends_on 'casacore' depends_on 'boost' depends_on 'readline' depends_on 'wcslib' depends_on 'hdf5' depends_on 'gcc' # def patches # p = [] # # Fixes disallowed size_t vs int* comparison, which used to be specially # # included for Darwin systems, but does not seem relevant anymore (fixed in HEAD). # p << 'https://gist.github.com/raw/4705907/678753a3fc04751457271c82f4a3fe39149b5819/patch1.diff' if not build.head? # # Add boost_system library to avoid missing symbols (fixed in HEAD) # p << 'https://gist.github.com/raw/4705907/a199623d33e3dd566a8ffe15cc0448f6e771e44d/patch2.diff' if not build.head? # return p.empty? ? nil : p # end def install # Workaround to get fortran and C++ to play together (see Homebrew issue #20173) ENV.append 'LDFLAGS', "-L/usr/lib -lstdc++" # Force clang to use the old standard library for now (solves issue with complex type) ENV.append 'CXXFLAGS', "-stdlib=libstdc++" if ENV.compiler == :clang mkdir_p 'build' cd 'build' cmake_args = std_cmake_args cmake_args << "-DCASACORE_ROOT_DIR=#{HOMEBREW_PREFIX}" cmake_args << "-DHDF5_ROOT_DIR=#{HOMEBREW_PREFIX}" system 'cmake', '..', *cmake_args system "make install" mkdir_p "#{share}/casarest" mv '../measures_data', "#{share}/casarest/data" end end <file_sep>class ObitDownloadStrategy < SubversionDownloadStrategy def stage obit_location = "#{cached_location}/trunk/ObitSystem/Obit" # Bake SVN revision into ObitVersion.c before staging/exporting the Obit tarball without commit history quiet_system "python", "#{obit_location}/share/scripts/getVersion.py", obit_location ohai "Obit version is " + File.open("#{obit_location}/src/ObitVersion.c") { |f| f.read[/"(\d+M*)"/][$1] } super end end class Obit < Formula desc "Radio astronomy software for imaging algorithm development" homepage "http://www.cv.nrao.edu/~bcotton/Obit.html" head "https://github.com/bill-cotton/Obit/", :using => ObitDownloadStrategy # We need to find the MacTeX executables in order to build the Obit # user manuals and they are not in the Homebrew restricted path. # Also, since Obit is still quite experimental we want debug symbols # included, which are aggressively stripped out in superenv. env :std depends_on "autoconf" => :build depends_on "automake" => :build depends_on "pkg-config" => :build depends_on "pgplot" depends_on "cfitsio" depends_on "glib" depends_on "fftw" depends_on "gsl" depends_on "openmotif" depends_on "xmlrpc-c" if MacOS.version == :el_capitan depends_on "libxml2" # because the system version is broken on macOS 10.11 end depends_on "boost" depends_on "libair" depends_on "gcc" conflicts_with "plplot", :because => "it has a float type mismatch and configure can't disable it" # Build main Obit library as shared dylib # Improve installation procedure for Python module # Don't update version in install as it is done as part of staging now # Add missing build dependencies to enable parallel builds # Move include_dirs into Extension class in Python setup.py # Set install_name with full path on libObit.dylib to appease macOS SIP # Work around glib issue (https://bugzilla.gnome.org/show_bug.cgi?id=780238 and # https://github.com/Homebrew/homebrew-core/issues/5404) by forcing arch to x86_64 patch :DATA def install # Obtain information on Python and X11 installations python_xy = "python" + `python -c "import sys;print(sys.version[:3])"`.chomp site_packages = lib + "#{python_xy}/site-packages" global_site_packages = HOMEBREW_PREFIX/"lib/#{python_xy}/site-packages" x11_inc = `bash -c "PKG_CONFIG_PATH=/usr/X11/lib/pkgconfig pkg-config x11 --cflags"`.chomp x11_lib = `bash -c "PKG_CONFIG_PATH=/usr/X11/lib/pkgconfig pkg-config x11 --libs"`.chomp cd "trunk/ObitSystem" ohai "Building and installing main Obit package" ohai "-----------------------------------------" cd "Obit" # Attempt to make ALMAWVR aka libair support work inreplace "m4/wvr.m4", "almawvr/almaabs_c.h", "almaabs_c.h" inreplace "m4/wvr.m4", "wvr_almaabs_ret", "almaabs_ret" inreplace "tasks/WVRCal.c", "almawvr/almaabs_c.h", "almaabs_c.h" # This fixes the install_name of libObit.dylib to avoid the following # dlopen error when importing the Obit Python module: # "unsafe use of relative rpath libObit.dylib in ...Obit.so with restricted binary" # which is due to System Integrity Protection (SIP) added in macOS 10.11 (El Capitan) # (see https://stackoverflow.com/questions/31343299) inreplace "lib/Makefile", "@prefix@/lib", lib # PLplot supports floating-point pen widths since version 5.10.0 (2014-02-13) # inreplace "src/ObitPlot.c", "plwid ((PLINT)lwidth);", "plwidth ((PLFLT)lwidth);" safe_system "aclocal -I m4; autoconf" # Unfortunately PLplot has a 32-bit PLFLT while Obit has a 64-bit ofloat so disable it # [doesn't work, use conflicts_with instead in the meantime] system "./configure", "--prefix=#{prefix}", "--without-plplot" system "make" # Assemble debug symbol (*.dSYM) files safe_system "dsymutil", "lib/libObit.dylib", "python/build/site-packages/Obit.so" # Since Obit does not do its own "make install", we have to do it ourselves ohai "make install" rm_f ["bin/.cvsignore", "include/.cvsignore"] prefix.install "bin" prefix.install "include" lib.install Dir["lib/libObit.dylib*"] mkdir_p site_packages cp_r "python/build/site-packages", "#{site_packages}/../" mkdir_p "#{share}/obit" cp_r ["share/data", "share/scripts", "TDF"], "#{share}/obit" mv "testData", "#{share}/obit/data/test" mv "testScripts", "#{share}/obit/scripts/test" ohai "Building and installing ObitTalk package" ohai "----------------------------------------" cd "../ObitTalk" begin ohai "Checking for the presence of LaTeX and friends for building documentation" safe_system "which latex bibtex dvips dvipdf" rescue ErrorDuringExecution # Remove the documentation build (brittle but preferable to getting aclocal and automake involved) inreplace "Makefile.in", " doc", "" opoo "No TeX installation found - documentation will not be built (please install MacTeX first if you want docs)" end inreplace "bin/ObitTalk.in", "@datadir@/python", global_site_packages inreplace "bin/ObitTalkServer.in", "@datadir@/python", global_site_packages inreplace "python/Makefile.in", "share/obittalk/python", "lib/#{python_xy}/site-packages" inreplace "python/Proxy/Makefile.in", "$(pkgdatadir)/python", "$(prefix)/lib/#{python_xy}/site-packages" inreplace "python/Wizardry/Makefile.in", "$(pkgdatadir)/python", "$(prefix)/lib/#{python_xy}/site-packages" inreplace "python/Proxy/ObitTask.py", "/usr/lib/obit/tdf", "#{share}/obit/TDF" inreplace "python/Proxy/ObitTask.py", "/usr/lib/obit/bin", bin inreplace "doc/Makefile.in", "../../doc", "#{share}/doc/obit" system "./configure", "PYTHONPATH=#{site_packages}:$PYTHONPATH", "DYLD_LIBRARY_PATH=#{lib}", "--prefix=#{prefix}" system "make" system "make", "install", "prefix=#{prefix}" ohai "Building and installing ObitView package" ohai "----------------------------------------" cd "../ObitView" system "./configure", "CFLAGS=#{x11_inc}", "LDFLAGS=#{x11_lib}", "--with-obit=#{prefix}", "--prefix=#{prefix}" system "make" system "make", "install", "prefix=#{prefix}" end test do mktemp do cp_r "#{share}/obit/data/test", "data" safe_system "gunzip data/*.gz" tests = ["testObit", "testContourPlot", "testFeather", "testHGeom", "testUVImage", "testUVSub", "testCleanVis"] tests.each do |name| safe_system "python", "#{share}/obit/scripts/test/#{name}.py", "data" ohai "#{name} OK" end end end end __END__ diff --git a/trunk/ObitSystem/Obit/lib/Makefile b/trunk/ObitSystem/Obit/lib/Makefile index 39f372a..9dcf2a1 100644 --- a/trunk/ObitSystem/Obit/lib/Makefile +++ b/trunk/ObitSystem/Obit/lib/Makefile @@ -35,7 +35,7 @@ #------------------------------------------------------------------------ # targets to build TARGETS = libObit.a -SHTARGETS = libObit.so +SHTARGETS = libObit.dylib # list of object modules OBJECTS := $(wildcard *.o) @@ -53,6 +53,10 @@ libObit.so: ${OBJECTS} gcc -shared -o libObit.so ${OBJECTS} cp libObit.so ../../../deps/lib +# build Obit shared library on Mac +libObit.dylib: $(OBJECTS) + $(CC) -dynamiclib -flat_namespace -undefined dynamic_lookup -install_name @prefix@/lib/libObit.dylib -o $@ $^ + clean: rm -f $(TARGETS) $(SHTARGETS) diff --git a/trunk/ObitSystem/Obit/tasks/Makefile.in b/trunk/ObitSystem/Obit/tasks/Makefile.in index a7995bd..1884fec 100644 --- a/trunk/ObitSystem/Obit/tasks/Makefile.in +++ b/trunk/ObitSystem/Obit/tasks/Makefile.in @@ -63,7 +63,14 @@ ALL_LDFLAGS = $(LDFLAGS) @CFITSIO_LDFLAGS@ @FFTW_LDFLAGS@ @FFTW3_LDFLAGS@ \ @GSL_LDFLAGS@ @PLPLOT_LDFLAGS@ @PGPLOT_LDFLAGS@ @WVR_LDFLAGS@ \ $(CLIENT_LDFLAGS) $(SERVER_LDFLAGS) -LIBS = ../lib/libObit.a @CFITSIO_LIBS@ @FFTW_LIBS@ @FFTW3_LIBS@ @GLIB_LIBS@ \ +# Static library option +# OBIT_LIB_TARGET = ../lib/libObit.a +# OBIT_LIB = ../lib/libObit.a +# Shared library option +OBIT_LIB_TARGET = ../lib/libObit.dylib +OBIT_LIB = -L../lib -lObit + +LIBS = $(OBIT_LIB) @CFITSIO_LIBS@ @FFTW_LIBS@ @FFTW3_LIBS@ @GLIB_LIBS@ \ @GSL_LIBS@ @PLPLOT_LIBS@ @PGPLOT_LIBS@ $(CLIENT_LIBS) $(SERVER_LIBS) \ @LIBS@ @FLIBS@ @GTHREAD_LIBS@ @WVR_LIBS@ @@ -76,17 +83,18 @@ TARGETS := $(addprefix $(BINDIR),$(EXECU)) all: $(TARGETS) # generic C compile/link -$(TARGETS): $(BINDIR)% : %.c ../lib/libObit.a +$(TARGETS): $(BINDIR)% : %.c $(OBIT_LIB_TARGET) echo "compile $*.c" $(CC) $(ALL_CPPFLAGS) $(ALL_CFLAGS) $(ALL_LDFLAGS) $*.c -o $* $(LIBS) mv $* $(BINDIR) # For specific executables -$(EXECU): % : %.c ../lib/libObit.a +$(EXECU): % : %.c $(OBIT_LIB_TARGET) $(CC) $(ALL_CPPFLAGS) $(ALL_CFLAGS) $(ALL_LDFLAGS) $< -o $* $(LIBS) mv $* $(BINDIR) clean: rm -f $(TARGETS) rm -f *.o + rm -rf *.dSYM diff --git a/trunk/ObitSystem/Obit/python/Makefile.in b/trunk/ObitSystem/Obit/python/Makefile.in index 695f215..e6dd7f4 100644 --- a/trunk/ObitSystem/Obit/python/Makefile.in +++ b/trunk/ObitSystem/Obit/python/Makefile.in @@ -72,12 +76,17 @@ SWIG = @SWIG@ SWIGLIB = # Libraries in case they've changed -MYLIBS := $(wildcard ../lib/lib*.a) +# MYLIBS := $(wildcard ../lib/lib*.a) +MYLIBS := $(wildcard ../lib/lib*.dylib) # Do everything in one big module TARGETS := Obit -all: $(TARGETS) +all: install + +install: $(TARGETS) + mkdir -p build/site-packages + cp *.py $(TARGETS) build/site-packages # Build shared library for python interface $(TARGETS): setupdata.py $(MYLIBS) diff --git a/trunk/ObitSystem/Obit/Makefile.in b/trunk/ObitSystem/Obit/Makefile.in index 7b03cca..d11461b 100644 --- a/trunk/ObitSystem/Obit/Makefile.in +++ b/trunk/ObitSystem/Obit/Makefile.in @@ -87,7 +87,7 @@ cd src; $(MAKE) # update library directory libupdate: - cd lib; $(MAKE) RANLIB="$(RANLIB)" + cd lib; $(MAKE) RANLIB="$(RANLIB)" CC="$(CC)" # update test software directory testupdate: diff --git a/trunk/ObitSystem/ObitTalk/python/Makefile.in b/trunk/ObitSystem/ObitTalk/python/Makefile.in index 85e49b7..a68c62a 100644 --- a/trunk/ObitSystem/ObitTalk/python/Makefile.in +++ b/trunk/ObitSystem/ObitTalk/python/Makefile.in @@ -76,8 +76,8 @@ PROXYTAR:= $(DESTDIR)$(PYTHONDIR)/Proxy/AIPSData.py \ WIZTAR:= $(DESTDIR)$(PYTHONDIR)/Wizardry/AIPSData.py \ $(DESTDIR)$(PYTHONDIR)/Wizardry/__init__.py -# make all = directories -all: $(DESTDIR)$(PREFIX)/share $(DESTDIR)$(PREFIX)/share/obittalk +all: + echo "Nothing to make." install: $(PYTHONTAR) $(PROXYTAR) $(WIZTAR) diff --git a/trunk/ObitSystem/Obit/Makefile.in b/trunk/ObitSystem/Obit/Makefile.in index d11461b..f2fdfb0 100644 --- a/trunk/ObitSystem/Obit/Makefile.in +++ b/trunk/ObitSystem/Obit/Makefile.in @@ -56,7 +56,7 @@ DISTRIB = @PACKAGE_TARNAME@@PACKAGE_VERSION@ DIRN = @PACKAGE_NAME@ #------------------------------------------------------------------------ -TARGETS = versionupdate cfitsioupdate xmlrpcupdate srcupdate libupdate \ +TARGETS = cfitsioupdate xmlrpcupdate srcupdate libupdate \ pythonupdate taskupdate all: $(TARGETS) diff --git a/trunk/ObitSystem/Obit/Makefile.in b/trunk/ObitSystem/Obit/Makefile.in index f2fdfb0..296094e 100644 --- a/trunk/ObitSystem/Obit/Makefile.in +++ b/trunk/ObitSystem/Obit/Makefile.in @@ -86,15 +86,15 @@ srcupdate: cd src; $(MAKE) # update library directory -libupdate: +libupdate: srcupdate cd lib; $(MAKE) RANLIB="$(RANLIB)" CC="$(CC)" # update test software directory -testupdate: +testupdate: libupdate cd test; $(MAKE) # update task software directory -taskupdate: +taskupdate: libupdate cd tasks; $(MAKE) # update work directory @@ -102,7 +102,7 @@ work: cd src/work; $(MAKE) CC="$(CC)" CFLAGS="$(CFLAGS)" LIB="$(LIB)" # update python directory -pythonupdate: +pythonupdate: libupdate cd python; $(MAKE) # update from cvs repository diff --git a/trunk/ObitSystem/ObitTalk/python/Makefile.in b/trunk/ObitSystem/ObitTalk/python/Makefile.in index a68c62a..7dd5e90 100644 --- a/trunk/ObitSystem/ObitTalk/python/Makefile.in +++ b/trunk/ObitSystem/ObitTalk/python/Makefile.in @@ -95,7 +95,7 @@ $(DESTDIR)$(PREFIX)/share: $(DESTDIR)$(PREFIX) $(DESTDIR)$(PREFIX)/share/obittalk: $(DESTDIR)$(PREFIX)/share if test ! -d $(DESTDIR)$(PREFIX)/share/obittalk; then mkdir $(DESTDIR)$(PREFIX)/share/obittalk; fi -$(DESTDIR)$(PYTHONDIR):$(DESTDIR)$(PREFIX)/share/obittalk +$(DESTDIR)$(PYTHONDIR): if test ! -d $(DESTDIR)$(PYTHONDIR); then mkdir $(DESTDIR)$(PYTHONDIR); fi $(DESTDIR)$(PROXYDIR):$(DESTDIR)$(PYTHONDIR) @@ -107,49 +107,49 @@ $(DESTDIR)$(WIZDIR):$(DESTDIR)$(PYTHONDIR) $(DESTDIR)$(PYTHONDIR)/AIPSData.py: AIPSData.py $(DESTDIR)$(PYTHONDIR) cp AIPSData.py $@ -$(DESTDIR)$(PYTHONDIR)/AIPS.py: AIPS.py +$(DESTDIR)$(PYTHONDIR)/AIPS.py: AIPS.py $(DESTDIR)$(PYTHONDIR) cp AIPS.py $@ -$(DESTDIR)$(PYTHONDIR)/AIPSTask.py: AIPSTask.py +$(DESTDIR)$(PYTHONDIR)/AIPSTask.py: AIPSTask.py $(DESTDIR)$(PYTHONDIR) cp AIPSTask.py $@ -$(DESTDIR)$(PYTHONDIR)/AIPSTV.py: AIPSTV.py +$(DESTDIR)$(PYTHONDIR)/AIPSTV.py: AIPSTV.py $(DESTDIR)$(PYTHONDIR) cp AIPSTV.py $@ -$(DESTDIR)$(PYTHONDIR)/AIPSUtil.py: AIPSUtil.py +$(DESTDIR)$(PYTHONDIR)/AIPSUtil.py: AIPSUtil.py $(DESTDIR)$(PYTHONDIR) cp AIPSUtil.py $@ -$(DESTDIR)$(PYTHONDIR)/FITSData.py: FITSData.py +$(DESTDIR)$(PYTHONDIR)/FITSData.py: FITSData.py $(DESTDIR)$(PYTHONDIR) cp FITSData.py $@ -$(DESTDIR)$(PYTHONDIR)/FITS.py: FITS.py +$(DESTDIR)$(PYTHONDIR)/FITS.py: FITS.py $(DESTDIR)$(PYTHONDIR) cp FITS.py $@ -$(DESTDIR)$(PYTHONDIR)/LocalProxy.py: LocalProxy.py +$(DESTDIR)$(PYTHONDIR)/LocalProxy.py: LocalProxy.py $(DESTDIR)$(PYTHONDIR) cp LocalProxy.py $@ -$(DESTDIR)$(PYTHONDIR)/MinimalMatch.py: MinimalMatch.py +$(DESTDIR)$(PYTHONDIR)/MinimalMatch.py: MinimalMatch.py $(DESTDIR)$(PYTHONDIR) cp MinimalMatch.py $@ -$(DESTDIR)$(PYTHONDIR)/ObitTalk.py: ObitTalk.py +$(DESTDIR)$(PYTHONDIR)/ObitTalk.py: ObitTalk.py $(DESTDIR)$(PYTHONDIR) cp ObitTalk.py $@ -$(DESTDIR)$(PYTHONDIR)/ObitTalkUtil.py: ObitTalkUtil.py +$(DESTDIR)$(PYTHONDIR)/ObitTalkUtil.py: ObitTalkUtil.py $(DESTDIR)$(PYTHONDIR) cp ObitTalkUtil.py $@ -$(DESTDIR)$(PYTHONDIR)/ObitTask.py: ObitTask.py +$(DESTDIR)$(PYTHONDIR)/ObitTask.py: ObitTask.py $(DESTDIR)$(PYTHONDIR) cp ObitTask.py $@ -$(DESTDIR)$(PYTHONDIR)/ObitScript.py: ObitScript.py +$(DESTDIR)$(PYTHONDIR)/ObitScript.py: ObitScript.py $(DESTDIR)$(PYTHONDIR) cp ObitScript.py $@ -$(DESTDIR)$(PYTHONDIR)/otcompleter.py: otcompleter.py +$(DESTDIR)$(PYTHONDIR)/otcompleter.py: otcompleter.py $(DESTDIR)$(PYTHONDIR) cp otcompleter.py $@ -$(DESTDIR)$(PYTHONDIR)/Task.py: Task.py +$(DESTDIR)$(PYTHONDIR)/Task.py: Task.py $(DESTDIR)$(PYTHONDIR) cp Task.py $@ -$(DESTDIR)$(PYTHONDIR)/XMLRPCServer.py: XMLRPCServer.py +$(DESTDIR)$(PYTHONDIR)/XMLRPCServer.py: XMLRPCServer.py $(DESTDIR)$(PYTHONDIR) cp XMLRPCServer.py $@ @@ -160,32 +160,32 @@ $(DESTDIR)$(PYTHONDIR)/Proxy/AIPSData.py: Proxy/AIPSData.py $(DESTDIR)$(PROXYDIR $(DESTDIR)$(PYTHONDIR)/Proxy/FITSData.py: Proxy/FITSData.py $(DESTDIR)$(PROXYDIR) cp ./Proxy/FITSData.py $@ -$(DESTDIR)$(PYTHONDIR)/Proxy/AIPS.py: Proxy/AIPS.py +$(DESTDIR)$(PYTHONDIR)/Proxy/AIPS.py: Proxy/AIPS.py $(DESTDIR)$(PROXYDIR) cp ./Proxy/AIPS.py $@ -$(DESTDIR)$(PYTHONDIR)/Proxy/AIPSTask.py: Proxy/AIPSTask.py +$(DESTDIR)$(PYTHONDIR)/Proxy/AIPSTask.py: Proxy/AIPSTask.py $(DESTDIR)$(PROXYDIR) cp ./Proxy/AIPSTask.py $@ -$(DESTDIR)$(PYTHONDIR)/Proxy/__init__.py: Proxy/__init__.py +$(DESTDIR)$(PYTHONDIR)/Proxy/__init__.py: Proxy/__init__.py $(DESTDIR)$(PROXYDIR) cp ./Proxy/__init__.py $@ -$(DESTDIR)$(PYTHONDIR)/Proxy/ObitTask.py: Proxy/ObitTask.py +$(DESTDIR)$(PYTHONDIR)/Proxy/ObitTask.py: Proxy/ObitTask.py $(DESTDIR)$(PROXYDIR) cp ./Proxy/ObitTask.py $@ -$(DESTDIR)$(PYTHONDIR)/Proxy/ObitScriptP.py: Proxy/ObitScriptP.py +$(DESTDIR)$(PYTHONDIR)/Proxy/ObitScriptP.py: Proxy/ObitScriptP.py $(DESTDIR)$(PROXYDIR) cp ./Proxy/ObitScriptP.py $@ -$(DESTDIR)$(PYTHONDIR)/Proxy/Popsdat.py: Proxy/Popsdat.py +$(DESTDIR)$(PYTHONDIR)/Proxy/Popsdat.py: Proxy/Popsdat.py $(DESTDIR)$(PROXYDIR) cp ./Proxy/Popsdat.py $@ -$(DESTDIR)$(PYTHONDIR)/Proxy/Task.py: Proxy/Task.py +$(DESTDIR)$(PYTHONDIR)/Proxy/Task.py: Proxy/Task.py $(DESTDIR)$(PROXYDIR) cp ./Proxy/Task.py $@ # Wizardry $(DESTDIR)$(PYTHONDIR)/Wizardry/AIPSData.py: Wizardry/AIPSData.py $(DESTDIR)$(WIZDIR) cp ./Wizardry/AIPSData.py $@ -$(DESTDIR)$(PYTHONDIR)/Wizardry/__init__.py: Wizardry/__init__.py +$(DESTDIR)$(PYTHONDIR)/Wizardry/__init__.py: Wizardry/__init__.py $(DESTDIR)$(WIZDIR) cp ./Wizardry/__init__.py $@ clean: diff --git a/trunk/ObitSystem/ObitView/Makefile.in b/trunk/ObitSystem/ObitView/Makefile.in index 433277e..0276e5c 100644 --- a/trunk/ObitSystem/ObitView/Makefile.in +++ b/trunk/ObitSystem/ObitView/Makefile.in @@ -88,47 +88,47 @@ CLIENT_LIBS = lib/libObitView.a @MOTIF_LIBS@ @X_LIBS@ @OBIT_LIBS@ @GLIB_LIBS@ \ all: $(TARGETS) # update source/object directory -srcupdate: +srcupdate: src/*.c cd src; $(MAKE) # update library directory -libupdate: +libupdate: srcupdate cd lib; $(MAKE) RANLIB="$(RANLIB)" # Link ObitView -ObitView: src/*.c srcupdate ObitView.c +ObitView: libupdate ObitView.c $(CC) ObitView.c -o ObitView $(SERVER_CFLAGS) $(SERVER_CPPFLAGS) \ $(SERVER_LDFLAGS) $(SERVER_LIBS) $(CLIENT_LIBS) # Link ObitMess -ObitMess: src/*.c srcupdate ObitMess.c +ObitMess: libupdate ObitMess.c $(CC) ObitMess.c -o ObitMess $(SERVER_CFLAGS) $(SERVER_CPPFLAGS) \ $(SERVER_LDFLAGS) $(SERVER_LIBS) $(CLIENT_LIBS) # Link clientTest -clientTest: clientTest.c +clientTest: libupdate clientTest.c $(CC) clientTest.c -o clientTest -Iinclude $(CLIENT_CFLAGS) \ $(CLIENT_CPPFLAGS) $(CLIENT_LDFLAGS) \ $(CLIENT_LIBS) # Link clientFCopy -clientFCopy: clientFCopy.c +clientFCopy: libupdate clientFCopy.c $(CC) clientFCopy.c -o clientFCopy -Iinclude $(CLIENT_CFLAGS) \ $(CLIENT_CPPFLAGS) $(CLIENT_LDFLAGS) \ $(CLIENT_LIBS) # test run ObitView -testObitView: +testObitView: ObitView ObitView aaaSomeFile.fits # test run ObitMess -testObitMess: +testObitMess: ObitMess ObitMess & # Need to wait to start python testObitMess.py # Copy to where it should go -install: @exec_prefix@/bin +install: @exec_prefix@/bin ObitView ObitMess @install_sh@ -s ObitView @exec_prefix@/bin/ @install_sh@ -s ObitMess @exec_prefix@/bin/ diff --git a/trunk/ObitSystem/Obit/python/makesetup.py b/trunk/ObitSystem/Obit/python/makesetup.py index 77c4e28..c69e716 100644 --- a/trunk/ObitSystem/Obit/python/makesetup.py +++ b/trunk/ObitSystem/Obit/python/makesetup.py @@ -111,6 +111,6 @@ outfile.write(' [\''+packageName+'_wrap.c\'],'+os.l outfile.write(' extra_compile_args='+str(compileArgs)+','+os.linesep) outfile.write(' library_dirs='+str(libDirs)+','+os.linesep) outfile.write(' libraries='+str(libs)+','+os.linesep) -outfile.write(' runtime_library_dirs='+str(runtimeLibDirs)+')],'+os.linesep) -outfile.write(' include_dirs='+str(incDirs)+os.linesep) +outfile.write(' runtime_library_dirs='+str(runtimeLibDirs)+','+os.linesep) +outfile.write(' include_dirs='+str(incDirs)+')]'+os.linesep) outfile.write(')') diff --git a/trunk/ObitSystem/Obit/lib/Makefile b/trunk/ObitSystem/Obit/lib/Makefile index 9dcf2a1..d5812e2 100644 --- a/trunk/ObitSystem/Obit/lib/Makefile +++ b/trunk/ObitSystem/Obit/lib/Makefile @@ -40,7 +40,7 @@ SHTARGETS = libObit.dylib # list of object modules OBJECTS := $(wildcard *.o) -all: $(TARGETS) +all: $(TARGETS) $(SHTARGETS) share: $(SHTARGETS) # build static Obit library diff --git a/trunk/ObitSystem/Obit/python/Makefile.in b/trunk/ObitSystem/Obit/python/Makefile.in index e6dd7f4..d8fae4e 100644 --- a/trunk/ObitSystem/Obit/python/Makefile.in +++ b/trunk/ObitSystem/Obit/python/Makefile.in @@ -87,7 +87,7 @@ all: install $(TARGETS): setupdata.py $(MYLIBS) rm -rf build python2.7 makesetup.py - python2.7 setup.py build install --install-lib=. - python3 setup.py build install --install-lib=. + ARCHFLAGS="-arch x86_64" python2.7 setup.py build install --install-lib=. + ARCHFLAGS="-arch x86_64" python3 setup.py build install --install-lib=. install: $(TARGETS) mkdir -p build/site-packages <file_sep>class Libwww < Formula desc 'A highly modular, general-purpose client side Web API written in C' homepage 'http://www.w3.org/Library/' url 'http://www.w3.org/Library/Distribution/w3c-libwww-5.4.0.tgz' sha256 '64841cd99a41c84679cfbc777ebfbb78bdc2a499f7f6866ccf5cead391c867ef' depends_on 'pkg-config' => :build # MacPorts patches patch :p0 do url 'https://trac.macports.org/export/100399/trunk/dports/www/libwww/files/patch-configure.diff' end patch :p0 do url 'https://trac.macports.org/export/100399/trunk/dports/www/libwww/files/libwww-config.in.diff' end def install ENV.deparallelize system "./configure", "--disable-debug", "--disable-dependency-tracking", "--prefix=#{prefix}" system "make install" end end <file_sep>class Libair < Formula desc "Atmospheric inference for phase correction of ALMA data using WVR" homepage "http://www.mrao.cam.ac.uk/~bn204/alma/sweng/libairbuild.html" url "http://www.mrao.cam.ac.uk/~bn204/soft/libair-1.2.tar.bz2" sha256 "aa639c0be126bcc8f0c40af3fa53e40628cd659d873a9cd03d028b6cc9b314e7" depends_on "boost" depends_on "bnmin1" depends_on "pkg-config" => :build # Patch 1: Allow the use of SWIG 2.x for Python bindings # Patch 2: Fix C++ implicit instantiation error # Patch 3: Fix const problem with comparison operator patch :DATA def install ENV.deparallelize system "./configure", "--disable-debug", "--disable-dependency-tracking", "--prefix=#{prefix}", "--disable-pybind" system "make", "install" end test do system "#{bin}/wvrretrieve", "--help" end end __END__ diff --git a/pybind/configure b/pybind/configure index 828ea58..0d06394 100755 --- a/pybind/configure +++ b/pybind/configure @@ -15462,9 +15462,9 @@ $as_echo "$swig_version" >&6; } if test -z "$available_patch" ; then available_patch=0 fi - if test $available_major -ne $required_major \ - -o $available_minor -ne $required_minor \ - -o $available_patch -lt $required_patch ; then + if test $available_major -lt $required_major \ + -o $available_major -eq $required_major -a $available_minor -lt $required_minor \ + -o $available_major -eq $required_major -a $available_minor -eq $required_minor -a $available_patch -lt $required_patch ; then { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: SWIG version >= 1.3.31 is required. You have $swig_version. You should look at http://www.swig.org" >&5 $as_echo "$as_me: WARNING: SWIG version >= 1.3.31 is required. You have $swig_version. You should look at http://www.swig.org" >&2;} SWIG='echo "Error: SWIG version >= 1.3.31 is required. You have '"$swig_version"'. You should look at http://www.swig.org" ; false' diff --git a/src/model_water.hpp b/src/model_water.hpp index a8d1d3d..fc792c7 100644 --- a/src/model_water.hpp +++ b/src/model_water.hpp @@ -182,6 +182,9 @@ namespace LibAIR { } + // Declare explicit specialization before implicit instantiation below + template<> const double WaterModel<ICloudyWater>::tau_bump; + template<> inline void WaterModel<ICloudyWater>::dTdTau (std::vector<double> &res) const { diff --git a/src/radiometer_utils.cpp b/src/radiometer_utils.cpp index 9a995d0..6e83060 100644 --- a/src/radiometer_utils.cpp +++ b/src/radiometer_utils.cpp @@ -38,7 +38,7 @@ namespace LibAIR { return ( f_i == f_end ); } - bool operator< ( const RadioIter & other ) + bool operator< ( const RadioIter & other ) const { if (atend()) { <file_sep>class Sketch < Formula desc 'A 3D scene description translator for producing line drawings in TeX' homepage 'http://sketch4latex.sourceforge.net/' url 'http://sketch4latex.sourceforge.net/sketch-0.3.7.tgz' sha256 '12962ad5fe5a0f7c9fc6d84bd4d09b879bbf604975c839405f1613be657ba804' # Building the documentation requires access to GhostScript env :userpaths depends_on 'epstool' => :build def install system "make docs" bin.install "sketch" doc.install "Doc/sketch.pdf" mkdir_p "#{share}/sketch/examples" cp_r Dir['Data/*'], "#{share}/sketch/examples/" end test do mktemp do cp_r Dir["#{share}/sketch/examples/*.sk"], '.' Dir['*.sk'].each do |name| # Contains a pspicture baseline that causes unhappiness next if name == 'buggy.sk' quiet_system "#{bin}/sketch -T #{name} > #{name}.tex" quiet_system '#{bin}/latex', "#{name}.tex" quiet_system '#{bin}/dvips', "#{name}.dvi" quiet_system '#{bin}/ps2pdf', "#{name}.ps" # quiet_system 'open', "#{name}.pdf" ohai "#{name} OK" end end end end
786f530f5030a9eadc269ddf3bafe048a2287271
[ "Markdown", "Ruby" ]
25
Markdown
ska-sa/homebrew-tap
4997580dd0262c0dd29366e9ee51bd59ade540e0
1009383086fbba209c51a89714ad6f755e6b562b
refs/heads/main
<file_sep>##about me Name : <NAME> Registration number : 20BAI10182 I am <NAME>ya first year student at vit bhopal opted for cse with specialization in ai and ml .
010168a24947ed699cb0016697dcb50225e26992
[ "Markdown" ]
1
Markdown
nidhish2001/GeekWeek-Local
70c916f7312d1a870e580dc1a6df651e523c3445
d35e8b92c55e6cb29574a0125a58409a4aa1c631
refs/heads/master
<file_sep>package Enaleev.interpreter.util; import java.util.Iterator; public class LinkedListInt implements Iterable<Integer> { private static class Element { int value; Element next; Element previous; Element (int value, Element next, Element previous) { this.value = value; this.next = next; this.previous = previous; } Element (int value) { this(value, null, null); } } private Element firstElement; private Element lastElement; public LinkedListInt() { firstElement = null; lastElement = null; } // Добавить элемент в начало списка public void addFirst (int value) { if (firstElement == null) { firstElement = lastElement = new Element(value); } else { Element newElement = new Element(value, firstElement, null); firstElement.previous = newElement; firstElement = newElement; } } // Добавить элемент в конец списка public void addLast (int value) { if (lastElement == null) { firstElement = lastElement = new Element(value); } else { Element newElement = new Element(value, null, lastElement); lastElement.next = newElement; lastElement = newElement; } } // Вставить элемент по индексу public void add (int index, int value) { Element element; for (element = firstElement; element != null && index != 0; element = element.next, index--); if (element == firstElement) addFirst(value); else if (element == null && firstElement != null && index == 0) addLast(value); else { Element newElement = new Element(value, element, element.previous); element.previous.next = newElement; element.previous = newElement; } } // Посмотреть первый элемент списка public int peekFirst () { return firstElement.value; } // Посмотреть последний элемнт списка public int peekLast () { return lastElement.value; } // Посмотреть элемнт списка public int peek (int index) { Element element; for (element = firstElement; element != lastElement && index != 0; element = element.next, index--); try { return element.value; } finally { } } // Извлекает первый элемент из списка public int getFirst () { try { return firstElement.value; } finally { if (firstElement != lastElement) { firstElement = firstElement.next; firstElement.previous = null; } else firstElement = lastElement = null; } } // Извлекает последний элемент списка public int getLast () { try { return lastElement.value; } finally { if (lastElement != firstElement) { lastElement = lastElement.previous; lastElement.next = null; } else firstElement = lastElement = null; } } // Извлечь элемент по индексу public int get (int index) { Element element; for (element = firstElement; element != lastElement && index != 0; element = element.next, index--); try { return element.value; } finally { if (element == firstElement) getFirst(); else if (element == lastElement && index == 0) getLast(); else { element.previous.next = element.next; element.next.previous = element.previous; } } } // Вывод списка public void printList () { System.out.print("["); for (Element element = firstElement; element != null; element = element.next) { System.out.print(element.value); if (element.next != null) System.out.print(", "); else System.out.print("]"); } } public int contains (int value) { int index = 0; for (Element element = firstElement; element != null; element = element.next, index++) { if (element.value == value) return index; } return -1; } public int size () { int size = 0; for (Element element = firstElement; element != null; element = element.next, size++); return size; } // Реализация итератора @Override public Iterator iterator() { return new Iterator() { Element nextElement = firstElement; @Override public boolean hasNext() { return nextElement != null; } @Override public Integer next() { try { return nextElement.value; } finally { nextElement = nextElement.next; } } }; } } <file_sep>package Enaleev.interpreter.tokens; public enum LexType { NAME, //ключевые слова WHILE, IF, ELIF, ELSE, FOR, DO, PRINT, LIST, SET, //литералы NUM, BOOLEAN, //операторы OP_ASSIGN, SEMICOLON, L_BRACKET, R_BRACKET, L_BRACE, R_BRACE, OP_DOT, COMMA, //Арифметичекие операторы OP_MUL, OP_DIV, OP_ADD, OP_SUB, //Логические операторы OP_EQUAL, OP_MORE, OP_LESS, OP_MORE_EQUAL, OP_LESS_EQUAL, OP_NOT_EQUAL, //Служебная лексема перехода JMP_VALUE, JMP, FUNC, ERROR, //Лексема окончания кода END, } <file_sep>package Enaleev.interpreter.tree; public enum NodeType { Language, LanguageConst, AssignConst, WhileConst, DoWhileConst, IfConst, ElifConst, ElseConst, ForConst, PrintConst, Block, Expression, Member, Op, BracketMember, ListConst, MemberCont, CallFuncConst, SetConst, } <file_sep>package Enaleev.interpreter; import Enaleev.interpreter.tokens.LexType; import Enaleev.interpreter.tokens.Lexeme; import Enaleev.interpreter.util.HashSetInt; import Enaleev.interpreter.util.LinkedListInt; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.Set; import static Enaleev.interpreter.tokens.LexType.*; public class StackMachine { private ArrayList <Lexeme> RPN; private int index; private HashMap <String, Integer> variables; private HashMap <String, LinkedListInt> variablesList; private HashMap <String, HashSetInt> variablesSet; private LinkedList <Lexeme> stack; public StackMachine (ArrayList <Lexeme> RPN) { this.RPN = RPN; this.variables = new HashMap<>(); this.variablesList = new HashMap<>(); this.variablesSet = new HashMap<>(); this.stack = new LinkedList<>(); } public void run () { long time_analysis = System.nanoTime(); System.out.println("[StackMachine] Output:"); for (index = 0; index < RPN.size(); index++) { switch (RPN.get(index).getType()) { case OP_ADD: stack.addFirst(sum(stack.removeFirst(), stack.removeFirst())); break; case OP_SUB: stack.addFirst(sub(stack.removeFirst(), stack.removeFirst())); break; case OP_MUL: stack.addFirst(mul(stack.removeFirst(), stack.removeFirst())); break; case OP_DIV: stack.addFirst(div(stack.removeFirst(), stack.removeFirst())); break; case OP_ASSIGN: assign(stack.removeFirst(), stack.removeFirst()); break; case OP_EQUAL: stack.addFirst(equal(stack.removeFirst(), stack.removeFirst())); break; case OP_NOT_EQUAL: stack.addFirst(notEqual(stack.removeFirst(), stack.removeFirst())); break; case OP_MORE: stack.addFirst(more(stack.removeFirst(), stack.removeFirst())); break; case OP_LESS: stack.addFirst(less(stack.removeFirst(), stack.removeFirst())); break; case OP_MORE_EQUAL: stack.addFirst(moreEqual(stack.removeFirst(), stack.removeFirst())); break; case OP_LESS_EQUAL: stack.addFirst(lessEqual(stack.removeFirst(), stack.removeFirst())); break; case IF: ifConst(stack.removeFirst(), stack.removeFirst()); break; case ELIF: ifConst(stack.removeFirst(), stack.removeFirst()); break; case WHILE: whileConst(stack.removeFirst(), stack.removeFirst()); break; case JMP: index = Integer.parseInt(stack.removeFirst().get_value()) - 1; break; case DO: doWhileConst(stack.removeFirst(), stack.removeFirst()); break; case FOR: ForConst(stack.removeFirst(), stack.removeFirst()); break; case FUNC: funcConst(RPN.get(index)); break; case PRINT: printConst(stack.removeFirst()); break; case LIST: listConst(stack.removeFirst()); break; case SET: setConst(stack.removeFirst()); break; default: stack.addFirst(RPN.get(index)); } } System.out.println("[StackMachine] Time run: " + (System.nanoTime() - time_analysis) / 1_000_000.0 + "ms"); } private void setConst(Lexeme a) { if(variablesList.containsKey(a.get_value()) || variables.containsKey(a.get_value())) { //throw new Exeption (); } else { variablesSet.put(a.get_value(), new HashSetInt()); } } private void listConst(Lexeme a) { if(variablesList.containsKey(a.get_value()) || variables.containsKey(a.get_value())) { //throw new Exeption (); } else { variablesList.put(a.get_value(), new LinkedListInt()); } } private void funcConst(Lexeme lexeme) { Lexeme name = stack.removeFirst(); if (variablesList.containsKey(name.get_value())) { if (lexeme.get_value().equals("add")) { Lexeme value = stack.removeFirst(); Lexeme index = stack.removeFirst(); int index_value = index.getType() == NAME ? variables.get(index.get_value()) : Integer.parseInt(index.get_value()); int value_value = value.getType() == NAME ? variables.get(value.get_value()) : Integer.parseInt(value.get_value()); variablesList.get(name.get_value()).add(index_value, value_value); } else if (lexeme.get_value().equals("peek")) { Lexeme index = stack.removeFirst(); int index_value = index.getType() == NAME ? variables.get(index.get_value()) : Integer.parseInt(index.get_value()); stack.addFirst(new Lexeme(LexType.NUM, variablesList.get(name.get_value()).peek(index_value))); } else if (lexeme.get_value().equals("get")) { Lexeme index = stack.removeFirst(); int index_value = index.getType() == NAME ? variables.get(index.get_value()) : Integer.parseInt(index.get_value()); stack.addFirst(new Lexeme(LexType.NUM, variablesList.get(name.get_value()).get(index_value))); } else if (lexeme.get_value().equals("printList")) { variablesList.get(name.get_value()).printList(); System.out.println(); } } else if (variablesSet.containsKey(name.get_value())) { if (lexeme.get_value().equals("add")) { Lexeme value = stack.removeFirst(); int value_value = value.getType() == NAME ? variables.get(value.get_value()) : Integer.parseInt(value.get_value()); variablesSet.get(name.get_value()).add(value_value); } else if (lexeme.get_value().equals("contains")) { Lexeme index = stack.removeFirst(); int value_value = index.getType() == NAME ? variables.get(index.get_value()) : Integer.parseInt(index.get_value()); stack.addFirst(new Lexeme(BOOLEAN, variablesSet.get(name.get_value()).contains(value_value) == -1 ? Boolean.toString(false) : Boolean.toString(true))); } else if (lexeme.get_value().equals("delete")) { Lexeme index = stack.removeFirst(); int value_value = index.getType() == NAME ? variables.get(index.get_value()) : Integer.parseInt(index.get_value()); variablesSet.get(name.get_value()).delete(value_value); } else if (lexeme.get_value().equals("printSet")) { variablesSet.get(name.get_value()).print(); System.out.println(); } } } private void printConst(Lexeme a) { int a_value = a.getType() == NAME ? variables.get(a.get_value()) : Integer.parseInt(a.get_value()); System.out.println(a_value); } private void ForConst(Lexeme jmp, Lexeme bool) { int jmp_value = Integer.parseInt(jmp.get_value()); boolean bool_value = Boolean.parseBoolean(bool.get_value()); if (!bool_value) index = jmp_value - 1; } private void doWhileConst(Lexeme jmp, Lexeme bool) { int jmp_value = Integer.parseInt(jmp.get_value()); boolean bool_value = Boolean.parseBoolean(bool.get_value()); if (bool_value) index = jmp_value - 1; } private void whileConst(Lexeme jmp, Lexeme bool) { int jmp_value = Integer.parseInt(jmp.get_value()); boolean bool_value = Boolean.parseBoolean(bool.get_value()); if (!bool_value) index = jmp_value - 1; } private Lexeme notEqual(Lexeme a, Lexeme b) { int a_value = a.getType() == NAME ? variables.get(a.get_value()) : Integer.parseInt(a.get_value()); int b_value = b.getType() == NAME ? variables.get(b.get_value()) : Integer.parseInt(b.get_value()); return new Lexeme(BOOLEAN, Boolean.toString(b_value != a_value)); } private Lexeme lessEqual(Lexeme a, Lexeme b) { int a_value = a.getType() == NAME ? variables.get(a.get_value()) : Integer.parseInt(a.get_value()); int b_value = b.getType() == NAME ? variables.get(b.get_value()) : Integer.parseInt(b.get_value()); return new Lexeme(BOOLEAN, Boolean.toString(b_value <= a_value)); } private Lexeme moreEqual(Lexeme a, Lexeme b) { int a_value = a.getType() == NAME ? variables.get(a.get_value()) : Integer.parseInt(a.get_value()); int b_value = b.getType() == NAME ? variables.get(b.get_value()) : Integer.parseInt(b.get_value()); return new Lexeme(BOOLEAN, Boolean.toString(b_value >= a_value)); } private Lexeme less(Lexeme a, Lexeme b) { int a_value = a.getType() == NAME ? variables.get(a.get_value()) : Integer.parseInt(a.get_value()); int b_value = b.getType() == NAME ? variables.get(b.get_value()) : Integer.parseInt(b.get_value()); return new Lexeme(BOOLEAN, Boolean.toString(b_value < a_value)); } private Lexeme more(Lexeme a, Lexeme b) { int a_value = a.getType() == NAME ? variables.get(a.get_value()) : Integer.parseInt(a.get_value()); int b_value = b.getType() == NAME ? variables.get(b.get_value()) : Integer.parseInt(b.get_value()); return new Lexeme(BOOLEAN, Boolean.toString(b_value > a_value)); } private void ifConst(Lexeme jmp, Lexeme bool) { int jmp_value = Integer.parseInt(jmp.get_value()); boolean bool_value = Boolean.parseBoolean(bool.get_value()); if (!bool_value) index = jmp_value - 1; } private Lexeme equal(Lexeme a, Lexeme b) { int a_value = a.getType() == NAME ? variables.get(a.get_value()) : Integer.parseInt(a.get_value()); int b_value = b.getType() == NAME ? variables.get(b.get_value()) : Integer.parseInt(b.get_value()); return new Lexeme(BOOLEAN, Boolean.toString(b_value == a_value)); } private Lexeme div(Lexeme a, Lexeme b) { int a_value = a.getType() == NAME ? variables.get(a.get_value()) : Integer.parseInt(a.get_value()); int b_value = b.getType() == NAME ? variables.get(b.get_value()) : Integer.parseInt(b.get_value()); return new Lexeme(NUM, Integer.toString(b_value / a_value)); } private Lexeme mul(Lexeme a, Lexeme b) { int a_value = a.getType() == NAME ? variables.get(a.get_value()) : Integer.parseInt(a.get_value()); int b_value = b.getType() == NAME ? variables.get(b.get_value()) : Integer.parseInt(b.get_value()); return new Lexeme(NUM, Integer.toString(b_value * a_value)); } private Lexeme sub(Lexeme a, Lexeme b) { int a_value = a.getType() == NAME ? variables.get(a.get_value()) : Integer.parseInt(a.get_value()); int b_value = b.getType() == NAME ? variables.get(b.get_value()) : Integer.parseInt(b.get_value()); return new Lexeme(NUM, Integer.toString(b_value - a_value)); } private void assign(Lexeme a, Lexeme b) { variables.put(b.get_value(), Integer.parseInt(a.get_value())); } private Lexeme sum(Lexeme a, Lexeme b) { int a_value = a.getType() == NAME ? variables.get(a.get_value()) : Integer.parseInt(a.get_value()); int b_value = b.getType() == NAME ? variables.get(b.get_value()) : Integer.parseInt(b.get_value()); return new Lexeme(NUM, Integer.toString(a_value+b_value)); } private boolean isOp(Lexeme lexeme) { LexType type = lexeme.getType(); return type == OP_ADD || type == OP_SUB || type == OP_DIV || type == OP_MUL || type == OP_EQUAL || type == OP_LESS || type == OP_LESS_EQUAL || type == OP_MORE || type == OP_MORE_EQUAL || type == OP_NOT_EQUAL || type == OP_ASSIGN; } public void print () { System.out.println("[StackMachine] Variable values:"); Set <String> keys = variables.keySet(); for (String name: keys) { System.out.println(name + " " + variables.get(name)); } } } <file_sep>package Enaleev.interpreter.tree; import Enaleev.interpreter.tokens.Lexeme; import java.util.ArrayList; import java.util.List; public class TreeNode { private NodeType type; private List <TreeNode> nodes; private List <Lexeme> leafs; public TreeNode(NodeType type) { this.type = type; this.leafs = new ArrayList<>(); this.nodes = new ArrayList<>(); } public TreeNode(NodeType type, List <TreeNode> nodes, List <Lexeme> leafs) { this.type = type; this.leafs = leafs; this.nodes = nodes; } public void addLeaf (Lexeme leaf) { leafs.add(leaf); } public void addNode (TreeNode node) { nodes.add(node); } public void print () { this.printNext("", "", "", true); } private void printNext (String format, String format2, String format3, boolean last) { if (last) System.out.printf(format2); else System.out.printf(format3); System.out.println("╥" + type); for (int i = 0; i < leafs.size(); i++) { if (i == leafs.size() - 1 && this.nodes.size()==0) { System.out.printf(format + "╙────"); System.out.println(leafs.get(i).getType() + (leafs.get(i).get_value() == null ? "" :(" (" + leafs.get(i).get_value() + ")"))); } else { System.out.printf(format + "╟────"); System.out.println(leafs.get(i).getType() + (leafs.get(i).get_value() == null ? "" :(" (" + leafs.get(i).get_value() + ")"))); } } for (int i = 0; i < nodes.size(); i++) { if (i == nodes.size()-1) nodes.get(i).printNext(format + " ", format + "╟────", format + "╙────", false); else nodes.get(i).printNext(format + "║ ", format + "╟────", format + "╙────", true); } } public NodeType getType() { return type; } public List <TreeNode> getNodes () { return nodes; } public List <Lexeme> getLeafs () { return leafs; } } <file_sep>package Enaleev.interpreter.tokens; public class Lexeme { private LexType type; private String value; public Lexeme(LexType type, String value) { this.type = type; this.value = value; } public Lexeme(LexType type, int value) { this.type = type; this.value = Integer.toString(value); } public Lexeme(LexType type) { this(type, null); } public LexType getType() { return type; } public String get_value () { return value; } public void set_value (String s) { this.value = s; } public void print () { System.out.printf("%-20s%-20s", type, value == null ? " " : value); } public void println () { System.out.printf("%-20s%-20s\n", type, value == null ? " " : value); } } <file_sep>package Enaleev.interpreter; import Enaleev.interpreter.tokens.Lexeme; import Enaleev.interpreter.tree.TreeNode; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import static Enaleev.interpreter.tokens.LexType.*; import static Enaleev.interpreter.tree.NodeType.*; public class TranslatorRPN { private TreeNode AST; private LinkedList <Lexeme> texas; private ArrayList <Lexeme> RPN; private HashSet<String> variables; private HashSet<String> variablesList; private HashSet<String> variablesSet; public TranslatorRPN (TreeNode AST) { this.AST = AST; this.texas = new LinkedList<>(); this.RPN = new ArrayList<>(); this.variables = new HashSet<>(); this.variablesList = new HashSet<>(); this.variablesSet = new HashSet<>(); } public void translate () { long time_analysis = System.nanoTime(); try { for (TreeNode node : AST.getNodes()) { languageConst(node); } } catch (Exception e) { e.printStackTrace(); } System.out.println("[TranslatorRPN] time translate: " + (System.nanoTime() - time_analysis) / 1_000_000.0 + "ms"); } private void languageConst(TreeNode node) throws Exception { TreeNode nodeConst = node.getNodes().get(0); if (nodeConst.getType() == AssignConst) { assignConst(nodeConst); } else if (nodeConst.getType() == IfConst) { ifConst(nodeConst); } else if (nodeConst.getType() == WhileConst) { whileConst(nodeConst); } else if (nodeConst.getType() == DoWhileConst) { doWhileConst(nodeConst); } else if (nodeConst.getType() == ForConst) { forConst(nodeConst); } else if (nodeConst.getType() == PrintConst) { printConst(nodeConst); } else if (nodeConst.getType() == ListConst) { listConst(nodeConst); } else if (nodeConst.getType() == CallFuncConst) { callFuncConst(nodeConst); } else if (nodeConst.getType() == SetConst) { setConst(nodeConst); } } private void setConst(TreeNode nodeConst) { addOprand(nodeConst.getLeafs().get(1)); addOprand(nodeConst.getLeafs().get(0)); variables.add(nodeConst.getLeafs().get(1).get_value()); variablesSet.add(nodeConst.getLeafs().get(1).get_value()); } private void callFuncConst(TreeNode node) throws Exception { if (!variables.contains(node.getLeafs().get(0).get_value()) && (!variablesList.contains(node.getLeafs().get(0).get_value()) || !variablesSet.contains(node.getLeafs().get(0).get_value()))) { throw new Exception (); } if (variablesList.contains(node.getLeafs().get(0).get_value())) { if (node.getLeafs().get(2).get_value().equals("add")) { if (node.getNodes().size() == 2) { expression(node.getNodes().get(0)); expression(node.getNodes().get(1)); } else { throw new Exception(); } } else if (node.getLeafs().get(2).get_value().equals("printList")) { if (node.getNodes().size() == 0) { } else { throw new Exception(); } } else { throw new Exception(); } } else if (variablesSet.contains(node.getLeafs().get(0).get_value())) { if (node.getLeafs().get(2).get_value().equals("add")) { if (node.getNodes().size() == 1) { expression(node.getNodes().get(0)); } else { throw new Exception(); } } else if (node.getLeafs().get(2).get_value().equals("delete")) { if (node.getNodes().size() == 1) { expression(node.getNodes().get(0)); } else { throw new Exception(); } } else if (node.getLeafs().get(2).get_value().equals("printSet")) { if (node.getNodes().size() == 0) { } else { throw new Exception(); } } else { throw new Exception(); } } addOprand(node.getLeafs().get(0)); addOprand(node.getLeafs().get(2)); } private void listConst(TreeNode nodeConst) throws Exception { addOprand(nodeConst.getLeafs().get(1)); addOprand(nodeConst.getLeafs().get(0)); variables.add(nodeConst.getLeafs().get(1).get_value()); variablesList.add(nodeConst.getLeafs().get(1).get_value()); } private void printConst(TreeNode nodeConst) throws Exception { expression(nodeConst.getNodes().get(0)); flushTexas(); addOprand(nodeConst.getLeafs().get(0)); } private void forConst(TreeNode nodeConst) throws Exception { assignConst(nodeConst.getNodes().get(0)); int start = RPN.size(); expression(nodeConst.getNodes().get(1)); flushTexas(); Lexeme point = new Lexeme(JMP_VALUE); addOprand(point); addOprand(nodeConst.getLeafs().get(0)); block(nodeConst.getNodes().get(3)); assignConst(nodeConst.getNodes().get(2)); Lexeme endPoint = new Lexeme(JMP_VALUE); addOprand(endPoint); addOprand(new Lexeme (JMP)); point.set_value(Integer.toString(RPN.size())); endPoint.set_value(Integer.toString(start)); } private void doWhileConst(TreeNode nodeConst) throws Exception { int start = RPN.size(); block(nodeConst.getNodes().get(0)); expression(nodeConst.getNodes().get(1)); flushTexas(); Lexeme point = new Lexeme(JMP_VALUE); addOprand(point); addOprand(nodeConst.getLeafs().get(0)); point.set_value(Integer.toString(start)); } private void whileConst(TreeNode nodeConst) throws Exception { int start = RPN.size(); expression(nodeConst.getNodes().get(0)); flushTexas(); Lexeme point = new Lexeme(JMP_VALUE); addOprand(point); addOprand(nodeConst.getLeafs().get(0)); block(nodeConst.getNodes().get(1)); Lexeme endPoint = new Lexeme(JMP_VALUE); addOprand(endPoint); addOprand(new Lexeme (JMP)); point.set_value(Integer.toString(RPN.size())); endPoint.set_value(Integer.toString(start)); } private void ifConst(TreeNode nodeConst) throws Exception { expression(nodeConst.getNodes().get(0)); flushTexas(); Lexeme point = new Lexeme(JMP_VALUE); addOprand(point); addOprand(nodeConst.getLeafs().get(0)); block(nodeConst.getNodes().get(1)); Lexeme endPoint = new Lexeme(JMP_VALUE); addOprand(endPoint); addOprand(new Lexeme (JMP)); point.set_value(Integer.toString(RPN.size())); for (int i = 2; i < nodeConst.getNodes().size(); i++) { if (nodeConst.getNodes().get(i).getType() == ElifConst) { elifConst(nodeConst.getNodes().get(i), endPoint); } else if (nodeConst.getNodes().get(i).getType() == ElseConst) { elseConst(nodeConst.getNodes().get(i)); } } endPoint.set_value(Integer.toString(RPN.size())); } private void elifConst(TreeNode nodeConst, Lexeme endPoint) throws Exception { expression(nodeConst.getNodes().get(0)); flushTexas(); Lexeme point = new Lexeme(JMP_VALUE); addOprand(point); addOprand(nodeConst.getLeafs().get(0)); block(nodeConst.getNodes().get(1)); addOprand(endPoint); addOprand(new Lexeme (JMP)); point.set_value(Integer.toString(RPN.size())); } private void elseConst(TreeNode nodeConst) throws Exception { block(nodeConst.getNodes().get(0)); } private void block(TreeNode topNode) throws Exception { for(TreeNode node: topNode.getNodes()) { languageConst(node); } } private void assignConst(TreeNode nodeConst) throws Exception { addOprand(nodeConst.getLeafs().get(0)); addOperator(nodeConst.getLeafs().get(1)); expression(nodeConst.getNodes().get(0)); flushTexas(); variables.add(nodeConst.getLeafs().get(0).get_value()); } private void expression(TreeNode topNode) throws Exception { List<TreeNode> nextNodes = topNode.getNodes(); if (nextNodes.get(0).getType() == Member) { member(nextNodes.get(0)); } else if (nextNodes.get(0).getType() == BracketMember) { bracketMember(nextNodes.get(0)); } else if (nextNodes.get(0).getType() == MemberCont) { memberCont(nextNodes.get(0)); } if (nextNodes.size()>1) { op(nextNodes.get(1)); expression(nextNodes.get(2)); } } private void memberCont(TreeNode node) throws Exception { if (!variables.contains(node.getLeafs().get(0).get_value()) && (!variablesList.contains(node.getLeafs().get(0).get_value()) || !variablesSet.contains(node.getLeafs().get(0).get_value()))) { throw new Exception (); } if (variablesList.contains(node.getLeafs().get(0).get_value())) { if (node.getLeafs().get(2).get_value().equals("get")) { if (node.getNodes().size() == 1) { expression(node.getNodes().get(0)); } else { throw new Exception(); } } else if (node.getLeafs().get(2).get_value().equals("peek")) { if (node.getNodes().size() == 1) { expression(node.getNodes().get(0)); } else { throw new Exception(); } } else { throw new Exception(); } } else if (variablesSet.contains(node.getLeafs().get(0).get_value())) { if (node.getLeafs().get(2).get_value().equals("contains")) { if (node.getNodes().size() == 1) { expression(node.getNodes().get(0)); } else { throw new Exception(); } } else { throw new Exception(); } } addOprand(node.getLeafs().get(0)); addOprand(node.getLeafs().get(2)); } private void bracketMember(TreeNode node) throws Exception { addOperator(node.getLeafs().get(0)); expression(node.getNodes().get(0)); addOperator(node.getLeafs().get(1)); } private void op(TreeNode node) { addOperator(node.getLeafs().get(0)); } private void member(TreeNode node) throws Exception { if (node.getLeafs().get(0).getType() == NAME && !variables.contains(node.getLeafs().get(0).get_value()) && (variablesList.contains(node.getLeafs().get(0).get_value()) || variablesSet.contains(node.getLeafs().get(0).get_value()))) { throw new Exception (); } addOprand(node.getLeafs().get(0)); } private int opPriority (Lexeme op) { int priority; if (op.getType() == OP_ASSIGN) priority = 0; else if (op.getType() == OP_LESS) priority = 5; else if (op.getType() == OP_MORE) priority = 5; else if (op.getType() == OP_LESS_EQUAL) priority = 5; else if (op.getType() == OP_MORE_EQUAL) priority = 5; else if (op.getType() == OP_NOT_EQUAL) priority = 5; else if (op.getType() == OP_EQUAL) priority = 5; else if (op.getType() == OP_SUB) priority = 9; else if (op.getType() == OP_MUL) priority = 10; else if (op.getType() == OP_DIV) priority = 10; else if (op.getType() == OP_ADD) priority = 9; else priority = 0; return priority; } private void addOprand (Lexeme lexeme) { RPN.add(lexeme); } private void addOperator (Lexeme lexeme) { if (lexeme.getType() == L_BRACKET) { texas.addFirst(lexeme); return; } if (lexeme.getType() == R_BRACKET) { while (texas.peek().getType() != L_BRACKET) { RPN.add(texas.removeFirst()); } texas.removeFirst(); return; } while (true) { if (texas.peek()!=null && opPriority(texas.peek()) > opPriority(lexeme)) RPN.add(texas.removeFirst()); else { texas.addFirst(lexeme); return; } } } private void flushTexas () { int size = texas.size(); for (int i = 0; i < size; i++) { RPN.add(texas.removeFirst()); } } public void print () { System.out.println("[TranslatorRPN] reverse polish notation: "); System.out.printf("%-4s%-20s%-20s\n","№", "Name lexeme", "Value"); int i = 0; for (Lexeme lexeme: RPN) { System.out.printf("%-4s", i++); lexeme.println(); } } public ArrayList<Lexeme> getRPN() { return RPN; } } <file_sep>package Enaleev.interpreter; import Enaleev.interpreter.tokens.LexType; import Enaleev.interpreter.tokens.Lexeme; import Enaleev.interpreter.tree.TreeNode; import java.util.List; import static Enaleev.interpreter.tokens.LexType.*; import static Enaleev.interpreter.tree.NodeType.*; public class Parser { private List<Lexeme> lexemes; private int position; TreeNode AST; public Parser (List <Lexeme> lexemes) { this.lexemes = lexemes; this.position = 0; } public void analysis () { long time_analysis = System.nanoTime(); AST = new TreeNode(Language); while (currentLexeme() != END) { try { languageConst(AST); } catch (Exception e) { //System.out.println("Синтаксическая ошибка: " + position + currentLexeme()); e.printStackTrace(); break; } } System.out.println("[Parser] time analysis: " + (System.nanoTime() - time_analysis) / 1_000_000.0 + "ms"); } private void languageConst(TreeNode astTop) throws Exception { TreeNode astNext = new TreeNode(LanguageConst); astTop.addNode(astNext); if (currentLexeme() == NAME) { if (nextLexeme() == OP_DOT) { callFuncConst(astNext); } else { assignConst(astNext); } } else if (currentLexeme() == WHILE) { whileConst(astNext); } else if (currentLexeme() == IF) { ifConst(astNext); } else if (currentLexeme() == DO) { doWhileConst(astNext); } else if (currentLexeme() == FOR) { forConst(astNext); } else if (currentLexeme() == PRINT) { printConst(astNext); } else if (currentLexeme() == LIST) { listConst(astNext); } else if (currentLexeme() == SET) { setConst(astNext); }else { throw new Exception(); } } private void callFuncConst(TreeNode astTop) throws Exception { TreeNode astNext = new TreeNode(CallFuncConst); astTop.addNode(astNext); if (currentLexeme() == NAME) { astNext.addLeaf(LexCheck(NAME)); astNext.addLeaf(LexCheck(OP_DOT)); astNext.addLeaf(new Lexeme (FUNC, LexCheck(NAME).get_value())); astNext.addLeaf(LexCheck(L_BRACKET)); if (currentLexeme() != R_BRACKET) { expression(astNext); while (currentLexeme() == COMMA) { astNext.addLeaf(LexCheck(COMMA)); expression(astNext); } } astNext.addLeaf(LexCheck(R_BRACKET)); astNext.addLeaf(LexCheck(SEMICOLON)); } else throw new Exception(); } private void listConst(TreeNode astTop) throws Exception { TreeNode astNext = new TreeNode(ListConst); astTop.addNode(astNext); astNext.addLeaf(LexCheck(LIST)); astNext.addLeaf(LexCheck(NAME)); astNext.addLeaf(LexCheck(SEMICOLON)); } private void setConst(TreeNode astTop) throws Exception { TreeNode astNext = new TreeNode(SetConst); astTop.addNode(astNext); astNext.addLeaf(LexCheck(SET)); astNext.addLeaf(LexCheck(NAME)); astNext.addLeaf(LexCheck(SEMICOLON)); } private void printConst(TreeNode astTop) throws Exception { TreeNode astNext = new TreeNode(PrintConst); astTop.addNode(astNext); astNext.addLeaf(LexCheck(PRINT)); expression(astNext); astNext.addLeaf(LexCheck(SEMICOLON)); } private void doWhileConst(TreeNode astTop) throws Exception { TreeNode astNext = new TreeNode(DoWhileConst); astTop.addNode(astNext); astNext.addLeaf(LexCheck(DO)); block(astNext); astNext.addLeaf(LexCheck(WHILE)); astNext.addLeaf(LexCheck(L_BRACKET)); expression(astNext); astNext.addLeaf(LexCheck(R_BRACKET)); astNext.addLeaf(LexCheck(SEMICOLON)); } private void forConst(TreeNode astTop) throws Exception { TreeNode astNext = new TreeNode(ForConst); astTop.addNode(astNext); astNext.addLeaf(LexCheck(FOR)); astNext.addLeaf(LexCheck(L_BRACKET)); assignConstFor(astNext); astNext.addLeaf(LexCheck(SEMICOLON)); expression(astNext); astNext.addLeaf(LexCheck(SEMICOLON)); assignConstFor(astNext); astNext.addLeaf(LexCheck(R_BRACKET)); block(astNext); } private void assignConstFor(TreeNode astTop) throws Exception { TreeNode astNext = new TreeNode(AssignConst); astTop.addNode(astNext); astNext.addLeaf(LexCheck(NAME)); astNext.addLeaf(LexCheck(OP_ASSIGN)); expression(astNext); } private void ifConst(TreeNode astTop) throws Exception { TreeNode astNext = new TreeNode(IfConst); astTop.addNode(astNext); astNext.addLeaf(LexCheck(IF)); astNext.addLeaf(LexCheck(L_BRACKET)); expression(astNext); astNext.addLeaf(LexCheck(R_BRACKET)); block(astNext); while (currentLexeme() == ELIF) elifConst(astNext); if (currentLexeme() == ELSE) elseConst(astNext); } private void elifConst(TreeNode astTop) throws Exception { TreeNode astNext = new TreeNode(ElifConst); astTop.addNode(astNext); astNext.addLeaf(LexCheck(ELIF)); astNext.addLeaf(LexCheck(L_BRACKET)); expression(astNext); astNext.addLeaf(LexCheck(R_BRACKET)); block(astNext); } private void elseConst(TreeNode astTop) throws Exception { TreeNode astNext = new TreeNode(ElseConst); astTop.addNode(astNext); astNext.addLeaf(LexCheck(ELSE)); block(astNext); } private void whileConst(TreeNode astTop) throws Exception { TreeNode astNext = new TreeNode(WhileConst); astTop.addNode(astNext); astNext.addLeaf(LexCheck(WHILE)); astNext.addLeaf(LexCheck(L_BRACKET)); expression(astNext); astNext.addLeaf(LexCheck(R_BRACKET)); block(astNext); } private void block(TreeNode astTop) throws Exception { TreeNode astNext = new TreeNode(Block); astTop.addNode(astNext); if (currentLexeme() == L_BRACE) { astNext.addLeaf(LexCheck(L_BRACE)); while (currentLexeme() != R_BRACE) languageConst(astNext); astNext.addLeaf(LexCheck(R_BRACE)); } else { languageConst(astNext); } } private void assignConst(TreeNode astTop) throws Exception { TreeNode astNext = new TreeNode(AssignConst); astTop.addNode(astNext); astNext.addLeaf(LexCheck(NAME)); astNext.addLeaf(LexCheck(OP_ASSIGN)); expression(astNext); astNext.addLeaf(LexCheck(SEMICOLON)); } private boolean isOp (LexType type) { return type == OP_ADD || type == OP_SUB || type == OP_DIV || type == OP_MUL || type == OP_EQUAL || type == OP_LESS || type == OP_LESS_EQUAL || type == OP_MORE || type == OP_MORE_EQUAL || type == OP_NOT_EQUAL; } private void expression(TreeNode astTop) throws Exception { TreeNode astNext = new TreeNode(Expression); astTop.addNode(astNext); if (currentLexeme() == NUM || currentLexeme() == NAME) { if (currentLexeme() == NAME && nextLexeme() == OP_DOT) { memberCont(astNext); } else { member(astNext); } } else if (currentLexeme() == L_BRACKET) { memberBracket(astNext); } else { throw new Exception(); } while (isOp(currentLexeme())) { op(astNext); expression(astNext); } } private void memberCont(TreeNode astTop) throws Exception { TreeNode astNext = new TreeNode(MemberCont); astTop.addNode(astNext); if (currentLexeme() == NAME) { astNext.addLeaf(LexCheck(NAME)); astNext.addLeaf(LexCheck(OP_DOT)); astNext.addLeaf(new Lexeme (FUNC, LexCheck(NAME).get_value())); astNext.addLeaf(LexCheck(L_BRACKET)); if (currentLexeme() != R_BRACKET) { expression(astNext); while (currentLexeme() == COMMA) { astNext.addLeaf(LexCheck(COMMA)); expression(astNext); } } astNext.addLeaf(LexCheck(R_BRACKET)); } else throw new Exception(); } private void op(TreeNode astTop) throws Exception { TreeNode astNext = new TreeNode(Op); astTop.addNode(astNext); if (isOp(currentLexeme())) astNext.addLeaf(getNextLexeme()); else throw new Exception(); } private void memberBracket(TreeNode astTop) throws Exception { TreeNode astNext = new TreeNode(BracketMember); astTop.addNode(astNext); astNext.addLeaf(LexCheck(L_BRACKET)); expression(astNext); astNext.addLeaf(LexCheck(R_BRACKET)); } private void member(TreeNode astTop) throws Exception { TreeNode astNext = new TreeNode(Member); astTop.addNode(astNext); if (currentLexeme() == NUM || currentLexeme() == NAME) astNext.addLeaf(getNextLexeme()); else throw new Exception(); } private Lexeme LexCheck(LexType type) throws Exception { if (currentLexeme() != type) throw new Exception(); else return lexemes.get(position++); } private Lexeme getNextLexeme () { return lexemes.get(position++); } private LexType nextLexeme () { return lexemes.get(position + 1).getType(); } private LexType currentLexeme () { return lexemes.get(position).getType(); } public TreeNode getTree() { return AST; } }
1b95ce920b53e4bcc2e65e6a6c1668e80e1f9642
[ "Java" ]
8
Java
GawainOrkney/EnaleevSPO
e5b73242eeff44fb289ed1511dda065b39da9026
4911c534389233378a6ea0ddd0f057c53eedff14
refs/heads/main
<repo_name>hakoemmy/shell-script-to-monitor-memory-usage-on-linux<file_sep>/check-vps-memory-usage.sh #!/bin/bash ramusage=$(free | awk '/Mem/{printf("RAM Usage: %.2f\n"), $3/$2*100}'| awk '{print $3}' | cut -d. -f1) if [ $ramusage -ge 45 ]; then SUBJECT="ATTENTION: Your VPS Memory Utilization is High on $(hostname) at $(date)" MESSAGE="/tmp/Mail.out" TO="<EMAIL>" echo "VPS Memory Current Usage is: $ramusage%" >> $MESSAGE echo "" >> $MESSAGE echo "------------------------------------------------------------------" >> $MESSAGE echo "Top Memory Consuming Processes Using top command" >> $MESSAGE echo "------------------------------------------------------------------" >> $MESSAGE echo "$(top -b -o +%MEM | head -n 20)" >> $MESSAGE echo "" >> $MESSAGE echo "------------------------------------------------------------------" >> $MESSAGE echo "Top Memory Consuming Processes Using ps command" >> $MESSAGE echo "------------------------------------------------------------------" >> $MESSAGE echo "$(ps -eo pid,ppid,%mem,%cpu,cmd --sort=-%mem | head)" >> $MESSAGE mail -s "$SUBJECT" "$TO" < $MESSAGE rm /tmp/Mail.out fi<file_sep>/README.md # shell-script-to-monitor-memory-usage-on-linux > Monitor CPU utilization, Memory utilization, swap utilization and disk space utilization when they reach the threshold, send an email to the devOps engineer # HOW TO SET IT UP? - Run ```sudo nano check-vps-memory-usage.sh``` in terminal and paste in the shell script code - Run ```chmod 755 check-vps-memory-usage.sh ``` to give a full permissions to the shell script - To execute it, run ``` ./check-vps-memory-usage.sh``` in terminal. When the threshold that you set in code has reached, you should get an email. For my side I did set 45% of the usage, you can tweak it to your needs. - Instead of doing this manually, we can automate this via crontab: Run ``` crontab -e``` and then put in this line to run cronjob every five minutes: ``` */5 * * * * /bin/bash check-vps-memory-usage.sh```
22420af3e0c53d51da850dcff0823cb2d3cb269d
[ "Markdown", "Shell" ]
2
Markdown
hakoemmy/shell-script-to-monitor-memory-usage-on-linux
03bb710b5275f888fb9ff5f6995191733731f33f
9470410cf84b152a392465610624c0d156f5ae4e
refs/heads/master
<repo_name>dragonmaster-alpha/Decetraland-Market-Alpha<file_sep>/back-end/controllers/card.controller.js import Card from '../models/card.model' const fs = require('fs'); const path = require('path'); const multer = require("multer"); const multiparty = require('multiparty'); const cardsSerializer = data => ({ id: data.id, // user_id: data.user_id, card_name: data.card_name, card_desc: data.card_desc, card_price: data.card_price, img_url: data.img_url, status: data.status, owner: data.owner, register_date: data.register_date }); // Retrieve all data exports.findAll = (req, res) => { Card.find() .then(async data => { const cards = await Promise.all(data.map(cardsSerializer)); res.send(cards); }).catch(err => { res.status(500).send({ message: err.message || "Some error occurred while retrieving scenes." }); }); }; // Retrieve all data exports.findAllByUserID = (req, res) => { console.log(req.headers); Card.find({owner: req.user.id}) .then(async data => { const cards = await Promise.all(data.map(cardsSerializer)); console.log(cards); res.send(cards); }).catch(err => { res.status(500).send({ message: err.message || "Some error occurred while retrieving scenes." }); }); }; // Retrieve data with pagination exports.findPagination = async (req, res) => { const page = req.query.page; const limit = req.query.limit; let query = {} const paginated = await Card.paginate( query, { page, limit, lean: true, sort: { updatedAt: "desc" } } ) const { docs } = paginated; const cards = await Promise.all(docs.map(cardsSerializer)); delete paginated["docs"]; const meta = paginated res.json({ meta, cards }); }; exports.getReceivedBid = (req, res) => { console.log('asfdher'); if (!req.user.id) { return res.status(400).send({ message: "User should log in first." }); } Card.aggregate([ // { // $project: { // 'id': card_details.id, // // user_id: data.user_id, // 'card_name': card_details.card_name, // 'card_desc': card_details.card_desc, // 'card_price': card_details.card_price, // 'img_url': card_details.img_url, // 'status': card_details.status, // 'owner': card_details.owner, // 'register_date': card_details.register_date // } // }, { $match: { owner: req.user.id } }, { $addFields: { cardID : {$toString : '$_id'} } }, { $lookup: { from: 'bid', localField: 'cardID', foreignField: 'card_id', as: 'bid_details' } } ]).then(async data => { console.log(data); const cards = await Promise.all(data.map(cardsSerializer)); // const user = bidsSerializer(data) res.send(cards); }).catch(err => { res.status(500).send({ message: err.message || "Some error occurred while retrieving the placed bids." }); }); }; exports.findOne = (req, res) => { Card.findById(req.params.id) .then(data => { if(!data) { return res.status(404).send({ message: "card not found with id " + req.params.id }); } const card = cardsSerializer(data) res.send(card); }).catch(err => { if(err.kind === 'ObjectId') { return res.status(404).send({ message: "Card not found with id " + req.params.id }); } return res.status(500).send({ message: "Error retrieving card with id " + req.params.id }); }); }; exports.create = (req, res) => { let form = new multiparty.Form(); var cardName, cardPrice, cardDesc, userId, file; const storage = multer.diskStorage({ destination: "./uploads/", filename: function(req, file, cb){ cb(null,"IMAGE-" + Date.now() + path.extname(file.originalname)); } }); const upload = multer({ storage: storage, limits:{fileSize: 10000000}, }).fields([ { name: 'file', maxCount: 1 }, ]); upload(req, res, function(err) { var generatedFilePath = req.files['file'][0]['path']; if (err) { // ... } // Get posted data: if(!req.body.card_name || !req.body.card_desc || !req.body.card_price) { return res.status(400).send({ message: "Name, Description and Price can not be empty" }); } if (!req.body.user_id) { return res.status(400).send({ message: "Please check if you already log in." }); } const card = new Card({ card_name: req.body.card_name.trim(), card_desc: req.body.card_desc.trim(), card_price: req.body.card_price, // user_id: req.body.user_id, owner: req.body.user_id, img_url: generatedFilePath }); card.save() .then(data => { const card = cardsSerializer(data) res.send(card); }).catch(err => { res.status(500).send({ message: err.message || "Some error occurred while creating the Card." }); }); var obj = { myField1: req.body.card_name, myField2: req.body.card_desc }; console.log(obj); // ... }); // form.parse(req, function(err, fields, files) { // cardName = fields['card_name'][0]; // cardDesc = fields['card_desc'][0]; // cardPrice = fields['card_price'][0]; // userId = fields['user_id'][0]; // file = files['file'][0]; // console.log(file); // // fs.writeFile("IMAGE-" + Date.now() + path.extname(file.originalFilename)); // if(!cardName || !cardDesc || !cardPrice) { // return res.status(400).send({ // message: "Name, Description and Price can not be empty" // }); // } // if (!userId) { // return res.status(400).send({ // message: "Please check if you already log in." // }); // } // const card = new Card({ // card_name: cardName.trim(), // card_desc: cardDesc.trim(), // card_price: cardPrice, // user_id: userId // }); // card.save() // .then(data => { // const card = cardsSerializer(data) // res.send(card); // }).catch(err => { // res.status(500).send({ // message: err.message || "Some error occurred while creating the Card." // }); // }); // }); // const storage = multer.diskStorage({ // destination: "./uploads/", // filename: function(req, file, cb){ // cb(null,"IMAGE-" + Date.now() + path.extname(file.originalname)); // } // }); // const upload = multer({ // storage: storage, // limits:{fileSize: 1000000}, // }).single("file"); // console.log(req.card_name); // if(!req.body.card_name || !req.body.card_desc || !req.body.card_price) { // return res.status(400).send({ // message: "Name, Description and Price can not be empty" // }); // } // if (!req.body.user_id) { // return res.status(400).send({ // message: "Please check if you already log in." // }); // } // const card = new Card({ // card_name: req.body.card_name.trim(), // card_desc: req.body.card_desc.trim(), // card_price: req.body.card_price, // user_id: req.body.user_id // }); // card.save() // .then(data => { // const card = cardsSerializer(data) // res.send(card); // }).catch(err => { // res.status(500).send({ // message: err.message || "Some error occurred while creating the Card." // }); // }); }; exports.updateByID = (req, res) => { if(!req.user.id || !req.body.status) { return res.status(400).send({ message: "Owner, and Status can not be empty" }); } Card.findOneAndUpdate({_id:req.body.id/*, status: {$ne: 'Sold'}*/}, { owner: req.user.id, status: req.body.status, }, {new: true}) .then(data => { if(!data) { return res.status(404).send({ message: "Card not found with id " + req.body.id }); } const card = cardsSerializer(data) res.send(card); }).catch(err => { if(err.kind === 'ObjectId') { return res.status(404).send({ message: "Card not found with id " + req.body.id }); } return res.status(500).send({ message: "Error updating card with id " + req.params.id }); }); } exports.update = (req, res) => { if(!req.body.card_name || !req.body.card_desc || !req.body.card_price ) { return res.status(400).send({ message: "Name, Description and Price can not be empty" }); } Card.findByIdAndUpdate(req.params.id, { card_name: req.body.card_name.trim(), card_desc: req.body.card_desc.trim(), card_price: req.body.card_price.trim(), }, {new: true}) .then(data => { if(!data) { return res.status(404).send({ message: "Card not found with id " + req.params.id }); } const card = cardsSerializer(data) res.send(card); }).catch(err => { if(err.kind === 'ObjectId') { return res.status(404).send({ message: "Card not found with id " + req.params.id }); } return res.status(500).send({ message: "Error updating card with id " + req.params.id }); }); }; exports.delete = (req, res) => { Card.findByIdAndRemove(req.params.id) .then(card => { if(!card) { return res.status(404).send({ message: "Card not found with id " + req.params.id }); } res.send({ id: req.params.id, message: "Card deleted successfully!" }); }).catch(err => { if(err.kind === 'ObjectId') { return res.status(404).send({ message: "Card not found with id " + req.params.id }); } return res.status(500).send({ message: "Could not delete card with id " + req.params.id }); }); }; <file_sep>/front-end/src/views/utils/api.js import axios from "axios"; const http = axios.create({ baseURL: 'http://localhost:3000/api/', headers: { "Content-type": "application/json", } }); export default { auth(url = 'auth') { return { login: ({username, password}) => http.post(url + '/login', {username, password}), register: ({email, username, password}) => http.post(url + '/register', {email, username, password}), verify: (code) => http.get(url + '/confirm/' + code) } }, user(url = 'user') { const config = { headers: { 'authorization': 'Bearer ' + localStorage.getItem('token'), } }; return { fetchAll: () => http.get(url + '/list', config), fetchPagination: (page, limit) => http.get(url + "?page=" + page + "&limit=" + limit, config), fetchById: id => http.get(url + "/" + id, config), create: newRecord => http.post(url, newRecord, config), update: (id, updatedRecord) => http.put(url + "/" + id, updatedRecord, config), delete: id => http.delete(url + "/" + id, config), updateMana: mana => http.post(url + "/update-mana", mana, config), } }, card(url = 'card') { const config = { headers: { 'authorization': 'Bearer ' + localStorage.getItem('token') } }; const configForm = { headers: { 'authorization': 'Bearer ' + localStorage.getItem('token'), 'content-type': 'multipart/form-data' } }; return { fetchAll: () => http.get(url + '/list', config), fetchPagination: (page, limit) => http.get(url + "?page=" + page + "&limit=" + limit, config), fetchById: id => http.get(url + "/" + id, config), // create: ({card_name, card_desc, card_price, user_id}) => http.post(url, {card_name, card_desc, card_price, user_id}, config), create: (newRecord) => http.post(url, newRecord, configForm), update: (id, updatedRecord) => http.put(url + "/" + id, updatedRecord, config), delete: id => http.delete(url + "/" + id, config), loadSubAll: () => http.get(url + "/sub-list", config), updateStatus: (newRecord) => http.post(url + "/update-status", newRecord, config), getReceivedBid: () => http.get(url + "/get-received-bid", config), } }, bid(url = 'bid') { const config = { headers: { 'authorization': 'Bearer ' + localStorage.getItem('token') } }; return { fetchAll: () => http.get(url + '/list', config), fetchPagination: (page, limit) => http.get(url + "?page=" + page + "&limit=" + limit, config), fetchById: id => http.get(url + "/" + id, config), // create: ({card_name, card_desc, card_price, user_id}) => http.post(url, {card_name, card_desc, card_price, user_id}, config), create: (newRecord) => http.post(url, newRecord, config), update: (id, updatedRecord) => http.put(url + "/" + id, updatedRecord, config), delete: id => http.delete(url + "/" + id, config), getMatchedBid: (newRecord) => http.post(url + "/get-bid", newRecord, config), updateOrCreate: (newRecord) => http.post(url + "/update", newRecord, config), getPlacedBid: () => http.get(url + "/get-placed-bid", config), getReceivedBid: () => http.get(url + "/get-received-bid", config), } }, }<file_sep>/front-end/src/views/users/User.js import React, { useState, useEffect } from 'react' import { CCard, CCardBody, CCardHeader, CCol, CRow } from '@coreui/react' // import CIcon from '@coreui/icons-react' // import usersData from './UsersData' import API from "../utils/api" const User = ({match}) => { // const user = usersData.find( user => user.id.toString() === match.params.id) // const userDetails = user ? Object.entries(user) : // [['id', (<span><CIcon className="text-muted" name="cui-icon-ban" /> Not found</span>)]] var [userDetails, setUserDetails] = useState([]); useEffect(() => { API.user().fetchById(match.params.id) .then(res =>{ console.log(res.data); setUserDetails(res.data); }) .catch(err => console.log(err)) }, []) return ( <CRow> <CCol lg={12}> <CCard> <CCardHeader> Name: <b>{userDetails.username}</b> </CCardHeader> <CCardBody> <p>Email : {userDetails.email}</p> <p>Mana : {userDetails.mana}</p> {/* <table className="table table-striped table-hover"> <tbody> { userDetails.map(([key, value], index) => { return ( <tr key={index.toString()}> <td>{`${key}:`}</td> <td><strong>{value}</strong></td> </tr> ) }) } </tbody> </table> */} </CCardBody> </CCard> </CCol> </CRow> ) } export default User <file_sep>/front-end/src/components/GameCard.js import React, { Suspense } from 'react' import { Redirect, Route, Switch } from 'react-router-dom' import { CImg, } from '@coreui/react' import { CContainer, CFade } from '@coreui/react' import { Link } from "react-router-dom"; // routes config import routes from '../routes' import CIcon from '@coreui/icons-react' const GameCard = (props) => { return ( <Link to={"/card/" + props.cid} className="card-container text-decoration-none" style={{backgroundImage: `url(http://localhost:3000/${props.imgurl})`, backgroundSize: "cover"}}> <div className="overlay"></div> {/* <CImg src={'background/thumbnail.jpg'} alt="Empty Card" className="game-card-image" /> */} {/* <div role="listbox" aria-expanded="false" class="ui dropdown" tabindex="0"> <i aria-hidden="true" class="dropdown icon"></i> <div class="menu transition left"> <div role="option" class="item"> <span class="text">Duplicate</span> </div> <div role="option" class="item"> <span class="text">Download</span> </div> <div role="option" class="item"> <span class="text">Delete</span> </div> </div> </div> */} <div className="game-card-desc"> <div className="game-card-title"> <div className="game-caption"> {props.title} </div> </div> <div className="game-card-price"> {props.price} </div> </div> </Link> ) } export default React.memo(GameCard) <file_sep>/front-end/src/App.test.js import React from 'react' import { shallow } from 'enzyme/build' import App from './App' import Home from './views/home/Home.js' it('mounts App without crashing', () => { const wrapper = shallow(<App/>) wrapper.unmount() }) it('mounts Home without crashing', () => { const wrapper = shallow(<Home/>) wrapper.unmount() }) <file_sep>/back-end/routes/track.routes.js import { Router } from "express"; const trackRouter = Router(); const trackController = require('../controllers/track.controller.js'); // Retrieve All data trackRouter.get('/list', trackController.findAll); // Set Data by team ID trackRouter.post('/set', trackController.addTrack); //Retrieve collection list trackRouter.get('/collections', trackController.getCollections); //Retrieve time history list trackRouter.get('/timehistory', trackController.getTimeHistory); export default trackRouter <file_sep>/front-end/src/views/users/Users.js import React, { useState, useEffect } from 'react' import { useHistory } from 'react-router-dom' import { CBadge, CCard, CCardBody, CCardHeader, CCol, CDataTable, CRow, CPagination } from '@coreui/react' import API from "../utils/api" // import usersData from './UsersData' const getBadge = status => { switch (status) { case 'Active': return 'success' case 'Inactive': return 'secondary' case 'Pending': return 'warning' case 'Banned': return 'danger' default: return 'primary' } } const Users = () => { const history = useHistory() const limit = 10; var [totalPages, setTotalPages] = useState(1); var [totalUsers, setTotalUsers] = useState(1); var [currentPage, setCurrentPage] = useState(1); var [usersData, setUsersData] = useState([]); useEffect(() => { getUsers(currentPage, limit); }, []) const getUsers = (page, limit) => { API.user().fetchPagination(page, Math.abs(limit)) .then(res =>{ setTotalPages(res.data.meta.totalPages); setTotalUsers(res.data.meta.totalDocs); console.log(usersData.length); if(usersData.length < res.data.meta.totalDocs){ setUsersData(usersData.concat(res.data.users)); } }) .catch(err => console.log(err)) } const pageChange = newPage => { if(currentPage !== newPage){ setCurrentPage(newPage); getUsers(newPage, limit); } } console.log(usersData) return ( <CRow> <CCol xl={12}> <CCard> <CCardHeader> Users </CCardHeader> <CCardBody> <CDataTable items={usersData} fields={[ { key: 'team_id', _classes: 'font-weight-bold' }, 'username', 'email', 'register_date', ]} hover striped itemsPerPage={limit} activePage={currentPage} clickableRows onRowClick={(item) => history.push(`/users/${item.id}`)} scopedSlots = {{ 'status': (item)=>( <td> <CBadge color={getBadge(item.status)}> {item.status} </CBadge> </td> ) }} /> <CPagination activePage={currentPage} onActivePageChange={pageChange} pages={totalPages} doubleArrows={true} align="center" /> </CCardBody> </CCard> </CCol> </CRow> ) } export default Users <file_sep>/front-end/src/views/auth/SigninLinkedin.js import React, { useState, useEffect } from 'react' import axios from "axios"; const SigninLinkedin = (props) => { console.log(props.location.search) var search = props.location.search.split("&"); var code = search[0].substr(6); console.log(code) var redirect_uri = encodeURI("http://localhost:8000/signin-linkedin") var client_id = "78h4kkaooe3g65"; var client_secret = "<KEY>" axios.post("https://www.linkedin.com/oauth/v2/accessToken?client_id="+client_id+ "&client_secret="+client_secret+ "&grant_type=authorization_code&redirect_uri="+redirect_uri+ "&code="+code, { headers:{ "Content-Type": "application/x-www-form-urlencoded", }, }).then(function (response){ console.log("got an access token"); console.log(response); localStorage.setItem('token', response.access_token); localStorage.setItem('authType', 'linkedin') }).catch(err => { console.error("link err: "+err); }); return ( <div className="c-app c-default-layout flex-row align-items-center"> </div> ) } export default SigninLinkedin <file_sep>/README.md # MERN-Admin-Panel ## Backend Node ``` bash copy .env.example to .env update MONGO_DB_NAME and JWT_SECRET on .env file # install dependencies npm install # serve with hot reload at localhost:3000 npm run dev ``` ## Frontend React ``` bash copy .env.example to .env npm install # run at localhost:8000 npm start # build for production with minification npm build ``` <file_sep>/back-end/controllers/bid.controller.js import Bid from '../models/bid.model' const bidsSerializer = data => ({ id: data.id, user_id: data.user_id, card_id: data.card_id, bid_price: data.bid_price, expire_date: data.expire_date, status: data.status, register_date: data.register_date }); // Retrieve all data exports.findAll = (req, res) => { Bid.find() .then(async data => { const scenes = await Promise.all(data.map(bidsSerializer)); res.send(scenes); }).catch(err => { res.status(500).send({ message: err.message || "Some error occurred while retrieving scenes." }); }); }; // Retrieve data with pagination exports.findPagination = async (req, res) => { const page = req.query.page; const limit = req.query.limit; let query = {} const paginated = await Bid.paginate( query, { page, limit, lean: true, sort: { updatedAt: "desc" } } ) const { docs } = paginated; const users = await Promise.all(docs.map(bidsSerializer)); delete paginated["docs"]; const meta = paginated res.json({ meta, users }); }; exports.findOne = (req, res) => { Bid.findById(req.params.id) .then(data => { if(!data) { return res.status(404).send({ message: "user not found with id " + req.params.id }); } const user = bidsSerializer(data) res.send(user); }).catch(err => { if(err.kind === 'ObjectId') { return res.status(404).send({ message: "User not found with id " + req.params.id }); } return res.status(500).send({ message: "Error retrieving user with id " + req.params.id }); }); }; exports.findMatchBid = (req, res) => { console.log(req.body.id); console.log(req.user.id); Bid.findOne({card_id : req.body.id, user_id : req.user.id}) .then(data => { if(!data) { return res.status(404).send({ message: "Bid not found with id " + req.body.id }); } const bid = bidsSerializer(data) res.send(bid); }).catch(err => { if(err.kind === 'ObjectId') { return res.status(404).send({ message: "Bid not found with id " + req.body.id }); } return res.status(500).send({ message: "Error retrieving bid with id " + err.kind }); }); }; exports.create = (req, res) => { if(!req.body.bid_price || !req.body.id || !req.user.id || !req.body.expire_date) { return res.status(400).send({ message: "Card id, Price and Expire date can not be empty" }); } const bid = new Bid({ card_id: req.body.id, user_id: req.user.id, bid_price: req.body.bid_price, expire_date: req.body.expire_date }); bid.save() .then(data => { const user = bidsSerializer(data) res.send(user); }).catch(err => { res.status(500).send({ message: err.message || "Some error occurred while creating the User." }); }); }; exports.getPlacedBid = (req, res) => { if (!req.user.id) { return res.status(400).send({ message: "User should log in first." }); } Bid.aggregate([ // { // $project: { // 'id': card_details.id, // // user_id: data.user_id, // 'card_name': card_details.card_name, // 'card_desc': card_details.card_desc, // 'card_price': card_details.card_price, // 'img_url': card_details.img_url, // 'status': card_details.status, // 'owner': card_details.owner, // 'register_date': card_details.register_date // } // }, { $match: { user_id: req.user.id } }, { $addFields: { cardID : {$toObjectId : '$card_id'} } }, { $lookup: { from: 'card', localField: 'cardID', foreignField: '_id', as: 'card_details' } } ]).then(async data => { const cards = await Promise.all(data.map(dt => ({ id: dt.card_details[0].id, // user_id: data.user_id, card_name: dt.card_details[0].card_name, card_desc: dt.card_details[0].card_desc, card_price: dt.card_details[0].card_price, img_url: dt.card_details[0].img_url, status: dt.card_details[0].status, owner: dt.card_details[0].owner, register_date: dt.card_details[0].register_date }))); // const user = bidsSerializer(data) res.send(cards); }).catch(err => { res.status(500).send({ message: err.message || "Some error occurred while retrieving the placed bids." }); }); }; exports.getReceivedBid = (req, res) => { console.log('here'); if (!req.user.id) { return res.status(400).send({ message: "User should log in first." }); } Bid.aggregate([ { $addFields: { cardID : {$toObjectId : '$card_id'} } }, { $lookup: { from: 'card', localField: 'cardID', foreignField: '_id', as: 'card_details' } }, { $unwind: { path: "$card_details" } }, { $match: { "card_details.owner": req.user.id } }, ]).then(async data => { console.log(data) const cards = await Promise.all(data.map(dt => ({ id: dt.card_id, // user_id: data.user_id, card_name: dt.card_details.card_name, card_desc: dt.card_details.card_desc, card_price: dt.card_details.card_price, bid_price: dt.bid_price, img_url: dt.card_details.img_url, status: dt.card_details.status, owner: dt.card_details.owner, bidder: dt.user_id, register_date: dt.card_details.register_date }))); console.log(cards) // const user = bidsSerializer(data) res.send(cards); }).catch(err => { res.status(500).send({ message: err.message || "Some error occurred while retrieving the placed bids." }); }); }; exports.updateOrCreate = (req, res) => { if(!req.body.bid_price || !req.body.id || !req.user.id || !req.body.expire_date) { return res.status(400).send({ message: "Card id, Price and Expire date can not be empty" }); } Bid.updateOne({card_id : req.body.id, user_id : req.user.id}, { card_id: req.body.id, user_id: req.user.id, bid_price: req.body.bid_price, expire_date: req.body.expire_date }, {upsert: true}) .then(data => { console.log(data) if(!data) { return res.status(404).send({ message: "Bids not found with id " + req.body.id }); } const bid = bidsSerializer(data) res.send(bid); }).catch(err => { console.log(err) if(err.kind === 'ObjectId') { return res.status(404).send({ message: "Bid not found with id " + req.body.id }); } return res.status(500).send({ message: "Error retrieving bid with id " + err.kind }); }); }; exports.update = (req, res) => { if(!req.body.username || !req.body.email ) { return res.status(400).send({ message: "Name and Email can not be empty" }); } Bid.findByIdAndUpdate(req.params.id, { username: req.body.username.trim(), email: req.body.email.trim(), }, {new: true}) .then(data => { if(!data) { return res.status(404).send({ message: "User not found with id " + req.params.id }); } const user = bidsSerializer(data) res.send(user); }).catch(err => { if(err.kind === 'ObjectId') { return res.status(404).send({ message: "User not found with id " + req.params.id }); } return res.status(500).send({ message: "Error updating user with id " + req.params.id }); }); }; exports.delete = (req, res) => { Bid.findByIdAndRemove(req.params.id) .then(user => { if(!user) { return res.status(404).send({ message: "User not found with id " + req.params.id }); } res.send({ id: req.params.id, message: "User deleted successfully!" }); }).catch(err => { if(err.kind === 'ObjectId' || err.username === 'NotFound') { return res.status(404).send({ message: "User not found with id " + req.params.id }); } return res.status(500).send({ message: "Could not delete user with id " + req.params.id }); }); }; <file_sep>/back-end/routes/bid.routes.js import jwt from '../middleware/auth'; import { Router } from "express"; const bidRouter = Router(); const bidController = require('../controllers/bid.controller.js'); // Retrieve All data bidRouter.get('/list', jwt, bidController.findAll); // Retrieve data with pagination bidRouter.get('/', bidController.findPagination); // Retrieve placed bid data bidRouter.get('/get-placed-bid', jwt, bidController.getPlacedBid); bidRouter.get('/get-received-bid', jwt, bidController.getReceivedBid); // Retrieve received bid data // Find one by ID bidRouter.get('/:id', bidController.findOne); // Create bidRouter.post('/', jwt, bidController.create); // Update bidRouter.put('/:id', jwt, bidController.update); // Delete bidRouter.delete('/:id', jwt, bidController.delete); // Get matched bid bidRouter.post('/get-bid', jwt, bidController.findMatchBid); // Update or Create bidRouter.post('/update', jwt, bidController.updateOrCreate); export default bidRouter; <file_sep>/back-end/models/card.model.js import { Schema, model } from 'mongoose'; const mongoosePaginate = require('mongoose-paginate-v2'); // Create Schema const CardSchema = new Schema({ // user_id: { // type: String, // required: true // }, card_name: { type: String, required: true }, card_desc: { type: String, required: true }, card_price: { type: Number, required: true }, img_url: { type: String, required: true }, status: { type: String, enum: ['Pending', 'Sold', 'Active'], default: 'Active' }, owner: { type: String, default: 'no', required: true }, register_date: { type: Date, default: Date.now } }, { timestamps: true }); CardSchema.plugin(mongoosePaginate); const Card = model('card', CardSchema, 'card'); export default Card; <file_sep>/front-end/src/containers/TheFooter.js import React from 'react' import { CFooter } from '@coreui/react' import { Link } from "react-router-dom"; const TheFooter = () => { return ( <CFooter fixed={false} className="bg-black container"> <div> <Link to="/home" className="text-decoration-none footer-text-color">Home</Link> <Link to="/privacy" className="text-decoration-none ml-3 footer-text-color">Privacy Policy</Link> <Link to="/terms" className="text-decoration-none ml-3 footer-text-color">Terms of Use</Link> <Link to="/content-policy" className="text-decoration-none ml-3 footer-text-color">Content Policy</Link> <Link to="/code-ethics" className="text-decoration-none ml-3 footer-text-color">Code of Ethics</Link> </div> <div className="mfs-auto"> <span className="mr-1 footer-text-color">© 2021 Metrix</span> </div> </CFooter> ) } export default React.memo(TheFooter) <file_sep>/front-end/src/components/SlideShow.js import React, { Suspense, useEffect, useState } from 'react' import { Redirect, Route, Switch } from 'react-router-dom' import { CContainer, CFade } from '@coreui/react' import { Link } from "react-router-dom"; // routes config import routes from '../routes' import CIcon from '@coreui/icons-react' import EachSlider from './EachSlide' import API from "../views/utils/api" import { useSelector, useDispatch } from 'react-redux' import { isAuthenticated } from '../App'; const SlideShow = (props) => { const dispatch = useDispatch(); const allCardList = useSelector(state => state.allCardList); const getAllCardList = () => { API.card().fetchAll() .then(res => { dispatch({type: 'SET_ALL_CARD_LIST', allCardList: res.data}); }) .catch(err => console.log(err)); } useEffect(() => { getAllCardList(); console.log(allCardList) }, []) return ( <div className="slide-show container"> <div className="header-menu"> <div className="header-menu-title title-style">{props.title}</div> <div className="header-menu-view-all"> <Link to="/browse" className="text-decoration-none text-danger"> View all <CIcon name="cil-chevron-right" className="ml-1"/> </Link> </div> </div> { !allCardList.length ? ( <> <div className="CardList"> <div className="empty-projects"> <div> It looks like there aren't any cards available. <br/> </div> </div> </div> </> ) : ( <div className="slides-container"> { allCardList.map((card, idx) => ( <EachSlider key={idx} title={card.card_name} price={card.card_price} desc={card.card_desc} owner={card.owner} cid={card.id} imgurl={card.img_url.replace("\\", '/')} /> )) } </div> ) } </div> ) } export default React.memo(SlideShow) <file_sep>/front-end/src/views/home/CardDetail.js import React, { useEffect, useState } from 'react' import { toast } from 'react-toastify'; import { CButton, CImg, } from '@coreui/react' import CIcon from '@coreui/icons-react' import API from "../utils/api" import Select from "react-dropdown-select"; import Loader from "react-loader-spinner"; import "react-loader-spinner/dist/loader/css/react-spinner-loader.css"; import { Link, useHistory } from "react-router-dom"; import Card from '../../components/GameCard' import AddCardModal from '../../components/AddCardModal'; import { useSelector, useDispatch } from 'react-redux' import { isAuthenticated } from '../../App'; import TabComponent from "../../components/TabComponent" const CardDetail = (props) => { const history = useHistory(); const dispatch = useDispatch(); const cardDetail = useSelector(state => state.cardDetail); const [userID, setUserID] = useState(''); const isLoggedIn = isAuthenticated(); const [ownerName, setOwnerName] = useState(''); const getCardDetail = async () => { // if (isLoggedIn) { console.log(props.match.params.id); const usr = localStorage.getItem('authUser'); if (usr !== null) { let log_usr = JSON.parse(usr); setUserID(log_usr.id); } await API.card().fetchById(props.match.params.id) .then(res => { dispatch({type: 'SET_CARD_DETAIL', cardDetail : res.data}); API.user().fetchById(res.data.owner).then((res) => { setOwnerName(res.data.username); }).catch(err => console.log(err)); }) .catch(err => console.log(err)); console.log(cardDetail.owner); } useEffect(() => { getCardDetail(); }, []) return ( <> <TabComponent tabkind="" /> <div className="container detail-wrapper"> <CButton onClick={() => history.goBack()} className="text-decoration-none"> <div className="back-url"></div> </CButton> </div> <div className="full-width-image"> <CImg src={`http://localhost:3000/${cardDetail.img_url}`} alt="thumbnail" className="full-image" /> </div> <div className="container"> <div className="row-title"> <div className="left-wrapper"> <div className="left-caption"> {cardDetail.card_name} </div> </div> <div className="right-wrapper"> <div className="owner-name"> {ownerName} </div> </div> </div> <div className="row-description"> <div className="sub-desc-caption">Description</div> <div className="description-text">{cardDetail.card_desc}</div> </div> <div className="row-wrapper"> <div className="left-wrapper"> <span className="stats-wrapper"> <div className="stats-header">price</div> <div className="stats-body"> ⏣ {cardDetail.card_price} </div> </span> <span className="stats-wrapper"> <div className="stats-header">Expires in</div> <div className="stats-body"> in 25 days </div> </span> </div> <div className="right-wrapper"> { cardDetail.owner !== userID ? ( <> <Link to={ isAuthenticated() ? "/buy/" + props.match.params.id : "/login"} className="text-decoration-none btn-buy">Buy</Link> <Link to={ isAuthenticated() ? "/bid/" + props.match.params.id : "/login"} className="text-decoration-none btn-bid">Bid</Link> </> ) : ( <> You are the Owner. </> ) } </div> </div> </div> </> ) } export default CardDetail <file_sep>/front-end/src/containers/TheHeader.js import React, {useEffect} from 'react' import { useSelector, useDispatch } from 'react-redux' import { Link } from "react-router-dom"; import { CHeader, CToggler, CHeaderBrand, CHeaderNav, CHeaderNavItem, CHeaderNavLink, CSubheader, CBreadcrumbRouter, CLink } from '@coreui/react' import CIcon from '@coreui/icons-react' // routes config import routes from '../routes' import { TheHeaderDropdown, TheHeaderDropdownMssg, TheHeaderDropdownNotif, // TheHeaderDropdownTasks } from './index' import { isAuthenticated } from '../App'; import Api from "../views/utils/api" const TheHeader = () => { const dispatch = useDispatch() const sidebarShow = useSelector(state => state.sidebarShow) const mana = useSelector(state => state.mana); let isLoggedIn = isAuthenticated(); const toggleSidebar = () => { const val = [true, 'responsive'].includes(sidebarShow) ? false : 'responsive' dispatch({type: 'set', sidebarShow: val}) } const toggleSidebarMobile = () => { const val = [false, 'responsive'].includes(sidebarShow) ? true : 'responsive' dispatch({type: 'set', sidebarShow: val}) } useEffect(() => { if (isAuthenticated()) { let userId = 0; const usr = localStorage.getItem('authUser'); if (usr !== null) { let log_usr = JSON.parse(usr); userId = log_usr.id; } Api.user().fetchById(userId) .then(res => { console.log(res); dispatch({type: 'SET_MANA', mana: res.data.mana}); }) .catch(err => console.log(err)); } }, []) return ( <CHeader withSubheader className="bg-black container position-absolute"> {/* <CToggler inHeader className="ml-md-3 d-lg-none" onClick={toggleSidebarMobile} /> <CToggler inHeader className="ml-3 d-md-down-none" onClick={toggleSidebar} /> */} <CHeaderBrand to="/"> <div className="logo-bkg"></div> </CHeaderBrand> <CHeaderNav className="d-md-down-none mr-auto"> <CHeaderNavItem className="px-3" > <CHeaderNavLink to="/home" className="text-dark">MARKETPLACE</CHeaderNavLink> </CHeaderNavItem> <CHeaderNavItem className="px-3" > <CHeaderNavLink to="/builder" className="text-dark">BUILDER</CHeaderNavLink> </CHeaderNavItem> <CHeaderNavItem className="px-3"> <CHeaderNavLink to="/docs" className="text-dark">DOCS</CHeaderNavLink> </CHeaderNavItem> <CHeaderNavItem className="px-3"> <CHeaderNavLink to="/events" className="text-dark">EVENTS</CHeaderNavLink> </CHeaderNavItem> <CHeaderNavItem className="px-3"> <CHeaderNavLink to="/dao" className="text-dark">DAO</CHeaderNavLink> </CHeaderNavItem> <CHeaderNavItem className="px-3"> <CHeaderNavLink to="/blog" className="text-dark">BLOG</CHeaderNavLink> </CHeaderNavItem> {/* <CHeaderNavItem className="px-3"> <CHeaderNavLink>Settings</CHeaderNavLink> </CHeaderNavItem> */} </CHeaderNav> { isLoggedIn ? ( <CHeaderNav className="pl-3"> {/* <TheHeaderDropdownNotif/> <TheHeaderDropdownTasks/> <TheHeaderDropdownMssg/> */} <TheHeaderDropdownNotif/> <div> ⏣ {mana} </div> <TheHeaderDropdown/> </CHeaderNav> ) : ( <CHeaderNav className="px-3"> <Link to="/login" className="text-decoration-none text-dark mr-4">SIGN IN</Link> <Link to="/register" className="text-decoration-none text-dark">SIGN UP</Link> </CHeaderNav> ) } </CHeader> ) } export default TheHeader <file_sep>/front-end/src/views/home/MyBids.js import React, { useEffect, useState } from 'react' import { CButton } from '@coreui/react' import CIcon from '@coreui/icons-react' import API from "../utils/api" import Select from "react-dropdown-select"; import Loader from "react-loader-spinner"; import "react-loader-spinner/dist/loader/css/react-spinner-loader.css"; import { Link, useHistory } from "react-router-dom"; import TabComponent from "../../components/TabComponent" import { useSelector, useDispatch } from 'react-redux' import EachSlider from '../../components/EachSlide' import { isAuthenticated } from '../../App'; const MyBids = () => { const dispatch = useDispatch(); const placedBids = useSelector(state => state.placedBids); const receivedBids = useSelector(state => state.receivedBids); const isLoggedIn = isAuthenticated(); const getPlacedBids = () => { if (isLoggedIn) { API.bid().getPlacedBid() .then(res => { console.log(res.data); dispatch({type: 'SET_PLACED_BIDS', placedBids: res.data}); }) .catch(err => console.log(err)); } else { dispatch({type: 'SET_PLACED_BIDS', placedBids: []}); } } const getReceivedBids = () => { if (isLoggedIn) { API.bid().getReceivedBid() .then(res => { console.log(res.data); dispatch({type: 'SET_RECEIVED_BIDS', receivedBids: res.data}); }) .catch(err => console.log(err)); } else { dispatch({type: 'SET_RECEIVED_BIDS', receivedBids: []}); } } useEffect(() => { getPlacedBids(); getReceivedBids(); }, []) return ( <> <TabComponent tabkind="mybids" /> <div className="container"> {/* <div className="topbar"> <div className="TextFilter Filter"> <div className="text-input"> <input placeholder="Search +1,000 results..." value="" /> </div> </div> </div> */} <div className="bid-header-menu"> <div className="bid-header-menu-left"> <div className="bid-sub-header">Bids received</div> </div> </div> <div className="bids-container"> { !receivedBids.length ? ( <div className="center"> { isLoggedIn ? ( "You haven't received any bids yet..." ) : ( "You haven't logged in yet..." ) } </div> ) : ( <div className="browse-cards"> { receivedBids.map((card, idx) => ( <EachSlider key={idx} title={card.card_name} bidder={card.bidder} bid_price={card.bid_price} price={card.card_price} desc={card.card_desc} owner={card.owner} cid={card.id} imgurl={card.img_url.replace("\\", '/')} /> )) } </div> ) } </div> <div className="bid-header-menu"> <div className="bid-header-menu-left"> <div className="bid-sub-header">Bids placed</div> </div> </div> <div className="bids-container"> { !placedBids.length ? ( <div className="center"> { isLoggedIn ? ( "You haven't placed any bids yet..." ) : ( "You haven't logged in yet..." ) } </div> ) : ( <div className="browse-cards"> { placedBids.map((card, idx) => ( <EachSlider key={idx} title={card.card_name} price={card.card_price} desc={card.card_desc} owner={card.owner} cid={card.id} imgurl={card.img_url.replace("\\", '/')} /> )) } </div> ) } </div> <div className="load-more"> <CButton className="ui inverted primary button">Load more</CButton> </div> </div> </> ) } export default MyBids <file_sep>/front-end/src/components/EachSlide.js import React, { Suspense, useEffect, useState } from 'react' import { Redirect, Route, Switch } from 'react-router-dom' import { CImg, } from '@coreui/react' import { CContainer, CFade } from '@coreui/react' import { Link } from "react-router-dom"; // routes config import routes from '../routes' import CIcon from '@coreui/icons-react' import API from "../views/utils/api" const EachSlide = (props) => { const [ownerName, setOwnerName] = useState(''); const [bidderName, setBidderName] = useState(''); useEffect(() => { API.user().fetchById(props.owner).then(res => { setOwnerName(res.data.username); }).catch(err => console.log(err)); if (props.bidder) { API.user().fetchById(props.bidder).then(res => { setBidderName(res.data.username); }).catch(err => console.log(err)); } }, []) return ( <Link to={"/card/" + props.cid} className="slide-container text-decoration-none text-white"> <div className="cardimage-container"> <div className="image-wrapper"> <div className="card-image"> <CImg src={`http://localhost:3000/${props.imgurl}`} alt="thumbnail" className="full-image" /> </div> </div> </div> <div className="card-info"> <div className="card-header"> <div className="card-title">{props.title}</div> <div className="card-price">⏣ {props.price}</div> </div> <div className="card-desc">{props.desc}</div> <div className="card-action"> <span className="show-owner">{ownerName ? ownerName : 'unknown'}</span> { props.bidder && props.bid_price && ( <> <span className="bidder-name">{bidderName}</span> <span className="bid-price">⏣ {props.bid_price}</span> </> ) } </div> </div> </Link> ) } export default React.memo(EachSlide) <file_sep>/back-end/routes/card.routes.js import jwt from '../middleware/auth'; import { Router } from "express"; const cardRouter = Router(); const cardController = require('../controllers/card.controller.js'); // Retrieve All data cardRouter.get('/list', cardController.findAll); // Find all by User ID cardRouter.get('/sub-list', jwt, cardController.findAllByUserID); cardRouter.get('/get-received-bid', jwt, cardController.getReceivedBid); // Update cardRouter.post('/update-status', jwt, cardController.updateByID); // Retrieve data with pagination cardRouter.get('/', cardController.findPagination); // Find one by ID cardRouter.get('/:id', cardController.findOne); // Create cardRouter.post('/', jwt, cardController.create); // Update cardRouter.put('/:id', jwt, cardController.update); // Delete cardRouter.delete('/:id', jwt, cardController.delete); export default cardRouter; <file_sep>/back-end/.env.example PORT=3000 MONGO_URI=mongodb://localhost:27017 MONGO_DB_NAME=null JWT_SECRET=null<file_sep>/front-end/src/views/auth/Login.js import React, {useState, useEffect}from 'react' import { Link } from 'react-router-dom' import { CButton, CCard, CCardBody, CCardGroup, CCol, CContainer, CForm, CInput, CInputGroup, CInputGroupPrepend, CInputGroupText, CRow } from '@coreui/react' import CIcon from '@coreui/icons-react' import API from "../utils/api" import { toast } from 'react-toastify'; import { loadCaptchaEnginge, LoadCanvasTemplate, validateCaptcha } from 'react-simple-captcha'; import { GoogleLogin } from 'react-google-login'; import { LinkedIn } from 'react-linkedin-login-oauth2'; import linkedin from 'react-linkedin-login-oauth2/assets/linkedin.png' import axios from "axios"; import { useSelector, useDispatch } from 'react-redux' const Login = (props) => { const dispatch = useDispatch(); var [username, setUsername] = useState(""); var [password, setPassword] = useState(""); // var [token, setToken] = useState(null); // var [authUser, setAuthUser] = useState(null); var [captchaVal, setCaptchaVal] = useState(""); useEffect(() => { loadCaptchaEnginge(6); }, []); const setLogin = (data) => { if (data) { localStorage.setItem('token', data.token) localStorage.setItem('authUser', JSON.stringify(data.user)) localStorage.setItem('authType', '') dispatch({type: 'SET_MANA', mana : data.user.mana}); // setToken(data.token); // setAuthUser(data.user); } else { // setToken(null); // setAuthUser(null); localStorage.clear() } } const handleLogin = () => { setLogin(null) if (username !== "" && password !== "") { if(validateCaptcha(captchaVal) === true ){ API.auth().login({ username, password }) .then(res => { // console.log("res : ", JSON.stringify(res.data)) if (res.status === 200 && res.data) { setLogin(res.data) // toast.success("Log in successful!") props.history.push('/') return true } else { toast.error(res.data.message); return false } }) .catch(err => { if (err.response) toast.error(err.response.data.message) else { toast.error(err) } return false }); } else{ toast.error("Captcha does not match!") } } else { toast.error("username and password is empty") return false } } const responseGoogle = (response) => { console.log(response) if(response.tokenId){ localStorage.setItem('token', response.tokenId) localStorage.setItem('authType', 'google') props.history.push('/') } } const handleSuccess = (data) => { console.log("linkedin success"); console.log("link in : ", data.code); axios.post("https://www.linkedin.com/oauth/v2/accessToken",{ headers:{ "Content-Type": "application/x-www-form-urlencoded", }, data: { grant_type : 'authorization_code', code : data.code, redirect_uri: "http://localhost:8000", client_id :'78h4kkaooe3g65', client_secret: '<KEY>' } }).then(function (response){ console.log("got an access token"); console.log(response); localStorage.setItem('token', response.access_token); localStorage.setItem('authType', 'linkedin') }).catch(err => { console.error(err); }); } const handleFailure = (error) => { console.log("linked failure"); console.log(error.errorMessage) } return ( <div className="c-app c-default-layout flex-row align-items-center"> <CContainer> <CRow className="justify-content-center"> <CCol md="8"> <CCardGroup> <CCard className="p-4"> <CCardBody> <CForm className="was-validated"> <h1>Login</h1> <p className="text-muted">Sign In to your account</p> <CInputGroup className="mb-3"> <CInputGroupPrepend> <CInputGroupText> <CIcon name="cil-user" /> </CInputGroupText> </CInputGroupPrepend> <CInput value={username} onChange={e => setUsername(e.target.value)} type="text" placeholder="username" autoComplete="username" required/> </CInputGroup> <CInputGroup className="mb-4"> <CInputGroupPrepend> <CInputGroupText> <CIcon name="cil-lock-locked" /> </CInputGroupText> </CInputGroupPrepend> <CInput value={password} onChange={e => setPassword(e.target.value)} type="password" placeholder="<PASSWORD>" autoComplete="current-password" required/> </CInputGroup> <LoadCanvasTemplate /> <CInputGroup className="mb-3"> <CInputGroupPrepend> <CInputGroupText> <CIcon name="cil-pencil" /> </CInputGroupText> </CInputGroupPrepend> <CInput value={captchaVal} onChange={e => setCaptchaVal(e.target.value)} type="text" placeholder="captcha value" autoComplete="captcha" required/> </CInputGroup> <CRow> <CCol xs="6"> <CButton onClick={handleLogin} color="primary" className="px-4">Login</CButton> </CCol> {/* <CCol xs="6" className="text-right"> <CButton color="link" className="px-0">Forgot password?</CButton> </CCol> */} </CRow> </CForm> </CCardBody> </CCard> <CCard className="text-white bg-primary py-5 d-md-down-none" style={{ width: '44%' }}> <CCardBody className="text-center"> <div> <h2>Sign up</h2> <br/> <p>If you don't have any account, create new your own account.</p> <Link to="/register"> <CButton color="primary" style={{borderColor : 'white'}} className="mt-3" active tabIndex={-1}>Register Now!</CButton> </Link> <br/> <br/> <p> Or you can sign in with Googld or LinkedIn account.</p> <GoogleLogin clientId="619796199014-01tgui96qd1nme0rsf7lofhb571u04c7.apps.googleusercontent.com" buttonText="Sign in with Google" onSuccess={responseGoogle} onFailure={responseGoogle} cookiePolicy={'single_host_origin'} /> <br/> <br/> <LinkedIn clientId="78h4kkaooe3g65" onFailure={handleFailure} onSuccess={handleSuccess} redirectUri="http://localhost:8000/" > <img src={linkedin} alt="Log in with Linked In" style={{ maxWidth: '180px' }} /> </LinkedIn> </div> </CCardBody> </CCard> </CCardGroup> </CCol> </CRow> </CContainer> </div> ) } export default Login <file_sep>/front-end/src/components/AddCardModal.js import React, {useState, useEffect, Suspense} from 'react' import Modal from 'react-bootstrap/Modal'; import { Button} from 'react-bootstrap'; import { toast } from 'react-toastify'; import { ImagePicker } from 'react-file-picker' import { Redirect, Route, Switch } from 'react-router-dom' import { CImg, CInput, } from '@coreui/react' import { CContainer, CFade } from '@coreui/react' import { Link, useHistory } from "react-router-dom"; // routes config import routes from '../routes' import CIcon from '@coreui/icons-react' import API from "../views/utils/api" const AddCardModal = (props) => { let history = useHistory(); const [cardname, setCardname] = useState(props.cname); const [description, setDescription] = useState(props.cdesc); const [price, setPrice] = useState(props.cprice); const [selectedFile, setSelectedFile] = useState(); const [isFilePicked, setIsFilePicked] = useState(false); let userId = 0; const changeFile = (event) => { setSelectedFile(event.target.files[0]); setIsFilePicked(true); }; const createCard = (event) => { const usr = localStorage.getItem('authUser'); if (usr !== null) { let log_usr = JSON.parse(usr); userId = log_usr.id; } console.log(selectedFile); console.log(userId); if (!cardname || !description || parseFloat(price) === null) { toast.error('Please fill out all the fields'); return ; } const formData = new FormData(); formData.append("card_name", cardname); formData.append("card_desc", description); formData.append("card_price", parseFloat(price)); formData.append("user_id", userId); formData.append("file", selectedFile); // let newRecode = {'card_name': cardname, 'card_desc': description, 'card_price': parseFloat(price), 'user_id': userId}; API.card().create(formData).then(res => { // console.log("res : ", JSON.stringify(res.data)) if (res.status === 200 && res.data) { setCardname(''); setDescription(''); setPrice(''); // history.push('/builder'); props.onHide(); props.getaddcardlist(res.data); } else { toast.error(res.data.message); return false } }) .catch(err => { if (err.response) toast.error(err.response.data.message) else { toast.error(err) } return false }); } return ( <Modal {...props} size="lg" aria-labelledby="contained-modal-title-vcenter" centered className="add-card-modal" > <Modal.Header closeButton> <Modal.Title id="contained-modal-title-vcenter"> Create an Image Card </Modal.Title> </Modal.Header> <Modal.Body> <div className="input-group"> <label className="modal-label">Name</label> <CInput value={cardname} onChange={e => setCardname(e.target.value)} type="text" placeholder="Card Name" autoComplete="cardname" required/> </div> <div className="input-group"> <label className="modal-label">Description</label> <CInput value={description} onChange={e => setDescription(e.target.value)} type="text" placeholder="Card Description" autoComplete="description" required/> </div> <div className="input-group"> <label className="modal-label">Price</label> <CInput value={price} onChange={e => setPrice(e.target.value)} type="text" placeholder="Set Price" autoComplete="Price" required/> </div> <div className="input-group"> <label className="modal-label">Image file</label> <CInput type="file" name="file" onChange={changeFile} placeholder="File upload" autoComplete="file" accept=".jpg,.jpeg,.png,.bmp" required/> </div> </Modal.Body> <Modal.Footer> <Button onClick={createCard} className="text-white bg-success border-0">Confirm</Button> <Button onClick={props.onHide}>Close</Button> </Modal.Footer> </Modal> ); } export default React.memo(AddCardModal) <file_sep>/front-end/src/store.js import { createStore } from 'redux' const initialState = { sidebarShow: 'responsive', cardList: [], allCardList: [], cardDetail: {}, mana: 0, myCards:[], receivedBids:[], placedBids:[], } const changeState = (state = initialState, { type, ...rest }) => { switch (type) { case 'SET_CARD_LIST': return { ...state, cardList: rest.cardList } case 'SET_ALL_CARD_LIST': return { ...state, allCardList: rest.allCardList } case 'SET_CARD_DETAIL': return { ...state, cardDetail: rest.cardDetail } case 'SET_MY_CARDS': return { ...state, myCards: rest.myCards } case 'SET_MANA': return { ...state, mana: rest.mana } case 'SET_RECEIVED_BIDS': return { ...state, receivedBids: rest.receivedBids } case 'SET_PLACED_BIDS': return { ...state, placedBids: rest.placedBids } case 'set': return {...state, ...rest } default: return state } } const store = createStore(changeState) export default store<file_sep>/front-end/src/views/auth/Verify.js import React, { useState } from 'react' import { Link } from 'react-router-dom' import { CButton, CCard, CCardBody, CCol, CContainer, CForm, CInput, CInputGroup, CInputGroupPrepend, CInputGroupText, CRow } from '@coreui/react' import CIcon from '@coreui/icons-react' import API from "../utils/api" import { toast } from 'react-toastify'; const Verify = (props) => { const [confirmStatus, setConfirmStatus] = useState(false); if(props.match.path === "/confirm/:confirmationCode"){ API.auth().verify(props.match.params.confirmationCode) .then(res => { setConfirmStatus(true); }).catch(err => { if(err) setConfirmStatus(false); }); } return ( <div className="c-app c-default-layout flex-row align-items-center"> <CContainer> <CRow className="justify-content-center"> <CCol md="9" lg="7" xl="6"> <CCard className="mx-4"> <CCardBody className="p-4"> { confirmStatus ? ( <div> <h2>Acount Email Confirmed!</h2> <br/> <Link to="/login"> <CButton color="primary" block>Please Login</CButton> </Link> </div> ) : ( <div> <h2>Acount Email Confirmation Failed!</h2> <br/> <h4>Please, check email and try again!</h4> <Link to="/register"> <CButton color="primary" block>Register</CButton> </Link> </div> ) } </CCardBody> </CCard> </CCol> </CRow> </CContainer> </div> ) } export default Verify <file_sep>/back-end/config/nodemailer.config.js import nodemailer from "nodemailer"; import config from "../config"; const {PASS, USER} = config; const transport = nodemailer.createTransport({ host: 'smtp.gmail.com', port: 587, tls: { secure: false, ignoreTLS: true, rejectUnauthorized: false }, auth: { user: USER, pass: <PASSWORD>, }, }); exports.sendConfirmationEmail = (name, email, confirmationCode) => { let mailOptions = { from: USER, to: email, subject: "Please confirm your account", html: `<h1>Email Confirmation</h1> <h2>Hello ${name}</h2> <h5>Thank you for subscribing. Please confirm your email by clicking on the following link</h5> <a href=http://localhost:8000/#/confirm/${confirmationCode}><h3> Click here</h3></a> </div>` }; console.log("Check"); transport.sendMail(mailOptions, (error, info) => { if (error) { console.log('Error', error); } else{ console.log('Success', info); } }); };
92a7d1520cb0a028ee64b4418bd5c5d223fea355
[ "Markdown", "Shell", "JavaScript" ]
25
Markdown
dragonmaster-alpha/Decetraland-Market-Alpha
3caa5d9433f90541118388f306a7c8d05ea21cb8
9c24238d121542ec95a538759c24a4bb65540459
refs/heads/main
<repo_name>tejas2600/Digit-Recognition<file_sep>/README.md # Digit-Recognition Digit recognition using MNIST dataset with CNN having two convolution layer , two pooling layer , 1 Dropout and one hidden layer.
b99bc171c1fd871759929daafb8dd4cc3c6f956f
[ "Markdown" ]
1
Markdown
tejas2600/Digit-Recognition
909e81eb1607e137c0917c32d7b262bcaf192bd9
ec69fd8fc752c4b42f2f35ce1c1e7c5254d2a957
refs/heads/master
<file_sep># Infrastructure This document is a reference of all the apps maintained by the ember learning team. The main website [https://emberjs.com][15] uses the [heroku static buildpack][14] to proxy to various different sites via the [static.json][16] configuration file. ## Overview | Repository | Purpose | Current tech | Direct URL | |-------------------------------------|--------------------------------------|-----------------------------------------------|-------------------------------------------------------| | [emberjs/website][1] | emberjs.com home page | static site built on Middleman |https://ember-website.herokuapp.com/ | | [emberjs/rfcs][2] | RFC's page | static site generated from markdown by mdbook |https://emberjs.github.io/rfcs | | [ember-learn/ember-api-docs][3] | Ember API docs | ember app with fastboot running on express |https://ember-api-docs-frontend.global.ssl.fastly.net | | [ember-learn/statusboard][4] | Status of ember milestone projects | ember app with prember |https://ember-learn.github.io/statusboard/ | | [ember-learn/deprecations-app][5] | List deprecations in ember | ember app with prember |https://deprecations-app-prod.herokuapp.com/ | | [ember-learn/builds][6] | Shows ember releases | ember app | | ## Sub domains | Repository | Purpose | Current tech | URL | |-------------------------------------|--------------------------------------|-----------------------------------------------|-------------------------------------------------------| | [ember-learn/ember-help-wanted][7] | List issues across ember repos that need community help | ember app |https://help-wanted.emberjs.com/ | | [ember-learn/guides-app][17] | TBD | ember app with prember |https://ember-guides-prod.herokuapp.com/ | | [ember-learn/cli-guides][18] | new ember-cli docs | ember app with prember |https://ember-cli-guides.netlify.com/ | ## On hosting preferences [Heroku][8] sponsors our hosting & [Fastly][9] sponsors our CDN :heart:. While heroku does have [a fastly addon][10], for billing & maintenance reasons its easier to manage one fastly account with multiple service accounts configured in it. Heroku lets us have [pipelines][11] that enables us to have different environments like staging & production. It also lets us have review apps explained in the following section. We have hosted few apps directly on GitHub pages. These are apps where only content of the app is changed by internal teams that they don't require the sophisticated setup that the other apps enjoy. We've deployed apps prerendered with prember on [Netlify][19]. ## Review apps Heroku enables us to create [review apps][12] which are same as regular apps but lets us review changes in pull requests. They're automatically created when members with write access of a repo raise a PR (also depends on whether the pipeline is configured to auto-deploy). To create a review app for a PR raised by non-members, go to the heroku pipeline and manually create the review app. Review apps get deleted after few days of inactivity on the PR. They also get deployed only on successful builds on Travis. Creation & maintenance of review apps on netlify is automated & doesn't require manual intervention. ## Heroku deployment Heroku deployment doesn't require special deploy section on `.travis.yml` configuration file since we always setup github integration via the [heroku dashboard][13]. The deployment on heroku still checks to ensure that travis builds were successful before autodeploying the changes. All our heroku apps are set to autodeploy `master` branch to their staging apps. The changes are usually elevated to production after a member manually deploys the production app. **DO NOT USE** the `promote to production` button to promote staging changes to production. This copies over the assets as is from staging container to production. This is problematic in our setup because we have variables that differ between staging and production that drive our ember app builds. e.g., `FASTLY_CDN_URL` is a typical environment variable we use across our ember apps. Promoting as is from staging would result in production pointing to staging's fastly url. This will start producing errors as soon as different changes are deployed to staging & those files are no longer available. [1]: https://github.com/emberjs/website [2]: https://github.com/emberjs/rfcs [3]: https://github.com/ember-learn/ember-api-docs [4]: https://github.com/ember-learn/statusboard [5]: https://github.com/ember-learn/deprecation-app [6]: https://github.com/ember-learn/builds [7]: https://github.com/ember-learn/ember-help-wanted [8]: https://heroku.com [9]: https://fastly.com [10]: https://elements.heroku.com/addons/fastly [11]: https://devcenter.heroku.com/articles/pipelines [12]: https://devcenter.heroku.com/articles/github-integration-review-apps [13]: https://dashboard.heroku.com/teams/ember/apps [14]: https://github.com/heroku/heroku-buildpack-static [15]: https://emberjs.com [16]: https://github.com/emberjs/website/blob/master/static.json [17]: https://github.com/ember-learn/guides-app [18]: https://github.com/ember-learn/cli-guides [19]: https://www.netlify.com/ <file_sep>In order to mentor and develop leadership skills within the Ember Learning Core Team, it benefits us to have a plan for ensuring we pay attention to the growth within our team. ## Weekly meeting leadership Currently, Todd has been facilitating meetings, with Mel as the backup. One way to share leadership in the learning team is to have rotating meeting leadership responsibilities. ### Responsibilities would include: - set up the agenda on Dropbox, ideally by the Monday of the week of the meeting - Create a document using the `Learn Team Agenda 2019-MM-DD` template - Add link to previous week's meeting - Update the "Every Timezone" link - post the link in the core-learning channel description - act as the meeting facilitator (leading the discussion, ensuring that we stay on track with the agenda & conversation) - extract the public notes and submit them to the GitHub repository for core team notes - synthesize the to-do items into issues in the relevant GitHub repository for tracking ### Schedule It would be beneficial to have a different meeting facilitator every two weeks. At the end of each core team meeting, the meeting facilitator can identify who the next meeting facilitator will be (either themselves for the second week, or ask for a volunteer). We should be roughly striving for equal rotation of willing participants. <file_sep># Domains The domains are managed as part of the Ember brand by Tilde. ## Sub-domains We will employ the use of sub-domains for official Ember projects. Examples: - emberjs.com - guides.emberjs.com - api.emberjs.com - blog.emberjs.com (covers all products; no other sub-domain should have a separate blog) - data.emberjs.com - cli.emberjs.com - engines.emberjs.com Sub-domains are strongly preferred in cases where parts of our sites work best as standalone, separately maintained apps. - It is the best fit for the way that Netlify hosting works and will allow us to maintain service workers independently on separate apps when the time comes. - It’s better for us to use sub-domains because it allows for us to use service workers (via @Todd J ) ## Implementation Process - The source of a website being configured as an official sub-domain must be in the `emberjs`, `ember-learn` or `glimmer` orgs on GitHub. - Anyone with access to the website must use 2FA and have appropriate access rights. This includes 2FA on GitHub, Heroku, Netlify and Fastly. - Our DNS management provider DNSimple provides free SSL certificates via Lets Encrypt. But in cases of providers like Heroku, certs can be created and managed by Heroku. Either way ensure that the new site has SSL setup and that http to https redirects are setup. Netlify manages certs without user intervention. All our sites must run on https and the http to https redirects are setup. - Sites are Ember apps and should endeavour to still work with no JS (with prember/fastboot etc) - We use `yarn` as our package manager unless there’s a technical barrier<file_sep># Ember Releases When a new version of Ember is released, the learning team has to make sure some parts of our infrastructure are adequately updated to account for it. These are: - Guides - API documentation - Release blog post
14184d390e762b398f8892f9ee6629f213b9694d
[ "Markdown" ]
4
Markdown
sdahlbac/handbook
e4d117ca8cfb0b985e77f46f62aea0760d5392bf
c726fa74b0a29f552adc7697062b098bdabfdd61
refs/heads/master
<repo_name>mediact/docker-compose-development-manager<file_sep>/CHANGELOG.md # Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). ## [1.4.4] - Fix issue with AMQP >= 3.9.0 refusing to start with deprecated ENV variable names ## [1.4.3] ### Fixed - Issue resolve issue where newest version after 8.0.28-19. - Change image of nginx-fpm to one where xdebug works out of the box. ## [1.4.2] ### Fixed - Issue where the nginx image was wrongly configured ## [1.4.1] ### Security - [INTAINTD-338] Additionally fixed the port bindings for AMQP in the magento-2 template ## [1.4.0] ### Security - [INTAINTD-338] Forced binding of all exposed ports to localhost (IPv4). Note that if you have IPv6 enabled and using localhost you might need to explicitly use 127.0.0.1 ## [1.3.2] ### Fixed - [INTAINTD-259] Update `magento-2-console` images to latest (supported) version. ## [1.3.1] ### Added - M2: Rabbitmq now has its own `volume` and hostname so queues persist between a `dev down && dev up`. ## [1.3.0] ### Added - Extended PHP environment for generic use that is more inline with the current magento stack. ## [1.2.0] ### Changed - M2: Redis now has its own `volume` so config cache and sessions persist between a `dev down && dev up`. ## [1.1.0] ### Changed - Instead of adding Rabbitmq-server this will also add a UI that can be reached using localhost:15672 in your web browser. ## [1.0.1] ### Changed - Template for M2 now also enables xdebug of composer. - Updated the version of the template for M2 template. - Changed mysql from 5.6 to 5.7 for M1 template. - Changed php from 7.2 to 7.3. ### Removed - Unused variable. <file_sep>/README.md # Introduction This tool allows for loading of environment variables similar to `symfony/dotenv`, only then for Docker Compose environments. Loading environment variable this way should help with a more consistent development process. # Installation Checkout the project and add `dev` to `$PATH`. # Usage Ensure `docker-compose.yml`, `.env` and `.env.dev` are available and configured. Then start the environment with `dev up`. It's possible to install template environments from this project using `dev init`, which will install useful files for a quick setup. # Updating Templates Whenever you update a file for a certain template like magento-2. You should also update the `version` of the `docker-compose.yml`. You can find it here: ```yaml x-custom: version: 1.x.x type: magento-2 ``` Whenever you update a template in a project make sure you revert the custom changes. You know when you have to update the templates when you see the message: ```yaml The current docker template is outdated, please run "dev init TEMPLATE_NAME -f" to update it. ``` <file_sep>/dev #!/usr/bin/env bash # vim: et:sw=2:ts=2:ai # Load environment variables load_env() { # We use "tr" to translate the uppercase "uname" output into lowercase UNAME=$(uname -s | tr '[:upper:]' '[:lower:]') # Then we map the output to the names used on the Github releases page case "$UNAME" in linux*) MACHINE=linux;; darwin*) MACHINE=macos;; mingw*) MACHINE=windows;; esac export MACHINE # OSX requires coreutils if [[ "${MACHINE}" == "macos" ]] && ! which gtouch > /dev/null; then echo "Required tools are missing, please run: brew install coreutils" exit 1 fi if [[ "${MACHINE}" == "macos" ]]; then touch() { gtouch "$@" } fi # Set the default environment export SPECIFIED_ENV=dev # Ensure the docker host is accessible if [[ "${MACHINE}" == "windows" ]]; then HOST_IP=host.docker.internal elif [[ "${MACHINE}" == "macos" ]]; then HOST_IP=host.docker.internal else HOST_IP=$(ip -4 addr show docker0 | grep -Po 'inet \K[\d.]+') fi export HOST_IP # Ensure an SSH socket is available if [[ "$SSH_AUTH_SOCK" == "" ]]; then SSH_AUTH_SOCK="/tmp/.ssh-sock" ssh-agent -a "${SSH_AUTH_SOCK}" fi export SSH_AUTH_SOCK source_env "${APP_PROJECT_PATH}" PROJECT="${APP_PROJECT}" export PROJECT CACHE_DIR="${HOME}/.cache/development-manager-docker-compose" export CACHE_DIR GID=$(id -g) export GID export UID if [[ "${MACHINE}" == "windows" ]]; then DC="winpty docker-compose" CUID="1000" CGID="1000" CHOME="/home/app" else DC="docker-compose" CUID="${UID}" CGID="${GID}" CHOME="${HOME}" fi export CUID export CGID export CHOME } function parse_yaml { local prefix=$2 local s='[[:space:]]*' w='[a-zA-Z0-9_\-]*' fs=$(echo @|tr @ '\034') sed -ne "s|^\($s\):|\1|" \ -e "s|^\($s\)\($w\)$s:$s[\"']\(.*\)[\"']$s\$|\1$fs\2$fs\3|p" \ -e "s|^\($s\)\($w\)$s:$s\(.*\)$s\$|\1$fs\2$fs\3|p" $1 | awk -F$fs '{ indent = length($1)/2; vname[indent] = $2; for (i in vname) {if (i > indent) {delete vname[i]}} if (length($3) > 0) { vn=""; for (i=0; i<indent; i++) {vn=(vn)(vname[i])("_")} sub(/-/, "_", vn) sub(/-/, "_", $2) printf("%s%s%s=\"%s\"\n", "'$prefix'",vn, $2, $3); } }' } source_env() { # Configure .env files local env="${1}/.env" local env_local="${1}/.env.local" # Load all variables as if they are exported set -a # Check and load if environment .env file exists # shellcheck source=.env if [ -e "$env" ]; then source "$env" fi # Check and load if environment local .env file exists # shellcheck source=.env.local if [ -e "$env_local" ]; then source "$env_local" fi # Configure .env files for specified SPECIFIED_ENV local specified_env="${1}/.env.${SPECIFIED_ENV}" local specified_env_local="${1}/.env.${SPECIFIED_ENV}.local" # Check and load if environment specific .env file exists # shellcheck source=.env.dev if [ -e "$specified_env" ]; then source "$specified_env" fi # Check and load if environment specific local .env file exists # shellcheck source=.env.dev.local if [ -e "$specified_env_local" ]; then source "$specified_env_local" fi # Don't automatically export set variables set +a } # Container for all supported commands run() { # Initialize primary variables APP_SELF_PATH=$(dirname "$(realpath "$0")") APP_PROJECT_PATH=$(pwd) APP_PROJECT=$(basename "${APP_SELF_PATH}") # Turn on and attach to specified container attach() { $DC up "$1" return $? } # Check system and update if marked old autoupdate() { local cache_limit local cache_project local cache_tool cache_limit="${CACHE_DIR}/limit" cache_project="${CACHE_DIR}/$(pwd | base64)" cache_tool="${CACHE_DIR}/dev" # Ensure cache directory exists test ! -d "${CACHE_DIR}" && mkdir -p "${CACHE_DIR}" # Remove old cache files find "${CACHE_DIR}" -type f -mtime +1 -delete # Set limit of last check touch -d '-16 hours' "${cache_limit}" # Ensure a last check file exists test ! -f "${cache_project}" && touch -d '-17 hours' "${cache_project}" # Ensure a last check file exists test ! -f "${cache_tool}" && touch -d '-17 hours' "${cache_tool}" # Check if the last check exceeds the given limit if [ "${cache_limit}" -nt "${cache_project}" ]; then touch "${cache_project}" echo "Checking if new images are available ..." # Run the pull command and download images if available pull fi # Check if the last check exceeds the given limit if [ "${cache_limit}" -nt "${cache_tool}" ]; then touch "${cache_tool}" # Run the self update command selfupdate fi check } # Open the shell of a container console() { autoupdate local shell="console" [ "$1" != "" ] && shell=$1 $DC run \ --rm \ -u "$(id -u):$(id -g)" \ --no-deps \ "$shell" return $? } # Checks whether the current template version of the project is still the latest check() { if [ -e "docker-compose.yml" ] || [ -e "docker-compose.yaml" ]; then if [ -e "docker-compose.yml" ]; then eval "$(parse_yaml docker-compose.yml "COMPOSE_VAR_")" &> /dev/null elif [ -e "docker-compose.yaml" ]; then eval "$(parse_yaml docker-compose.yaml "COMPOSE_VAR_")" &> /dev/null fi if [ -n "${COMPOSE_VAR_x_custom_type}" ]; then local latestFilePath latestFilePath="${APP_SELF_PATH}/templates/${COMPOSE_VAR_x_custom_type}/docker-compose.yml" eval "$(parse_yaml $latestFilePath "COMPOSE_LATEST_VAR_")" &> /dev/null if [ -n "${COMPOSE_VAR_x_custom_version}" ] || [ -n "${COMPOSE_LATEST_VAR_x_custom_version}" ] && [ "${COMPOSE_LATEST_VAR_x_custom_version}" != "${COMPOSE_VAR_x_custom_version}" ]; then echo "The current docker template is outdated, please run \"dev init ${COMPOSE_VAR_x_custom_type} -f\" to update it." else echo "The current docker template is up-to-date." fi else echo "The current docker template is outdated, please run \"dev init TEMPLATE_NAME -f\" to update it." fi fi } # Run a Docker Compose command dc() { $DC "$@" return $? } # Turn off all containers or a specific container down() { # If there is a docker-compose file present in the current directory, use the default. if [ -e "docker-compose.yml" ] || [ -e "docker-compose.yaml" ]; then $DC down "$@" else if [ -e "${CACHE_DIR}/known_locations" ]; then while read -r location do if [ -e "${location}/docker-compose.yml" ]; then source_env "${location}" $DC -f "${location}/docker-compose.yml" down "$@" fi done < "${CACHE_DIR}/known_locations" fi fi return $? } # Execute a command on a specified container exec() { $DC exec "$@" return $? } # Get help for commands help() { attach() { echo "Attach to a container." echo "Usage: $0 attach <container-name>" return 0 } console() { echo "Open up a console on a service." echo "Usage: $0 console [service]" echo "Options:" echo " service: Defaults to console" echo "Available services:" load_env $DC ps --services | xargs echo " " return 0 } check() { echo "Check whether the currently used template is up-to-date." return 0 } dc() { echo "Execute a Docker Compose command directly, using configured .env* files." echo "Usage: $0 dc [options...]" return 0 } down() { echo "Turn off development environment." echo "Usage: $0 down [options...]" echo "For more info, see: docker-compose help down" return 0 } exec() { echo "Execute a command on a specified container" echo "Usage: $0 exec <container> <command> [options...]" echo "Example: $0 exec redis redis-cli flushall" echo "For more info, see: docker-compose help exec" return 0 } init() { echo "Initialize a project type for development." echo "Usage: $0 init [-f|--force] <project-type>" echo "Available project types: " for type in "${APP_SELF_PATH}"/templates/*; do echo "- $(basename "${type}")" done return 0 } logs() { echo "Display container output logs." echo "Usage: $0 logs [-f] [service]" echo "For more info, see: docker-compose help logs" return 0 } ps() { echo "Display container status for current project" echo "Usage: $0 ps" echo "For more info, see: docker-compose help ps" return 0 } pull() { echo "Pull latest development environment images." echo "Usage: $0 pull" echo "For more info, see: docker-compose help pull" return 0 } run() { echo "Run a command on the development environment." echo "Usage: $0 run <command>" echo "For more info, see: docker-compose help run" return 0 } selfupdate() { echo "Run self update." echo "Usage: $0 selfupdate" return 0 } up() { echo "Turn on development environment." echo "Usage: $0 up [options...]" echo "For more info, see: docker-compose help up" return 0 } # Attempt to run a command or output the help if [ "$(type -t "$1")" == "function" ]; then "$@" return $? else echo "Usage: $0 <option>" echo "The following options are available" echo " console: Open the console" echo " dc: Execute a Docker Compose command" echo " down: Stop the environment" echo " exec: Execute a command on a container" echo " init: Initialize a project based on a template" echo " logs: Display container output logs" echo " ps: Display container status" echo " pull: Pull latest images" echo " run: Run a command" echo " selfupdate: Run self update" echo " up: Start the environment" fi return $? } # Initialize a project type for development # shellcheck disable=SC2120 init() { local force=0 local type="" for option in "$@"; do case "$option" in -f|--force) force=1 ;; *) if [ "$type" == "" ]; then type="$option" fi ;; esac done if [ "${type}" == "" ]; then echo "Error: Type not given" help init exit 1 fi if [ ! -e "${APP_SELF_PATH}"/templates/"${type}" ]; then echo "Error: Type '$type' not found." exit 1 fi if [ ! -e "${APP_PROJECT_PATH}/docker-compose.yml" ] && [ ! -e "${APP_PROJECT_PATH}/docker-compose.yaml" ] || [ "$force" == "1" ]; then cp -prf "${APP_SELF_PATH}"/templates/"${type}"/* "${APP_PROJECT_PATH}" cp -prf "${APP_SELF_PATH}"/templates/"${type}"/.[!.]* "${APP_PROJECT_PATH}" echo "Initialized $type project." return $? elif [ -e "${APP_PROJECT_PATH}/docker-compose.yml" ] || [ -e "${APP_PROJECT_PATH}/docker-compose.yaml" ]; then echo "Warning: Project already initialized. Use --force to re-initialize the project" exit 1 fi run help init exit 1 } # Show container output logs logs() { $DC logs "$@" return $? } # Show container status ps() { $DC ps "$@" return $? } # Pull latest images pull() { $DC pull "$@" return $? } # Run a command run() { autoupdate $DC run console "$@" return $? } # Try to self update selfupdate() { # shellcheck disable=SC2164 pushd "${APP_SELF_PATH}" > /dev/null git pull origin master chmod +x "$0" # shellcheck disable=SC2164 popd > /dev/null } # Turn on all containers or a specific container up() { autoupdate if ! grep -qxF $(pwd) "${CACHE_DIR}/known_locations" &> /dev/null; then pwd >> "${CACHE_DIR}/known_locations" fi $DC up -d "$@" return $? } # Attempt to run a command or output the help if [ "$(type -t "$1")" == "function" ]; then if [ "$1" == "init" ] || [ "$1" == "help" ] || load_env; then "$@" fi return $? else help "$@" return 1 fi } # Main process execution main() { # Ensure root does not use this if [[ "$(id -u)" == "0" ]]; then echo "This script should not be run as root." exit 1 fi # Ensure this is not executed from a docker container if [[ -e /proc/1/cgroup ]] && grep -c docker /proc/1/cgroup > /dev/null; then echo "This script should not be run from a docker container." exit 1 fi # Run the tool run "$@" exit $? } # Run the manager main "$@" <file_sep>/templates/magento-2/env-dev.php <?php return [ 'backend' => [ 'frontName' => getenv('BACKEND__FRONT_NAME'), ], 'crypt' => [ 'key' => getenv('CRYPT__KEY'), ], 'db' => [ 'connection' => [ 'indexer' => [ 'host' => getenv('DB__CONNECTION__INDEXER__HOST'), 'dbname' => getenv('DB__CONNECTION__INDEXER__DBNAME'), 'username' => getenv('DB__CONNECTION__INDEXER__USERNAME'), 'password' => getenv('<PASSWORD>CONNECTION__INDEXER__PASSWORD'), 'model' => 'mysql4', 'engine' => 'innodb', 'initStatements' => 'SET NAMES utf8;', 'active' => '1', 'persistent' => null, ], 'default' => [ 'host' => getenv('DB__CONNECTION__DEFAULT__HOST'), 'dbname' => getenv('DB__CONNECTION__DEFAULT__DBNAME'), 'username' => getenv('DB__CONNECTION__DEFAULT__USERNAME'), 'password' => getenv('<PASSWORD>'), 'model' => 'mysql4', 'engine' => 'innodb', 'initStatements' => 'SET NAMES utf8;', 'active' => '1', ], ], 'table_prefix' => '' ], 'resource' => [ 'default_setup' => [ 'connection' => 'default', ], ], 'session' => [ 'save' => 'redis', 'redis' => [ 'host' => getenv('SESSION__REDIS__HOST'), 'port' => getenv('SESSION__REDIS__PORT'), 'password' => getenv('<PASSWORD>'), 'timeout' => '2.5', 'persistent_identifier' => '', 'database' => getenv('SESSION__REDIS__DATABASE'), 'compression_threshold' => '2048', 'compression_library' => 'gzip', 'log_level' => '1', 'max_concurrency' => '6', 'break_after_frontend' => '5', 'break_after_adminhtml' => '30', 'first_lifetime' => '600', 'bot_first_lifetime' => '600', 'bot_lifetime' => '60', 'disable_locking' => '0', 'min_lifetime' => '60', 'max_lifetime' => '2592000', 'sentinel_master' => '', 'sentinel_servers' => '', 'sentinel_connect_retries' => '5', 'sentinel_verify_master' => '0', ] ], 'x-frame-options' => 'SAMEORIGIN', 'cache_types' => [ 'config' => 1, 'layout' => 1, 'block_html' => 1, 'collections' => 1, 'reflection' => 1, 'db_ddl' => 1, 'compiled_config' => 1, 'eav' => 1, 'customer_notification' => 1, 'config_integration' => 1, 'config_integration_api' => 1, 'target_rule' => 1, 'google_product' => 1, 'full_page' => 1, 'config_webservice' => 1, 'translate' => 1, 'vertex' => 1, ], 'install' => [ 'date' => '$(date -R)', ], 'queue' => [ 'amqp' => [ 'host' => getenv('QUEUE__AMQP__HOST'), 'port' => getenv('QUEUE__AMQP__PORT'), 'user' => getenv('QUEUE__AMQP__USER'), 'password' => getenv('QUEUE__AMQP__PASSWORD'), 'virtualhost' => getenv('QUEUE__AMQP__VIRTUALHOST'), ], ], 'http_cache_hosts' => [ 0 => [ 'host' => getenv('HTTPS_CACHE_HOSTS__0__HOST'), 'port' => getenv('HTTPS_CACHE_HOSTS__0__PORT'), ], ], 'cache' => [ 'frontend' => [ 'default' => [ 'id_prefix' => '40d_', 'backend' => 'Cm_Cache_Backend_Redis', 'backend_options' => [ 'server' => getenv('CACHE__FRONTEND__DEFAULT__BACKEND_OPTIONS__HOST'), 'port' => getenv('CACHE__FRONTEND__DEFAULT__BACKEND_OPTIONS__PORT'), 'database' => getenv('CACHE__FRONTEND__DEFAULT__BACKEND_OPTIONS__DATABASE'), 'password' => getenv('CACHE__FRONTEND__DEFAULT__BACKEND_OPTIONS__PASSWORD'), 'compress_data' => '1', 'compression_lib' => '', ], ], 'page_cache' => [ 'id_prefix' => '40d_', 'backend' => 'Cm_Cache_Backend_Redis', 'backend_options' => [ 'server' => getenv('CACHE__FRONTEND__PAGE_CACHE__BACKEND_OPTIONS__HOST'), 'port' => getenv('CACHE__FRONTEND__PAGE_CACHE__BACKEND_OPTIONS__PORT'), 'database' => getenv('CACHE__FRONTEND__PAGE_CACHE__BACKEND_OPTIONS__DATABASE'), 'password' => getenv('<PASSWORD>'), 'compress_data' => '0', 'compression_lib' => '', ], ], ], ], 'system' => [ 'default' => [ 'twofactorauth' => [ 'general' => [ 'disabled_users' => 'mediact*' ] ] ] ] ]; <file_sep>/templates/basic-php/docker-compose.yml # vim: ai:ts=2:sw=2:et version: "3.4" networks: {} volumes: db-data: db-logs: x-custom: type: basic-php version: 1.1.0 environment: &env-vars # Environment settings - "HOME=${CHOME}" - COMPOSER_MEMORY_LIMIT - XDEBUG_CONFIG - SSH_AUTH_SOCK # Database settings - DB_HOST - DB_USER - DB_PASS - DB_NAME - MYSQL_PORT services: console: image: "chialab/php:${PHP_VERSION}" command: sh user: "${CUID}:${CGID}" links: - db - redis network_mode: bridge environment: *env-vars working_dir: "${PWD}" volumes: - "${HOME}:${CHOME}" - "${PWD}:${PWD}" - "${SSH_AUTH_SOCK}:${SSH_AUTH_SOCK}" - /etc/group:/etc/group:ro - /etc/passwd:/etc/passwd:ro - /etc/shadow:/etc/shadow:ro db: image: percona:5.7 environment: - MYSQL_ROOT_PASSWORD ports: - "127.0.0.1:${MYSQL_PORT}:3306" network_mode: bridge volumes: - db-data:/var/lib/mysql:rw - db-logs:/var/logs/mysql:rw redis: image: redis:5.0-alpine network_mode: bridge web: image: nginx:alpine links: - worker network_mode: bridge ports: - "127.0.0.1:${WEB_PORT_HTTP}:80" volumes: - "${PWD}:/var/www/html:ro" - ./nginx.conf:/etc/nginx/conf.d/default.conf:ro worker: image: "chialab/php:${PHP_VERSION}-fpm" user: "${CUID}:${CGID}" links: - db - redis network_mode: bridge environment: *env-vars volumes: - "${PWD}:/var/www/html:rw" - /etc/group:/etc/group:ro - /etc/passwd:/etc/passwd:ro - /etc/shadow:/etc/shadow:ro
d820195e861f5bf5d12ce191f795defa5680f80f
[ "Markdown", "Shell", "YAML", "PHP" ]
5
Markdown
mediact/docker-compose-development-manager
dac34aac7dacdd2b88cc3e027ea384bd505a8c37
ae9697427b3dd651e15517dd24ef6272ed73776e
refs/heads/master
<file_sep>//initialize function called when the script loads function initialize(){ cities(); }; //function to create a table with cities and their populations function cities(){ //define two arrays for cities and population var cityPop = [ { city: 'Madison', population: 233209 }, { city: 'Milwaukee', population: 594833 }, { city: 'Green Bay', population: 104057 }, { city: 'Superior', population: 27244 }, { city: 'Boston', population: 655884 }, { city: 'San Francisco', population: 852469 }, { city: 'New York City', population: 8491079 }, { city: 'Nouakchott', population: 2000000 } ]; //append the table element to the div $("#mydiv").append("<table>"); //append a header row to the table $("table").append("<tr>"); //add the "City" and "Population" columns to the header row $("tr").append("<th>City</th><th>Population</th>"); //loop to add a new row for each city for (var i = 0; i < cityPop.length; i++){ //assign longer html strings to a variable var rowHtml = "<tr><td>" + cityPop[i].city + "</td><td>" + cityPop[i].population + "</td></tr>"; //add the row's html string to the table $("table").append(rowHtml); console.log("This is working"); }; // Now, we'll declare the addColumns function function addColumns(cityPop){ //Let's make sure it works console.log("This is working too"); //Loop through each table row using .each method $('tr').each(function(i){ console.log(cityPop) // when i is in position 0, we want a table heading "city size" if (i == 0){ //"append" originally spelled "apend", needed fix $(this).append('<th>City Size</th>'); //otherwise, let's go through the rest of the rows } else { // set variable var citySize; // take into account that the first row is a header if (cityPop[i-1].population < 100000){ //classify local variable citySize = 'Small'; //console.log(i); //console.log(cityPop[i-1].population); } else if (cityPop[i-1].population < 500000){ //"citySize" originally spelled "citysize", needed fix //re-classify variable (local) citySize = 'Medium'; //console.log(i); //console.log(cityPop[i-1].population); } else { // re-classify citySize = 'Large'; //console.log(i); //console.log(cityPop[i-1].population); }; //Missing parenthesis around $this, missing < ? $(this).append('<td>' + citySize + '</td>'); }; }); }; //Call the function addColumns(cityPop) //this is the beginning of the color function // Declare addEvents function function addEvents(){ // utlize mouseover method - function executed upon mouseover event $('table').mouseover(function(){ // set color variable to rgb(some random colors here) var color = "rgb("; // do a loop through three random numbers for (var i=0; i<3; i++){ // set a random variable var random = Math.round(Math.random() * 255); // add each iteration to color variable color += random; // when number is in first two positions, add comma if (i<2){ color += ","; // if not, we know it's last, and close the parenthesis w/ quote } else { color += ")"; }; } // use 'this' method to set style using css style $(this).css('color', color); }); } //this is the end of the color function //let's call the addEvents function addEvents() //This is the beginning of the click function, with slightly edited syntax // too many brackets in original debug.js // when table clicked, execute one-time function (removed name) $('table').on('click', function (){ // function executes the alert command alert('Hey, you clicked me!'); }); //this is the end of the "clickme!" function }; //call the initialize function when the document has loaded $(document).ready(initialize); // this is me trying to figure out javascript var btn = document.createElement("BUTTON"); var btn_text = document.createTextNode("Click me!"); btn.appendChild(btn_text); document.body.appendChild(btn); $(btn).append(" Please!"); $(btn).on('click', function(){ alert('This table is super dope'); }); var para = document.getElementById("para1"); var node = document.createTextNode("This is text"); para.appendChild(node); document.getElementById("para1").innerHTML = "Please enjoy it" document.getElementById("list1").innerHTML = "This is Starr's Webpage," jQuery('#para1').html("Welcome.") var list3 = document.createElement("li") para1.appendChild(list3); //goodbye console.log("start of ajax") //We'll call an AJAX function function jQueryAjax(){ //defining a variable to hold the data var mydata; //here is the jQuery ajax method, where we want to pull our data from a file $.ajax("data/MegaCities.GeoJSON", { // dataType is first parameter: our data type dataType: "json", // success is our second parameter: success starts the callback function success: function(response){ // response is the first and most important parameter of callback function: your data mydata = response; //Here, we'll console.log the data - which will appear as an array of objects because it's read within the function //Array appears in the console, but only after the initial console log reads undefined console.log(mydata); } }); //will read "undefined" in console message- the variable written outside the function. // This will be executed before callback function, so will appear empty! console.log(mydata); }; //Let's call the function jQueryAjax() console.log("end of script") //This is the debugAjax function function debugAjax(){ //This is the ajax query method. We request the GeoJSON MegaCities file $.ajax("data/MegaCities.GeoJSON", { //first parameter dataType is set to JSON (file-type of MegaCites) dataType: "json", //success is the second parameter: this initiates the callback function success: function(response){ //we nest the command within the callback function //the command tells us to append the GeoJSON file to the div, with line breaks $("#mydiv").append('<br>GeoJSON data:<br>' + JSON.stringify(response)); } }); }; //Once the document is ready, we'll call the debugAjax function $(document).ready(debugAjax);
7ac339e3e2303a5b4067587c72e75b9c959f9df0
[ "JavaScript" ]
1
JavaScript
shmoss/my_website
cb8ae9e8c1b9ae36e6ab6a968cee9c9ac53504bb
06a56b2acce6ae2c90cdb3c88bc81aa6bbc17eba
refs/heads/master
<file_sep>using System; using System.ComponentModel; //using System.Net; //using System.Windows; //using System.Windows.Controls; //using System.Windows.Documents; //using System.Windows.Ink; //using System.Windows.Input; //using System.Windows.Media; //using System.Windows.Media.Animation; //using System.Windows.Shapes; namespace WageCalculator.Model { public class Salary : INotifyPropertyChanged { private decimal _baseSalary; public decimal BaseSalary { get { return _baseSalary; } set { PropertyChanged.ChangeAndNotify(ref _baseSalary, value, () => BaseSalary); // _baseSalary = value; } } // Possible interface private decimal _deductionPercentage; public decimal DeductionPercentage { get { return _deductionPercentage; } set { if (_deductionPercentage == value) return; PropertyChanged.ChangeAndNotify(ref _deductionPercentage, value, () => DeductionPercentage); } } private decimal _weeklyWages; public decimal WeeklyWages { get { return _weeklyWages; } set { value = _baseSalary / 52; PropertyChanged.ChangeAndNotify(ref _weeklyWages, value, () => WeeklyWages); // _weeklyWages = value; } } private decimal _hourlyRate; public decimal HourlyRate { get { return _hourlyRate; } set { value = _weeklyWages / 40; PropertyChanged.ChangeAndNotify(ref _hourlyRate, value, () => HourlyRate); // _hourlyRate = value; } } public Salary() { } public event PropertyChangedEventHandler PropertyChanged = null; // public event PropertyChangingEventHandler PropertyChanging; } } <file_sep>using System; using System.ComponentModel; //using System.Net; //using System.Windows; //using System.Windows.Controls; //using System.Windows.Documents; //using System.Windows.Ink; //using System.Windows.Input; //using System.Windows.Media; //using System.Windows.Media.Animation; //using System.Windows.Shapes; namespace WageCalculator.Model { public class Hourly : INotifyPropertyChanged { // THe Base Hourly Rate - no overtime private decimal _baseHourlyRate; public decimal BaseHourlyRate { get { return _baseHourlyRate; } set { if (_baseHourlyRate == value) return; PropertyChanged.ChangeAndNotify(ref _baseHourlyRate, value, () => BaseHourlyRate); } } private decimal _weeklyPay; public decimal WeeklyPay { get { return _weeklyPay * _baseHourlyRate; } set { PropertyChanged.ChangeAndNotify(ref _weeklyPay, value, () => WeeklyPay); } } private readonly decimal _overTimeRate; public decimal OverTimeRate { get { return _overTimeRate * _baseHourlyRate; } } private decimal _annualSalary; public decimal AnnualSalary { get { return _annualSalary; } set { PropertyChanged.ChangeAndNotify(ref _annualSalary, value, () => AnnualSalary); } } private decimal _deductionPercentage; public decimal DeductionPercentage { get { return _deductionPercentage; } set { if (_deductionPercentage == value) return; PropertyChanged.ChangeAndNotify(ref _deductionPercentage, value, () => DeductionPercentage); } } // How much Gov't or Elected deductions to remove private decimal _postDeductionSalary; public decimal PostDeductionSalary { get { return _postDeductionSalary; } set { PropertyChanged.ChangeAndNotify(ref _postDeductionSalary, value, () => PostDeductionSalary); } } public Hourly() { _overTimeRate = 1.50M; } private void RaisePropertyChanged(string name) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(name)); } public event PropertyChangedEventHandler PropertyChanged = null; //public event PropertyChangingEventHandler PropertyChanging; } } <file_sep>using System; using System.Collections.ObjectModel; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; namespace WageCalculator.Model { public class MultiColumnStackPanel : StackPanel { public int NumberOfColumns { get; set; } public static readonly DependencyProperty ItemsProperty = DependencyProperty.Register("Items", typeof(Collection<UIElement>), typeof(MultiColumnStackPanel), new PropertyMetadata(new Collection<UIElement>())); public Collection<UIElement> Items { get { return (Collection<UIElement>)GetValue(ItemsProperty); } } public MultiColumnStackPanel() { Orientation = Orientation.Vertical; Loaded += (s, e) => LoadItems(); } private void LoadItems() { Children.Clear(); if (Items == null) return; StackPanel sp = CreateNewStackPanel(); foreach (UIElement item in Items) { sp.Children.Add(item); if (sp.Children.Count == NumberOfColumns) { Children.Add(sp); sp = CreateNewStackPanel(); } } if (sp.Children.Count > 0) Children.Add(sp); } private static StackPanel CreateNewStackPanel() { return new StackPanel() { Orientation = Orientation.Horizontal }; } } } <file_sep>using System; using System.Windows; using Microsoft.Phone.Controls; using System.Windows.Interactivity; //using System.Net; //using System.Windows.Controls; //using System.Windows.Documents; //using System.Windows.Ink; //using System.Windows.Input; //using System.Windows.Media; //using System.Windows.Media.Animation; //using System.Windows.Shapes; namespace WageCalculator.Model { public class SelectAllTextBoxBehavior : Behavior<PhoneTextBox> { protected override void OnAttached() { base.OnAttached(); AssociatedObject.GotFocus += new RoutedEventHandler(AssociatedObject_GotFocus); } void AssociatedObject_GotFocus(object sender, RoutedEventArgs e) { ((PhoneTextBox)sender).SelectAll(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Windows; using Microsoft.Phone.Controls; using Microsoft.Phone.Tasks; //using System.IO.IsolatedStorage; //using System.Net; //using System.Windows.Controls; //using System.Windows.Documents; //using System.Windows.Input; //using System.Windows.Media; //using System.Windows.Media.Animation; //using System.Windows.Navigation; //using System.Windows.Shapes; //using System.Diagnostics; //using WageCalculator.ViewModel; namespace WageCalculator.Views { public partial class HourlySalaryPivotPage : PhoneApplicationPage { public HourlySalaryPivotPage() { InitializeComponent(); } private void ContactHyperlinkButton_Click(object sender, RoutedEventArgs e) { try { EmailComposeTask emailComposeTask = new EmailComposeTask(); emailComposeTask.To = "<EMAIL>"; emailComposeTask.Body = string.Empty; emailComposeTask.Subject = "The Wagenator (ver 1.5.0.2) - Support and Feedback"; emailComposeTask.Show(); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK); } } private void SMSContactHyperlinkButton_Click(object sender, RoutedEventArgs e) { try { SmsComposeTask smsComposeTask = new SmsComposeTask(); smsComposeTask.To = "<EMAIL>"; smsComposeTask.Body = "RE: The Wagenator v1.5.0.2 - "; smsComposeTask.Show(); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK); } } private void MarketplaceReviewButton_Click(object sender, RoutedEventArgs e) { try { MarketplaceReviewTask marketplaceReviewTask = new MarketplaceReviewTask(); marketplaceReviewTask.Show(); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK); } } private void MarketplaceSearchHyperlinkButton_Click(object sender, RoutedEventArgs e) { try { MarketplaceSearchTask marketplaceSearchTask = new MarketplaceSearchTask(); marketplaceSearchTask.SearchTerms = "J3nius"; marketplaceSearchTask.Show(); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK); } } private void PrivacyPolicyHyperlinkButton_Click(object sender, RoutedEventArgs e) { MessageBox.Show("Neither personal nor location services data is stored or shared. To disable the usage of location services, " + "turn off location services in your phone's settings.", "Privacy policy", MessageBoxButton.OK); } } }<file_sep>using System; using GalaSoft.MvvmLight; using WageCalculator.Model; //using System.ComponentModel; namespace WageCalculator.ViewModel { /// <summary> /// This class contains properties that a View can data bind to. /// <para> /// Use the <strong>mvvminpc</strong> snippet to add bindable properties to this ViewModel. /// </para> /// <para> /// You can also use Blend to data bind with the tool's support. /// </para> /// <para> /// See http://www.galasoft.ch/mvvm/getstarted /// </para> /// </summary> public class HourlySalaryViewModel : ViewModelBase { /// <summary> /// Initializes a new instance of the HourlySalaryViewModel class. /// </summary> public HourlySalaryViewModel() { ////if (IsInDesignMode) ////{ //// // Code runs in Blend --> create design time data. ////} ////else ////{ //// // Code runs "for real": Connect to service, etc... ////} _hourly = new Hourly(); // Initialize Hourly Model to ViewModel _dFontSize = 22D; // Default font size _IsNotFullTime = false; _IsHoursDisplayValueEnabled = false; _HoursDisplayValue = 40.0M; // hours worked _hoursContentValue = "Full Time"; _IsNotFullYear = false; _IsWeeksDisplayValueEnabled = false; _WeeksDisplayValue = 52; // 1 year _weeksContentValue = "Full Year"; _salary = new Salary(); // Initialize Salary Model to ViewModel _IsSalNotFullTime = false; _IsSalHoursDisplayValueEnabled = false; _SalHoursDisplayValue = 40.0M; // hours worked _SalHoursContentValue = "Full Time"; _IsSalNotFullYear = false; _IsSalWeeksDisplayValueEnabled = false; _SalWeeksDisplayValue = 52; // 1 year _SalWeeksContentValue = "Full Year"; // Cori Code //Recalculate(); //SalRecalculate(); } ////public override void Cleanup() ////{ //// // Clean own resources if needed //// base.Cleanup(); ////} #region Hourly // Hourly private readonly Hourly _hourly; public Hourly Hourly { get { return _hourly; } } private double _dFontSize; public double dFontSize { get { return _dFontSize; } set { if (_dFontSize == value) return; _dFontSize = value; RaisePropertyChanged("dFontSize"); Recalculate(); } } private bool _IsNotFullTime; public bool IsNotFullTime { get { return _IsNotFullTime; } set { if (_IsNotFullTime == value) return; _IsNotFullTime = value; RaisePropertyChanged("IsNotFullTime"); //Recalculate(); //Cori Code RaisePropertyChanged("IsFullTime"); Recalculate(); } } //Cori Code public bool IsFullTime { get { return !_IsNotFullTime; } set { if (!_IsNotFullTime == value) return; _IsNotFullTime = !value; RaisePropertyChanged("IsNotFullTime"); RaisePropertyChanged("IsFullTime"); Recalculate(); } } private string _hoursContentValue; public string HoursContentValue { get { return _hoursContentValue; } set { if (_hoursContentValue == value) return; _hoursContentValue = value; RaisePropertyChanged("HoursContentValue"); Recalculate(); } } private bool _IsNotFullYear; public bool IsNotFullYear { get { return _IsNotFullYear; } set { if (_IsNotFullYear == value) return; _IsNotFullYear = value; RaisePropertyChanged("IsNotFullYear"); RaisePropertyChanged("IsFullYear"); // Cori Code Recalculate(); } } // Cori Code public bool IsFullYear { get { return !IsNotFullYear; } set { if (!_IsNotFullYear == value) return; _IsNotFullYear = !value; RaisePropertyChanged("IsNotFullYear"); RaisePropertyChanged("IsFullYear"); Recalculate(); } } private string _weeksContentValue; public string WeeksContentValue { get { return _weeksContentValue; } set { if (_weeksContentValue == value) return; _weeksContentValue = value; RaisePropertyChanged("WeeksContentValue"); Recalculate(); } } private bool _IsHoursDisplayValueEnabled; public bool IsHoursDisplayValueEnabled { get { return _IsHoursDisplayValueEnabled; } set { if (_IsHoursDisplayValueEnabled == value) return; _IsHoursDisplayValueEnabled = value; RaisePropertyChanged("IsHoursDisplayValueEnabled"); Recalculate(); } } private bool _IsWeeksDisplayValueEnabled; public bool IsWeeksDisplayValueEnabled { get { return _IsWeeksDisplayValueEnabled; } set { if (_IsWeeksDisplayValueEnabled == value) return; _IsWeeksDisplayValueEnabled = value; RaisePropertyChanged("IsWeeksDisplayValueEnabled"); Recalculate(); } } private decimal _HoursDisplayValue; public decimal HoursDisplayValue { get { return _HoursDisplayValue; } set { if (_HoursDisplayValue == value) return; // Verify that the number of hours entered are in range of 0 and 40 (enhance for overtime) if (value < 0M) value = 0M; if (value > 40M) value = 40M; _HoursDisplayValue = value; RaisePropertyChanged("HoursDisplayValue"); Recalculate(); } } private int _WeeksDisplayValue; public int WeeksDisplayValue { get { return _WeeksDisplayValue; } set { if (_WeeksDisplayValue == value) return; // Verify that the number of weeks entered are in range of 0 and 52 if (value < 0) value = 0; if (value > 52) value = 52; _WeeksDisplayValue = value; RaisePropertyChanged("WeeksDisplayValue"); Recalculate(); } } public decimal BaseHourlyRate { get { return _hourly.BaseHourlyRate; } set { if (_hourly.BaseHourlyRate == value) return; // Verify that the rate entered isn't less than 0 // Verify that the hourly rate entered isn't less than 0 nor greater than 480,769.23 if (value < 0) value = 0; if (value > 480769.23M) value = 480769.23M; _hourly.BaseHourlyRate = value; // Reduce the FontSize if the Base Hourly Rate is larger than $9995. dFontSize = _hourly.BaseHourlyRate < 9995.0M ? 22D : 20.5D; Recalculate(); } } public decimal DeductionPercentage { get { return _hourly.DeductionPercentage; } set { if (_hourly.DeductionPercentage == value) return; // Verify that the deduction percentage is in range of 0 and 100 if (value < 0M) value = 0M; if (value > 100M) value = 100M; _hourly.DeductionPercentage = value; RaisePropertyChanged("DeductionPercentage"); Recalculate(); } } public string BaseHourlyRateText { get { return String.Format("{0:C2}", BaseHourlyRate); } } public decimal BaseHourlyRateDeduction { get { return BaseHourlyRate - (BaseHourlyRate * (DeductionPercentage / 100)); } } public string BaseHourlyRateDeductionText { get { return String.Format("{0:C2}", BaseHourlyRateDeduction); } } public decimal OverTimeHourlyRate { get { return _hourly.OverTimeRate; } } public string OverTimeHourlyRateText { get { return String.Format("{0:C2}", OverTimeHourlyRate); } } public decimal OverTimeHourlyRateDeduction { get { return OverTimeHourlyRate - (OverTimeHourlyRate * (DeductionPercentage / 100)); } } public string OverTimeHourlyRateDeductionText { get { return String.Format("{0:C2}", OverTimeHourlyRateDeduction); } } public decimal WeeklyPay { get { return _hourly.BaseHourlyRate * _HoursDisplayValue; } } public string WeeklyPayText { get { return String.Format("{0:C2}", WeeklyPay); } } public decimal WeeklyPayDeduction { get { return WeeklyPay - (WeeklyPay * (DeductionPercentage / 100)); } } public string WeeklyPayDeductionText { get { return String.Format("{0:C2}", WeeklyPayDeduction); } } public decimal BiWeeklyPay { get { return _hourly.BaseHourlyRate * _HoursDisplayValue * 2; } } public string BiWeeklyPayText { get { return String.Format("{0:C2}", BiWeeklyPay); } } public decimal BiWeeklyPayDeduction { get { return BiWeeklyPay - (BiWeeklyPay * (DeductionPercentage / 100)); } } public string BiWeeklyPayDeductionText { get { return String.Format("{0:C2}", BiWeeklyPayDeduction); } } public decimal AnnualSalary { get { return _hourly.BaseHourlyRate * _HoursDisplayValue * _WeeksDisplayValue; } } public string AnnualSalaryText { get { return String.Format("{0:C2}", AnnualSalary); } } public decimal AnnualSalaryDeduction { get { return AnnualSalary - (AnnualSalary * (DeductionPercentage / 100)); } } public string AnnualSalaryDeductionText { get { return String.Format("{0:C2}", AnnualSalaryDeduction); } } private void Recalculate() // check for changes { RecalculateHours(IsNotFullTime); RecalculateWeeks(IsNotFullYear); } private void RecalculateWeeks(bool fullYear) { IsWeeksDisplayValueEnabled = fullYear; if (!fullYear) { WeeksDisplayValue = 52; WeeksContentValue = "Full Year"; } else { WeeksContentValue = "Custom Year"; } UpdateProperties(); } private void RecalculateHours(bool fullTime) { IsHoursDisplayValueEnabled = fullTime; if (!fullTime) { HoursDisplayValue = 40.0M; HoursContentValue = "Full Time"; } else { HoursContentValue = "Custom Time"; } UpdateProperties(); } private void UpdateProperties() { RaisePropertyChanged("BaseHourlyRate"); RaisePropertyChanged("BaseHourlyRateText"); RaisePropertyChanged("BaseHourlyRateDeductionText"); RaisePropertyChanged("dFontSize"); RaisePropertyChanged("DeductionPercentage"); RaisePropertyChanged("HoursDisplayValue"); RaisePropertyChanged("WeeksDisplayValue"); RaisePropertyChanged("HoursContentValue"); RaisePropertyChanged("WeeksContentValue"); RaisePropertyChanged("OverTimeHourlyRate"); RaisePropertyChanged("OverTimeHourlyRateText"); RaisePropertyChanged("OverTimeHourlyRateDeductionText"); RaisePropertyChanged("WeeklyPay"); RaisePropertyChanged("WeeklyPayText"); RaisePropertyChanged("WeeklyPayDeductionText"); RaisePropertyChanged("BiWeeklyPay"); RaisePropertyChanged("BiWeeklyPayText"); RaisePropertyChanged("BiWeeklyPayDeductionText"); RaisePropertyChanged("AnnualSalary"); RaisePropertyChanged("AnnualSalaryText"); RaisePropertyChanged("AnnualSalaryDeductionText"); } #endregion #region Salary // Salary private readonly Salary _salary; public Salary Salary { get { return _salary; } } private bool _IsSalNotFullTime; public bool IsSalNotFullTime { get { return _IsSalNotFullTime; } set { if (_IsSalNotFullTime == value) return; _IsSalNotFullTime = value; RaisePropertyChanged("IsSalNotFullTime"); RaisePropertyChanged("IsSalFullTime"); // Cori Code SalRecalculate(); } } // Cori Code public bool IsSalFullTime { get { return !_IsSalNotFullTime; } set { if (!_IsSalNotFullTime == value) return; _IsSalNotFullTime = !value; RaisePropertyChanged("IsSalNotFullTime"); RaisePropertyChanged("IsSalFullTime"); SalRecalculate(); } } private bool _IsSalHoursDisplayValueEnabled; public bool IsSalHoursDisplayValueEnabled { get { return _IsSalHoursDisplayValueEnabled; } set { if (_IsSalHoursDisplayValueEnabled == value) return; _IsSalHoursDisplayValueEnabled = value; RaisePropertyChanged("IsSalHoursDisplayValueEnabled"); SalRecalculate(); } } private decimal _SalHoursDisplayValue; public decimal SalHoursDisplayValue { get { return _SalHoursDisplayValue; } set { if (_SalHoursDisplayValue == value) return; // Verify that the number of hours entered are in range of 0 and 100 // If you are working more than 100 hours a week, you need a new job. if (value < 0) value = 0; if (value > 100) value = 100; _SalHoursDisplayValue = value; RaisePropertyChanged("SalHoursDisplayValue"); SalRecalculate(); } } private string _SalWeeksContentValue; public string SalWeeksContentValue { get { return _SalWeeksContentValue; } set { if (_SalWeeksContentValue == value) return; _SalWeeksContentValue = value; RaisePropertyChanged("SalWeeksContentValue"); SalRecalculate(); } } private string _SalHoursContentValue; public string SalHoursContentValue { get { return _SalHoursContentValue; } set { if (_SalHoursContentValue == value) return; _SalHoursContentValue = value; RaisePropertyChanged("SalHoursContentValue"); SalRecalculate(); } } public decimal BaseAnnualSalary { get { return _salary.BaseSalary; } set { if (_salary.BaseSalary == value) return; // Verify that the salary entered isn't less than 0 nor greater than 999,999,999.99 if (value < 0) value = 0; if (value > 999999999.99M) value = 999999999.99M; _salary.BaseSalary = value; RaisePropertyChanged("BaseAnnualSalary"); SalRecalculate(); } } public decimal SalDeductionPercentage { get { return _salary.DeductionPercentage; } set { if (_salary.DeductionPercentage == value) return; // Verify that the deduction percentage is in range of 0 and 100 if (value < 0) value = 0; if (value > 100) value = 100; _salary.DeductionPercentage = value; RaisePropertyChanged("SalDeductionPercentage"); SalRecalculate(); } } private bool _IsSalWeeksDisplayValueEnabled; public bool IsSalWeeksDisplayValueEnabled { get { return _IsSalWeeksDisplayValueEnabled; } set { if (_IsSalWeeksDisplayValueEnabled == value) return; _IsSalWeeksDisplayValueEnabled = value; RaisePropertyChanged("IsSalWeeksDisplayValueEnabled"); SalRecalculate(); } } //private bool _IsSalNotFullYear; //public bool IsSalNotFullYear //{ // get { return _IsSalNotFullYear; } // set // { // if (_IsSalNotFullYear == value) // return; // _IsSalNotFullYear = value; // RaisePropertyChanged("IsSalNotFullYear"); // SalRecalculate(); // } //} // Cori Code private bool _IsSalNotFullYear; public bool IsSalNotFullYear { get { return _IsSalNotFullYear; } set { if (_IsSalNotFullYear == value) return; _IsSalNotFullYear = value; RaisePropertyChanged("IsSalNotFullYear"); RaisePropertyChanged("IsSalFullYear"); SalRecalculate(); } } public bool IsSalFullYear { get { return !_IsSalNotFullYear; } set { if (!_IsSalNotFullYear == value) return; _IsSalNotFullYear = !value; RaisePropertyChanged("IsSalNotFullYear"); RaisePropertyChanged("IsSalFullYear"); SalRecalculate(); } } private int _SalWeeksDisplayValue; public int SalWeeksDisplayValue { get { return _SalWeeksDisplayValue; } set { if (_SalWeeksDisplayValue == value) return; // Verify that the number of weeks entered are in range of 0 and 52 if (value < 0) value = 0; if (value > 52) value = 52; _SalWeeksDisplayValue = value; RaisePropertyChanged("SalWeeksDisplayValue"); SalRecalculate(); } } private void SalRecalculate() // check for changes { RecalculateSalHours(IsSalNotFullTime); RecalculateSalWeeks(IsSalNotFullYear); } private void RecalculateSalHours(bool fullTime) { IsSalHoursDisplayValueEnabled = fullTime; if (!fullTime) { SalHoursDisplayValue = 40.0M; SalHoursContentValue = "Full Time"; } else { SalHoursContentValue = "Custom Time"; } UpdateSalaryProperties(); } private void RecalculateSalWeeks(bool fullYear) { IsSalWeeksDisplayValueEnabled = fullYear; if (!fullYear) // Custom Time is selected { SalWeeksDisplayValue = 52; SalWeeksContentValue = "Full Year"; } else { SalWeeksContentValue = "Custom Year"; } UpdateSalaryProperties(); } private void UpdateSalaryProperties() { RaisePropertyChanged("BaseAnnualSalary"); RaisePropertyChanged("BaseAnnualSalaryText"); RaisePropertyChanged("SalDeductionPercentage"); RaisePropertyChanged("SalHoursDisplayValue"); RaisePropertyChanged("SalHoursContentValue"); RaisePropertyChanged("SalWeeksDisplayValue"); RaisePropertyChanged("SalWeeksContentValue"); RaisePropertyChanged("SalaryPayDeduction"); RaisePropertyChanged("SalaryPayDeductionText"); RaisePropertyChanged("SalBiWeeklyPay"); RaisePropertyChanged("SalBiWeeklyPayText"); RaisePropertyChanged("SalBiWeeklyPayDeductionText"); RaisePropertyChanged("SalaryWeeklyPay"); RaisePropertyChanged("SalaryWeeklyPayText"); RaisePropertyChanged("SalaryWeeklyPayDeductionText"); RaisePropertyChanged("BaseHourlyPay"); RaisePropertyChanged("BaseHourlyPayText"); RaisePropertyChanged("BaseHourlyPayDeductionText"); } public string BaseAnnualSalaryText { get { return String.Format("{0:C2}", BaseAnnualSalary); } } public decimal SalaryPayDeduction { get { return _salary.BaseSalary - (_salary.BaseSalary * (SalDeductionPercentage / 100)); } } public string SalaryPayDeductionText { get { return String.Format("{0:C2}", SalaryPayDeduction); } } public decimal SalBiWeeklyPay { get { return (_salary.BaseSalary / _SalWeeksDisplayValue) * 2; } } public string SalBiWeeklyPayText { get { return String.Format("{0:C2}", SalBiWeeklyPay); } } public decimal SalBiWeeklyPayDeduction { get { return SalBiWeeklyPay - (SalBiWeeklyPay * (SalDeductionPercentage / 100)); } } public string SalBiWeeklyPayDeductionText { get { return String.Format("{0:C2}", SalBiWeeklyPayDeduction); } } public decimal SalaryWeeklyPay { get { return _salary.BaseSalary / _SalWeeksDisplayValue; } } public string SalaryWeeklyPayText { get { return String.Format("{0:C2}", SalaryWeeklyPay); } } public decimal SalaryWeeklyPayDeduction { get { return SalaryWeeklyPay - (SalaryWeeklyPay * (SalDeductionPercentage / 100)); } } public string SalaryWeeklyPayDeductionText { get { return String.Format("{0:C2}", SalaryWeeklyPayDeduction); } } public decimal BaseHourlyPay { get { return _salary.BaseSalary / _SalWeeksDisplayValue / _SalHoursDisplayValue; } } public string BaseHourlyPayText { get { return String.Format("{0:C2}", BaseHourlyPay); } } public decimal BaseHourlyPayDeduction { get { return BaseHourlyPay - (BaseHourlyPay * (SalDeductionPercentage / 100)); } } public string BaseHourlyPayDeductionText { get { return String.Format("{0:C2}", BaseHourlyPayDeduction); } } } #endregion }
3dbc37eac03a054c987dfac09f58dcec8c028ab1
[ "C#" ]
6
C#
jaseporter01/WagenatorWP7
98dcb189ae8cf539842829d80121b19a2567e236
ca4b7b62a92ae1e17884fa48c92f77768c950f95
refs/heads/master
<file_sep>(function () { var f = !0, h = null, i = !1, j = this; function aa(a) { var b = typeof a; if ("object" == b) if (a) { if (a instanceof Array) return "array"; if (a instanceof Object) return b; var c = Object.prototype.toString.call(a); if ("[object Window]" == c) return "object"; if ("[object Array]" == c || "number" == typeof a.length && "undefined" != typeof a.splice && "undefined" != typeof a.propertyIsEnumerable && !a.propertyIsEnumerable("splice")) return "array"; if ("[object Function]" == c || "undefined" != typeof a.call && "undefined" != typeof a.propertyIsEnumerable && !a.propertyIsEnumerable("call")) return "function" } else return "null"; else if ("function" == b && "undefined" == typeof a.call) return "object"; return b } function k(a) { return void 0 !== a } function l(a) { return "string" == typeof a } function m(a, b) { var c = a.split("."), d = j; !(c[0] in d) && d.execScript && d.execScript("var " + c[0]); for (var e; c.length && (e = c.shift());)!c.length && k(b) ? d[e] = b : d = d[e] ? d[e] : d[e] = {} } function n(a, b) { function c() {} c.prototype = b.prototype; a.M = b.prototype; a.prototype = new c }; function o(a, b) { for (var c in a) if (a[c] == b) return f; return i }; var s = {}; m("sb.NodeType", s); s.UnspecifiedEntity = "unspecified entity"; s.SimpleChemical = "simple chemical"; s.Macromolecule = "macromolecule"; s.NucleicAcidFeature = "nucleic acid feature"; s.SimpleChemicalMultimer = "simple chemical multimer"; s.MacromoleculeMultimer = "macromolecule multimer"; s.NucleicAcidFeatureMultimer = "nucleic acid feature multimer"; s.Complex = "complex"; s.ComplexMultimer = "complex multimer"; s.SourceAndSink = "source and sink"; s.Perturbation = "perturbation"; s.BiologicalActivity = "biological activity"; s.PerturbingAgent = "perturbing agent"; s.Compartment = "compartment"; s.Submap = "submap"; s.Tag = "tag"; s.Terminal = "terminal"; s.Process = "process"; s.OmittedProcess = "omitted process"; s.UncertainProcess = "uncertain process"; s.Association = "association"; s.Dissociation = "dissociation"; s.Phenotype = "phenotype"; s.And = "and"; s.Or = "or"; s.Not = "not"; s.StateVariable = "state variable"; s.UnitOfInformation = "unit of information"; s.Stoichiometry = "stoichiometry"; s.Entity = "entity"; s.Outcome = "outcome"; s.Observable = "observable"; s.Interaction = "interaction"; s.InfluenceTarget = "influence target"; s.Annotation = "annotation"; s.VariableValue = "variable value"; s.ImplicitXor = "implicit xor"; s.Delay = "delay"; s.Existence = "existence"; s.Location = "location"; s.Cardinality = "cardinality"; function ba(a) { return o(s, a) } m("sb.NodeTypeHelper.isNodeTypeSupported", ba); function ca(a) { for (var b = 0, c = ("" + t).replace(/^[\s\xa0]+|[\s\xa0]+$/g, "").split("."), a = ("" + a).replace(/^[\s\xa0]+|[\s\xa0]+$/g, "").split("."), d = Math.max(c.length, a.length), e = 0; 0 == b && e < d; e++) { var g = c[e] || "", O = a[e] || "", p = RegExp("(\\d*)(\\D*)", "g"), v = RegExp("(\\d*)(\\D*)", "g"); do { var q = p.exec(g) || ["", "", ""], r = v.exec(O) || ["", "", ""]; if (0 == q[0].length && 0 == r[0].length) break; b = ((0 == q[1].length ? 0 : parseInt(q[1], 10)) < (0 == r[1].length ? 0 : parseInt(r[1], 10)) ? -1 : (0 == q[1].length ? 0 : parseInt(q[1], 10)) > (0 == r[1].length ? 0 : parseInt(r[1], 10)) ? 1 : 0) || ((0 == q[2].length) < (0 == r[2].length) ? -1 : (0 == q[2].length) > (0 == r[2].length) ? 1 : 0) || (q[2] < r[2] ? -1 : q[2] > r[2] ? 1 : 0) } while (0 == b) } return b }; var u = Array.prototype, da = u.indexOf ? function (a, b, c) { return u.indexOf.call(a, b, c) } : function (a, b, c) { c = c == h ? 0 : 0 > c ? Math.max(0, a.length + c) : c; if (l(a)) return !l(b) || 1 != b.length ? -1 : a.indexOf(b, c); for (; c < a.length; c++) if (c in a && a[c] === b) return c; return -1 }, w = u.forEach ? function (a, b, c) { u.forEach.call(a, b, c) } : function (a, b, c) { for (var d = a.length, e = l(a) ? a.split("") : a, g = 0; g < d; g++) g in e && b.call(c, e[g], g, a) }, x = u.filter ? function (a, b, c) { return u.filter.call(a, b, c) } : function (a, b, c) { for (var d = a.length, e = [], g = 0, O = l(a) ? a.split("") : a, p = 0; p < d; p++) if (p in O) { var v = O[p]; b.call(c, v, p, a) && (e[g++] = v) } return e }; function ea(a, b) { return 0 <= da(a, b) } function y(a, b) { ea(a, b) || a.push(b) }; function z(a, b) { this.g = {}; this.c = []; var c = arguments.length; if (1 < c) { if (c % 2) throw Error("Uneven number of arguments"); for (var d = 0; d < c; d += 2) this.set(arguments[d], arguments[d + 1]) } else if (a) { var e; if (a instanceof z) { A(a); d = a.c.concat(); A(a); e = []; for (c = 0; c < a.c.length; c++) e.push(a.g[a.c[c]]) } else { var c = [], g = 0; for (d in a) c[g++] = d; d = c; c = []; g = 0; for (e in a) c[g++] = a[e]; e = c } for (c = 0; c < d.length; c++) this.set(d[c], e[c]) } } z.prototype.k = 0; z.prototype.remove = function (a) { return Object.prototype.hasOwnProperty.call(this.g, a) ? (delete this.g[a], this.k--, this.c.length > 2 * this.k && A(this), f) : i }; function A(a) { if (a.k != a.c.length) { for (var b = 0, c = 0; b < a.c.length;) { var d = a.c[b]; Object.prototype.hasOwnProperty.call(a.g, d) && (a.c[c++] = d); b++ } a.c.length = c } if (a.k != a.c.length) { for (var e = {}, c = b = 0; b < a.c.length;) d = a.c[b], Object.prototype.hasOwnProperty.call(e, d) || (a.c[c++] = d, e[d] = 1), b++; a.c.length = c } } z.prototype.get = function (a, b) { return Object.prototype.hasOwnProperty.call(this.g, a) ? this.g[a] : b }; z.prototype.set = function (a, b) { Object.prototype.hasOwnProperty.call(this.g, a) || (this.k++, this.c.push(a)); this.g[a] = b }; z.prototype.r = function () { return new z(this) }; function B() { this.i = new z } m("sb.model.AttributeObject", B); B.prototype.b = function (a, b, c) { if (k(b)) { var d = this.i.get(a); this.i.set(a, b); c && "id" == a && (d && c.s.remove(d), c.s.set(b, this)); return this } return this.i.get(a) }; B.prototype.attr = B.prototype.b; function C(a) { this.i = new z; this.a = a; this.q = []; this.parent = h } n(C, B); m("sb.model.Element", C); C.prototype.id = function (a) { if (k(a)) { var b = this.a.element(a); if (b && b != this) throw Error("Given element id " + a + " already existed"); } return this.b("id", a, this.a) }; C.prototype.id = C.prototype.id; C.prototype.d = function (a) { a.parent && a.parent.removeChild(a); y(this.q, a); a.parent = this }; C.prototype.addChild = C.prototype.d; C.prototype.removeChild = function (a) { var b = this.q, c = da(b, a); 0 <= c && u.splice.call(b, c, 1); a.parent = h }; C.prototype.removeChild = C.prototype.removeChild; C.prototype.children = function () { return this.q }; C.prototype.children = C.prototype.children; function D(a) { C.call(this, a) } n(D, C); m("sb.Port", D); function E(a) { C.call(this, a) } n(E, C); m("sb.Node", E); E.prototype.type = function (a) { if (k(a) && !ba(a)) throw Error("Given node type " + a + " is not supported."); return this.b("type", a) }; E.prototype.type = E.prototype.type; E.prototype.label = function (a) { return this.b("label", a) }; E.prototype.label = E.prototype.label; E.prototype.r = function (a) { return this.b("clone", a) }; E.prototype.clone = E.prototype.r; E.prototype.u = function (a) { a = this.a.createNode(a); this.d(a); return a }; E.prototype.createSubNode = E.prototype.u; E.prototype.f = function (a) { a = this.a.f(a); this.d(a); return a }; E.prototype.createPort = E.prototype.f; var F = {}; m("sb.ArcType", F); F.Production = "production"; F.Consumption = "consumption"; F.Catalysis = "catalysis"; F.Modulation = "modulation"; F.Stimulation = "stimulation"; F.Inhibition = "inhibition"; F.Assignment = "assignment"; F.Interaction = "interaction"; F.AbsoluteInhibition = "absolute inhibition"; F.AbsoluteStimulation = "absolute stimulation"; F.PositiveInfluence = "positive influence"; F.NegativeInfluence = "negative influence"; F.UnknownInfluence = "unknown influence"; F.EquivalenceArc = "equivalence arc"; F.NecessaryStimulation = "necessary stimulation"; F.LogicArc = "logic arc"; function fa(a) { return o(F, a) } m("sb.ArcTypeHelper.isArcTypeSupported", fa); function G(a) { C.call(this, a) } n(G, C); m("sb.Arc", G); G.prototype.type = function (a) { if (k(a) && !fa(a)) throw Error("Given arc type " + a + " is not supported."); return this.b("type", a) }; G.prototype.type = G.prototype.type; G.prototype.source = function (a) { if (a && l(a)) { var b = this.a.element(a); if (!b) throw Error("Element " + a + " do not exist."); a = b } return this.b("source", a) }; G.prototype.source = G.prototype.source; G.prototype.target = function (a) { if (a && l(a)) { var b = this.a.element(a); if (!b) throw Error("Element " + a + " do not exist."); a = b } return this.b("target", a) }; G.prototype.target = G.prototype.target; G.prototype.f = function (a) { a = this.a.f(a); this.d(a); return a }; G.prototype.createPort = G.prototype.f; function ga(a) { C.call(this, a) } n(ga, C); m("sb.ArcGroup", ga); function H(a) { this.i = new z; this.id = a; this.H = this.A = this.G = 1; this.s = new z; this.t = []; this.p = []; this.I = [] } n(H, B); m("sb.Document", H); H.prototype.createNode = function (a) { a = a ? a : ha(this); a = (new E(this)).id(a); y(this.t, a); return a }; H.prototype.createNode = H.prototype.createNode; function ha(a) { var b = "node" + a.G++; return a.element(b) ? ha(a) : b } H.prototype.w = function (a) { return a ? x(this.t, function (a) { return a.parent ? i : f }) : this.t }; H.prototype.nodes = H.prototype.w; H.prototype.v = function (a) { a = this.element(a); return a instanceof E ? a : h }; H.prototype.node = H.prototype.v; H.prototype.element = function (a) { return this.s.get(a) }; H.prototype.e = function (a) { a = a ? a : ia(this); a = (new G(this)).id(a); y(this.p, a); return a }; H.prototype.createArc = H.prototype.e; H.prototype.D = function (a, b) { var c = this.e(); c.source(a).target(b); return c }; H.prototype.connect = H.prototype.D; function ia(a) { var b = "arc" + a.A++; return a.element(b) ? ia(a) : b } H.prototype.B = function () { return this.p }; H.prototype.arcs = H.prototype.B; H.prototype.arc = function (a) { a = this.element(a); return a instanceof G ? a : h }; H.prototype.arc = H.prototype.arc; function ja(a) { var b = "port" + a.H++; return a.element(b) ? ja(a) : b } H.prototype.f = function (a) { a = a ? a : ja(this); a = (new D(this)).id(a); y(this.I, a); return a }; H.prototype.createPort = H.prototype.f; H.prototype.lang = function (a) { if (k(a) && !o(ka, a)) throw Error("Given SBGN language type " + a + " is not supported."); return this.b("language", a) }; var ka = { J: "activity flow", K: "entity relationship", L: "process description" }; m("sb.Language", ka); function la(a, b) { this.x = k(a) ? a : 0; this.y = k(b) ? b : 0 } m("sb.Point", la); function I(a, b, c, d) { this.x = k(a) ? a : 0; this.y = k(b) ? b : 0; this.width = k(c) ? c : 0; this.height = k(d) ? d : 0 } m("sb.Box", I); I.prototype.contains = function (a) { return a.x >= this.x && a.y >= this.y && this.x + this.width >= a.x + a.width && this.y + this.height >= a.y + a.height }; var J, K, L, M; function ma() { return j.navigator ? j.navigator.userAgent : h } M = L = K = J = i; var N; if (N = ma()) { var na = j.navigator; J = 0 == N.indexOf("Opera"); K = !J && -1 != N.indexOf("MSIE"); L = !J && -1 != N.indexOf("WebKit"); M = !J && !L && "Gecko" == na.product } var P = K, oa = M, pa = L, t; a: { var Q = "", R; if (J && j.opera) var qa = j.opera.version, Q = "function" == typeof qa ? qa() : qa; else if (oa ? R = /rv\:([^\);]+)(\)|;)/ : P ? R = /MSIE\s+([^\);]+)(\)|;)/ : pa && (R = /WebKit\/(\S+)/), R) var ra = R.exec(ma()), Q = ra ? ra[1] : ""; if (P) { var sa, ta = j.document; sa = ta ? ta.documentMode : void 0; if (sa > parseFloat(Q)) { t = "" + sa; break a } } t = Q } var S = {}, ua = {}; function va() { return ua[9] || (ua[9] = P && !! document.documentMode && 9 <= document.documentMode) }; !P || va(); var wa = !oa && !P || P && va() || oa && (S["1.9.1"] || (S["1.9.1"] = 0 <= ca("1.9.1"))); P && (S["9"] || (S["9"] = 0 <= ca("9"))); function xa(a) { return wa && void 0 != a.children ? a.children : x(a.childNodes, function (a) { return 1 == a.nodeType }) }; function ya(a) { if ("undefined" != typeof XMLSerializer) return (new XMLSerializer).serializeToString(a); if (a = a.xml) return a; throw Error("Your browser does not support serializing XML documents"); }; function za() {} function Aa(a) { "\ufeff" == a.charAt(0) && (a = a.substr(1, a.length)); new z; if ("undefined" != typeof DOMParser) a = (new DOMParser).parseFromString(a, "application/xml"); else if ("undefined" != typeof ActiveXObject) { var b = new ActiveXObject("MSXML2.DOMDocument"); if (b) { b.resolveExternals = i; b.validateOnParse = i; try { b.setProperty("ProhibitDTD", f), b.setProperty("MaxXMLSize", 2048), b.setProperty("MaxElementDepth", 256) } catch (c) {} } b.loadXML(a); a = b } else throw Error("Your browser does not support loading xml documents"); return a } function Ba(a, b) { Ca(a, b); w(b.childNodes, function (a) { 1 == a.nodeType && Ba(this, a) }, a); Da(a, b) }; function Ea() { this.m = [] } Ea.prototype.push = function (a) { this.m.push(a) }; Ea.prototype.pop = function () { return this.m.pop() }; function T() { this.j = this.a = this.l = this.h = h } n(T, za); m("sb.io.SbgnReader", T); T.prototype.n = function (a) { this.h = new Ea; this.a = new H; this.j = []; this.l = []; Ba(this, Aa(a).documentElement); w(this.l, function (a) { var c = this.a.arc(a.getAttribute("id")), d = a.getAttribute("target"), a = a.getAttribute("source"); c.source(a).target(d) }, this); return this.a }; T.prototype.parseText = T.prototype.n; function Ca(a, b) { var c = b.tagName, c = c ? c.toLocaleLowerCase() : h, d = b.getAttribute("id"), e = a.h.m[a.h.m.length - 1]; if ("glyph" == c) d = e instanceof E ? e.u(d) : a.a.createNode(d), c = b.getAttribute("class"), d.type(c), a.h.push(d), "compartment" == c && y(a.j, d); else if ("port" == c)(e instanceof E || e instanceof G) && e.f(d); else if ("arc" == c) c = a.a.e(d), d || b.setAttribute("id", c.id()), d = b.getAttribute("class"), c.type(d), a.h.push(c), y(a.l, b); else if ("label" == c) e.label(b.getAttribute("text")); else if ("bbox" == c) { var g = new I(Number(b.getAttribute("x")), Number(b.getAttribute("y")), Number(b.getAttribute("w")), Number(b.getAttribute("h"))); "label" == b.parentNode.tagName.toLocaleLowerCase() ? e.b("label.pos", g) : (e.b("box", g), e instanceof E && "compartment" != e.type() && w(a.j, function (a) { a.b("box").contains(g) && a.d(e) }, a)) } else "start" == c || "end" == c ? e instanceof G && e.b(c, new la(Number(b.getAttribute("x")), Number(b.getAttribute("y")))) : "map" == c ? ((d = b.getAttribute("language")) && a.a.lang(d), a.h.push(a.a)) : "entity" == c && e.b("entity", b.getAttribute("name")) } function Da(a, b) { var c = b.tagName; ("glyph" == c || "arc" == c || "map" == c) && a.h.pop() }; function U(a, b, c) { this.url = a; this.C = c; this.F = Fa(this); c = document.createElement("script"); c.setAttribute("type", "text/javascript"); var d = "", b = b || {}, e; for (e in b) b.hasOwnProperty(e) && (d += encodeURIComponent(e) + "=" + encodeURIComponent(b[e]) + "&"); c.setAttribute("src", a + "?" + d + "callback=sb.io.Jsonp." + this.F); this.z = document.getElementsByTagName("head")[0].appendChild(c) } m("sb.io.Jsonp", U); U.call = function (a, b, c) { new U(a, b, c) }; function Fa(a) { for (var b = "", c = 0; 15 > c; c++) b += "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".charAt(Math.floor(52 * Math.random())); U[b] = function (c) { a.C(c); delete U[b]; a.z.parentNode.removeChild(a.z) }; return b }; var V = {}; m("sb.sbo.NodeTypeMapping", V); V["unspecified entity"] = 285; V.compartment = 290; V.macromolecule = 245; V["macromolecule multimer"] = 420; V["simple chemical"] = 247; V["simple chemical multimer"] = 421; V.complex = 253; V["complex multimer"] = 418; V.process = 375; V["omitted process"] = 379; V["uncertain process"] = 396; V.annotation = 110003; V.phenotype = 358; V["nucleic acid feature"] = 250; V["nucleic acid feature multimer"] = 250; V.association = 177; V.dissociation = 180; V.entity = 245; V.submap = 395; V.terminal = 110004; V["perturbing agent"] = 405; V["variable value"] = 110001; V["implicit xor"] = -1; V.tag = 110002; V.and = 173; V.or = 174; V.not = 238; V.delay = 225; V["source and sink"] = 291; V.perturbation = 405; V["biological activity"] = 412; var W = {}; m("sb.sbo.ArcTypeMapping", W); W.production = 393; W["equivalence arc"] = 15; W["logic arc"] = 15; W["necessary stimulation"] = 461; W.assignment = 464; W.interaction = 342; W["absolute inhibition"] = 407; W.modulation = 168; W.inhibition = 169; W["absolute stimulation"] = 411; W["unknown influence"] = 168; W["positive influence"] = 170; W["negative influence"] = 169; W.stimulation = 170; W.catalysis = 172; W.consumption = 15; W.production = 393; W.catalysis = 13; function Ga() { this.o = void 0 } function Ha(a) { var b = []; Ia(new Ga, a, b); return b.join("") } function Ia(a, b, c) { switch (typeof b) { case "string": Ja(b, c); break; case "number": c.push(isFinite(b) && !isNaN(b) ? b : "null"); break; case "boolean": c.push(b); break; case "undefined": c.push("null"); break; case "object": if (b == h) { c.push("null"); break } if ("array" == aa(b)) { var d = b.length; c.push("["); for (var e = "", g = 0; g < d; g++) c.push(e), e = b[g], Ia(a, a.o ? a.o.call(b, "" + g, e) : e, c), e = ","; c.push("]"); break } c.push("{"); d = ""; for (g in b) Object.prototype.hasOwnProperty.call(b, g) && (e = b[g], "function" != typeof e && (c.push(d), Ja(g, c), c.push(":"), Ia(a, a.o ? a.o.call(b, g, e) : e, c), d = ",")); c.push("}"); break; case "function": break; default: throw Error("Unknown type: " + typeof b); } } var Ka = { '"': '\\"', "\\": "\\\\", "/": "\\/", "\u0008": "\\b", "\u000c": "\\f", "\n": "\\n", "\r": "\\r", "\t": "\\t", "\x0B": "\\u000b" }, La = /\uffff/.test("\uffff") ? /[\\\"\x00-\x1f\x7f-\uffff]/g : /[\\\"\x00-\x1f\x7f-\xff]/g; function Ja(a, b) { b.push('"', a.replace(La, function (a) { if (a in Ka) return Ka[a]; var b = a.charCodeAt(0), e = "\\u"; 16 > b ? e += "000" : 256 > b ? e += "00" : 4096 > b && (e += "0"); return Ka[a] = e + b.toString(16) }), '"') }; function Ma() {} m("sb.io.JsbgnWriter", Ma); var X = []; X["entity relationship"] = "ER"; X["activity flow"] = "AF"; X["process description"] = "PD"; Ma.prototype.write = function (a) { var b = { nodes: [], edges: [] }; a.lang() && (b.sbgnlang = X[a.lang()]); w(a.w(), function (a) { if (!(a instanceof D) && !ea(["unit of information", "state variable"], a.type())) { var d = {}; d.id = a.id(); d.sbo = V[a.type()]; d.is_abstract = i; var e = {}; d.data = e; a.r() && (e.clone = f); a.label() && (e.label = a.label()); var g = a.b("box"); g && (e.x = g.x, e.y = g.y, e.width = g.width, e.height = g.height); w(a.children(), function (a) { if (!(a instanceof D)) if (a.type() == "unit of information") { e.unitofinformation || (e.unitofinformation = []); y(e.unitofinformation, a.label() ? a.label() : "") } else if (a.type() != "state variable") { e.subnodes || (e.subnodes = []); y(e.subnodes, a.id()) } }, this); y(b.nodes, d) } }, this); w(a.p, function (a) { var d = {}; d.id = a.id(); d.sbo = W[a.type()]; d.source = a.source().id(); d.target = a.target().id(); d.data = {}; y(b.edges, d) }, this); return Ha(b) }; function Y(a, b, c) { a = xa(a); w(a, b, c) } function Z(a, b, c, d) { a = x(xa(a), function (a) { return a.tagName == b }); w(a, c, d) }; function $() { this.j = this.a = this.l = this.h = h } n($, za); m("sb.io.SbmlReader", $); $.prototype.n = function (a) { this.a = new H; this.j = []; this.l = []; var a = Aa(a), b = {}; Z(a.documentElement, "model", function (a) { Z(a, "listOfCompartments", function (a) { Y(a, function (a) { this.a.createNode(a.getAttribute("id")).type("compartment") }, this) }, this); Z(a, "listOfSpecies", function (a) { Y(a, function (a) { var c = this.a.createNode(a.getAttribute("id")), d = a.getAttribute("id"), p = a.getAttribute("id") + a.getAttribute("name"), v = this.a.v(a.getAttribute("compartment")); v.d(c); b[d] = v; - 1 != p.toLowerCase().indexOf("sink") || -1 != p.toLowerCase().indexOf("emptyset") ? c.type("source and sink") : -1 != p.toLowerCase().indexOf("dna") || -1 != p.toLowerCase().indexOf("rna") ? c.type("nucleic acid feature") : -1 != ya(a).indexOf("urn:miriam:obo.chebi") ? c.type("simple chemical") : -1 != ya(a).indexOf("urn:miriam:pubchem") ? c.type("simple chemical") : -1 != ya(a).indexOf("urn:miriam:uniprot") ? c.type("macromolecule") : c.type("unspecified entity") }, this) }, this); Z(a, "listOfReactions", function (a) { Z(a, "reaction", function (a) { var c = a.getAttribute("id"), d = this.a.createNode(c).type("process"); console.log("reaction_id " + c); var p = i, v = i, q; Z(a, "listOfReactants", function (a) { Y(a, function (a) { a = a.getAttribute("species"); this.a.e(a + "_to_" + c).source(a).target(c).type("consumption"); p = f; q = b[a] }, this) }, this); Z(a, "listOfProducts", function (a) { Y(a, function (a) { a = a.getAttribute("species"); this.a.e(c + "_to_" + a).source(c).target(a).type("production"); v = f; q = b[a] }, this) }, this); Z(a, "listOfModifiers", function (a) { Y(a, function (a) { a = a.getAttribute("species"); this.a.e(a + "_to_" + c).source(a).target(c).type("modulation") }, this) }, this); q.d(d); if (!p) { var a = c + "_source", r = this.a.createNode(a).type("source and sink"), d = c; q.d(r); this.a.e(a + "_to_" + d).source(a).target(d).type("consumption") } v || (d = c + "_sink", r = this.a.createNode(d).type("source and sink"), a = c, q.d(r), this.a.e(a + "_to_" + d).source(a).target(d).type("production")) }, this) }, this) }, this); return this.a }; $.prototype.parseText = $.prototype.n; function Na(a, b) { var c; if ("sbgn" == b) c = new T; else throw Error("Format " + b + " not supported"); return c.n(a) } m("sb.io.read", Na); m("sb.io.readUrl", function (a, b, c) { new U("http://chemhack.com/jsonp/ba-simple-proxy.php", { url: a }, function (a) { 200 == a.status.http_code && (a = Na(a.contents, b), c(a)) }) }); m("sb.io.write", function (a, b) { var c; if ("jsbgn" == b) c = new Ma; else throw Error("Format " + b + " not supported"); return c.write(a) }); })();<file_sep>jSBGN_network = '{ "nodes": [ \ {"id":"glucose"}, \ {"id":"glycerol"} \ ], \ "edges": [ \ {"source":"glucose", "target":"glycerol"} \ ] \ }'; <file_sep>var serverURL; /** * Representation of Graphs using nodes and edges arrays. Used as * a placeholder for importing graphs into biographer-ui. Look up * on the biographer wiki on the format specification. * @constructor */ var jSBGN = function () { this.nodes = []; this.edges = []; this.state = {}; this.initialState = {}; }; /** * Substitutes the node id's in source and target properties * of edges with the actual node objects, as required for the d3 * layouter. * @param {boolean} truth Whether the nodes should be connected or not */ jSBGN.prototype.connectNodes = function (truth) { var i, j; for (i in this.edges) { if (truth) { for (j in this.nodes) { if (this.edges[i].source == this.nodes[j].id) this.edges[i].source = this.nodes[j]; if (this.edges[i].target == this.nodes[j].id) this.edges[i].target = this.nodes[j]; } } else { this.edges[i].source = this.edges[i].source.id; this.edges[i].target = this.edges[i].target.id; } } }; /** * Customised d3 force layouter. The d3 layouter is called synchronously. * The layout is calculated till the alpha value drops below a certain * threshold. * @param {bui.Graph} graph The bui graph instance. */ jSBGN.prototype.layoutGraph = function (graph) { // Give a canvas to the d3 layouter with the dimensions of the window var ratio = $(window).width() / $(window).height(); var width = 1e6; var height = width / ratio; var layouter = d3.layout.force() // Charge is proportional to the size of the label .charge(function (node) { var size = 0; if (typeof (node.data.label) !== 'undefined') size = node.id.length; return -2000 - 500 * size; }) // Link distance depends on two factors: The length of the labels of // the source and target and the number of nodes connected to the source .linkDistance(function (edge) { var size = 0; if (typeof (edge.source.data.label) !== 'undefined') size = edge.source.id.length + edge.target.id.length; return 100 + 30 * (edge.source.weight) + 5 * size; }) .linkStrength(1) .gravity(0.1) .nodes(this.nodes) .links(this.edges) .size([width, height]); // Run the d3 layouter synchronously, alpha cut-off 0.005 layouter.start(); while (layouter.alpha() > 0.005) layouter.tick(); layouter.stop(); // Copy the layout data from d3 to jSBGN format var node, i; for (i = 0; i < this.nodes.length; i++) { node = this.nodes[i]; node.data.x = node.x; node.data.y = node.y; } }; /** * Import a Boolean Net file(R/Python) into the jSBGN object. These * files are quite simple with each line containing an update rule. By * parsing this line the connections between nodes are made. * @param {string} data The data contained in the Boolean Net file. * @param {string} splitKey The character separating the LHS and RHS of * a update rule. */ jSBGN.prototype.importBooleanNetwork = function (data, splitKey, reImport) { var targetNode, sourceNode; var targetID, sourceID, edgeID; var rules = {}, ruleIDs, rule, right = [], left = []; var doc = new sb.Document(); doc.lang(sb.Language.AF); // rxncon exported Boolean networks need to be adjusted in order to work with BoolnetOnline if (data.indexOf('*=') + 1 + data.indexOf('-_P_') + 1 + data.indexOf('_P+_') + 1 + data.indexOf('_P-_') + 1 + data.indexOf('_Ub+_') + 1 + data.indexOf('_Ub-_') + 1 + data.indexOf('-_Cytoplasm_') + 1 + data.indexOf('-_Nucleus_') + 1 > 0) { console.log("Not actually Python. Looks like someone is trying to import a rxncon exported boolean network. Converting ..."); data = data .replace(/\*\=/g, '=') .replace(/\-_P_/g, '_P') .replace(/_P\+_/g, '_phos_') .replace(/_P\-_/g, '_dephos_') .replace(/_Ub\+_/g, '_ubi_') .replace(/_Ub\-_/g, '_deubi_') .replace(/\-_Cytoplasm_/g, '_Cytoplasm') .replace(/\-_Nucleus_/g, '_Nucleus') .replace(/\-/g, '_'); //.replace(/__/g, '_'); //console.log(data); } // The file consists of multiple lines with each line representing // the update rule for a node var lines, cols, i, j, trimmed; lines = data.split('\n'); console.log('Importing Boolean network from ' + lines.length + ' lines of text ...'); for (i = 0; i < lines.length; i++) { trimmed = lines[i].trim(); // Skip empty lines if (trimmed.length === 0) continue; if (trimmed[0] != '#') { // Extract the columns using the split key which is different // for R and Python Boolean Net cols = trimmed.split(splitKey); if (cols.length != 2) { console.error('Syntax error: An update rule must have exactly two sides; line ' + i + ': "' + trimmed + '"'); return false; } //console.log('Target: '+cols[0]); //console.log('Rule: '+cols[1]); targetID = cols[0].trim(); if (!reImport) { if (splitKey === ',') { if (targetID === 'targets') continue; } else { if (targetID[targetID.length - 1] === '*') { targetID = targetID.substring(0, targetID.length - 1); } else { // Set inital node states if ($('#seedFile').attr('checked')) { rule = cols[cols.length - 1].trim(); for (j = 0; j < cols.length - 1; j++) { targetID = cols[j].trim(); if (rule === 'True') this.state[targetID] = true; else if (rule === 'False') this.state[targetID] = false; else this.state[targetID] = controls.getRandomSeed(); } } else if ($('#seedTrue').attr('checked')) { this.state[targetID] = true; } else if ($('#seedFalse').attr('checked')) { this.state[targetID] = false; } else if ($('#seedRandom').attr('checked')) { this.state[targetID] = controls.getRandomSeed(); } this.initialState[targetID] = this.state[targetID]; } } // Convert R or Python logic to JavaScript rule = cols[1] .replace(/\bTrue\b/g, 'true') .replace(/\bFalse\b/g, 'false') .replace(/[&]/g, ' && ') .replace(/[|]/g, ' || ') .replace(/\band\b/g, '&&') .replace(/\bor\b/g, '||') .replace(/\bnot\b/g, '!') .replace(/ +/g, ' ') .trim(); if (rule == 'true' || rule == 'false') console.log('Initial state: '+rule); else console.log('Update rule: '+rule); } else { rule = cols[1].trim(); } // Check, whether the targetID contains illegal characters var check = targetID.match(/[A-Za-z0-9_]+/g); if (check[0] !== targetID) { console.error('Syntax error: Bogus target ID; line ' + i + ': "' + trimmed + '"'); return false; } // Create the node if it does not exist if (doc.node(targetID) === null) { targetNode = doc.createNode(targetID).type(sb.NodeType.Macromolecule).label(targetID); console.log('Node created: '+targetID); } else { console.log('Node exists: '+targetID); } // Assign rules (right side equation) to nodes (left side of equation) rules[targetID] = rule; /* * A rule shall neither be empty nor statically be true or false. * Instead such a "static" node shall assume it's previous state upon simulation, * which might be switched by clicking. */ if (rule == '' || rule == 'true' || rule == 'false' || rule == targetID) { rules[targetID] = targetID; continue; } // Extract all the node id's in the update rule ruleIDs = rules[targetID].match(/[A-Za-z0-9_]+/g); right = $.unique($.merge(right, ruleIDs)); left.push(targetID); // Inspect node dependencies and add edges appropriately for (j in ruleIDs) { sourceID = ruleIDs[j]; // no arcs for the trivial rules // catch here if statement at line 206 fails if (sourceID == 'true' || sourceID == 'false' || sourceID == targetID) continue; // Create the node if it does not exist if (doc.node(sourceID) === null) { sourceNode = doc.createNode(sourceID).type(sb.NodeType.Macromolecule).label(sourceID); } // Connect the source and target and create the edge edgeID = sourceID + ' -> ' + targetID; if (doc.arc(edgeID) === null) { re = new RegExp('![ ]*' + sourceID, 'g'); var matches = rule.match(re); if (matches !== null) doc.createArc(edgeID).type(sb.ArcType.Inhibition).source(sourceID).target(targetID); else doc.createArc(edgeID).type(sb.ArcType.Production).source(sourceID).target(targetID); } } } } var jsbgn = JSON.parse(sb.io.write(doc, 'jsbgn')); this.nodes = jsbgn.nodes; this.edges = jsbgn.edges; this.rules = rules; this.right = right; this.left = left; console.log('Imported '+this.nodes.length+' nodes and '+this.edges.length+' edges:'); console.log(this.nodes); console.log(this.edges); return (this.nodes.length > 0); }; jSBGN.prototype.importjSBGN = function (data) { var jsbgn; try { jsbgn = JSON.parse(data); } catch (e) { console.error("JSON parser raised an exception: "+e); return false; } this.nodes = jsbgn.nodes; this.edges = jsbgn.edges; this.rules = jsbgn.rules; left = []; right = []; for (i in this.rules) { if (this.rules[i] !== i) { var ruleIDs = this.rules[i].match(/[A-Za-z0-9_]+/g); right = $.unique($.merge(right, ruleIDs)); left.push(i); } } this.right = right; this.left = left; return true; }; <file_sep>/* * Generate a map for the state of the network. * @param {Object} state The state of the network. * @return {string} A map of the state of the network */ encodeStateMap = function (state) { var map = '', i; for (i in state) map += +state[i]; return map; }; /* * Decode the map of the state of the network * @param {string} map The map of the state of the network * @returns {Object} The state of the network */ decodeStateMap = function (map) { var state = {}, i, j = 0; for (i in network.state) state[i] = Boolean(parseInt(map[j++], 10)); return state; }; /* * Get some random initial states, used by the attractorSearch function. * @returns {Array} A list of states */ getSomeRandomStates = function () { var i, j; var initStates = []; for (i = 0; i < 30; i++) { initStates.push({}); for (j in network.state) { initStates[i][j] = Boolean(Math.round(Math.random())); } } return initStates; }; /* * Assign the state defined by the node in the State transition graph * to the nodes in the Network graph. */ copyStateNetwork = function () { var id = $(this) .attr('id'), i; network.state = decodeStateMap(id); for (i in network.state) updateNodeColor(i); }; /* * Calculate the attractors for the network graph and display a state * transition graph. The algorithm used is quite a simple one. * For each initial state successive states are calculated and the nodes * (representing the state of the network) are added to the graph, * and if a ndoe is repeated a edge is created and the next initial * state is chosen. */ findAttractors = function () { var doc = new sb.Document(); doc.lang(sb.Language.AF); var i, j; var initStates = getSomeRandomStates(); // Loop over all the initial states to find the attractors var cycle, attractors = []; var map, prev, node, idx; var currStates, state; for (i in initStates) { state = initStates[i]; currStates = []; prev = ''; // Run the iterations for each initial state for (j = 0;; j++) { // A map is used to match two states, faster than directly // comparing the objects map = encodeStateMap(state); node = doc.node(map); // If the map does not exist in the graph document, create it if (node !== null) { idx = currStates.indexOf(map); // If the map already exists in the visited node array it means // that we have found a attractor if (idx !== -1) { cycle = currStates.slice(idx); attractors.push(cycle); } // Create the connecting arc for the state transition graph if (prev.length > 0) doc.createArc(prev + '->' + map) .type(sb.ArcType.PositiveInfluence) .source(prev) .target(map); break; } else { doc.createNode(map) .type(sb.NodeType.SimpleChemical); if (prev.length > 0) doc.createArc(prev + '->' + map) .type(sb.ArcType.PositiveInfluence) .source(prev) .target(map); } currStates.push(map); // Get the new states synchronousUpdate(state); prev = map; } } drawAttractors(doc, attractors); }; /* * Import the generated Attractor network into the State Transition Graph. * The d3 force layouter is applied to the graph, event handlers are * bound for each node and the attractors are colored. * @param {sb.Document} doc The SBGN document for the graph. * @param {Array} attractors A list of attractors of the graph. */ drawAttractors = function (doc, attractors) { // Convert the SBGN document to jSBGN var jsbgn = new jSBGN(); var tmp = JSON.parse(sb.io.write(doc, 'jsbgn')); jsbgn.nodes = tmp.nodes; jsbgn.edges = tmp.edges; // Import the State transition graph into a bui.Graph instance controls.importNetwork(jsbgn, '#graphStateTransition'); // Bind the event handlers for the node var i, id; for (i in jsbgn.nodes) { id = '#' + jsbgn.nodes[i].id; $(id) .hover(showStateBox, removeInfoBox); $(id) .click(copyStateNetwork); } // Color all the attractors with a unique color for each attractor var cycle, j, color; for (i in attractors) { cycle = attractors[i]; color = randomColor(); for (j in cycle) $('#' + cycle[j] + ' :eq(0)') .css('fill', color); } };<file_sep>#!/usr/bin/python # # Pack all BoolnetOnline files into # one standalone HTML5 app # from os.path import basename # open main HTML file main = open('index.html').read() # pack all stylesheets styles = '' includes = ['css/jquery-ui-1.8.22.custom.css', 'css/visualization-html.css', 'css/simulator.css'] for infile in includes: comment = """/* * """+basename(infile)+""" */ """ styles += comment+open(infile).read()+'\n' # pack all JavaScripts scripts = '' includes = ['include/jquery-1.7.2.min.js', 'include/jquery-ui-1.8.22.custom.min.js', 'settings.js', 'js/controls.js'] for infile in includes: comment = """/* * """+basename(infile)+""" */ """ scripts += comment+open(infile).read()+'\n' # embed images as base64-encoded byte-stream # ... # combine all in one file p = main.find('<body') packed = """<html> <head> <title>BoolnetOnline</title> <style> """+styles+""" </style> <script type="text/javascript"> """+scripts+""" </script> </head> """+main[p:] # save open('BoolnetOnline.html5', 'w').write(packed) <file_sep> var controls, simulator = null; var networkGraph = null; var transitionGraph = null; var prevTab = 2; rulesChanged = false; $(document).ready(function () { // Load up the UI controls = new Controls(); controls.initialize(); }); /** * The Controls class hosts all the variables related to the UI, the * event handlers for the various jQuery UI components and additional * functions to fetch scripts and import networks into graphs. * @constructor */ var Controls = function () { // Private variables to hold the bui.Graph instances var obj = this; /** * initialize all the UI components and fetch the extra js files. The * UI consists of buttons, dialog boxes, a slider and a tab interface. */ this.initialize = function () { // Load the jQuery UI tabs $('#tabs').tabs(); $('#tabs').tabs('select', '#tabNetwork'); $('#tabs').bind('tabsshow', changeTab); // initialize all the jQuery UI components $('.legendTrue').css('background-color', yellow); $('.legendFalse').css('background-color', blue); $('#buttonCreate') .button({ icons: { primary: "ui-icon-star" } }) .click(createDefaultNetwork); $('#buttonInitialCreate') .button({ icons: { primary: "ui-icon-star" } }) .click(createDefaultNetwork); // the corresponding .click function is reloadUpdateRules // which is set in editrule.js $('#buttonSaveRules') .button({ icons: { primary: "ui-icon-check" } }); $('#buttonDiscardChanges') .button({ icons: { primary: "ui-icon-trash" } }); $('#buttonSimulate').button({ icons: { primary: "ui-icon-play" } }); $('#buttonResetTime') .button( {icons: {primary: "ui-icon-seek-first"}} ) .click(function () { resetTimeseries(); }); $( "#divNetworkLegend" ) .draggable({ containment: "#tabNetwork", scroll: false }); $('#buttonResetStates') .button( {icons: {primary: "ui-icon-arrowreturnthick-1-w"}} ); $('#buttonAllTrue') .button( {icons: {primary: "ui-icon-arrowthick-1-n"}} ); $('#buttonAllFalse') .button( {icons: {primary: "ui-icon-arrowthick-1-s"}} ); $('#dialogAddNode').dialog({ autoOpen: false, minWidth: 200, modal: true }); $('#buttonAddNodeCancel').click(function () { $('#dialogAddNode').dialog('close'); }); $('#dialogDeleteNode').dialog({ autoOpen: false, minWidth: 300, minHeight: 80, resizable: false, modal: true }); $('#buttonDeleteNodeNo').click(function () { $('#dialogDeleteNode').dialog('close'); }); $('#dialogImport').dialog({ autoOpen: false, minWidth: 450, resizable: false, modal: true }); $('#buttonImportDialog').button({ icons: { primary: "ui-icon-folder-open" } }).click(openImportDialog); $('#buttonImportFile').click(importFile); $('#buttonImportCancel').click(function () { $('#dialogImport').dialog('close'); }); $('#buttonDemo1').click(importDemo1); $('#buttonDemo2').click(importDemo2); $('#dialogExport').dialog({ autoOpen: false, minWidth: 400, modal: true }); $('#buttonExportDialog').button({ icons: { primary: "ui-icon-disk" } }).click(openExportDialog); $('#buttonExportFile').click(exportFile); $('#buttonExportCancel').click(function () { $('#dialogExport').dialog('close'); }); $('#dialogPreferences').dialog({ autoOpen: false, minWidth: 520, resizable: false, modal: true, buttons: { Ok: function() { $(this).dialog('close'); } } }); $('#buttonPreferences').button({ icons: { primary: "ui-icon-wrench" } }).click(function () { $('#dialogPreferences').dialog('open'); }); $('#dialogHelp').dialog({ autoOpen: false, minWidth: 650, resizable: false, modal: false }); $('#buttonHelp').button({ icons: { primary: "ui-icon-help" } }).click(function () { $('#dialogHelp').dialog('open'); }); $('#buttonHelpClose').click(function () { $('#dialogHelp').dialog('close'); }); $('#dialogConfirm').dialog({ autoOpen: false, minWidth: 400, resizable: false, modal: true }); $('#buttonConfirmExport').click(function () { $('#dialogConfirm').dialog('close'); $('#dialogExport').dialog('open'); }); $('#buttonConfirmNo').click(function () { $('#dialogConfirm').dialog('close'); }); $('#buttonSimulate').click(function () { if (network == null || network == undefined || network == {}) { alert('You need to create or import a network before you can start simulation.'); return; } }); // load the additional JavaScripts loadAdditionalResources(); }; /** * Fetch all the scripts not essential to UI asynchronously. All the * external libraries excluding the jquery core are fetched using this * method in addition to import and simulator js files. */ var loadAdditionalResources = function () { // Ensure that the files are fetched as JS. $.ajaxSetup({ cache: true, beforeSend: function (xhr) { xhr.overrideMimeType("text/javascript"); } }); $.getScript("include/jquery.simulate.js"); $.getScript("include/jquery.color-2.1.1.min.js", function () { jQuery.Color.hook("fill stroke"); }); $.getScript("include/biographer-ui.js", function () { bui.settings.css.stylesheetUrl = 'css/visualization-svg.css'; }); $.getScript("include/interact.js"); $.getScript("include/d3.v2.js"); //$.getScript("include/rickshaw.js"); $.getScript("include/libSBGN.js"); $.getScript("js/import.js"); $.getScript("js/export.js"); $.getScript("js/infobox.js"); $.getScript("js/editrule.js"); $.getScript("js/timeseries.js"); //$.getScript("js/attractors.js"); $.getScript("js/steadystates.js"); $.getScript("js/simulator.js"); //$.getScript("js/spellchecker.js"); $.ajaxSetup({ beforeSend: null }); }; /** * The event handler for a change in the value of the Graph Zoom slider. * A corresponding scale is applied to the selected graph tab. * @param {Event} event The event object containing information about the * type of event. * @param {UI} ui Contains the value of the slider. */ zoomGraph = function (event, ui) { // Get the index of the selected tab. var index = $('#tabs').tabs('option', 'selected'); var graph = null; // Get the correct bui.Graph instance depending on the current tab. if (index === 0) graph = networkGraph; // Exit if the graph has not been imported yet if (graph === null) return; // Scale the bui graph to the value set by the slider graph.scale(ui.value); graph.reduceTopLeftWhitespace(); }; /** * The event handler for a tab change. It just sets the slider value * for the current tab graph. * @param {Event} event The event object containing information about the * type of event. * @param {UI} ui Contains the index of the selected tab. */ changeTab = function (event, ui) { // select 1: Rules tab if (ui.index == 0 && network != null) $('#divNetworkLegend').css('visibility', 'visible'); else $('#divNetworkLegend').css('visibility', 'hidden'); if (ui.index == 1) $('#textRules').focus(); prevTab = ui.index; }; createDefaultNetwork = function () { plaintextImporter('demoNode* = not demoNode\n', false); }; /** * The event handler for opening the import dialog box. All the elements * are given a default value */ openImportDialog = function () { // If the simulator is running stop it. if (simulator !== null) simulator.stop(); // Set all values to their initial states. $('#fileNetwork').attr({ value: '' }); $('#dialogImport').dialog('open'); }; plaintextImporter = function (data, confirmed) { // Depending on the file type option checked in the import dialog box // call the appropriate importer // if a network is loaded already, confirm overwrite first if ((!confirmed) && (networkGraph !== null)) { // $('#buttonConfirmYes').unbind('click'); $('#buttonConfirmYes').click(function () { $('#buttonConfirmYes').unbind('click'); $('#dialogConfirm').dialog('close'); plaintextImporter(data, true); }); $('#dialogConfirm').dialog('open'); return; } var guessed = 'unrecognized'; var jsbgn = new jSBGN(); if ($('#formatGuess').attr('checked')) { if (data.indexOf(' and ') + data.indexOf(' or ') + data.indexOf('*') > -1) guessed = 'Python'; else if (data.indexOf(' & ') + data.indexOf(' | ') > -1) guessed = 'R'; else if ((data.indexOf(' && ') + data.indexOf(' || ') > -1) || (data.indexOf('"sbgnlang"') > -1)) guessed = 'jSBGN'; /* else if (data.indexOf('<gxl') > -1) guessed = 'GINML'; */ else { console.log('Import aborted: Inferring file format did not succeed.'); alert('Sorry,\nthe format of your file could not be inferred.\nPlease try specifying it manually in the import dialog.'); return; } console.log('Inferred file format: ' + guessed); } var result; var doLayout = true; if ($('#formatPyBooleanNet').attr('checked') || guessed == 'Python') result = jsbgn.importBooleanNetwork(data, '=', false); else if ($('#formatRBoolNet').attr('checked') || guessed == 'R') result = jsbgn.importBooleanNetwork(data, ',', false); /* else if ($('#formatGINML').attr('checked') || guessed == 'GINML') result = jsbgn.importGINML(data); */ else if ($('#formatjSBGN').attr('checked') || guessed == 'jSBGN') { result = jsbgn.importjSBGN(data); doLayout = false; } else { console.log('Import failed: Unrecognized file format'); alert('Import failed: Unrecognized file format'); return; } if (!result) { console.log('Import failed: There appear to be syntax errors in the input file.'); alert('Import failed: There appear to be syntax errors in your input file.'); return; } /* * Steady states: * Identify input/output states */ identifyIONodes(jsbgn.left, jsbgn.right); jsbgn.model = data; //$('#graphStateTransition').html(''); // Import the jSBGN object into a bui.Graph instance obj.importNetwork(jsbgn, '#tabNetwork', doLayout); $('#tabNetwork').bind('contextmenu', addNodeDialog); $('#textRules').prop('disabled', false); $('#textIteration').text(timeseriesLabelCounter); // Delete any previous instance of the Simulator and initialize a new one //if (simulator !== null) simulator.destroy(); //simulator = new Simulator(); destroySimulator(); // if ($('#formatSBML').attr('checked')) simulator.scopes = true; var settings = { simDelay: simDelay, oneClick: typeof ($('#optionsOneClick').attr('checked')) !== "undefined" }; initializeSimulator(jsbgn, settings, networkGraph); loadRulesText(); rulesChanged = false; $('.spellcheckWarning').remove(); highlightIONodes(); if (typeof ($('#optionsSimulateAfterImport').attr('checked')) !== "undefined") startSimulator(); }; /** * The event handler for the import file button in the import file dialog * box. The file is read using the appropriate boolean network importer. * The simulator is then initialized using this network. */ importFile = function () { // import file var files = $('#fileNetwork')[0].files; if (files.length === 0) { alert('Please choose a file to be imported.'); return; } var file = files[0]; // close import dialog $('#dialogImport').dialog('close'); // Create an instance of the file reader and jSBGN. var reader = new FileReader(); // This event handler is called when the file reading task is complete reader.onload = function (read) { // Get the data contained in the file plaintextImporter(read.target.result, false); }; reader.readAsText(file); }; importDemo1 = function () { // close import dialog $('#dialogImport').dialog('close'); setTimeout(function () { plaintextImporter($('#demoNetwork1').html(), false); }, 200); }; importDemo2 = function () { // close import dialog $('#dialogImport').dialog('close'); setTimeout(function () { plaintextImporter($('#demoNetwork2').html(), false); }, 200); }; /** * Import a jSBGN object into the Network tab by creating a new bui.Graph * instance. First the layouting is done and then the graph is scaled * appropriately. * @param {jSBGN} jsbgn The network in the form of a jSBGN object. * @param {string} tab The tab in which to display the graph. * @returns {bui.Graph} The graph for the network. */ this.importNetwork = function (jsbgn, tab, doLayout) { // only invoke d3 layouting, if doLayout was not specified or if it's true if (typeof doLayout == 'undefined' || doLayout) { // Do the layouting jsbgn.connectNodes(true); jsbgn.layoutGraph(); jsbgn.connectNodes(false); } // Fix Self-loop edges for (i in jsbgn.edges) { var edge = jsbgn.edges[i]; if (edge.source == edge.target) { edge.data.type = 'spline'; edge.data.handles = [{ "x": 80.25, "y": -136 }, { "x": -92.25, "y": -119 }]; } } $(tab).html(''); var graph = new bui.Graph($(tab)[0]); var handle = graph.suspendRedraw(20000); bui.importFromJSON(graph, jsbgn); // Center the graph and optionally scale it graph.reduceTopLeftWhitespace(); if (typeof ($('#optionsScale').attr('checked')) !== "undefined") graph.fitToPage(); graph.unsuspendRedraw(handle); // $('#sliderZoom').slider('option', 'value', graph.scale()); $('#tabs').tabs('select', tab); $('#divNetworkLegend').css('visibility', 'visible'); if (tab === '#graphStateTransition') transitionGraph = graph; else networkGraph = graph; }; this.getRandomSeed = function () { return Boolean(Math.round(Math.random())); }; /** * Get the seed to be given initially to the network. * @returns {Boolean} The seed for the node in the network. */ this.getInitialSeed = function () { if ($('#seedTrue').attr('checked')) return true; else if ($('#seedFalse').attr('checked')) return false; else if ($('#seedRandom').attr('checked')) return this.getRandomSeed(); else return true; }; /** * The event handler for opening the export dialog. The simulator is * stopped if it's running. */ openExportDialog = function () { if (network == null || network == undefined || network == {}) { alert('You need to create or import a network, before you can export it.'); return; } if (simulator !== null) simulator.stop(); $('#dialogExport').dialog('open'); }; var addNode = function (id, coords) { //Add node to the jSBGN var doc = new sb.Document(); doc.lang(sb.Language.AF); doc.createNode(id).type(sb.NodeType.Macromolecule).label(id); var jsbgn = JSON.parse(sb.io.write(doc, 'jsbgn')); network.nodes.push(jsbgn.nodes[0]); network.state[id] = controls.getInitialSeed(); network.freeze[id] = false; ruleFunctions[id] = rule2function(id, network.rules[id]); for (var j = 0; j <= iterationCounter; j++) states[j][id] = network.state[id]; //Add node physically to the graph var node = networkGraph.add(bui.Macromolecule, id); node.label(id); var drawables = networkGraph.drawables(); updateGraphNode(drawables, id); drawables[id].positionCenter(coords.x, coords.y); updateTimeseries(); }; var deleteNode = function (id) { //delete node from jSBGN delete network.state[id]; delete network.freeze[id]; delete ruleFunctions[id]; delete network.rules[id]; //delete node from other node's rules for (i in network.rules) { var rule = network.rules[i]; rule = rule.replace(/ /g, ''); var re = new RegExp('[&|]+!*' + id, 'g'); rule = rule.replace(re, ''); re = new RegExp('\\(' + id + '[&|]*', 'g'); rule = rule.replace(re, ''); var matches = rule.match(/\(!*[A-Za-z0-9_]+\)/g); for (j in matches) { rule = rule.replace(matches[j], matches[j].slice(1, matches[j].length - 1)); } network.rules[i] = rule; ruleFunctions[i] = rule2function(i, rule); } //delete node from nodes, edges, left, right for (i in network.nodes) { var node = network.nodes[i]; if (node.id == id) { network.nodes.splice(i, 1); break; } } for (i in network.edges) { var edge = network.edges[i]; if ((edge.source == id) || (edge.target == id)) { network.edges.splice(i, 1); } } for (i in network.left) { var node = network.left[i]; if (node == id) { network.left.splice(i, 1); break; } } for (i in network.right) { var node = network.right[i]; if (node == id) { network.right.splice(i, 1); break; } } for (var j = 0; j <= iterationCounter; j++) delete states[j][id]; //delete node from graph var drawables = networkGraph.drawables(); drawables[id].remove(); updateTimeseries(); //~ identifyIONodes(network.left, network.right); //~ highlightIONodes(); //~ createSteadyStates(); }; this.deleteNodeFromGraph = function (event) { var id = event.data; deleteNode(id); $('#dialogDeleteNode').dialog('close'); }; addNodeDialog = function (event) { if (running) { alert('You need to stop simulation before you can add nodes.'); event.preventDefault(); return; } if (event.ctrlKey) { event.preventDefault(); $('#dialogAddNode').dialog('open'); $('#textNodeID').val(''); $('#buttonAddNode').unbind('click'); $('#buttonAddNode').bind('click', networkGraph.toGraphCoords(event.clientX, event.clientY - $('#tabs > ul').height()), addNodeToGraph); } }; addNodeToGraph = function (event) { var id = $('#textNodeID').val(); if (network.state.hasOwnProperty(id)) { alert('A node with that name already exists.\nPlease choose a new name.'); } else if (id.match(/[A-Za-z0-9_]/g).length !== id.length) { alert('Illegal character in name!\nOnly alphanumeric characters and underscore are allowed.'); } else { addNode(id, event.data); } $('#dialogAddNode').dialog('close'); }; /** * The event handler for clicking the export file button of the export * file dialog box. Multiple file export options are supported, if * a graph is exported then a file is created of the specified graph * type. If the update rules are exported then the respective boolean * network file is generated. The link is passed as a data URI. */ exportFile = function () { // close the dialog and start to do the export $('#dialogExport').dialog('close'); // Get the bui.Graph instance of the select graph to export var graph, bn, content, jsbgn; graph = networkGraph; // export R if ($('#exportNetworkRBoolNet').attr('checked')) { bn = exportRBoolNet(network); content = "data:text/plain," + encodeURIComponent(bn); window.open(content, 'tmp'); } else // export Python if ($('#exportNetworkPyBooleanNet').attr('checked')) { bn = exportPythonBooleanNet(network); content = "data:text/plain," + encodeURIComponent(bn); window.open(content, 'tmp'); } else // export jSBGN if ($('#exportjSBGN').attr('checked')) { jsbgn = graph.toJSON(); jsbgn = $.extend(jsbgn, { rules: network.rules }); content = "data:application/json," + encodeURIComponent(JSON.stringify(jsbgn)); window.open(content, 'tmp'); } else // export SVG if ($('#exportSVG').attr('checked')) { var svg = graph.rawSVG(); content = "data:image/svg+xml," + encodeURIComponent(svg); window.open(content, 'tmp'); } // export Time Series if ($('#exportTimeseries').attr('checked')) { $('#tabs').tabs('select', '#tabTimeseries'); var svg = $('#divTimeseries > svg')[0].parentNode.innerHTML; content = "data:image/svg+xml," + encodeURIComponent(svg); window.open(content, 'tmp'); } }; };<file_sep>/* * The event handler for hovering over a node: displays update rule */ showRuleBox = function (event) { $('#boxInfo') .remove(); var id = $(this) .attr('id'); var rule = id + ' = ' + network.rules[id]; var mainEvent = event ? event : window.event; // var menuHeight = 41; // the height of <ul class="ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all"> // Create the info box $('<div/>', { id: 'boxInfo', text: rule, style: "left: " + event.clientX + "; top: " + event.clientY + "; width: auto;" }) .prependTo('#tabNetwork') .click(removeInfoBox); }; /* * The event handler for hovering over a node. Displays The state * defined by the node for the network. */ showStateBox = function () { var id = $(this) .attr('id'); // Get the state from the node id which is a map var state = decodeStateMap(id), i; var info = ''; for (i in state) info += i + ': ' + state[i] + '<br>'; // Generate the info box $('<div/>', { id: 'boxInfo', html: info }) .prependTo('#graphStateTransition'); }; /* * The event handler for unhovering a node: delete info box */ removeInfoBox = function () { $('#boxInfo') .remove(); };<file_sep> function jSBGN_to_d3(network) { var i; for (i in network.nodes) { n = network.nodes[i]; n.index = i; n.x = 10; n.y = 10; n.px = 1; n.py = 1; n.fixed = false; n.weight = 1; } function getNodeById(id) { console.log(id); var i; for (i in network.nodes) { if (network.nodes[i].id == id || network.nodes[i] == id) { // console.log(i+': '+network.nodes[i].id); return network.nodes[i]; } } console.error('node '+id+' not found. created.'); return network.nodes.append( {'index':network.nodes.length, 'x':1, 'y':1, 'fixed':false} ); } // // d3 expects edge source and targets specified as object links, rather than ids or indices // var i; for (i in network.edges) { network.edges[i].sourceNode = getNodeById(network.edges[i].source); network.edges[i].targetNode = getNodeById(network.edges[i].target); console.log('edge '+i+' from '+network.edges[i].sourceNode.id+' to '+network.edges[i].targetNode.id); } return network; } <file_sep>Online boolean network Simulator for demo use ====================================== This webapp allows the user to load Boolean networks in various formats, display and interactively simulate them, it's only for demo use now, since I iterates the model using the synchronous state updating method, which is not quite proper for most cases. For getting use of updating method like general asynchronous and random order asynchronous, please refer to https://github.com/ialbert/booleannet. Have fun! <file_sep>/** * Import an SBML file into the jSBGN object. The libSBGN.js library is * used as the initial importer. All the compartment and process nodes * are disabled. * @param {File} file The file object of the SBML file. * @param {string} data The data contained in the SBML file. */ jSBGN.prototype.importSBML = function (file, data) { // File submitted to server using a form var formData = new FormData(); formData.append('file', file); /* // The SBML File is uploaded to the server so that it can be opened by // libscopes which runs on the server $.ajax({ url: serverURL + '/Put/UploadSBML', type: 'POST', data: formData, contentType: false, processData: false, async: false }); */ // Use libSBGN.js's SBML reader var reader = new sb.io.SbmlReader(); var doc = reader.parseText(data); var jsbgn = JSON.parse(sb.io.write(doc, 'jsbgn')); this.nodes = jsbgn.nodes; this.edges = jsbgn.edges; this.rules = {}; // Disable rules for nodes that are of type compartment or process var i, node; for (i in this.nodes) { node = this.nodes[i]; node.data.label = node.id; if ((node.sbo === sb.sbo.NodeTypeMapping[sb.NodeType.Compartment]) || (node.sbo === sb.sbo.NodeTypeMapping[sb.NodeType.Process])) this.rules[node.id] = ''; else this.rules[node.id] = 'update'; } }; <file_sep> all: make bui make rickshaw exit bui: if [ ! -e 'include/biographer' ]; then \ hg clone https://code.google.com/p/biographer/ include/biographer; \ else \ cd include/biographer; hg pull; \ fi cd include/biographer/bui/src/main/javascript; \ cat 'intro' \ 'settings.js' \ 'core.js' \ 'util.js' \ 'observable.js' \ 'edges/connectingArcs.js' \ 'graph.js' \ 'drawable.js' \ 'node/node.js' \ 'node/labelable.js' \ 'node/edgeHandle.js' \ 'node/association.js' \ 'node/dissociation.js' \ 'node/logicalOperator.js' \ 'node/splineEdgeHandle.js' \ 'node/rectangularNode.js' \ 'node/unitOfInformation.js' \ 'node/macromolecule.js' \ 'node/variableValue.js' \ 'node/complex.js' \ 'node/perturbation.js' \ 'node/phenotype.js' \ 'node/tag.js' \ 'node/compartment.js' \ 'node/nucleicAcidFeature.js' \ 'node/stateVariable.js' \ 'node/simpleChemical.js' \ 'node/unspecifiedEntity.js' \ 'node/emptySet.js' \ 'node/process.js' \ 'edges/attachedDrawable.js' \ 'edges/abstractLine.js' \ 'edges/straightLine.js' \ 'edges/spline.js' \ 'edges/edge.js' \ 'sboMappings.js' \ 'importer.js' \ 'layouter.js' \ 'layout-grid.js' \ 'outro' > ../../../../../biographer-ui.js rickshaw: wget https://raw.github.com/shutterstock/rickshaw/master/rickshaw.js -O include/rickshaw.js <file_sep> /* * Rules tab has been selected. * Write current network rule configuration to edit field ! */ loadRulesText = function () { var text = ''; $('#textRules').val(''); for (node in network.rules) { text += node + ' = ' + network.rules[node] + '\n'; } //console.log(text); $('#textRules').val(text); $('#textRules').attr('backup', text); if (running) $('#textRules').prop('disabled', true); else $('#textRules').prop('disabled', false); }; // // Clicking "Save Rules" button in "Rules" tab // Read and parse edit field, refresh network graph if successfull // reloadUpdateRules = function () { if ($('#textRules').prop('disabled')) { return false; } var jsbgn = new jSBGN(); if (!jsbgn.importBooleanNetwork($('#textRules').val(), '=', true)) { alert('Please check the syntax of your update rules'); return false; } var jsbgnNodes = {}; for (i in jsbgn.nodes) { var id = jsbgn.nodes[i].id; jsbgnNodes[id] = true; } var added = jsbgn.nodes.filter(function (i) { return !network.state.hasOwnProperty(i.id); }); var removed = network.nodes.filter(function (i) { return !jsbgnNodes.hasOwnProperty(i.id); }); var same = jsbgn.nodes.filter(function (i) { return network.state.hasOwnProperty(i.id); }); // deepcopy as backup in case of errors var oldRules = jQuery.extend(true, {}, ruleFunctions); for (i in same) { var id = same[i].id; ruleFunctions[id] = rule2function(id, jsbgn.rules[id]); if (ruleFunctions[id] == null) { alert('Please check the syntax of your update rules'); ruleFunctions = oldRules; // fall back to previous rules return false; } } // deepcopy as backup in case of errors var oldNetwork = jQuery.extend(true, {}, network); for (i in added) { var id = added[i].id; network.state[id] = controls.getInitialSeed(); for (var j = 0; j <= iterationCounter; j++) states[j][id] = network.state[id]; network.freeze[id] = false; ruleFunctions[id] = rule2function(id, jsbgn.rules[id]); if (ruleFunctions[id] == null) { alert('Please check the syntax of your update rules'); network = oldNetwork; // fall back to previous network ruleFunctions = oldRules; // and previous rules return false; } } for (i in removed) { var id = removed[i].id; delete network.state[id]; delete network.freeze[id]; delete ruleFunctions[id]; } // time consuming, could be reduced controls.importNetwork(jsbgn, '#tabNetwork'); updateAllGraphNodes(network.state, networkGraph); network.rules = jsbgn.rules; network.nodes = jsbgn.nodes; network.edges = jsbgn.edges; network.left = jsbgn.left; network.right = jsbgn.right; //updateTimeseries(); resetTimeseries(); //~ identifyIONodes(network.left, network.right); //~ highlightIONodes(); //~ createSteadyStates(); // Save was successfull $('#labelSaved').css('visibility', 'hidden'); $('#textRules').attr('backup', $('#textRules').val()); return true; }; revertToSavedVersion = function() { var backup = $('#textRules').attr('backup'); if (backup != undefined) { $('#textRules').val(backup).focus(); rulesChanged = false; $('#labelSaved').css('visibility', 'hidden'); $('.spellcheckWarning').remove(); spell.check(); } }; $('#buttonSaveRules').click(reloadUpdateRules); $('#buttonDiscardChanges').click(revertToSavedVersion); <file_sep>/** * Import a GINML file into the jSBGN object. The jQuery XML library * makes parsing simple. By just passing a tag, all the respective * elements can be selected. * @param {string} data The data contained in the GINML file. */ jSBGN.prototype.importGINML = function (data) { // Use jQuery's XML parser var xml; try { xml = $.parseXML(data); } catch (e) { return false; } var nodes = $(xml).find('node'); var edges = $(xml).find('edge'); // Set the SBGN language to Activity Flow var doc = new sb.Document(); doc.lang(sb.Language.AF); // Extract all nodes in the XML file $(nodes).each(function () { var id = $(this).attr('id'); doc.createNode(id).type(sb.NodeType.Macromolecule).label(id); }); // Extract all edges taking care of the sign $(edges).each(function () { var sign = $(this).attr('sign'), type; var id = $(this).attr('id'); if (typeof (sign) !== 'undefined') { if (sign === 'positive') type = sb.ArcType.PositiveInfluence; else if (sign === 'negative') type = sb.ArcType.NegativeInfluence; } else type = sb.ArcType.UnknownInfluence; doc.createArc(id).type(type).source($(this).attr('from')).target($(this).attr('to')); }); // Generate rules from the GINML file // There are two types of rules, the rule defined by the connecting // arcs and the other rule defined by the parameter tag for each node. var rules = {}; $(nodes).each(function () { var i, rule; var arcs = doc.arcs(), incoming; var id = $(this).attr('id'); incoming = []; // Create the rule given by the edges rule1 = ''; for (i in arcs) { if (arcs[i].target().id() === id) { if ( rule1.length > 0 ) rule1 += ' || '; rule1 += arcs[i].source().id(); incoming.push(arcs[i].id()); } } // Add rules derived from the Active Interations for a node.' rule2 = 'false'; $(this).find('parameter').each(function () { var i, links; links = $(this).attr('idActiveInteractions').split(' '); incoming = incoming.filter(function (i) { return links.indexOf(i) < 0; }); rule = ''; for (i in links){ if ( rule.length > 0 ) rule += ' && '; rule += doc.arc(links[i]).source().id(); } for (i in incoming) { if ( rule.length > 0 ) rule += ' && '; rule += '(!' + doc.arc(incoming[i]).source().id() + ')'; } rule2 += ' || (' + rule + ')'; }); var base = Boolean(parseInt($(this).attr('basevalue'), 10)); if (rule1.length > 0) { if (base) { rules[id] = '!(' + rule1 + ') || '; } else { rules[id] = ''; } if (rule2 == 'false') { rules[id] += rule2; } else { rules[id] += '((' + rule1 + ') && (' + rule2 + '))'; } } else { rules[id] = rule2; } rules[id] = rules[id].replace(/false \|\| /g, ''); rules[id] = rules[id].replace(/ \|\| false/g, ''); }); // Export the SBGN to jSBGN var jsbgn = JSON.parse(sb.io.write(doc, 'jsbgn')); this.nodes = jsbgn.nodes; this.edges = jsbgn.edges; this.rules = rules; this.right = Object.keys(rules); this.left = Object.keys(rules); return true; };<file_sep>var encounteredStateCombinations = []; var networkInputNodes, networkOutputNodes; /* * create an empty table in the SteadyStates tab */ var identifyIONodes = function (leftNodes, rightNodes) { networkInputNodes = rightNodes.filter(function (i) { return leftNodes.indexOf(i) < 0; }); networkOutputNodes = leftNodes.filter(function (i) { return rightNodes.indexOf(i) < 0; }); } var highlightIONodes = function () { input_color = "#3f84c6"; output_color = "#c63fb8"; for (i in networkInputNodes) { nodeid = networkInputNodes[i]; $('#' + nodeid).css('stroke', input_color); } for (i in networkOutputNodes) { nodeid = networkOutputNodes[i]; $('#' + nodeid).css('stroke', output_color); } } createSteadyStates = function () { // var html = "<tr><th colspan="+(networkInputNodes.length+networkOutputNodes.length+1)+">Passed steady states</th></tr>\n"; var html = "<tr><th colspan=" + networkInputNodes.length + ">Input nodes</th>"; html += '<th style="width: 10px;">&nbsp;</th>'; html += "<th colspan=" + networkOutputNodes.length + ">Output nodes</th></tr>"; html += "<tr>\n"; var i; for (i in networkInputNodes) { html += "<th>" + networkInputNodes[i] + "</th>"; } html += "<th></th>"; for (i in networkOutputNodes) { html += "<th>" + networkOutputNodes[i] + "</th>"; } html += "</tr>\n"; // set content of SteadyStates <table> $("#SteadyStates") .html(html); } appendSteadyStatesTable = function (stateCombination) { var row = "<tr>"; var i; for (i in stateCombination) { // spacer between input and output nodes if (i == networkInputNodes.length) row += '<td style="border: none;"></td>'; // green for on, white for off var state = "off"; var color = "white"; if (stateCombination[i]) { state = "on"; color = "#10d010"; } row += '<td style="background-color: ' + color + ';">' + state + '</td>'; } row += "</tr>\n"; $("#SteadyStates") .append(row); } workaroundChromiumArrayBug = function (stateCombination) { var result = ""; for (i in stateCombination) { if (stateCombination[i]) { result += "1"; } else { result += "0"; } } return result; } /* * every time, the statespace is updated, check if * a new state combination has occured */ updateSteadyStates = function () { var currentStateCombination = []; var i; for (i in networkInputNodes) { currentStateCombination.push(network.state[networkInputNodes[i]]); } for (i in networkOutputNodes) { currentStateCombination.push(network.state[networkOutputNodes[i]]); } s = workaroundChromiumArrayBug(currentStateCombination); if (encounteredStateCombinations.indexOf(s) < 0) { encounteredStateCombinations.push(s); appendSteadyStatesTable(currentStateCombination); } }
8c81bd921b86046221313e2b1a864deacb209d36
[ "Makefile", "Markdown", "JavaScript", "Python" ]
14
Makefile
xiongzhp/BoolnetOnline
911e38bc2d7e14466f5fa912a68143b85a96371b
cacf462a51f2fe2a2fb2f86bb3342df170f951a7
refs/heads/master
<repo_name>SchleimKeim/uebung5_09112018<file_sep>/src/zhaw/uebung05/app/Main.java package zhaw.uebung05.app; import java.io.IOException; import javax.swing.JFileChooser; import javax.swing.filechooser.FileSystemView; import zhaw.uebung05.app.ActivityController; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Menu; import javafx.scene.control.MenuBar; import javafx.scene.control.MenuItem; import javafx.scene.layout.BorderPane; import javafx.stage.Stage; import zhaw.uebung05.model.Activities; public class Main extends Application { private Stage _primaryStage; private BorderPane _rootLayout; private Scene _scene; private Button _btnRoll; private Activities _activities; private MenuBar _menuBar; private Menu _menuFile; private javafx.scene.control.MenuItem _load; private javafx.scene.control.MenuItem _save; private javafx.scene.control.MenuItem _exit; @Override public void start(Stage primaryStage) throws Exception { _primaryStage = primaryStage; _primaryStage.setTitle("Entscheidungsknopf"); _activities = new Activities(); initRootLayout(); setUpControls(); setUpEvents(); } public Stage getPrimaryStage() { return _primaryStage; } private void setUpEvents() { _btnRoll.setOnMouseClicked((me) -> { _btnRoll.setText(_activities.getRandomActivity()); }); _save.setOnAction(ae -> { final JFileChooser chooser = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory()); chooser.showSaveDialog(null); new ActivityController(_activities).Save(chooser.getSelectedFile().getPath()); }); _load.setOnAction(ae -> { final JFileChooser chooser = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory()); chooser.showOpenDialog(null); _activities = new ActivityController(null).Load(chooser.getSelectedFile().getPath()); }); _exit.setOnAction(ae -> { _primaryStage.close(); }); } private void setUpControls() throws Exception { _btnRoll = (Button)_scene.lookup("#btnRoll"); _menuBar = (MenuBar)_scene.lookup("#menuBar"); _menuFile = (Menu)_menuBar.getMenus().stream().findFirst().get(); if(_menuFile == null) throw new Exception("menuFile nicht gefunden!"); _load = getMenuItem(_menuFile, "miLoad"); _save = getMenuItem(_menuFile, "miSave"); _exit = getMenuItem(_menuFile, "miQuit"); if(_load == null || _save == null || _exit == null) throw new Exception("Whoops!"); } private MenuItem getMenuItem(Menu menu, String key) { MenuItem item = null; for (MenuItem menuItem : menu.getItems()) { String id = menuItem.getId(); if(id.equalsIgnoreCase(key)) { item = menuItem; break; } } return item; } private void initRootLayout() { try { // Load root layout from fxml file FXMLLoader loader = new FXMLLoader(); loader.setLocation(Main.class.getResource("../view/MainView.fxml")); _rootLayout = (BorderPane) loader.load(); // Show the scene conaining the root layout. _scene = new Scene(_rootLayout); _primaryStage.setScene(_scene); _primaryStage.show(); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { launch(args); } } <file_sep>/src/zhaw/uebung05/model/Activities.java package zhaw.uebung05.model; import java.util.ArrayList; import java.util.Random; public class Activities implements java.io.Serializable { private static final long serialVersionUID = -8462533337964093086L; private String[] _defaultActivities = new String[] { "Kino", "Konzert", "Tanzen", "Essen" }; private String[] _activities; public Activities(ArrayList<String> activities) { if(activities == null) { _activities = _defaultActivities; return; } ArrayList<String> list = new ArrayList<String>(); for (String activity : activities) { list.add(activity); } _activities = (String[]) list.toArray(); } public Activities() { } public String getRandomActivity() { return _activities[new Random().ints(0, _activities.length).findFirst().getAsInt()]; } }
20e7e5f9af69f6d4a35b7253c9d447ca6094cdcd
[ "Java" ]
2
Java
SchleimKeim/uebung5_09112018
6497018b2af2d313290cd047f3a0046c660b6f58
334261c545cd8a48139dcd897965bb8a9e43c95b
refs/heads/master
<file_sep>import React, { Component } from 'react'; import { Layout, Menu, Icon, Avatar } from 'antd'; import Home from './design/Home'; import About from './design/About'; import Profile from './design/Profile'; import Work from './design/Work'; import Referal from './design/Referal'; import { Switch, Link } from "react-router-dom"; const { Content, Footer, Sider } = Layout; //icons export default class LayoutMain extends Component { state = { collapsed: true, }; componentDidMount() { this.setState({ view: <Home /> }) } onCollapse = collapsed => { console.log(collapsed); this.setState({ collapsed }); }; getLocation = (data) => { console.log(data.key) if (data.key === '1') { this.setState({ view: <Home /> }) } else if (data.key === '2') { this.setState({ view: <About/> }) } else if (data.key === '3') { this.setState({ view: <Profile/> }) } else if (data.key === '4') { this.setState({ view: <Work/> }) } else if (data.key === '5') { this.setState({ view: <Referal/> }) } } render() { return ( <div> <Layout style={{ minHeight: '100vh', }}> <Sider collapsible collapsed={this.state.collapsed} > <div className="logo"> <h3>RB</h3> </div> <Menu onClick={this.getLocation} defaultSelectedKeys={['1']} mode="inline"> <Menu.Item key="1" > <Icon type="home" /> <span>Home</span> </Menu.Item> <Menu.Item key="2"> <Icon type="usergroup-add" /> <span>Profile</span> </Menu.Item> <Menu.Item key="3"> <Icon type="credit-card" /> <span>About</span> </Menu.Item> <Menu.Item key="4"> <Icon type="user" /> <span>Work</span> </Menu.Item> <Menu.Item key="5"> <Icon type="monitor" /> <span>Referal</span> </Menu.Item> </Menu> </Sider> <Layout> <Content> <nav className="uk-navbar-container" style={{ background: '#fff' }} uk-navbar="true"> <div className="uk-navbar-left"> <ul className="uk-navbar-nav"> <li> <Link to="#"> Resume Builder App </Link> </li> </ul> </div> <div className="uk-navbar-right"> <ul className="uk-navbar-nav"> <li> <Link to="#"> <Avatar className="uk-margin-right" src="https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png" /> : Account </Link> <div className="uk-navbar-dropdown"> <ul className="uk-nav uk-navbar-dropdown-nav"> <li className="uk-active"><Link to="#" onClick={this.logout}>Logout</Link></li> </ul> </div> </li> </ul> </div> </nav> <div style={{ padding: 24, background: '#F0F4F7', minHeight: 360 }}> <Switch onChange={this.handleChange}> { this.state.view } </Switch> </div> </Content> <Footer style={{ textAlign: 'center', fontSize: '15px', letterSpacing: '1px', color: '#29435d', fontWeight: '600' }}>A PINKFRY PRODUCT </Footer> </Layout> </Layout> </div> ) } }
620ec5b1a227af496947988ac93b056a17d6d9c7
[ "JavaScript" ]
1
JavaScript
aafi786/resumebuilder-dash
16c1daa048236606fceeda53df369b8df8140d8a
1524022070b2329a475ea1dd23641e33014cdd43
refs/heads/master
<file_sep>!****************************************************************************** ! MODULE: mercury_constant !****************************************************************************** ! ! DESCRIPTION: !> @brief Global constant of the Mercury Code, numerical constant that fix !! some numerical problems. ! !****************************************************************************** module mercury_constant use types_numeriques implicit none integer, parameter :: CMAX = 1000 !< CMAX = maximum number of close-encounter minima monitored simultaneously integer, parameter :: NMESS = 1000 !< NMESS = maximum number of messages in message.in integer, parameter :: NFILES = 5000 !< NFILES = maximum number of files that can be open at the same time real(double_precision), parameter :: HUGE = 9.9d29 !< HUGE = an implausibly large number real(double_precision), parameter :: TINY = 4.D-15 !< A small number !... convergence criteria for danby real(double_precision), parameter :: DANBYAC= 1.0d-14 real(double_precision), parameter :: DANBYB = 1.0d-13 !... loop limits in the Laguerre attempts integer, parameter :: NLAG1 = 1000 integer, parameter :: NLAG2 = 1000 end module mercury_constant <file_sep>import os os.system('rm -rf *.dmp *.tmp *.out *.aei ') <file_sep>!****************************************************************************** ! MODULE: mercury_globals !****************************************************************************** ! ! DESCRIPTION: !> @brief Modules that contains all the globals variables of mercury ! !****************************************************************************** module mercury_globals use types_numeriques use mercury_constant implicit none integer :: nb_bodies_initial !< number of bodies when we start the simulation. Used for local variables in several modules. integer, dimension(14) :: opt = (/0,1,1,2,0,1,0,0,0,0,0,1,0,0/) !< Default options (can be overwritten later in the code) for mercury.\n !!\n OPT(1) = close-encounter option (0=stop after an encounter, 1=continue) !!\n OPT(2) = collision option (0=no collisions, 1=merge, 2=merge+fragment) !!\n OPT(3) = time style (0=days 1=Greg.date 2/3=days/years w/respect to start) !!\n OPT(4) = o/p precision (1,2,3 = 4,9,15 significant figures) !!\n OPT(5) = < Not used at present > !!\n OPT(6) = < Not used at present > !!\n OPT(7) = apply post-Newtonian correction? (0=no, 1=yes) !!\n OPT(8) = apply user-defined force routine mfo_user (0=no, 1=yes) !!\n OPT(9) = apply pebble accretion routine massgrowth (0=no, 1=yes) !!\n OPT(10) = apply inner viscous heated disk region (0=no, 1=yes) !!\n OPT(11) = include the time evolution of accretion rate (0=no, 1=yes) !!\n OPT(12) = include disk migration (0=no, 1= typeI, 2= both typeI&II) !!\n OPT(13) = include pebble isolation mass (0=no, 1=yes) !!\n OPT(14) = include gas accretion (0=no, 1=yes) character(len=80), dimension(NMESS) :: mem !< Various messages and strings used by mercury integer, dimension(NMESS) :: lmem !< the length of each string of the 'mem' elements character(len=80), dimension(3) :: outfile !< filenames for output files (*.out) !!\n OUTFILE (1) = osculating coordinates/velocities and masses !!\n OUTFILE (2) = close encounter details !!\n OUTFILE (3) = information file character(len=80), dimension(4) :: dumpfile !< filenames for dump files (*.dmp) !!\n DUMPFILE (1) = Big-body data !!\n DUMPFILE (2) = Small-body data !!\n DUMPFILE (3) = integration parameters !!\n DUMPFILE (4) = restart file integer :: algor !< An index that represent the algorithm used. \n !!\n ALGOR = 1 -> Mixed-variable symplectic !!\n 2 -> Bulirsch-Stoer integrator !!\n 3 -> " " (conservative systems only) !!\n 4 -> RA15 `radau' integrator !!\n 10 -> Hybrid MVS/BS (democratic-heliocentric coords) !!\n 11 -> Close-binary hybrid (close-binary coords) !!\n 12 -> Wide-binary hybrid (wide-binary coords) real(double_precision) :: tstart !< epoch of first required output (days) real(double_precision) :: tstop !< epoch final required output (days) real(double_precision) :: tdump !< time of next data dump (days) real(double_precision) :: dtout !< data output interval (days) real(double_precision) :: dtdump !< data-dump interval (days) real(double_precision) :: dtfun !< interval for other periodic effects (e.g. check for ejections) real(double_precision) :: rmax !< heliocentric distance at which objects are considered ejected (AU) real(double_precision) :: alpha_t !< turbulent alpha real(double_precision) :: alpha !< viscous alpha real(double_precision) :: mdot_gas0 !< initial gas accretion rate real(double_precision) :: L_s !< stellar luninosity real(double_precision) :: Rdisk0 !< power index of aspect ratio real(double_precision) :: Mdot_peb !< disk pebble mass flux (Mearth/yr) real(double_precision) :: tau_s !< pebble stokes number real(double_precision) :: kap !< opacity coefficient real(double_precision) :: t0_dep !< onset time of disk dispersal [Myr] real(double_precision) :: tau_dep !< disk dispersal timescale [Myr] end module mercury_globals <file_sep>!****************************************************************************** ! MODULE: algo_mvs !****************************************************************************** ! ! DESCRIPTION: !> @brief Modules that gather various functions about the mvs !! algorithm.\n\n !! The standard symplectic (MVS) algorithm is described in J.Widsom and !! M.Holman (1991) Astronomical Journal, vol 102, pp1528. ! !****************************************************************************** module algo_mvs !************************************************************* !** Modules that gather various functions about the mvs !** algorithm. !** !** Version 1.0 - june 2011 !************************************************************* use types_numeriques use mercury_globals use system_properties use user_module use forces, only : mfo_ngf implicit none private ! values that need to be saved in mdt_mvs real(double_precision), dimension(:,:), allocatable :: a, xj, angf, ausr ! (3,Number of bodies) real(double_precision), dimension(:), allocatable :: gm ! (Number of bodies) public :: mdt_mvs, mco_h2mvs, mco_mvs2h, mco_h2j, allocate_mvs contains !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% !> @author !> <NAME> ! !> @date 2011 ! ! DESCRIPTION: !> @brief allocate various private variable of the module to avoid !! testing at each timestep ! !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% subroutine allocate_mvs(nb_bodies) implicit none integer, intent(in) :: nb_bodies !< [in] number of bodies, that is, the size of the arrays if (.not. allocated(a)) then allocate(a(3,nb_bodies)) a(1:3,1:nb_bodies) = 0.d0 end if if (.not. allocated(angf)) then allocate(angf(3,nb_bodies)) angf(1:3,1:nb_bodies) = 0.d0 end if if (.not. allocated(ausr)) then allocate(ausr(3,nb_bodies)) ausr(1:3,1:nb_bodies) = 0.d0 end if if (.not. allocated(xj)) then allocate(xj(3,nb_bodies)) xj(1:3,1:nb_bodies) = 0.d0 end if if (.not. allocated(gm)) then allocate(gm(nb_bodies)) gm(1:nb_bodies) = 0.d0 end if end subroutine allocate_mvs !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% !> @author !> <NAME> ! !> @date 28 March 2001 ! ! DESCRIPTION: !> @brief Applies an inverse symplectic corrector, which converts coordinates with !! respect to the central body to integrator coordinates for a second-order !! mixed-variable symplectic integrator. ! !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% subroutine mco_h2mvs (time,jcen,nbod,nbig,h,m,xh,vh,x,v,ngf,ngflag,rphys) use physical_constant use mercury_constant use drift implicit none ! Input integer, intent(in) :: nbod !< [in] current number of bodies (1: star; 2-nbig: big bodies; nbig+1-nbod: small bodies) integer, intent(in) :: nbig !< [in] current number of big bodies (ones that perturb everything else) integer, intent(in) :: ngflag !< [in] do any bodies experience non-grav. forces? !!\n ( 0 = no non-grav forces) !!\n 1 = cometary jets only !!\n 2 = radiation pressure/P-R drag only !!\n 3 = both real(double_precision), intent(in) :: time !< [in] current epoch (days) real(double_precision), intent(in) :: jcen(3) !< [in] J2,J4,J6 for central body (units of RCEN^i for Ji) real(double_precision), intent(in) :: h !< [in] current integration timestep (days) real(double_precision), intent(in) :: m(nbod) !< [in] mass (in solar masses * K2) real(double_precision), intent(in) :: rphys(nbod) !< [in] raidus (in AU) real(double_precision), intent(in) :: xh(3,nbod) !< [in] coordinates (x,y,z) with respect to the central body (AU) real(double_precision), intent(in) :: vh(3,nbod) !< [in] velocities (vx,vy,vz) with respect to the central body (AU/day) real(double_precision), intent(in) :: ngf(4,nbod) !< [in] non gravitational forces parameters !! \n(1-3) cometary non-gravitational (jet) force parameters !! \n(4) beta parameter for radiation pressure and P-R drag ! Input/Output real(double_precision), intent(inout) :: x(3,nbod) real(double_precision), intent(inout) :: v(3,nbod) ! Local integer :: j,k,iflag,stat(nb_bodies_initial) real(double_precision) :: minside,msofar,gm(nb_bodies_initial) real(double_precision) :: a(3,nb_bodies_initial),xj(3,nb_bodies_initial),vj(3,nb_bodies_initial) real(double_precision) :: ha(2),hb(2),rt10,angf(3,nb_bodies_initial),ausr(3,nb_bodies_initial) !------------------------------------------------------------------------------ rt10 = sqrt(10.d0) ha(1) = -h * rt10 / 5.d0 hb(1) = -h * rt10 / 24.d0 ha(2) = -h * rt10 * 3.d0 / 10.d0 hb(2) = h * rt10 / 72.d0 do j = 2, nbod angf(1,j) = 0.d0 angf(2,j) = 0.d0 angf(3,j) = 0.d0 ausr(1,j) = 0.d0 ausr(2,j) = 0.d0 ausr(3,j) = 0.d0 end do call mco_iden (time,jcen,nbod,nbig,h,m,xh,vh,x,v,ngf,ngflag) ! Calculate effective central masses for Kepler drifts minside = m(1) do j = 2, nbig msofar = minside + m(j) gm(j) = m(1) * msofar / minside minside = msofar end do do k = 1, 2 ! Advance Keplerian Hamiltonian (Jacobi/helio coords for Big/Small bodies) call mco_h2j (jcen,nbig,nbig,h,m,x,v,xj,vj) do j = 2, nbig iflag = 0 call drift_one (gm(j),xj(1,j),xj(2,j),xj(3,j),vj(1,j),vj(2,j),vj(3,j),ha(k),iflag) end do do j = nbig + 1, nbod iflag = 0 call drift_one (m(1),x(1,j),x(2,j),x(3,j),v(1,j),v(2,j),v(3,j),ha(k),iflag) end do ! Advance Interaction Hamiltonian call mco_j2h (time,jcen,nbig,nbig,h,m,xj,vj,x,v,ngf,ngflag) call mfo_mvs (jcen,nbod,nbig,m,x,xj,a,stat) ! If required, apply non-gravitational and user-defined forces if (opt(8).eq.1) call mfo_user (time,jcen,nbod,nbig,m,rphys,x,v,ausr) if ((ngflag.eq.1).or.(ngflag.eq.3)) call mfo_ngf (nbod,x,v,angf,ngf) do j = 2, nbod v(1,j) = v(1,j) + hb(k) * (angf(1,j) + ausr(1,j) + a(1,j)) v(2,j) = v(2,j) + hb(k) * (angf(2,j) + ausr(2,j) + a(2,j)) v(3,j) = v(3,j) + hb(k) * (angf(3,j) + ausr(3,j) + a(3,j)) end do ! Advance Keplerian Hamiltonian (Jacobi/helio coords for Big/Small bodies) call mco_h2j (jcen,nbig,nbig,h,m,x,v,xj,vj) do j = 2, nbig iflag = 0 call drift_one (gm(j),xj(1,j),xj(2,j),xj(3,j),vj(1,j),vj(2,j),vj(3,j),-2.d0*ha(k),iflag) end do do j = nbig + 1, nbod iflag = 0 call drift_one (m(1),x(1,j),x(2,j),x(3,j),v(1,j),v(2,j),v(3,j),-2.d0*ha(k),iflag) end do ! Advance Interaction Hamiltonian call mco_j2h (time,jcen,nbig,nbig,h,m,xj,vj,x,v,ngf,ngflag) call mfo_mvs (jcen,nbod,nbig,m,x,xj,a,stat) ! If required, apply non-gravitational and user-defined forces if (opt(8).eq.1) call mfo_user (time,jcen,nbod,nbig,m,rphys,x,v,ausr) if ((ngflag.eq.1).or.(ngflag.eq.3)) call mfo_ngf (nbod,x,v,angf,ngf) do j = 2, nbod v(1,j) = v(1,j) - hb(k) * (angf(1,j) + ausr(1,j) + a(1,j)) v(2,j) = v(2,j) - hb(k) * (angf(2,j) + ausr(2,j) + a(2,j)) v(3,j) = v(3,j) - hb(k) * (angf(3,j) + ausr(3,j) + a(3,j)) end do ! Advance Keplerian Hamiltonian (Jacobi/helio coords for Big/Small bodies) call mco_h2j (jcen,nbig,nbig,h,m,x,v,xj,vj) do j = 2, nbig iflag = 0 call drift_one (gm(j),xj(1,j),xj(2,j),xj(3,j),vj(1,j),vj(2,j),vj(3,j),ha(k),iflag) end do do j = nbig + 1, nbod iflag = 0 call drift_one (m(1),x(1,j),x(2,j),x(3,j),v(1,j),v(2,j),v(3,j),ha(k),iflag) end do call mco_j2h (time,jcen,nbig,nbig,h,m,xj,vj,x,v,ngf,ngflag) end do !------------------------------------------------------------------------------ return end subroutine mco_h2mvs !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% !> @author !> <NAME> ! !> @date 28 March 2001 ! ! DESCRIPTION: !> @brief Applies a symplectic corrector, which converts coordinates for a second- !! order mixed-variable symplectic integrator to ones with respect to the !! central body. ! !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% subroutine mco_mvs2h (time,jcen,nbod,nbig,h,m,x,v,xh,vh,ngf,ngflag,rphys) use physical_constant use mercury_constant use drift implicit none ! Input integer, intent(in) :: nbod !< [in] current number of bodies (1: star; 2-nbig: big bodies; nbig+1-nbod: small bodies) integer, intent(in) :: nbig !< [in] current number of big bodies (ones that perturb everything else) integer, intent(in) :: ngflag !< [in] do any bodies experience non-grav. forces? !!\n ( 0 = no non-grav forces) !!\n 1 = cometary jets only !!\n 2 = radiation pressure/P-R drag only !!\n 3 = both real(double_precision), intent(in) :: time !< [in] current epoch (days) real(double_precision), intent(in) :: jcen(3) !< [in] J2,J4,J6 for central body (units of RCEN^i for Ji) real(double_precision), intent(in) :: h !< [in] current integration timestep (days) real(double_precision), intent(in) :: m(nbod) !< [in] mass (in solar masses * K2) real(double_precision), intent(in) :: rphys(nbod) !< [in] radius (in AU) real(double_precision), intent(in) :: x(3,nbod) real(double_precision), intent(in) :: v(3,nbod) real(double_precision), intent(in) :: ngf(4,nbod) !< [in] non gravitational forces parameters !! \n(1-3) cometary non-gravitational (jet) force parameters !! \n(4) beta parameter for radiation pressure and P-R drag ! Input/Output real(double_precision), intent(inout) :: xh(3,nbod) !< [in,out] coordinates (x,y,z) with respect to the central body (AU) real(double_precision), intent(inout) :: vh(3,nbod) !< [in,out] velocities (vx,vy,vz) with respect to the central body (AU/day) ! Local integer :: j,k,iflag,stat(nb_bodies_initial) real(double_precision) :: minside,msofar,gm(nb_bodies_initial) real(double_precision) :: a(3,nb_bodies_initial),xj(3,nb_bodies_initial),vj(3,nb_bodies_initial) real(double_precision) :: ha(2),hb(2),rt10,angf(3,nb_bodies_initial),ausr(3,nb_bodies_initial) !------------------------------------------------------------------------------ rt10 = sqrt(10.d0) ha(1) = h * rt10 * 3.d0 / 10.d0 hb(1) = -h * rt10 / 72.d0 ha(2) = h * rt10 / 5.d0 hb(2) = h * rt10 / 24.d0 do j = 2, nbod angf(1,j) = 0.d0 angf(2,j) = 0.d0 angf(3,j) = 0.d0 ausr(1,j) = 0.d0 ausr(2,j) = 0.d0 ausr(3,j) = 0.d0 end do call mco_iden (time,jcen,nbod,nbig,h,m,x,v,xh,vh,ngf,ngflag) ! Calculate effective central masses for Kepler drifts minside = m(1) do j = 2, nbig msofar = minside + m(j) gm(j) = m(1) * msofar / minside minside = msofar end do ! Two step corrector do k = 1, 2 ! Advance Keplerian Hamiltonian (Jacobi/helio coords for Big/Small bodies) call mco_h2j(jcen,nbig,nbig,h,m,xh,vh,xj,vj) do j = 2, nbig iflag = 0 call drift_one (gm(j),xj(1,j),xj(2,j),xj(3,j),vj(1,j),vj(2,j),vj(3,j),ha(k),iflag) end do do j = nbig + 1, nbod iflag = 0 call drift_one (m(1),xh(1,j),xh(2,j),xh(3,j),vh(1,j),vh(2,j),vh(3,j),ha(k),iflag) end do ! Advance Interaction Hamiltonian call mco_j2h(time,jcen,nbig,nbig,h,m,xj,vj,xh,vh,ngf,ngflag) call mfo_mvs (jcen,nbod,nbig,m,xh,xj,a,stat) ! If required, apply non-gravitational and user-defined forces if (opt(8).eq.1) call mfo_user (time,jcen,nbod,nbig,m,rphys,xh,vh,ausr) if ((ngflag.eq.1).or.(ngflag.eq.3)) call mfo_ngf (nbod,xh,vh,angf,ngf) do j = 2, nbod vh(1,j) = vh(1,j) - hb(k) * (angf(1,j) + ausr(1,j) + a(1,j)) vh(2,j) = vh(2,j) - hb(k) * (angf(2,j) + ausr(2,j) + a(2,j)) vh(3,j) = vh(3,j) - hb(k) * (angf(3,j) + ausr(3,j) + a(3,j)) end do ! Advance Keplerian Hamiltonian (Jacobi/helio coords for Big/Small bodies) call mco_h2j(jcen,nbig,nbig,h,m,xh,vh,xj,vj) do j = 2, nbig iflag = 0 call drift_one (gm(j),xj(1,j),xj(2,j),xj(3,j),vj(1,j),vj(2,j),vj(3,j),-2.d0*ha(k),iflag) end do do j = nbig + 1, nbod iflag = 0 call drift_one (m(1),xh(1,j),xh(2,j),xh(3,j),vh(1,j),vh(2,j),vh(3,j),-2.d0*ha(k),iflag) end do ! Advance Interaction Hamiltonian call mco_j2h(time,jcen,nbig,nbig,h,m,xj,vj,xh,vh,ngf,ngflag) call mfo_mvs (jcen,nbod,nbig,m,xh,xj,a,stat) ! If required, apply non-gravitational and user-defined forces if (opt(8).eq.1) call mfo_user (time,jcen,nbod,nbig,m,rphys,xh,vh,ausr) if (ngflag.eq.1.or.ngflag.eq.3) call mfo_ngf (nbod,xh,vh,angf,ngf) do j = 2, nbod vh(1,j) = vh(1,j) + hb(k) * (angf(1,j) + ausr(1,j) + a(1,j)) vh(2,j) = vh(2,j) + hb(k) * (angf(2,j) + ausr(2,j) + a(2,j)) vh(3,j) = vh(3,j) + hb(k) * (angf(3,j) + ausr(3,j) + a(3,j)) end do ! Advance Keplerian Hamiltonian (Jacobi/helio coords for Big/Small bodies) call mco_h2j(jcen,nbig,nbig,h,m,xh,vh,xj,vj) do j = 2, nbig iflag = 0 call drift_one (gm(j),xj(1,j),xj(2,j),xj(3,j),vj(1,j),vj(2,j),vj(3,j),ha(k),iflag) end do do j = nbig + 1, nbod iflag = 0 call drift_one (m(1),xh(1,j),xh(2,j),xh(3,j),vh(1,j),vh(2,j),vh(3,j),ha(k),iflag) end do call mco_j2h(time,jcen,nbig,nbig,h,m,xj,vj,xh,vh,ngf,ngflag) end do !------------------------------------------------------------------------------ return end subroutine mco_mvs2h !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% !> @author !> <NAME> ! !> @date 28 March 2001 ! ! DESCRIPTION: !> @brief Integrates NBOD bodies (of which NBIG are Big) for one timestep H !! using a second-order mixed-variable symplectic integrator. !\n !!\n DTFLAG = 0 implies first ever call to this subroutine, !!\n = 1 implies first call since number/masses of objects changed. !!\n = 2 normal call !> @note Input/output must be in coordinates with respect to the central body. ! !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% subroutine mdt_mvs (time,h0,tol,en,am,jcen,rcen,nbod,nbig,m,x,v,s,rphys,rcrit,rce,stat,id,ngf,dtflag,ngflag,& opflag,colflag,nclo,iclo,jclo,dclo,tclo,ixvclo,jxvclo) use physical_constant use mercury_constant use drift use dynamic implicit none ! Input integer, intent(in) :: nbod !< [in] current number of bodies (1: star; 2-nbig: big bodies; nbig+1-nbod: small bodies) integer, intent(in) :: nbig !< [in] current number of big bodies (ones that perturb everything else) integer, intent(in) :: ngflag !< [in] do any bodies experience non-grav. forces? !!\n ( 0 = no non-grav forces) !!\n 1 = cometary jets only !!\n 2 = radiation pressure/P-R drag only !!\n 3 = both integer, intent(in) :: opflag !< [in] integration mode (-2 = synchronising epochs) !!\n -1 = integrating towards start epoch !!\n 0 = main integration, normal output !!\n 1 = main integration, full output real(double_precision), intent(in) :: time !< [in] current epoch (days) real(double_precision), intent(in) :: h0 !< [in] initial integration timestep (days) real(double_precision), intent(in) :: tol !< [in] Integrator tolerance parameter (approx. error per timestep) real(double_precision), intent(in) :: am(3) !< [in] (initial angular momentum, current angular momentum, !! angular momentum change due to collision and ejection) of the system real(double_precision), intent(in) :: jcen(3) !< [in] J2,J4,J6 for central body (units of RCEN^i for Ji) real(double_precision), intent(in) :: rcen !< [in] radius of central body (AU) real(double_precision), intent(in) :: rphys(nbod) real(double_precision), intent(in) :: rce(nbod) real(double_precision), intent(in) :: rcrit(nbod) real(double_precision), intent(in) :: ngf(4,nbod) !< [in] non gravitational forces parameters !! \n(1-3) cometary non-gravitational (jet) force parameters !! \n(4) beta parameter for radiation pressure and P-R drag character(len=8), intent(in) :: id(nbod) !< [in] name of the object (8 characters) ! Output integer, intent(out) :: colflag integer, intent(out) :: nclo integer, intent(out) :: iclo(CMAX) integer, intent(out) :: jclo(CMAX) real(double_precision), intent(out) :: tclo(CMAX) real(double_precision), intent(out) :: dclo(CMAX) real(double_precision), intent(out) :: ixvclo(6,CMAX) real(double_precision), intent(out) :: jxvclo(6,CMAX) ! Input/Output integer, intent(inout) :: stat(nbod) !< [in,out] status (0 => alive, <>0 => to be removed) integer, intent(inout) :: dtflag real(double_precision), intent(inout) :: m(nbod) !< [in,out] mass (in solar masses * K2) real(double_precision), intent(inout) :: x(3,nbod) real(double_precision), intent(inout) :: v(3,nbod) real(double_precision), intent(inout) :: s(3,nbod) !< [in,out] spin angular momentum (solar masses AU^2/day) real(double_precision), intent(inout) :: en(3) !< [in,out] (initial energy, current energy, energy change due to collision and ejection) of the system ! Local integer :: j,iflag,nhit,ihit(CMAX),jhit(CMAX),chit(CMAX),nowflag real(double_precision) :: vj(3,nb_bodies_initial) real(double_precision) :: hby2,thit1,temp real(double_precision) :: msofar,minside,x0(3,nb_bodies_initial),v0(3,nb_bodies_initial),dhit(CMAX),thit(CMAX) !------------------------------------------------------------------------------ hby2 = .5d0 * h0 nclo = 0 ! If accelerations from previous call are not valid, calculate them now, ! and also the Jacobi coordinates XJ, and effective central masses GM. if (dtflag.ne.2) then dtflag = 2 call mco_h2j (jcen,nbig,nbig,h0,m,x,v,xj,vj) call mfo_mvs (jcen,nbod,nbig,m,x,xj,a,stat) minside = m(1) do j = 2, nbig msofar = minside + m(j) gm(j) = m(1) * msofar / minside minside = msofar angf(1,j) = 0.d0 angf(2,j) = 0.d0 angf(3,j) = 0.d0 ausr(1,j) = 0.d0 ausr(2,j) = 0.d0 ausr(3,j) = 0.d0 end do ! If required, apply non-gravitational and user-defined forces if (opt(8).eq.1) call mfo_user (time,jcen,nbod,nbig,m,rphys,x,v,ausr) if (ngflag.eq.1.or.ngflag.eq.3) call mfo_ngf (nbod,x,v,angf,ngf) end if ! Advance interaction Hamiltonian for H/2 do j = 2, nbod v(1,j) = v(1,j) + hby2 * (angf(1,j) + ausr(1,j) + a(1,j)) v(2,j) = v(2,j) + hby2 * (angf(2,j) + ausr(2,j) + a(2,j)) v(3,j) = v(3,j) + hby2 * (angf(3,j) + ausr(3,j) + a(3,j)) end do ! Save current coordinates and velocities call mco_iden (time,jcen,nbod,nbig,h0,m,x,v,x0,v0,ngf,ngflag) ! Advance Keplerian Hamiltonian (Jacobi/helio coords for Big/Small bodies) call mco_h2j (jcen,nbig,nbig,h0,m,x,v,xj,vj) do j = 2, nbig iflag = 0 call drift_one (gm(j),xj(1,j),xj(2,j),xj(3,j),vj(1,j),vj(2,j),vj(3,j),h0,iflag) end do do j = nbig + 1, nbod iflag = 0 call drift_one (m(1),x(1,j),x(2,j),x(3,j),v(1,j),v(2,j),v(3,j),h0,iflag) end do call mco_j2h (time,jcen,nbig,nbig,h0,m,xj,vj,x,v,ngf,ngflag) ! Check for close-encounter minima during drift step temp = time + h0 call mce_stat (temp,h0,rcen,nbod,nbig,m,x0,v0,x,v,rce,rphys,nclo,iclo,jclo,dclo,tclo,ixvclo,jxvclo,nhit,ihit,jhit,chit,dhit,& thit,thit1,nowflag,stat,outfile(3)) ! Advance interaction Hamiltonian for H/2 call mfo_mvs (jcen,nbod,nbig,m,x,xj,a,stat) if (opt(8).eq.1) call mfo_user (time,jcen,nbod,nbig,m,rphys,x,v,ausr) if ((ngflag.eq.1).or.(ngflag.eq.3)) call mfo_ngf (nbod,x,v,angf,ngf) do j = 2, nbod v(1,j) = v(1,j) + hby2 * (angf(1,j) + ausr(1,j) + a(1,j)) v(2,j) = v(2,j) + hby2 * (angf(2,j) + ausr(2,j) + a(2,j)) v(3,j) = v(3,j) + hby2 * (angf(3,j) + ausr(3,j) + a(3,j)) end do !------------------------------------------------------------------------------ return end subroutine mdt_mvs !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% !> @author !> <NAME> ! !> @date 2 October 2000 ! ! DESCRIPTION: !> @brief Calculates accelerations on a set of NBOD bodies (of which NBIG are Big) !! due to gravitational perturbations by all the other bodies. !! This routine is designed for use with a mixed-variable symplectic !! integrator using Jacobi coordinates. !!\n\n !! Based upon routines from Levison and Duncan's SWIFT integrator. ! !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% subroutine mfo_mvs (jcen,nbod,nbig,m,x,xj,a,stat) use physical_constant use mercury_constant use forces, only : mfo_obl implicit none ! Input integer, intent(in) :: nbod !< [in] current number of bodies (1: star; 2-nbig: big bodies; nbig+1-nbod: small bodies) integer, intent(in) :: nbig !< [in] current number of big bodies (ones that perturb everything else) integer, intent(in) :: stat(nbod) !< [in] status (0 => alive, <>0 => to be removed) real(double_precision), intent(in) :: jcen(3) !< [in] J2,J4,J6 for central body (units of RCEN^i for Ji) real(double_precision), intent(in) :: m(nbod) !< [in] mass (in solar masses * K2) real(double_precision), intent(in) :: x(3,nbod) real(double_precision), intent(in) :: xj(3,nbod) ! Output real(double_precision), intent(out) :: a(3,nbod) ! Local integer :: i,j,k,k1 real(double_precision) :: fac0,fac1,fac12,fac2,minside,dx,dy,dz,s_1,s2,s_3,faci,facj real(double_precision), dimension(3) :: a0,a0tp real(double_precision), dimension(3,nb_bodies_initial) :: a1,a2,a3,aobl real(double_precision) :: r,r2,r3,rj,rj2,rj3,q,q2,q3,q4,q5,q6,q7,acen(3) !------------------------------------------------------------------------------ ! Initialize variables a0(1) = 0.d0 a0(2) = 0.d0 a0(3) = 0.d0 a1(1,2) = 0.d0 a1(2,2) = 0.d0 a1(3,2) = 0.d0 a2(1,2) = 0.d0 a2(2,2) = 0.d0 a2(3,2) = 0.d0 minside = 0.d0 ! Calculate acceleration terms do k = 3, nbig k1 = k - 1 minside = minside + m(k1) r2 = x(1,k) * x(1,k) + x(2,k) * x(2,k) + x(3,k) * x(3,k) rj2 = xj(1,k) * xj(1,k) + xj(2,k) * xj(2,k) + xj(3,k) * xj(3,k) r = 1.d0 / sqrt(r2) rj = 1.d0 / sqrt(rj2) r3 = r * r * r rj3 = rj * rj * rj fac0 = m(k) * r3 fac12 = m(1) * rj3 fac2 = m(k) * fac12 / (minside + m(1)) q = (r2 - rj2) * .5d0 / rj2 q2 = q * q q3 = q * q2 q4 = q2 * q2 q5 = q2 * q3 q6 = q3 * q3 q7 = q3 * q4 fac1 = 402.1875d0*q7 - 187.6875d0*q6 + 86.625d0*q5 - 39.375d0*q4 + 17.5d0*q3 - 7.5d0*q2 + 3.d0*q - 1.d0 ! Add to A0 term a0(1) = a0(1) - fac0 * x(1,k) a0(2) = a0(2) - fac0 * x(2,k) a0(3) = a0(3) - fac0 * x(3,k) ! Calculate A1 for this body a1(1,k) = fac12 * (xj(1,k) + fac1*x(1,k)) a1(2,k) = fac12 * (xj(2,k) + fac1*x(2,k)) a1(3,k) = fac12 * (xj(3,k) + fac1*x(3,k)) ! Calculate A2 for this body a2(1,k) = a2(1,k1) + fac2 * xj(1,k) a2(2,k) = a2(2,k1) + fac2 * xj(2,k) a2(3,k) = a2(3,k1) + fac2 * xj(3,k) end do r2 = x(1,2) * x(1,2) + x(2,2) * x(2,2) + x(3,2) * x(3,2) r = 1.d0 / sqrt(r2) r3 = r * r * r fac0 = m(2) * r3 a0tp(1) = a0(1) - fac0 * x(1,2) a0tp(2) = a0(2) - fac0 * x(2,2) a0tp(3) = a0(3) - fac0 * x(3,2) ! Calculate A3 (direct terms) do k = 2, nbod a3(1,k) = 0.d0 a3(2,k) = 0.d0 a3(3,k) = 0.d0 end do do i = 2, nbig do j = i + 1, nbig dx = x(1,j) - x(1,i) dy = x(2,j) - x(2,i) dz = x(3,j) - x(3,i) s2 = dx*dx + dy*dy + dz*dz s_1 = 1.d0 / sqrt(s2) s_3 = s_1 * s_1 * s_1 faci = m(i) * s_3 facj = m(j) * s_3 a3(1,j) = a3(1,j) - faci * dx a3(2,j) = a3(2,j) - faci * dy a3(3,j) = a3(3,j) - faci * dz a3(1,i) = a3(1,i) + facj * dx a3(2,i) = a3(2,i) + facj * dy a3(3,i) = a3(3,i) + facj * dz end do do j = nbig + 1, nbod dx = x(1,j) - x(1,i) dy = x(2,j) - x(2,i) dz = x(3,j) - x(3,i) s2 = dx*dx + dy*dy + dz*dz s_1 = 1.d0 / sqrt(s2) s_3 = s_1 * s_1 * s_1 faci = m(i) * s_3 a3(1,j) = a3(1,j) - faci * dx a3(2,j) = a3(2,j) - faci * dy a3(3,j) = a3(3,j) - faci * dz end do end do ! Big-body accelerations do k = 2, nbig a(1,k) = a0(1) + a1(1,k) + a2(1,k) + a3(1,k) a(2,k) = a0(2) + a1(2,k) + a2(2,k) + a3(2,k) a(3,k) = a0(3) + a1(3,k) + a2(3,k) + a3(3,k) end do ! Small-body accelerations do k = nbig + 1, nbod a(1,k) = a0tp(1) + a3(1,k) a(2,k) = a0tp(2) + a3(2,k) a(3,k) = a0tp(3) + a3(3,k) end do ! Correct for oblateness of the central body if ((jcen(1).ne.0).or.(jcen(2).ne.0).or.(jcen(3).ne.0)) then call mfo_obl (jcen,nbod,m,x,aobl,acen) do k = 2, nbod a(1,k) = a(1,k) + (aobl(1,k) - acen(1)) a(2,k) = a(2,k) + (aobl(2,k) - acen(2)) a(3,k) = a(3,k) + (aobl(3,k) - acen(3)) end do end if !------------------------------------------------------------------------------ return end subroutine mfo_mvs !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% !> @author !> <NAME> ! !> @date 2 March 2001 ! ! DESCRIPTION: !> @brief Converts Jacobi coordinates to coordinates with respect to the central !! body. ! !> @note The Jacobi coordinates of the small bodies are assumed to be equal !! to their coordinates with respect to the central body. ! !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% subroutine mco_j2h (time,jcen,nbod,nbig,h,m,x,v,xh,vh,ngf,ngflag) implicit none ! Input integer, intent(in) :: nbod !< [in] current number of bodies (1: star; 2-nbig: big bodies; nbig+1-nbod: small bodies) integer, intent(in) :: nbig !< [in] current number of big bodies (ones that perturb everything else) integer, intent(in) :: ngflag !< [in] do any bodies experience non-grav. forces? !!\n ( 0 = no non-grav forces) !!\n 1 = cometary jets only !!\n 2 = radiation pressure/P-R drag only !!\n 3 = both real(double_precision), intent(in) :: time !< [in] current epoch (days) real(double_precision), intent(in) :: jcen(3) !< [in] J2,J4,J6 for central body (units of RCEN^i for Ji) real(double_precision), intent(in) :: h !< [in] current integration timestep (days) real(double_precision), intent(in) :: m(nbod) !< [in] mass (in solar masses * K2) real(double_precision), intent(in) :: x(3,nbod) real(double_precision), intent(in) :: v(3,nbod) real(double_precision), intent(in) :: ngf(4,nbod) !< [in] non gravitational forces parameters !! \n(1-3) cometary non-gravitational (jet) force parameters !! \n(4) beta parameter for radiation pressure and P-R drag ! Output real(double_precision), intent(out) :: xh(3,nbod) !< [out] coordinates (x,y,z) with respect to the central body (AU) real(double_precision), intent(out) :: vh(3,nbod) !< [out] velocities (vx,vy,vz) with respect to the central body (AU/day) ! Local integer :: j real(double_precision) :: mtot, mx, my, mz, mu, mv, mw, temp !------------------------------------------------------------------------------ xh(1,2) = x(1,2) xh(2,2) = x(2,2) xh(3,2) = x(3,2) vh(1,2) = v(1,2) vh(2,2) = v(2,2) vh(3,2) = v(3,2) mtot = m(2) temp = m(2) / (mtot + m(1)) mx = temp * x(1,2) my = temp * x(2,2) mz = temp * x(3,2) mu = temp * v(1,2) mv = temp * v(2,2) mw = temp * v(3,2) do j = 3, nbig - 1 xh(1,j) = x(1,j) + mx xh(2,j) = x(2,j) + my xh(3,j) = x(3,j) + mz vh(1,j) = v(1,j) + mu vh(2,j) = v(2,j) + mv vh(3,j) = v(3,j) + mw mtot = mtot + m(j) temp = m(j) / (mtot + m(1)) mx = mx + temp * x(1,j) my = my + temp * x(2,j) mz = mz + temp * x(3,j) mu = mu + temp * v(1,j) mv = mv + temp * v(2,j) mw = mw + temp * v(3,j) enddo if (nbig.gt.2) then xh(1,nbig) = x(1,nbig) + mx xh(2,nbig) = x(2,nbig) + my xh(3,nbig) = x(3,nbig) + mz vh(1,nbig) = v(1,nbig) + mu vh(2,nbig) = v(2,nbig) + mv vh(3,nbig) = v(3,nbig) + mw end if do j = nbig + 1, nbod xh(1,j) = x(1,j) xh(2,j) = x(2,j) xh(3,j) = x(3,j) vh(1,j) = v(1,j) vh(2,j) = v(2,j) vh(3,j) = v(3,j) end do !------------------------------------------------------------------------------ return end subroutine mco_j2h !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% !> @author !> <NAME> ! !> @date 2 March 2001 ! ! DESCRIPTION: !> @brief Converts coordinates with respect to the central body to Jacobi coordinates. ! ! @note The coordinates respect to the central body for the small bodies !! are assumed to be equal to their Jacobi coordinates. ! !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% subroutine mco_h2j (jcen,nbod,nbig,h,m,xh,vh,x,v) implicit none ! Input integer, intent(in) :: nbod !< [in] current number of bodies (1: star; 2-nbig: big bodies; nbig+1-nbod: small bodies) integer, intent(in) :: nbig !< [in] current number of big bodies (ones that perturb everything else) real(double_precision), intent(in) :: jcen(3) !< [in] J2,J4,J6 for central body (units of RCEN^i for Ji) real(double_precision), intent(in) :: h !< [in] current integration timestep (days) real(double_precision), intent(in) :: m(nbig) !< [in] mass (in solar masses * K2) real(double_precision), intent(in) :: xh(3,nbig) !< [in] coordinates (x,y,z) with respect to the central body (AU) real(double_precision), intent(in) :: vh(3,nbig) !< [in] velocities (vx,vy,vz) with respect to the central body (AU/day) ! Output real(double_precision), intent(out) :: x(3,nbig) real(double_precision), intent(out) :: v(3,nbig) ! Local integer :: j real(double_precision) :: mtot, mx, my, mz, mu, mv, mw, temp !------------------------------------------------------------------------------c mtot = m(2) x(1,2) = xh(1,2) x(2,2) = xh(2,2) x(3,2) = xh(3,2) v(1,2) = vh(1,2) v(2,2) = vh(2,2) v(3,2) = vh(3,2) mx = m(2) * xh(1,2) my = m(2) * xh(2,2) mz = m(2) * xh(3,2) mu = m(2) * vh(1,2) mv = m(2) * vh(2,2) mw = m(2) * vh(3,2) do j = 3, nbig - 1 temp = 1.d0 / (mtot + m(1)) mtot = mtot + m(j) x(1,j) = xh(1,j) - temp * mx x(2,j) = xh(2,j) - temp * my x(3,j) = xh(3,j) - temp * mz v(1,j) = vh(1,j) - temp * mu v(2,j) = vh(2,j) - temp * mv v(3,j) = vh(3,j) - temp * mw mx = mx + m(j) * xh(1,j) my = my + m(j) * xh(2,j) mz = mz + m(j) * xh(3,j) mu = mu + m(j) * vh(1,j) mv = mv + m(j) * vh(2,j) mw = mw + m(j) * vh(3,j) enddo if (nbig.gt.2) then temp = 1.d0 / (mtot + m(1)) x(1,nbig) = xh(1,nbig) - temp * mx x(2,nbig) = xh(2,nbig) - temp * my x(3,nbig) = xh(3,nbig) - temp * mz v(1,nbig) = vh(1,nbig) - temp * mu v(2,nbig) = vh(2,nbig) - temp * mv v(3,nbig) = vh(3,nbig) - temp * mw end if do j = nbig + 1, nbod x(1,j) = xh(1,j) x(2,j) = xh(2,j) x(3,j) = xh(3,j) v(1,j) = vh(1,j) v(2,j) = vh(2,j) v(3,j) = vh(3,j) end do !------------------------------------------------------------------------------ return end subroutine mco_h2j end module algo_mvs <file_sep>!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ! ELEMENT6.FOR (ErikSoft 5 June 2001) !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ! Author: <NAME> ! Makes output files containing Keplerian orbital elements from data created ! by Mercury6 and higher. ! The user specifies the names of the required objects in the file elements.in ! See subroutine get_aei_format for the identities of each element in the EL array ! e.g. el(1)=a, el(2)=e etc. !------------------------------------------------------------------------------ program element use types_numeriques use physical_constant use mercury_constant use ascii_conversion use orbital_elements use utilities use mercury_outputs use mercury_globals use system_properties use algo_mvs, only : mco_h2j implicit none integer :: itmp,i,j,k,l,precision,lenin integer :: nmaster,nopen,nwait,nbig,nsml,nbod,nsub,lim(2,100) integer :: year,month,timestyle,line_num,lenhead integer :: nchar,centre,allflag,firstflag,ninfile,nel,iel(22) integer :: nbod1,nbig1 real(double_precision) :: time,teval,t0,t1,tprevious,rcen,rfac,rhocgs,temp real(double_precision) :: mcen,jcen(3), s(3) real(double_precision) :: fr,theta,phi,fv,vtheta,vphi,gm logical test character(len=250) :: string,fout,header,infile(5000) character(len=80) :: cc character(len=5) :: fin character(len=1) :: check,style,type,c1 character(len=2) :: c2 ! fake variables to be able to use mco_iden integer :: ngflag !< do any bodies experience non-grav. forces? !!\n ( 0 = no non-grav forces) !!\n 1 = cometary jets only !!\n 2 = radiation pressure/P-R drag only !!\n 3 = both real(double_precision), dimension(1,1) :: ngf integer :: error ! to store error when we allocate integer, dimension(:), allocatable :: unit, master_unit, code, iback ! (Number of bodies) character(len=80), dimension(:), allocatable :: c ! (Number of bodies) character(len=8), dimension(:), allocatable :: master_id, id ! (Number of bodies) real(double_precision), dimension(:), allocatable :: m, m_x, a, ns, is ! (Number of bodies) real(double_precision), dimension(:,:), allocatable :: el ! (22,Number of bodies) real(double_precision), dimension(:,:), allocatable :: x, v, xh, vh ! (3,Number of bodies) !------------------------------------------------------------------------------ call getNumberOfBodies(nb_big_bodies=nbig, nb_bodies=nb_bodies_initial) ! We allocate and initialize arrays now that we know their sizes allocate(unit(nb_bodies_initial), stat=error) if (error.ne.0) then write(*,*) 'Error: failed to allocate "unit" array' end if unit(1:nb_bodies_initial) = 0 allocate(master_unit(nb_bodies_initial), stat=error) if (error.ne.0) then write(*,*) 'Error: failed to allocate "master_unit" array' end if master_unit(1:nb_bodies_initial) = 0 allocate(code(nb_bodies_initial), stat=error) if (error.ne.0) then write(*,*) 'Error: failed to allocate "code" array' end if code(1:nb_bodies_initial) = 0 allocate(iback(nb_bodies_initial), stat=error) if (error.ne.0) then write(*,*) 'Error: failed to allocate "iback" array' end if iback(1:nb_bodies_initial) = 0 allocate(c(nb_bodies_initial), stat=error) if (error.ne.0) then write(*,*) 'Error: failed to allocate "c" array' end if c(1:nb_bodies_initial) = '' allocate(master_id(nb_bodies_initial), stat=error) if (error.ne.0) then write(*,*) 'Error: failed to allocate "master_id" array' end if master_id(1:nb_bodies_initial) = '' allocate(id(nb_bodies_initial), stat=error) if (error.ne.0) then write(*,*) 'Error: failed to allocate "id" array' end if id(1:nb_bodies_initial) = '' allocate(m(nb_bodies_initial), stat=error) if (error.ne.0) then write(*,*) 'Error: failed to allocate "m" array' end if m(1:nb_bodies_initial) = 0.d0 allocate(m_x(nb_bodies_initial), stat=error) if (error.ne.0) then write(*,*) 'Error: failed to allocate "m_x" array' end if m_x(1:nb_bodies_initial) = 0.d0 allocate(a(nb_bodies_initial), stat=error) if (error.ne.0) then write(*,*) 'Error: failed to allocate "a" array' end if a(1:nb_bodies_initial) = 0.d0 allocate(ns(nb_bodies_initial), stat=error) if (error.ne.0) then write(*,*) 'Error: failed to allocate "ns" array' end if ns(1:nb_bodies_initial) = 0.d0 allocate(is(nb_bodies_initial), stat=error) if (error.ne.0) then write(*,*) 'Error: failed to allocate "is" array' end if is(1:nb_bodies_initial) = 0.d0 allocate(el(22,nb_bodies_initial), stat=error) if (error.ne.0) then write(*,*) 'Error: failed to allocate "el" array' end if el(1:22,1:nb_bodies_initial) = 0.d0 allocate(x(3,nb_bodies_initial), stat=error) if (error.ne.0) then write(*,*) 'Error: failed to allocate "x" array' end if x(1:3,1:nb_bodies_initial) = 0.d0 allocate(v(3,nb_bodies_initial), stat=error) if (error.ne.0) then write(*,*) 'Error: failed to allocate "v" array' end if v(1:3,1:nb_bodies_initial) = 0.d0 allocate(vh(3,nb_bodies_initial), stat=error) if (error.ne.0) then write(*,*) 'Error: failed to allocate "vh" array' end if vh(1:3,1:nb_bodies_initial) = 0.d0 allocate(xh(3,nb_bodies_initial), stat=error) if (error.ne.0) then write(*,*) 'Error: failed to allocate "xh" array' end if xh(1:3,1:nb_bodies_initial) = 0.d0 !------------------------------------------------------------------------------ allflag = 0 tprevious = 0.d0 rhocgs = AU * AU * AU * K2 / MSUN ! Read in output messages inquire (file='message.in', exist=test) if (.not.test) then write (*,'(/,2a)') ' ERROR: This file is needed to continue: ',' message.in' stop end if open (14, file='message.in', status='old') 10 continue read (14,'(i3,1x,i2,1x,a80)',end=20) j,lmem(j),mem(j) goto 10 20 close (14) ! Open file containing parameters for this programme inquire (file='element.in', exist=test) if (test) then open (10, file='element.in', status='old') else call mio_err (6,mem(81),lmem(81),mem(88),lmem(88),' ',1,'element.in',9) end if ! Read number of input files 30 read (10,'(a250)') string if (string(1:1).eq.')') goto 30 call mio_spl (250,string,nsub,lim) read (string(lim(1,nsub):lim(2,nsub)),*) ninfile ! Make sure all the input files exist do j = 1, ninfile 40 read (10,'(a250)') string if (string(1:1).eq.')') goto 40 call mio_spl (250,string,nsub,lim) infile(j)(1:(lim(2,1)-lim(1,1)+1)) = string(lim(1,1):lim(2,1)) inquire (file=infile(j), exist=test) ! xv*.out file if (.not.test) call mio_err (6,mem(81),lmem(81),mem(88),lmem(88),' ',1,infile(j),80) end do ! What type elements does the user want? centre = 0 45 read (10,'(a250)') string if (string(1:1).eq.')') goto 45 call mio_spl (250,string,nsub,lim) c2 = string(lim(1,nsub):(lim(1,nsub)+1)) if (c2.eq.'ce'.or.c2.eq.'CE'.or.c2.eq.'Ce') then centre = 0 else if (c2.eq.'ba'.or.c2.eq.'BA'.or.c2.eq.'Ba') then centre = 1 else if (c2.eq.'ja'.or.c2.eq.'JA'.or.c2.eq.'Ja') then centre = 2 else call mio_err (6,mem(81),lmem(81),mem(107),lmem(107),' ',1,' Check element.in',23) end if ! Read parameters used by this programme timestyle = 1 do j = 1, 4 50 read (10,'(a250)') string if (string(1:1).eq.')') goto 50 call mio_spl (250,string,nsub,lim) c1 = string(lim(1,nsub):lim(2,nsub)) if (j.eq.1) read (string(lim(1,nsub):lim(2,nsub)),*) teval teval = abs(teval) * .999d0 if (j.eq.2.and.(c1.eq.'d'.or.c1.eq.'D')) timestyle = 0 if (j.eq.3.and.(c1.eq.'y'.or.c1.eq.'Y')) timestyle = timestyle+2 if (j.eq.4) call get_aei_format (string,timestyle,nel,iel,fout,header,lenhead) end do ! Read in the names of the objects for which orbital elements are required nopen = 0 nwait = 0 nmaster = 0 60 continue read (10,'(a250)',end=70) string call mio_spl (250,string,nsub,lim) if (string(1:1).eq.')'.or.lim(1,1).eq.-1) goto 60 ! Either open an aei file for this object or put it on the waiting list nmaster = nmaster + 1 itmp = min(7,lim(2,1)-lim(1,1)) master_id(nmaster)=' ' master_id(nmaster)(1:itmp+1) = string(lim(1,1):lim(1,1)+itmp) if (nopen.lt.NFILES) then nopen = nopen + 1 master_unit(nmaster) = 10 + nopen call mio_aei (master_id(nmaster),master_unit(nmaster), header,lenhead) else nwait = nwait + 1 master_unit(nmaster) = -2 end if goto 60 70 continue ! If no objects are listed in ELEMENT.IN assume that all objects are required if (nopen.eq.0) allflag = 1 close (10) !------------------------------------------------------------------------------ ! LOOP OVER EACH INPUT FILE CONTAINING INTEGRATION DATA 90 continue firstflag = 0 do i = 1, ninfile line_num = 0 open (10, file=infile(i), status='old') ! Loop over each time slice 100 continue line_num = line_num + 1 read (10,'(3a1)',end=900,err=666) check,style,type line_num = line_num - 1 backspace 10 ! Check if this is an old style input file if (ichar(check).eq.12.and.(style.eq.'0'.or.style.eq.'1'.or.style.eq.'2'.or.style.eq.'3'.or.style.eq.'4')) then write (*,'(/,2a)') ' ERROR: This is an old style data file',' Try running m_elem5.for instead.' stop end if if (ichar(check).ne.12) goto 666 !------------------------------------------------------------------------------ ! IF SPECIAL INPUT, READ TIME, PARAMETERS, NAMES, MASSES ETC. if (type.eq.'a') then line_num = line_num + 1 read (10,'(3x,i2,a62,i1)') algor,cc(1:62),precision ! Decompress the time, number of objects, central mass and J components etc. time = mio_c2fl (cc(1:8)) nbig = int(.5d0 + mio_c2re(cc(9:16), 0.d0, 11239424.d0, 3)) nsml = int(.5d0 + mio_c2re(cc(12:19),0.d0, 11239424.d0, 3)) mcen = mio_c2fl (cc(15:22)) jcen(1) = mio_c2fl (cc(23:30)) jcen(2) = mio_c2fl (cc(31:38)) jcen(3) = mio_c2fl (cc(39:46)) rcen = mio_c2fl (cc(47:54)) rmax = mio_c2fl (cc(55:62)) rfac = log10 (rmax / rcen) ! Read in strings containing compressed data for each object do j = 1, nbig + nsml line_num = line_num + 1 ! read (10,'(a)',err=666) c(j)(1:51) read (10,'(a)',err=666) c(j)(1:59) end do ! Create input format list if (precision.eq.1) nchar = 2 if (precision.eq.2) nchar = 4 if (precision.eq.3) nchar = 7 lenin = 3 + 6 * nchar fin(1:5) = '(a00)' write (fin(3:4),'(i2)') lenin ! For each object decompress its name, code number, mass, spin and density do j = 1, nbig + nsml k = int(.5d0 + mio_c2re(c(j)(1:8),0.d0,11239424.d0,3)) id(k) = c(j)(4:11) el(18,k) = mio_c2fl (c(j)(12:19))!m el(22,k) = mio_c2fl (c(j)(52:59))!m_x s(1) = mio_c2fl (c(j)(20:27)) s(2) = mio_c2fl (c(j)(28:35)) s(3) = mio_c2fl (c(j)(36:43)) el(21,k) = mio_c2fl (c(j)(44:51)) ! Calculate spin rate and longitude & inclination of spin vector temp = sqrt(s(1)*s(1) + s(2)*s(2) + s(3)*s(3)) if (temp.gt.0) then call mce_spin (1.d0,el(18,k)*K2,temp*K2,el(21,k)*rhocgs,el(20,k)) temp = s(3) / temp if (abs(temp).lt.1.d0) then is(k) = acos (temp) ns(k) = atan2 (s(1), -s(2)) else if (temp.gt.0) is(k) = 0.d0 if (temp.lt.0) is(k) = PI ns(k) = 0.d0 end if else el(20,k) = 0.d0 is(k) = 0.d0 ns(k) = 0.d0 end if ! Find the object on the master list unit(k) = 0 do l = 1, nmaster if (id(k).eq.master_id(l)) unit(k) = master_unit(l) end do ! If object is not on the master list, add it to the list now if (unit(k).eq.0) then nmaster = nmaster + 1 master_id(nmaster) = id(k) ! Either open an aei file for this object or put it on the waiting list if (allflag.eq.1) then if (nopen.lt.NFILES) then nopen = nopen + 1 master_unit(nmaster) = 10 + nopen call mio_aei (master_id(nmaster),master_unit(nmaster),header,lenhead) else nwait = nwait + 1 master_unit(nmaster) = -2 end if else master_unit(nmaster) = -1 end if unit(k) = master_unit(nmaster) end if end do !------------------------------------------------------------------------------ ! IF NORMAL INPUT, READ COMPRESSED ORBITAL VARIABLES FOR ALL OBJECTS else if (type.eq.'b') then line_num = line_num + 1 read (10,'(3x,a14)',err=666) cc(1:14) ! Decompress the time and the number of objects time = mio_c2fl (cc(1:8)) nbig = int(.5d0 + mio_c2re(cc(9:16), 0.d0, 11239424.d0, 3)) nsml = int(.5d0 + mio_c2re(cc(12:19), 0.d0, 11239424.d0, 3)) nbod = nbig + nsml if (firstflag.eq.0) t0 = time ! Read in strings containing compressed data for each object do j = 1, nbod line_num = line_num + 1 read (10,fin,err=666) c(j)(1:lenin) end do ! Look for objects for which orbital elements are required m(1) = mcen * K2 do j = 1, nbod code(j) = int(.5d0 + mio_c2re(c(j)(1:8), 0.d0,11239424.d0, 3)) if (code(j).gt.nb_bodies_initial) then write (*,'(/,2a)') mem(81)(1:lmem(81)), mem(90)(1:lmem(90)) stop end if ! Decompress orbital variables for each object l = j + 1 m(l) = el(18,code(j)) * K2 m_x(l) = el(22,code(j)) * K2 fr = mio_c2re (c(j)(4:11), 0.d0, rfac, nchar) theta = mio_c2re (c(j)(4+ nchar:11+ nchar), 0.d0, PI, nchar) phi = mio_c2re (c(j)(4+2*nchar:11+2*nchar), 0.d0, TWOPI, nchar) fv = mio_c2re (c(j)(4+3*nchar:11+3*nchar), 0.d0, 1.d0, nchar) vtheta = mio_c2re (c(j)(4+4*nchar:11+4*nchar), 0.d0, PI, nchar) vphi = mio_c2re (c(j)(4+5*nchar:11+5*nchar), 0.d0, TWOPI, nchar) call mco_ov2x (rcen,m(1),m(l),fr,theta,phi,fv,vtheta,vphi,x(1,l),x(2,l),x(3,l),v(1,l),v(2,l),v(3,l)) el(16,code(j)) = sqrt(x(1,l)*x(1,l) + x(2,l)*x(2,l) + x(3,l)*x(3,l)) end do ! Convert to barycentric, Jacobi or close-binary coordinates if desired nbod1 = nbod + 1 nbig1 = nbig + 1 !~ xh(:,:) = x(:,:) !~ vh(:,:) = v(:,:) call mco_iden (time,jcen,nbod1,nbig1,temp,m,x,v,xh,vh,ngf,ngflag) if (centre.eq.1) call mco_h2b (jcen,nbod1,nbig1,temp,m,xh,vh,x,v) if (centre.eq.2) call mco_h2j (jcen,nbod1,nbig1,temp,m,xh,vh,x,v) if ((centre.eq.0).and.(algor.eq.11)) call mco_h2cb (jcen,nbod1,nbig1,temp,m,xh,vh,x,v) ! Put Cartesian coordinates into element arrays do j = 1, nbod k = code(j) l = j + 1 el(10,k) = x(1,l) el(11,k) = x(2,l) el(12,k) = x(3,l) el(13,k) = v(1,l) el(14,k) = v(2,l) el(15,k) = v(3,l) ! Convert to Keplerian orbital elements gm = (mcen + el(18,k)) * K2 call mco_x2el (gm,el(10,k),el(11,k),el(12,k),el(13,k),el(14,k),el(15,k),el(8,k),el(2,k),el(3,k),el(7,k),el(5,k),el(6,k)) el(1,k) = el(8,k) / (1.d0 - el(2,k)) el(9,k) = el(1,k) * (1.d0 + el(2,k)) el(4,k) = mod(el(7,k) - el(5,k) + TWOPI, TWOPI) ! Calculate true anomaly if (el(2,k).eq.0) then el(17,k) = el(6,k) else temp = (el(8,k)*(1.d0 + el(2,k))/el(16,k) - 1.d0) /el(2,k) temp = sign (min(abs(temp), 1.d0), temp) el(17,k) = acos(temp) if (sin(el(6,k)).lt.0.d0) el(17,k) = TWOPI - el(17,k) end if ! Calculate obliquity el(19,k) = acos (cos(el(3,k))*cos(is(k))+ sin(el(3,k))*sin(is(k))*cos(ns(k) - el(5,k))) ! Convert angular elements from radians to degrees do l = 3, 7 el(l,k) = mod(el(l,k) * RAD2DEG, 360.d0) end do el(17,k) = el(17,k) * RAD2DEG el(19,k) = el(19,k) * RAD2DEG end do ! Convert time to desired format if (timestyle.eq.0) t1 = time if (timestyle.eq.1) call mio_jd2y (time,year,month,t1) if (timestyle.eq.2) t1 = time - t0 if (timestyle.eq.3) t1 = (time - t0) / 365.25d0 ! If output is required at this epoch, write elements to appropriate files if ((firstflag.eq.0).or.(abs(time-tprevious).ge.teval)) then firstflag = 1 tprevious = time ! Write required elements to the appropriate aei file do j = 1, nbod k = code(j) if (unit(k).ge.10) then if (timestyle.eq.1) then write (unit(k),fout) year,month,t1,(el(iel(l),k),l=1,nel) else write (unit(k),fout) t1,(el(iel(l),k),l=1,nel) end if end if end do end if !------------------------------------------------------------------------------ ! IF TYPE IS NOT 'a' OR 'b', THE INPUT FILE IS CORRUPTED else goto 666 end if ! Move on to the next time slice goto 100 ! If input file is corrupted, try to continue from next uncorrupted time slice 666 continue write (*,'(2a,/,a,i10)') mem(121)(1:lmem(121)),infile(i)(1:60),mem(104)(1:lmem(104)),line_num c1 = ' ' do while (ichar(c1).ne.12) line_num = line_num + 1 read (10,'(a1)',end=900) c1 end do line_num = line_num - 1 backspace 10 ! Move on to the next file containing integration data 900 continue close (10) end do ! Close aei files do j = 1, nopen close (10+j) end do nopen = 0 ! If some objects remain on waiting list, read through input files again if (nwait.gt.0) then do j = 1, nmaster if (master_unit(j).ge.10) master_unit(j) = -1 if ((master_unit(j).eq.-2).and.(nopen.lt.NFILES)) then nopen = nopen + 1 nwait = nwait - 1 master_unit(j) = 10 + nopen call mio_aei (master_id(j),master_unit(j),header,lenhead) end if end do goto 90 end if !------------------------------------------------------------------------------ ! CREATE A SUMMARY OF FINAL MASSES AND ELEMENTS open (10, file='element.out', status='unknown') rewind 10 if ((timestyle.eq.0).or.(timestyle.eq.2)) then !modified by CWO write (10,'(a,es25.16)') '#pars::[Time(days)]::',t1 else if (timestyle.eq.1) then write (10,'(/,a,i10,1x,i2,1x,f8.5,/)') ' Date: ',year,month,t1 else if (timestyle.eq.3) then !modified by CWO write (10,'(a,es25.16)') '#pars::[Time(years)]::',t1 end if !modified by CWO write (10,'(2a)') '#cols::[id,mass,m_x,sma,ecc,inc,peri,node,M,x,y,z,vx,vy,vz,rot/day,Obl]','' ! Sort surviving objects in order of increasing semi-major axis do j = 1, nbod k = code(j) a(j) = el(1,k) end do call mxx_sort (nbod,a,iback) ! Write values of a, e, i and m for surviving objects in an output file do j = 1, nbod k = code(iback(j)) write (10,213) id(k),el(18,k),el(22,k),& el(1,k),el(2,k),el(3,k),el(4,k),el(5,k),el(6,k),& el(10,k),el(11,k),el(12,k),el(13,k),el(14,k),el(15,k),& el(20,k), el(19,k) end do !------------------------------------------------------------------------------ ! Format statements (changed by CWO) 213 format (1x,a8,1x,14es24.16,1p,e11.4,f9.3,1x,f9.2) !213 format (1x,a8,1x,es22.15,1x,f7.5,1x,f7.3,1p,e11.4,0p,1x,f6.3,1x,f6.2) end program element !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% !> @author <NAME> !> ! !> @date 31 January 2001 ! ! DESCRIPTION: !> @brief Makes an output format list and file header for the orbital-element files !! created by M_ELEM3.FOR\n !! Also identifies which orbital elements will be output for each object. ! !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% subroutine get_aei_format (string,timestyle,nel,iel,fout,header,lenhead) use physical_constant use mercury_constant use utilities, only : mio_spl implicit none ! Input integer, intent(in) :: timestyle character(len=250), intent(in) :: string ! Output integer, intent(out) :: nel integer, intent(out) :: iel(22) integer, intent(out) :: lenhead character(len=250), intent(out) :: header character(len=250), intent(out) :: fout ! Local integer :: i,j,pos,nsub,lim(2,20),formflag,lenfout,f1,f2,itmp character(len=1), dimension(22), parameter :: elcode = (/ 'a','e','i','g','n','l','p','q','b','x','y','z','u','v',& 'w','r','f','m','o','s','d','c'/) character(len=4), dimension(22), parameter :: elhead = (/ ' a ',' e ',' i ','peri','node',' M ','long',' q ',& ' Q ',' x ',' y ',' z ',' vx ',' vy ',' vz ',' r ',' f ','mass','oblq','spin','dens','comp'/) !------------------------------------------------------------------------------ ! Initialize header to a blank string do i = 1, 250 header(i:i) = ' ' end do ! Create part of the format list and header for the required time style select case (timestyle) case (0,2) fout(1:9) = '(1x,f18.5' lenfout = 9 header(1:19) = ' Time (days) ' lenhead = 19 case (1) fout(1:21) = '(1x,i10,1x,i2,1x,f8.5' lenfout = 21 header(1:23) = ' Year/Month/Day ' lenhead = 23 case (3) fout(1:9) = '(1x,f18.7' lenfout = 9 header(1:19) = ' Time (years) ' lenhead = 19 case default lenfout = 0 lenhead = 0 end select ! Identify the required elements call mio_spl (250,string,nsub,lim) do i = 1, nsub do j = 1, 22 if (string(lim(1,i):lim(1,i)).eq.elcode(j)) iel(i) = j end do end do nel = nsub ! For each element, see whether normal or exponential notation is required do i = 1, nsub formflag = 0 do j = lim(1,i)+1, lim(2,i) if (formflag.eq.0) pos = j if (string(j:j).eq.'.') formflag = 1 if (string(j:j).eq.'e') formflag = 2 end do ! Create the rest of the format list and header if (formflag.eq.1) then read (string(lim(1,i)+1:pos-1),*) f1 read (string(pos+1:lim(2,i)),*) f2 write (fout(lenfout+1:lenfout+10),'(a10)') ',1x,f . ' write (fout(lenfout+6:lenfout+7),'(i2)') f1 write (fout(lenfout+9:lenfout+10),'(i2)') f2 lenfout = lenfout + 10 else if (formflag.eq.2) then read (string(lim(1,i)+1:pos-1),*) f1 write (fout(lenfout+1:lenfout+16),'(a16)') ',1x,1p,e . ,0p' write (fout(lenfout+9:lenfout+10),'(i2)') f1 write (fout(lenfout+12:lenfout+13),'(i2)') f1 - 7 lenfout = lenfout + 16 end if itmp = (f1 - 4) / 2 header(lenhead+itmp+2:lenhead+itmp+5) = elhead(iel(i)) lenhead = lenhead + f1 + 1 end do lenfout = lenfout + 1 fout(lenfout:lenfout) = ')' !------------------------------------------------------------------------------ return end subroutine get_aei_format <file_sep>!****************************************************************************** ! MODULE: physical_constant !****************************************************************************** ! ! DESCRIPTION: !> @brief Modules that contain all physical and mathematical constants !! needed for Mercury ! !****************************************************************************** module physical_constant use types_numeriques implicit none !------------------------------------------------------------------------------ ! Constants: ! DR = conversion factor from degrees to radians ! K2 = Gaussian gravitational constant squared ! AU = astronomical unit in cm ! MSUN = mass of the Sun in g real(double_precision), parameter :: PI = 3.141592653589793d0 real(double_precision), parameter :: TWOPI = PI * 2.d0 real(double_precision), parameter :: PIBY2 = PI * .5d0 real(double_precision), parameter :: DEG2RAD = PI / 180.d0 !< DEG2RAD = conversion factor from degrees to radians real(double_precision), parameter :: RAD2DEG = 180.d0 / PI !< RAD2DEG = conversion factor from radian to degrees ! Values in CGS real(double_precision), parameter :: AU = 1.4959787e13 !< AU = astronomical unit in [cm] real(double_precision), parameter :: MSUN = 1.9891e33 !< MSUN = mass of the Sun in [g] real(double_precision), parameter :: DAY = 86400.d0 !< amount of second in one day. [s] ! values in numerical Units. Time is in Days, lengths are in AU and masses are in MSUN real(double_precision), parameter :: K2 = 2.959122082855911d-4 !< K2 = Gaussian gravitational constant squared [AU^3.MSUN-1.DAY-2] !! 1W=1kg.m^2s^(-3) [W.m-2.K-4] = [M T-3 K-4] ; real(double_precision), parameter :: SIGMA_STEFAN = 5.670400d-8 / (1.d-3 * MSUN) * DAY**3 !< stefan-Boltzmann constant [MSUN.DAY-3.T-4] !! in CGS : \sigma \approx 5.6704 \times 10^{-5}\ \textrm{erg}\,\textrm{cm}^{-2}\,\textrm{s}^{-1}\,\textrm{K}^{-4} ! Various constants in (MSUN, AU, DAY) units real(double_precision), parameter :: EARTH_MASS = 3.00374072d-6 !< the mass of the earth in solar mass [MSUN] ! Numerical Constants real(double_precision), parameter :: THIRD = .33333333333333333d0 real(double_precision), parameter :: TWOTHIRD = 0.66666666666666666d0 end module physical_constant <file_sep>#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Jun 26 10:07:49 2019 @author: jooehn """ import numpy as np import matplotlib.pyplot as plt from diskmodel import * from astrounit import * from labellines import labelLines from plotset import * msuntome = Msun/Mearth M_s = 1 mdot_gas = 1e-7*M_s**2 mdot_peb = 4e-4 #earthmasses/yr L_s = M_s**2 alpha_v = 1e-3 alpha_d = 1e-3 kap = 1e-2 G = 4*np.pi**2 opt_vis = True st = 1e-1 a = np.linspace(0.1,100,50) r_trans = rtrans(mdot_gas,L_s,M_s,alpha_v,kap,opt_vis) r_snow = rsnow(mdot_gas,L_s,M_s,alpha_v,kap,opt_vis) fig,ax = plt.subplots(1,2,figsize=(12,6),sharey=True) masslist = [0.1,1,10,30,50,100] clist = ['tab:blue','tab:purple','tab:orange','tab:green','tab:red','tab:brown'] for m,c in zip(masslist,clist): tmig1vals = tmig_1(m,a,mdot_gas,L_s,M_s,alpha_v,kap,opt_vis=True) tpebvals = tpeb(m,a,mdot_gas,mdot_peb,L_s,M_s,alpha_d,alpha_v,kap,st,opt_vis=True) ax[0].plot(a,tmig1vals,color=c,label=r'$'+'{}'.format(m)+'\ M_\oplus $') ax[1].plot(a,tpebvals,'-.',color=c,label=r'$'+'{}'.format(m)+'\ M_\oplus $') for i in ax: i.set_xlabel('$a\ [\mathrm{AU}]$') i.set_xscale('log') i.set_yscale('log') i.set_xlim(0.1,100) i.set_ylim(1e3,1e8) i.axvline(r_trans,linewidth=lw2, color='c', linestyle='--') i.axvline(r_snow,linewidth=lw2, color='m', linestyle='--') i.text(1.04*r_trans,3e6,'$\\rm r_{\\rm trans}$', fontsize= fs2,color='c') i.text(0.6*r_snow,3e6,'$\\rm r_{\\rm ice}$', fontsize= fs2,color='m') ax[0].set_ylabel(r'$\tau_I\ [\mathrm{yr}]$') ax[1].set_ylabel(r'$\tau_\mathrm{PA}\ [\mathrm{yr}]$') fig.subplots_adjust(wspace=0.1) labelLines(ax[0].lines,fontsize=10) add_date(fig)<file_sep>!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ! CLOSE6.FOR (ErikSoft 5 June 2001) !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ! Author: <NAME> ! Makes output files containing details of close encounters that occurred ! during an integration using Mercury6 or higher. ! The user specifies the names of the required objects in the file close.in !------------------------------------------------------------------------------ program close use types_numeriques use physical_constant use mercury_constant use ascii_conversion use orbital_elements use mercury_outputs use mercury_globals use utilities implicit none integer :: itmp,i,j,k,l,iclo,jclo,precision,lenin integer :: nmaster,nopen,nwait,nbig,nsml,nsub,lim(2,100) integer :: year,month,timestyle,line_num,lenhead integer :: nchar,allflag,firstflag,ninfile real(double_precision) :: time,t0,t1,rcen,rfac,dclo,mcen,jcen(3) real(double_precision) :: fr,theta,phi,fv,vtheta,vphi,gm real(double_precision) :: x1(3),x2(3),v1(3),v2(3) real(double_precision) :: a1,a2,e1,e2,i1,i2,p1,p2,n1,n2,l1,l2,q1,q2 logical test character(len=250) :: string,fout,header,infile(5000) character(len=80) :: cc character(len=5) :: fin character(len=1) :: check,style,type,c1 integer :: error integer, dimension(:), allocatable :: unit, master_unit ! (Number of bodies) character(len=80), dimension(:), allocatable :: c ! (Number of bodies) character(len=8), dimension(:), allocatable :: master_id, id ! (Number of bodies) real(double_precision), dimension(:), allocatable :: m ! (Number of bodies) !------------------------------------------------------------------------------ call getNumberOfBodies(nb_big_bodies=nbig, nb_bodies=nb_bodies_initial) ! We allocate and initialize arrays now that we know their sizes allocate(unit(nb_bodies_initial), stat=error) if (error.ne.0) then write(*,*) 'Error: failed to allocate "unit" array' end if unit(1:nb_bodies_initial) = 0 allocate(master_unit(nb_bodies_initial), stat=error) if (error.ne.0) then write(*,*) 'Error: failed to allocate "master_unit" array' end if master_unit(1:nb_bodies_initial) = 0 allocate(c(nb_bodies_initial), stat=error) if (error.ne.0) then write(*,*) 'Error: failed to allocate "c" array' end if c(1:nb_bodies_initial) = '' allocate(master_id(nb_bodies_initial), stat=error) if (error.ne.0) then write(*,*) 'Error: failed to allocate "master_id" array' end if master_id(1:nb_bodies_initial) = '' allocate(id(nb_bodies_initial), stat=error) if (error.ne.0) then write(*,*) 'Error: failed to allocate "id" array' end if id(1:nb_bodies_initial) = '' allocate(m(nb_bodies_initial), stat=error) if (error.ne.0) then write(*,*) 'Error: failed to allocate "m" array' end if m(1:nb_bodies_initial) = 0.d0 !------------------------------------------------------------------------------ allflag = 0 ! Read in output messages inquire (file='message.in', exist=test) if (.not.test) then write (*,'(/,2a)') ' ERROR: This file is needed to continue: ',' message.in' stop end if open (14, file='message.in', status='old') do read (14,'(i3,1x,i2,1x,a80)', iostat=error) j,lmem(j),mem(j) if (error /= 0) exit end do close (14) ! Open file containing parameters for this programme inquire (file='close.in', exist=test) if (test) then open (10, file='close.in', status='old') else call mio_err (6,mem(81),lmem(81),mem(88),lmem(88),' ',1,'close.in',9) end if ! Read number of input files 30 read (10,'(a250)') string if (string(1:1).eq.')') goto 30 call mio_spl (250,string,nsub,lim) read (string(lim(1,nsub):lim(2,nsub)),*) ninfile ! Make sure all the input files exist do j = 1, ninfile 40 read (10,'(a250)') string if (string(1:1).eq.')') goto 40 call mio_spl (250,string,nsub,lim) infile(j)(1:(lim(2,1)-lim(1,1)+1)) = string(lim(1,1):lim(2,1)) inquire (file=infile(j), exist=test) if (.not.test) call mio_err (6,mem(81),lmem(81),mem(88),lmem(88),' ',1,infile(j),80) end do ! Read parameters used by this programme timestyle = 1 do j = 1, 2 50 read (10,'(a250)') string if (string(1:1).eq.')') goto 50 call mio_spl (250,string,nsub,lim) c1 = string(lim(1,nsub):lim(2,nsub)) if (j.eq.1.and.(c1.eq.'d'.or.c1.eq.'D')) timestyle = 0 if (j.eq.2.and.(c1.eq.'y'.or.c1.eq.'Y')) timestyle = timestyle+2 end do ! Read in the names of the objects for which orbital elements are required nopen = 0 nwait = 0 nmaster = 0 call get_clo_format (timestyle,fout,header,lenhead) 60 continue read (10,'(a250)',end=70) string call mio_spl (250,string,nsub,lim) if (string(1:1).eq.')'.or.lim(1,1).eq.-1) goto 60 ! Either open an aei file for this object or put it on the waiting list nmaster = nmaster + 1 itmp = min(7,lim(2,1)-lim(1,1)) master_id(nmaster)=' ' master_id(nmaster)(1:itmp+1) = string(lim(1,1):lim(1,1)+itmp) if (nopen.lt.NFILES) then nopen = nopen + 1 master_unit(nmaster) = 10 + nopen call mio_clo (master_id(nmaster),master_unit(nmaster), header,lenhead) else nwait = nwait + 1 master_unit(nmaster) = -2 end if goto 60 70 continue ! If no objects are listed in CLOSE.IN assume that all objects are required if (nopen.eq.0) allflag = 1 close (10) !------------------------------------------------------------------------------ ! LOOP OVER EACH INPUT FILE CONTAINING INTEGRATION DATA 90 continue firstflag = 0 do i = 1, ninfile line_num = 0 open (10, file=infile(i), status='old') ! Loop over each time slice 100 continue line_num = line_num + 1 read (10,'(3a1)',end=900,err=666) check,style,type line_num = line_num - 1 backspace 10 ! Check if this is an old style input file if (ichar(check).eq.12.and.(style.eq.'0'.or.style.eq.'1'.or.style.eq.'2'.or.style.eq.'3'.or.style.eq.'4')) then write (*,'(/,2a)') ' ERROR: This is an old style data file',' Try running m_close5.for instead.' stop end if if (ichar(check).ne.12) goto 666 !------------------------------------------------------------------------------ ! IF SPECIAL INPUT, READ TIME, PARAMETERS, NAMES, MASSES ETC. if (type.eq.'a') then line_num = line_num + 1 read (10,'(3x,i2,a62,i1)') algor,cc(1:62),precision ! Decompress the time, number of objects, central mass and J components etc. time = mio_c2fl (cc(1:8)) if (firstflag.eq.0) then t0 = time firstflag = 1 end if nbig = int(.5d0 + mio_c2re(cc(9:16), 0.d0, 11239424.d0, 3)) nsml = int(.5d0 + mio_c2re(cc(12:19),0.d0, 11239424.d0, 3)) mcen = mio_c2fl (cc(15:22)) * K2 jcen(1) = mio_c2fl (cc(23:30)) jcen(2) = mio_c2fl (cc(31:38)) jcen(3) = mio_c2fl (cc(39:46)) rcen = mio_c2fl (cc(47:54)) rmax = mio_c2fl (cc(55:62)) rfac = log10 (rmax / rcen) ! Read in strings containing compressed data for each object do j = 1, nbig + nsml line_num = line_num + 1 read (10,'(a)',err=666) c(j)(1:51) end do ! Create input format list select case (precision) case(1) nchar = 2 case(2) nchar = 4 case(3) nchar = 7 case default nchar = 0 end select lenin = 3 + 6 * nchar fin(1:5) = '(a00)' write (fin(3:4),'(i2)') lenin ! For each object decompress its name, code number, mass, spin and density do j = 1, nbig + nsml k = int(.5d0 + mio_c2re(c(j)(1:8),0.d0,11239424.d0,3)) id(k) = c(j)(4:11) m(k) = mio_c2fl (c(j)(12:19)) * K2 ! Find the object on the master list unit(k) = 0 do l = 1, nmaster if (id(k).eq.master_id(l)) unit(k) = master_unit(l) end do ! If object is not on the master list, add it to the list now if (unit(k).eq.0) then nmaster = nmaster + 1 master_id(nmaster) = id(k) ! Either open an aei file for this object or put it on the waiting list if (allflag.eq.1) then if (nopen.lt.NFILES) then nopen = nopen + 1 master_unit(nmaster) = 10 + nopen call mio_clo (master_id(nmaster),master_unit(nmaster),header,lenhead) else nwait = nwait + 1 master_unit(nmaster) = -2 end if else master_unit(nmaster) = -1 end if unit(k) = master_unit(nmaster) end if end do !------------------------------------------------------------------------------ ! IF NORMAL INPUT, READ COMPRESSED DATA ON THE CLOSE ENCOUNTER else if (type.eq.'b') then line_num = line_num + 1 read (10,'(3x,a70)',err=666) cc(1:70) ! Decompress time, distance and orbital variables for each object time = mio_c2fl (cc(1:8)) iclo = int(.5d0 + mio_c2re(cc(9:16), 0.d0, 11239424.d0, 3)) jclo = int(.5d0 + mio_c2re(cc(12:19), 0.d0, 11239424.d0, 3)) if (iclo.gt.nb_bodies_initial.or.jclo.gt.nb_bodies_initial) then write (*,'(/,2a)') mem(81)(1:lmem(81)),mem(90)(1:lmem(90)) stop end if dclo = mio_c2fl (cc(15:22)) fr = mio_c2re (cc(23:30), 0.d0, rfac, 4) theta = mio_c2re (cc(27:34), 0.d0, PI, 4) phi = mio_c2re (cc(31:38), 0.d0, TWOPI, 4) fv = mio_c2re (cc(35:42), 0.d0, 1.d0, 4) vtheta = mio_c2re (cc(39:46), 0.d0, PI, 4) vphi = mio_c2re (cc(43:50), 0.d0, TWOPI, 4) call mco_ov2x (rcen,mcen,m(iclo),fr,theta,phi,fv,vtheta,vphi,x1(1),x1(2),x1(3),v1(1),v1(2),v1(3)) fr = mio_c2re (cc(47:54), 0.d0, rfac, 4) theta = mio_c2re (cc(51:58), 0.d0, PI, 4) phi = mio_c2re (cc(55:62), 0.d0, TWOPI, 4) fv = mio_c2re (cc(59:66), 0.d0, 1.d0, 4) vtheta = mio_c2re (cc(63:70), 0.d0, PI, 4) vphi = mio_c2re (cc(67:74), 0.d0, TWOPI, 4) call mco_ov2x (rcen,mcen,m(jclo),fr,theta,phi,fv,vtheta,vphi,x2(1),x2(2),x2(3),v2(1),v2(2),v2(3)) ! Convert to Keplerian elements gm = mcen + m(iclo) call mco_x2el (gm,x1(1),x1(2),x1(3),v1(1),v1(2),v1(3),q1,e1,i1,p1,n1,l1) a1 = q1 / (1.d0 - e1) gm = mcen + m(jclo) call mco_x2el (gm,x2(1),x2(2),x2(3),v2(1),v2(2),v2(3),q2,e2,i2,p2,n2,l2) a2 = q2 / (1.d0 - e2) i1 = i1 * RAD2DEG i2 = i2 * RAD2DEG ! Convert time to desired format if (timestyle.eq.0) t1 = time if (timestyle.eq.1) call mio_jd2y (time,year,month,t1) if (timestyle.eq.2) t1 = time - t0 if (timestyle.eq.3) t1 = (time - t0) / 365.25d0 ! Write encounter details to appropriate files if (timestyle.eq.1) then if (unit(iclo).ge.10) write (unit(iclo),fout) year,month,t1,id(jclo),dclo,a1,e1,i1,a2,e2,i2 if (unit(jclo).ge.10) write (unit(jclo),fout) year,month,t1,id(iclo),dclo,a2,e2,i2,a1,e1,i1 else if (unit(iclo).ge.10) write (unit(iclo),fout) t1,id(jclo),dclo,a1,e1,i1,a2,e2,i2 if (unit(jclo).ge.10) write (unit(jclo),fout) t1,id(iclo),dclo,a2,e2,i2,a1,e1,i1 end if !------------------------------------------------------------------------------ ! IF TYPE IS NOT 'a' OR 'b', THE INPUT FILE IS CORRUPTED else goto 666 end if ! Move on to the next time slice goto 100 ! If input file is corrupted, try to continue from next uncorrupted time slice 666 continue write (*,'(2a,/,a,i10)') mem(121)(1:lmem(121)),infile(i)(1:60),mem(104)(1:lmem(104)),line_num c1 = ' ' do while (ichar(c1).ne.12) line_num = line_num + 1 read (10,'(a1)',end=900) c1 end do line_num = line_num - 1 backspace 10 ! Move on to the next file containing close encounter data 900 continue close (10) end do ! Close clo files do j = 1, nopen close (10+j) end do nopen = 0 ! If some objects remain on waiting list, read through input files again if (nwait.gt.0) then do j = 1, nmaster if (master_unit(j).ge.10) master_unit(j) = -1 if (master_unit(j).eq.-2.and.nopen.lt.NFILES) then nopen = nopen + 1 nwait = nwait - 1 master_unit(j) = 10 + nopen call mio_clo (master_id(j),master_unit(j),header,lenhead) end if end do goto 90 end if end program close !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% !> @author !> <NAME> ! !> @date 30 November 1999 ! ! DESCRIPTION: !> @brief This routine gives the header of the output .clo file regarding the timestyle used. !! The len of the header, and the output format is also returned. ! !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% subroutine get_clo_format (timestyle,fout,header,lenhead) implicit none ! Input integer, intent(in) :: timestyle ! Output integer, intent(out) :: lenhead ! length of the header character(len=250), intent(out) :: fout ! The output format for the .clo file character(len=250), intent(out) :: header ! The header of the .clo file !------------------------------------------------------------------------------ select case (timestyle) case (0,2) header(1:19) = ' Time (days) ' header(20:58) = ' Object dmin (AU) a1 e1 ' header(59:90) = ' i1 a2 e2 i2' lenhead = 90 fout = '(1x,f18.5,1x,a8,1x,f10.8,2(1x,f9.4,1x,f8.6,1x,f7.3))' case (1) header(1:23) = ' Year/Month/Day ' header(24:62) = ' Object dmin (AU) a1 e1 ' header(63:94) = ' i1 a2 e2 i2' lenhead = 94 fout(1:37) = '(1x,i10,1x,i2,1x,f8.5,1x,a8,1x,f10.8,' fout(38:64) = '2(1x,f9.4,1x,f8.6,1x,f7.3))' case default header(1:19) = ' Time (years) ' header(20:58) = ' Object dmin (AU) a1 e1 ' header(59:90) = ' i1 a2 e2 i2' fout = '(1x,f18.7,1x,a8,1x,f10.8,2(1x,f9.4,1x,f8.6,1x,f7.3))' lenhead = 90 end select !------------------------------------------------------------------------------ return end subroutine get_clo_format <file_sep>!****************************************************************************** ! MODULE: system_properties !****************************************************************************** ! ! DESCRIPTION: !> @brief Modules that compute various properties of the system like !! the total energy and angular momentum, jacobi constants, !! hill radii, if there are ejections and so on. ! !****************************************************************************** module system_properties use types_numeriques use mercury_globals implicit none private m_sfunc contains !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% !> @author !> <NAME> ! !> @date 4 October 2000 ! ! DESCRIPTION: !> @brief Calculates the Hill radii for all objects given their masses, M, !! coordinates, X, and velocities, V; plus the mass of the central body, M(1) !! Where HILL = a * (m/3*m(1))^(1/3) !!\n\n !! If the orbit is hyperbolic or parabolic, the Hill radius is calculated using: !!\n HILL = r * (m/3*m(1))^(1/3) !! where R is the current distance from the central body. !!\n\n !! The routine also gives the semi-major axis, A, of each object's orbit. ! !> @note Designed to use heliocentric coordinates, but should be adequate using !! barycentric coordinates. ! !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% subroutine mce_hill (nbod,m,x,v,hill,a) use physical_constant use mercury_constant use orbital_elements implicit none ! Input/Output integer, intent(in) :: nbod !< [in] current number of bodies (1: star; 2-nbig: big bodies; nbig+1-nbod: small bodies) real(double_precision), intent(in) :: m(nbod) !< [in] mass (in solar masses * K2) real(double_precision), intent(in) :: x(3,nbod) real(double_precision), intent(in) :: v(3,nbod) real(double_precision), intent(out) :: hill(nbod) real(double_precision), intent(out) :: a(nbod) ! Local integer :: j real(double_precision) :: r, v2, gm !------------------------------------------------------------------------------ do j = 2, nbod gm = m(1) + m(j) call mco_x2a (gm,x(1,j),x(2,j),x(3,j),v(1,j),v(2,j),v(3,j),a(j),r,v2) ! If orbit is hyperbolic, use the distance rather than the semi-major axis if (a(j).le.0) a(j) = r hill(j) = a(j) * (THIRD * m(j) / m(1))**THIRD end do !------------------------------------------------------------------------------ return end subroutine mce_hill !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% !> @author !> <NAME> ! !> @date 28 February 2001 ! ! DESCRIPTION: !> @brief Calculates close-approach limits RCE (in AU) and physical radii RPHYS !! (in AU) for all objects, given their masses M, coordinates X, velocities !! V, densities RHO, and close-approach limits RCEH (in Hill radii). !!\n\n !! Also calculates the changeover distance RCRIT, used by the hybrid !! symplectic integrator. RCRIT is defined to be the larger of N1*HILL and !! N2*H*VMAX, where HILL is the Hill radius, H is the timestep, VMAX is the !! largest expected velocity of any body, and N1, N2 are parameters (see !! section 4.2 of Chambers 1999, Monthly Notices, vol 304, p793-799). ! !> @note Designed to use heliocentric coordinates, but should be adequate using !! barycentric coordinates. ! !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% subroutine mce_init (h,jcen,rcen,cefac,nbod,nbig,m,x,v,s,rho,rceh,rphys,rce,rcrit,id,outfile,rcritflag,m_x) use physical_constant use mercury_constant use ascii_conversion implicit none real(double_precision), parameter :: N2=.4d0 ! Input/Output integer, intent(in) :: nbod !< [in] current number of bodies (1: star; 2-nbig: big bodies; nbig+1-nbod: small bodies) integer, intent(in) :: nbig !< [in] current number of big bodies (ones that perturb everything else) integer, intent(in) :: rcritflag real(double_precision), intent(in) :: m(nbod) !< [in] mass (in solar masses * K2) real(double_precision), intent(in) :: m_x(nbod) !< [in] mass of element X (in solar masses * K2) real(double_precision), intent(in) :: x(3,nbod) real(double_precision), intent(in) :: v(3,nbod) real(double_precision), intent(in) :: rho(nbod) !< [in] physical density (g/cm^3) real(double_precision), intent(in) :: rceh(nbod) !< [in] close-encounter limit (Hill radii) real(double_precision), intent(in) :: jcen(3) !< [in] J2,J4,J6 for central body (units of RCEN^i for Ji) real(double_precision), intent(in) :: s(3,nbod) !< [in] spin angular momentum (solar masses AU^2/day) real(double_precision), intent(in) :: h !< [in] current integration timestep (days) real(double_precision), intent(in) :: rcen !< [in] radius of central body (AU) real(double_precision), intent(in) :: cefac character(len=8), intent(in) :: id(nbod) !< [in] name of the object (8 characters) character(len=80), intent(in) :: outfile real(double_precision), intent(out) :: rce(nbod) real(double_precision), intent(out) :: rphys(nbod) real(double_precision), intent(out) :: rcrit(nbod) ! Local integer :: j, error real(double_precision) :: a(nb_bodies_initial),hill(nb_bodies_initial),temp,amin,vmax,k_2,rhocgs,rcen_2 character(len=80) :: header,c(nb_bodies_initial) !------------------------------------------------------------------------------ rhocgs = AU * AU * AU * K2 / MSUN k_2 = 1.d0 / K2 rcen_2 = 1.d0 / (rcen * rcen) amin = HUGE ! Calculate the Hill radii call mce_hill (nbod,m,x,v,hill,a) ! Determine the maximum close-encounter distances, and the physical radii temp = 2.25d0 * m(1) / PI do j = 2, nbod rce(j) = hill(j) * rceh(j) rphys(j) = hill(j) / a(j) * (temp/rho(j))**THIRD amin = min (a(j), amin) end do ! If required, calculate the changeover distance used by hybrid algorithm if (rcritflag.eq.1) then vmax = sqrt (m(1) / amin) temp = N2 * h * vmax do j = 2, nbod rcrit(j) = max(hill(j) * cefac, temp) end do end if ! Write list of object's identities to close-encounter output file header(1:8) = mio_fl2c (tstart) header(9:16) = mio_re2c (dble(nbig - 1), 0.d0, 11239423.99d0) header(12:19) = mio_re2c (dble(nbod - nbig),0.d0, 11239423.99d0) header(15:22) = mio_fl2c (m(1) * k_2) header(23:30) = mio_fl2c (jcen(1) * rcen_2) header(31:38) = mio_fl2c (jcen(2) * rcen_2 * rcen_2) header(39:46) = mio_fl2c (jcen(3) * rcen_2 * rcen_2 * rcen_2) header(47:54) = mio_fl2c (rcen) header(55:62) = mio_fl2c (rmax) do j = 2, nbod c(j)(1:8) = mio_re2c (dble(j - 1), 0.d0, 11239423.99d0) c(j)(4:11) = id(j) c(j)(12:19) = mio_fl2c (m(j) * k_2) !do not write m_x in ce.out c(j)(52:59) = mio_fl2c (m_x(j) * k_2) c(j)(20:27) = mio_fl2c (s(1,j) * k_2) c(j)(28:35) = mio_fl2c (s(2,j) * k_2) c(j)(36:43) = mio_fl2c (s(3,j) * k_2) c(j)(44:51) = mio_fl2c (rho(j) / rhocgs) end do ! Write compressed output to file : ce.out open (22, file=outfile, status='old', position='append', iostat=error) if (error /= 0) then write (*,'(/,2a)') " ERROR: Programme terminated. Unable to open ",trim(outfile) stop end if write (22,'(a1,a2,i2,a62,i1)') char(12),'6a',algor,header(1:62),opt(4) do j = 2, nbod write (22,'(a51)') c(j)(1:51) end do close (22) !------------------------------------------------------------------------------ return end subroutine mce_init !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% !> @author !> <NAME> ! !> @date 21 February 2001 ! ! DESCRIPTION: !> @brief Calculates the total energy and angular-momentum for a system of objects !! with masses M, coordinates X, velocities V and spin angular momenta S. ! !> @note All coordinates and velocities must be with respect to the central !! body. ! !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% subroutine mxx_en (jcen,nbod,nbig,m,xh,vh,s,e,l2) use physical_constant use mercury_constant implicit none ! Input/Output integer, intent(in) :: nbod !< [in] current number of bodies (1: star; 2-nbig: big bodies; nbig+1-nbod: small bodies) integer, intent(in) :: nbig !< [in] current number of big bodies (ones that perturb everything else) real(double_precision), intent(in) :: jcen(3) !< [in] J2,J4,J6 for central body (units of RCEN^i for Ji) real(double_precision), intent(in) :: m(nbod) !< [in] mass (in solar masses * K2) real(double_precision), intent(in) :: xh(3,nbod) !< [in] coordinates (x,y,z) with respect to the central body (AU) real(double_precision), intent(in) :: vh(3,nbod) !< [in] velocities (vx,vy,vz) with respect to the central body (AU/day) real(double_precision), intent(in) :: s(3,nbod) !< [in] spin angular momentum (solar masses AU^2/day) real(double_precision), intent(out) :: e ! energy real(double_precision), intent(out) :: l2 ! angular momentum ! Local integer :: j,k,iflag,itmp(8) real(double_precision) :: x(3,nb_bodies_initial),v(3,nb_bodies_initial),temp,dx,dy,dz,r2,tmp,ke,pe,l(3) real(double_precision) :: r_1,r_2,r_4,r_6,u2,u4,u6,tmp2(4,nb_bodies_initial) !------------------------------------------------------------------------------ ke = 0.d0 pe = 0.d0 l(1) = 0.d0 l(2) = 0.d0 l(3) = 0.d0 ! Convert to barycentric coordinates and velocities call mco_h2b(jcen,nbod,nbig,temp,m,xh,vh,x,v) ! Do the spin angular momenta first (probably the smallest terms) do j = 1, nbod l(1) = l(1) + s(1,j) l(2) = l(2) + s(2,j) l(3) = l(3) + s(3,j) end do ! Orbital angular momentum and kinetic energy terms do j = 1, nbod l(1) = l(1) + m(j)*(x(2,j) * v(3,j) - x(3,j) * v(2,j)) l(2) = l(2) + m(j)*(x(3,j) * v(1,j) - x(1,j) * v(3,j)) l(3) = l(3) + m(j)*(x(1,j) * v(2,j) - x(2,j) * v(1,j)) ke = ke + m(j)*(v(1,j)*v(1,j)+v(2,j)*v(2,j)+v(3,j)*v(3,j)) end do ! Potential energy terms due to pairs of bodies do j = 2, nbod tmp = 0.d0 do k = j + 1, nbod dx = x(1,k) - x(1,j) dy = x(2,k) - x(2,j) dz = x(3,k) - x(3,j) r2 = dx*dx + dy*dy + dz*dz if (r2.ne.0) tmp = tmp + m(k) / sqrt(r2) end do pe = pe - tmp * m(j) end do ! Potential energy terms involving the central body do j = 2, nbod dx = x(1,j) - x(1,1) dy = x(2,j) - x(2,1) dz = x(3,j) - x(3,1) r2 = dx*dx + dy*dy + dz*dz if (r2.ne.0) pe = pe - m(1) * m(j) / sqrt(r2) end do ! Corrections for oblateness if (jcen(1).ne.0.or.jcen(2).ne.0.or.jcen(3).ne.0) then do j = 2, nbod r2 = xh(1,j)*xh(1,j) + xh(2,j)*xh(2,j) + xh(3,j)*xh(3,j) r_1 = 1.d0 / sqrt(r2) r_2 = r_1 * r_1 r_4 = r_2 * r_2 r_6 = r_4 * r_2 u2 = xh(3,j) * xh(3,j) * r_2 u4 = u2 * u2 u6 = u4 * u2 pe = pe + m(1) * m(j) * r_1 * (jcen(1) * r_2 * (1.5d0*u2 - 0.5d0) + jcen(2) * r_4 * (4.375d0*u4 - 3.75d0*u2 + .375d0)& + jcen(3) * r_6 *(14.4375d0*u6 - 19.6875d0*u4 + 6.5625d0*u2 - .3125d0)) end do end if e = .5d0 * ke + pe l2 = sqrt(l(1)*l(1) + l(2)*l(2) + l(3)*l(3)) !------------------------------------------------------------------------------ return end subroutine mxx_en !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% !> @author !> <NAME> ! !> @date 2 March 2001 ! ! DESCRIPTION: !> @brief Calculates the Jacobi constant for massless particles. This assumes that !! there are only 2 massive bodies (including the central body) moving on !! circular orbits. ! !> @note All coordinates and velocities must be heliocentric! ! !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% subroutine mxx_jac (jcen,nbod,nbig,m,xh,vh,jac) use physical_constant use mercury_constant implicit none ! Input/Output integer, intent(in) :: nbod !< [in] current number of bodies (1: star; 2-nbig: big bodies; nbig+1-nbod: small bodies) integer, intent(in) :: nbig !< [in] current number of big bodies (ones that perturb everything else) real(double_precision), intent(in) :: jcen(3) !< [in] J2,J4,J6 for central body (units of RCEN^i for Ji) real(double_precision), intent(in) :: m(nbod) !< [in] mass (in solar masses * K2) real(double_precision), intent(in) :: xh(3,nbod) !< [in] coordinates (x,y,z) with respect to the central body (AU) real(double_precision), intent(in) :: vh(3,nbod) !< [in] velocities (vx,vy,vz) with respect to the central body (AU/day) real(double_precision), intent(out) :: jac(nbod) ! Local integer :: j,itmp(8),iflag real(double_precision) :: x(3,nb_bodies_initial),v(3,nb_bodies_initial),temp,dx,dy,dz,r,d,a2,n real(double_precision) :: tmp2(4,nb_bodies_initial) !------------------------------------------------------------------------------ call mco_h2b(jcen,nbod,nbig,temp,m,xh,vh,x,v) dx = x(1,2) - x(1,1) dy = x(2,2) - x(2,1) dz = x(3,2) - x(3,1) a2 = dx*dx + dy*dy + dz*dz n = sqrt((m(1)+m(2)) / (a2*sqrt(a2))) do j = nbig + 1, nbod dx = x(1,j) - x(1,1) dy = x(2,j) - x(2,1) dz = x(3,j) - x(3,1) r = sqrt(dx*dx + dy*dy + dz*dz) dx = x(1,j) - x(1,2) dy = x(2,j) - x(2,2) dz = x(3,j) - x(3,2) d = sqrt(dx*dx + dy*dy + dz*dz) jac(j) = .5d0*(v(1,j)*v(1,j) + v(2,j)*v(2,j) + v(3,j)*v(3,j)) - m(1)/r - m(2)/d - n*(x(1,j)*v(2,j) - x(2,j)*v(1,j)) end do !------------------------------------------------------------------------------ return end subroutine mxx_jac !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% !> @author !> <NAME> ! !> @date 2 November 2000 ! ! DESCRIPTION: !> @brief Calculates the distance from the central body of each object with index !! I >= I0. If this distance exceeds RMAX, the object is flagged for ejection !! (STAT set to -3). If any object is to be ejected, EJFLAG = 1 on exit, !! otherwise EJFLAG = 0.\n\n !! !! Also updates the values of EN(3) and AM(3)---the change in energy and !! angular momentum due to collisions and ejections. ! !> @note All coordinates must be with respect to the central body! ! !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% subroutine mxx_ejec (time,en,am,jcen,i0,nbod,nbig,m,x,v,s,stat,id,ejflag,outfile) use physical_constant use mercury_constant use utilities implicit none ! Input integer, intent(in) :: i0, nbod, nbig real(double_precision), intent(in) :: time !< [in] current epoch (days) real(double_precision), intent(in) :: jcen(3) !< [in] J2,J4,J6 for central body (units of RCEN^i for Ji) real(double_precision), intent(in) :: x(3,nbod) real(double_precision), intent(in) :: v(3,nbod) character(len=80), intent(in) :: outfile character(len=8), intent(in) :: id(nbod) !< [in] name of the object (8 characters) ! Output real(double_precision), intent(out) :: en(3) !< [out] (initial energy, current energy, energy change due to collision and ejection) of the system real(double_precision), intent(out) :: am(3) !< [out] (initial angular momentum, current angular momentum, !! angular momentum change due to collision and ejection) of the system integer, intent(out) :: ejflag integer, intent(out) :: stat(nbod) !< [out] status (0 => alive, <>0 => to be removed) ! Input/Output real(double_precision), intent(inout) :: m(nbod) !< [in,out] mass (in solar masses * K2) real(double_precision), intent(inout) :: s(3,nbod) !< [in,out] spin angular momentum (solar masses AU^2/day) ! Local integer :: j,j0, year, month real(double_precision) :: r2,rmax2,t1,e,l character(len=38) :: flost character(len=6) :: tstring integer :: error !------------------------------------------------------------------------------ if (i0.le.0) then j0 = 2 else j0 = i0 end if ejflag = 0 rmax2 = rmax * rmax ! Calculate initial energy and angular momentum call mxx_en (jcen,nbod,nbig,m,x,v,s,e,l) ! Flag each object which is ejected, and set its mass to zero do j = j0, nbod r2 = x(1,j)*x(1,j) + x(2,j)*x(2,j) + x(3,j)*x(3,j) if (r2.gt.rmax2) then ejflag = 1 stat(j) = -3 m(j) = 0.d0 s(1,j) = 0.d0 s(2,j) = 0.d0 s(3,j) = 0.d0 ! Write message to information file open (23,file=outfile,status='old',position='append',iostat=error) if (error /= 0) then write (*,'(/,2a)') " ERROR: Programme terminated. Unable to open ",trim(outfile) stop end if if (opt(3).eq.1) then call mio_jd2y (time,year,month,t1) flost = '(1x,a8,a,i10,1x,i2,1x,f8.5)' write (23,flost) id(j),mem(68)(1:lmem(68)),year,month,t1 else if (opt(3).eq.3) then t1 = (time - tstart) / 365.25d0 tstring = mem(2) flost = '(1x,a8,a,f18.7,a)' else if (opt(3).eq.0) t1 = time if (opt(3).eq.2) t1 = time - tstart tstring = mem(1) flost = '(1x,a8,a,f18.5,a)' end if write (23,flost) id(j),mem(68)(1:lmem(68)),t1,tstring end if close (23) end if end do ! If ejections occurred, update ELOST and LLOST if (ejflag.ne.0) then call mxx_en (jcen,nbod,nbig,m,x,v,s,en(2),am(2)) en(3) = en(3) + (e - en(2)) am(3) = am(3) + (l - am(2)) end if !------------------------------------------------------------------------------ return end subroutine mxx_ejec !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% !> @author !> <NAME> ! !> @date 2 March 2001 ! ! DESCRIPTION: !> @brief Converts barycentric coordinates to coordinates with respect to the central !! body. ! !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% subroutine mco_b2h (time,jcen,nbod,nbig,h,m,x,v,xh,vh,ngf,ngflag) implicit none ! Input integer,intent(in) :: nbod !< [in] current number of bodies (1: star; 2-nbig: big bodies; nbig+1-nbod: small bodies) integer,intent(in) :: nbig !< [in] current number of big bodies (ones that perturb everything else) integer,intent(in) :: ngflag !< [in] do any bodies experience non-grav. forces? !!\n ( 0 = no non-grav forces) !!\n 1 = cometary jets only !!\n 2 = radiation pressure/P-R drag only !!\n 3 = both real(double_precision),intent(in) :: time !< [in] current epoch (days) real(double_precision),intent(in) :: h !< [in] current integration timestep (days) real(double_precision),intent(in) :: jcen(3) !< [in] J2,J4,J6 for central body (units of RCEN^i for Ji) real(double_precision),intent(in) :: m(nbod) !< [in] mass (in solar masses * K2) real(double_precision),intent(in) :: x(3,nbod) real(double_precision),intent(in) :: v(3,nbod) real(double_precision),intent(in) :: ngf(4,nbod) !< [in] non gravitational forces parameters !! \n(1-3) cometary non-gravitational (jet) force parameters !! \n(4) beta parameter for radiation pressure and P-R drag ! Output real(double_precision),intent(out) :: xh(3,nbod) !< [out] coordinates (x,y,z) with respect to the central body (AU) real(double_precision),intent(out) :: vh(3,nbod) !< [out] velocities (vx,vy,vz) with respect to the central body (AU/day) ! Local integer :: j !------------------------------------------------------------------------------ do j = 2, nbod xh(1,j) = x(1,j) - x(1,1) xh(2,j) = x(2,j) - x(2,1) xh(3,j) = x(3,j) - x(3,1) vh(1,j) = v(1,j) - v(1,1) vh(2,j) = v(2,j) - v(2,1) vh(3,j) = v(3,j) - v(3,1) enddo !------------------------------------------------------------------------------ return end subroutine mco_b2h !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% !> @author !> <NAME> ! !> @date 2 March 2001 ! ! DESCRIPTION: !> @brief Converts coordinates with respect to the central body to barycentric !! coordinates. ! !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% subroutine mco_h2b (jcen,nbod,nbig,h,m,xh,vh,x,v) implicit none ! Input/Output integer,intent(in) :: nbod !< [in] current number of bodies (1: star; 2-nbig: big bodies; nbig+1-nbod: small bodies) integer,intent(in) :: nbig !< [in] current number of big bodies (ones that perturb everything else) real(double_precision),intent(in) :: h !< [in] current integration timestep (days) real(double_precision),intent(in) :: jcen(3) !< [in] J2,J4,J6 for central body (units of RCEN^i for Ji) real(double_precision),intent(in) :: m(nbod) !< [in] mass (in solar masses * K2) real(double_precision),intent(in) :: xh(3,nbod) !< [in] coordinates (x,y,z) with respect to the central body (AU) real(double_precision),intent(in) :: vh(3,nbod) !< [in] velocities (vx,vy,vz) with respect to the central body (AU/day) real(double_precision),intent(out) :: x(3,nbod) real(double_precision),intent(out) :: v(3,nbod) ! Local integer :: j real(double_precision) :: mtot,temp !------------------------------------------------------------------------------ mtot = 0.d0 x(1,1) = 0.d0 x(2,1) = 0.d0 x(3,1) = 0.d0 v(1,1) = 0.d0 v(2,1) = 0.d0 v(3,1) = 0.d0 ! Calculate coordinates and velocities of the central body do j = 2, nbod mtot = mtot + m(j) x(1,1) = x(1,1) + m(j) * xh(1,j) x(2,1) = x(2,1) + m(j) * xh(2,j) x(3,1) = x(3,1) + m(j) * xh(3,j) v(1,1) = v(1,1) + m(j) * vh(1,j) v(2,1) = v(2,1) + m(j) * vh(2,j) v(3,1) = v(3,1) + m(j) * vh(3,j) enddo temp = -1.d0 / (mtot + m(1)) x(1,1) = temp * x(1,1) x(2,1) = temp * x(2,1) x(3,1) = temp * x(3,1) v(1,1) = temp * v(1,1) v(2,1) = temp * v(2,1) v(3,1) = temp * v(3,1) ! Calculate the barycentric coordinates and velocities do j = 2, nbod x(1,j) = xh(1,j) + x(1,1) x(2,j) = xh(2,j) + x(2,1) x(3,j) = xh(3,j) + x(3,1) v(1,j) = vh(1,j) + v(1,1) v(2,j) = vh(2,j) + v(2,1) v(3,j) = vh(3,j) + v(3,1) enddo !------------------------------------------------------------------------------ return end subroutine mco_h2b !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% !> @author !> <NAME> ! !> @date 2 November 2000 ! ! DESCRIPTION: !> @brief Convert coordinates with respect to the central body to close-binary !! coordinates. ! !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% subroutine mco_h2cb (jcen,nbod,nbig,h,m,xh,vh,x,v) implicit none ! Input/Output integer,intent(in) :: nbod !< [in] current number of bodies (1: star; 2-nbig: big bodies; nbig+1-nbod: small bodies) integer,intent(in) :: nbig !< [in] current number of big bodies (ones that perturb everything else) real(double_precision),intent(in) :: jcen(3) !< [in] J2,J4,J6 for central body (units of RCEN^i for Ji) real(double_precision),intent(in) :: h !< [in] current integration timestep (days) real(double_precision),intent(in) :: m(nbod) !< [in] mass (in solar masses * K2) real(double_precision),intent(in) :: xh(3,nbod) !< [in] coordinates (x,y,z) with respect to the central body (AU) real(double_precision),intent(in) :: vh(3,nbod) !< [in] velocities (vx,vy,vz) with respect to the central body (AU/day) real(double_precision),intent(out) :: x(3,nbod) real(double_precision),intent(out) :: v(3,nbod) ! Local integer :: j real(double_precision) :: msum,mvsum(3),temp,mbin,mbin_1,mtot_1 !------------------------------------------------------------------------------ msum = 0.d0 mvsum(1) = 0.d0 mvsum(2) = 0.d0 mvsum(3) = 0.d0 mbin = m(1) + m(2) mbin_1 = 1.d0 / mbin x(1,2) = xh(1,2) x(2,2) = xh(2,2) x(3,2) = xh(3,2) temp = m(1) * mbin_1 v(1,2) = temp * vh(1,2) v(2,2) = temp * vh(2,2) v(3,2) = temp * vh(3,2) do j = 3, nbod msum = msum + m(j) mvsum(1) = mvsum(1) + m(j) * vh(1,j) mvsum(2) = mvsum(2) + m(j) * vh(2,j) mvsum(3) = mvsum(3) + m(j) * vh(3,j) end do mtot_1 = 1.d0 / (msum + mbin) mvsum(1) = mtot_1 * (mvsum(1) + m(2)*vh(1,2)) mvsum(2) = mtot_1 * (mvsum(2) + m(2)*vh(2,2)) mvsum(3) = mtot_1 * (mvsum(3) + m(2)*vh(3,2)) temp = m(2) * mbin_1 do j = 3, nbod x(1,j) = xh(1,j) - temp * xh(1,2) x(2,j) = xh(2,j) - temp * xh(2,2) x(3,j) = xh(3,j) - temp * xh(3,2) v(1,j) = vh(1,j) - mvsum(1) v(2,j) = vh(2,j) - mvsum(2) v(3,j) = vh(3,j) - mvsum(3) end do !------------------------------------------------------------------------------ return end subroutine mco_h2cb !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% !> @author !> <NAME> ! !> @date 2 November 2000 ! ! DESCRIPTION: !> @brief Fake subroutine that simulate a change of coordinate system. In fact, !! it only duplicate the existing coordinates. So it's the identity. !! It is used to test the program with a fake algorithm (I think) ! !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% subroutine mco_iden (time,jcen,nbod,nbig,h,m,x_in,v_in,x_out,v_out,ngf,ngflag) implicit none ! Input integer,intent(in) :: nbod !< [in] current number of bodies (1: star; 2-nbig: big bodies; nbig+1-nbod: small bodies) integer,intent(in) :: nbig !< [in] current number of big bodies (ones that perturb everything else) integer,intent(in) :: ngflag !< [in] do any bodies experience non-grav. forces? !!\n ( 0 = no non-grav forces) !!\n 1 = cometary jets only !!\n 2 = radiation pressure/P-R drag only !!\n 3 = both real(double_precision),intent(in) :: time !< [in] current epoch (days) real(double_precision),intent(in) :: jcen(3) !< [in] J2,J4,J6 for central body (units of RCEN^i for Ji) real(double_precision),intent(in) :: h !< [in] current integration timestep (days) real(double_precision),intent(in) :: m(nbod) !< [in] mass (in solar masses * K2) real(double_precision),intent(in) :: x_in(3,nbod) real(double_precision),intent(in) :: v_in(3,nbod) real(double_precision),intent(in) :: ngf(4,nbod) !< [in] non gravitational forces parameters !! \n(1-3) cometary non-gravitational (jet) force parameters !! \n(4) beta parameter for radiation pressure and P-R drag ! Output real(double_precision), intent(out) :: x_out(3,nbod) real(double_precision), intent(out) :: v_out(3,nbod) ! Local integer :: j !------------------------------------------------------------------------------ do j = 1, nbod x_out(1,j) = x_in(1,j) x_out(2,j) = x_in(2,j) x_out(3,j) = x_in(3,j) v_out(1,j) = v_in(1,j) v_out(2,j) = v_in(2,j) v_out(3,j) = v_in(3,j) enddo !------------------------------------------------------------------------------ return end subroutine mco_iden !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% !> @author !> <NAME> ! !> @date 2 December 1999 ! ! DESCRIPTION: !> @brief Calculates the spin rate (in rotations per day) for a fluid body given !! its mass, spin angular momentum and density. The routine assumes the !! body is a MacClaurin ellipsoid, whose axis ratio is defined by the !! quantity SS = SQRT(A^2/C^2 - 1), where A and C are the !! major and minor axes. ! !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% subroutine mce_spin (g,mass,spin,rho,rote) use physical_constant use mercury_constant implicit none ! Input/Output real(double_precision),intent(in) :: g real(double_precision),intent(in) :: mass !< [in] mass (in solar masses * K2) real(double_precision),intent(in) :: spin !< [in] spin angular momentum (solar masses AU^2/day) real(double_precision),intent(in) :: rho !< [in] physical density (g/cm^3) real(double_precision),intent(out) :: rote !< [out] spin rate (in rotations per day) ! Local integer :: k real(double_precision) :: ss,s2,f,df,z,dz,tmp0,tmp1,t23 !------------------------------------------------------------------------------ t23 = 2.d0 / 3.d0 tmp1 = spin * spin / (2.d0 * PI * rho * g) * ( 250.d0*PI*PI*rho*rho / (9.d0*mass**5) )**t23 ! Calculate SS using Newton's method ss = 1.d0 do k = 1, 20 s2 = ss * ss tmp0 = (1.d0 + s2)**t23 call m_sfunc (ss,z,dz) f = z * tmp0 - tmp1 df = tmp0 * ( dz + 4.d0 * ss * z / (3.d0*(1.d0 + s2)) ) ss = ss - f/df end do rote = sqrt(TWOPI * g * rho * z) / TWOPI !------------------------------------------------------------------------------ return end subroutine mce_spin !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% !> @author !> <NAME> ! !> @date 14 November 1998 ! ! DESCRIPTION: !> @brief Calculates Z = [ (3 + S^2)arctan(S) - 3S ] / S^3 and its derivative DZ, !! for S > 0. ! !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% subroutine m_sfunc (s,z,dz) implicit none ! Input/Output real(double_precision),intent(in) :: s real(double_precision),intent(out) :: z real(double_precision),intent(out) :: dz ! Local real(double_precision) :: s2,s4,s6,s8,a !------------------------------------------------------------------------------ s2 = s * s if (s.gt.1.d-2) then a = atan(s) z = ((3.d0 + s2)*a - 3.d0*s) / (s * s2) dz = (2.d0*s*a - 3.d0 + (3.d0+s2)/(1.d0+s2)) / (s * s2) - 3.d0 * z / s else s4 = s2 * s2 s6 = s2 * s4 s8 = s4 * s4 z = - .1616161616161616d0*s8 + .1904761904761905d0*s6 - .2285714285714286d0*s4 + .2666666666666667d0*s2 dz = s * (- 1.292929292929293d0*s6 + 1.142857142857143d0*s4 - 0.914285714285714d0*s2 + 0.533333333333333d0) end if !------------------------------------------------------------------------------ return end subroutine m_sfunc end module system_properties <file_sep>#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Jul 24 11:12:25 2019 @author: jooehn """ import os import numpy as np import matplotlib.pyplot as plt from diskmodel import * from astrounit import * from labellines import labelLines from plotset import * from m6_funcs import get_disk_params #If an input file is provided, we use the given inputs from it try: sys.argv[1] except (IndexError,NameError): source = 'pa+mig10' else: source = sys.argv[1] #The vars.ini file cdir = os.getcwd()#+'/' #current dir sourcedir = cdir+'/../sim/'+source+'/' pydir = cdir # python dir workdir = cdir+'/../figure/' ## in source direction, generating the aei output file os.chdir(sourcedir) avals = np.linspace(0.1,100,100) _,alpha_v,mdot_gas,L_s,_,mdot_peb,st,kap,M_s,opt_vis = get_disk_params() r_trans = rtrans(mdot_gas,L_s,M_s,alpha_v,kap,opt_vis) r_snow = rsnow(mdot_gas,L_s,M_s,alpha_v,kap,opt_vis) # change into figure direction os.chdir(workdir) fig, ax = plt.subplots(figsize=(8,6)) alpha_d = np.array([1e-3,1e-4]) cols = ['tab:green','tab:blue'] lines = [] for i in range(len(alpha_d)): m_gap = gap_mass(avals,mdot_gas,L_s,M_s,alpha_d[i],alpha_v,kap,opt_vis) m_iso = m_gap/2.3 m_opt = opt_mass(avals,mdot_gas,L_s,M_s,alpha_d[i],alpha_v,kap,opt_vis) line, = ax.plot(avals,m_gap,linestyle='-',color=cols[i],\ label=r'$\alpha_t='+'{:.0e}'.format(alpha_d[i])+'$') lines.append(line) ax.plot(avals,m_iso,linestyle='--',color=cols[i]) ax.plot(avals,m_opt,linestyle='-.',color=cols[i]) gaphandle, = ax.plot([],[],'k-',label='$M_\mathrm{gap}$') isohandle, = ax.plot([],[],'k--',label='$M_\mathrm{iso}$') opthandle, = ax.plot([],[],'k-.',label='$M_\mathrm{opt}$') ax.axvline(r_trans,linewidth=lw2, color='c', linestyle='--') ax.axvline(r_snow,linewidth=lw2, color='m', linestyle='--') ax.text(1.04*r_trans,4,'$\\rm r_{\\rm trans}$', fontsize= fs2,color='c') ax.text(1.04*r_snow,4,'$\\rm r_{\\rm ice}$', fontsize= fs2,color='m') add_date(fig) ax.set_xscale('log') ax.set_yscale('log') ax.set_xlim(0.1,100) ax.set_ylim(1,200) labelLines(lines,fontsize=12,xvals=[1,1]) ax.set_xlabel('$a\ \mathrm{[AU]}$') ax.set_ylabel(r'$M\ \mathrm{[M}_\oplus]$') ax.legend(handles = [gaphandle,isohandle,opthandle],prop={'size':13})<file_sep># -*- coding: utf-8 -*- #!/usr/bin/env python # type I migration torque Paardekooper2011 import matplotlib.pyplot as plt import numpy as np import math import matplotlib from astrounit import * from diskmodel import * from plotset import * import subprocess as sp from plotset import * nint = 1e+2 k1 = 200 k2 = 200 M_s = 1 mdot_gas = 1e-7*M_s**2 L_s = M_s**2 alpha_v = 1e-3 alpha_d = 1e-3 kap = 1e-2 opt_vis = True # calculate the transtion radius for two disk regions r_trans = rtrans(mdot_gas,L_s,M_s,alpha_v,kap,opt_vis) r_snow = rsnow(mdot_gas,L_s,M_s,alpha_v,kap,opt_vis) # calculate temperature q = np.zeros(k2) r = np.zeros(k1) q_gap = np.zeros(k1) Temp_vis = np.zeros(k1) Temp_irr = np.zeros(k1) Temp = np.zeros(k1) Surf = np.zeros(k1) torq = np.zeros((k2,k1)) f = np.zeros((k2,k1)) f_tot = np.zeros((k2,k1)) # get the temerature at two disk regions for j in range(0,k1): r[j] = (j+1.0)/nint # different location r[j] = 10**(np.log10(5e-2) - j*(np.log10(5e-2)-np.log10(50)) /(k1-1)) # different location Temp[j] = Tgas(r[j],mdot_gas,L_s,M_s,alpha_v,kap,opt_vis) Surf[j] = siggas(r[j],mdot_gas,L_s,M_s,alpha_v,kap, opt_vis) for i in range(0,k2): q[i] = 10**(np.log10(3e-8) - i*(np.log10(3e-8)-np.log10(3e-4)) /(k2-1)) # different planetary mass for j in range(0,k1): torq[i][j], f[i][j] = torque(q[i],r[j],mdot_gas,L_s,M_s,alpha_v,alpha_d,kap,opt_vis) r_t = r_trans*np.ones(k2) r_s = r_snow*np.ones(k2) plt.clf() # clear image plt.close('all') # delete figure ################# ### figure 3 #### ################# levels = np.linspace(-4.5,4.5,300) cmap='seismic' fig, [ax1,ax2] = plt.subplots(2,sharex= True, sharey = False, gridspec_kw={'height_ratios':[2.,4]}, figsize=(8,6), num= 3) fig.subplots_adjust(hspace=0.07) yy = np.linspace(0.1,1e+4,len(r_t)) ax1.plot(r,Surf,linewidth=lw1, color='k') ax1.plot(r_t,yy,linewidth=lw2, color='c', linestyle='solid') ax1.plot(r_s,yy,linewidth=lw2, color='m', linestyle='solid') ax1.semilogy() ax1.semilogx() ax1.set_yticks([1,100,1000]) ax1.set_yticklabels(['$1$','$10^{2}$','$10^{3}$'],fontsize=fs1) ax1.set_ylabel('$ \\rm \\Sigma_{g} \\ [gcm^{-2}]$',fontsize=fs1) ax1.set_ylim(0.5,1.e+4) axx = ax1.twiny() axx.semilogx() axx.set_xlim(ax1.get_xlim()) axx.set_xticks([0.1,1,5,10]) axx.set_xticklabels(['$0.1$','$1$','$5$','$10$'],fontsize=fs1) axx.set_xlabel('$\\rm Radius \\ [AU]$',fontsize=fs1) axx.set_xlim(0.1,40) ax11 = ax1.twinx() ax11.set_ylabel('$ \\rm T_{g} \\ [K]$',fontsize=fs1) ax11.set_ylim(11,4e+3) ax11.set_xlim(ax1.get_xlim()) ax11.set_yticks([100,1000]) ax11.set_yticklabels(['$100$','$1000$'],fontsize=fs1,color='b') ax11.spines['right'].set_color('b') ax11.yaxis.label.set_color('b') ax11.semilogy() ax11.semilogx() #[r.set_color('b') for r in ax11.yaxis.get_ticklabels()] ax11.plot(r,Temp,linewidth=lw1, color='b') ax2.plot(r_t,q*M_s,linewidth=lw2, color='c', linestyle='solid') ax2.text(1.04*r_trans,1.8e-5,'$\\rm r_{\\rm trans}$', fontsize= fs2,color='c') ax2.plot(r_s,q*M_s,linewidth=lw2, color='m', linestyle='solid') ax2.text(0.68*r_snow,1.8e-5,'$\\rm r_{\\rm ice}$', fontsize= fs2,color='m') CS=ax2.contourf(r,q*M_s,f,levels,cmap=cmap,alpha=1) CD=ax2.contour(r,q*M_s,f,0,colors=(0.3,0.3,0.3)) #ax2.set_xlabel('$\\rm Radius \\ [AU]$',fontsize=fs1) ax2.set_ylabel('$\\rm Planet \\ mass \\ [M_{\\oplus}$]',fontsize=fs1) ax2.set_ylim(3e-8,3e-4) ax2.semilogy() ax2.semilogx() ax2.set_xlim(0.1,40) ax2.tick_params(axis='x', # changes apply to the x-axis which='both', # both major and minor ticks are affected bottom=False, # ticks along the bottom edge are off labelbottom=False) #ax2.set_xticks([0.2,1,5,10]) #ax2.set_xticklabels(['$0.2$','$1$','$5$','$10$'],fontsize=fs1) ax2.set_yticks([3e-7,9e-7,3e-6,9e-6,3e-5,9e-5]) ax2.set_yticklabels(['$0.1$','$0.3$','$1$','$3$','$10$','$30$'],fontsize=fs1) #fig.colorbar(CS,orientation='horizontal',aspect=40,fraction=0.1, ticks=[-2,0,2],pad=0.7) #fig.colorbar(CS,orientation='vertical',aspect=25,ticks=[-2,0,2],pad=0.1) cbax = fig.add_axes([0.15, 0.04, 0.75, 0.03]) # setup colorbar axes. cb1 = fig.colorbar(CS, cmap=cmap,cax=cbax, norm=levels,ticks=[-4,-2,0,2,4], orientation='horizontal') add_date(fig,xcoord=0.85,ycoord=0.91) fig.savefig('migration_map.pdf',orientation='landscape', format='pdf',bbox_inches='tight', pad_inches=0.01) sp.call(['mv', 'migration_map.pdf', '../figure/']) <file_sep>import matplotlib.pyplot as plt import numpy as np import datetime ##### plot setting for python #### fs0 = 10 fs1 = 13 fs2 = 15 fs3 = 17 lw0 = 0.5 lw1 = 0.8 lw2 = 1.2 lw3 = 2.5 lw4 = 4.2 lw5 = 5 plt.rcParams['font.size']= 16 plt.rcParams['xtick.minor.visible'], plt.rcParams['xtick.top'] = True,True plt.rcParams['ytick.minor.visible'], plt.rcParams['ytick.right'] = True,True plt.rcParams['xtick.direction'], plt.rcParams['ytick.direction'] = 'in','in' plt.rcParams['xtick.labelsize'] = plt.rcParams['ytick.labelsize'] = 14 plt.rcParams['axes.labelsize'] = 18 plt.rcParams['mathtext.fontset'] = 'cm' def discrete_cmap(N, base_cmap=None): """Create an N-bin discrete colormap from the specified input map""" # Note that if base_cmap is a string or None, you can simply do # return plt.cm.get_cmap(base_cmap, N) # The following works for string, None, or a colormap instance: base = plt.cm.get_cmap(base_cmap) color_list = base(np.linspace(0, 1, N)) cmap_name = base.name + str(N) return base.from_list(cmap_name, color_list, N) def add_date(fig,xcoord=0.88,ycoord=0.945): """Adds a box with the current date in the upper right corner of the figure""" date = datetime.datetime.now() datestr = '${0}$-${1}$-${2}$'.format(date.day,date.month,date.year) fig.text(xcoord,ycoord,datestr,bbox=dict(facecolor='None'),fontsize=14)<file_sep>#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jul 8 14:26:51 2019 @author: jooehn """ import numpy as np import matplotlib.pyplot as plt from diskmodel import * from astrounit import * from labellines import labelLines from plotset import * from m6_funcs import safronov_number from mpl_toolkits.axes_grid1 import make_axes_locatable from matplotlib.colors import LogNorm msuntome = Msun/Mearth M_s = 1 mdot_gas = 1e-7*M_s**2 mdot_peb = 4e-4 #earthmasses/yr L_s = M_s**2 alpha_v = 1e-3 alpha_d = 1e-3 kap = 1e-2 G = 4*np.pi**2 opt_vis = True st = 1e-1 r_trans = rtrans(mdot_gas,L_s,M_s,alpha_v,kap,opt_vis) r_snow = rsnow(mdot_gas,L_s,M_s,alpha_v,kap,opt_vis) fig,ax = plt.subplots(figsize=(10,6)) masses = np.linspace(0.1,50,100) avals = np.linspace(0.1,100,100) xx, yy = np.meshgrid(avals,masses) safvals = safronov_number(yy,M_s,xx) levels = np.logspace(np.log10(safvals.min()),1,100) contax = ax.contourf(xx,yy,safvals,levels=levels,cmap='plasma',norm=LogNorm()) cont1 = ax.contour(xx,yy,safvals,levels = [1],colors=['w'],linestyles='--',norm=LogNorm()) divider = make_axes_locatable(ax) cax = divider.append_axes('right', size='5%', pad=0.1) cbar = plt.colorbar(contax,cax=cax) cbar.set_label(r'$\Theta$') cbar.set_ticks([1e-2,1e-1,1e0,1e1]) ax.set_xlabel('$a\ [\mathrm{AU}]$') ax.set_ylabel(r'$M_p\ [M_\oplus]$') ax.set_xscale('log') ax.set_yscale('log') ax.set_xlim(0.1,100) ax.set_ylim(0.1,50) fmt = {} c_label = [r'$\Theta = 1$'] for l, s in zip(cont1.levels, c_label): fmt[l] = s ax.clabel(cont1, cont1.levels, inline=True, fmt=fmt, colors='w', fontsize=12,\ manual=True) ax.axvline(r_trans,linewidth=lw2, color='c', linestyle='--') ax.axvline(r_snow,linewidth=lw2, color='k', linestyle='--') ax.text(1.04*r_trans,.2,'$\\rm r_{\\rm trans}$', fontsize= fs2,color='c') ax.text(1.04*r_snow,.2,'$\\rm r_{\\rm ice}$', fontsize= fs2,color='k') add_date(fig)<file_sep># -*- coding: utf-8 -*- #!/usr/bin/env python # disk model from Gauard&Lin2007, Liu2015 # type I migration torque from Paardekooper2011 import matplotlib.pyplot as plt import numpy as np import math import sys import matplotlib from astrounit import * ### scale functions of disk accretion rate/luminosity and disk radius on the stellar mass ### def mdot_gas_0(mdot_0, M_s): res = mdot_0*(M_s/1.0)**1.8 # [Msun/yr] Hartmann 1998 return res # [Msun/yr] def Lum(M_s): res = (M_s/1.0)**2 # any reference return res # [Lsun] def Rdisk_0(R0, M_s): res = R0*(M_s/1.0)**(0.0) # need to find some reference return res # [AU] # smooth function to combined viscous and irradiation disks def fs(r,r_trans,opt_vis): if opt_vis == True: res = 1./(1. + (r/r_trans)**4) else: res = 0.0 return res # viscous disk: surface density, temperature, scale height def siggas_vis(r,mdot_gas,M_s,alpha,kap): sig_vis0 = 740*(mdot_gas/1e-8)**(1./2)*(M_s/1.0)**(1./8)*(alpha/1e-3)**(-3./4)*(kap/0.01)**(-1./4.) # [g/cm^2] res = sig_vis0*r**-0.375 return res # [g/cm^2] def hgas_vis(r,mdot_gas,M_s,alpha,kap): # hoverr0 = (3./64./pi**2/gamma**0.5*(Rg*gamma/mu)**3*1e-2/sigma*(flux0*Msun/year)**2*(G*Msun)**(-5./2.)*AU**(-0.5)/alpha0)**(1./8.) hgas_vis0 = 4.5e-2*(mdot_gas/1e-8)**(1./4)*(M_s/1.0)**(-5./16)*(alpha/1e-3)**(-1./8)*(kap/0.01)**(1./8) res = hgas_vis0*r**(-1./16) return res def T_vis(r,mdot_gas,M_s,alpha,kap): T_vis0 = 500.*(mdot_gas/1e-8)**(1./2)*(M_s/1.0)**(3./8)*(alpha/1e-3)**(-1./4)*(kap/0.01)**(1./4) res = T_vis0*r**-1.125 return res #[K] # irradition disk: surface density, temperature, scale height def siggas_irr(r,mdot_gas,L_s,M_s,alpha): sig_irr0 = 2500*(mdot_gas/1e-8)*(L_s/1.0)**(-2./7)*(M_s/1.0)**(9./14)*(alpha/1e-3)**(-1) # [g/cm^2] res = sig_irr0*r**(-15./14) #sig_irr0 = 1340*(mdot_gas/1e-8)*(L_s/1.0)**(-1./4)*(M_s/1.0)**(1./2)*(alpha/1e-3)**(-1) # [g/cm^2] #res = sig_irr0*r**(-1) return res # [g/cm^2] def hgas_irr(r,L_s,M_s): hgas_irr0 = 2.45e-2*(L_s/1.0)**(1./7)*(M_s/1.0)**(-4./7) #hgas_irr0 = 2.6e-2*(L_s/1.0)**(1./7)*(M_s/1.0)**(-4./7) #hgas_irr0 = 2.2e-2*(L_s/1.0)**(1./7)*(M_s/1.0)**(-4./7) res = hgas_irr0*r**(2./7) #hgas_irr0 = 3.35e-2*(L_s/1.0)**(1./8)*(M_s/1.0)**(-1./2) #res = hgas_irr0*r**(1./4) return res def T_irr(r,L_s,M_s): T_irr0 = 150.*(L_s/1.0)**(2./7)*(M_s/1.0)**(-1./7) #T_irr0 = 170.*(L_s/1.0)**(2./7)*(M_s/1.0)**(-1./7) #T_irr0 = 125.*(L_s/1.0)**(2./7)*(M_s/1.0)**(-1./7) res = T_irr0*r**(-3./7) #T_irr0 = 280.*(L_s/1.0)**(1./4) #res = T_irr0*r**(-1./2) return res #[K] def rtrans(mdot_gas,L_s,M_s,alpha,kap,opt_vis): if opt_vis == True: res = (500./150.)**(56./39)*(mdot_gas/1e-8)**(28./39)*(M_s/1.0)**(29./39)*(alpha/1e-3)**(-14./39)*(L_s/1.0)**(-16./39)*(kap/0.01)**(14./39) # transit location # res = (500./170.)**(56./39)*(mdot_gas/1e-8)**(28./39)*(M_s/1.0)**(29./39)*(alpha/1e-3)**(-14./39)*(L_s/1.0)**(-16./39)*(kap/0.01)**(14./39) # transit location #res = (500./125.)**(56./39)*(mdot_gas/1e-8)**(28./39)*(M_s/1.0)**(29./39)*(alpha/1e-3)**(-14./39)*(L_s/1.0)**(-16./39)*(kap/0.01)**(14./39) # transit location #res = (500./280.)**(8./5)*(mdot_gas/1e-8)**(4./5)*(M_s/1.0)**(3./5)*(alpha/1e-3)**(-2./5)*(L_s/1.0)**(-2./5)*(kap/0.01)**(2./5) # transit location else: res = 0.0 return res #[AU] def rsnow(mdot_gas,L_s,M_s,alpha,kap,opt_vis): rsnow_vis = (50./17)**(8./9)*(mdot_gas/1e-8)**(4./9)*(M_s/1.0)**(1./3)*(alpha/1e-3)**(-2./9)*(kap/0.01)**(2./9) rsnow_irr = (15./17)**(7./3)*(M_s/1.0)**(-1./3)*(L_s/1.0)**(2./3) if opt_vis == True: res = max(rsnow_vis,rsnow_irr) else: res = rsnow_irr return res #[AU] # surface density def siggas(r,mdot_gas,L_s,M_s,alpha,kap, opt_vis): r_trans = rtrans(mdot_gas,L_s,M_s,alpha,kap,opt_vis) fsmooth = fs(r,r_trans,opt_vis) if opt_vis == True: res = fsmooth*siggas_vis(r,mdot_gas,M_s,alpha,kap) + (1-fsmooth)*siggas_irr(r,mdot_gas,L_s,M_s,alpha) else: res = siggas_irr(r,mdot_gas,L_s,M_s,alpha) return res # [g/cm^2] # apsect ratio def hgas(r,mdot_gas,L_s,M_s,alpha,kap,opt_vis): r_trans = rtrans(mdot_gas,L_s,M_s,alpha,kap,opt_vis) fsmooth = fs(r,r_trans,opt_vis) if opt_vis == True: res = fsmooth*hgas_vis(r,mdot_gas,M_s,alpha,kap) + (1-fsmooth)*hgas_irr(r,L_s,M_s) else: res = hgas_irr(r,L_s,M_s) return res # headwind pressure prefactor: from Bitsch2018 Eq(9) [some errors] def eta_gas(r,mdot_gas,L_s,M_s,alpha,kap,opt_vis): r_trans = rtrans(mdot_gas,L_s,M_s,alpha,kap,opt_vis) #eta_irr = -0.5*hgas_irr(1,L_s,M_s)**2*r**(2*2./7)*(2*2./7-15./14-2) #eta_vis = -0.5*hgas_vis(1,mdot_gas,M_s,alpha,kap)**2*r**(-2*.1/16)*(-2*1./16-3./8-2) eta_irr = 0.5*hgas_irr(r,L_s,M_s)**2*(-2./7+15./14+2) eta_vis = 0.5*hgas_vis(r,mdot_gas,M_s,alpha,kap)**2*(1./16+3./8+2) if opt_vis == True: fsmooth = fs(r,r_trans,opt_vis) res = fsmooth*eta_vis + (1-fsmooth)*eta_irr else: res = eta_irr return res # temperature def Tgas(r,mdot_gas,L_s,M_s,alpha,kap,opt_vis): r_trans = rtrans(mdot_gas,L_s,M_s,alpha,kap,opt_vis) if opt_vis == True: fsmooth = fs(r,r_trans,opt_vis) res = fsmooth*T_vis(r,mdot_gas,M_s,alpha,kap) + (1-fsmooth)*T_irr(r,L_s,M_s) else: res = T_irr(r,L_s,M_s) return res #[K] # saturation pressure for water def Psat(T): ## cgs unit from Lichtenegger1991 #A = 1.14e+13 #B = 6062 ## SI unit from ? A = 6.034e+11 B = 5938.0 res = A*np.exp(-B/T) return res # water vapor pressure def P_vapor(r,mdot_gas,L_s,M_s,alpha,kap, opt_vis,ceta): # in cgs unit ## ''' T = Tgas(r,mdot_gas,L_s,M_s,alpha,kap,opt_vis) sig = siggas(r,mdot_gas,L_s,M_s,alpha,kap, opt_vis) h = hgas(r,mdot_gas,L_s,M_s,alpha,kap,opt_vis) rhogas = sig/((2*np.pi)**0.5*h*(r*AU)) Z_H2O = 1e-2 # metallicity of water N_a = 6.022e+23 # avogadro constant [mol^-1] m_H2O = 18. # mass of water per mol [g/mol^{-1}] m_H2O = m_H2O/N_a # mean molecule weight of water [g] kB = 1.38e-16 # Boltzmann constant [ergK^-1] rho_vapor = rhogas*Z_H2O/m_H2O res = rho_vapor*kB*T ''' T = Tgas(r,mdot_gas,L_s,M_s,alpha,kap,opt_vis) sig = 10*siggas(r,mdot_gas,L_s,M_s,alpha,kap, opt_vis) # in SI unit h = hgas(r,mdot_gas,L_s,M_s,alpha,kap,opt_vis) rhogas = sig/((2*np.pi)**0.5*h*(r*AU/100.)) # AU/100 is in SI unit #Z_H2O = 1e-2 # metallicity of water Z_H2O = ceta # metallicity of water N_a = 6.022e+23 # avogadro constant [mol^-1] m_H2O = 1.8e-2 # mass of water per mol [kg/mol^{-1}] m_H2O = m_H2O/N_a # mean molecule weight of water [kg] kB = 1.38e-23 # Boltzmann constant [JK^-1] rho_vapor = rhogas*Z_H2O/m_H2O res = rho_vapor*kB*T return res def rsnow_new(r,mdot_gas,L_s,M_s,alpha,kap, opt_vis,ceta): T = Tgas(r,mdot_gas,L_s,M_s,alpha,kap,opt_vis) P1 = Psat(T) P2 = P_vapor(r,mdot_gas,L_s,M_s,alpha,kap, opt_vis,ceta) nlist = np.argmin( abs(P1/P2-1)) # when these two equals res = r[nlist] return res #[AU] # migration torque from Paardekooper2011 def torque(q,r,mdot_gas,L_s,M_s,alpha_v,alpha_d,kap,opt_vis): r_trans = rtrans(mdot_gas,L_s,M_s,alpha_v,kap,opt_vis) p = 2./3.*q**0.75/((2.0*np.pi*alpha_d)**0.5*hgas(r,mdot_gas,L_s,M_s,alpha_v,kap,opt_vis)**1.75) pp = p/(8.0/(45.0*np.pi))**0.5 ppp = p/(28.0/(45.0*np.pi))**0.5 fp = 1./(1. + (p/1.3)**2) pps = 1./(1. + pp**4) gpp = pps*(16.*pp**1.5/25.) + (1. - pps)*(1.-9.*pp**(-2.67)/25.) ppps = 1./(1. + ppp**4) akppp = ppps*(16.*ppp**1.5/25.) + (1. - ppps)*(1.-9.*ppp**(-2.67)/25.) # ftot # factors of each torques in viscous region: -0.375, -1.125 flb_vis = -4.375 fhb_vis = 1.2375 fhe_vis = 5.5018 fcb_vis = 0.7875 fce_vis = 1.17 # factors of each torques in irr region: -3/7, -15/14 flb_irr = -3.08 fhb_irr = 0.47 fhe_irr = 0 fcb_irr = 0.3 fce_irr = 0.0 ftot_vis = flb_vis + (fhb_vis + fhe_vis*fp)*fp*gpp + (1 - akppp)*(fcb_vis + fce_vis) ftot_irr = flb_irr + (fhb_irr + fhe_irr*fp)*fp*gpp + (1 - akppp)*(fcb_irr + fce_irr) # get torque factor = (r*AU)*(G*M_s*Msun)*(q/hgas(r,mdot_gas,L_s,M_s,alpha_v,kap,opt_vis))**2 torq_vis = ftot_vis*factor*siggas_vis(r,mdot_gas,M_s,alpha_v,kap) torq_irr = ftot_irr*factor*siggas_irr(r,mdot_gas,L_s,M_s,alpha_v) if opt_vis == True: fsmooth = fs(r,r_trans,opt_vis) torq = torq_vis*fsmooth + torq_irr*(1-fsmooth) # [cm g s] unit else: torq = torq_irr # [cm g s] unit # here choose only inward migration torque torque #torq = ftot_irr*factor*siggas(r,mdot_gas,L_s,M_s,alpha_v,kap, opt_vis) f = torq/factor/siggas(r,mdot_gas,L_s,M_s,alpha_v,kap,opt_vis) # normalized torque return torq, f def tmig_1(mp,a,mdot_gas,L_s,M_s,alpha_v,kap,opt_vis=True): """Computes the type I migration time for a given planetary mass at a given semi-major axis. mp: mass given in earth masses a : semi-major axis in AU mdot_gas: the gas accretion rate L_s: stellar luminosity M_s: stellar mass alpha_v: viscous alpha kap: disk opacity coefficient opt_vis: boolean statement for the inclusion of a modulation factor""" sigma_g = siggas(a,mdot_gas,L_s,M_s,alpha_v,kap,opt_vis)*(AU**2/Msun) hg = hgas(a,mdot_gas,L_s,M_s,alpha_v,kap,opt_vis) t = (M_s/(mp/msuntome))*(M_s/(sigma_g*a**2))*hg**2*(a**3/(4*np.pi**2*M_s))**(0.5) return t #[yr] def tpeb(mp,a,mdot_gas,mdot_peb,L_s,M_s,alpha_d,alpha_v,kap,st,opt_vis=True): """Computes the pebble accretion time for a given planetary mass at a given semi-major axis. If the planets satisfies Racc>Hpeb we have 2D accretion while we have 3D if Racc<Hpeb. mp: mass given in earth masses a : semi-major axis in AU mdot_gas: the gas accretion rate mdot_peb: the pebble accretion rate L_s: stellar luminosity M_s: stellar mass alpha_v: viscous alpha kap: disk opacity coefficient st: stokes number of the pebbles in the disk opt_vis: boolean statement for the inclusion of a modulation factor""" hg = hgas(a,mdot_gas,L_s,M_s,alpha_v,kap,opt_vis) hpeb = np.sqrt(alpha_d/(alpha_d+st))*hg Mp = mp/msuntome Rh = a*(Mp/(3*M_s))**(1/3) Racc = Rh*st**(1/3) acc_2d = Racc>hpeb*a acc_3d = Racc<hpeb*a #We compute the pebble accretion efficiency eta = eta_gas(a,mdot_gas,L_s,M_s,alpha_v,kap,opt_vis) eps_2d = 3e-3*(mp/1e-2)**(2/3)*(st/1e-2)**(-1/3)*(eta[acc_2d]/3e-3)**(-1) eps_3d = 4e-3*(mp/1e-2)*M_s**(-1)*(hpeb[acc_3d]/3e-3)**(-1)*(eta[acc_3d]/3e-3)**(-1) t = np.zeros(len(a)) t[acc_2d] = mp/(eps_2d*mdot_peb) t[acc_3d] = mp/(eps_3d*mdot_peb) return t#[yr] def tpeb_alt(mp,a,mdot_gas,mdot_peb,L_s,M_s,alpha_d,alpha_v,kap,st,opt_vis=True): """Computes the pebble accretion time for a given planetary mass at a given semi-major axis. If the planets satisfies Racc>Hpeb we have 2D accretion while we have 3D if Racc<Hpeb. mp: mass given in earth masses a : semi-major axis in AU mdot_gas: the gas accretion rate mdot_peb: the pebble accretion rate L_s: stellar luminosity M_s: stellar mass alpha_v: viscous alpha kap: disk opacity coefficient st: stokes number of the pebbles in the disk opt_vis: boolean statement for the inclusion of a modulation factor""" hg = hgas(a,mdot_gas,L_s,M_s,alpha_v,kap,True) hpeb = np.sqrt(alpha_v/(alpha_v+st))*hg Mp = mp/msuntome Rh = a*(Mp/(3*M_s))**(1/3) Racc = Rh*st**(1/3) acc_2d = Racc>hpeb*a acc_3d = Racc<hpeb*a #We compute the pebble accretion efficiency eta = eta_gas(a,mdot_gas,L_s,M_s,alpha_v,kap,opt_vis) # fset = np.exp(-0.07*(eta/2.5e-3)**2*(mp/0.01)**(-2/3)*(st/0.1)**(2/3))s t = np.zeros(len(a)) t[acc_2d] = 9e-4*(mp/0.05)**(1/3)*(st/0.1)**(1/3)*(eta[acc_2d]/2.5e-3)*(mdot_peb/100)**(-1) t[acc_3d] = 9e-4*(hpeb[acc_3d]/4.2e-3)*(eta[acc_3d]/2.5e-3)*(mdot_peb/100)**(-1) return t#[yr] def gap_mass(a,mdot_gas,L_s,M_s,alpha_d,alpha_v,kap,opt_vis): """Computes the gap opening mass for a given radius in a PPD and returns it in units of Earth masses.""" h_g = hgas(a,mdot_gas,L_s,M_s,alpha_v,kap,opt_vis) M_gap = 30*(alpha_d/1e-3)**(0.5)*(h_g/0.05)**(2.5)*M_s return M_gap def iso_mass(a,mdot_gas,L_s,M_s,alpha_d,alpha_v,kap,opt_vis): """Computes the isolation mass for a given radius in a PPD and returns it in units of Earth masses.""" M_iso = gap_mass(a,mdot_gas,L_s,M_s,alpha_d,alpha_v,kap,opt_vis)/2.3 return M_iso def opt_mass(a,mdot_gas,L_s,M_s,alpha_d,alpha_v,kap,opt_vis): """Computes the optimal mass for outward migration at a given radius in a PPD and returns it in units of Earth masses.""" h_g = hgas(a,mdot_gas,L_s,M_s,alpha_v,kap,opt_vis) M_opt = 5*(alpha_d/1e-3)**(2/3)*(h_g/0.05)**(7/3)*M_s return M_opt<file_sep>!****************************************************************************** ! MODULE: dynamic !****************************************************************************** ! ! DESCRIPTION: !> @brief Modules that compute various dynamic behaviour such as !! collision, close encounter, close approach to central body ! !****************************************************************************** module dynamic use types_numeriques use utilities use mercury_globals implicit none contains !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% !> @author !> <NAME> ! !> @date 4 March 2001 ! ! DESCRIPTION: !> @brief Checks all objects with index I >= I0, to see if they have had a collision !! with the central body in a time interval H, when given the initial and !! final coordinates and velocities. The routine uses cubic interpolation !! to estimate the minimum separations. ! !> @attention All coordinates & velocities must be with respect to the central body! !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% subroutine mce_cent (time,h,rcen,jcen,start_index,nbod,nbig,m,x0,v0,x1,v1,nhit,jhit,thit,dhit,ngf,ngflag) use physical_constant use mercury_constant implicit none ! Input integer, intent(in) :: start_index integer, intent(in) :: nbod !< [in] current number of bodies (1: star; 2-nbig: big bodies; nbig+1-nbod: small bodies) integer, intent(in) :: nbig !< [in] current number of big bodies (ones that perturb everything else) integer, intent(in) :: ngflag !< [in] do any bodies experience non-grav. forces? !!\n ( 0 = no non-grav forces) !!\n 1 = cometary jets only !!\n 2 = radiation pressure/P-R drag only !!\n 3 = both real(double_precision), intent(in) :: time !< [in] current epoch (days) real(double_precision), intent(in) :: h !< [in] current integration timestep (days) real(double_precision), intent(in) :: rcen !< [in] radius of central body (AU) real(double_precision), intent(in) :: jcen(3) !< [in] J2,J4,J6 for central body (units of RCEN^i for Ji) real(double_precision), intent(in) :: m(nbod) !< [in] mass (in solar masses * K2) real(double_precision), intent(in) :: x0(3,nbod) real(double_precision), intent(in) :: v0(3,nbod) real(double_precision), intent(in) :: x1(3,nbod) real(double_precision), intent(in) :: v1(3,nbod) real(double_precision), intent(in) :: ngf(4,nbod) !< [in] non gravitational forces parameters !! \n(1-3) cometary non-gravitational (jet) force parameters !! \n(4) beta parameter for radiation pressure and P-R drag ! Output integer, intent(out) :: nhit integer, intent(out) :: jhit(CMAX) real(double_precision), intent(out) :: thit(CMAX) real(double_precision), intent(out) :: dhit(CMAX) ! Local integer :: i0 !< starting index for checking close encounters, mainly equal to start_index integer :: j real(double_precision) :: rcen2,a,q,u0,uhit,m0,mhit,mm,r0,mcen real(double_precision) :: hx,hy,hz,h2,p,rr0,rr1,rv0,rv1,temp,e,v2 real(double_precision) :: xu0(3,nb_bodies_initial),xu1(3,nb_bodies_initial),vu0(3,nb_bodies_initial),vu1(3,nb_bodies_initial) !------------------------------------------------------------------------------ if (start_index.le.0) then i0 = 2 else i0 = start_index endif nhit = 0 rcen2 = rcen * rcen mcen = m(1) ! If using close-binary code, convert to coords with respect to the binary ! if (algor.eq.11) then ! mcen = m(1) + m(2) ! call mco_h2ub (temp,jcen,nbod,nbig,h,m,x0,v0,xu0,vu0,ngf,ngflag) ! call mco_h2ub (temp,jcen,nbod,nbig,h,m,x1,v1,xu1,vu1,ngf,ngflag) ! end if ! Check for collisions with the central body do j = i0, nbod if (algor.eq.11) then rr0 = xu0(1,j)*xu0(1,j) + xu0(2,j)*xu0(2,j) +xu0(3,j)*xu0(3,j) rr1 = xu1(1,j)*xu1(1,j) + xu1(2,j)*xu1(2,j) +xu1(3,j)*xu1(3,j) rv0 = vu0(1,j)*xu0(1,j) + vu0(2,j)*xu0(2,j) +vu0(3,j)*xu0(3,j) rv1 = vu1(1,j)*xu1(1,j) + vu1(2,j)*xu1(2,j) +vu1(3,j)*xu1(3,j) else rr0 = x0(1,j)*x0(1,j) + x0(2,j)*x0(2,j) + x0(3,j)*x0(3,j) rr1 = x1(1,j)*x1(1,j) + x1(2,j)*x1(2,j) + x1(3,j)*x1(3,j) rv0 = v0(1,j)*x0(1,j) + v0(2,j)*x0(2,j) + v0(3,j)*x0(3,j) rv1 = v1(1,j)*x1(1,j) + v1(2,j)*x1(2,j) + v1(3,j)*x1(3,j) end if ! If inside the central body, or passing through pericentre, use 2-body approx. if ((rv0*h.le.0.and.rv1*h.ge.0).or.min(rr0,rr1).le.rcen2) then if (algor.eq.11) then hx = xu0(2,j) * vu0(3,j) - xu0(3,j) * vu0(2,j) hy = xu0(3,j) * vu0(1,j) - xu0(1,j) * vu0(3,j) hz = xu0(1,j) * vu0(2,j) - xu0(2,j) * vu0(1,j) v2 = vu0(1,j)*vu0(1,j) +vu0(2,j)*vu0(2,j) +vu0(3,j)*vu0(3,j) else hx = x0(2,j) * v0(3,j) - x0(3,j) * v0(2,j) hy = x0(3,j) * v0(1,j) - x0(1,j) * v0(3,j) hz = x0(1,j) * v0(2,j) - x0(2,j) * v0(1,j) v2 = v0(1,j)*v0(1,j) + v0(2,j)*v0(2,j) + v0(3,j)*v0(3,j) end if h2 = hx*hx + hy*hy + hz*hz p = h2 / (mcen + m(j)) r0 = sqrt(rr0) temp = 1.d0 + p*(v2/(mcen + m(j)) - 2.d0/r0) e = sqrt( max(temp,0.d0) ) q = p / (1.d0 + e) ! If the object hit the central body if (q.le.rcen) then nhit = nhit + 1 jhit(nhit) = j dhit(nhit) = rcen ! Time of impact relative to the end of the timestep if (e.lt.1) then a = q / (1.d0 - e) uhit = sign (acos((1.d0 - rcen/a)/e), -h) u0 = sign (acos((1.d0 - r0/a )/e), rv0) mhit = mod (uhit - e*sin(uhit) + PI, TWOPI) - PI m0 = mod (u0 - e*sin(u0) + PI, TWOPI) - PI else a = q / (e - 1.d0) uhit = sign (arcosh((1.d0 - rcen/a)/e), -h) u0 = sign (arcosh((1.d0 - r0/a )/e), rv0) mhit = mod (uhit - e*sinh(uhit) + PI, TWOPI) - PI m0 = mod (u0 - e*sinh(u0) + PI, TWOPI) - PI end if mm = sqrt((mcen + m(j)) / (a*a*a)) thit(nhit) = (mhit - m0) / mm + time end if end if end do !------------------------------------------------------------------------------ return end subroutine mce_cent !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% !> @author !> <NAME> ! !> @date 2 October 2000 ! ! DESCRIPTION: !> @brief Resolves a collision between two objects, using the collision model chosen !! by the user. Also writes a message to the information file, and updates the !! value of ELOST, the change in energy due to collisions and ejections. ! !> @note All coordinates and velocities must be with respect to central body. ! !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% subroutine mce_coll (time,elost,jcen,planet_id_1,planet_id_2,nbod,nbig,m,xh,vh,s,rphys,stat,id,outfile,m_x,rho) use physical_constant use mercury_constant implicit none ! Input/Output integer, intent(in) :: planet_id_1 integer, intent(in) :: planet_id_2 integer, intent(in) :: nbod !< [in] current number of bodies (1: star; 2-nbig: big bodies; nbig+1-nbod: small bodies) integer, intent(in) :: nbig !< [in] current number of big bodies (ones that perturb everything else) integer, intent(inout) :: stat(nbod) !< [in,out] status (0 => alive, <>0 => to be removed) real(double_precision), intent(in) :: time !< [in] current epoch (days) real(double_precision), intent(in) :: jcen(3) !< [in] J2,J4,J6 for central body (units of RCEN^i for Ji) real(double_precision), intent(inout) :: m(nbod) !< [in,out] mass (in solar masses * K2) real(double_precision), intent(inout) :: m_x(nbod) !< [in,out] mass of element X (in solar masses * K2) real(double_precision), intent(inout) :: rho(nbod) !< [in,out] density real(double_precision), intent(inout) :: xh(3,nbod) !< [in,out] coordinates (x,y,z) with respect to the central body (AU) real(double_precision), intent(inout) :: vh(3,nbod) !< [in,out] velocities (vx,vy,vz) with respect to the central body (AU/day) real(double_precision), intent(inout) :: s(3,nbod) !< [in,out] spin angular momentum (solar masses AU^2/day) real(double_precision), intent(in) :: rphys(nbod) character(len=80), intent(in) :: outfile character(len=8), intent(in) :: id(nbod) !< [in] name of the object (8 characters) real(double_precision), intent(inout) :: elost ! Local integer :: i integer :: j integer :: year,month,itmp, error real(double_precision) :: t1 character(len=38) :: flost,fcol character(len=6) :: tstring !------------------------------------------------------------------------------ ! If two bodies collided, check that the less massive one is removed ! (unless the more massive one is a Small body) if (planet_id_1.ne.0) then if (m(planet_id_2).gt.m(planet_id_1).and.planet_id_2.le.nbig) then i = planet_id_2 j = planet_id_1 else i = planet_id_1 j = planet_id_2 end if end if ! Write message to info file (I=0 implies collision with the central body) open (23, file=outfile, status='old', position='append', iostat=error) if (error /= 0) then write (*,'(/,2a)') " ERROR: Programme terminated. Unable to open ",trim(outfile) stop end if if (opt(3).eq.1) then call mio_jd2y (time,year,month,t1) if (i.eq.0) then flost = '(1x,a8,a,i10,1x,i2,1x,f8.5)' write (23,flost) id(j),mem(67)(1:lmem(67)),year,month,t1 else fcol = '(1x,a8,a,a8,a,i10,1x,i2,1x,f4.1)' write (23,fcol) id(i),mem(69)(1:lmem(69)),id(j),mem(71)(1:lmem(71)),year,month,t1 end if else if (opt(3).eq.3) then t1 = (time - tstart) / 365.25d0 tstring = mem(2) flost = '(1x,a8,a,f18.7,a)' fcol = '(1x,a8,a,a8,a,1x,f14.3,a)' else if (opt(3).eq.0) t1 = time if (opt(3).eq.2) t1 = time - tstart tstring = mem(1) flost = '(1x,a8,a,f18.5,a)' fcol = '(1x,a8,a,a8,a,1x,f14.1,a)' end if if (i.eq.0.or.i.eq.1) then write (23,flost) id(j),mem(67)(1:lmem(67)),t1,tstring else write (23,fcol) id(i),mem(69)(1:lmem(69)),id(j),mem(71)(1:lmem(71)),t1,tstring end if end if close (23) ! Do the collision (inelastic merger) call mce_merg (jcen,i,j,nbod,nbig,m,xh,vh,s,stat,elost,m_x,rho) !------------------------------------------------------------------------------ return end subroutine mce_coll !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% !> @author !> <NAME> ! !> @date 2 October 2000 ! ! DESCRIPTION: !> @brief Merges objects I and J inelastically to produce a single new body by !! conserving mass and linear momentum. !! If J <= NBIG, then J is a Big body !! If J > NBIG, then J is a Small body !! If I = 0, then I is the central body ! !> @note All coordinates and velocities must be with respect to central body. ! !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% subroutine mce_merg (jcen,i,j,nbod,nbig,m,xh,vh,s,stat,elost,m_x,rho) use physical_constant use mercury_constant use system_properties implicit none ! Input integer, intent(in) :: i integer, intent(in) :: j integer, intent(in) :: nbod !< [in] current number of bodies (1: star; 2-nbig: big bodies; nbig+1-nbod: small bodies) integer, intent(in) :: nbig !< [in] current number of big bodies (ones that perturb everything else) real(double_precision), intent(in) :: jcen(3) !< [in] J2,J4,J6 for central body (units of RCEN^i for Ji) ! Output integer, intent(inout) :: stat(nbod) !< [in,out] status (0 => alive, <>0 => to be removed) real(double_precision), intent(inout) :: m(nbod) !< [in,out] mass (in solar masses * K2) real(double_precision), intent(inout) :: m_x(nbod) !< [in,out] mass of element X (in solar masses * K2) real(double_precision), intent(inout) :: rho(nbod) !< [in,out] density real(double_precision), intent(inout) :: xh(3,nbod) !< [in,out] coordinates (x,y,z) with respect to the central body (AU) real(double_precision), intent(inout) :: vh(3,nbod) !< [in,out] velocities (vx,vy,vz) with respect to the central body (AU/day) real(double_precision), intent(inout) :: s(3,nbod) !< [in,out] spin angular momentum (solar masses AU^2/day) real(double_precision), intent(inout) :: elost ! Local integer :: k real(double_precision) :: tmp1, tmp2, dx, dy, dz, du, dv, dw, msum, mredu, msum_1, msum_x, volsum real(double_precision) :: e0, e1, l2 !------------------------------------------------------------------------------ ! If a body hits the central body if (i.le.1) then call mxx_en (jcen,nbod,nbig,m,xh,vh,s,e0,l2) ! If a body hit the central body... msum = m(1) + m(j) msum_1 = 1.d0 / msum mredu = m(1) * m(j) * msum_1 dx = xh(1,j) dy = xh(2,j) dz = xh(3,j) du = vh(1,j) dv = vh(2,j) dw = vh(3,j) ! Calculate new spin angular momentum of the central body s(1,1) = s(1,1) + s(1,j) + mredu * (dy * dw - dz * dv) s(2,1) = s(2,1) + s(2,j) + mredu * (dz * du - dx * dw) s(3,1) = s(3,1) + s(3,j) + mredu * (dx * dv - dy * du) ! Calculate shift in barycentric coords and velocities of central body tmp2 = m(j) * msum_1 xh(1,1) = tmp2 * xh(1,j) xh(2,1) = tmp2 * xh(2,j) xh(3,1) = tmp2 * xh(3,j) vh(1,1) = tmp2 * vh(1,j) vh(2,1) = tmp2 * vh(2,j) vh(3,1) = tmp2 * vh(3,j) m(1) = msum m(j) = 0.d0 s(1,j) = 0.d0 s(2,j) = 0.d0 s(3,j) = 0.d0 ! Shift the heliocentric coordinates and velocities of all bodies do k = 2, nbod xh(1,k) = xh(1,k) - xh(1,1) xh(2,k) = xh(2,k) - xh(2,1) xh(3,k) = xh(3,k) - xh(3,1) vh(1,k) = vh(1,k) - vh(1,1) vh(2,k) = vh(2,k) - vh(2,1) vh(3,k) = vh(3,k) - vh(3,1) end do ! Calculate energy loss due to the collision call mxx_en (jcen,nbod,nbig,m,xh,vh,s,e1,l2) elost = elost + (e0 - e1) else ! If two bodies collided... msum = m(i) + m(j) msum_x = m_x(i) + m_x(j) ! calculate the total volume volsum = m(i)/rho(i) + m(j)/rho(j) msum_1 = 1.d0 / msum mredu = m(i) * m(j) * msum_1 dx = xh(1,i) - xh(1,j) dy = xh(2,i) - xh(2,j) dz = xh(3,i) - xh(3,j) du = vh(1,i) - vh(1,j) dv = vh(2,i) - vh(2,j) dw = vh(3,i) - vh(3,j) ! Calculate energy loss due to the collision elost = elost + .5d0 * mredu * (du*du + dv*dv + dw*dw) - m(i) * m(j) / sqrt(dx*dx + dy*dy + dz*dz) ! Calculate spin angular momentum of the new body s(1,i) = s(1,i) + s(1,j) + mredu * (dy * dw - dz * dv) s(2,i) = s(2,i) + s(2,j) + mredu * (dz * du - dx * dw) s(3,i) = s(3,i) + s(3,j) + mredu * (dx * dv - dy * du) ! Calculate new coords and velocities by conserving centre of mass & momentum tmp1 = m(i) * msum_1 tmp2 = m(j) * msum_1 xh(1,i) = xh(1,i) * tmp1 + xh(1,j) * tmp2 xh(2,i) = xh(2,i) * tmp1 + xh(2,j) * tmp2 xh(3,i) = xh(3,i) * tmp1 + xh(3,j) * tmp2 vh(1,i) = vh(1,i) * tmp1 + vh(1,j) * tmp2 vh(2,i) = vh(2,i) * tmp1 + vh(2,j) * tmp2 vh(3,i) = vh(3,i) * tmp1 + vh(3,j) * tmp2 m(i) = msum m_x(i) = msum_x ! calculate the density change rho(i) = m(i)/volsum end if ! Flag the lost body for removal, and move it away from the new body stat(j) = -2 xh(1,j) = -xh(1,j) xh(2,j) = -xh(2,j) xh(3,j) = -xh(3,j) vh(1,j) = -vh(1,j) vh(2,j) = -vh(2,j) vh(3,j) = -vh(3,j) m(j) = 0.d0 m_x(j) = 0.d0 rho(j) = 0.d0 s(1,j) = 0.d0 s(2,j) = 0.d0 s(3,j) = 0.d0 !------------------------------------------------------------------------------ return end subroutine mce_merg !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% !> @author !> <NAME> ! !> @date 13 February 2001 ! ! DESCRIPTION: !> @brief Removes any objects with STAT < 0 (i.e. those that have been flagged for !! removal) and reindexes all the appropriate arrays for the remaining objects. ! !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% subroutine mxx_elim (nbod,nbig,m,x,v,s,rho,rceh,rcrit,ngf,stat,id,outfile,nelim, m_x) use physical_constant use mercury_constant implicit none ! Input real(double_precision), intent(in) :: rcrit(nbod) character(len=80), intent(in) :: outfile ! Input/Output integer, intent(inout) :: nbod !< [in,out] current number of bodies (INCLUDING the central object) integer, intent(inout) :: nbig !< [in,out] current number of big bodies (ones that perturb everything else) integer, intent(inout) :: nelim integer, intent(inout) :: stat(nbod) !< [in,out] status (0 => alive, <>0 => to be removed) real(double_precision), intent(inout) :: m(nbod) !< [in,out] mass (in solar masses * K2) real(double_precision), intent(inout) :: m_x(nbod) !< [in,out] mass of element X (in solar masses * K2) real(double_precision), intent(inout) :: x(3,nbod) real(double_precision), intent(inout) :: v(3,nbod) real(double_precision), intent(inout) :: s(3,nbod) !< [in,out] spin angular momentum (solar masses AU^2/day) real(double_precision), intent(inout) :: rho(nbod) !< [in,out] physical density (g/cm^3) real(double_precision), intent(inout) :: rceh(nbod) !< [in,out] close-encounter limit (Hill radii) real(double_precision), intent(inout) :: ngf(4,nbod) !< [in,out] non gravitational forces parameters !! \n(1-3) cometary non-gravitational (jet) force parameters !! \n(4) beta parameter for radiation pressure and P-R drag character(len=8), intent(inout) :: id(nbod) !< [in,out] name of the object (8 characters) ! Local integer :: j, k, l, nbigelim, elim(nb_bodies_initial+1) integer :: error !------------------------------------------------------------------------------ ! Find out how many objects are to be removed nelim = 0 nbigelim = 0 do j = 2, nbod if (stat(j).lt.0) then nelim = nelim + 1 elim(nelim) = j if (j.le.nbig) nbigelim = nbigelim + 1 end if end do elim(nelim+1) = nbod + 1 ! Eliminate unwanted objects do k = 1, nelim do j = elim(k) - k + 1, elim(k+1) - k - 1 l = j + k x(1,j) = x(1,l) x(2,j) = x(2,l) x(3,j) = x(3,l) v(1,j) = v(1,l) v(2,j) = v(2,l) v(3,j) = v(3,l) m(j) = m(l) m_x(j) = m_x(l) s(1,j) = s(1,l) s(2,j) = s(2,l) s(3,j) = s(3,l) rho(j) = rho(l) rceh(j) = rceh(l) stat(j) = stat(l) id(j) = id(l) ngf(1,j) = ngf(1,l) ngf(2,j) = ngf(2,l) ngf(3,j) = ngf(3,l) ngf(4,j) = ngf(4,l) end do end do ! Update total number of bodies and number of Big bodies nbod = nbod - nelim nbig = nbig - nbigelim ! If no massive bodies remain, stop the integration if (nbig.lt.1) then open (23,file=outfile,status='old',position='append',iostat=error) if (error /= 0) then write (*,'(/,2a)') " ERROR: Programme terminated. Unable to open ",trim(outfile) stop end if write (23,'(2a)') mem(81)(1:lmem(81)),mem(124)(1:lmem(124)) close (23) stop end if !------------------------------------------------------------------------------ return end subroutine mxx_elim !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% !> @author !> <NAME> ! !> @date 3 October 2000 ! ! DESCRIPTION: !> @brief Given initial and final coordinates and velocities X and V, and a timestep !! H, the routine estimates which objects were involved in a close encounter !! during the timestep. The routine examines all objects with indices I >= I0. !! !! Returns an array CE, which for each object is: !! 0 if it will undergo no encounters !! 2 if it will pass within RCRIT of a Big body !! !! Also returns arrays ICE and JCE, containing the indices of each pair of !! objects estimated to have undergone an encounter. !! !> @note All coordinates must be with respect to the central body!!! ! !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% subroutine mce_snif (h,start_index,nbod,nbig,x0,v0,x1,v1,rcrit,ce,nce,ice,jce) use physical_constant use mercury_constant implicit none ! Input integer, intent(in) :: start_index integer, intent(in) :: nbod !< [in] current number of bodies (1: star; 2-nbig: big bodies; nbig+1-nbod: small bodies) integer, intent(in) :: nbig !< [in] current number of big bodies (ones that perturb everything else) real(double_precision), intent(in) :: x0(3,nbod) real(double_precision), intent(in) :: v0(3,nbod) real(double_precision), intent(in) :: x1(3,nbod) real(double_precision), intent(in) :: v1(3,nbod) real(double_precision), intent(in) :: h !< [in] current integration timestep (days) real(double_precision), intent(in) :: rcrit(nbod) ! Output integer, intent(out) :: ce(nbod) !< [out] close encounter status integer, intent(out) :: nce integer, intent(out) :: ice(CMAX) integer, intent(out) :: jce(CMAX) ! Local integer :: i0 !< starting index for checking close encounters, mainly equal to start_index integer :: i,j real(double_precision) :: d0,d1,d0t,d1t,d2min,temp,tmin,rc,rc2 real(double_precision) :: dx0,dy0,dz0,du0,dv0,dw0,dx1,dy1,dz1,du1,dv1,dw1 real(double_precision) :: xmin(nb_bodies_initial),xmax(nb_bodies_initial),ymin(nb_bodies_initial),ymax(nb_bodies_initial) !------------------------------------------------------------------------------ if (start_index.le.0) then i0 = 2 else i0 = start_index endif nce = 0 do j = 2, nbod ce(j) = 0 end do ! Calculate maximum and minimum values of x and y coordinates call mce_box (nbod,h,x0,v0,x1,v1,xmin,xmax,ymin,ymax) ! Adjust values for the Big bodies by symplectic close-encounter distance do j = i0, nbig xmin(j) = xmin(j) - rcrit(j) xmax(j) = xmax(j) + rcrit(j) ymin(j) = ymin(j) - rcrit(j) ymax(j) = ymax(j) + rcrit(j) end do ! Identify pairs whose X-Y boxes overlap, and calculate minimum separation do i = i0, nbig do j = i + 1, nbod if (xmax(i).ge.xmin(j).and.xmax(j).ge.xmin(i).and.ymax(i).ge.ymin(j).and.ymax(j).ge.ymin(i)) then ! Determine the maximum separation that would qualify as an encounter rc = max(rcrit(i), rcrit(j)) rc2 = rc * rc ! Calculate initial and final separations dx0 = x0(1,i) - x0(1,j) dy0 = x0(2,i) - x0(2,j) dz0 = x0(3,i) - x0(3,j) dx1 = x1(1,i) - x1(1,j) dy1 = x1(2,i) - x1(2,j) dz1 = x1(3,i) - x1(3,j) d0 = dx0*dx0 + dy0*dy0 + dz0*dz0 d1 = dx1*dx1 + dy1*dy1 + dz1*dz1 ! Check for a possible minimum in between du0 = v0(1,i) - v0(1,j) dv0 = v0(2,i) - v0(2,j) dw0 = v0(3,i) - v0(3,j) du1 = v1(1,i) - v1(1,j) dv1 = v1(2,i) - v1(2,j) dw1 = v1(3,i) - v1(3,j) d0t = (dx0*du0 + dy0*dv0 + dz0*dw0) * 2.d0 d1t = (dx1*du1 + dy1*dv1 + dz1*dw1) * 2.d0 ! If separation derivative changes sign, find the minimum separation d2min = HUGE if (d0t*h.le.0.and.d1t*h.ge.0) call mce_min (d0,d1,d0t,d1t,h,d2min,tmin) ! If minimum separation is small enough, flag this as a possible encounter temp = min (d0,d1,d2min) if (temp.le.rc2) then ce(i) = 2 ce(j) = 2 if (nce.lt.CMAX) then nce = nce + 1 ice(nce) = i jce(nce) = j else write(*,*) 'Error: The number of close encounters exceed the limit (CMAX=',CMAX,').' write(*,*) ' All remaining close encounters are skipped' return end if end if end if end do end do !------------------------------------------------------------------------------ return end subroutine mce_snif !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% !> @author <NAME> !> ! !> @date 1 March 2001 ! ! DESCRIPTION: !> @brief Returns details of all close-encounter minima involving at least one Big !! body during a timestep. The routine estimates minima using the initial !! and final coordinates X(0),X(1) and velocities V(0),V(1) of the step, and !! the stepsize H. !!\n\n !! ICLO, JCLO contain the indices of the objects\n !! DCLO is their minimum separation\n !! TCLO is the time of closest approach relative to current time !!\n\n !! The routine also checks for collisions/near misses given the physical radii !! RPHYS, and returns the time THIT of the collision/near miss closest to the !! start of the timestep, and the identities IHIT and JHIT of the objects !! involved.\n\n !! !! NHIT = +1 implies a collision\n !! -1 " a near miss\n ! !> @note All coordinates & velocities must be with respect to the central body! ! !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% subroutine mce_stat (time,h,rcen,nbod,nbig,m,x0,v0,x1,v1,rce,rphys,nclo,iclo,jclo,dclo,tclo,ixvclo,jxvclo,nhit,ihit,jhit,chit,dhit,& thit,thit1,nowflag,stat,outfile) use physical_constant use mercury_constant implicit none ! Input/Output integer, intent(in) :: nbod !< [in] current number of bodies (1: star; 2-nbig: big bodies; nbig+1-nbod: small bodies) integer, intent(in) :: nbig !< [in] current number of big bodies (ones that perturb everything else) integer, intent(in) :: stat(nbod) !< [in] status (0 => alive, <>0 => to be removed) integer, intent(out) :: nowflag integer, intent(out) :: nclo integer, intent(out) :: iclo(CMAX) integer, intent(out) :: jclo(CMAX) integer, intent(out) :: nhit integer, intent(out) :: ihit(CMAX) integer, intent(out) :: jhit(CMAX) integer, intent(out) :: chit(CMAX) real(double_precision), intent(in) :: time !< [in] current epoch (days) real(double_precision), intent(in) :: h !< [in] current integration timestep (days) real(double_precision), intent(in) :: rcen !< [in] radius of central body (AU) real(double_precision), intent(in) :: m(nbod) !< [in] mass (in solar masses * K2) real(double_precision), intent(in) :: x0(3,nbod) real(double_precision), intent(in) :: v0(3,nbod) real(double_precision), intent(in) :: x1(3,nbod) real(double_precision), intent(in) :: v1(3,nbod) real(double_precision), intent(in) :: rce(nbod) real(double_precision), intent(in) :: rphys(nbod) real(double_precision), intent(out) :: dclo(CMAX) real(double_precision), intent(out) :: tclo(CMAX) real(double_precision), intent(out) :: thit(CMAX) real(double_precision), intent(out) :: dhit(CMAX) real(double_precision), intent(out) :: thit1 real(double_precision), intent(out) :: ixvclo(6,CMAX) real(double_precision), intent(out) :: jxvclo(6,CMAX) character(len=80), intent(in) :: outfile ! Local integer :: i,j, error real(double_precision) :: d0,d1,d0t,d1t,hm1,tmp0,tmp1 real(double_precision) :: dx0,dy0,dz0,du0,dv0,dw0,dx1,dy1,dz1,du1,dv1,dw1 real(double_precision) :: xmin(nb_bodies_initial),xmax(nb_bodies_initial),ymin(nb_bodies_initial),ymax(nb_bodies_initial) real(double_precision) :: d2min,d2ce,d2near,d2hit,temp,tmin !------------------------------------------------------------------------------ nhit = 0 thit1 = sign(HUGE, h) hm1 = 1.d0 / h ! Calculate maximum and minimum values of x and y coords for each object call mce_box (nbod,h,x0,v0,x1,v1,xmin,xmax,ymin,ymax) ! Adjust values by the maximum close-encounter radius plus a fudge factor do j = 2, nbod temp = rce(j) * 1.2d0 xmin(j) = xmin(j) - temp xmax(j) = xmax(j) + temp ymin(j) = ymin(j) - temp ymax(j) = ymax(j) + temp end do ! Check for close encounters between each pair of objects do i = 2, nbig do j = i + 1, nbod if (xmax(i).ge.xmin(j).and.xmax(j).ge.xmin(i).and.ymax(i).ge.ymin(j).and.ymax(j).ge.ymin(i).and.& stat(i).ge.0.and.stat(j).ge.0) then ! If the X-Y boxes for this pair overlap, check circumstances more closely dx0 = x0(1,i) - x0(1,j) dy0 = x0(2,i) - x0(2,j) dz0 = x0(3,i) - x0(3,j) du0 = v0(1,i) - v0(1,j) dv0 = v0(2,i) - v0(2,j) dw0 = v0(3,i) - v0(3,j) d0t = (dx0*du0 + dy0*dv0 + dz0*dw0) * 2.d0 dx1 = x1(1,i) - x1(1,j) dy1 = x1(2,i) - x1(2,j) dz1 = x1(3,i) - x1(3,j) du1 = v1(1,i) - v1(1,j) dv1 = v1(2,i) - v1(2,j) dw1 = v1(3,i) - v1(3,j) d1t = (dx1*du1 + dy1*dv1 + dz1*dw1) * 2.d0 ! Estimate minimum separation during the time interval, using interpolation d0 = dx0*dx0 + dy0*dy0 + dz0*dz0 d1 = dx1*dx1 + dy1*dy1 + dz1*dz1 call mce_min (d0,d1,d0t,d1t,h,d2min,tmin) d2ce = max (rce(i), rce(j)) d2hit = rphys(i) + rphys(j) d2ce = d2ce * d2ce d2hit = d2hit * d2hit d2near = d2hit * 4.d0 !if (abs(time - 2452983.63D0) <= 10.D0 .and. (i == 3 .or. j == 3)) then ! print *, 'clo', time, i, j, d2min,d2ce,d0t,h,d1t,d2hit !end if ! If the minimum separation qualifies as an encounter or if a collision ! is in progress, store details if ((d2min.le.d2ce.and.d0t*h.le.0.and.d1t*h.ge.0).or.(d2min.le.d2hit)) then nclo = nclo + 1 !if (i == 3 .or. j == 3) then ! print *, 'clo', time, nclo, i, j !end if if (nclo.gt.CMAX) then open (23,file=outfile,status='old',position='append',iostat=error) if (error /= 0) then write (*,'(/,2a)') " ERROR: Programme terminated. Unable to open ",trim(outfile) stop end if write (23,'(/,2a,/,a)') mem(121)(1:lmem(121)),mem(132)(1:lmem(132)),mem(82)(1:lmem(82)) close (23) else tclo(nclo) = tmin + time dclo(nclo) = sqrt (max(0.d0,d2min)) iclo(nclo) = i jclo(nclo) = j ! Make sure the more massive body is listed first if (m(j).gt.m(i).and.j.le.nbig) then iclo(nclo) = j jclo(nclo) = i end if ! Make linear interpolation to get coordinates at time of closest approach tmp0 = 1.d0 + tmin*hm1 tmp1 = -tmin*hm1 ixvclo(1,nclo) = tmp0 * x0(1,i) + tmp1 * x1(1,i) ixvclo(2,nclo) = tmp0 * x0(2,i) + tmp1 * x1(2,i) ixvclo(3,nclo) = tmp0 * x0(3,i) + tmp1 * x1(3,i) ixvclo(4,nclo) = tmp0 * v0(1,i) + tmp1 * v1(1,i) ixvclo(5,nclo) = tmp0 * v0(2,i) + tmp1 * v1(2,i) ixvclo(6,nclo) = tmp0 * v0(3,i) + tmp1 * v1(3,i) jxvclo(1,nclo) = tmp0 * x0(1,j) + tmp1 * x1(1,j) jxvclo(2,nclo) = tmp0 * x0(2,j) + tmp1 * x1(2,j) jxvclo(3,nclo) = tmp0 * x0(3,j) + tmp1 * x1(3,j) jxvclo(4,nclo) = tmp0 * v0(1,j) + tmp1 * v1(1,j) jxvclo(5,nclo) = tmp0 * v0(2,j) + tmp1 * v1(2,j) jxvclo(6,nclo) = tmp0 * v0(3,j) + tmp1 * v1(3,j) end if end if ! Check for a near miss or collision if (d2min.le.d2near) then nhit = nhit + 1 ihit(nhit) = i jhit(nhit) = j thit(nhit) = tmin + time dhit(nhit) = sqrt(d2min) chit(nhit) = -1 if (d2min.le.d2hit) chit(nhit) = 1 ! Make sure the more massive body is listed first if (m(jhit(nhit)).gt.m(ihit(nhit)).and.j.le.nbig) then ihit(nhit) = j jhit(nhit) = i end if ! Is this the collision closest to the start of the time step? if ((tmin-thit1)*h.lt.0) then thit1 = tmin nowflag = 0 if (d1.le.d2hit) nowflag = 1 end if end if end if ! Move on to the next pair of objects end do end do !------------------------------------------------------------------------------ return end subroutine mce_stat end module dynamic <file_sep>#!/usr/bin/env python #make all plots for planetesmial grwoth, like semi-time, ecc-time and mass-time figure import numpy as np import math import string import os import csv import pylab import sys import matplotlib import subprocess as sp import matplotlib.pyplot as plt from astrounit import * from diskmodel import rtrans,rsnow from m6_funcs import * from plotset import * ################################################### ############# read data files into array ########## ################################################### def readdata(filename): data = np.loadtxt(filename) if data.ndim != 1: time = data[:,0]/365.25 # in unit of year count = len(time) # total line of time array; or np.size(time) semi = data[:,1] ecc = data[:,2] inc = data[:,3]*np.pi/180 peri = data[:,4] # periastron node = data[:,5] # ascending node mean = data[:,6] #mean anormal mass = data[:,7]*msuntome masswater = data[:,14] # mass in water fwater = data[:,14]/data[:,7] # water fraction else : time = data[0]/365.25 # in unit of year count = 1 # total line of time array; or np.size(time) semi = data[1] ecc = data[2] inc = data[3]*np.pi/180 peri = data[4] # periastron node = data[5] # ascending node mean = data[6] #mean anormal mass = data[7]*msuntome masswater = data[14] # mass in water fwater = data[14]/data[7] # water fraction # calculate the mass increase rate dmass #dm = np.diff(mass) #dt = np.diff(time) #dmdt = dm/dt return time, semi, ecc, inc, mass, fwater ##### defualt simulation infomation #### #If an input file is provided, we use the given inputs from it try: sys.argv[1] except (IndexError,NameError): source = 'diskdep_uni3' else: source = sys.argv[1] #The vars.ini file # vars_ = process_input(inputfile) # source = vars_[8][0].rstrip('\n') big = True # plot big planets generate_newdata = False print('data file', source) ##### defualt figure parameters #### tmin = 1e+5 # year tmax = 2e+6 # year amin = .1 # 1 amax = 100 #8 emin = 1e-7 emax = 1 imin = 1e-7 imax = 1 mmin = 1e-1#1e-11 mmax = 1e3 dmmin = 1e-16 dmmax = 3e-10 # linewidth lw1 = 0.25 lw2 = 0.5 lw3 = 0.85 lw4 = 2.5 lw5 = 5.5 # fontsize fs1 = 12 fs2 = 16 fs3 = 17 cdir = os.getcwd()#+'/' #current dir sourcedir = cdir+'/../sim/'+source+'/' pydir = cdir # python dir workdir = cdir+'/../figure/' ## in source direction, generating the aei output file os.chdir(sourcedir) #We get the number of bodies nbig = len(get_names()) #As well as the collision info from the simulation collinfo = detect_merger() #And finally the disk parameters used alpha_d, alpha_v, mdot_gas, L_s, _, _, st, kap, M_s, opt_vis = get_disk_params() # calculate the transtion radius for two disk regions r_trans = rtrans(mdot_gas,L_s,M_s,alpha_v,kap,opt_vis) r_snow = rsnow(mdot_gas,L_s,M_s,alpha_v,kap,opt_vis) #We get an array of indices for survivors surv_ids = get_survivor_ids() # change into figure direction os.chdir(workdir) plt.clf() # clear image plt.close('all') # delete figure #### We get colour for the different planets ccycle = plt.rcParams['axes.prop_cycle'].by_key()['color'] if nbig > len(ccycle): ncycle = int(np.ceil(nbig/len(ccycle))) ccycle = np.concatenate([ccycle]*ncycle) else: ccycle = ccycle[:nbig] ######################################### ###### Main rountine: make figures ###### ######################################### fig_all, ax = plt.subplots(2,2,figsize=(12,8),sharey=True) fig_all.subplots_adjust(wspace=0.01) axlist = np.ravel(ax) for k in range(0,4): fig, axes = plt.subplots(figsize=(8,5)) ## k is the output figure type ## if k == 0: output = 'semi_time' axes.axhline(r_trans,linewidth=1.5, color='c', linestyle='--',zorder=2) axes.axhline(r_snow,linewidth=1.5, color='m', linestyle='--',zorder=2) axlist[k].axhline(r_trans,linewidth=1.5, color='c', linestyle='--',zorder=2) axlist[k].axhline(r_snow,linewidth=1.5, color='m', linestyle='--',zorder=2) print (output) if k == 1: output = 'semi_time_zoom' axes.axhline(r_trans,linewidth=lw4, color='c', linestyle='--',zorder=2) axes.axhline(r_snow,linewidth=lw4, color='m', linestyle='--',zorder=2) axes.text(2.01e6,r_trans,'$\\rm r_{\\rm trans}$',color='c') axes.text(2.01e6,r_snow,'$\\rm r_{\\rm ice}$',color='m') axlist[k].axhline(r_trans,linewidth=1.5, color='c', linestyle='--',zorder=2) axlist[k].axhline(r_snow,linewidth=1.5, color='m', linestyle='--',zorder=2) axlist[k].text(2.01e6,r_trans,'$\\rm r_{\\rm trans}$',color='c') axlist[k].text(2.01e6,r_snow,'$\\rm r_{\\rm ice}$',color='m') print (output) if k == 2: output = 'mass_time' print (output) if k == 3: output = 'mass_semi' print (output) axes.axvline(r_trans,linewidth=1.5, color='c', linestyle='--',zorder=2) axes.axvline(r_snow,linewidth=1.5, color='m', linestyle='--',zorder=2) axes.text(r_trans,500,'$\\rm r_{\\rm trans}$',color='c',ha='left',va='center') axes.text(r_snow,500,'$\\rm r_{\\rm ice}$',color='m',ha='left',va='center') axlist[k].axvline(r_trans,linewidth=1.5, color='c', linestyle='--',zorder=2) axlist[k].axvline(r_snow,linewidth=1.5, color='m', linestyle='--',zorder=2) axlist[k].text(r_trans,500,'$\\rm r_{\\rm trans}$',color='c',ha='left',va='center') axlist[k].text(r_snow,500,'$\\rm r_{\\rm ice}$',color='m',ha='left',va='center') if big == True and nbig >0: for i in range(1, nbig+1): filename = sourcedir+ 'P'+ str(i)+'.aei' time_big, semi_big, ecc_big, inc_big, mass_big, fwater_big = \ readdata(filename) #To account for possible negative semi_values we set these values #to the radius where we have our cavity semi_big[semi_big<0] = 1e-1 #We set the color or the alpha value given the final mass of the planet #and if it survives the integration. Only isolation mass planets #get colour, the rest are set to black with a low alpha im_idx = check_isomass(semi_big,mass_big,mdot_gas,L_s,M_s,alpha_d,alpha_v,kap,opt_vis) if im_idx is None: alph = 0.4 col = 'k' zord = 0 zordm = 1 else: alph = 1 col = ccycle[i-1] zord = 2 zordm = 3 if output =='mass_time': #We check if the planet reaches its gap opening mass at any point #of its evolution. If so, we increase the thickness of its #plot line width gm_idx = check_gapmass(semi_big,mass_big,mdot_gas,L_s,M_s,alpha_d,alpha_v,kap,opt_vis) if gm_idx is None: lw = lw3 else: lw = lw4 if im_idx is not None: pidx = im_idx+1 else: pidx = im_idx axes.plot(time_big[:pidx],mass_big[:pidx],linewidth=lw,color='k',\ zorder=zord,alpha=0.4) axlist[k].plot(time_big[:pidx],mass_big[:pidx],linewidth=lw,color='k',\ zorder=zord,alpha=0.4) if im_idx is not None: axes.plot(time_big[pidx-1:],mass_big[pidx-1:],linewidth=lw,color=col,\ zorder=zord,alpha=alph) axlist[k].plot(time_big[pidx-1:],mass_big[pidx-1:],linewidth=lw,color=col,\ zorder=zord,alpha=alph) axes.set_xlabel(r'$\mathrm{ Time \ (yr)}$') axes.set_ylabel('$ {\\rm Mass \\ (M_{\\oplus})}$') axes.set_ylim(mmin,mmax) #We also plot the data in a separate figure axlist[k].set_xlabel(r'$\mathrm{ Time \ (yr)}$') axlist[k].set_ylabel('$ {\\rm Mass \\ (M_{\\oplus})}$') axlist[k].set_ylim(mmin,mmax) #We check if the planet has undergone collisions and plot them #if that's the case if i in collinfo[0]: idx = np.where(i==collinfo[0])[0] for j in range(len(idx)): colj = col alphj = alph if im_idx is not None: cmass_idx = np.where(collinfo[1,idx[j]]==mass_big)[0] if cmass_idx<im_idx: colj = 'k' alphj = 0.4 axes.plot(collinfo[2,idx[j]],collinfo[1,idx[j]],'X',markersize=5,markerfacecolor=colj,\ markeredgecolor='k',markeredgewidth=0.5,zorder=zordm,alpha=alphj) axlist[k].plot(collinfo[2,idx[j]],collinfo[1,idx[j]],'X',markersize=5,markerfacecolor=colj,\ markeredgecolor='k',markeredgewidth=0.5,zorder=zordm,alpha=alphj) if output in ['semi_time','semi_time_zoom']: #We check if the planet reaches its gap opening mass at any point #of its evolution. If so, we increase the thickness of its #plot line width gm_idx = check_gapmass(semi_big,mass_big,mdot_gas,L_s,M_s,alpha_d,alpha_v,kap,opt_vis) if gm_idx is None: lw = lw3 else: lw = lw4 if im_idx is not None: pidx = im_idx+1 else: pidx = im_idx axes.plot(time_big[:pidx],semi_big[:pidx],linewidth=lw,color='k',\ zorder=zord,alpha=0.4) axlist[k].plot(time_big[:pidx],semi_big[:pidx],linewidth=lw,color='k',\ zorder=zord,alpha=0.4) if im_idx is not None: axes.plot(time_big[pidx-1:],semi_big[pidx-1:],linewidth=lw,color=col,\ zorder=zord,alpha=alph) axlist[k].plot(time_big[pidx-1:],semi_big[pidx-1:],linewidth=lw,color=col,\ zorder=zord,alpha=alph) axes.set_xlabel('${\\rm Time \\ (yr)}$') axes.set_ylabel('$ {\\rm Semimajor \\ axis \\ (AU)}$') axes.set_ylim(amin,amax) axlist[k].set_xlabel('${\\rm Time \\ (yr)}$') axlist[k].set_ylabel('$ {\\rm Semimajor \\ axis \\ (AU)}$') axlist[k].set_ylim(amin,amax) #If the planet has reach its isolation mass we plot the corresponding #time and semi-major axis # if im_idx is not None: # axes.plot(time_big[im_idx],semi_big[im_idx],'p',markersize=5,markerfacecolor=col,\ # markeredgecolor='k',markeredgewidth=0.5,zorder=zordm) # axlist[k].plot(time_big[im_idx],semi_big[im_idx],'p',markersize=5,markerfacecolor=col,\ # markeredgecolor='k',markeredgewidth=0.5,zorder=zordm) #If the planet survives the integration we plot a dot with a #size proportional to its mass at its final radius if i in surv_ids: msize = mass_big[-1]**(1/3) axes.text(time_big[-1],semi_big[-1],r'$\bullet$',fontsize=msize,color=col,\ zorder=3,ha='center',va='center') axlist[k].text(time_big[-1],semi_big[-1],r'$\bullet$',fontsize=msize,color=col,\ zorder=3,ha='center',va='center') #We check if the planet has undergone collisions and plot them #if that's the case if i in collinfo[0]: idx = np.where(i==collinfo[0])[0] for j in range(len(idx)): colj = col alphj = alph if im_idx is not None: cmass_idx = np.where(collinfo[1,idx[j]]==mass_big)[0] if cmass_idx<im_idx: colj = 'k' alphj = 0.4 axes.plot(collinfo[2,idx[j]],collinfo[3,idx[j]],'X',markersize=5,markerfacecolor=colj,\ markeredgecolor='k',markeredgewidth=0.5,zorder=zordm,alpha=alphj) axlist[k].plot(collinfo[2,idx[j]],collinfo[3,idx[j]],'X',markersize=5,markerfacecolor=colj,\ markeredgecolor='k',markeredgewidth=0.5,zorder=zordm,alpha=alphj) if output == 'mass_semi': #We check if the planet reaches its gap opening mass at any point #of its evolution. If so, we increase the thickness of its #plot line width gm_idx = check_gapmass(semi_big,mass_big,mdot_gas,L_s,M_s,alpha_d,alpha_v,kap,opt_vis) if gm_idx is None: lw = lw3 else: lw = lw4 if im_idx is not None: pidx = im_idx+1 else: pidx = im_idx axes.plot(semi_big[:pidx],mass_big[:pidx],linewidth=lw,color='k',\ zorder=zord,alpha=0.4) axlist[k].plot(semi_big[:pidx],mass_big[:pidx],linewidth=lw,color='k',\ zorder=zord,alpha=0.4) if im_idx is not None: axes.plot(semi_big[pidx-1:],mass_big[pidx-1:],linewidth=lw,color=col,\ zorder=zord,alpha=alph) axlist[k].plot(semi_big[pidx-1:],mass_big[pidx-1:],linewidth=lw,color=col,\ zorder=zord,alpha=alph) axes.set_ylabel('${\\rm Mass \\ (M_{\\oplus})}$') axes.set_xlabel('$ {\\rm Semimajor \\ axis \\ (AU)}$') axes.set_ylim(mmin,mmax) # axlist[k].set_ylabel('${\\rm Mass \\ (M_{\\oplus})}$') axlist[k].set_xlabel('$ {\\rm Semimajor \\ axis \\ (AU)}$') axlist[k].set_ylim(mmin,mmax) #If the planet has reach its isolation mass we plot the corresponding #time and semi-major axis # if im_idx is not None: # axes.plot(time_big[im_idx],semi_big[im_idx],'p',markersize=5,markerfacecolor=col,\ # markeredgecolor='k',markeredgewidth=0.5,zorder=zordm) # axlist[k].plot(time_big[im_idx],semi_big[im_idx],'p',markersize=5,markerfacecolor=col,\ # markeredgecolor='k',markeredgewidth=0.5,zorder=zordm) #If the planet survives the integration we plot a dot with a #size proportional to its mass at its final radius # if i in surv_ids: # msize = mass_big[-1]**(1/3) # axes.text(semi_big[-1],mass_big[-1],r'$\bullet$',fontsize=msize,color=col,\ # zorder=3,ha='center',va='center') # axlist[k].text(semi_big[-1],mass_big[-1],r'$\bullet$',fontsize=msize,color=col,\ # zorder=3,ha='center',va='center') #We check if the planet has undergone collisions and plot them #if that's the case if i in collinfo[0]: idx = np.where(i==collinfo[0])[0] for j in range(len(idx)): colj = col alphj = alph if im_idx is not None: cmass_idx = np.where(collinfo[1,idx[j]]==mass_big)[0] if cmass_idx<im_idx: colj = 'k' alphj = 0.4 axes.plot(collinfo[3,idx[j]],collinfo[1,idx[j]],'X',markersize=5,markerfacecolor=colj,\ markeredgecolor='k',markeredgewidth=0.5,zorder=zordm,alpha=alphj) axlist[k].plot(collinfo[3,idx[j]],collinfo[1,idx[j]],'X',markersize=5,markerfacecolor=colj,\ markeredgecolor='k',markeredgewidth=0.5,zorder=zordm,alpha=alphj) if output =='ecc_time': axes.plot(time_big,ecc_big,linewidth=lw3,color=col,alpha=alph,zorder=zord) axes.set_xlabel('${\\rm Time \\ (yr)}$') axes.set_ylabel('$ {\\rm Eccentricity}$') axes.set_ylim(emin,emax) axlist[k].plot(time_big,ecc_big,linewidth=lw3,color=col,alpha=alph,zorder=zord) axlist[k].set_xlabel('${\\rm Time \\ (yr)}$') axlist[k].set_ylabel('$ {\\rm Eccentricity}$') axlist[k].set_ylim(emin,emax) if output =='inc_time': axes.plot(time_big,inc_big,linewidth=lw3,color=col,alpha=alph,zorder=zord) axes.set_xlabel('${\\rm Time \\ (yr)}$') axes.set_ylabel('$ {\\rm Inclination (radian)}$') axes.set_ylim(imin,imax) axlist[k].plot(time_big,inc_big,linewidth=lw3,color=col,alpha=alph,zorder=zord) axlist[k].set_xlabel('${\\rm Time \\ (yr)}$') axlist[k].set_ylabel('$ {\\rm Inclination (radian)}$') axlist[k].set_ylim(imin,imax) if output == 'semi_time_zoom': axes.set_xlim(1e6,tmax) axes.set_ylim(5,amax) elif output == 'mass_semi': axes.set_xlim(amin,amax) else: axes.set_xlim(tmin,tmax) axes.semilogx() axes.semilogy() axlist[k].semilogx() axlist[k].semilogy() if output == 'semi_time_zoom': axlist[k].set_xlim(1e6,tmax) axlist[k].set_ylim(5,amax) axlist[k].set_ylabel(None) axlist[k].set_xscale('log') axlist[k].set_xticks([1e+6,1.5e6,2e+6],['$10^6$','$1.5\cdot10^6$','$2\cdot10^6$']) # axlist[k].get_xaxis().set_major_formatter(matplotlib.ticker.ScalarFormatter()) elif output == 'mass_semi': axlist[k].set_xlim(amin,amax) else: axlist[k].set_xlim(tmin,tmax) # axlist[k].set_xticks([1e+2,1e+3,1e+4,1e+5,1e+6],['$10^{2}$','$10^{3}$','$10^{4}$','$10^{5}$','$10^{6}$']) fig.suptitle(r'$\tau_s = '+'{:.2E},\ '.format(st)+r'\alpha_t = '+'{:.2E},\ '.format(alpha_d)+r'\alpha_g = '+'{:.2E},\ '.format(alpha_v)+r'\kappa = '+'{:.2E}'.format(kap)+'$') add_date(fig) fig.savefig(source+'_'+output+'.pdf',orientation='landscape', format='pdf',bbox_inches='tight', pad_inches=0.1) fig_all.suptitle(r'$\tau_s = '+'{:.2E},\ '.format(st)+r'\alpha_t = '+'{:.2E},\ '.format(alpha_d)+r'\alpha_g = '+'{:.2E},\ '.format(alpha_v)+r'\kappa = '+'{:.2E}'.format(kap)+'$') add_date(fig_all) fig_all.savefig(source+'_'+'all'+'.pdf',orientation='landscape', format='pdf',bbox_inches='tight', pad_inches=0.1) os.chdir(pydir) <file_sep>!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ! Author: <NAME> (and <NAME>) ! Mercury is a general-purpose N-body integration package for problems in ! celestial mechanics. ! Modified by <NAME> (Nov 2017): ! added or changed file: user_module.f90, massgrowth.f90, algo_hybrid.f90, dynamics.f90, ! system_properties.f90, mercury_output.f90, mercury_global.f90, ! messgin.in, param.in, big.in !1. add disk parameter into the MODULE mercury_gloabl.f90 and read it from the param.in; add these new constants in mercury.f90 !siggas0, hgas0, tau_dep, index_p, index_q, Mdot_peb, tau_s,alpha, opt(9) !1). mercury_output.f90: add opflag=0,siggas0... save the output information !2). mercury_global.f90: add opt(9)=0, define this opt=1 with pebble accretion; opt =0 W/O pebble accretion !2. new subrountines !1) massgrowth.f90 for pebble accretion: pebble !2) user_module.f90 for gas drag and type I migrarion: gasdrag,type12 !3. remove some outputs from screen and file: !1) mercury_output.f90: do not show first 5 line of *.aei !2) mercury.f90: do not show begin and end of the intergration !4. mercury.f90: include the pebble accretion in B-S method and hybrid method when opt(9)=1 !4. add planetary compostion (element X): m_x for the following subrountine ! initial setup: big.in mio_in ! main integration: mal_hvar, mal_con, massgrowth, mxx_elim, mce_coll, mce_init, mce_merg, mdt_hkce, mdt_hy ! write output : mio_dump, element.f90 !5. collision accounts for the density change: mce_coll, mce_merg !------------------------------------------------------------------------------ program mercury use types_numeriques use physical_constant use mercury_constant use mercury_globals use system_properties use mercury_outputs use utilities use massgrowth, only: pebbleaccretion,gasaccretion ! ALGORITHMS use algo_hybrid use algo_mvs use algo_bs1 use algo_bs2 use algo_radau ! FORCES use forces implicit none integer :: j,nbod,nbig integer :: opflag,ngflag,ndump,nfun integer :: error real(double_precision) :: cefac,time,h0,tol,en(3),am(3),rcen,jcen(3) integer, dimension(:), allocatable :: stat ! (Number of bodies) real(double_precision), dimension(:), allocatable :: m,m_x,rho,rceh,epoch ! (Number of bodies) real(double_precision), dimension(:,:), allocatable :: xh,vh,s ! (3,Number of bodies) real(double_precision), dimension(:,:), allocatable :: ngf ! (4,Number of bodies) character(len=8), dimension(:), allocatable :: id ! (Number of bodies) !------------------------------------------------------------------------------ ! We get the number of big bodies and the total number of bodies before reading effectively the parameter files call getNumberOfBodies(nb_big_bodies=nbig, nb_bodies=nb_bodies_initial) !~ !~ ! We allocate and initialize arrays now that we know their sizes allocate(stat(nb_bodies_initial), stat=error) if (error.ne.0) then write(*,*) 'Error: failed to allocate "stat" array' end if stat(1:nb_bodies_initial) = 0 allocate(m(nb_bodies_initial), stat=error) if (error.ne.0) then write(*,*) 'Error: failed to allocate "m" array' end if m(1:nb_bodies_initial) = 0.d0 allocate(m_x(nb_bodies_initial), stat=error) if (error.ne.0) then write(*,*) 'Error: failed to allocate "m_x" array' end if m_x(1:nb_bodies_initial) = 0.d0 allocate(rho(nb_bodies_initial), stat=error) if (error.ne.0) then write(*,*) 'Error: failed to allocate "rho" array' end if rho(1:nb_bodies_initial) = 0.d0 allocate(rceh(nb_bodies_initial), stat=error) if (error.ne.0) then write(*,*) 'Error: failed to allocate "rceh" array' end if rceh(1:nb_bodies_initial) = 0.d0 allocate(epoch(nb_bodies_initial), stat=error) if (error.ne.0) then write(*,*) 'Error: failed to allocate "epoch" array' end if epoch(1:nb_bodies_initial) = 0.d0 allocate(xh(3,nb_bodies_initial), stat=error) if (error.ne.0) then write(*,*) 'Error: failed to allocate "xh" array' end if xh(1:3,1:nb_bodies_initial) = 0.d0 allocate(vh(3,nb_bodies_initial), stat=error) if (error.ne.0) then write(*,*) 'Error: failed to allocate "vh" array' end if vh(1:3,1:nb_bodies_initial) = 0.d0 allocate(s(3,nb_bodies_initial), stat=error) if (error.ne.0) then write(*,*) 'Error: failed to allocate "s" array' end if s(1:3,1:nb_bodies_initial) = 0.d0 allocate(ngf(4,nb_bodies_initial), stat=error) if (error.ne.0) then write(*,*) 'Error: failed to allocate "ngf" array' end if ngf(1:4,1:nb_bodies_initial) = 0.d0 allocate(id(nb_bodies_initial), stat=error) if (error.ne.0) then write(*,*) 'Error: failed to allocate "id" array' end if id(1:nb_bodies_initial) = '' ! We allocate private variables of several modules ! (since we want to 'save' them, we cannot have a dynamic array). ! To avoid testing the allocation at each timestep, we allocate them ! in a sort of initialisation subroutine. Module that need to have ! initialisation will have a subroutine with "allocate" in their name. call allocate_hy(nb_bodies=nb_bodies_initial) call allocate_mvs(nb_bodies=nb_bodies_initial) call allocate_radau(nb_bodies=nb_bodies_initial) !------------------------------------------------------------------------------ ! Get initial conditions and integration parameters call mio_in (time,h0,tol,rcen,jcen,en,am,cefac,ndump,nfun,nbod,nbig,m,xh,vh,s,rho,rceh,id,& epoch,ngf,opflag,ngflag,m_x) ! If this is a new integration, integrate all the objects to a common epoch. if (opflag.eq.-2) then open (23,file=outfile(3),status='old',position='append',iostat=error) if (error /= 0) then write (*,'(/,2a)') " ERROR: Programme terminated. Unable to open ",trim(outfile(3)) stop end if ! We only synchronize if there are small bodies. if (nbod.ne.nbig) then write (23,'(/,a)') mem(55)(1:lmem(55)) write (*,'(a)') mem(55)(1:lmem(55)) call mxx_sync (time,h0,tol,jcen,nbod,nbig,m,xh,vh,s,rho,rceh,stat,id,epoch,ngf,ngflag) else write (23,'(/,a)') "No need to synchronize epochs since we don't have small bodies" ! write (*,'(a)') "No need to synchronize epochs since we don't have small bodies" end if write (23,'(/,a,/)') mem(56)(1:lmem(56)) ! write (*,'(a)') mem(56)(1:lmem(56)) opflag = -1 close (23) end if ! Main integration if (algor.eq.1) call mal_hcon (time,h0,tol,jcen,rcen,en,am,cefac,ndump,nfun,nbod,nbig,m,xh,vh,s,& rho,rceh,stat,id,ngf,opflag,ngflag,mdt_mvs,mco_h2mvs,mco_mvs2h,m_x) if (algor.eq.9) call mal_hcon (time,h0,tol,jcen,rcen,en,am,cefac,ndump,nfun,nbod,nbig,m,xh,vh,s,& rho,rceh,stat,id,ngf,opflag,ngflag,mdt_mvs,mco_iden,mco_iden,m_x) if (algor.eq.2) call mal_hvar (time,h0,tol,jcen,rcen,en,am,cefac,ndump,nfun,nbod,nbig,m,xh,vh,s,& rho,rceh,stat,id,ngf,opflag,ngflag,mdt_bs1,m_x) if (algor.eq.3) call mal_hvar (time,h0,tol,jcen,rcen,en,am,cefac,ndump,nfun,nbod,nbig,m,xh,vh,s,& rho,rceh,stat,id,ngf,opflag,ngflag,mdt_bs2,m_x) if (algor.eq.4) call mal_hvar (time,h0,tol,jcen,rcen,en,am,cefac,ndump,nfun,nbod,nbig,m,xh,vh,s,& rho,rceh,stat,id,ngf,opflag,ngflag,mdt_ra15,m_x) if (algor.eq.10) call mal_hcon (time,h0,tol,jcen,rcen,en,am,cefac,ndump,nfun,nbod,nbig,m,xh,vh,s,& rho,rceh,stat,id,ngf,opflag,ngflag,mdt_hy,mco_h2dh,mco_dh2h,m_x) ! Do a final data dump do j = 2, nbod epoch(j) = time end do call mio_dump (time,h0,tol,jcen,rcen,en,am,cefac,ndump,nfun,nbod,nbig,m,xh,vh,s,rho,rceh,stat,& id,ngf,epoch,opflag,m_x) ! Calculate and record the overall change in energy and ang. momentum open (23, file=outfile(3), status='old', position='append',iostat=error) if (error /= 0) then write (*,'(/,2a)') " ERROR: Programme terminated. Unable to open ",trim(outfile(3)) stop end if write (23,'(/,a)') mem(57)(1:lmem(57)) call mxx_en (jcen,nbod,nbig,m,xh,vh,s,en(2),am(2)) write (23,231) mem(58)(1:lmem(58)),abs((en(2) + en(3) - en(1)) / en(1)) write (23,232) mem(59)(1:lmem(59)), abs((am(2) + am(3) - am(1)) / am(1)) write (23,231) mem(60)(1:lmem(60)), abs(en(3) / en(1)) write (23,232) mem(61)(1:lmem(61)), abs(am(3) / am(1)) close (23) !write (*,'(a)') mem(57)(1:lmem(57)) !------------------------------------------------------------------------------ 231 format (/,a,1p1e12.5) 232 format (a,1p1e12.5) stop contains !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% !> @author !> <NAME> ! !> @date 4 May 2001 ! ! DESCRIPTION: !> @brief Reads names, masses, coordinates and velocities of all the bodies, !! and integration parameters for the MERCURY integrator package. !! If DUMPFILE(4) exists, the routine assumes this is a continuation of !! an old integration, and reads all the data from the dump files instead !! of the input files. !> @note All coordinates are with respect to the central body! ! !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% subroutine mio_in (time,h0,tol,rcen,jcen,en,am,cefac,ndump,nfun,nbod,nbig,m,x,v,s,rho,rceh,& id,epoch,ngf,opflag,ngflag,m_x) use orbital_elements implicit none ! Output integer, intent(out) :: nbod !< [out] current number of bodies (INCLUDING the central object) integer, intent(out) :: nbig !< [out] current number of big bodies (ones that perturb everything else) integer, intent(out) :: opflag !< [out] integration mode (-2 = synchronising epochs) !!\n -1 = integrating towards start epoch !!\n 0 = main integration, normal output !!\n 1 = main integration, full output integer, intent(out) :: ngflag !< [out] do any bodies experience non-grav. forces? !!\n ( 0 = no non-grav forces) !!\n 1 = cometary jets only !!\n 2 = radiation pressure/P-R drag only !!\n 3 = both integer, intent(out) :: ndump integer, intent(out) :: nfun real(double_precision), intent(out) :: time !< [out] current epoch (days) real(double_precision), intent(out) :: h0 !< [out] initial integration timestep (days) real(double_precision), intent(out) :: tol !< [out] Integrator tolerance parameter (approx. error per timestep) real(double_precision), intent(out) :: rcen !< [out] radius of central body (AU) real(double_precision), intent(out) :: jcen(3) !< [out] J2,J4,J6 for central body (units of RCEN^i for Ji) real(double_precision), intent(out) :: en(3) !< [out] (initial energy, current energy, energy change due to collision and ejection) of the system real(double_precision), intent(out) :: am(3) !< [out] (initial angular momentum, current angular momentum, !! angular momentum change due to collision and ejection) of the system real(double_precision), intent(out) :: m(nb_bodies_initial) !< [out] mass (in solar masses * K2) real(double_precision), intent(out) :: m_x(nb_bodies_initial) !< [out] mass of X element (in solar masses * K2) real(double_precision), intent(out) :: x(3,nb_bodies_initial) real(double_precision), intent(out) :: v(3,nb_bodies_initial) real(double_precision), intent(out) :: s(3,nb_bodies_initial) !< [out] spin angular momentum (solar masses AU^2/day) real(double_precision), intent(out) :: rho(nb_bodies_initial) !< [out] physical density (g/cm^3) real(double_precision), intent(out) :: rceh(nb_bodies_initial) !< [out] close-encounter limit (Hill radii) real(double_precision), intent(out) :: epoch(nb_bodies_initial) !< [out] epoch of orbit (days) real(double_precision), intent(out) :: ngf(4,nb_bodies_initial) !< [out] non gravitational forces parameters !! \n(1-3) cometary non-gravitational (jet) force parameters !! \n(4) beta parameter for radiation pressure and P-R drag real(double_precision), intent(out) :: cefac character(len=8), intent(out) :: id(nb_bodies_initial) !< [out] name of the object (8 characters) ! Local integer :: j,k,itmp,jtmp,informat,lim(2,10),nsub,year,month,lineno real(double_precision) :: q,a,e,i,p,n,l,temp,tmp2,tmp3,rhocgs,t1,tmp4,tmp5,tmp6 ! real(double_precision) :: v0(3,Number of bodies),x0(3,Number of bodies) logical test,oldflag,flag1,flag2 character(len=1) :: c1 character(len=3) :: c3 character(len=80) :: infile(3),filename,c80 character(len=150) :: string integer :: error character(len=3), dimension(60), parameter :: alg = (/'MVS','Mvs','mvs','mvs','mvs',& 'BS ','Bs ','bs ','Bul', 'bul',& 'BS2','Bs2','bs2','Bu2','bu2',& 'RAD','Rad','rad','RA ', 'ra ',& 'xxx','xxx','xxx','xxx','xxx',& 'xxx','xxx','xxx','xxx', 'xxx',& 'xxx','xxx','xxx','xxx','xxx',& 'xxx','xxx','xxx','xxx', 'xxx',& 'TES','Tes','tes','Tst','tst',& 'HYB','Hyb','hyb','HY ', 'hy ',& 'CLO','Clo','clo','CB ','cb ',& 'WID','Wid','wid','WB ', 'wb '/) rhocgs = AU * AU * AU * K2 / MSUN do j = 1, 80 filename(j:j) = ' ' end do do j = 1, 3 infile(j) = filename outfile(j) = filename dumpfile(j) = filename end do dumpfile(4) = filename ! Read in output messages inquire (file='message.in', exist=test) if (.not.test) then write (*,'(/,2a)') ' ERROR: This file is needed to start',' the integration: message.in' stop end if open (16, file='message.in', status='old') do read (16,'(i3,1x,i2,1x,a80)', iostat=error) j,lmem(j),mem(j) if (error /= 0) exit end do close (16) ! Read in filenames and check for duplicate filenames inquire (file='files.in', exist=test) if (.not.test) call mio_err (6,mem(81),lmem(81),mem(88),lmem(88),' ',1,'files.in',8) open (15, file='files.in', status='old') ! Input files do j = 1, 3 read (15,'(a150)') string call mio_spl (150,string,nsub,lim) infile(j)(1:(lim(2,1)-lim(1,1)+1)) = string(lim(1,1):lim(2,1)) do k = 1, j - 1 if (infile(j).eq.infile(k)) call mio_err (6,mem(81),lmem(81),mem(89),lmem(89),infile(j),80,mem(86),lmem(86)) end do end do ! Output files do j = 1, 3 read (15,'(a150)') string call mio_spl (150,string,nsub,lim) outfile(j)(1:(lim(2,1)-lim(1,1)+1)) = string(lim(1,1):lim(2,1)) do k = 1, j - 1 if (outfile(j).eq.outfile(k)) call mio_err (6,mem(81),lmem(81),mem(89),lmem(89),outfile(j),80,mem(86),lmem(86)) end do do k = 1, 3 if (outfile(j).eq.infile(k)) call mio_err (6,mem(81),lmem(81),mem(89),lmem(89),outfile(j),80,mem(86),lmem(86)) end do end do ! Dump files do j = 1, 4 read (15,'(a150)') string call mio_spl (150,string,nsub,lim) dumpfile(j)(1:(lim(2,1)-lim(1,1)+1)) = string(lim(1,1):lim(2,1)) do k = 1, j - 1 if (dumpfile(j).eq.dumpfile(k)) call mio_err (6,mem(81),lmem(81),mem(89),lmem(89),dumpfile(j),80,mem(86),lmem(86)) end do do k = 1, 3 if (dumpfile(j).eq.infile(k)) call mio_err (6,mem(81),lmem(81),mem(89),lmem(89),dumpfile(j),80,mem(86),lmem(86)) end do do k = 1, 3 if (dumpfile(j).eq.outfile(k)) call mio_err (6,mem(81),lmem(81),mem(89),lmem(89),dumpfile(j),80,mem(86),lmem(86)) end do end do close (15) ! Find out if this is an old integration (i.e. does the restart file exist) inquire (file=dumpfile(4), exist=oldflag) ! Check if information file exists, and append a continuation message if (oldflag) then inquire (file=outfile(3), exist=test) if (.not.test) call mio_err (6,mem(81),lmem(81),mem(88),lmem(88),' ',1,outfile(3),80) open(23,file=outfile(3),status='old',position='append',iostat=error) if (error /= 0) then write (*,'(/,2a)') " ERROR: Programme terminated. Unable to open ",trim(outfile(3)) stop end if else ! If new integration, check information file doesn't exist, and then create it inquire (file=outfile(3), exist=test) if (test) call mio_err (6,mem(81),lmem(81),mem(87),lmem(87),' ',1,outfile(3),80) open(23, file = outfile(3), status = 'new', iostat=error) if (error /= 0) then write (*,'(/,2a)') " ERROR: Programme terminated. Unable to open ",trim(outfile(3)) stop end if end if !------------------------------------------------------------------------------ ! READ IN INTEGRATION PARAMETERS ! Check if the file containing integration parameters exists, and open it filename = infile(3) if (oldflag) filename = dumpfile(3) inquire (file=filename, exist=test) if (.not.test) call mio_err (23,mem(81),lmem(81),mem(88),lmem(88),' ',1,filename,80) open(13, file=filename, status='old', iostat=error) if (error /= 0) then write (*,'(/,2a)') " ERROR: Programme terminated. Unable to open ",trim(filename) stop end if ! Read integration parameters lineno = 0 do j = 1, 42 do lineno = lineno + 1 read (13,'(a150)') string if (string(1:1).ne.')') exit end do call mio_spl (150,string,nsub,lim) c80(1:3) = ' ' c80 = string(lim(1,nsub):lim(2,nsub)) if (j.eq.1) then algor = 0 do k = 1, 60 if (c80(1:3).eq.alg(k)) algor = (k + 4) / 5 end do if (algor.eq.0) call mio_err (23,mem(81),lmem(81),mem(98),lmem(98),c80(lim(1,nsub):lim(2,nsub)),lim(2,nsub)-lim(1,nsub)+1,& mem(85),lmem(85)) end if if (j.eq.2) read (c80,*,err=661) tstart if (j.eq.3) read (c80,*,err=661) tstop if (j.eq.4) read (c80,*,err=661) dtout if (j.eq.5) read (c80,*,err=661) h0 if (j.eq.6) read (c80,*,err=661) tol c1 = c80(1:1) if ((j.eq.7).and.((c1.eq.'y').or.(c1.eq.'Y'))) opt(1) = 1 if ((j.eq.8).and.((c1.eq.'n').or.(c1.eq.'N'))) opt(2) = 0 if ((j.eq.9).and.((c1.eq.'y').or.(c1.eq.'Y'))) opt(2) = 2 if ((j.eq.10).and.((c1.eq.'d').or.(c1.eq.'D'))) opt(3) = 0 if ((j.eq.11).and.((c1.eq.'y').or.(c1.eq.'Y'))) opt(3) = opt(3) + 2 if (j.eq.12) then if((c1.eq.'l').or.(c1.eq.'L')) then opt(4) = 1 else if ((j.eq.12).and.(c1.eq.'m'.or.c1.eq.'M')) then opt(4) = 2 else if ((j.eq.12).and.(c1.eq.'h'.or.c1.eq.'H')) then opt(4) = 3 else goto 661 end if end if if ((j.eq.15).and.(c1.eq.'y'.or.c1.eq.'Y')) opt(8) = 1 if (j.eq.16) read (c80,*,err=661) rmax if (j.eq.17) read (c80,*,err=661) rcen if (j.eq.18) read (c80,*,err=661) m(1) if (j.eq.19) read (c80,*,err=661) jcen(1) if (j.eq.20) read (c80,*,err=661) jcen(2) if (j.eq.21) read (c80,*,err=661) jcen(3) if (j.eq.24) read (c80,*,err=661) cefac if (j.eq.25) read (c80,*,err=661) ndump if (j.eq.26) read (c80,*,err=661) nfun if (j.eq.27) read (c80,*,err=661) alpha_t if (j.eq.28) read (c80,*,err=661) alpha if (j.eq.29) read (c80,*,err=661) mdot_gas0 if (j.eq.30) read (c80,*,err=661) L_s if (j.eq.31) read (c80,*,err=661) Rdisk0 if (j.eq.32) read (c80,*,err=661) Mdot_peb if (j.eq.33) read (c80,*,err=661) tau_s if (j.eq.34) read (c80,*,err=661) kap if (j.eq.35) read (c80,*,err=661) t0_dep if (j.eq.36) read (c80,*,err=661) tau_dep if ((j.eq.37).and.((c1.eq.'y').or.(c1.eq.'Y'))) opt(9) = 1 if ((j.eq.38).and.((c1.eq.'y').or.(c1.eq.'Y'))) opt(10) = 1 if ((j.eq.39).and.((c1.eq.'y').or.(c1.eq.'Y'))) opt(11) = 1 if ((j.eq.40).and.(c1.eq.'0')) opt(12) = 0 if ((j.eq.40).and.(c1.eq.'1')) opt(12) = 1 if ((j.eq.40).and.(c1.eq.'2')) opt(12) = 2 if ((j.eq.40).and.(c1.eq.'3')) opt(12) = 3 if ((j.eq.41).and.((c1.eq.'y').or.(c1.eq.'Y'))) opt(13) = 1 if ((j.eq.42).and.((c1.eq.'y').or.(c1.eq.'Y'))) opt(14) = 1 end do h0 = abs(h0) tol = abs(tol) rmax = abs(rmax) rcen = abs(rcen) cefac = abs(cefac) close (13) ! Change quantities for central object to suitable units m(1) = abs(m(1)) * K2 jcen(1) = jcen(1) * rcen * rcen jcen(2) = jcen(2) * rcen * rcen * rcen * rcen jcen(3) = jcen(3) * rcen * rcen * rcen * rcen * rcen * rcen s(1,1) = 0.d0 s(2,1) = 0.d0 s(3,1) = 0.d0 ! Make sure that RCEN isn't too small, since it is used to scale the output ! (Minimum value corresponds to a central body with density 100g/cm^3). temp = 1.1235d-3 * m(1) ** .333333333333333d0 if (rcen.lt.temp) then rcen = temp write (13,'(/,2a)') mem(121)(1:lmem(121)),mem(131)(1:lmem(131)) end if !------------------------------------------------------------------------------ ! READ IN DATA FOR BIG AND SMALL BODIES nbod = 1 do j = 1, 2 if (j.eq.2) nbig = nbod ! Check if the file containing data for Big bodies exists, and open it filename = infile(j) if (oldflag) filename = dumpfile(j) inquire (file=filename, exist=test) if (.not.test) call mio_err (23,mem(81),lmem(81),mem(88),lmem(88),' ',1,filename,80) open (11, file=filename, status='old', iostat=error) if (error /= 0) then write (*,'(/,2a)') " ERROR: Programme terminated. Unable to open ",trim(filename) stop end if ! Read data style do read (11,'(a150)') string if (string(1:1).ne.')') exit end do call mio_spl (150,string,nsub,lim) c3 = string(lim(1,nsub):(lim(1,nsub)+2)) select case (c3) case ('Car', 'car', 'CAR') informat = 1 case ('Ast', 'ast', 'AST') informat = 2 case ('Com', 'com', 'COM') informat = 3 case default informat = 0 call mio_err (23,mem(81),lmem(81),mem(91),lmem(91),' ',1,mem(82+j),lmem(82+j)) end select ! Read epoch of Big bodies if (j.eq.1) then do read (11,'(a150)') string if (string(1:1).ne.')') exit end do call mio_spl (150,string,nsub,lim) read (string(lim(1,nsub):lim(2,nsub)),*,err=667) time end if ! Read information for each object do read (11,'(a)',iostat=error) string if (error /= 0) exit if (string(1:1).eq.')') cycle call mio_spl (150,string,nsub,lim) if (lim(1,1).eq.-1) exit ! Determine the name of the object nbod = nbod + 1 if (nbod.gt.nb_bodies_initial) call mio_err (23,mem(81),lmem(81),mem(90),lmem(90),' ',1,mem(82),lmem(82)) if ((lim(2,1)-lim(1,1)).gt.7) then write (23,'(/,3a)') mem(121)(1:lmem(121)),mem(122)(1:lmem(122)),string( lim(1,1):lim(2,1) ) end if id(nbod) = string( lim(1,1):min(7+lim(1,1),lim(2,1)) ) ! Check if another object has the same name do k = 1, nbod - 1 if (id(k).eq.id(nbod)) call mio_err (23,mem(81),lmem(81),mem(103),lmem(103),id(nbod),8,' ',1) end do ! Default values of mass, close-encounter limit, density etc. m(nbod) = 0.d0 m_x(nbod) = 0.d0 rceh(nbod) = 1.d0 rho(nbod) = rhocgs epoch(nbod) = time do k = 1, 4 ngf(k,nbod) = 0.d0 end do ! Read values of mass, close-encounter limit, density etc. do k = 3, nsub+1, 2 c80 = string(lim(1,k-1):lim(2,k-1)) ! write(*,'(a150)') c80 ! print*,k read (string(lim(1,k):lim(2,k)),*,err=666) temp if (c80(1:1).eq.'m'.or.c80(1:1).eq.'M') then m(nbod) = temp * K2 else if (c80(1:1).eq.'r'.or.c80(1:1).eq.'R') then rceh(nbod) = temp else if (c80(1:1).eq.'d'.or.c80(1:1).eq.'D') then rho(nbod) = temp * rhocgs else if (c80(1:1).eq.'x'.or.c80(1:1).eq.'X') then m_x(nbod) = temp * K2 else if (m(nbod).lt.0.or.rceh(nbod).lt.0.or.rho(nbod).lt.0) then call mio_err (23,mem(81),lmem(81),mem(97),lmem(97),id(nbod),8,mem(82+j),lmem(82+j)) else if (c80(1:2).eq.'ep'.or.c80(1:2).eq.'EP'.or.c80(1:2).eq.'Ep') then epoch (nbod) = temp else if (c80(1:2).eq.'a1'.or.c80(1:2).eq.'A1') then ngf (1,nbod) = temp else if (c80(1:2).eq.'a2'.or.c80(1:2).eq.'A2') then ngf (2,nbod) = temp else if (c80(1:2).eq.'a3'.or.c80(1:2).eq.'A3') then ngf (3,nbod) = temp else if (c80(1:1).eq.'b'.or.c80(1:1).eq.'B') then ngf (4,nbod) = temp else goto 666 end if end do ! If required, read Cartesian coordinates, velocities and spins of the bodies jtmp = 100 do read (11,'(a150)',end=666) string if (string(1:1).ne.')') exit end do backspace 11 if (informat.eq.1) then read (11,*,err=666) x(1,nbod),x(2,nbod),x(3,nbod),v(1,nbod),v(2,nbod),v(3,nbod),s(1,nbod),s(2,nbod) else read (11,*,err=666) a,e,i,p,n,l,s(1,nbod),s(2,nbod),s(3,nbod) i = i * DEG2RAD p = (p + n) * DEG2RAD n = n * DEG2RAD temp = m(nbod) + m(1) ! Alternatively, read Cometary or asteroidal elements if (informat.eq.3) then q = a a = q / (1.d0 - e) l = mod (sqrt(temp/(abs(a*a*a))) * (epoch(nbod) - l), TWOPI) else q = a * (1.d0 - e) l = l * DEG2RAD end if if ((algor.eq.11).and.(nbod.ne.2)) temp = temp + m(2) call mco_el2x (temp,q,e,i,p,n,l,x(1,nbod),x(2,nbod),x(3,nbod),v(1,nbod),v(2,nbod),v(3,nbod)) end if s(1,nbod) = s(1,nbod) * K2 s(2,nbod) = s(2,nbod) * K2 s(3,nbod) = s(3,nbod) * K2 end do close (11) end do ! Set non-gravitational-forces flag, NGFLAG ngflag = 0 do j = 2, nbod if (ngf(1,j).ne.0.or.ngf(2,j).ne.0.or.ngf(3,j).ne.0) then if (ngflag.eq.0) ngflag = 1 if (ngflag.eq.2) ngflag = 3 else if (ngf(4,j).ne.0) then if (ngflag.eq.0) ngflag = 2 if (ngflag.eq.1) ngflag = 3 end if end do !------------------------------------------------------------------------------ ! IF CONTINUING AN OLD INTEGRATION if (oldflag) then if (opt(3).eq.1) then call mio_jd2y (time,year,month,t1) write (23,'(/,a,i10,i2,f8.5,/)') mem(62)(1:lmem(62)),year,month,t1 else if (opt(3).eq.3) then t1 = (time - tstart) / 365.25d0 write (23,'(/,a,f18.7,a,/)') mem(62)(1:lmem(62)),t1,mem(2)(1:lmem(2)) else if (opt(3).eq.0) t1 = time if (opt(3).eq.2) t1 = time - tstart write (23,'(/,a,f18.5,a,/)') mem(62)(1:lmem(62)),t1,mem(1)(1:lmem(1)) end if ! Read in energy and angular momentum variables, and convert to internal units open (35, file=dumpfile(4), status='old', iostat=error) if (error /= 0) then write (*,'(/,2a)') " ERROR: Programme terminated. Unable to open ",trim(dumpfile(4)) stop end if read (35,*) opflag read (35,*) en(1),am(1),en(3),am(3) en(1) = en(1) * K2 en(3) = en(3) * K2 am(1) = am(1) * K2 am(3) = am(3) * K2 read (35,*) s(1,1),s(2,1),s(3,1) s(1,1) = s(1,1) * K2 s(2,1) = s(2,1) * K2 s(3,1) = s(3,1) * K2 close (35) if (opflag.eq.0) opflag = 1 !------------------------------------------------------------------------------ ! IF STARTING A NEW INTEGRATION else opflag = -2 ! Write integration parameters to information file write (23,'(/,a)') mem(11)(1:lmem(11)) write (23,'(a)') mem(12)(1:lmem(12)) j = algor + 13 write (23,'(/,2a)') mem(13)(1:lmem(13)),mem(j)(1:lmem(j)) if ((tstart.ge.1.d11).or.(tstart.le.-1.d10)) then write (23,'(/,a,1p,e19.13,a)') mem(26)(1:lmem(26)),tstart,mem(1)(1:lmem(1)) else write (23,'(/,a,f19.7,a)') mem(26)(1:lmem(26)),tstart,mem(1)(1:lmem(1)) end if if (tstop.ge.1.d11.or.tstop.le.-1.d10) then write (23,'(a,1p,e19.13)') mem(27)(1:lmem(27)),tstop else write (23,'(a,f19.7)') mem(27)(1:lmem(27)),tstop end if write (23,'(a,f15.3)') mem(28)(1:lmem(28)),dtout if (opt(4).eq.1) write (23,'(2a)') mem(40)(1:lmem(40)),mem(7)(1:lmem(7)) if (opt(4).eq.2) write (23,'(2a)') mem(40)(1:lmem(40)),mem(8)(1:lmem(8)) if (opt(4).eq.3) write (23,'(2a)') mem(40)(1:lmem(40)),mem(9)(1:lmem(9)) write (23,'(/,a,f10.3,a)') mem(30)(1:lmem(30)),h0,mem(1)(1:lmem(1)) write (23,'(a,1p1e10.4)') mem(31)(1:lmem(31)),tol write (23,'(a,1p1e10.4,a)') mem(32)(1:lmem(32)),m(1)/K2,mem(3)(1:lmem(3)) write (23,'(a,1p1e11.4)') mem(33)(1:lmem(33)),jcen(1)/rcen**2 write (23,'(a,1p1e11.4)') mem(34)(1:lmem(34)),jcen(2)/rcen**4 write (23,'(a,1p1e11.4)') mem(35)(1:lmem(35)),jcen(3)/rcen**6 write (23,'(a,1p1e10.4,a)') mem(36)(1:lmem(36)),rmax,mem (4)(1:lmem(4)) write (23,'(a,1p1e10.4,a)') mem(37)(1:lmem(37)),rcen,mem (4)(1:lmem(4)) itmp = 5 if (opt(2).eq.1.or.opt(2).eq.2) itmp = 6 write (23,'(/,2a)') mem(41)(1:lmem(41)),mem(itmp)(1:lmem(itmp)) itmp = 5 if (opt(2).eq.2) itmp = 6 write (23,'(2a)') mem(42)(1:lmem(42)),mem(itmp)(1:lmem(itmp)) itmp = 5 if (opt(7).eq.1) itmp = 6 write (23,'(2a)') mem(45)(1:lmem(45)),mem(itmp)(1:lmem(itmp)) itmp = 5 if (opt(8).eq.1) itmp = 6 write (23,'(2a)') mem(46)(1:lmem(46)),mem(itmp)(1:lmem(itmp)) ! Check that element and close-encounter files don't exist, and create them do j = 1, 2 inquire (file=outfile(j), exist=test) if (test) call mio_err (23,mem(81),lmem(81),mem(87),lmem(87),' ',1,outfile(j),80) open (20+j, file=outfile(j), status='new', iostat=error) if (error /= 0) then write (*,'(/,2a)') " ERROR: Programme terminated. Unable to open ",trim(outfile(j)) stop end if close (20+j) end do ! Check that dump files don't exist, and then create them do j = 1, 4 inquire (file=dumpfile(j), exist=test) if (test) call mio_err (23,mem(81),lmem(81),mem(87),lmem(87),' ',1,dumpfile(j),80) open (30+j, file=dumpfile(j), status='new', iostat=error) if (error /= 0) then write (*,'(/,2a)') " ERROR: Programme terminated. Unable to open ",trim(dumpfile(j)) stop end if close (30+j) end do ! Write number of Big bodies and Small bodies to information file write (23,'(/,a,i4)') mem(38)(1:lmem(38)), nbig - 1 write (23,'(a,i4)') mem(39)(1:lmem(39)), nbod - nbig ! Calculate initial energy and angular momentum and write to information file s(1,1) = 0.d0 s(2,1) = 0.d0 s(3,1) = 0.d0 call mxx_en (jcen,nbod,nbig,m,x,v,s,en(1),am(1)) write (23,'(//,a)') mem(51)(1:lmem(51)) write (23,'(a)') mem(52)(1:lmem(52)) write (23,'(/,a,1p1e12.5,a)') mem(53)(1:lmem(53)),en(1)/K2,mem(72)(1:lmem(72)) write (23,'(a,1p1e12.5,a)') mem(54)(1:lmem(54)),am(1)/K2,mem(73)(1:lmem(73)) ! Initialize lost energy and angular momentum en(3) = 0.d0 am(3) = 0.d0 ! Write warning messages if necessary if (tstop.lt.tstart) write (23,'(/,2a)') mem(121)(1:lmem(121)),mem(123)(1:lmem(123)) if (nbig.le.0) write (23,'(/,2a)') mem(121)(1:lmem(121)),mem(124)(1:lmem(124)) if (nbig.eq.nbod) write (23,'(/,2a)') mem(121)(1:lmem(121)),mem(125)(1:lmem(125)) end if !------------------------------------------------------------------------------ ! CHECK FOR ATTEMPTS TO DO INCOMPATIBLE THINGS ! If using close-binary algorithm, set radius of central body to be no less ! than the periastron of binary star. if (algor.eq.11) then temp = m(1) + m(2) call mco_x2el (temp,x(1,2),x(2,2),x(3,2),v(1,2),v(2,2),v(3,2),a,tmp2,tmp3,tmp4,tmp5,tmp6) rcen = max (rcen, a) end if ! Check if non-grav forces are being used with an incompatible algorithm if ((ngflag.ne.0).and.((algor.eq.3).or.(algor.eq.11).or.(algor.eq.12))) then call mio_err (23,mem(81),lmem(81),mem(92),lmem(92),' ',1,mem(85),lmem(85)) endif ! Check if user-defined force routine is being used with wrong algorithm if ((opt(8).eq.1).and.((algor.eq.11).or.(algor.eq.12))) call mio_err(23,mem(81),lmem(81),mem(93),lmem(93),' ',1,mem(85),lmem(85)) ! Check whether MVS is being used to integrate massive Small bodies, ! or whether massive Small bodies have different epochs than Big bodies. flag1 = .false. flag2 = .false. do j = nbig + 1, nbod if (m(j).ne.0) then if (algor.eq.1) call mio_err (23,mem(81),lmem(81),mem(94),lmem(94),' ',1,mem(85),lmem(85)) flag1 = .true. end if if (epoch(j).ne.time) flag2 = .true. end do if (flag1.and.flag2) call mio_err (23,mem(81),lmem(81),mem(95), lmem(95),' ',1,mem(84),lmem(84)) ! Check if central oblateness is being used with close-binary algorithm if (algor.eq.11.and.(jcen(1).ne.0.or.jcen(2).ne.0.or.jcen(3).ne.0)) then call mio_err (23,mem(81),lmem(81),mem(102),lmem(102),' ',1,mem(85),lmem(85)) endif ! Check whether RCEN > RMAX or RMAX/RCEN is very large if (rcen.gt.rmax) call mio_err (23,mem(81),lmem(81),mem(105),lmem(105),' ',1,mem(85),lmem(85)) if (rmax/rcen.ge.1.d12) write (23,'(/,2a,/a)') mem(121)(1:lmem(121)),mem(106)(1:lmem(106)),mem(85)(1:lmem(85)) close (23) return ! Error reading from the input file containing integration parameters 661 write (c3,'(i3)') lineno call mio_err (23,mem(81),lmem(81),mem(99),lmem(99),c3,3,mem(85),lmem(85)) ! Error reading from the input file for Big or Small bodies 666 call mio_err (23,mem(81),lmem(81),mem(100),lmem(100),id(nbod),8,mem(82+j),lmem(82+j)) ! Error reading epoch of Big bodies 667 call mio_err (23,mem(81),lmem(81),mem(101),lmem(101),' ',1,mem(83),lmem(83)) !------------------------------------------------------------------------------ ! ##K## ! Always initialize the variable array STAT for all bodies with 0. !------------------------------------------------------------------------------ do j = 2, nbod stat(j) = 0 end do !------------------------------------------------------------------------------ ! ##K## !------------------------------------------------------------------------------ end subroutine mio_in !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% !> @author !> <NAME> ! !> @date 4 March 2001 ! ! DESCRIPTION: !> @brief Does an integration using a variable-timestep integration algorithm. The !! particular integrator routine is ONESTEP and the algorithm must use !! coordinates with respect to the central body. !> @note This routine is also called by the synchronisation routine mxx_sync, !! in which case OPFLAG = -2. Beware when making changes involving OPFLAG. ! !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% subroutine mal_hvar (time,h0,tol,jcen,rcen,en,am,cefac,ndump,nfun,nbod,nbig,m,xh,vh,s,rho,rceh,stat,& id,ngf,opflag,ngflag,onestep,m_x) use dynamic implicit none ! Input integer, intent(in) :: ngflag !< [in] do any bodies experience non-grav. forces? !!\n ( 0 = no non-grav forces) !!\n 1 = cometary jets only !!\n 2 = radiation pressure/P-R drag only !!\n 3 = both integer, intent(in) :: ndump integer, intent(in) :: nfun real(double_precision), intent(in) :: h0 !< [in] initial integration timestep (days) real(double_precision), intent(in) :: tol !< [in] Integrator tolerance parameter (approx. error per timestep) real(double_precision), intent(in) :: jcen(3) !< [in] J2,J4,J6 for central body (units of RCEN^i for Ji) real(double_precision), intent(in) :: rcen !< [in] radius of central body (AU) real(double_precision), intent(in) :: cefac ! Input/Output integer, intent(inout) :: opflag !< [in,out] integration mode (-2 = synchronising epochs) !!\n -1 = integrating towards start epoch !!\n 0 = main integration, normal output !!\n 1 = main integration, full output integer, intent(inout) :: nbod !< [in,out] current number of bodies (INCLUDING the central object) integer, intent(inout) :: nbig !< [in,out] current number of big bodies (ones that perturb everything else) integer, intent(inout) :: stat(nbod) !< [in,out] status (0 => alive, <>0 => to be removed) real(double_precision), intent(inout) :: time !< [in,out] current epoch (days) real(double_precision), intent(inout) :: en(3) !< [in,out] (initial energy, current energy, energy change due to collision and ejection) of the system real(double_precision), intent(inout) :: am(3) !< [in,out] (initial angular momentum, current angular momentum, !! angular momentum change due to collision and ejection) of the system real(double_precision), intent(inout) :: m(nbod) !< [in,out] mass (in solar masses * K2) real(double_precision), intent(inout) :: m_x(nbod) !< [in,out] mass of element X (in solar masses * K2) real(double_precision), intent(inout) :: xh(3,nbod) !< [in,out] coordinates (x,y,z) with respect to the central body (AU) real(double_precision), intent(inout) :: vh(3,nbod) !< [in,out] velocities (vx,vy,vz) with respect to the central body (AU/day) real(double_precision), intent(inout) :: s(3,nbod) !< [in,out] spin angular momentum (solar masses AU^2/day) real(double_precision), intent(inout) :: rho(nbod) !< [in,out] physical density (g/cm^3) real(double_precision), intent(inout) :: rceh(nbod) !< [in,out] close-encounter limit (Hill radii) real(double_precision), intent(inout) :: ngf(4,nbod) !< [in,out] non gravitational forces parameters !! \n(1-3) cometary non-gravitational (jet) force parameters !! \n(4) beta parameter for radiation pressure and P-R drag character(len=8), intent(inout) :: id(nbod) !< [in,out] name of the object (8 characters) ! Local integer :: i,j,k,n,itmp,nhit,ihit(CMAX),jhit(CMAX),chit(CMAX),im integer :: dtflag,ejflag,nowflag,stopflag,nstored,ce(nb_bodies_initial) integer :: nclo,iclo(CMAX),jclo(CMAX),nce,ice(CMAX),jce(CMAX) real(double_precision) :: tmp0,h,hdid,tout,tfun,tlog,tsmall real(double_precision) :: thit(CMAX),dhit(CMAX),thit1,x0(3,nb_bodies_initial),v0(3,nb_bodies_initial) real(double_precision) :: rce(nb_bodies_initial),rphys(nb_bodies_initial),rcrit(nb_bodies_initial),a(nb_bodies_initial) real(double_precision) :: dclo(CMAX),tclo(CMAX),epoch(nb_bodies_initial) real(double_precision) :: ixvclo(6,CMAX),jxvclo(6,CMAX) external onestep !------------------------------------------------------------------------------ ! Initialize variables. DTFLAG = 0 implies first ever call to ONESTEP dtout = abs(dtout) dtdump = abs(h0) * dfloat(ndump) dtfun = abs(h0) * dfloat(nfun) dtflag = 0 nstored = 0 tsmall = h0 * 1.d-8 h = h0 do j = 2, nbod ce(j) = 0 end do ! Calculate close-encounter limits and physical radii for massive bodies call mce_init (h0,jcen,rcen,cefac,nbod,nbig,m,xh,vh,s,rho,rceh,rphys,rce,rcrit,id,outfile(2),1,m_x) ! Set up time of next output, times of previous dump, log and periodic effect if (opflag.eq.-1) then tout = tstart else n = int (abs (time - tstart) / dtout) + 1 tout = tstart + dtout * sign (dble(n), tstop - tstart) if ((tstop - tstart)*(tout - tstop).gt.0) tout = tstop end if tdump = time tfun = time tlog = time !------------------------------------------------------------------------------ ! MAIN LOOP STARTS HERE do ! Is it time for output ? if (abs(tout-time).lt.abs(tsmall).and.opflag.ge.-1) then ! Beware: the integration may change direction at this point!!! if (opflag.eq.-1) dtflag = 0 ! Output data for all bodies call mio_out (time,jcen,rcen,nbod,nbig,m,xh,vh,s,rho,stat,id,opflag,outfile(1),m_x) call mio_ce (time,rcen,nbod,nbig,m,stat,id,0,iclo,jclo,stopflag,tclo,dclo,ixvclo,jxvclo,& nstored,0) tmp0 = tstop - tout tout = tout + sign( min( abs(tmp0), abs(dtout) ), tmp0 ) ! Update the data dump files do j = 2, nbod epoch(j) = time end do call mio_dump (time,h,tol,jcen,rcen,en,am,cefac,ndump,nfun,nbod,nbig,m,xh,vh,s,rho,rceh,stat,& id,ngf,epoch,opflag,m_x) tdump = time end if ! If integration has finished return to the main part of programme if (abs(tstop-time).le.abs(tsmall).and.opflag.ne.-1) return ! Set the timestep if (opflag.eq.-1) tmp0 = tstart - time if (opflag.eq.-2) tmp0 = tstop - time if (opflag.ge.0) tmp0 = tout - time h = sign ( max( min( abs(tmp0), abs(h) ), tsmall), tmp0 ) ! Save the current coordinates and velocities !~ x0(:,:) = xh(:,:) !~ v0(:,:) = vh(:,:) call mco_iden (time,jcen,nbod,nbig,h,m,xh,vh,x0,v0,ngf,ngflag) ! Advance one timestep call onestep (time,h,hdid,tol,jcen,nbod,nbig,m,xh,vh,s,rphys,rcrit,ngf,stat,dtflag,ngflag,nce,ice,jce,mfo_all) time = time + hdid ! pebble accretion for B-S method if (opt(9) == 1) then call pebbleaccretion(time,hdid,nbig,m,xh,vh,rphys,rho,m_x) end if ! gas accretion for B-S method if (opt(14) == 1) then call gasaccretion(time,hdid,nbig,m,xh,vh,rphys,rho,m_x) end if ! Check if close encounters or collisions occurred nclo = 0 call mce_stat (time,h,rcen,nbod,nbig,m,x0,v0,xh,vh,rce,rphys,nclo,iclo,jclo,dclo,tclo,ixvclo,jxvclo,nhit,ihit,jhit,chit,dhit,& thit,thit1,nowflag,stat,outfile(3)) !------------------------------------------------------------------------------ ! CLOSE ENCOUNTERS ! If encounter minima occurred, output details and decide whether to stop if (nclo.gt.0.and.opflag.ge.-1) then itmp = 1 if (nhit.ne.0) itmp = 0 call mio_ce (time,rcen,nbod,nbig,m,stat,id,nclo,iclo,jclo,stopflag,tclo,dclo,ixvclo,jxvclo,nstored,itmp) if (stopflag.eq.1) return end if !------------------------------------------------------------------------------ ! COLLISIONS ! If a collision occurred, output details and resolve the collision if (nhit.gt.0.and.opt(2).ne.0) then do k = 1, nhit if (chit(k).eq.1) then i = ihit(k) j = jhit(k) ! print*,'before time ',time/365.25d0 ! print*,'before m ', time,m/K2,m_x/K2 ! print*,'before r ', rphys ! print*,'before d ', rho/498. ! print*,'before rce', rce call mce_coll (thit(k),en(3),jcen,i,j,nbod,nbig,m,xh,vh,s,rphys,stat,id,outfile(3),m_x,rho) ! print*,'after time ',time/365.25d0 ! print*,'after m ', m/K2,m_x/K2 ! print*,'after r ', rphys ! print*,'after d ', rho/498. ! print*,'after rce', rce end if end do ! Remove lost objects, reset flags and recompute Hill and physical radii call mxx_elim (nbod,nbig,m,xh,vh,s,rho,rceh,rcrit,ngf,stat,id,outfile(3),itmp,m_x) dtflag = 1 if (opflag.ge.0) opflag = 1 ! at right now only change the mass and density of the planet, not change the radius, radius is calculated in mce_init call mce_init (h0,jcen,rcen,cefac,nbod,nbig,m,xh,vh,s,rho,rceh,rphys,rce,rcrit,id,outfile(2),1,m_x) end if !------------------------------------------------------------------------------ ! COLLISIONS WITH CENTRAL BODY ! Check for collisions call mce_cent (time,hdid,rcen,jcen,2,nbod,nbig,m,x0,v0,xh,vh,nhit,jhit,thit,dhit,ngf,ngflag) ! Resolve the collisions if (nhit.gt.0) then do k = 1, nhit i = 1 j = jhit(k) call mce_coll (thit(k),en(3),jcen,i,j,nbod,nbig,m,xh,vh,s,rphys,stat,id,outfile(3),m_x,rho) end do ! Remove lost objects, reset flags and recompute Hill and physical radii call mxx_elim (nbod,nbig,m,xh,vh,s,rho,rceh,rcrit,ngf,stat,id,outfile(3),itmp, m_x) dtflag = 1 if (opflag.ge.0) opflag = 1 call mce_init (h0,jcen,rcen,cefac,nbod,nbig,m,xh,vh,s,rho,rceh,rphys,rce,rcrit,id,outfile(2),0,m_x) end if !------------------------------------------------------------------------------ ! DATA DUMP AND PROGRESS REPORT ! Do the data dump if (abs(time-tdump).ge.abs(dtdump).and.opflag.ge.-1) then do j = 2, nbod epoch(j) = time end do call mio_ce (time,rcen,nbod,nbig,m,stat,id,0,iclo,jclo,stopflag,tclo,dclo,ixvclo,jxvclo,& nstored,0) call mio_dump (time,h,tol,jcen,rcen,en,am,cefac,ndump,nfun,nbod,nbig,m,xh,vh,s,rho,rceh,stat,& id,ngf,epoch,opflag,m_x) tdump = time end if ! Write a progress report to the log file if (abs(time-tlog).ge.abs(dtdump).and.opflag.ge.0) then call mxx_en (jcen,nbod,nbig,m,xh,vh,s,en(2),am(2)) call mio_log (time,en,am) tlog = time end if !------------------------------------------------------------------------------ ! CHECK FOR EJECTIONS AND DO OTHER PERIODIC EFFECTS if (abs(time-tfun).ge.abs(dtfun).and.opflag.ge.-1) then ! Recompute close encounter limits, to allow for changes in Hill radii call mce_hill (nbod,m,xh,vh,rce,a) do j = 2, nbod rce(j) = rce(j) * rceh(j) end do ! Check for ejections call mxx_ejec (time,en,am,jcen,2,nbod,nbig,m,xh,vh,s,stat,id,ejflag,outfile(3)) ! Remove lost objects, reset flags and recompute Hill and physical radii if (ejflag.ne.0) then call mxx_elim (nbod,nbig,m,xh,vh,s,rho,rceh,rcrit,ngf,stat,id,outfile(3),itmp, m_x) dtflag = 1 if (opflag.ge.0) opflag = 1 call mce_init (h0,jcen,rcen,cefac,nbod,nbig,m,xh,vh,s,rho,rceh,rphys,rce,rcrit,id,outfile(2),0,m_x) end if tfun = time end if ! Go on to the next time step end do !------------------------------------------------------------------------------ end subroutine mal_hvar !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% !> @author !> <NAME> ! !> @date 28 March 2001 ! ! DESCRIPTION: !> @brief Does an integration using an integrator with a constant stepsize H. !! Input and output to this routine use coordinates XH, and velocities VH, !! with respect to the central body, but the integration algorithm uses !! its own internal coordinates X, and velocities V. !!\n\n !! The programme uses the transformation routines COORD and BCOORD to change !! to and from the internal coordinates, respectively. ! !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% subroutine mal_hcon (time,h0,tol,jcen,rcen,en,am,cefac,ndump,nfun,nbod,nbig,m,xh,vh,s,rho,rceh,stat,& id,ngf,opflag,ngflag,onestep,coord,bcoord,m_x) use dynamic implicit none ! Input integer, intent(in) :: ngflag !< [in] do any bodies experience non-grav. forces? !!\n ( 0 = no non-grav forces) !!\n 1 = cometary jets only !!\n 2 = radiation pressure/P-R drag only !!\n 3 = both integer, intent(in) :: ndump integer, intent(in) :: nfun real(double_precision), intent(in) :: tol !< [in] Integrator tolerance parameter (approx. error per timestep) real(double_precision), intent(in) :: jcen(3) !< [in] J2,J4,J6 for central body (units of RCEN^i for Ji) real(double_precision), intent(in) :: rcen !< [in] radius of central body (AU) real(double_precision), intent(in) :: cefac ! Input/Output integer, intent(inout) :: nbod !< [in,out] current number of bodies (INCLUDING the central object) integer, intent(inout) :: nbig !< [in,out] current number of big bodies (ones that perturb everything else) integer, intent(inout) :: stat(nbod) !< [in,out] status (0 => alive, <>0 => to be removed) integer, intent(inout) :: opflag !< [in,out] integration mode (-2 = synchronising epochs) !!\n -1 = integrating towards start epoch !!\n 0 = main integration, normal output !!\n 1 = main integration, full output real(double_precision), intent(inout) :: time !< [in,out] current epoch (days) real(double_precision), intent(inout) :: h0 !< [in,out] initial integration timestep (days) real(double_precision), intent(inout) :: en(3) !< [in,out] (initial energy, current energy, energy change due to collision and ejection) of the system real(double_precision), intent(inout) :: am(3) !< [in,out] (initial angular momentum, current angular momentum, !! angular momentum change due to collision and ejection) of the system real(double_precision), intent(inout) :: m(nbod) !< [in,out] mass (in solar masses * K2) real(double_precision), intent(inout) :: m_x(nbod) !< [in,out] mass of element X(in solar masses * K2) real(double_precision), intent(inout) :: xh(3,nbod) !< [in,out] coordinates (x,y,z) with respect to the central body (AU) real(double_precision), intent(inout) :: vh(3,nbod) !< [in,out] velocities (vx,vy,vz) with respect to the central body (AU/day) real(double_precision), intent(inout) :: s(3,nbod) !< [in,out] spin angular momentum (solar masses AU^2/day) real(double_precision), intent(inout) :: rho(nbod) !< [in,out] physical density (g/cm^3) real(double_precision), intent(inout) :: rceh(nbod) !< [in,out] close-encounter limit (Hill radii) real(double_precision), intent(inout) :: ngf(4,nbod) !< [in,out] non gravitational forces parameters !! \n(1-3) cometary non-gravitational (jet) force parameters !! \n(4) beta parameter for radiation pressure and P-R drag character(len=8), intent(inout) :: id(nbod) !< [in,out] name of the object (8 characters) ! Local integer :: i,j,k,n,itmp,nclo,nhit,jhit(CMAX),iclo(CMAX),jclo(CMAX),im integer :: dtflag,ejflag,stopflag,colflag,nstored real(double_precision) :: x(3,nb_bodies_initial),v(3,nb_bodies_initial),xh0(3,nb_bodies_initial),vh0(3,nb_bodies_initial) real(double_precision) :: rce(nb_bodies_initial),rphys(nb_bodies_initial),rcrit(nb_bodies_initial),epoch(nb_bodies_initial) real(double_precision) :: hby2,tout,tmp0,tfun,tlog real(double_precision) :: dclo(CMAX),tclo(CMAX),dhit(CMAX),thit(CMAX) real(double_precision) :: ixvclo(6,CMAX),jxvclo(6,CMAX),a(nb_bodies_initial) external onestep,coord,bcoord !------------------------------------------------------------------------------ ! Initialize variables. DTFLAG = 0/2: first call ever/normal dtout = abs(dtout) dtdump = abs(h0) * dfloat(ndump) dtfun = abs(h0) * dfloat(nfun) dtflag = 0 nstored = 0 hby2 = 0.500001d0 * abs(h0) ! Calculate close-encounter limits and physical radii call mce_init (h0,jcen,rcen,cefac,nbod,nbig,m,xh,vh,s,rho,rceh,rphys,rce,rcrit,id,outfile(2),1,m_x) ! Set up time of next output, times of previous dump, log and periodic effect if (opflag.eq.-1) then tout = tstart else n = int (abs (time-tstart) / dtout) + 1 tout = tstart + dtout * sign (dble(n), tstop - tstart) if ((tstop-tstart)*(tout-tstop).gt.0) tout = tstop end if tdump = time tfun = time tlog = time ! Convert to internal coordinates and velocities call coord (time,jcen,nbod,nbig,h0,m,xh,vh,x,v,ngf,ngflag) !------------------------------------------------------------------------------ ! MAIN LOOP STARTS HERE do ! Is it time for output ? if (abs(tout-time).le.hby2.and.opflag.ge.-1) then ! Beware: the integration may change direction at this point!!! if ((opflag.eq.-1).and.(dtflag.ne.0)) dtflag = 1 ! Convert to heliocentric coordinates and output data for all bodies call bcoord (time,jcen,nbod,nbig,h0,m,x,v,xh,vh,ngf,ngflag) call mio_out (time,jcen,rcen,nbod,nbig,m,xh,vh,s,rho,stat,id,opflag,outfile(1),m_x) call mio_ce (time,rcen,nbod,nbig,m,stat,id,0,iclo,jclo,stopflag,tclo,dclo,ixvclo,jxvclo,nstored,0) tmp0 = tstop - tout tout = tout + sign( min( abs(tmp0), abs(dtout) ), tmp0 ) ! Update the data dump files do j = 2, nbod epoch(j) = time end do call mio_dump (time,h0,tol,jcen,rcen,en,am,cefac,ndump,nfun,nbod,nbig,m,xh,vh,s,rho,rceh,stat,id,ngf,epoch,opflag,m_x) tdump = time end if ! If integration has finished, convert to heliocentric coords and return if (abs(tstop-time).le.hby2.and.opflag.ge.0) then call bcoord (time,jcen,nbod,nbig,h0,m,x,v,xh,vh,ngf,ngflag) return end if ! Make sure the integration is heading in the right direction ! The timestep will be redo if there are collisions with central body. Else, we exit the loop in the last 'if' statement. do tmp0 = tstop - time if (opflag.eq.-1) tmp0 = tstart - time h0 = sign (h0, tmp0) ! Save the current heliocentric coordinates and velocities if (algor.eq.1) then !~ xh0(:,:) = x(:,:) !~ vh0(:,:) = v(:,:) call mco_iden (time,jcen,nbod,nbig,h0,m,x,v,xh0,vh0,ngf,ngflag) else call bcoord(time,jcen,nbod,nbig,h0,m,x,v,xh0,vh0,ngf,ngflag) end if call onestep (time,h0,tol,en,am,jcen,rcen,nbod,nbig,m,x,v,s,rphys,rcrit,rce,stat,id,ngf,dtflag,& ngflag,opflag,colflag,nclo,iclo,jclo,dclo,tclo,ixvclo,jxvclo) time = time + h0 !------------------------------------------------------------------------------ ! pebble accretion for hybrid method if (opt(9) == 1) then call pebbleaccretion(time,h0,nbod,m,x,v,rphys,rho,m_x) end if ! gas accretion for hybrid method if (opt(14) == 1) then call gasaccretion(time,h0,nbod,m,x,v,rphys,rho,m_x) end if ! CLOSE ENCOUNTERS ! If encounter minima occurred, output details and decide whether to stop if ((nclo.gt.0).and.(opflag.ge.-1)) then itmp = 1 if (colflag.ne.0) itmp = 0 call mio_ce (time,rcen,nbod,nbig,m,stat,id,nclo,iclo,jclo,stopflag,tclo,dclo,ixvclo,jxvclo,nstored,itmp) if (stopflag.eq.1) return end if !------------------------------------------------------------------------------ ! COLLISIONS ! If collisions occurred, output details and remove lost objects if (colflag.ne.0) then ! Reindex the surviving objects call bcoord (time,jcen,nbod,nbig,h0,m,x,v,xh,vh,ngf,ngflag) call mxx_elim (nbod,nbig,m,xh,vh,s,rho,rceh,rcrit,ngf,stat,id,outfile(3),itmp,m_x) ! Reset flags, and calculate new Hill radii and physical radii dtflag = 1 if (opflag.ge.0) opflag = 1 call mce_init (h0,jcen,rcen,cefac,nbod,nbig,m,xh,vh,s,rho,rceh,rphys,rce,rcrit,id,outfile(2),1,m_x) call coord (time,jcen,nbod,nbig,h0,m,xh,vh,x,v,ngf,ngflag) end if !------------------------------------------------------------------------------ ! COLLISIONS WITH CENTRAL BODY ! Check for collisions with the central body if (algor.eq.1) then !~ xh(:,:) = x(:,:) !~ vh(:,:) = v(:,:) call mco_iden(time,jcen,nbod,nbig,h0,m,x,v,xh,vh,ngf,ngflag) else call bcoord (time,jcen,nbod,nbig,h0,m,x,v,xh,vh,ngf,ngflag) end if itmp = 2 if ((algor.eq.11).or.(algor.eq.12)) itmp = 3 call mce_cent (time,h0,rcen,jcen,itmp,nbod,nbig,m,xh0,vh0,xh,vh,nhit,jhit,thit,dhit,ngf,ngflag) ! If something hit the central body, restore the coords prior to this step if (nhit.eq.0) then exit else ! Redo that integration time step !~ xh(:,:) = xh0(:,:) !~ vh(:,:) = vh0(:,:) call mco_iden (time,jcen,nbod,nbig,h0,m,xh0,vh0,xh,vh,ngf,ngflag) time = time - h0 ! Merge the object(s) with the central body do k = 1, nhit i = 1 j = jhit(k) call mce_coll (thit(k),en(3),jcen,i,j,nbod,nbig,m,xh,vh,s,rphys,stat,id,outfile(3),m_x,rho) end do ! Remove lost objects, reset flags and recompute Hill and physical radii call mxx_elim (nbod,nbig,m,xh,vh,s,rho,rceh,rcrit,ngf,stat,id,outfile(3),itmp,m_x) if (opflag.ge.0) opflag = 1 dtflag = 1 call mce_init (h0,jcen,rcen,cefac,nbod,nbig,m,xh,vh,s,rho,rceh,rphys,rce,rcrit,id,outfile(2),0,m_x) if (algor.eq.1) then !~ x(:,:) = xh(:,:) !~ v(:,:) = vh(:,:) call mco_iden (time,jcen,nbod,nbig,h0,m,xh,vh,x,v,ngf,ngflag) else call coord (time,jcen,nbod,nbig,h0,m,xh,vh,x,v,ngf,ngflag) end if end if end do !------------------------------------------------------------------------------ ! DATA DUMP AND PROGRESS REPORT ! Convert to heliocentric coords and do the data dump if (abs(time-tdump).ge.abs(dtdump).and.opflag.ge.-1) then call bcoord (time,jcen,nbod,nbig,h0,m,x,v,xh,vh,ngf,ngflag) do j = 2, nbod epoch(j) = time end do call mio_ce (time,rcen,nbod,nbig,m,stat,id,0,iclo,jclo,stopflag,tclo,dclo,ixvclo,jxvclo,& nstored,0) call mio_dump (time,h0,tol,jcen,rcen,en,am,cefac,ndump,nfun,nbod,nbig,m,xh,vh,s,rho,rceh,& stat,id,ngf,epoch,opflag,m_x) tdump = time end if ! Convert to heliocentric coords and write a progress report to the log file if (abs(time-tlog).ge.abs(dtdump).and.opflag.ge.0) then call bcoord (time,jcen,nbod,nbig,h0,m,x,v,xh,vh,ngf,ngflag) call mxx_en (jcen,nbod,nbig,m,xh,vh,s,en(2),am(2)) call mio_log (time,en,am) tlog = time end if !------------------------------------------------------------------------------ ! CHECK FOR EJECTIONS AND DO OTHER PERIODIC EFFECTS if (abs(time-tfun).ge.abs(dtfun).and.opflag.ge.-1) then if (algor.eq.1) then !~ xh(:,:) = x(:,:) !~ vh(:,:) = v(:,:) call mco_iden (time,jcen,nbod,nbig,h0,m,x,v,xh,vh,ngf,ngflag) else call bcoord(time,jcen,nbod,nbig,h0,m,x,v,xh,vh,ngf,ngflag) end if ! Recompute close encounter limits, to allow for changes in Hill radii call mce_hill (nbod,m,xh,vh,rce,a) do j = 2, nbod rce(j) = rce(j) * rceh(j) end do ! Check for ejections itmp = 2 if ((algor.eq.11).or.(algor.eq.12)) itmp = 3 call mxx_ejec (time,en,am,jcen,itmp,nbod,nbig,m,xh,vh,s,stat,id,ejflag,outfile(3)) ! Remove ejected objects, reset flags, calculate new Hill and physical radii if (ejflag.ne.0) then call mxx_elim (nbod,nbig,m,xh,vh,s,rho,rceh,rcrit,ngf,stat,id,outfile(3),itmp,m_x) if (opflag.ge.0) opflag = 1 dtflag = 1 call mce_init (h0,jcen,rcen,cefac,nbod,nbig,m,xh,vh,s,rho,rceh,rphys,rce,rcrit,id,outfile(2),0,m_x) if (algor.eq.1) then !~ x(:,:) = xh(:,:) !~ v(:,:) = vh(:,:) call mco_iden (time,jcen,nbod,nbig,h0,m,xh,vh,x,v,ngf,ngflag) else call coord (time,jcen,nbod,nbig,h0,m,xh,vh,x,v,ngf,ngflag) end if end if tfun = time end if ! Go on to the next time step end do !------------------------------------------------------------------------------ end subroutine mal_hcon !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% !> @author !> <NAME> ! !> @date 2 March 2001 ! ! DESCRIPTION: !> @brief Synchronizes the epochs of NBIG Big bodies (having a common epoch) and !! NBOD-NBIG Small bodies (possibly having differing epochs), for an !! integration using MERCURY. !! The Small bodies are picked up in order starting with the one with epoch !! furthest from the time, TSTART, at which the main integration will begin !! producing output. ! @note The synchronization integrations use Everhart's RA15 routine. ! !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% subroutine mxx_sync (time,h0,tol,jcen,nbod,nbig,m,x,v,s,rho,rceh,stat,id,epoch,ngf,ngflag) implicit none ! Input integer, intent(in) :: nbod !< [in] current number of bodies (1: star; 2-nbig: big bodies; nbig+1-nbod: small bodies) integer, intent(in) :: nbig !< [in] current number of big bodies (ones that perturb everything else) integer, intent(in) :: ngflag !< [in] do any bodies experience non-grav. forces? !!\n ( 0 = no non-grav forces) !!\n 1 = cometary jets only !!\n 2 = radiation pressure/P-R drag only !!\n 3 = both real(double_precision), intent(in) :: h0 !< [in] initial integration timestep (days) real(double_precision), intent(in) :: tol !< [in] Integrator tolerance parameter (approx. error per timestep) real(double_precision), intent(in) :: jcen(3) !< [in] J2,J4,J6 for central body (units of RCEN^i for Ji) real(double_precision), intent(in) :: ngf(4,nbod) !< [in] non gravitational forces parameters !! \n(1-3) cometary non-gravitational (jet) force parameters !! \n(4) beta parameter for radiation pressure and P-R drag ! Input/Output integer, intent(inout) :: stat(nbod) !< [in,out] status (0 => alive, <>0 => to be removed) real(double_precision), intent(inout) :: time !< [in,out] current epoch (days) real(double_precision), intent(inout) :: m(nbod) !< [in,out] mass (in solar masses * K2) real(double_precision), intent(inout) :: x(3,nbod) real(double_precision), intent(inout) :: v(3,nbod) real(double_precision), intent(inout) :: s(3,nbod) !< [in,out] spin angular momentum (solar masses AU^2/day) real(double_precision), intent(inout) :: rceh(nbod) !< [in,out] close-encounter limit (Hill radii) real(double_precision), intent(inout) :: rho(nbod) !< [in,out] physical density (g/cm^3) real(double_precision), intent(inout) :: epoch(nbod) !< [in,out] epoch of orbit (days) character(len=8), intent(inout) :: id(nbod) !< [in,out] name of the object (8 characters) ! Local integer :: j,k,l,nsml,nsofar,indx(nb_bodies_initial),itemp,jtemp(nb_bodies_initial) integer :: raflag,nce,ice(CMAX),jce(CMAX) real(double_precision) :: temp,epsml(nb_bodies_initial),rtemp(nb_bodies_initial) real(double_precision) :: h,hdid,tsmall,rphys(nb_bodies_initial),rcrit(nb_bodies_initial) character(len=8) :: ctemp(nb_bodies_initial) !------------------------------------------------------------------------------ ! Reorder Small bodies by epoch so that ep(1) is furthest from TSTART nsml = nbod - nbig do j = nbig + 1, nbod epsml(j-nbig) = epoch(j) end do call mxx_sort (nsml,epsml,indx) if (abs(epsml(1)-tstart).lt.abs(epsml(nsml)-tstart)) then k = nsml + 1 do j = 1, nsml / 2 l = k - j temp = epsml(j) epsml(j) = epsml (l) epsml(l) = temp itemp = indx(j) indx(j) = indx (l) indx(l) = itemp end do end if do j = nbig + 1, nbod epoch(j) = epsml(j-nbig) end do ! Reorder the other arrays associated with each Small body do k = 1, 3 do j = 1, nsml rtemp(j) = x(k,j+nbig) end do do j = 1, nsml x(k,j+nbig) = rtemp(indx(j)) end do do j = 1, nsml rtemp(j) = v(k,j+nbig) end do do j = 1, nsml v(k,j+nbig) = rtemp(indx(j)) end do do j = 1, nsml rtemp(j) = s(k,j+nbig) end do do j = 1, nsml s(k,j+nbig) = rtemp(indx(j)) end do end do do j = 1, nsml rtemp(j) = m(j+nbig) end do do j = 1, nsml m(j+nbig) = rtemp(indx(j)) end do do j = 1, nsml rtemp(j) = rceh(j+nbig) end do do j = 1, nsml rceh(j+nbig) = rtemp(indx(j)) end do do j = 1, nsml rtemp(j) = rho(j+nbig) end do do j = 1, nsml rho(j+nbig) = rtemp(indx(j)) end do do j = 1, nsml ctemp(j) = id(j+nbig) jtemp(j) = stat(j+nbig) end do do j = 1, nsml id(j+nbig) = ctemp(indx(j)) stat(j+nbig) = jtemp(indx(j)) end do ! Integrate Small bodies up to the same epoch h = h0 tsmall = h0 * 1.d-12 raflag = 0 do j = nbig + 1, nbod nsofar = j - 1 do while (abs(time-epoch(j)).gt.tsmall) temp = epoch(j) - time h = sign(max(min(abs(temp),abs(h)),tsmall),temp) call mdt_ra15 (time,h,hdid,tol,jcen,nsofar,nbig,m,x,v,s,rphys,rcrit,ngf,stat,raflag,ngflag,nce,ice,jce,mfo_all) time = time + hdid end do raflag = 1 end do !------------------------------------------------------------------------------ return end subroutine mxx_sync end program mercury <file_sep>#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Aug 7 14:00:18 2019 @author: <NAME> """ import os import numpy as np import matplotlib.pyplot as plt from diskmodel import * from astrounit import * from labellines import labelLines from plotset import * from m6_funcs import get_disk_params #If an input file is provided, we use the given inputs from it try: sys.argv[1] except (IndexError,NameError): source = 't2migtest4' else: source = sys.argv[1] #The vars.ini file cdir = os.getcwd()#+'/' #current dir sourcedir = cdir+'/../sim/'+source+'/' pydir = cdir # python dir workdir = cdir+'/../figure/' ## in source direction, generating the aei output file os.chdir(sourcedir) _,alpha_v,mdot_gas,L_s,_,mdot_peb,st,kap,M_s,opt_vis = get_disk_params() r_trans = rtrans(mdot_gas,L_s,M_s,alpha_v,kap,opt_vis) # change into figure direction os.chdir(workdir) fig, ax = plt.subplots(figsize=(8,6)) #alpha_d = np.array([1e-3,1e-4]) alpha_d = np.logspace(-5,1,500) cols = ['tab:green','tab:blue','tab:orange'] m_gap = gap_mass(r_trans,mdot_gas,L_s,M_s,alpha_d,alpha_v,kap,opt_vis) m_iso = m_gap/2.3 m_opt = opt_mass(r_trans,mdot_gas,L_s,M_s,alpha_d,alpha_v,kap,opt_vis) ax.plot(alpha_d,m_gap,linestyle='-',color=cols[0],label='$M_\mathrm{gap}$') ax.plot(alpha_d,m_iso,linestyle='-',color=cols[1],label='$M_\mathrm{iso}$') ax.plot(alpha_d,m_opt,linestyle='-',color=cols[2],label='$M_\mathrm{opt}$') add_date(fig) ax.set_xscale('log') ax.set_yscale('log') ax.set_xlim(1e-5,1) ax.set_ylim(1,2e3) labelLines(ax.get_lines(),fontsize=12,xvals = [1e-4,1e-3,1e-2]) ax.set_xlabel(r'$\alpha_t$') ax.set_ylabel(r'$M\ \mathrm{[M}_\oplus]$') ax.set_title('$\mathrm{Mass\ limits\ at\ }r_\mathrm{trans}$')<file_sep># Nbodypps N-body code based on MERCURY6 by <NAME> written in Fortran90 used to investigate the growth of planetary embryos when including planetary migration and pebble accretion effects. Also includes a Python script that allows for comparison with an analytical disk model based on Liu (2015) and Garaud & Lin (2007). <file_sep>!****************************************************************************** ! MODULE: algo_bs1 !****************************************************************************** ! ! DESCRIPTION: !> @brief Modules that gather various functions about the BS !! algorithm.\n\n !! The Bulirsch-Stoer algorithms are described in W.H.Press et al. (1992) !! ``Numerical Recipes in Fortran'', pub. Cambridge. ! !****************************************************************************** module algo_bs1 use types_numeriques private real(double_precision), parameter :: SHRINK=.55d0 !< Multiplication factor in case we have to decrease the timestep real(double_precision), parameter :: GROW=1.3d0 !< Multiplication factor in case we can increase the timestep public :: mdt_bs1 contains !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% !> @author !> <NAME> ! !> @date 2 March 2001 ! ! DESCRIPTION: !> @brief Integrates NBOD bodies (of which NBIG are Big) for one timestep H0 !! using the Bulirsch-Stoer method. The accelerations are calculated using the !! subroutine FORCE. The accuracy of the step is approximately determined !! by the tolerance parameter TOL. ! !> @note Input/output must be in coordinates with respect to the central body. ! !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% subroutine mdt_bs1 (time,h0,hdid,tol,jcen,nbod,nbig,mass,x0,v0,s,rphys,rcrit,ngf,stat,dtflag,ngflag,nce,ice,jce,force) use physical_constant use mercury_constant use mercury_globals implicit none ! Input/Output integer, intent(in) :: nbod !< [in] current number of bodies (1: star; 2-nbig: big bodies; nbig+1-nbod: small bodies) integer, intent(in) :: nbig !< [in] current number of big bodies (ones that perturb everything else) integer, intent(in) :: stat(nbod) !< [in] status (0 => alive, <>0 => to be removed) integer, intent(in) :: dtflag integer, intent(in) :: ngflag !< [in] do any bodies experience non-grav. forces? !!\n ( 0 = no non-grav forces) !!\n 1 = cometary jets only !!\n 2 = radiation pressure/P-R drag only !!\n 3 = both integer, intent(in) :: nce integer, intent(in) :: ice(nce) integer, intent(in) :: jce(nce) real(double_precision), intent(in) :: time !< [in] current epoch (days) real(double_precision), intent(in) :: tol !< [in] Integrator tolerance parameter (approx. error per timestep) real(double_precision), intent(in) :: jcen(3) !< [in] J2,J4,J6 for central body (units of RCEN^i for Ji) real(double_precision), intent(in) :: mass(nbod) !< [in] mass (in solar masses * K2) real(double_precision), intent(in) :: s(3,nbod) !< [in] spin angular momentum (solar masses AU^2/day) real(double_precision), intent(in) :: ngf(4,nbod) !< [in] non gravitational forces parameters !! \n(1-3) cometary non-gravitational (jet) force parameters !! \n(4) beta parameter for radiation pressure and P-R drag real(double_precision), intent(in) :: rphys(nbod) real(double_precision), intent(in) :: rcrit(nbod) real(double_precision), intent(out) :: hdid real(double_precision), intent(inout) :: h0 !< [inout] initial integration timestep (days) real(double_precision), intent(inout) :: x0(3,nbod) real(double_precision), intent(inout) :: v0(3,nbod) external force ! Local integer :: j, j1, k, n real(double_precision) :: tmp0,tmp1,tmp2,errmax,tol2,h,hx2,h2(8) real(double_precision) :: x(3,nb_bodies_initial),v(3,nb_bodies_initial),xend(3,nb_bodies_initial),vend(3,nb_bodies_initial) real(double_precision) :: a(3,nb_bodies_initial),a0(3,nb_bodies_initial),d(6,nb_bodies_initial,8) real(double_precision) :: xscal(nb_bodies_initial),vscal(nb_bodies_initial) !------------------------------------------------------------------------------ tol2 = tol * tol ! Calculate arrays used to scale the relative error (R^2 for position and ! V^2 for velocity). do k = 2, nbod tmp1 = x0(1,k)*x0(1,k) + x0(2,k)*x0(2,k) + x0(3,k)*x0(3,k) tmp2 = v0(1,k)*v0(1,k) + v0(2,k)*v0(2,k) + v0(3,k)*v0(3,k) xscal(k) = 1.d0 / tmp1 vscal(k) = 1.d0 / tmp2 end do ! Calculate accelerations at the start of the step call force (time,jcen,nbod,nbig,mass,x0,v0,s,rcrit,a0,stat,ngf,ngflag,nce,ice,jce,rphys) do ! For each value of N, do a modified-midpoint integration with 2N substeps do n = 1, 8 h = h0 / (2.d0 * float(n)) h2(n) = .25d0 / (n*n) hx2 = h * 2.d0 do k = 2, nbod x(1,k) = x0(1,k) + h*v0(1,k) x(2,k) = x0(2,k) + h*v0(2,k) x(3,k) = x0(3,k) + h*v0(3,k) v(1,k) = v0(1,k) + h*a0(1,k) v(2,k) = v0(2,k) + h*a0(2,k) v(3,k) = v0(3,k) + h*a0(3,k) end do call force (time,jcen,nbod,nbig,mass,x,v,s,rcrit,a,stat,ngf,ngflag,nce,ice,jce,rphys) do k = 2, nbod xend(1,k) = x0(1,k) + hx2*v(1,k) xend(2,k) = x0(2,k) + hx2*v(2,k) xend(3,k) = x0(3,k) + hx2*v(3,k) vend(1,k) = v0(1,k) + hx2*a(1,k) vend(2,k) = v0(2,k) + hx2*a(2,k) vend(3,k) = v0(3,k) + hx2*a(3,k) end do do j = 2, n call force (time,jcen,nbod,nbig,mass,xend,vend,s,rcrit,a,stat,ngf,ngflag,nce,ice,jce,rphys) do k = 2, nbod x(1,k) = x(1,k) + hx2*vend(1,k) x(2,k) = x(2,k) + hx2*vend(2,k) x(3,k) = x(3,k) + hx2*vend(3,k) v(1,k) = v(1,k) + hx2*a(1,k) v(2,k) = v(2,k) + hx2*a(2,k) v(3,k) = v(3,k) + hx2*a(3,k) end do call force (time,jcen,nbod,nbig,mass,x,v,s,rcrit,a,stat,ngf,ngflag,nce,ice,jce,rphys) do k = 2, nbod xend(1,k) = xend(1,k) + hx2*v(1,k) xend(2,k) = xend(2,k) + hx2*v(2,k) xend(3,k) = xend(3,k) + hx2*v(3,k) vend(1,k) = vend(1,k) + hx2*a(1,k) vend(2,k) = vend(2,k) + hx2*a(2,k) vend(3,k) = vend(3,k) + hx2*a(3,k) end do end do call force (time,jcen,nbod,nbig,mass,xend,vend,s,rcrit,a,stat,ngf,ngflag,nce,ice,jce,rphys) do k = 2, nbod d(1,k,n) = .5d0*(xend(1,k) + x(1,k) + h*vend(1,k)) d(2,k,n) = .5d0*(xend(2,k) + x(2,k) + h*vend(2,k)) d(3,k,n) = .5d0*(xend(3,k) + x(3,k) + h*vend(3,k)) d(4,k,n) = .5d0*(vend(1,k) + v(1,k) + h*a(1,k)) d(5,k,n) = .5d0*(vend(2,k) + v(2,k) + h*a(2,k)) d(6,k,n) = .5d0*(vend(3,k) + v(3,k) + h*a(3,k)) end do ! Update the D array, used for polynomial extrapolation do j = n - 1, 1, -1 j1 = j + 1 tmp0 = 1.d0 / (h2(j) - h2(n)) tmp1 = tmp0 * h2(j1) tmp2 = tmp0 * h2(n) do k = 2, nbod d(1,k,j) = tmp1 * d(1,k,j1) - tmp2 * d(1,k,j) d(2,k,j) = tmp1 * d(2,k,j1) - tmp2 * d(2,k,j) d(3,k,j) = tmp1 * d(3,k,j1) - tmp2 * d(3,k,j) d(4,k,j) = tmp1 * d(4,k,j1) - tmp2 * d(4,k,j) d(5,k,j) = tmp1 * d(5,k,j1) - tmp2 * d(5,k,j) d(6,k,j) = tmp1 * d(6,k,j1) - tmp2 * d(6,k,j) end do end do ! After several integrations, test the relative error on extrapolated values if (n.gt.3) then errmax = 0.d0 ! Maximum relative position and velocity errors (last D term added) do k = 2, nbod tmp1 = max( d(1,k,1)*d(1,k,1), d(2,k,1)*d(2,k,1), d(3,k,1)*d(3,k,1) ) tmp2 = max( d(4,k,1)*d(4,k,1), d(5,k,1)*d(5,k,1), d(6,k,1)*d(6,k,1) ) errmax = max(errmax, tmp1*xscal(k), tmp2*vscal(k)) end do ! If error is smaller than TOL, update position and velocity arrays, and exit if (errmax.le.tol2) then do k = 2, nbod x0(1,k) = d(1,k,1) x0(2,k) = d(2,k,1) x0(3,k) = d(3,k,1) v0(1,k) = d(4,k,1) v0(2,k) = d(5,k,1) v0(3,k) = d(6,k,1) end do do j = 2, n do k = 2, nbod x0(1,k) = x0(1,k) + d(1,k,j) x0(2,k) = x0(2,k) + d(2,k,j) x0(3,k) = x0(3,k) + d(3,k,j) v0(1,k) = v0(1,k) + d(4,k,j) v0(2,k) = v0(2,k) + d(5,k,j) v0(3,k) = v0(3,k) + d(6,k,j) end do end do ! Save the actual stepsize used hdid = h0 ! Recommend a new stepsize for the next call to this subroutine if (n.eq.8) h0 = h0 * SHRINK if (n.lt.7) h0 = h0 * GROW return end if end if end do ! If errors were too large, redo the step with half the previous step size. h0 = h0 * .5d0 end do !------------------------------------------------------------------------------ end subroutine mdt_bs1 end module algo_bs1 <file_sep>!****************************************************************************** ! MODULE: massgrwoth !****************************************************************************** ! ! DESCRIPTION: !> @brief Modules that planet mass increases by pebble accretion ! !****************************************************************************** module massgrowth use orbital_elements use types_numeriques use physical_constant, only : PI, TWOPI, MSUN, K2, EARTH_MASS, AU ! implicit none contains !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% !> @author !> Beibei Liu ! !> @date 12 Jan 2018 ! ! DESCRIPTION: !> @brief Calculates the mass increase of the planet by pebble accretion !!\n\n based on the formulas of Liu & Ormel 2018, Ormel & Liu2018 !! The routine also gives the compostion X, planet radius Rp of each object. ! !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% subroutine pebbleaccretion (t,hstep,nbod,m,x,v,rphys,rho,m_x) ! t = current epoch [days] ! hstep = timestep [days] ! x = coordinates (x,y,z) with respect to the central body [AU] ! v = velocities (vx,vy,vz) with respect to the central body [AU/day] ! m = planet mass (in solar masses * K2) ! nbod = number of bodies ! rphys = planet radius [AU] ! rho = planet density ! m_x = mass of element X in planet (in solar masses * K2) ! use types_numeriques ! use physical_constant, only : PI, TWOPI, MSUN, K2, EARTH_MASS, AU use mercury_globals, only : opt,alpha_t, kap, mdot_gas0, L_s, Rdisk0, Mdot_peb, alpha, tau_s,t0_dep,tau_dep use user_module, only: gasdisk implicit none ! Input integer, intent(in) :: nbod real(double_precision),intent(in) :: t, hstep real(double_precision),intent(inout) :: x(3,nbod), v(3,nbod) real(double_precision),intent(inout) :: m(nbod) real(double_precision),intent(inout) :: m_x(nbod) real(double_precision),intent(inout) :: rphys(nbod) real(double_precision),intent(inout) :: rho(nbod) real(double_precision) :: ts(nbod) ! pebble's stokes number real(double_precision) :: f_ice ! ice fraction in pebbles real(double_precision) :: asemi(nbod), ecc(nbod), inc(nbod), rplanet(nbod), rdisk(nbod) real(double_precision) :: prob(nbod), prob2d(nbod), prob3d(nbod) real(double_precision) :: siggas, hgas, etagas, rhogas real(double_precision) :: q, rp_to_a, mdot real(double_precision) :: rtemp(nbod), filter(nbod),temp, newprob(nbod), detm(nbod) real(double_precision) :: rho_ice, rho_sil real(double_precision) :: m_iso, vol_tot real(double_precision) :: rtrans, siggas_vis, siggas_irr integer :: ilist(nbod) integer i, k, j ! ### material density of water ice and silicate ### rho_ice = 1.d0* ( AU * AU * AU * K2 / MSUN) rho_sil = 3.d0* ( AU * AU * AU * K2 / MSUN) ! ### pebble mass flux (Mdot_peb): in earth mass/year ### ! ### mdot: in solar mass/day ### mdot = Mdot_peb*EARTH_MASS/365.25d0 !####################################################################### !### calculate from xyz to semimajor axis, ecc & inclination(radian) ### !####################################################################### call xyztoaei(nbod,m,x,v,rdisk,asemi,ecc,inc) do i = 2, nbod !########################################## !### get disk infomation: etagas, hgas #### !########################################## call gasdisk (t,rdisk(i),x(3,i),m(1),alpha,kap,hgas,etagas,siggas,siggas_vis,siggas_irr,rhogas,rtrans) !########################################### !### get the pebble accretion efficiency ### !########################################### ts(i) = tau_s rp_to_a = rphys(i)/asemi(i) ! ratio of planet radius to semimajor axis if (rp_to_a > 0.d0) then ! still bound to the system q = m(i)/m(1) ! mass ratio between the planet and the central star prob(i) = eps_PA (ts(i), q, ecc(i), inc(i), alpha_t, etagas, hgas, rp_to_a) else ! planet escape from the system (a<0), then no accretion prob(i) = 0.d0 end if end do ! ### initial set-up sepeartion rtemp ### do i = 1, nbod rdisk(i) = (x(1, i)**2 + x(2, i)**2)**0.5d0 rtemp(i) = rdisk(i) end do !### define a radii array that modst distant body's position ranks the first ### do i =1, nbod-1 do j = i+1, nbod if (rtemp(i) < rtemp(j)) then temp = rtemp(i) rtemp(i) = rtemp(j) rtemp(j) = temp end if end do end do !### to calculate the filing factor of i planet ### prob(1) = 0.0d0 ! no mass increase of central star !#### give the ilist where ilist(i)=1 means rdisk(i) = maximum #### do i =1, nbod do j = 1, nbod if (rdisk(i) ==rtemp(j)) then ilist(i) = j newprob(j) = prob(i) end if end do end do ! ### filter is the flux ratio = M_real(i)/M_disk ### ! ### i=1,2,3 countes from the distant body ### ! ### newprob(1,2,3) is the efficiency from the distant body while prob(1,2,3) os the efficiency from the list i ### do i =1, nbod if ( i ==1 ) then filter(i) = 1.d0 else filter(i) = filter(i-1)*(1-newprob(i-1)) end if end do ! #################################################################################### ! #### add the mass/radius increase dm = prob* Mdot_real = prob* Mdot_disk*filter ### ! #################################################################################### do i =2, nbod ! #### mass increase by pebble accretion #### detm(i) = newprob(ilist(i))*hstep*mdot*K2*filter(ilist(i)) f_ice = 0.5d0 ! right now assume outside of the water ice line ! update the mass increase, consider the pebble isolation m_iso = pebble_iso(hgas,alpha_t,etagas,ts(i),m(1)) ! in earth mass m_iso = m_iso*EARTH_MASS*K2 !!!! unsolved, think about isolation mass around low-mass star if (m(i) > m_iso .and. opt(13)==1) then ! mass growth quenched by pebble isolation m(i) = m(i) m_x(i) = m_x(i) else m(i) = m(i) + (0.5d0 + f_ice)*detm(i) m_x(i) = m_x(i) + f_ice*detm(i) end if !### calculate the new density based on pebble accretion ### !vol_tot = m_x(i)/rho_ice +(m(i)-m_x(i))/rho_sil !rho(i) = m(i) /vol_tot ! ### update the radius due to mass increase ### !rphys(i)=(3d0*m(i)/(4d0*rho(i)*PI))**(1.d0/3.d0) !### calculate radius and density based on mass ### ! infer gas giant's radius from the mass based on Lissauer2011 mass-radius relationship rphys(i) = (m(i)/K2/EARTH_MASS)**(1./2.06)*4.3d-5 ! AU rho(i)= 3d0*m(i)/(4d0*PI*rphys(i)**3) ! in code unit ! rho(i)/( AU * AU * AU * K2 / MSUN) ! in g/cm^3 ! ############################################################### ! ###stop the integration if planet orbit is less than 0.1 AU ### ! ############################################################### !if (rdisk(i) <0.1d0 .and. asemi(i) < 0.1d0) stop end do end subroutine pebbleaccretion subroutine gasaccretion (t,hstep,nbod,m,x,v,rphys,rho,m_x) ! t = current epoch [days] ! hstep = timestep [days] ! x = coordinates (x,y,z) with respect to the central body [AU] ! v = velocities (vx,vy,vz) with respect to the central body [AU/day] ! m = planet mass (in solar masses * K2) ! nbod = number of bodies ! rphys = planet radius [AU] ! rho = planet density ! m_x = mass of element X in planet (in solar masses * K2) ! use types_numeriques ! use physical_constant, only : PI, TWOPI, MSUN, K2, EARTH_MASS, AU use mercury_globals, only : opt,alpha_t, kap, mdot_gas0, alpha,tau_s,t0_dep,tau_dep use user_module implicit none ! Input integer, intent(in) :: nbod real(double_precision),intent(in) :: t, hstep real(double_precision),intent(inout) :: x(3,nbod), v(3,nbod) real(double_precision),intent(inout) :: m(nbod) real(double_precision),intent(inout) :: m_x(nbod) real(double_precision),intent(inout) :: rphys(nbod) real(double_precision),intent(inout) :: rho(nbod) real(double_precision) :: ts(nbod) ! pebble's stokes number real(double_precision) :: detm(nbod), dmdt(nbod) real(double_precision) :: rdisk(nbod) real(double_precision) :: m_iso, m_planet,m_gap real(double_precision) :: rtrans, siggas_vis, siggas_irr real(double_precision) :: siggas, hgas, etagas, rhogas real(double_precision) :: dmdt_gas1, dmdt_gas2, dmdt_gas3 integer :: ilist(nbod) integer i, k, j !############################################### !## update the mass increase by gas accretion ## !############################################### do i =2, nbod rdisk(i) = (x(1, i)**2 + x(2, i)**2)**0.5d0 !########################################## !### get disk infomation: etagas, hgas #### !########################################## call gasdisk (t,rdisk(i),x(3,i),m(1),alpha,kap,hgas,etagas,siggas,siggas_vis,siggas_irr,rhogas,rtrans) ts(i) = tau_s m_iso = pebble_iso(hgas,alpha_t,etagas,ts(i),m(1)) ! in earth mass m_iso = m_iso*EARTH_MASS*K2 !!!! unsolved, think about isolation mass around low-mass star if (m(i) >=m_iso .and. opt(14)==1) then ! mass growth by gas accretion ! #### mass increase by gas accretion #### m_planet = m(i)/(EARTH_MASS*K2) ! in Earth mass m_gap = gap_opening(hgas,alpha_t,m(1)) !gap-opening mass ! in Earth mass dmdt_gas1 = dmdt_gas_KH(m_planet) ! in Mearth/yr dmdt_gas2 = dmdt_gas_Hill(m(i),m(1),m_gap,hgas,alpha,mdot_gas0) ! in Mearth/yr dmdt_gas3 = (mdot_gas0/EARTH_MASS) ! in Mearth/yr dmdt(i) = min(dmdt_gas1, dmdt_gas2,dmdt_gas3) ! in Mearth/yr dmdt(i) = dmdt(i)*EARTH_MASS/365.25d0 ! solar mass/day detm(i) = hstep*dmdt(i)*K2 ! mass increase during hstep m(i) = m(i) + detm(i) !### calculate radius and density based on mass ### !### based on Lissauer2011 mass-radius relationship ### rphys(i) = (m(i)/K2/EARTH_MASS)**(1./2.06)*4.3d-5 ! AU rho(i)= 3d0*m(i)/(4d0*PI*rphys(i)**3) ! in code unit ! rho(i)/( AU * AU * AU * K2 / MSUN) ! in g/cm^3 end if end do end subroutine gasaccretion !############################################### ! #### calculate the pebble isolation mass #### !############################################### !based on Bitsch+2018 function pebble_iso(hgas,alpha_t,etagas,ts,mstar) ! in Earth mass ! hgas = gas disk aspect ratio ! alpha_t = turbulent viscos alpha ! etagas = headwind prefactor ! ts = stokes number use physical_constant, only : K2 implicit none real(double_precision),intent(in) :: hgas, alpha_t, etagas,ts, mstar real(double_precision) :: f_miso, pebble_iso ! f_miso = (hgas/5d-2)**3*(0.34d0*(log10(alpha_t)/log10(1d-3))**4+ 0.66d0)!* & (1d0 - (2.5d0 +(-2d0*etagas/hgas**2) )/6d0) ! pebble_iso = 25d0*f_miso !+ alpha/(2d0*ts)/(4.76d-3/f_miso) ! pebble_iso = pebble_iso*(mstar/K2) ! consider the stellar mass dependence ! miso = mgap/2.3 pebble_iso = 30d0*(alpha_t/1d-3)**0.5*(hgas/5d-2)**2.5/2.3 pebble_iso = pebble_iso*(mstar/K2) ! consider the stellar mass dependence end function pebble_iso !############################################### ! #### calculate the gap opening mass #### !############################################### function gap_opening(hgas,alpha,mstar) ! in Earth mass ! hgas = gas disk aspect ratio ! alpha = turbulent viscos alpha use physical_constant, only : K2 implicit none real(double_precision),intent(in) :: hgas, alpha, mstar real(double_precision) :: gap_opening gap_opening = 30d0*(hgas/5d-2)**2.5*(alpha/1d-3)**0.5*(mstar/K2) end function gap_opening ! in Earth mass !##################################################### ! #### calculate Kelvin-Helmholtz gas contraction #### !##################################################### ! based on Ikoma2000 function dmdt_gas_KH(m_planet) ! in Earth mass/yr ! m_planet = planet mass in earth mass implicit none real(double_precision),intent(in) :: m_planet real(double_precision) :: kap_env, dmdt_gas_KH kap_env = 1.d0 ! 1cm^2g^-1 dmdt_gas_KH = 1d-5*(m_planet/1d+1)**4/kap_env end function dmdt_gas_KH !##################################################### !## calculate Hill sphere limited gas contraction #### !##################################################### ! based on Tanigawa & Tanaka 2016, but see modified in Liu et al. 2019 function dmdt_gas_Hill(mpl,mstar,mgap,hgas,alpha,mdot_gas0) ! in Earth mass/yr ! mpl = planet mass in code unit ! mstar = stellar mass in code unit ! mgap = gap opening planet mass in earth mass ! hgas = gas disk aspect ratio ! alpha = disk global angular momuntum transfer alpha use physical_constant, only : PI, TWOPI, MSUN, K2, EARTH_MASS, AU implicit none real(double_precision),intent(in) :: mpl,mgap,hgas,alpha,mstar,mdot_gas0 real(double_precision) :: dmdt_gas_Hill,f_acc, fk, m_planet f_acc = 0.5d0 m_planet = mpl/(EARTH_MASS*K2) ! in earth mass fk = 1.0d0 + (m_planet/mgap)**2 dmdt_gas_Hill = f_acc/(3d0*PI)*hgas**(-2)*(mpl/mstar/3.d0)**(2./3)*(mdot_gas0/EARTH_MASS)/alpha/fk end function dmdt_gas_Hill !###################################################### ! #### calculate from x, v to a, e, i #### !###################################################### subroutine xyztoaei(nbod,m,x,v,rdisk,asemi,ecc,inc) ! nbod = number of bodies ! m = planet mass (in solar masses * K2) ! x = coordinates (x,y,z) with respect to the central body [AU] ! v = velocities (vx,vy,vz) with respect to the central body [AU/day] ! asemi = semimajor axis ! rdisk = distance ! ecc = eccentricity ! inc = inclination (radian) implicit none ! Input integer :: k, i integer, intent(in) :: nbod real(double_precision),intent(in) :: x(3,nbod), v(3,nbod), m(nbod) real(double_precision), intent(inout) :: rdisk(nbod), asemi(nbod), ecc(nbod), inc(nbod) real(double_precision) :: r2, v2, rv, r, zmb, semi, ecc2, h2, hz asemi(1) = 0.d0 ecc(1) = 0.d0 inc(1) = 0.d0 do i = 2, nbod r2 = 0.d0 v2 = 0.d0 rv = 0.d0 do k = 1,3 r2 = r2 + x(k, i)**2 v2 = v2 + v(k, i)**2 rv = rv + x(k, i)*v(k, i) end do r = r2**0.5d0 ! 3 dimensional distance rdisk(i) = (x(1, i)**2 + x(2, i)**2)**0.5d0 ! xy dimensional distance zmb = m(1) + m(nbod) semi = 2.0d0/r - v2/zmb semi = 1.0d0/semi asemi(i) = semi ecc2 = (1.0d0 - r/semi)**2 + rv**2/(semi*zmb) ecc(i) = ecc2**0.5d0 hz=x(1, i)*v(2, i)-x(2, i)*v(1, i) h2=((x(2, i)*v(3, i)-x(3, i)*v(2, i))**2 & + (x(3, i)*v(1, i)-x(1, i)*v(3, i))**2+hz**2)**0.5d0 if (abs(hz/h2) < 1.d0) then inc(i) = acos(hz/h2) else if (hz/h2 > 0d0) inc(i) = 0.d0 if (hz/h2 < 0d0) inc(i) = PI ! in radian unit end if end do end subroutine xyztoaei function eps_PA (tau, qp, ecc, inc, alpha, etagas, hgas, rp_to_a) integer, parameter :: dp = kind(1.d0) real(dp), intent(in) :: tau, qp, ecc, inc, alpha, etagas, hgas, rp_to_a real(dp) :: vast, vturb, vcir, vecc, vz, detv real(dp) :: arg_xy, arg_z, ftrans, q_c, vxy, fturb real(dp), parameter :: PI = 4.d0*DATAN(1.d0) real(dp) :: A2 = 0.32d0, A3 =0.39d0, ash=0.52d0, acir=5.7d0,& aturb = 0.33d0, aset = 0.5d0, ai =0.68d0, ae=0.76d0 real(dp) :: prob2d_set, prob2d_bal, prob2d, hpeb, heff, prob3d_set, prob3d_bal, prob3d real(dp) :: eps_PA q_c = etagas**3/tau ! critical mass ratio separating the headwind and the shear regimes ! #### fitting factor to combine the settling and the balistic regime/settling factor #### vast = (qp/tau)**(1.d0/3.d0) vturb = hgas*alpha**0.5/(1.0d0 + tau)**0.5d0 ! turbulent velocity of particle = sqrt(D_gas/t_stop + t_corr) fturb = vast/(vast**2 + aturb*vturb**2)**0.5d0 vcir = 1.0d0/(1.0d0 + acir*(qp/q_c))*etagas + ash*(qp*tau)**(1.d0/3d0) vecc = ae*ecc vz = abs(ai*inc) ! #### xy plane relative velocity #### vxy = max(vcir, vecc) ! #### relative velocity between the planet and the pebble #### detv = max(vcir, vecc + vz) ! #### ratio between systematic and random motion #### ! #### in our case, random velocity is only applied in z-direction #### !!!arg_xy = vxy**2/vast**2 arg_xy = vxy**2/(vast**2 + aturb*vturb**2) !include vturb in xy plane arg_z = vz**2/(vast**2 + aturb*vturb**2) if(aset*(arg_xy + arg_z) >40d0) then !too large velocity ratio, then f=0 ftrans = 0d0 else ftrans = (exp(-aset*arg_xy )*fturb) * (exp(-aset*arg_z )*fturb) end if ! #### 2D accretion probability in different regimes #### prob2d_set = A2*qp**0.5d0/etagas*tau**(-0.5d0)*detv**0.5d0 prob2d_bal = rp_to_a/(2*PI*etagas*tau)*(detv**2 +2.d0*qp/rp_to_a)**0.5d0 ! #### 2D accretion probability combined two regimes #### prob2d = ftrans*prob2d_set + (1.0d0 -ftrans)*prob2d_bal ! prob2d = 1.d0 - exp(-prob2d) ! #### 3D accretion probability in different regimes #### hpeb = (alpha/(alpha+tau))**0.5d0 *hgas heff = (hpeb**2 + PI*inc**2/2.0d0*(1.0d0-exp(-inc/2d0/hpeb)))**0.5d0 prob3d_set = A3*qp/(etagas*heff) !prob3d_set = A3*q/(etagas*hpeb)!CWO debug prob3d_bal = 1.0d0/(4.d0*(2*PI)**0.5d0*etagas*heff*tau)*(2d0*qp/detv*rp_to_a + rp_to_a**2*detv) prob3d = prob3d_set*ftrans**2 + prob3d_bal*(1.0d0 - ftrans**2) eps_PA = (prob2d**(-2) + prob3d**(-2))**(-0.5d0) end function eps_PA end module massgrowth <file_sep># Number of planetary embryos 40 # Initial planetary mass range (Earth masses) 0.1,0.1 # Midpoint semi-major axis (AU) 30 # Separation between planets (Hill radii) 10 # Integration time (yr) 2e6 # Pebble stokes number 1E-1 # Turbulent viscosity strength alpha 1e-4 # Input new embryos every 10^4 yr? [yes/no] no # Source directory diskdep_uni6 <file_sep>AU = 1.4959787e13 # 1 astronimical unit [cm] Msun = 1.9891e33 # 1 solar mass [g] Lsun = 3.839e+33 # 1 solar luminoisty [ergs/s] Mearth = 5.972e27 # 1 earth mass [g] Rearth = 6.371e+8 # 1 earth radius [cm] Year = 3.15576e+7 # 1 year [s] G = 6.674e-8 # gravitational constant [cm^3/g/s^2] Omega = (G*Msun/AU**3)**0.5 # angular velocity at 1AU [s^-1] mu = 2.33 # mean molecular weight Rg = 8.31446e+7 # gas constant [erg/s/cm^2/K^4] sigma = 5.67e-5 # stefan Boltzman constant [erg/s/cm^2/K^4] msuntome = Msun/Mearth rjtoau = 1/2150 retoau = Rearth/1.495979e+13 <file_sep>#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Jun 25 10:33:31 2019 @author: jooehn """ import numpy as np import os from subprocess import call from astrounit import * from sys import argv from m6_funcs import * from diskmodel import rsnow,rtrans ############### Input ############### #If an input file is provided in the call, e.g. 'python m6_exe.py vars.ini' #we read the input from there. Otherwise, we use the input given in this script argv = [0,'vars.ini'] try: argv[1] except (IndexError,NameError): N = 1 #Number of planet embryos amid = 'ice' #Min semi-major axis val astep = 5 #Step in between planets mrange = np.array([0.01,0.01]) #Planetary mass in earth masses T = 2e5 #End time in yr st = 1e-2 inp_emb_str = 'yes' source = 'pa+mig4' else: inputfile = argv[1] #The vars.ini file vars_ = process_input(inputfile) N = int(vars_[0][0]) mrange = np.array(vars_[1][0].split(',')[:],dtype=float) try: amid = float(vars_[2][0]) except ValueError: amid = vars_[2][0].rstrip('\n') pass astep = float(vars_[3][0]) #In R_Hill T = float(vars_[4][0]) #In yr st = float(vars_[5][0]) alpha_d = float(vars_[6][0]) inp_emb_str = vars_[7][0].rstrip('\n') source = vars_[8][0].rstrip('\n') ############### Setup ############### #We first swap into the source directory cdir = os.getcwd()#+'/' #current dir sourcedir = cdir+'/../sim/'+source+'/' pydir = cdir # python dir workdir = cdir+'/../figure/' os.chdir(sourcedir) #We have the option to insert new planetary embryos at the iceline after a given #time interval if inp_emb_str in ['yes','Yes','y']: insert_embryo = True else: insert_embryo = False #We get the general disk parameters as set up in the param.in file _,alpha_v,mdot_gas,L_s,_,_,_,kap,M_s,opt_vis = get_disk_params() #We set up the big.in file with the number of planetary embryos we want #First we generate the masses in the range provided pmass = np.linspace(mrange[0],mrange[1],N) #We set up the container for the initial data of the embryos if insert_embryo: bigdata = np.zeros((1,10)) bignames = ['P1'] pmass = np.array([mrange[0]]) #We draw eccentricities from a Rayleigh distr. ep = np.random.rayleigh(1e-2,1) #We draw eccentricities from a Rayleigh distr. else: bigdata = np.zeros((N,10)) bignames = ['P{}'.format(i+1) for i in range(N)] #We draw eccentricities from a Rayleigh distr. ep = np.random.rayleigh(1e-2,N) #Next we set up the physical properties and the phase of the planets and #store them in an array of size (N,10) ip = 0.5*ep rp = 1.0 dp = 1.5 xp = 1.5e-9 mp = pmass*(Mearth/Msun) #Next, we generate the semi-major axis values given our separation and a min value #If amid is simply 'ice' or 'None', we set the initial position at the iceline if amid in ['ice','r_ice','None','none']: r_ice = rsnow(mdot_gas,L_s,M_s,alpha_v,kap,opt_vis) avals = np.asarray([r_ice]) elif type(amid) in [float,int]: #We separate the embryos in terms of Hill radii a_low = amid a_upp = amid avals_low = [] avals_upp = [] N_half = int(0.5*N) N_low = list(range(0,N_half+1)) N_low.reverse() N_upp = list(range(N_half,N)) for i in N_low[:-1]: R_hill_l = a_low*((mp[i]+mp[i-1])/(3*M_s))**(1/3) a_low -= astep*R_hill_l avals_low.append(a_low) for i in N_upp[:-1]: R_hill_u = a_upp*((mp[i]+mp[i+1])/(3*M_s))**(1/3) a_upp += astep*R_hill_u avals_upp.append(a_upp) avals_low.sort() avals = np.concatenate([avals_low,[amid],avals_upp]) else: raise ValueError('Not a valid input for a') props = np.array([0,rp,dp,xp,0,0,0,0,0,0]) bigdata[:] = props #We also insert the semi-major axis values and masses bigdata[:,0] = mp bigdata[:,4] = avals bigdata[:,5] = ep bigdata[:,6] = ip #Finally we write it all into our big.in file big_input(bignames,bigdata,asteroidal=True) #Uncomment the following lines to allow for input of a specific planet in big.in #mass_p = 100*(Mearth/Msun) #semi_p = rtrans(mdot_gas,L_s,M_s,alpha_v,kap,opt_vis) #insert_planet_embryo(mass_p,semi_p,N+1) #We set up the end time of the run which is divided into shorter integrations of #length dt dt = 1e4 setup_end_time(dt) #Furthermore, we set the input Stokes number set_stokes_number(st) #We also set the turbulent strength alpha set_turbulent_alpha(alpha_d) #We also remove old files bad_ext = ['*.dmp','*.tmp','*.aei','*.clo','*.out'] for j in bad_ext: call(['find',os.getcwd(),'-maxdepth','1','-type','f','-name',j,'-delete']) ############### Executing ############### print('Initiating integration') t = 0 i = 2 while t < T: if insert_embryo & (t>0) & (i<=N): insert_planet_embryo(mp[0],avals[0],i) i += 1 #We first perform the integration by calling MERCURY call(['./mercury']) #Since planets residing at our cavity at 0.2 AU will slow the integration #down significantly, we check if there is such a planet and #remove it if this is indeed the case all_in_cavity = check_cavity_planet() if all_in_cavity: print('All planets have entered cavity after {} yr'.format(t+dt)) print('Stopping integration') break extend_stop_time(dt) t += dt print('Creating .aei files') if not all_in_cavity: call(['./element']) #Finally, we create figures os.chdir(pydir) print('Creating figures') call(['python','MAEbig.py',source]) print('The deed is done')<file_sep>#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Jun 25 10:21:35 2019 @author: <NAME> Some functions that handles MERCURY input files """ import numpy as np import os import math from tempfile import mkstemp from subprocess import call from shutil import move from astrounit import * from diskmodel import iso_mass,gap_mass def setup_end_time(T,T_start=0): """Small function that sets up the duration of our integration. T: the total time of the integration given in yr T_start: we can also specify the start time. If no start time is given, it is set to zero by default. Should aso be given in yr""" #The string we want to change start_str = ' start time (days) = ' end_str = ' stop time (days) = ' #Makes temporary file fh, abs_path = mkstemp() with os.fdopen(fh,'w') as new_file: with open('param.in') as old_file: for line in old_file: if start_str in line: old_sstr = line # old_stime = float(old_sstr.strip(start_str)) new_stime = T_start new_sstr = start_str+str(new_stime)+'\n' new_file.write(line.replace(old_sstr, new_sstr)) elif end_str in line: old_estr = line etime = T*365.25 new_estr = end_str+str(etime)+'\n' new_file.write(line.replace(old_estr, new_estr)) else: new_file.write(line) #Remove original file and move new file os.remove('param.in') move(abs_path, 'param.in') def extend_stop_time(T): """Small function that updates the stop time in param.dmp to allow for an extended integration in case we have no collisions. Updates the old time value by adding the value T.""" #The string we want to change stime_str = ' stop time (days) = ' #Makes temporary file fh, abs_path = mkstemp() with os.fdopen(fh,'w') as new_file: with open('param.dmp') as old_file: for line in old_file: if stime_str in line: old_str = line old_time = float(old_str.strip(stime_str)) new_time = old_time+T*365.25 rep_str = stime_str+str(old_time) new_str = stime_str+str(new_time) new_file.write(line.replace(rep_str, new_str)) else: new_file.write(line) #Remove original file and move new file os.remove('param.dmp') move(abs_path, 'param.dmp') def big_input(names,bigdata,asteroidal=False,epoch=0): """Function that generates the big.in input file for MERCURY6 given an Nx10 array of data in the following format: Columns: 0: mass of the object given in solar masses 1: radius of the object in Hill radii 2: density of the object 3: x for the planet 4: semi-major axis in AU 5: eccentricity 6: inclination in degrees 7: argument of pericentre in degrees 8: longitude of the ascending node 9: mean anomaly in degrees We can also pass the argument asteroidal as True if we want that coordinate system. Also the epoch can be specified, it should be given in years.""" N = len(bigdata) if asteroidal: style = 'Asteroidal' else: style = 'Cartesian' initlist = [')O+_06 Big-body initial data (WARNING: Do not delete this line!!)\n',\ ") Lines beginning with `)' are ignored.\n",\ ')---------------------------------------------------------------------\n',\ ' style (Cartesian, Asteroidal, Cometary) = {}\n'.format(style),\ ' epoch (in days) = {}\n'.format(epoch*365.25),\ ')---------------------------------------------------------------------\n'] with open('big.in','w+') as bigfile: for i in initlist: bigfile.write(i) for j in range(N): bigfile.write(' {0:11}m={1:.17E} r={2:.0f}.d0 d={3:.2f} x={4:.2e}\n'.format(names[j],*bigdata[j,0:4])) bigfile.write(' {0: .17E} {1: .17E} {2: .17E}\n'.format(*bigdata[j,4:7])) bigfile.write(' {0: .17E} {1: .17E} {2: .17E}\n'.format(*bigdata[j,7:])) bigfile.write(' 0. 0. 0.\n') def process_input(file_): #Function that reads the input file if any h_file = [] input_ = open(file_, 'r') for line in input_: if line.find("#") != -1: continue elif line.find("\n") == 0: continue else: h_file.append(line.split('\t')) return h_file def check_timestep(): """Checks if the timestep has gone below values of 1 day. Returns either True or False depending on the timestep size.""" with open('param.dmp') as param: for line in param: if 'timestep' in line: timestep = float(line.split()[-1]) print('Current timestep: {} days'.format(timestep)) if timestep < 1: return True else: return False def get_names(dmp=False): """Returns a list with the names of the current objects active in our simulation.""" if dmp: file = 'big.dmp' else: file = 'big.in' with open(file,'r') as bigfile: biglines = bigfile.readlines() nameid = np.arange(6,len(biglines),4) names = [biglines[i].split()[0] for i in nameid] return names def get_survivor_ids(): """Returns a list with the index and massdotsize for survivors in the system""" survivors = get_names(True) surv_ids = [int(i.strip('P')) for i in survivors] return np.asarray(surv_ids) def check_cavity_planet(): """Removes planet that has entered our cavity in order to keep the timestep from converging at low values and thereby slowing down our integration. names: The names of our planets data: The corresponding data input data for the planets Returns True if all planets have entered the cavity and the integration should be terminated.""" #We generate output files call(['./element']) names = get_names(True) N = len(names) in_cavity = np.full(N,False) #We check the element file for the semi-major axis values of our planets with open('element.out') as element: elelines = element.readlines() for i in range(len(elelines[2:])): params = elelines[2:][i].split() x = float(params[9]) y = float(params[10]) z = float(params[11]) a = np.sqrt(x**2+y**2+z**2) #If a is less than our cavity value which is 0.2 AU we register the #corresponding planet if a <= 0.2: in_cavity[i] = True #We extract the ids of the planets that are in the cavity and remove them if np.all(in_cavity): return True elif np.any(in_cavity): cavity_ids = np.where(in_cavity)[0] old_names = [] for i in range(len(cavity_ids)): print('We remove P{} from the integration\n'.format(names[cavity_ids[i]])) old_names.append(names[cavity_ids[i]]) names.remove(names[cavity_ids[i]]) #We loop through each line in big.dmp and remove the information of the #planets inside the cavity #Makes temporary file fh, abs_path = mkstemp() with os.fdopen(fh,'w') as new_file: with open('big.dmp') as bigfile: biglines = bigfile.readlines() i = 6 while (len(biglines)>6) & (len(old_names)>0): if old_names[0] in biglines[i]: del biglines[i:i+4] del old_names[0] else: i += 4 new_file.writelines(biglines) #Remove original file and move new file call(['find',os.getcwd(),'-maxdepth','1','-type','f','-name','*.aei','-delete']) os.remove('big.dmp') move(abs_path, 'big.dmp') return False else: call(['find',os.getcwd(),'-maxdepth','1','-type','f','-name','*.aei','-delete']) return False def set_stokes_number(st): #The string we want to change st_str = " pebble's stokes number = " #Makes temporary file fh, abs_path = mkstemp() with os.fdopen(fh,'w') as new_file: with open('param.in') as old_file: for line in old_file: if st_str in line: rep_str = line new_str = st_str+'{:.0E}'.format(st)+'\n' new_file.write(line.replace(rep_str, new_str)) else: new_file.write(line) #Remove original file and move new file os.remove('param.in') move(abs_path, 'param.in') def set_turbulent_alpha(alpha): #The string we want to change turb_str = " turbulent strength alphad = " #Makes temporary file fh, abs_path = mkstemp() with os.fdopen(fh,'w') as new_file: with open('param.in') as old_file: for line in old_file: if turb_str in line: rep_str = line new_str = turb_str+'{:.17E}'.format(alpha)+'\n' new_file.write(line.replace(rep_str, new_str)) else: new_file.write(line) #Remove original file and move new file os.remove('param.in') move(abs_path, 'param.in') def get_disk_params(): """Finds the disk parameters given in the param.in file and returns them as an array in the following order: alpha_t, alpha_v, mdot_gas, L_s, R_disk, mdot_peb, st, kappa, M_s, opt_vis.""" parlist = [] with open('param.in','r') as paramfile: parlines = paramfile.readlines() for line in parlines[37:45]: parlist.append(float(line.split()[-1])) parlist.append(float(parlines[28].split()[-1])) if parlines[48].split()[-1] in ['yes','Yes','y']: parlist.append(True) else: parlist.append(False) return parlist def insert_planet_dmp(bigdata,name): """Converts the asteroidal input information for our new planet to cartesian coordinates and then writes it into our new big.dmp file.""" cwd = os.getcwd() os.chdir('../conversion/') bad_ext = ['*.dmp','*.tmp','*.aei','*.clo','*.out'] for j in bad_ext: call(['find',os.getcwd(),'-maxdepth','1','-type','f','-name',j,'-delete']) initlist = [')O+_06 Big-body initial data (WARNING: Do not delete this line!!)\n',\ ") Lines beginning with `)' are ignored.\n",\ ')---------------------------------------------------------------------\n',\ ' style (Cartesian, Asteroidal, Cometary) = Asteroidal\n',\ ' epoch (in days) = 0\n',\ ')---------------------------------------------------------------------\n'] with open('big.in','w+') as bigfile: for i in initlist: bigfile.write(i) bigfile.write(' {0:11}m={1:.17E} r={2:.0f}.d0 d={3:.2f} x={4:.2e}\n'.format(name,*bigdata[0:4])) bigfile.write(' {0: .17E} {1: .17E} {2: .17E}\n'.format(*bigdata[4:7])) bigfile.write(' {0: .17E} {1: .17E} {2: .17E}\n'.format(*bigdata[7:])) bigfile.write(' 0. 0. 0.\n') call(['./mercury']) with open('big.dmp','r') as bigdmp: bigdmplines = bigdmp.readlines() os.chdir(cwd) with open('big.dmp','a') as bigdmpnew: for line in bigdmplines[6:]: bigdmpnew.write(line) def insert_planet_embryo(mp,ap,emb_id): """Inserts a new embryo into the integration at the ice-line""" ep = np.random.rayleigh(1e-2) #We draw eccentricities from a Rayleigh distr. ip = 0.5*ep rp = 1.0 dp = 1.5 xp = 1.5e-9 #We insert our parameters into our data array bigdata = np.array([mp,rp,dp,xp,ap,ep,ip,0,0,0]) #Finally we generate the names and write it all into our big.in file name = 'P{}'.format(emb_id) with open('big.in','a') as bigfile: bigfile.write(' {0:11}m={1:.17E} r={2:.0f}.d0 d={3:.2f} x={4:.2e}\n'.format(name,*bigdata[0:4])) bigfile.write(' {0: .17E} {1: .17E} {2: .17E}\n'.format(*bigdata[4:7])) bigfile.write(' {0: .17E} {1: .17E} {2: .17E}\n'.format(*bigdata[7:])) bigfile.write(' 0. 0. 0.\n') #We then convert our aei coordinates to a cartesian frame using an external #mercury run for 0.1 days and write it into our new big.dmp file insert_planet_dmp(bigdata,name) def safronov_number(mp,ms,ap): """Computes the Safronov number assuming a constant density of the planetary embryos.""" #We assume a constant density mp = mp*Mearth ms = ms*Msun ap = ap*AU rho = 1.5 # rp = (3*mp/(4*np.pi*rho))**(1/3) rp = mp**(1/2.06)*retoau saf = np.sqrt(mp*ap/(ms*rp)) return saf def find_nearest(array,value): idx = np.searchsorted(array, value, side="left") if idx > 0 and (idx == len(array) or math.fabs(value - array[idx-1]) < math.fabs(value - array[idx])): return idx-1 else: return idx def detect_merger(): """Finds which planet has grown through collisions with another embryo at which time and mass.""" coll = 'was hit by' plist = [] tlist = [] mlist = [] alist = [] with open('info.out','r') as infofile: for line in infofile: if coll in line: cinfo = line.split() plist.append(cinfo[0]) tlist.append(float(cinfo[6])) for i in range(len(plist)): pdata = np.loadtxt(plist[i]+'.aei',skiprows=4) t = pdata[:,0] timeid = find_nearest(t,tlist[i])-1 mlist.append(pdata[timeid,7]) alist.append(pdata[timeid,1]) plistn = [int(i.strip('P')) for i in plist] return np.asarray([plistn,np.asarray(mlist)*msuntome,np.asarray(tlist)/365.25,np.asarray(alist)]) def check_isomass(a,mp,mdot_gas,L_s,M_s,alpha_d,alpha_v,kap,opt_vis): """Goes through the semi-major axis values and mass values at every point in time and compares the mass to the isolation mass at the corresponding a value. If we see a sign change in the difference, we note the index where it occured and return it.""" m_iso = iso_mass(a,mdot_gas,L_s,M_s,alpha_d,alpha_v,kap,opt_vis) rdsign = np.sign(m_iso-mp) if np.any(rdsign==-1): sz = rdsign == 0 while sz.any(): rdsign[sz] = np.roll(rdsign, 1)[sz] sz = rdsign == 0 schange = ((np.roll(rdsign, 1) - rdsign) != 0).astype(int) #We set the first element to zero due to the circular shift of #numpy.roll schange[0] = 0 #Finally we check where the array is equal to one and extract the #corresponding index if np.any(schange): scidx = np.where(schange)[0][0] else: scidx = 0 return scidx else: return None def check_gapmass(a,mp,mdot_gas,L_s,M_s,alpha_d,alpha_v,kap,opt_vis): """Goes through the semi-major axis values and mass values at every point in time and compares the mass to the gas accretion mass at the corresponding a value. If we see a sign change in the difference, we note the index where it occured and return it.""" m_gap = gap_mass(a,mdot_gas,L_s,M_s,alpha_d,alpha_v,kap,opt_vis) rdsign = np.sign(m_gap-mp) if np.any(rdsign==-1): sz = rdsign == 0 while sz.any(): rdsign[sz] = np.roll(rdsign, 1)[sz] sz = rdsign == 0 schange = ((np.roll(rdsign, 1) - rdsign) != 0).astype(int) #We set the first element to zero due to the circular shift of #numpy.roll schange[0] = 0 #Finally we check where the array is equal to one and extract the #corresponding index if np.any(schange): scidx = np.where(schange)[0][0] else: scidx = 0 return scidx else: return None <file_sep>import os os.system('rm -rf Out *.dmp *.tmp *.out *.aei ') <file_sep>!****************************************************************************** ! MODULE: mercury_outputs !****************************************************************************** ! ! DESCRIPTION: !> @brief Modules that write files, wether they are outputs files, or errors ! !****************************************************************************** module mercury_outputs use types_numeriques use mercury_globals implicit none character(len=1), dimension(5), parameter, private :: bad = (/'*', '/', '.', ':', '&'/) contains !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% !> @author !> <NAME> ! !> @date 1 March 2001 ! ! DESCRIPTION: !> @brief Writes details of close encounter minima to an output file, and decides how !! to continue the integration depending upon the close-encounter option !! chosen by the user. Close encounter details are stored until either 100 !! have been accumulated, or a data dump is done, at which point the stored !! encounter details are also output. !!\n\n !! For each encounter, the routine outputs the time and distance of closest !! approach, the identities of the objects involved, and the output !! variables of the objects at this time. The output variables are: !! expressed as !!\n r = the radial distance !!\n theta = polar angle !!\n phi = azimuthal angle !!\n fv = 1 / [1 + 2(ke/be)^2], where be and ke are the object's binding and !!\n kinetic energies. (Note that 0 < fv < 1). !!\n vtheta = polar angle of velocity vector !!\n vphi = azimuthal angle of the velocity vector ! !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% subroutine mio_ce (time,rcen,nbod,nbig,m,stat,id,nclo,iclo,jclo,stopflag,tclo,dclo,ixvclo,jxvclo,nstored,ceflush) use physical_constant use mercury_constant use ascii_conversion use orbital_elements use utilities implicit none ! Input/Output integer, intent(in) :: nbod !< [in] current number of bodies (1: star; 2-nbig: big bodies; nbig+1-nbod: small bodies) integer, intent(in) :: nbig !< [in] current number of big bodies (ones that perturb everything else) integer, intent(in) :: stat(nbod) !< [in] status (0 => alive, <>0 => to be removed) integer, intent(out) :: stopflag integer, intent(in) :: nclo integer, intent(in) :: iclo(nclo) integer, intent(in) :: jclo(nclo) integer, intent(inout) :: nstored integer, intent(in) :: ceflush real(double_precision), intent(in) :: time !< [in] current epoch (days) real(double_precision), intent(in) :: rcen !< [in] radius of central body (AU) real(double_precision), intent(in) :: m(nbod) !< [in] mass (in solar masses * K2) real(double_precision), intent(in) :: tclo(nclo) real(double_precision), intent(in) :: dclo(nclo) real(double_precision) :: ixvclo(6,nclo),jxvclo(6,nclo) character(len=8), intent(in) :: id(nbod) !< [in] name of the object (8 characters) ! Local integer :: k,year,month real(double_precision) :: tmp0,t1,rfac,fr,fv,theta,phi,vtheta,vphi character(len=80) :: c(CMAX*4) character(len=38) :: fstop character(len=6) :: tstring integer :: error !------------------------------------------------------------------------------ save c ! Scaling factor (maximum possible range) for distances rfac = log10 (rmax / rcen) ! Store details of each new close-encounter minimum do k = 1, nclo nstored = nstored + 1 c(nstored)(1:8) = mio_fl2c(tclo(k)) c(nstored)(9:16) = mio_re2c(dble(iclo(k)-1),0.d0,11239423.99d0) c(nstored)(12:19) = mio_re2c(dble(jclo(k)-1),0.d0,11239423.99d0) c(nstored)(15:22) = mio_fl2c(dclo(k)) call mco_x2ov (rcen,m(1),0.d0,ixvclo(1,k),ixvclo(2,k),ixvclo(3,k),ixvclo(4,k),ixvclo(5,k),ixvclo(6,k),fr,theta,phi,fv,& vtheta,vphi) c(nstored)(23:30) = mio_re2c (fr , 0.d0, rfac) c(nstored)(27:34) = mio_re2c (theta , 0.d0, PI) c(nstored)(31:38) = mio_re2c (phi , 0.d0, TWOPI) c(nstored)(35:42) = mio_re2c (fv , 0.d0, 1.d0) c(nstored)(39:46) = mio_re2c (vtheta, 0.d0, PI) c(nstored)(43:50) = mio_re2c (vphi , 0.d0, TWOPI) call mco_x2ov (rcen,m(1),0.d0,jxvclo(1,k),jxvclo(2,k),jxvclo(3,k),jxvclo(4,k),jxvclo(5,k),jxvclo(6,k),fr,theta,phi,fv,& vtheta,vphi) c(nstored)(47:54) = mio_re2c (fr , 0.d0, rfac) c(nstored)(51:58) = mio_re2c (theta , 0.d0, PI) c(nstored)(55:62) = mio_re2c (phi , 0.d0, TWOPI) c(nstored)(59:66) = mio_re2c (fv , 0.d0, 1.d0) c(nstored)(63:74) = mio_re2c (vtheta, 0.d0, PI) c(nstored)(67:78) = mio_re2c (vphi , 0.d0, TWOPI) end do ! If required, output the stored close encounter details if ((nstored.ge.CMAX*2).or.(ceflush.eq.0)) then open (22, file=outfile(2), status='old', position='append',iostat=error) if (error /= 0) then write (*,'(/,2a)') " ERROR: Programme terminated. Unable to open ",trim(outfile(2)) stop end if do k = 1, nstored write (22,'(a1,a2,a70)') char(12),'6b',c(k)(1:70) end do close (22) nstored = 0 end if ! If new encounter minima have occurred, decide whether to stop integration stopflag = 0 if ((opt(1).eq.1).and.(nclo.gt.0)) then open (23, file=outfile(3), status='old', position='append',iostat=error) if (error /= 0) then write (*,'(/,2a)') " ERROR: Programme terminated. Unable to open ",trim(outfile(3)) stop end if ! If time style is Gregorian date then... tmp0 = tclo(1) if (opt(3).eq.1) then fstop = '(5a,/,9x,a,i10,1x,i2,1x,f4.1)' call mio_jd2y (tmp0,year,month,t1) write (23,fstop) mem(121)(1:lmem(121)),mem(126)(1:lmem(126)),id(iclo(1)),',',id(jclo(1)),mem(71)(1:lmem(71)),year,month,t1 ! Otherwise... else if (opt(3).eq.3) then tstring = mem(2) fstop = '(5a,/,9x,a,f14.3,a)' t1 = (tmp0 - tstart) / 365.25d0 else tstring = mem(1) fstop = '(5a,/,9x,a,f14.1,a)' if (opt(3).eq.0) t1 = tmp0 if (opt(3).eq.2) t1 = tmp0 - tstart end if write (23,fstop) mem(121)(1:lmem(121)),mem(126)(1:lmem(126)),id(iclo(1)),',',id(jclo(1)),mem(71)(1:lmem(71)),t1,tstring end if stopflag = 1 close(23) end if !------------------------------------------------------------------------------ return end subroutine mio_ce !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% !> @author !> <NAME> ! !> @date 21 February 2001 ! ! DESCRIPTION: !> @brief Writes masses, coordinates, velocities etc. of all objects, and integration !! parameters, to dump files. Also updates a restart file containing other !! variables used internally by MERCURY. ! !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% subroutine mio_dump (time,h0,tol,jcen,rcen,en,am,cefac,ndump,nfun,nbod,nbig,m,x,v,s,rho,rceh,stat,id,ngf,epoch,opflag,m_x) use physical_constant use mercury_constant implicit none ! Input/Output integer, intent(in) :: nbod !< [in] current number of bodies (1: star; 2-nbig: big bodies; nbig+1-nbod: small bodies) integer, intent(in) :: nbig !< [in] current number of big bodies (ones that perturb everything else) integer, intent(in) :: stat(nbod) !< [in] status (0 => alive, <>0 => to be removed) integer, intent(in) :: opflag !< [in] integration mode (-2 = synchronising epochs) !!\n -1 = integrating towards start epoch !!\n 0 = main integration, normal output !!\n 1 = main integration, full output integer, intent(in) :: ndump integer, intent(in) :: nfun real(double_precision), intent(in) :: time !< [in] current epoch (days) real(double_precision), intent(in) :: h0 !< [in] initial integration timestep (days) real(double_precision), intent(in) :: tol !< [in] Integrator tolerance parameter (approx. error per timestep) real(double_precision), intent(in) :: en(3) !< [in] (initial energy, current energy, energy change due to collision and ejection) of the system real(double_precision), intent(in) :: am(3) !< [in] (initial angular momentum, current angular momentum, !! angular momentum change due to collision and ejection) of the system real(double_precision), intent(in) :: jcen(3) !< [in] J2,J4,J6 for central body (units of RCEN^i for Ji) real(double_precision), intent(in) :: rcen !< [in] radius of central body (AU) real(double_precision), intent(in) :: cefac real(double_precision), intent(in) :: m(nbod) !< [in] mass (in solar masses * K2) real(double_precision), intent(in) :: m_x(nbod) !< [in] mass of element X (in solar masses * K2) real(double_precision), intent(in) :: x(3,nbod) real(double_precision), intent(in) :: v(3,nbod) real(double_precision), intent(in) :: s(3,nbod) !< [in] spin angular momentum (solar masses AU^2/day) real(double_precision), intent(in) :: rho(nbod) !< [in] physical density (g/cm^3) real(double_precision), intent(in) :: rceh(nbod) !< [in] close-encounter limit (Hill radii) real(double_precision), intent(in) :: ngf(4,nbod) !< [in] non gravitational forces parameters !! \n(1-3) cometary non-gravitational (jet) force parameters !! \n(4) beta parameter for radiation pressure and P-R drag real(double_precision), intent(in) :: epoch(nbod) !< [in] epoch of orbit (days) character(len=8), intent(in) :: id(nbod) !< [in] name of the object (8 characters) ! Local integer :: idp,i,j,k,len,j1,j2 real(double_precision) :: rhocgs,k_2,rcen_2,rcen_4,rcen_6,x0(3,nb_bodies_initial),v0(3,nb_bodies_initial) character(len=150) :: c integer :: error !------------------------------------------------------------------------------ rhocgs = AU * AU * AU * K2 / MSUN k_2 = 1.d0 / K2 rcen_2 = 1.d0 / (rcen * rcen) rcen_4 = rcen_2 * rcen_2 rcen_6 = rcen_4 * rcen_2 ! If using close-binary star, convert to user coordinates ! if (algor.eq.11) call mco_h2ub (time,jcen,nbod,nbig,h0,m,x,v, ! % x0,v0) ! Dump to temporary files (idp=1) and real dump files (idp=2) do idp = 1, 2 ! Dump data for the Big (i=1) and Small (i=2) bodies do i = 1, 2 if (idp.eq.1) then if (i.eq.1) c(1:12) = 'big.tmp ' if (i.eq.2) c(1:12) = 'small.tmp ' open (31, file=c(1:12), status='unknown', iostat=error) if (error /= 0) then write (*,'(/,2a)') " ERROR: Programme terminated. Unable to open ",trim(c(1:12)) stop end if else open (31, file=dumpfile(i), status='old', iostat=error) if (error /= 0) then write (*,'(/,2a)') " ERROR: Programme terminated. Unable to open ",trim(dumpfile(i)) stop end if end if ! Write header lines, data style (and epoch for Big bodies) write (31,'(a)') mem(151+i)(1:lmem(151+i)) if (i.eq.1) then j1 = 2 j2 = nbig else j1 = nbig + 1 j2 = nbod end if write (31,'(a)') mem(154)(1:lmem(154)) write (31,'(a)') mem(155)(1:lmem(155)) write (31,*) mem(156)(1:lmem(156)),'Cartesian' if (i.eq.1) write (31,*) mem(157)(1:lmem(157)),time write (31,'(a)') mem(155)(1:lmem(155)) ! For each body... do j = j1, j2 len = 37 c(1:8) = id(j) write (c(9:37),'(1p,a3,e11.5,a3,e11.5)') ' r=',rceh(j),' d=',rho(j)/rhocgs if (m(j).gt.0) then write (c(len+1:len+25),'(1p,a3,e22.15)') ' m=',m(j)*k_2 len = len + 25 write (c(len+1:len+25),'(1p,a3,e22.15)') ' x=',m_x(j)*k_2 len = len + 25 end if do k = 1, 3 if (ngf(k,j).ne.0) then write (c(len+1:len+16),'(a2,i1,a1,e12.5)') ' a',k,'=',ngf(k,j) len = len + 16 end if end do if (ngf(4,j).ne.0) then write (c(len+1:len+15),'(a3,e12.5)') ' b=',ngf(4,j) len = len + 15 end if write (31,'(a)') c(1:len) if (algor.eq.11) then write (31,312) x0(1,j), x0(2,j), x0(3,j) write (31,312) v0(1,j), v0(2,j), v0(3,j) else write (31,312) x(1,j), x(2,j), x(3,j) write (31,312) v(1,j), v(2,j), v(3,j) end if write (31,312) s(1,j)*k_2, s(2,j)*k_2, s(3,j)*k_2 enddo close (31) end do ! Dump the integration parameters 40 if (idp.eq.1) open (33,file='param.tmp',status='unknown',err=40) 45 if (idp.eq.2) open (33, file=dumpfile(3), status='old', err=45) ! Important parameters write (33,'(a)') mem(151)(1:lmem(151)) write (33,'(a)') mem(154)(1:lmem(154)) write (33,'(a)') mem(155)(1:lmem(155)) write (33,'(a)') mem(158)(1:lmem(158)) write (33,'(a)') mem(155)(1:lmem(155)) if (algor.eq.1) then write (33,*) mem(159)(1:lmem(159)),'MVS' else if (algor.eq.2) then write (33,*) mem(159)(1:lmem(159)),'BS' else if (algor.eq.3) then write (33,*) mem(159)(1:lmem(159)),'BS2' else if (algor.eq.4) then write (33,*) mem(159)(1:lmem(159)),'RADAU' else if (algor.eq.10) then write (33,*) mem(159)(1:lmem(159)),'HYBRID' else if (algor.eq.11) then write (33,*) mem(159)(1:lmem(159)),'CLOSE' else if (algor.eq.12) then write (33,*) mem(159)(1:lmem(159)),'WIDE' else write (33,*) mem(159)(1:lmem(159)),'0' end if write (33,*) mem(160)(1:lmem(160)),tstart write (33,*) mem(161)(1:lmem(161)),tstop write (33,*) mem(162)(1:lmem(162)),dtout write (33,*) mem(163)(1:lmem(163)),h0 write (33,*) mem(164)(1:lmem(164)),tol ! Integration options write (33,'(a)') mem(155)(1:lmem(155)) write (33,'(a)') mem(165)(1:lmem(165)) write (33,'(a)') mem(155)(1:lmem(155)) if (opt(1).eq.0) then write (33,'(2a)') mem(166)(1:lmem(166)),mem(5)(1:lmem(5)) else write (33,'(2a)') mem(166)(1:lmem(166)),mem(6)(1:lmem(6)) end if if (opt(2).eq.0) then write (33,'(2a)') mem(167)(1:lmem(167)),mem(5)(1:lmem(5)) write (33,'(2a)') mem(168)(1:lmem(168)),mem(5)(1:lmem(5)) else if (opt(2).eq.2) then write (33,'(2a)') mem(167)(1:lmem(167)),mem(6)(1:lmem(6)) write (33,'(2a)') mem(168)(1:lmem(168)),mem(6)(1:lmem(6)) else write (33,'(2a)') mem(167)(1:lmem(167)),mem(6)(1:lmem(6)) write (33,'(2a)') mem(168)(1:lmem(168)),mem(5)(1:lmem(5)) end if if ((opt(3).eq.0).or.(opt(3).eq.2)) then write (33,'(2a)') mem(169)(1:lmem(169)),mem(1)(1:lmem(1)) else write (33,'(2a)') mem(169)(1:lmem(169)),mem(2)(1:lmem(2)) end if if ((opt(3).eq.2).or.(opt(3).eq.3)) then write (33,'(2a)') mem(170)(1:lmem(170)),mem(6)(1:lmem(6)) else write (33,'(2a)') mem(170)(1:lmem(170)),mem(5)(1:lmem(5)) end if if (opt(4).eq.1) then write (33,'(2a)') mem(171)(1:lmem(171)),mem(7)(1:lmem(7)) else if (opt(4).eq.3) then write (33,'(2a)') mem(171)(1:lmem(171)),mem(9)(1:lmem(9)) else write (33,'(2a)') mem(171)(1:lmem(171)),mem(8)(1:lmem(8)) end if write (33,'(a)') mem(172)(1:lmem(172)) if (opt(7).eq.1) then write (33,'(2a)') mem(173)(1:lmem(173)),mem(6)(1:lmem(6)) else write (33,'(2a)') mem(173)(1:lmem(173)),mem(5)(1:lmem(5)) end if if (opt(8).eq.1) then write (33,'(2a)') mem(174)(1:lmem(174)),mem(6)(1:lmem(6)) else write (33,'(2a)') mem(174)(1:lmem(174)),mem(5)(1:lmem(5)) end if ! Infrequently-changed parameters write (33,'(a)') mem(155)(1:lmem(155)) write (33,'(a)') mem(175)(1:lmem(175)) write (33,'(a)') mem(155)(1:lmem(155)) write (33,*) mem(176)(1:lmem(176)),rmax write (33,*) mem(177)(1:lmem(177)),rcen write (33,*) mem(178)(1:lmem(178)),m(1) * k_2 write (33,*) mem(179)(1:lmem(179)),jcen(1) * rcen_2 write (33,*) mem(180)(1:lmem(180)),jcen(2) * rcen_4 write (33,*) mem(181)(1:lmem(181)),jcen(3) * rcen_6 write (33,*) mem(182)(1:lmem(182)) write (33,*) mem(183)(1:lmem(183)) write (33,*) mem(184)(1:lmem(184)),cefac write (33,*) mem(185)(1:lmem(185)),ndump write (33,*) mem(186)(1:lmem(186)),nfun write (33,*) mem(188)(1:lmem(188)),alpha_t write (33,*) mem(189)(1:lmem(189)),alpha write (33,*) mem(190)(1:lmem(190)),mdot_gas0 write (33,*) mem(191)(1:lmem(191)),L_s write (33,*) mem(192)(1:lmem(192)),Rdisk0 write (33,*) mem(193)(1:lmem(193)),Mdot_peb write (33,*) mem(194)(1:lmem(194)),tau_s write (33,*) mem(195)(1:lmem(195)),kap write (33,*) mem(196)(1:lmem(196)),t0_dep write (33,*) mem(197)(1:lmem(197)),tau_dep if (opt(9).eq.1) then write (33,'(2a)') mem(198)(1:lmem(198)),mem(6)(1:lmem(6)) else write (33,'(2a)') mem(198)(1:lmem(198)),mem(5)(1:lmem(5)) end if if (opt(10).eq.1) then write (33,'(2a)') mem(199)(1:lmem(199)),mem(6)(1:lmem(6)) else write (33,'(2a)') mem(199)(1:lmem(199)),mem(5)(1:lmem(5)) end if if (opt(11).eq.1) then write (33,'(2a)') mem(200)(1:lmem(200)),mem(6)(1:lmem(6)) else write (33,'(2a)') mem(200)(1:lmem(200)),mem(5)(1:lmem(5)) end if !if (opt(12).eq.1) then !write (33,'(2a)') mem(199)(1:lmem(199)),mem(6)(1:lmem(6)) !else !write (33,'(2a)') mem(199)(1:lmem(199)),mem(5)(1:lmem(5)) !end if if (opt(12).eq.0) then write (33,'(2a)') mem(201)(1:lmem(201)),'0' else if (opt(12).eq.1) then write (33,'(2a)') mem(201)(1:lmem(201)),'1' else if (opt(12).eq.2) then write (33,'(2a)') mem(201)(1:lmem(201)),'2' else write (33,'(2a)') mem(201)(1:lmem(201)),'3' end if if (opt(13).eq.1) then write (33,'(2a)') mem(202)(1:lmem(202)),mem(6)(1:lmem(6)) else write (33,'(2a)') mem(202)(1:lmem(202)),mem(5)(1:lmem(5)) end if if (opt(14).eq.1) then write (33,'(2a)') mem(203)(1:lmem(203)),mem(6)(1:lmem(6)) else write (33,'(2a)') mem(203)(1:lmem(203)),mem(5)(1:lmem(5)) end if close (33) ! Create new version of the restart file 60 if (idp.eq.1) open (35, file='restart.tmp', status='unknown',err=60) 65 if (idp.eq.2) open (35, file=dumpfile(4), status='old', err=65) write (35,'(1x,i2)') opflag write (35,*) en(1) * k_2 write (35,*) am(1) * k_2 write (35,*) en(3) * k_2 write (35,*) am(3) * k_2 write (35,*) s(1,1) * k_2 write (35,*) s(2,1) * k_2 write (35,*) s(3,1) * k_2 close (35) end do !------------------------------------------------------------------------------ 312 format (1p,3(1x,e22.15),1x,i8) return end subroutine mio_dump !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% !> @author !> <NAME> ! !> @date 6 December 1999 ! ! DESCRIPTION: !> @brief Writes out an error message and terminates Mercury. ! !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% subroutine mio_err (unit,s1,ls1,s2,ls2,s3,ls3,s4,ls4) implicit none ! Input/Output integer, intent(in) :: unit integer, intent(in) :: ls1 integer, intent(in) :: ls2 integer, intent(in) :: ls3 integer, intent(in) :: ls4 character(len=80), intent(in) :: s1 character(len=80), intent(in) :: s2 character(len=*), intent(in) :: s3 character(len=*), intent(in) :: s4 !------------------------------------------------------------------------------ write (*,'(/,2a)') ' ERROR: Programme terminated. See information',' file for details.' write (unit,'(/,3a,/,2a)') s1(1:ls1),s2(1:ls2),s3(1:ls3),' ',s4(1:ls4) stop !------------------------------------------------------------------------------ end subroutine mio_err !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% !> @author !> <NAME> ! !> @date 25 February 2001 ! ! DESCRIPTION: !> @brief Writes a progress report to the log file (or the screen if you are running !! Mercury interactively). ! !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% subroutine mio_log (time,en,am) use physical_constant use mercury_constant use utilities implicit none ! Input real(double_precision), intent(in) :: time !< [in] current epoch (days) real(double_precision), intent(in) :: en(3) !< [in] (initial energy, current energy, energy change due to collision and ejection) of the system real(double_precision), intent(in) :: am(3) !< [in] (initial angular momentum, current angular momentum, !! angular momentum change due to collision and ejection) of the system ! Local integer :: year, month real(double_precision) :: tmp0, tmp1, t1 character(len=38) :: flog character(len=6) :: tstring !------------------------------------------------------------------------------ if (opt(3).eq.0.or.opt(3).eq.2) then tstring = mem(1) flog = '(1x,a,f14.1,a,2(a,1p1e12.5))' else if (opt(3).eq.1) then flog = '(1x,a,i10,1x,i2,1x,f4.1,2(a,1p1e12.5))' else tstring = mem(2) flog = '(1x,a,f14.3,a,2(a,1p1e12.5))' end if tmp0 = 0.d0 tmp1 = 0.d0 if (en(1).ne.0) tmp0 = (en(2) + en(3) - en(1)) / abs(en(1)) if (am(1).ne.0) tmp1 = (am(2) + am(3) - am(1)) / abs(am(1)) if (opt(3).eq.1) then call mio_jd2y (time,year,month,t1) write (*,flog) mem(64)(1:lmem(64)), year, month, t1,mem(65)(1:lmem(65)), tmp0,mem(66)(1:lmem(66)), tmp1 else if (opt(3).eq.0) t1 = time if (opt(3).eq.2) t1 = time - tstart if (opt(3).eq.3) t1 = (time - tstart) / 365.25d0 !write (*,flog) mem(63)(1:lmem(63)), t1, tstring,mem(65)(1:lmem(65)), tmp0, mem(66)(1:lmem(66)), tmp1 end if !------------------------------------------------------------------------------ return end subroutine mio_log !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ! MIO_OUT.FOR (ErikSoft 13 February 2001) !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ! Author: <NAME> ! Writes output variables for each object to an output file. Each variable ! is scaled between the minimum and maximum possible values and then ! written in a compressed format using ASCII characters. ! The output variables are: ! r = the radial distance ! theta = polar angle ! phi = azimuthal angle ! fv = 1 / [1 + 2(ke/be)^2], where be and ke are the object's binding and ! kinetic energies. (Note that 0 < fv < 1). ! vtheta = polar angle of velocity vector ! vphi = azimuthal angle of the velocity vector ! If this is the first output (OPFLAG = -1), or the first output since the ! number of the objects or their masses have changed (OPFLAG = 1), then ! the names, masses and spin components of all the objects are also output. ! N.B. Each object's distance must lie between RCEN < R < RMAX ! === !------------------------------------------------------------------------------ !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% !> @author !> <NAME> ! !> @date 13 February 2001 ! ! DESCRIPTION: !> @brief Writes output variables for each object to an output file. Each variable !! is scaled between the minimum and maximum possible values and then !! written in a compressed format using ASCII characters. !!\n The output variables are: !!\n r = the radial distance !!\n theta = polar angle !!\n phi = azimuthal angle !!\n fv = 1 / [1 + 2(ke/be)^2], where be and ke are the object's binding and !!\n kinetic energies. (Note that 0 < fv < 1). !!\n vtheta = polar angle of velocity vector !!\n vphi = azimuthal angle of the velocity vector !!\n\n !! If this is the first output (OPFLAG = -1), or the first output since the !! number of the objects or their masses have changed (OPFLAG = 1), then !! the names, masses and spin components of all the objects are also output. ! !> @note Each object's distance must lie between RCEN < R < RMAX ! !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% subroutine mio_out (time,jcen,rcen,nbod,nbig,m,xh,vh,s,rho,stat,id,opflag,outfile,m_x) use physical_constant use mercury_constant use ascii_conversion use orbital_elements implicit none ! Input integer, intent(in) :: nbod !< [in] current number of bodies (1: star; 2-nbig: big bodies; nbig+1-nbod: small bodies) integer, intent(in) :: nbig !< [in] current number of big bodies (ones that perturb everything else) integer, intent(in) :: stat(nbod) !< [in] status (0 => alive, <>0 => to be removed) real(double_precision), intent(in) :: time !< [in] current epoch (days) real(double_precision), intent(in) :: jcen(3) !< [in] J2,J4,J6 for central body (units of RCEN^i for Ji) real(double_precision), intent(in) :: rcen !< [in] radius of central body (AU) real(double_precision), intent(in) :: m(nbod) !< [in] mass (in solar masses * K2) real(double_precision), intent(in) :: m_x(nbod) !< [in] mass (in solar masses * K2) real(double_precision), intent(in) :: xh(3,nbod) !< [in] coordinates (x,y,z) with respect to the central body (AU) real(double_precision), intent(in) :: vh(3,nbod) !< [in] velocities (vx,vy,vz) with respect to the central body (AU/day) real(double_precision), intent(in) :: s(3,nbod) !< [in] spin angular momentum (solar masses AU^2/day) real(double_precision), intent(in) :: rho(nbod) !< [in] physical density (g/cm^3) character(len=80), intent(in) :: outfile character(len=8), intent(in) :: id(nbod) !< [in] name of the object (8 characters) ! Input/Output integer, intent(inout) :: opflag !< [in,out] integration mode (-2 = synchronising epochs) !!\n -1 = integrating towards start epoch !!\n 0 = main integration, normal output !!\n 1 = main integration, full output ! Local integer :: k, len, nchar real(double_precision) :: rhocgs,k_2,rfac,rcen_2,fr,fv,theta,phi,vtheta,vphi character(len=180) :: header,c(nb_bodies_initial) character(len=5) :: fout integer :: error !------------------------------------------------------------------------------ rhocgs = AU * AU * AU * K2 / MSUN k_2 = 1.d0 / K2 rcen_2 = 1.d0 / (rcen * rcen) ! Scaling factor (maximum possible range) for distances rfac = log10 (rmax / rcen) ! Create the format list, FOUT, used when outputting the orbital elements if (opt(4).eq.1) nchar = 2 if (opt(4).eq.2) nchar = 4 if (opt(4).eq.3) nchar = 7 len = 3 + 6 * nchar fout(1:5) = '(a )' if (len.lt.10) write (fout(3:3),'(i1)') len if (len.ge.10) write (fout(3:4),'(i2)') len ! Open the orbital-elements output file open (21, file=outfile, status='old', position='append', iostat=error) if (error /= 0) then write (*,'(/,2a)') " ERROR: Programme terminated. Unable to open ",trim(outfile) stop end if !------------------------------------------------------------------------------ ! SPECIAL OUTPUT PROCEDURE ! If this is a new integration or a complete output is required (e.g. because ! the number of objects has changed), then output object details & parameters. if (opflag.eq.-1.or.opflag.eq.1 .or. opflag.eq.0) then ! Compose a header line with time, number of objects and relevant parameters header(1:8) = mio_fl2c (time) header(9:16) = mio_re2c (dble(nbig - 1), 0.d0, 11239423.99d0) header(12:19) = mio_re2c (dble(nbod - nbig),0.d0, 11239423.99d0) header(15:22) = mio_fl2c (m(1) * k_2) header(23:30) = mio_fl2c (jcen(1) * rcen_2) header(31:38) = mio_fl2c (jcen(2) * rcen_2 * rcen_2) header(39:46) = mio_fl2c (jcen(3) * rcen_2 * rcen_2 * rcen_2) header(47:54) = mio_fl2c (rcen) header(55:62) = mio_fl2c (rmax) ! For each object, compress its index number, name, mass, spin components ! and density (some of these need to be converted to normal units). do k = 2, nbod c(k)(1:8) = mio_re2c (dble(k - 1), 0.d0, 11239423.99d0) c(k)(4:11) = id(k) c(k)(12:19) = mio_fl2c (m(k) * k_2) c(k)(20:27) = mio_fl2c (s(1,k) * k_2) c(k)(28:35) = mio_fl2c (s(2,k) * k_2) c(k)(36:43) = mio_fl2c (s(3,k) * k_2) c(k)(44:51) = mio_fl2c (rho(k) / rhocgs) c(k)(52:59) = mio_fl2c (m_x(k) * k_2) end do ! Write compressed output to file write (21,'(a1,a2,i2,a62,i1)') char(12),'6a',algor,header(1:62),opt(4) do k = 2, nbod write (21,'(a59)') c(k)(1:59) !write (21,'(a51)') c(k)(1:51) end do end if !------------------------------------------------------------------------------ ! NORMAL OUTPUT PROCEDURE ! Compose a header line containing the time and number of objects header(1:8) = mio_fl2c (time) header(9:16) = mio_re2c (dble(nbig - 1), 0.d0, 11239423.99d0) header(12:19) = mio_re2c (dble(nbod - nbig), 0.d0, 11239423.99d0) ! Calculate output variables for each body and convert to compressed format do k = 2, nbod call mco_x2ov (rcen,m(1),m(k),xh(1,k),xh(2,k),xh(3,k),vh(1,k),vh(2,k),vh(3,k),fr,theta,phi,fv,vtheta,vphi) ! Object's index number and output variables c(k)(1:8) = mio_re2c (dble(k - 1), 0.d0, 11239423.99d0) c(k)(4:11) = mio_re2c (fr, 0.d0, rfac) c(k)(4+ nchar:11+ nchar) = mio_re2c (theta, 0.d0, PI) c(k)(4+2*nchar:11+2*nchar) = mio_re2c (phi, 0.d0, TWOPI) c(k)(4+3*nchar:11+3*nchar) = mio_re2c (fv, 0.d0, 1.d0) c(k)(4+4*nchar:11+4*nchar) = mio_re2c (vtheta, 0.d0, PI) c(k)(4+5*nchar:11+5*nchar) = mio_re2c (vphi, 0.d0, TWOPI) end do ! Write compressed output to file write (21,'(a1,a2,a14)') char(12),'6b',header(1:14) do k = 2, nbod write (21,fout) c(k)(1:len) end do close (21) opflag = 0 !------------------------------------------------------------------------------ return end subroutine mio_out !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% !> @author !> <NAME> ! !> @date 31 January 2001 ! ! DESCRIPTION: !> @brief Creates a filename and opens a file to store aei information for an object. !! The filename is based on the name of the object. ! !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% subroutine mio_clo (id,unitnum,header,lenhead) use physical_constant use mercury_constant use utilities, only : mio_spl implicit none ! Input/Output integer, intent(in) :: unitnum integer, intent(in) :: lenhead character(len=8), intent(in) :: id !< [in] name of the object (8 characters) character(len=250), intent(in) :: header ! Parameter character(len=4),parameter :: extn = ".clo" ! Local integer :: j,k,itmp,nsub,lim(2,4) logical test character(len=250) :: filename !------------------------------------------------------------------------------ ! Create a filename based on the object's name call mio_spl (8,id,nsub,lim) itmp = min(7,lim(2,1)-lim(1,1)) filename(1:itmp+1) = id(1:itmp+1) filename(itmp+2:itmp+5) = extn do j = itmp + 6, 250 filename(j:j) = ' ' end do ! Check for inappropriate characters in the filename do j = 1, itmp + 1 do k = 1, 5 if (filename(j:j).eq.bad(k)) filename(j:j) = '_' end do end do ! If the file exists already, give a warning and don't overwrite it inquire (file=filename, exist=test) if (test) then write (*,'(/,3a)') mem(121)(1:lmem(121)),mem(87)(1:lmem(87)),filename(1:80) else open (unitnum, file=filename, status='new') write (unitnum, '(/,30x,a8,//,a)') id,header(1:lenhead) end if !------------------------------------------------------------------------------ return end subroutine mio_clo !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% !> @author !> <NAME> ! !> @date 31 January 2001 ! ! DESCRIPTION: !> @brief Creates a filename and opens a file to store aei information for an object. !! The filename is based on the name of the object. ! !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% subroutine mio_aei (id,unitnum,header,lenhead) use physical_constant use mercury_constant use utilities, only : mio_spl implicit none ! Input/Output integer, intent(in) :: unitnum integer, intent(in) :: lenhead character(len=8), intent(in) :: id !< [in] name of the object (8 characters) character(len=250), intent(in) :: header ! Parameter character(len=4),parameter :: extn = ".aei" ! Local integer :: j,k,itmp,nsub,lim(2,4) logical test character(len=250) :: filename !------------------------------------------------------------------------------ ! Create a filename based on the object's name call mio_spl (8,id,nsub,lim) itmp = min(7,lim(2,1)-lim(1,1)) filename(1:itmp+1) = id(1:itmp+1) filename(itmp+2:itmp+5) = extn do j = itmp + 6, 250 filename(j:j) = ' ' end do ! Check for inappropriate characters in the filename do j = 1, itmp + 1 do k = 1, 5 if (filename(j:j).eq.bad(k)) filename(j:j) = '_' end do end do ! If the file exists already, give a warning and don't overwrite it inquire (file=filename, exist=test) if (test) then write (*,'(/,3a)') mem(121)(1:lmem(121)),mem(87)(1:lmem(87)),filename(1:80) else open (unitnum, file=filename, status='new') ! write (unitnum, '(/,30x,a8,//,a)') id,header(1:lenhead) end if !------------------------------------------------------------------------------ return end subroutine mio_aei end module mercury_outputs <file_sep>!****************************************************************************** ! MODULE: forces !****************************************************************************** ! ! DESCRIPTION: !> @brief Modules that contains all common forces ! !****************************************************************************** module forces use types_numeriques use mercury_globals implicit none private public :: mfo_all public :: mfo_ngf ! Needed by HYBRID and MVS public :: mfo_obl ! Needed by HYBRID and MVS on respectively mfo_hy and mfo_mvs contains !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% !> @author <NAME> !> ! !> @date 2 March 2001 ! ! DESCRIPTION: !> @brief Calculates accelerations on a set of NBOD bodies (of which NBIG are Big) !! due to Newtonian gravitational perturbations, post-Newtonian !! corrections (if required), cometary non-gravitational forces (if required) !! and user-defined forces (if required). ! !> @note Input/output must be in coordinates with respect to the central body. ! !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% subroutine mfo_all (time,jcen,nbod,nbig,m,x,v,s,rcrit,a,stat,ngf,ngflag,nce,ice,jce,rphys) use physical_constant use mercury_constant use user_module implicit none ! Input integer, intent(in) :: nbod !< [in] current number of bodies (1: star; 2-nbig: big bodies; nbig+1-nbod: small bodies) integer, intent(in) :: nbig !< [in] current number of big bodies (ones that perturb everything else) integer, intent(in) :: ngflag !< [in] do any bodies experience non-grav. forces? !!\n ( 0 = no non-grav forces) !!\n 1 = cometary jets only !!\n 2 = radiation pressure/P-R drag only !!\n 3 = both integer, intent(in) :: stat(nbod) !< [in] status (0 => alive, <>0 => to be removed) integer, intent(in) :: nce integer, intent(in) :: ice(nce) integer, intent(in) :: jce(nce) real(double_precision), intent(in) :: time !< [in] current epoch (days) real(double_precision), intent(in) :: jcen(3) !< [in] J2,J4,J6 for central body (units of RCEN^i for Ji) real(double_precision), intent(in) :: m(nbod) !< [in] mass (in solar masses * K2) real(double_precision), intent(in) :: rphys(nbod) !< [in] radius (in AU) real(double_precision), intent(in) :: x(3,nbod) real(double_precision), intent(in) :: v(3,nbod) real(double_precision), intent(in) :: s(3,nbod) !< [in] spin angular momentum (solar masses AU^2/day) real(double_precision), intent(in) :: ngf(4,nbod) !< [in] non gravitational forces parameters !! \n(1-3) cometary non-gravitational (jet) force parameters !! \n(4) beta parameter for radiation pressure and P-R drag real(double_precision), intent(in) :: rcrit(nbod) ! Output real(double_precision), intent(out) :: a(3,nbod) ! Local integer :: j real(double_precision) :: acor(3,nb_bodies_initial),acen(3) !------------------------------------------------------------------------------ ! Newtonian gravitational forces call mfo_grav (nbod,nbig,m,x,v,a,stat) ! Correct for oblateness of the central body if (jcen(1).ne.0.or.jcen(2).ne.0.or.jcen(3).ne.0) then call mfo_obl (jcen,nbod,m,x,acor,acen) do j = 2, nbod a(1,j) = a(1,j) + (acor(1,j) - acen(1)) a(2,j) = a(2,j) + (acor(2,j) - acen(2)) a(3,j) = a(3,j) + (acor(3,j) - acen(3)) end do end if ! Include non-gravitational (cometary jet) accelerations if necessary if ((ngflag.eq.1).or.(ngflag.eq.3)) then call mfo_ngf (nbod,x,v,acor,ngf) do j = 2, nbod a(1,j) = a(1,j) + acor(1,j) a(2,j) = a(2,j) + acor(2,j) a(3,j) = a(3,j) + acor(3,j) end do end if ! Include radiation pressure/Poynting-Robertson drag if necessary if (ngflag.eq.2.or.ngflag.eq.3) then call mfo_pr (nbod,nbig,m,x,v,acor,ngf) do j = 2, nbod a(1,j) = a(1,j) + acor(1,j) a(2,j) = a(2,j) + acor(2,j) a(3,j) = a(3,j) + acor(3,j) end do end if ! Include post-Newtonian corrections if required if (opt(7).eq.1) then call mfo_pn (nbod,nbig,m,x,v,acor) do j = 2, nbod a(1,j) = a(1,j) + acor(1,j) a(2,j) = a(2,j) + acor(2,j) a(3,j) = a(3,j) + acor(3,j) end do end if ! Include user-defined accelerations if required if (opt(8).eq.1) then call mfo_user (time,jcen,nbod,nbig,m,rphys,x,v,acor) do j = 2, nbod a(1,j) = a(1,j) + acor(1,j) a(2,j) = a(2,j) + acor(2,j) a(3,j) = a(3,j) + acor(3,j) end do end if !------------------------------------------------------------------------------ return end subroutine mfo_all !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% !> @author <NAME> !> ! !> @date 3 October 2000 ! ! DESCRIPTION: !> @brief Calculates accelerations on a set of NBOD bodies (NBIG of which are Big) !! due to gravitational perturbations by all the other bodies, except that !! Small bodies do not interact with one another.\n\n !! !! The positions and velocities are stored in arrays X, V with the format !! (x,y,z) and (vx,vy,vz) for each object in succession. The accelerations !! are stored in the array A (ax,ay,az). ! !> @note All coordinates and velocities must be with respect to central body!!! ! !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% subroutine mfo_grav (nbod,nbig,m,x,v,a,stat) use physical_constant use mercury_constant implicit none ! Input integer, intent(in) :: nbod !< [in] current number of bodies (1: star; 2-nbig: big bodies; nbig+1-nbod: small bodies) integer, intent(in) :: nbig !< [in] current number of big bodies (ones that perturb everything else) integer, intent(in) :: stat(nbod) !< [in] status (0 => alive, <>0 => to be removed) real(double_precision), intent(in) :: m(nbod) !< [in] mass (in solar masses * K2) real(double_precision), intent(in) :: x(3,nbod) real(double_precision), intent(in) :: v(3,nbod) ! Output real(double_precision), intent(out) :: a(3,nbod) ! Local integer :: i, j real(double_precision) :: sx, sy, sz, dx, dy, dz, tmp1, tmp2, s_1, s2, s_3, r3(nb_bodies_initial) !------------------------------------------------------------------------------ sx = 0.d0 sy = 0.d0 sz = 0.d0 do i = 2, nbod a(1,i) = 0.d0 a(2,i) = 0.d0 a(3,i) = 0.d0 s2 = x(1,i)*x(1,i) + x(2,i)*x(2,i) + x(3,i)*x(3,i) s_1 = 1.d0 / sqrt(s2) r3(i) = s_1 * s_1 * s_1 end do do i = 2, nbod tmp1 = m(i) * r3(i) sx = sx - tmp1 * x(1,i) sy = sy - tmp1 * x(2,i) sz = sz - tmp1 * x(3,i) end do ! Direct terms do i = 2, nbig do j = i + 1, nbod dx = x(1,j) - x(1,i) dy = x(2,j) - x(2,i) dz = x(3,j) - x(3,i) s2 = dx*dx + dy*dy + dz*dz s_1 = 1.d0 / sqrt(s2) s_3 = s_1 * s_1 * s_1 tmp1 = s_3 * m(i) tmp2 = s_3 * m(j) a(1,j) = a(1,j) - tmp1 * dx a(2,j) = a(2,j) - tmp1 * dy a(3,j) = a(3,j) - tmp1 * dz a(1,i) = a(1,i) + tmp2 * dx a(2,i) = a(2,i) + tmp2 * dy a(3,i) = a(3,i) + tmp2 * dz end do end do ! Indirect terms (add these on last to reduce roundoff error) do i = 2, nbod tmp1 = m(1) * r3(i) a(1,i) = a(1,i) + sx - tmp1 * x(1,i) a(2,i) = a(2,i) + sy - tmp1 * x(2,i) a(3,i) = a(3,i) + sz - tmp1 * x(3,i) end do !------------------------------------------------------------------------------ return end subroutine mfo_grav !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% !> @author <NAME> !> ! !> @date 29 November 1999 ! ! DESCRIPTION: !> @brief Calculates accelerations on a set of NBOD bodies due to cometary !! non-gravitational jet forces. The positions and velocities are stored in !! arrays X, V with the format (x,y,z) and (vx,vy,vz) for each object in !! succession. The accelerations are stored in the array A (ax,ay,az). The !! non-gravitational accelerations follow a force law described by Marsden !! et al. (1973) Astron. J. 211-225, with magnitude determined by the !! parameters NGF(1,2,3) for each object. ! !> @note All coordinates and velocities must be with respect to central body!!! ! !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% subroutine mfo_ngf (nbod,x,v,a,ngf) use physical_constant use mercury_constant implicit none ! Input integer, intent(in) :: nbod !< [in] current number of bodies (1: star; 2-nbig: big bodies; nbig+1-nbod: small bodies) real(double_precision), intent(in) :: x(3,nbod) real(double_precision), intent(in) :: v(3,nbod) real(double_precision), intent(in) :: ngf(4,nbod) !< [in] non gravitational forces parameters !! \n(1-3) cometary non-gravitational (jet) force parameters !! \n(4) beta parameter for radiation pressure and P-R drag ! Output real(double_precision), intent(out) :: a(3,nbod) ! Local integer :: j real(double_precision) :: r2,r,rv,q,g,tx,ty,tz,nx,ny,nz,a1,a2,a3 !------------------------------------------------------------------------------ do j = 2, nbod r2 = x(1,j)*x(1,j) + x(2,j)*x(2,j) +x(3,j)*x(3,j) ! Only calculate accelerations if body is close to the Sun (R < 9.36 AU), ! or if the non-gravitational force parameters are exceptionally large. if (r2.lt.88.d0.or.abs(ngf(1,j)).gt.1d-7.or.abs(ngf(2,j)).gt.1d-7.or.abs(ngf(3,j)).gt.1d-7) then r = sqrt(r2) rv = x(1,j)*v(1,j) + x(2,j)*v(2,j) + x(3,j)*v(3,j) ! Calculate Q = R / R0, where R0 = 2.808 AU q = r * .3561253561253561d0 g = .111262d0 * q**(-2.15d0) * (1.d0+q**5.093d0)**(-4.6142d0) ! Within-orbital-plane transverse vector components tx = r2*v(1,j) - rv*x(1,j) ty = r2*v(2,j) - rv*x(2,j) tz = r2*v(3,j) - rv*x(3,j) ! Orbit-normal vector components nx = x(2,j)*v(3,j) - x(3,j)*v(2,j) ny = x(3,j)*v(1,j) - x(1,j)*v(3,j) nz = x(1,j)*v(2,j) - x(2,j)*v(1,j) ! Multiplication factors a1 = ngf(1,j) * g / r a2 = ngf(2,j) * g / sqrt(tx*tx + ty*ty + tz*tz) a3 = ngf(3,j) * g / sqrt(nx*nx + ny*ny + nz*nz) ! X,Y and Z components of non-gravitational acceleration a(1,j) = a1*x(1,j) + a2*tx + a3*nx a(2,j) = a1*x(2,j) + a2*ty + a3*ny a(3,j) = a1*x(3,j) + a2*tz + a3*nz else a(1,j) = 0.d0 a(2,j) = 0.d0 a(3,j) = 0.d0 end if end do !------------------------------------------------------------------------------ return end subroutine mfo_ngf !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% !> @author !> <NAME> ! !> @date 3 October 2000 ! ! DESCRIPTION: !> @brief Calculates post-Newtonian relativistic corrective accelerations for a set !! of NBOD bodies (NBIG of which are Big).\n\n !! !! This routine should not be called from the symplectic algorithm MAL_MVS !! or the conservative Bulirsch-Stoer algorithm MAL_BS2. ! !> @note All coordinates and velocities must be with respect to central body!!! ! !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% subroutine mfo_pn (nbod,nbig,m,x,v,a) use physical_constant use mercury_constant implicit none ! Input integer, intent(in) :: nbod !< [in] current number of bodies (1: star; 2-nbig: big bodies; nbig+1-nbod: small bodies) integer, intent(in) :: nbig !< [in] current number of big bodies (ones that perturb everything else) real(double_precision), intent(in) :: m(nbod) !< [in] mass (in solar masses * K2) real(double_precision), intent(in) :: x(3,nbod) real(double_precision), intent(in) :: v(3,nbod) ! Output real(double_precision), intent(out) :: a(3,nbod) ! Local integer :: j !------------------------------------------------------------------------------ do j = 1, nbod a(1,j) = 0.d0 a(2,j) = 0.d0 a(3,j) = 0.d0 end do !------------------------------------------------------------------------------ return end subroutine mfo_pn !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% !> @author !> <NAME> ! !> @date 3 October 2000 ! ! DESCRIPTION: !> @brief Calculates radiation pressure and Poynting-Robertson drag for a set !! of NBOD bodies (NBIG of which are Big).\n\n !! !! This routine should not be called from the symplectic algorithm MAL_MVS !! or the conservative Bulirsch-Stoer algorithm MAL_BS2. ! !> @note All coordinates and velocities must be with respect to central body!!! ! !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% subroutine mfo_pr (nbod,nbig,m,x,v,a,ngf) use physical_constant use mercury_constant implicit none ! Input integer, intent(in) :: nbod !< [in] current number of bodies (1: star; 2-nbig: big bodies; nbig+1-nbod: small bodies) integer, intent(in) :: nbig !< [in] current number of big bodies (ones that perturb everything else) real(double_precision), intent(in) :: m(nbod) !< [in] mass (in solar masses * K2) real(double_precision), intent(in) :: x(3,nbod) real(double_precision), intent(in) :: v(3,nbod) real(double_precision), intent(in) :: ngf(4,nbod) !< [in] non gravitational forces parameters !! \n(1-3) cometary non-gravitational (jet) force parameters !! \n(4) beta parameter for radiation pressure and P-R drag ! Output real(double_precision), intent(out) :: a(3,nbod) ! Local integer :: j !------------------------------------------------------------------------------ do j = 1, nbod a(1,j) = 0.d0 a(2,j) = 0.d0 a(3,j) = 0.d0 end do !------------------------------------------------------------------------------ return end subroutine mfo_pr !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% !> @author <NAME> !> ! !> @date 2 October 2000 ! ! DESCRIPTION: !> @brief Calculates barycentric accelerations of NBOD bodies due to oblateness of !! the central body. Also returns the corresponding barycentric acceleration !! of the central body. ! !> @note All coordinates must be with respect to the central body!!! ! !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% subroutine mfo_obl (jcen,nbod,m,x,a,acen) use physical_constant use mercury_constant implicit none ! Input integer, intent(in) :: nbod !< [in] current number of bodies (1: star; 2-nbig: big bodies; nbig+1-nbod: small bodies) real(double_precision), intent(in) :: jcen(3) !< [in] J2,J4,J6 for central body (units of RCEN^i for Ji) real(double_precision), intent(in) :: m(nbod) !< [in] mass (in solar masses * K2) real(double_precision), intent(in) :: x(3,nbod) ! Output real(double_precision), intent(out) :: acen(3) real(double_precision), intent(out) :: a(3,nbod) ! Local integer :: i real(double_precision) :: jr2,jr4,jr6,r2,r_1,r_2,r_3,u2,u4,u6,tmp1,tmp2,tmp3,tmp4 !------------------------------------------------------------------------------ acen(1) = 0.d0 acen(2) = 0.d0 acen(3) = 0.d0 do i = 2, nbod ! Calculate barycentric accelerations on the objects r2 = x(1,i)*x(1,i) + x(2,i)*x(2,i) + x(3,i)*x(3,i) r_1 = 1.d0 / sqrt(r2) r_2 = r_1 * r_1 r_3 = r_2 * r_1 jr2 = jcen(1) * r_2 jr4 = jcen(2) * r_2 * r_2 jr6 = jcen(3) * r_2 * r_2 * r_2 u2 = x(3,i) * x(3,i) * r_2 u4 = u2 * u2 u6 = u4 * u2 tmp1 = m(1) * r_3 tmp2 = jr2*(7.5d0*u2 - 1.5d0) + jr4*(39.375d0*u4 - 26.25d0*u2 + 1.875d0) + & jr6*(187.6875d0*u6 -216.5625d0*u4 +59.0625d0*u2 -2.1875d0) tmp3 = jr2*3.d0 + jr4*(17.5d0*u2 - 7.5d0) + jr6*(86.625d0*u4 - 78.75d0*u2 + 13.125d0) a(1,i) = x(1,i) * tmp1 * tmp2 a(2,i) = x(2,i) * tmp1 * tmp2 a(3,i) = x(3,i) * tmp1 * (tmp2 - tmp3) ! Calculate barycentric accelerations on the central body tmp4 = m(i) / m(1) acen(1) = acen(1) - tmp4 * a(1,i) acen(2) = acen(2) - tmp4 * a(2,i) acen(3) = acen(3) - tmp4 * a(3,i) end do !------------------------------------------------------------------------------ return end subroutine mfo_obl end module forces <file_sep>!****************************************************************************** ! MODULE: algo_hybrid !****************************************************************************** ! ! DESCRIPTION: !> @brief Modules that gather various functions about the hybrid algorithm.\n\n !! The hybrid symplectic algorithm is described in J.E.Chambers (1999) !! Monthly Notices of the RAS, vol 304, pp793. ! !****************************************************************************** module algo_hybrid use types_numeriques use mercury_globals use user_module use forces, only : mfo_ngf use system_properties, only : mco_iden implicit none private ! Values that need to be saved in mdt_hy real(double_precision) :: hrec real(double_precision), dimension(:,:), allocatable :: angf, ausr, a ! (3,Number of bodies) public :: mdt_hy, mco_h2dh, mco_dh2h, allocate_hy contains !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% !> @author !> <NAME> ! !> @date 2011 ! ! DESCRIPTION: !> @brief allocate various private variable of the module to avoid testing at each timestep ! !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% subroutine allocate_hy(nb_bodies) implicit none integer, intent(in) :: nb_bodies !< [in] number of bodies, that is, the size of the arrays if (.not. allocated(a)) then allocate(a(3,nb_bodies)) a(1:3,1:nb_bodies) = 0.d0 end if if (.not. allocated(angf)) then allocate(angf(3,nb_bodies)) angf(1:3,1:nb_bodies) = 0.d0 end if if (.not. allocated(ausr)) then allocate(ausr(3,nb_bodies)) ausr(1:3,1:nb_bodies) = 0.d0 end if end subroutine allocate_hy !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% !> @author !> <NAME> ! !> @date 2 March 2001 ! ! DESCRIPTION: !> @brief Integrates NBOD bodies (of which NBIG are Big) for one timestep H !!\n using a second-order hybrid-symplectic integrator algorithm !!\n !!\n DTFLAG = 0 implies first ever call to this subroutine, !!\n = 1 implies first call since number/masses of objects changed. !!\n = 2 normal call ! ! @note Input/output must be in democratic heliocentric coordinates. ! !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% subroutine mdt_hy (time,h0,tol,en,am,jcen,rcen,nbod,nbig,m,x,v,s,rphys,rcrit,rce,stat,id,ngf,dtflag,ngflag,& opflag,colflag,nclo,iclo,jclo,dclo,tclo,ixvclo,jxvclo,m_x,rho) use physical_constant use mercury_constant use drift use dynamic implicit none ! Input integer, intent(in) :: nbod !< [in] current number of bodies (1: star; 2-nbig: big bodies; nbig+1-nbod: small bodies) integer, intent(in) :: nbig !< [in] current number of big bodies (ones that perturb everything else) integer, intent(in) :: ngflag !< [in] do any bodies experience non-grav. forces? !!\n ( 0 = no non-grav forces) !!\n 1 = cometary jets only !!\n 2 = radiation pressure/P-R drag only !!\n 3 = both integer, intent(in) :: opflag !< [in] integration mode (-2 = synchronising epochs) !!\n -1 = integrating towards start epoch !!\n 0 = main integration, normal output !!\n 1 = main integration, full output real(double_precision), intent(in) :: time !< [in] current epoch (days) real(double_precision), intent(in) :: h0 !< [in] initial integration timestep (days) real(double_precision), intent(in) :: tol !< [in] Integrator tolerance parameter (approx. error per timestep) real(double_precision), intent(in) :: am(3) !< [in] (initial angular momentum, current angular momentum, !! angular momentum change due to collision and ejection) of the system real(double_precision), intent(in) :: jcen(3) !< [in] J2,J4,J6 for central body (units of RCEN^i for Ji) real(double_precision), intent(in) :: rcen !< [in] radius of central body (AU) real(double_precision), intent(in) :: rphys(nbod) real(double_precision), intent(in) :: rce(nbod) real(double_precision), intent(in) :: rcrit(nbod) real(double_precision), intent(in) :: ngf(4,nbod) !< [in] non gravitational forces parameters !! \n(1-3) cometary non-gravitational (jet) force parameters !! \n(4) beta parameter for radiation pressure and P-R drag character(len=8), intent(in) :: id(nbod) !< [in] name of the object (8 characters) ! Output integer, intent(out) :: colflag integer, intent(out) :: nclo integer, intent(out) :: iclo(CMAX) integer, intent(out) :: jclo(CMAX) real(double_precision), intent(out) :: tclo(CMAX) real(double_precision), intent(out) :: dclo(CMAX) real(double_precision), intent(out) :: ixvclo(6,CMAX) real(double_precision), intent(out) :: jxvclo(6,CMAX) ! Input/Output integer, intent(inout) :: stat(nbod) !< [in,out] status (0 => alive, <>0 => to be removed) integer, intent(inout) :: dtflag real(double_precision), intent(inout) :: m(nbod) !< [in,out] mass (in solar masses * K2) real(double_precision), intent(inout) :: m_x(nbod) !< [in,out] mass of element X (in solar masses * K2) real(double_precision), intent(inout) :: rho(nbod) ! density real(double_precision), intent(inout) :: x(3,nbod) real(double_precision), intent(inout) :: v(3,nbod) real(double_precision), intent(inout) :: s(3,nbod) !< [in,out] spin angular momentum (solar masses AU^2/day) real(double_precision), intent(inout) :: en(3) !< [in,out] (initial energy, current energy, energy change due to collision and ejection) of the system ! Local integer :: j,nce,iflag integer, dimension(nbod) :: ce ! is the planet in a close encounter? integer, dimension(CMAX) :: ice, jce ! arrays for close encounters real(double_precision) :: hby2,x0(3,nbod),v0(3,nbod),mvsum(3),temp !------------------------------------------------------------------------------ hby2 = h0 * .5d0 nclo = 0 colflag = 0 ! If accelerations from previous call are not valid, calculate them now if (dtflag.ne.2) then if (dtflag.eq.0) hrec = h0 call mfo_hy (jcen,nbod,nbig,m,x,rcrit,a,stat) dtflag = 2 do j = 2, nbod angf(1,j) = 0.d0 angf(2,j) = 0.d0 angf(3,j) = 0.d0 ausr(1,j) = 0.d0 ausr(2,j) = 0.d0 ausr(3,j) = 0.d0 end do ! If required, apply non-gravitational and user-defined forces if (opt(8).eq.1) call mfo_user (time,jcen,nbod,nbig,m,rphys,x,v,ausr) if ((ngflag.eq.1).or.(ngflag.eq.3)) call mfo_ngf (nbod,x,v,angf,ngf) end if ! Advance interaction Hamiltonian for H/2 do j = 2, nbod v(1,j) = v(1,j) + hby2 * (angf(1,j) + ausr(1,j) + a(1,j)) v(2,j) = v(2,j) + hby2 * (angf(2,j) + ausr(2,j) + a(2,j)) v(3,j) = v(3,j) + hby2 * (angf(3,j) + ausr(3,j) + a(3,j)) end do ! Advance solar Hamiltonian for H/2 mvsum(1) = 0.d0 mvsum(2) = 0.d0 mvsum(3) = 0.d0 do j = 2, nbod mvsum(1) = mvsum(1) + m(j) * v(1,j) mvsum(2) = mvsum(2) + m(j) * v(2,j) mvsum(3) = mvsum(3) + m(j) * v(3,j) end do temp = hby2 / m(1) mvsum(1) = temp * mvsum(1) mvsum(2) = temp * mvsum(2) mvsum(3) = temp * mvsum(3) do j = 2, nbod x(1,j) = x(1,j) + mvsum(1) x(2,j) = x(2,j) + mvsum(2) x(3,j) = x(3,j) + mvsum(3) end do ! Save the current coordinates and velocities !~ x0(:,:) = x(:,:) !~ v0(:,:) = v(:,:) call mco_iden (time,jcen,nbod,nbig,h0,m,x,v,x0,v0,ngf,ngflag) ! Advance H_K for H do j = 2, nbod iflag = 0 call drift_one (m(1),x(1,j),x(2,j),x(3,j),v(1,j),v(2,j),v(3,j),h0,iflag) end do ! Check whether any object separations were < R_CRIT whilst advancing H_K call mce_snif (h0,2,nbod,nbig,x0,v0,x,v,rcrit,ce,nce,ice,jce) ! If objects had close encounters, advance H_K using Bulirsch-Stoer instead if (nce.gt.0) then do j = 2, nbod if (ce(j).ne.0) then x(1,j) = x0(1,j) x(2,j) = x0(2,j) x(3,j) = x0(3,j) v(1,j) = v0(1,j) v(2,j) = v0(2,j) v(3,j) = v0(3,j) end if end do call mdt_hkce (time,h0,hrec,tol,en(3),jcen,rcen,nbod,nbig,m,x,v,s,rphys,rcrit,rce,stat,id,ngf,ngflag,& colflag,ce,nce,ice,jce,nclo,iclo,jclo,dclo,tclo,ixvclo,jxvclo,mfo_hkce,m_x,rho) end if ! Advance solar Hamiltonian for H/2 mvsum(1) = 0.d0 mvsum(2) = 0.d0 mvsum(3) = 0.d0 do j = 2, nbod mvsum(1) = mvsum(1) + m(j) * v(1,j) mvsum(2) = mvsum(2) + m(j) * v(2,j) mvsum(3) = mvsum(3) + m(j) * v(3,j) end do temp = hby2 / m(1) mvsum(1) = temp * mvsum(1) mvsum(2) = temp * mvsum(2) mvsum(3) = temp * mvsum(3) do j = 2, nbod x(1,j) = x(1,j) + mvsum(1) x(2,j) = x(2,j) + mvsum(2) x(3,j) = x(3,j) + mvsum(3) end do ! Advance interaction Hamiltonian for H/2 call mfo_hy (jcen,nbod,nbig,m,x,rcrit,a,stat) if (opt(8).eq.1) call mfo_user (time,jcen,nbod,nbig,m,rphys,x,v,ausr) if ((ngflag.eq.1).or.(ngflag.eq.3)) call mfo_ngf (nbod,x,v,angf,ngf) do j = 2, nbod v(1,j) = v(1,j) + hby2 * (angf(1,j) + ausr(1,j) + a(1,j)) v(2,j) = v(2,j) + hby2 * (angf(2,j) + ausr(2,j) + a(2,j)) v(3,j) = v(3,j) + hby2 * (angf(3,j) + ausr(3,j) + a(3,j)) end do !------------------------------------------------------------------------------ return end subroutine mdt_hy !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% !> @author !> <NAME> ! !> @date 1 March 2001 ! ! DESCRIPTION: !> @brief Integrates NBOD bodies (of which NBIG are Big) for one timestep H under !! the Hamiltonian H_K, including close-encounter terms. ! !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% subroutine mdt_hkce (time,h0,hrec,tol,elost,jcen,rcen,nbod,nbig,m,x,v,s,rphy,rcrit,rce,stat,id,ngf,ngflag,& colflag,ce,nce,ice,jce,nclo,iclo,jclo,dclo,tclo,ixvclo,jxvclo,force,m_x,rho) use physical_constant use mercury_constant use dynamic use algo_bs2 implicit none ! Input integer, intent(in) :: nbod !< [in] current number of bodies (1: star; 2-nbig: big bodies; nbig+1-nbod: small bodies) integer, intent(in) :: nbig !< [in] current number of big bodies (ones that perturb everything else) integer, intent(in) :: nce integer, intent(in) :: ice(CMAX) integer, intent(in) :: jce(CMAX) integer, intent(in) :: ngflag !< [in] do any bodies experience non-grav. forces? !!\n ( 0 = no non-grav forces) !!\n 1 = cometary jets only !!\n 2 = radiation pressure/P-R drag only !!\n 3 = both integer, intent(in) :: ce(nbod) !< [in] close encounter status real(double_precision), intent(in) :: time !< [in] current epoch (days) real(double_precision), intent(in) :: h0 !< [in] initial integration timestep (days) real(double_precision), intent(in) :: tol !< [in] Integrator tolerance parameter (approx. error per timestep) real(double_precision), intent(in) :: jcen(3) !< [in] J2,J4,J6 for central body (units of RCEN^i for Ji) real(double_precision), intent(in) :: rcen !< [in] radius of central body (AU) real(double_precision), intent(in) :: rce(nbod) real(double_precision), intent(in) :: rphy(nbod) real(double_precision), intent(in) :: rcrit(nbod) real(double_precision), intent(in) :: ngf(4,nbod) !< [in] non gravitational forces parameters !! \n(1-3) cometary non-gravitational (jet) force parameters !! \n(4) beta parameter for radiation pressure and P-R drag character(len=8), dimension(nbod), intent(in) :: id !< [in] name of the object (8 characters) ! Input/Output integer, intent(inout) :: nclo integer, intent(inout) :: colflag integer, intent(inout) :: iclo(CMAX) integer, intent(inout) :: jclo(CMAX) integer, intent(inout) :: stat(nbod) !< [in,out] status (0 => alive, <>0 => to be removed) real(double_precision), intent(inout) :: hrec real(double_precision), intent(inout) :: m(nbod) !< [in,out] mass (in solar masses * K2) real(double_precision), intent(inout) :: m_x(nbod) !< [in,out] mass of element X (in solar masses * K2) real(double_precision), intent(inout) :: rho(nbod) !< [in,out] density real(double_precision), intent(inout) :: x(3,nbod) real(double_precision), intent(inout) :: v(3,nbod) real(double_precision), intent(inout) :: s(3,nbod) !< [in,out] spin angular momentum (solar masses AU^2/day) real(double_precision), intent(inout) :: elost real(double_precision), intent(inout) :: dclo(CMAX) real(double_precision), intent(inout) :: tclo(CMAX) real(double_precision), intent(inout) :: ixvclo(6,CMAX) real(double_precision), intent(inout) :: jxvclo(6,CMAX) external force ! Local integer :: iback(nb_bodies_initial),index(nb_bodies_initial),ibs(CMAX),jbs(CMAX),nclo_old integer :: i,j,k,nbs,nbsbig,statbs(nb_bodies_initial) integer :: nhit,ihit(CMAX),jhit(CMAX),chit(CMAX),nowflag,dtflag real(double_precision) :: tlocal,hlocal,hdid,tmp0 real(double_precision) :: mbs(nb_bodies_initial),xbs(3,nb_bodies_initial),vbs(3,nb_bodies_initial),sbs(3,nb_bodies_initial) real(double_precision) :: rcritbs(nb_bodies_initial),rcebs(nb_bodies_initial),rphybs(nb_bodies_initial) real(double_precision) :: ngfbs(4,nb_bodies_initial),x0(3,nb_bodies_initial),v0(3,nb_bodies_initial) real(double_precision) :: thit(CMAX),dhit(CMAX),thit1,temp character(len=8) :: idbs(nb_bodies_initial) !------------------------------------------------------------------------------ ! N.B. Don't set nclo to zero! nbs = 1 nbsbig = 0 mbs(1) = m(1) if (algor.eq.11) mbs(1) = m(1) + m(2) sbs(1,1) = s(1,1) sbs(2,1) = s(2,1) sbs(3,1) = s(3,1) ! Put data for close-encounter bodies into local arrays for use with BS routine do j = 2, nbod if (ce(j).ne.0) then nbs = nbs + 1 if (j.le.nbig) nbsbig = nbs mbs(nbs) = m(j) xbs(1,nbs) = x(1,j) xbs(2,nbs) = x(2,j) xbs(3,nbs) = x(3,j) vbs(1,nbs) = v(1,j) vbs(2,nbs) = v(2,j) vbs(3,nbs) = v(3,j) sbs(1,nbs) = s(1,j) sbs(2,nbs) = s(2,j) sbs(3,nbs) = s(3,j) rcebs(nbs) = rce(j) rphybs(nbs) = rphy(j) statbs(nbs) = stat(j) rcritbs(nbs) = rcrit(j) idbs(nbs) = id(j) index(nbs) = j iback(j) = nbs end if end do do k = 1, nce ibs(k) = iback(ice(k)) jbs(k) = iback(jce(k)) end do tlocal = 0.d0 hlocal = sign(hrec,h0) ! Begin the Bulirsch-Stoer integration do tmp0 = abs(h0) - abs(tlocal) hrec = hlocal if (abs(hlocal).gt.tmp0) hlocal = sign (tmp0, h0) ! Save old coordinates and integrate !~ x0(:,:) = xbs(:,:) !~ v0(:,:) = vbs(:,:) call mco_iden (time,jcen,nbs,0,h0,mbs,xbs,vbs,x0,v0,ngf,ngflag) call mdt_bs2 (time,hlocal,hdid,tol,jcen,nbs,nbsbig,mbs,xbs,vbs,sbs,rphybs,rcritbs,ngfbs,statbs,dtflag,ngflag,nce,ibs,jbs,& force) tlocal = tlocal + hdid ! Check for close-encounter minima nclo_old = nclo temp = time + tlocal call mce_stat (temp,hdid,rcen,nbs,nbsbig,mbs,x0,v0,xbs,vbs,rcebs,rphybs,nclo,iclo,jclo,dclo,tclo,ixvclo,jxvclo,nhit,ihit,jhit,& chit,dhit,thit,thit1,nowflag,statbs,outfile(3)) ! If collisions occurred, resolve the collision and return a flag if ((nhit.gt.0).and.(opt(2).ne.0)) then do k = 1, nhit if (chit(k).eq.1) then i = ihit(k) j = jhit(k) call mce_coll (thit(k),elost,jcen,i,j,nbs,nbsbig,mbs,xbs,vbs,sbs,rphybs,statbs,idbs,outfile(3),m_x,rho) colflag = colflag + 1 end if end do end if ! If necessary, continue integrating objects undergoing close encounters if (.not.((tlocal - h0)*h0.lt.0)) exit end do ! Return data for the close-encounter objects to global arrays do k = 2, nbs j = index(k) m(j) = mbs(k) x(1,j) = xbs(1,k) x(2,j) = xbs(2,k) x(3,j) = xbs(3,k) v(1,j) = vbs(1,k) v(2,j) = vbs(2,k) v(3,j) = vbs(3,k) s(1,j) = sbs(1,k) s(2,j) = sbs(2,k) s(3,j) = sbs(3,k) stat(j) = statbs(k) end do do k = 1, nclo iclo(k) = index(iclo(k)) jclo(k) = index(jclo(k)) end do !------------------------------------------------------------------------------ return end subroutine mdt_hkce !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% !> @author !> <NAME> ! !> @date 2 March 2001 ! ! DESCRIPTION: !> @brief Convert coordinates with respect to the central body to democratic !! heliocentric coordinates. ! !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% subroutine mco_h2dh (time,jcen,nbod,nbig,h,m,xh,vh,x,v,ngf,ngflag) implicit none ! Input/Output integer, intent(in) :: nbod !< [in] current number of bodies (1: star; 2-nbig: big bodies; nbig+1-nbod: small bodies) integer, intent(in) :: nbig !< [in] current number of big bodies (ones that perturb everything else) integer, intent(in) :: ngflag !< [in] do any bodies experience non-grav. forces? !!\n ( 0 = no non-grav forces) !!\n 1 = cometary jets only !!\n 2 = radiation pressure/P-R drag only !!\n 3 = both real(double_precision),intent(in) :: time !< [in] current epoch (days) real(double_precision),intent(in) :: jcen(3) !< [in] J2,J4,J6 for central body (units of RCEN^i for Ji) real(double_precision),intent(in) :: h !< [in] current integration timestep (days) real(double_precision),intent(in) :: m(nbod) !< [in] mass (in solar masses * K2) real(double_precision),intent(in) :: xh(3,nbod) !< [in] coordinates (x,y,z) with respect to the central body (AU) real(double_precision),intent(in) :: vh(3,nbod) !< [in] velocities (vx,vy,vz) with respect to the central body (AU/day) real(double_precision),intent(in) :: ngf(4,nbod) !< [in] non gravitational forces parameters !! \n(1-3) cometary non-gravitational (jet) force parameters !! \n(4) beta parameter for radiation pressure and P-R drag real(double_precision),intent(out) :: v(3,nbod) real(double_precision),intent(out) :: x(3,nbod) ! Local integer :: j real(double_precision) :: mtot,temp,mvsum(3) !------------------------------------------------------------------------------ mtot = 0.d0 mvsum(1) = 0.d0 mvsum(2) = 0.d0 mvsum(3) = 0.d0 do j = 2, nbod x(1,j) = xh(1,j) x(2,j) = xh(2,j) x(3,j) = xh(3,j) mtot = mtot + m(j) mvsum(1) = mvsum(1) + m(j) * vh(1,j) mvsum(2) = mvsum(2) + m(j) * vh(2,j) mvsum(3) = mvsum(3) + m(j) * vh(3,j) end do temp = 1.d0 / (m(1) + mtot) mvsum(1) = temp * mvsum(1) mvsum(2) = temp * mvsum(2) mvsum(3) = temp * mvsum(3) do j = 2, nbod v(1,j) = vh(1,j) - mvsum(1) v(2,j) = vh(2,j) - mvsum(2) v(3,j) = vh(3,j) - mvsum(3) end do !------------------------------------------------------------------------------ return end subroutine mco_h2dh !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% !> @author !> <NAME> ! !> @date 2 March 2001 ! ! DESCRIPTION: !> @brief Converts democratic heliocentric coordinates to coordinates with respect !! to the central body. ! !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% subroutine mco_dh2h (time,jcen,nbod,nbig,h,m,x,v,xh,vh,ngf,ngflag) implicit none ! Input/Output integer,intent(in) :: nbod !< [in] current number of bodies (1: star; 2-nbig: big bodies; nbig+1-nbod: small bodies) integer,intent(in) :: nbig !< [in] current number of big bodies (ones that perturb everything else) integer,intent(in) :: ngflag !< [in] do any bodies experience non-grav. forces? !!\n ( 0 = no non-grav forces) !!\n 1 = cometary jets only !!\n 2 = radiation pressure/P-R drag only !!\n 3 = both real(double_precision),intent(in) :: time !< [in] current epoch (days) real(double_precision),intent(in) :: jcen(3) !< [in] J2,J4,J6 for central body (units of RCEN^i for Ji) real(double_precision),intent(in) :: h !< [in] current integration timestep (days) real(double_precision),intent(in) :: m(nbod) !< [in] mass (in solar masses * K2) real(double_precision),intent(in) :: x(3,nbod) real(double_precision),intent(in) :: v(3,nbod) real(double_precision),intent(in) :: ngf(4,nbod) !< [in] non gravitational forces parameters !! \n(1-3) cometary non-gravitational (jet) force parameters !! \n(4) beta parameter for radiation pressure and P-R drag real(double_precision), intent(out) :: xh(3,nbod) !< [out] coordinates (x,y,z) with respect to the central body (AU) real(double_precision), intent(out) :: vh(3,nbod) !< [out] velocities (vx,vy,vz) with respect to the central body (AU/day) ! Local integer :: j real(double_precision) :: mvsum(3),temp !------------------------------------------------------------------------------ mvsum(1) = 0.d0 mvsum(2) = 0.d0 mvsum(3) = 0.d0 do j = 2, nbod xh(1,j) = x(1,j) xh(2,j) = x(2,j) xh(3,j) = x(3,j) mvsum(1) = mvsum(1) + m(j) * v(1,j) mvsum(2) = mvsum(2) + m(j) * v(2,j) mvsum(3) = mvsum(3) + m(j) * v(3,j) end do temp = 1.d0 / m(1) mvsum(1) = temp * mvsum(1) mvsum(2) = temp * mvsum(2) mvsum(3) = temp * mvsum(3) do j = 2, nbod vh(1,j) = v(1,j) + mvsum(1) vh(2,j) = v(2,j) + mvsum(2) vh(3,j) = v(3,j) + mvsum(3) end do !------------------------------------------------------------------------------ return end subroutine mco_dh2h !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% !> @author !> <NAME> ! !> @date 27 February 2001 ! ! DESCRIPTION: !> @brief Calculates accelerations due to the Keplerian part of the Hamiltonian !! of a hybrid symplectic integrator, when close encounters are taking place, !! for a set of NBOD bodies (NBIG of which are Big). Note that Small bodies !! do not interact with one another. ! !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% subroutine mfo_hkce (time,jcen,nbod,nbig,m,x,v,spin,rcrit,a,stat,ngf,ngflag,nce,ice,jce) use physical_constant use mercury_constant implicit none ! Inputs integer, intent(in) :: nbod !< [in] current number of bodies (1: star; 2-nbig: big bodies; nbig+1-nbod: small bodies) integer, intent(in) :: nbig !< [in] current number of big bodies (ones that perturb everything else) integer, intent(in) :: stat(nbod) !< [in] status (0 => alive, <>0 => to be removed) integer, intent(in) :: ngflag !< [in] do any bodies experience non-grav. forces? !!\n ( 0 = no non-grav forces) !!\n 1 = cometary jets only !!\n 2 = radiation pressure/P-R drag only !!\n 3 = both integer, intent(in) :: nce integer, intent(in) :: ice(nce) integer, intent(in) :: jce(nce) real(double_precision), intent(in) :: time !< [in] current epoch (days) real(double_precision), intent(in) :: jcen(3) !< [in] J2,J4,J6 for central body (units of RCEN^i for Ji) real(double_precision), intent(in) :: rcrit(nbod) real(double_precision), intent(in) :: ngf(4,nbod) !< [in] non gravitational forces parameters !! \n(1-3) cometary non-gravitational (jet) force parameters !! \n(4) beta parameter for radiation pressure and P-R drag real(double_precision), intent(in) :: m(nbod) !< [in] mass (in solar masses * K2) real(double_precision), intent(in) :: x(3,nbod) real(double_precision), intent(in) :: v(3,nbod) real(double_precision), intent(in) :: spin(3,nbod) ! Output real(double_precision), intent(out) :: a(3,nbod) ! Local integer :: i, j, k real(double_precision) :: tmp2,dx,dy,dz,s,s_1,s2,s_3,faci,facj,rc,rc2,q,q2,q3,q4,q5 !------------------------------------------------------------------------------ ! Initialize accelerations do j = 1, nbod a(1,j) = 0.d0 a(2,j) = 0.d0 a(3,j) = 0.d0 end do ! Direct terms do k = 1, nce i = ice(k) j = jce(k) dx = x(1,j) - x(1,i) dy = x(2,j) - x(2,i) dz = x(3,j) - x(3,i) s2 = dx * dx + dy * dy + dz * dz rc = max (rcrit(i), rcrit(j)) rc2 = rc * rc if (s2.lt.rc2) then s_1 = 1.d0 / sqrt(s2) s_3 = s_1 * s_1 * s_1 if (s2.le.0.01*rc2) then tmp2 = s_3 else s = 1.d0 / s_1 q = (s - 0.1d0*rc) / (0.9d0 * rc) q2 = q * q q3 = q * q2 q4 = q2 * q2 q5 = q2 * q3 tmp2 = (1.d0 - 10.d0*q3 + 15.d0*q4 - 6.d0*q5) * s_3 end if faci = tmp2 * m(i) facj = tmp2 * m(j) a(1,j) = a(1,j) - faci * dx a(2,j) = a(2,j) - faci * dy a(3,j) = a(3,j) - faci * dz a(1,i) = a(1,i) + facj * dx a(2,i) = a(2,i) + facj * dy a(3,i) = a(3,i) + facj * dz end if end do ! Solar terms do i = 2, nbod s2 = x(1,i)*x(1,i) + x(2,i)*x(2,i) + x(3,i)*x(3,i) s_1 = 1.d0 / sqrt(s2) tmp2 = m(1) * s_1 * s_1 * s_1 a(1,i) = a(1,i) - tmp2 * x(1,i) a(2,i) = a(2,i) - tmp2 * x(2,i) a(3,i) = a(3,i) - tmp2 * x(3,i) end do !------------------------------------------------------------------------------ return end subroutine mfo_hkce !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% !> @author !> <NAME> ! !> @date 2 October 2000 ! ! DESCRIPTION: !> @brief Calculates accelerations due to the Interaction part of the Hamiltonian !! of a hybrid symplectic integrator for a set of NBOD bodies (NBIG of which !! are Big), where Small bodies do not interact with one another. ! !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% subroutine mfo_hy (jcen,nbod,nbig,m,x,rcrit,a,stat) use physical_constant use mercury_constant use forces, only : mfo_obl implicit none ! Inputs integer, intent(in) :: nbod !< [in] current number of bodies (1: star; 2-nbig: big bodies; nbig+1-nbod: small bodies) integer, intent(in) :: nbig !< [in] current number of big bodies (ones that perturb everything else) integer, intent(in) :: stat(nbod) !< [in] status (0 => alive, <>0 => to be removed) real(double_precision), intent(in) :: jcen(3) !< [in] J2,J4,J6 for central body (units of RCEN^i for Ji) real(double_precision), intent(in) :: m(nbod) !< [in] mass (in solar masses * K2) real(double_precision), intent(in) :: x(3,nbod) real(double_precision), intent(in) :: rcrit(nbod) ! Output real(double_precision), intent(out) :: a(3,nbod) ! Local integer :: k real(double_precision) :: aobl(3,nb_bodies_initial),acen(3) !------------------------------------------------------------------------------ ! Initialize accelerations to zero do k = 1, nbod a(1,k) = 0.d0 a(2,k) = 0.d0 a(3,k) = 0.d0 end do ! Calculate direct terms call mfo_drct (2,nbod,nbig,m,x,rcrit,a,stat) ! Add accelerations due to oblateness of the central body if (jcen(1).ne.0.or.jcen(2).ne.0.or.jcen(3).ne.0) then call mfo_obl (jcen,nbod,m,x,aobl,acen) do k = 2, nbod a(1,k) = a(1,k) + aobl(1,k) - acen(1) a(2,k) = a(2,k) + aobl(2,k) - acen(2) a(3,k) = a(3,k) + aobl(3,k) - acen(3) end do end if !------------------------------------------------------------------------------ return end subroutine mfo_hy !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% !> @author !> <NAME> ! !> @date 27 February 2001 ! ! DESCRIPTION: !> @brief Calculates direct accelerations between bodies in the interaction part !! of the Hamiltonian of a symplectic integrator that partitions close !! encounter terms (e.g. hybrid symplectic algorithms or SyMBA). !! The routine calculates accelerations between all pairs of bodies with !! indices I >= I0. ! !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% subroutine mfo_drct (start_index,nbod,nbig,m,x,rcrit,a,stat) use physical_constant use mercury_constant implicit none ! Input/Output integer, intent(in) :: start_index integer, intent(in) :: nbod !< [in] current number of bodies (1: star; 2-nbig: big bodies; nbig+1-nbod: small bodies) integer, intent(in) :: nbig !< [in] current number of big bodies (ones that perturb everything else) integer, intent(in) :: stat(nbod) !< [in] status (0 => alive, <>0 => to be removed) real(double_precision), intent(in) :: m(nbod) !< [in] mass (in solar masses * K2) real(double_precision), intent(in) :: x(3,nbod) real(double_precision), intent(in) :: rcrit(nbod) ! Input/Output real(double_precision), intent(inout) :: a(3,nbod) ! Local integer :: i0 integer :: i,j real(double_precision) :: dx,dy,dz,s,s_1,s2,s_3,rc,rc2,q,q2,q3,q4,q5,tmp2,faci,facj !------------------------------------------------------------------------------ if (start_index.le.0) then i0 = 2 else i0 = start_index endif do i = i0, nbig do j = i + 1, nbod dx = x(1,j) - x(1,i) dy = x(2,j) - x(2,i) dz = x(3,j) - x(3,i) s2 = dx * dx + dy * dy + dz * dz rc = max(rcrit(i), rcrit(j)) rc2 = rc * rc if (s2.ge.rc2) then s_1 = 1.d0 / sqrt(s2) tmp2 = s_1 * s_1 * s_1 else if (s2.le.0.01*rc2) then tmp2 = 0.d0 else s_1 = 1.d0 / sqrt(s2) s = 1.d0 / s_1 s_3 = s_1 * s_1 * s_1 q = (s - 0.1d0*rc) / (0.9d0 * rc) q2 = q * q q3 = q * q2 q4 = q2 * q2 q5 = q2 * q3 tmp2 = (10.d0*q3 - 15.d0*q4 + 6.d0*q5) * s_3 end if faci = tmp2 * m(i) facj = tmp2 * m(j) a(1,j) = a(1,j) - faci * dx a(2,j) = a(2,j) - faci * dy a(3,j) = a(3,j) - faci * dz a(1,i) = a(1,i) + facj * dx a(2,i) = a(2,i) + facj * dy a(3,i) = a(3,i) + facj * dz end do end do !------------------------------------------------------------------------------ return end subroutine mfo_drct end module algo_hybrid <file_sep>!****************************************************************************** ! MODULE: user_module !****************************************************************************** ! ! DESCRIPTION: !> @brief Module that contain user defined function. This module can call other module and subroutine. !! The only public routine is mfo_user, that return an acceleration that !! mimic a random force that depend on what the user want to model. ! !****************************************************************************** module user_module use types_numeriques use physical_constant implicit none private public :: mfo_user, gasdisk contains !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% !> @author !> <NAME> ! !> @date 2 March 2001 ! ! DESCRIPTION: !> @brief Applies an arbitrary force, defined by the user. !!\n\n !! If using with the symplectic algorithm MAL_MVS, the force should be !! small compared with the force from the central object. !! If using with the conservative Bulirsch-Stoer algorithm MAL_BS2, the !! force should not be a function of the velocities. !! \n\n !! Code Units are in AU, days and solar mass * K2 (mass are in solar mass, but multiplied by K2 earlier in the code). ! !> @note All coordinates and velocities must be with respect to central body ! !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% subroutine mfo_user (time,jcen,n_bodies,n_big_bodies,mass, phyradius, position, velocity,acceleration) ! mass = mass (in solar masses * K2) ! position = coordinates (x,y,z) with respect to the central body [AU] ! velocity = velocities (vx,vy,vz) with respect to the central body [AU/day] ! n_bodies = current number of bodies (INCLUDING the central object) ! n_big_bodies = " " " big bodies (ones that perturb everything else) ! time = current epoch [days] use physical_constant, only : PI, TWOPI, AU, MSUN, K2 implicit none ! Input integer, intent(in) :: n_bodies !< [in] current number of bodies (1: star; 2-nbig: big bodies; nbig+1-nbod: small bodies) integer, intent(in) :: n_big_bodies !< [in] current number of big bodies (ones that perturb everything else) real(double_precision), intent(in) :: time !< [in] current epoch (days) real(double_precision), intent(in) :: jcen(3) !< [in] J2,J4,J6 for central body (units of RCEN^i for Ji) real(double_precision), intent(in) :: mass(n_bodies) !< [in] mass (in solar masses * K2) real(double_precision), intent(in) :: phyradius(n_bodies) !< planet radius real(double_precision), intent(in) :: position(3,n_bodies) real(double_precision), intent(in) :: velocity(3,n_bodies) ! Output real(double_precision),intent(out) :: acceleration(3,n_bodies) !------------------------------------------------------------------------------ !------Local------- ! loop integers integer :: planet real(double_precision) :: radii ! distace of the planet ( in AU) real(double_precision) :: acc_mig(3), acc_drag(3) real(double_precision) :: msmall do planet = 2, n_bodies ! planet's location in disk radii = (position(1,planet)**2 + position(2,planet)**2)**0.5 ! truncate the disk at 0.2 AU if (radii >= 0.2d0) then if (planet <= n_big_bodies) then ! for big bodies ! calculate the acc from the migration call type12 (time,mass(1),planet,mass(planet),position(:,planet),velocity(:,planet),acc_mig(:)) acceleration(1,planet) = + acc_mig(1) acceleration(2,planet) = + acc_mig(2) acceleration(3,planet) = + acc_mig(3) else acceleration(1,planet) = 0.0d0 acceleration(2,planet) = 0.0d0 acceleration(3,planet) = 0.0d0 end if else ! inside the cavity acceleration(1,planet) = 0.0d0 acceleration(2,planet) = 0.0d0 acceleration(3,planet) = 0.0d0 end if end do !------------------------------------------------------------------------------ return end subroutine mfo_user !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% !%%% type I miration subroutine %%% !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ! Author: <NAME> ! Calculates the type I migration acceleration on a planet. ! Use the migration torque describled by Paarderkooper2011 ! Use the eccentricity and inclination damping from Cresswell & Nelson 2008 subroutine type12 (t,mstar,num,mpl,x,v,acc) ! mpl = planet mass (in solar masses * K2) ! mstar = star mass (in solar masses * K2) ! x = coordinates (x,y,z) with respect to the central body [AU] ! v = velocities (vx,vy,vz) with respect to the central body [AU/day] ! num = current number of bodies ! t = current epoch [days] use physical_constant, only : PI, TWOPI, AU, MSUN, K2, EARTH_MASS use mercury_globals, only : opt,alpha_t, kap, mdot_gas0, L_s, Rdisk0, alpha, tau_s,t0_dep,tau_dep use orbital_elements implicit none ! Input integer, intent(in) :: num real(double_precision), intent(in) :: t, mpl, mstar real(double_precision), intent(in) :: x(3), v(3) real(double_precision), intent(out) :: acc(3) real(double_precision) :: asemi(3), aecc(3), ainc real(double_precision) :: taumig, tauecc, tauinc real(double_precision) :: pecc, hgas, etagas, rhogas real(double_precision) :: rtrans, siggas_vis, siggas_irr,f1,f2,f_tot,fs real(double_precision) :: tauwave, rdisk, siggas, Omega, m_gap, m_planet,delta_m real(double_precision) :: r2, v2, rv, r real(double_precision) :: ecc, inc real(double_precision) ::peri,long,node,lmean integer k ! planet's location in the disk rdisk = (x(1)**2 + x(2)**2 )**0.5 ! ########################################### ! ### get disk properties:surface density ### ! ########################################### call gasdisk (t,rdisk,x(3),mstar,alpha,kap,hgas,etagas,siggas,siggas_vis,siggas_irr,rhogas,rtrans) ! angular velocity at planet's location Omega = (mstar/rdisk**3)**0.5d0 ! in day^{-1} r2 = 0.d0 v2 = 0.d0 rv = 0.d0 do k = 1,3 r2 = r2 + x(k)**2 v2 = v2 + v(k)**2 rv = rv + x(k)*v(k) end do r = r2**0.5d0 ! ######################################## ! ### from xyz to ecc and inc(radian) ### ! ######################################## call mco_x2el (mstar+mpl,x(1),x(2),x(3),v(1),v(2),v(3),peri,ecc,inc,long,node,lmean) ! wave timescale tauwave = (mstar/mpl)*(mstar/(siggas*rdisk**2))*hgas**4/Omega ! eccentricity damping timescale tauecc = tauwave/0.78d0*(1d0 - 0.14d0*(ecc/hgas)**2 & + 6d-2*(ecc/hgas)**3 + 0.18d0*(ecc/hgas)*(inc/hgas)**2) ! inclination damping timescale tauinc = tauwave/0.544d0*(1d0 - 0.3d0*(inc/hgas)**2 & + 0.24d0*(inc/hgas)**3 + 0.14d0*(ecc/hgas)**2*(inc/hgas)) pecc = ( 1d0 + (ecc/(2.25d0*hgas))**1.2d0 + & (ecc/(2.84d0*hgas))**6 )/(1.0d0 -(ecc/(2.02d0*hgas))**4 ) ! taumig = 2d0*tauwave/(2.7d0 - 1.1d0*index_p)/hgas**2*(pecc + pecc/abs(pecc) & ! *(0.07d0*(inc/hgas) + 0.085d0*(inc/hgas)**4 -0.08d0*(ecc/hgas)*(inc/hgas)**2 )) ! calculate the type I migration prefactor based on two-component disk structures call type1_prefactor (mpl,mstar,rdisk,siggas_vis,siggas_irr,siggas,hgas, rtrans,f1) ! only conside type I migration for all mass range if (opt(12) == 1 ) then f_tot = f1 end if ! both conside type I & II if (opt(12) == 2 .or. opt(12) == 3) then ! type II based on Kanagawa2018 if (opt(12) == 2) f2 = -1.d0 ! type II becomes infinite slow if (opt(12) == 3) f2 = -1d-10 ! gap opening mass m_gap = gap_opening(hgas,alpha_t,mstar) ! in earth mass m_planet = mpl/K2/EARTH_MASS ! planet mass in earth mass !!!! unsolved, think about stellar-mass dependence if (m_planet <m_gap) then f_tot = f1 else !fs = 1.d0/(1.d0 + (m_planet/m_gap)**4) !f_tot = f1*fs + f2*(1-fs) !f_tot = f_tot/(1.d0 + (m_planet/m_gap)**2) delta_m = m_gap/5.d0 fs = exp(-(m_planet-m_gap)/delta_m) f_tot = f1*fs + f2*(1.d0-fs)/(m_planet/m_gap)**2 end if end if ! print*, opt(12),alpha_t, m_gap, mpl,mpl/K2,mpl/K2/EARTH_MASS, mstar,K2 ! migration timescale f_tot>0, outward migration; f_tot<0, inward migration taumig = 2d0*tauwave/f_tot/hgas**2 ! print*,'f1',t/365.25d0,f1,taumig/365.25 ! print*,'check',mpl/mstar,mstar/(siggas*rdisk**2),hgas,6.28/Omega/365.25 ! implement the acceralation terms due to disk torques do k = 1,3 if (opt(12) /= 0) then ! include migration asemi(k) = v(k)/taumig else asemi(k) = 0d0 end if aecc(k) = -2*rv*x(k)/r**2/tauecc acc(k) = asemi(k) + aecc(k) end do ainc = -v(3)/tauinc acc(3) = acc(3) + ainc return end subroutine type12 !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% !%%% Gas drag on planetesimal %%% !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ! Author: <NAME> ! Calculates the gas drag acceleration on a body (mainly planetesimal). ! The drag force describled in Mandell 2007 subroutine gasdrag (t,mstar,num, mpl,rphypl, x,v,acc) ! mpl = planet mass (in solar masses * K2) ! rhypl = planet radius ! mstar = star mass (in solar masses * K2) ! x = coordinates (x,y,z) with respect to the central body [AU] ! v = velocities (vx,vy,vz) with respect to the central body [AU/day] ! num = current number of bodies ! t = current epoch [days] use physical_constant, only : PI, AU, MSUN, K2 use mercury_globals, only : alpha_t, kap, mdot_gas0, L_s, Rdisk0, alpha, t0_dep,tau_dep implicit none ! Input integer, intent(in) :: num real(double_precision), intent(in) :: t, mpl,rphypl, mstar real(double_precision), intent(in) :: x(3), v(3) real(double_precision), intent(out) :: acc(3) real(double_precision) :: hgas, rdisk, siggas, Omega, vk real(double_precision) :: tmp, vg_x, vg_y, cosf, sinf real(double_precision) :: dv_x,dv_y,dv_z, dv, vk_x,vk_y,vg_over_vk real(double_precision) :: Cgas = 0.5d0 ! gas drag coefficient real(double_precision) :: rhopl ! volumn density of the planet/planetesimal (in g/cm^3) real(double_precision) :: rhogas, rhogas_mid ! volumn density of the disk gas (in g/cm^3) real(double_precision) :: Rpl ! diamater of the planet/planetesimal (! in AU) real(double_precision) :: etagas ! headwind factor \eta real(double_precision) :: rtrans, siggas_vis, siggas_irr ! headwind factor \eta integer :: k ! planet's location in the disk r_p = (r,z) rdisk = (x(1)**2 + x(2)**2 )**0.5d0 !!!need to get a modt_gas(t) ! call gasdisk to calculate the surface density and apsect ratio, headwind prefactor at planet's location call gasdisk (t,rdisk,x(3),mstar,alpha,kap,hgas,etagas,siggas,siggas_vis,siggas_irr,rhogas,rtrans) ! planet's radius rhopl = 3d0*mpl/4d0/pi/rphypl**3/( AU * AU * AU * K2 / MSUN) !Rpl = (3.d0*mpl/K2*MSUN/PI/rhopl/4.d0)**(1d0/3d0)/AU ! (in AU) Rpl = rphypl ! (in AU) !print*, 'plt R',Rpl ! gas drag prefactor tmp = - 3.d0/8.d0*Cgas*(rhogas/rhopl)/Rpl ! angular velocity and Kepler velocity at the body's location Omega = (mstar/rdisk**3)**0.5d0 ! in day^{-1} vk = (mstar/rdisk)**0.5d0 ! in day^{-1} ! Keplerian velocity at planet's location (x,y) cosf = x(1)/rdisk sinf = x(2)/rdisk vk_x = - vk*sinf vk_y = vk*cosf ! the vg(z,r) with respect to vk(r) Takeuchi-Lin 2002 eq(7) vg_over_vk = (x(1)**2 + x(2)**2 + x(3)**2)**0.5d0/rdisk & *(1.d0 + 0.5d0*hgas**2*(0-2.d0 -(2d0*1-1.0d0) & !*(1.d0 + 0.5d0*hgas**2*(index_p+index_q-2.d0 -(2d0*index_q-1.0d0) & /2.0d0*(x(3)/hgas/rdisk)**2)) ! gas velocity at planet's location (x,y) vg_x = vg_over_vk*vk_x vg_y = vg_over_vk*vk_y ! relative velocity between gas and planet at planet's location (x,y,z) dv_x = v(1) - vg_x dv_y = v(2) - vg_y dv_z = v(3) dv = (dv_x**2 + dv_y**2 + dv_z**2)**0.5d0 acc(1) = tmp*dv_x*dv acc(2) = tmp*dv_y*dv acc(3) = tmp*dv_z*dv end subroutine gasdrag function fsmooth(r, rtrans) implicit none real(double_precision), intent(in) :: rtrans, r real(double_precision) :: fsmooth fsmooth = 1./(1. + (r/rtrans)**4) end function fsmooth !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% !%%% two-component disk structure %%% !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ! Author: <NAME> ! Calculates gas disk profile with inner viscously heated + outer stellar irradiation ! based on Liu 2019's population synthesis model subroutine gasdisk (t,r,z,mstar,alpha,kap,hgas,etagas,siggas,siggas_vis,siggas_irr,rhogas,rtrans) ! t = current epoch [days] ! r = disk radius [AU] ! z = vertical distance [AU] ! t0_dep = onset time of disk disposal [Myr] ! tau_dep = disk disposal timescale [Myr] ! mdot_gas = gas accretion rate at t [Msun/yr] ! siggas = gas surface desity at t [K*MSUN/AU^2] ! siggas_vis/irr = gas surface desity at viscous/irradiation zone [K*MSUN/AU^2] ! rhogas_mid = gas volumn desity in the midplane at r [g/cm^3] ! rhogas = gas volumn desity at (r,z) [g/cm^3] ! etagas = headwind prefactor ! hgas = gas disk aspect ratio ! rtrans = transition radius between two regions use physical_constant, only : PI, TWOPI, AU, MSUN, K2 use mercury_globals, only : opt, L_s,mdot_gas0, t0_dep,tau_dep implicit none real(double_precision), intent(in) :: t, r, z, mstar,alpha,kap real(double_precision), intent(out) :: etagas, siggas, rhogas,hgas real(double_precision), intent(out) :: rtrans, siggas_vis, siggas_irr real(double_precision) :: p, q, siggas0_vis, hgas0_vis, hgas_vis, T0_vis, T_vis real(double_precision) :: siggas0_irr, hgas0_irr, hgas_irr, T0_irr, T_irr real(double_precision) :: fs, Temp, rhogas_mid, etagas0 real(double_precision) :: Omega,v_0,ts_0,mdot_gas real(double_precision) :: M_s, t0, td !!! this will change in future !!! M_s = 1.0 !###gas viscous timescale ### p = - 15./14 q = 2./7 Omega = (mstar/r**3)**0.5d0 ! in day^{-1} hgas0_irr = 2.45e-2*(L_s/1.0)**(1./7)*(M_s/1.0)**(-4./7) hgas_irr = hgas0_irr*r**q v_0 =alpha*hgas_irr**2*Omega ts_0 = 1./(3d0*(2+p)**2)/v_0 ! day !######################################################## !####### consider gas accretion rate time-dependent ##### !######################################################## if ( opt(11) ==1 ) then ! time evolution of mdot_gas !mdot_gas = mdot_gas0*(t/ts_0 +1)**(-(2.5+p)/(2+p)) t0 = t0_dep*365.25d0*1d+6 ! day td = tau_dep*365.25d0*1d+6 ! day if (t<t0) then mdot_gas = mdot_gas0 else mdot_gas = mdot_gas0*exp(-(t-t0)/td) end if else mdot_gas = mdot_gas0 end if !### viscous heated region #### p = - 0.375 ! power law index for surface density q = -1./16 ! power law index for gas aspect ratio ! surface density at 1AU and as a function of r in g/cm^2 siggas0_vis = 740*(mdot_gas/1d-8)**(1./2)*(M_s/1.d0)**(1./8)*(alpha/1d-3)**(-3./4)*(kap/1d-2)**(-1./4.) siggas_vis = siggas0_vis*r**p ! apsect ratio at 1AU and as a function of r hgas0_vis = 4.5e-2*(mdot_gas/1d-8)**(1./4)*(M_s/1.0)**(-5./16)*(alpha/1d-3)**(-1./8)*(kap/1d-2)**(1./8) hgas_vis = hgas0_vis*r**q ! temperature at 1AU and as a function of r in K T0_vis = 500.*(mdot_gas/1d-8)**(1./2)*(M_s/1.0)**(3./8)*(alpha/1d-3)**(-1./4)*(kap/1d-2)**(1./4) T_vis = T0_vis*r**(2*q-1) !### stellar irradition region #### p = - 15./14 q = 2./7 ! surface density at 1AU and as a function of r in g/cm^2 siggas0_irr = 2500*(mdot_gas/1d-8)*(L_s/1.0)**(-2./7)*(M_s/1.0)**(9./14)*(alpha/1d-3)**(-1) siggas_irr = siggas0_irr*r**p ! apsect ratio at 1AU and as a function of r hgas0_irr = 2.45e-2*(L_s/1.0)**(1./7)*(M_s/1.0)**(-4./7) hgas_irr = hgas0_irr*r**q ! temperature at 1AU and as a function of r in K T0_irr = 150.*(L_s/1.0)**(2./7)*(M_s/1.0)**(-1./7) T_irr = T0_irr*r**(2*q-1) ! transition radius for two regions rtrans = (500./150.)**(56./39)*(mdot_gas/1d-8)**(28./39)*(M_s/1.0)**(29./39)& *(alpha/1d-3)**(-14./39)*(L_s/1.0)**(-16./39)*(kap/1d-2)**(14./39) ! combine of two regions if (opt(10) == 1) then ! include the inner viscously heated region fs= fsmooth(r, rtrans) else ! only irradiation fs = 0.0 end if siggas = fs*siggas_vis + (1.0 - fs)*siggas_irr Temp = fs*T_vis + (1.0 - fs)*T_irr hgas = fs*hgas_vis + (1.0 - fs)*hgas_irr ! midplane volume density in g/cm^3 rhogas_mid = siggas/TWOPI**0.5d0/hgas/AU ! gas volume density rho(r,z) rhogas = rhogas_mid*exp(-z**2/(hgas*r)**2) ! in g/cm^3 ! gas headwind prefactor at 1AU etagas0 = (2.d0 - p - q)/2.0d0 ! gas headwind prefactor etagas = etagas0*hgas**2 ! gas surface density at r [in solar mass*K2] siggas = siggas/MSUN*AU**2*K2 ! in solar mass*K2 siggas_vis = siggas_vis/MSUN*AU**2*K2 ! in solar mass*K2 siggas_irr = siggas_irr/MSUN*AU**2*K2 ! in solar mass*K2 end subroutine gasdisk !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% !%%% type 1 migration prefactor %%% !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ! Author: <NAME> ! Calculates type I migration prefactor two-component disk structure (inner viscously heated + outer stellar irradiation) ! based on Paardekoer2011 subroutine type1_prefactor (mpl,mstar,r,siggas_vis,siggas_irr,siggas,hgas, rtrans,f1) ! r =distance in the disk ! siggas_vis = gas surface desity in viscously heated region [solar mass*K2] ! siggas_irr = gas surface desity in stellar irradiation [solar mass*K2] ! siggas = gas surface desity [solar mass*K2] ! hgas = gas disk aspect ratio ! hgas_vis = gas disk aspect ratio in viscously heated region ! hgas_irr = gas disk aspect ratio in stellar irradiation region ! rtrans = transition radius use physical_constant, only : PI, TWOPI, AU, MSUN, K2 use mercury_globals, only : alpha_t implicit none real(double_precision), intent(in) :: r, rtrans, siggas_vis, siggas_irr, siggas real(double_precision), intent(in) :: hgas,mpl,mstar real(double_precision), intent(out) :: f1 character(len=5) :: opt_corotation_damping real(double_precision) :: p,pp,ppp,fp,pps,gpp,ppps,akppp real(double_precision) :: flb_vis,fhb_vis,fhe_vis,fcb_vis, fce_vis real(double_precision) :: flb_irr,fhb_irr,fhe_irr,fcb_irr, fce_irr real(double_precision) :: f1_vis,f1_irr, fs,f_ecc,f_inc opt_corotation_damping = 'False' ! calculate the type 1 migration prefactor ! saturation factor p = 2./3.*(mpl/mstar)**0.75/((2.0*PI*alpha_t)**0.5*hgas**1.75) pp = p/(8.0/(45.0*PI))**0.5 ppp = p/(28.0/(45.0*PI))**0.5 fp = 1./(1. + (p/1.3)**2) pps = 1./(1. + pp**4) gpp = pps*(16.*pp**1.5/25.) + (1. - pps)*(1.-9.*pp**(-2.67)/25.) ppps = 1./(1. + ppp**4) akppp = ppps*(16.*ppp**1.5/25.) + (1. - ppps)*(1.-9.*ppp**(-2.67)/25.) !ftot !factors of each torques in viscous region: -0.375, -1.125 flb_vis = -4.375 fhb_vis = 1.2375 fhe_vis = 5.5018 fcb_vis = 0.7875 fce_vis = 1.17 !factors of each torques in irr region: -3/7, -15/14 flb_irr = -3.08 fhb_irr = 0.47 fhe_irr = 0 fcb_irr = 0.3 fce_irr = 0.0 if (opt_corotation_damping == 'True') then ! consider the corotation torque attenuation due to high eccentricity and inclination Bitsch&Kley2010,Fendyke&Nelson2014 f_ecc = 1 !exp(-ecc) need to calculate ecc and inc!!! future f_inc = 1 ! f1_vis = flb_vis + (fhb_vis + fhe_vis*fp)*fp*gpp + (1 - akppp)*(fcb_vis + fce_vis)*f_ecc f1_irr = flb_irr + (fhb_irr + fhe_irr*fp)*fp*gpp + (1 - akppp)*(fcb_irr + fce_irr)*f_ecc else f1_vis = flb_vis + (fhb_vis + fhe_vis*fp)*fp*gpp + (1 - akppp)*(fcb_vis + fce_vis) f1_irr = flb_irr + (fhb_irr + fhe_irr*fp)*fp*gpp + (1 - akppp)*(fcb_irr + fce_irr) end if fs = fsmooth(r,rtrans) f1 = (f1_vis* siggas_vis*fs + f1_irr*siggas_irr*(1-fs))/siggas !!! ensure it is not zero if (abs(f1)<1d-10) Then f1 = 1d-10 end if end subroutine type1_prefactor !############################################### ! #### calculate the gap opening mass #### !############################################### function gap_opening(hgas,alpha,mstar) ! in Earth mass ! hgas = gas disk aspect ratio ! alpha = turbulent viscos alpha use physical_constant, only : K2 implicit none real(double_precision),intent(in) :: hgas, alpha, mstar real(double_precision) :: gap_opening gap_opening = 30d0*(hgas/5d-2)**2.5*(alpha/1d-3)**0.5*(mstar/K2) end function gap_opening ! in Earth mass end module user_module
a204c4a66ceddffd0523e8a38da41595fd04ac19
[ "Fortran Free Form", "Markdown", "INI", "Python" ]
30
Fortran Free Form
Jooehn/Nbodypps
0dc88709d5ccdeb938713c3c3b45180e8f3c5b46
f91f0945422930f5a727c8bcbb798a27d5927953
refs/heads/master
<repo_name>djeenwolfy/Fan-site<file_sep>/js/script.js /* var a=4,b=6; if (a>3 && b>3) console.log("Yes"); else console.log("No"); console.log("-------------------------"); if ((a>3 && b>=7)||a+b>10) console.log("Yes"); else console.log("No"); console.log("-------------------------"); if (a*b!=1) console.log("Yes"); else console.log("No"); console.log("-------------------------"); var z=13,y=2,n=229; var sum=z+y; if (z=>y) { if (sum=>n) console.log("Yes"); else console.log("No");} else {console.log("no"); } var z=13,y=2,n=229; var sum2=z+y; var raz=z-y; if (y!=z) if (z=>y) { if (sum=>n) console.log("Yes1"); else console.log("No1");} else { if (raz=>n) console.log("Yes2"); else console.log("No2"); } var z=13,y=2,n=16; var sum2=z+y; var raz=z-y; if (y != z) if (z >= y) { if (sum2 >= n) console.log("Yes1"); else console.log("No1");} else { if (raz >= n) console.log("Yes2"); else console.log("No2"); } var u,t,num; u=18; t=28; for( var k=0; k<=10; k++ ) { num=u+t; console.log(k); console.log(num); console.log("_____"); } console.log(" _____________________"); for( var k=0; k<=5; k++ ) { console.log("| |",k); } var total=0; console.log(" _____________________"); for( var k=0; k<=30; k=k+2) { total=total+k; console.log(total,k); } var one=4; var two=2; */ var kajdiy,pop,total=0; for (var k=0; k<=30; k++) { pop=k%2; if (pop!=0) total=total+k; console.log(total,k); }
1c078d20be481905e65aa4db567b5eee33593b6a
[ "JavaScript" ]
1
JavaScript
djeenwolfy/Fan-site
7f3c66e44ceb6f88d9a7fa4ddb12cc894e13dca0
2d0ee6f6a9c37673085e8f5f69613e235ae25c72
refs/heads/master
<repo_name>Rjacobucci/Psychometrics_Labs<file_sep>/Lab7/sim_sampSize_loadings.Rmd --- title: "sim_sampSize_loadings" author: "<NAME>" date: "October 14, 2014" output: pdf_document --- Simple simulation to see how the estimated mean factor loadings vary as a result of sample size. ```{r,message=FALSE,warning=FALSE} library(lavaan) res <- list() samps <- c(30,60,100,150,300) for(i in 1:length(samps)){ res[[i]] <- list() for(j in 1:300){ population.model <- ' f1 =~ 0.5*x1 + 0.6*x2 + 0.3*x3 + 0.8*x4 ' myData <- simulateData(population.model,model.type="cfa", sample.nobs=samps[i]) mod <- ' f1 =~ x1 + x2 + x3 + x4 ' mod.fit <- cfa(mod,myData,std.lv=T) res[[i]][[j]] <- mean(mod.fit@Fit@x[1:4]) } } ``` plot the mean of the factor loadings for 300 iterations Note -- anything above 1 is a Heywood case, or error -- the model didn't converge ```{r, echo=FALSE} plot(unlist(res[[1]]),main=samps[1]) plot(unlist(res[[2]]),main=samps[2]) plot(unlist(res[[3]]),main=samps[3]) plot(unlist(res[[4]]),main=samps[4]) plot(unlist(res[[5]]),main=samps[5]) ``` Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot. <file_sep>/Lab8/catDich_invariance.R # invariance for dichotomous items # works for a one factor model # more factors, follow steps on this site: # http://www.myweb.ttu.edu/spornpra/catInvariance.html library(lavaan) # same simulated dataset from mirt package set.seed(12345) a1 <- a2 <- matrix(abs(rnorm(15,1,.3)), ncol=1) d1 <- d2 <- matrix(rnorm(15,0,.7),ncol=1) a2[1:2, ] <- a1[1:2, ]/3 d1[c(1,3), ] <- d2[c(1,3), ]/4 head(data.frame(a.group1 = a1, a.group2 = a2, d.group1 = d1, d.group2 = d2)) itemtype <- rep('dich', nrow(a1)) N <- 1000 dataset1 <- simdata(a1, d1, N, itemtype) dataset2 <- simdata(a2, d2, N, itemtype, mu = .1, sigma = matrix(1.5)) dat <- rbind(dataset1, dataset2) group <- c(rep('D1', N), rep('D2', N)) dat <- data.frame(data.frame(dat),group) for(i in 1:15) dat[,i] <- ordered(dat[,i]) configural2 <- " f1 =~ Item_1 + Item_2 + Item_3 + c(1,1)*Item_4 + Item_5 + Item_6 + Item_7 + Item_8 + Item_9 + Item_10 + Item_11 + Item_12 + Item_13 + Item_14 + Item_15 Item_1 | c(t11, t11)*t1 Item_2 | c(t21, t21)*t1 Item_3 | c(t31, t31)*t1 Item_4 | c(t41, t41)*t1 Item_5 | c(t51, t51)*t1 Item_6 | c(t61, t61)*t1 Item_7 | c(t71, t71)*t1 Item_8 | c(t81, t81)*t1 Item_9 | c(t91,t91)*t1 Item_10 | c(t101, t101)*t1 Item_11 | c(t111, t111)*t1 Item_12 | c(t121, t121)*t1 Item_13 | c(t131, t131)*t1 Item_14 | c(t141, t141)*t1 Item_15 | c(t151, t151)*t1 f1 ~~ NA*f1 f1 ~ c(0, NA)*1 Item_1 ~~ c(1, NA)*Item_1 Item_2 ~~ c(1, NA)*Item_2 Item_3 ~~ c(1, NA)*Item_3 Item_4 ~~ c(1, 1)*Item_4 Item_5 ~~ c(1, NA)*Item_5 Item_6 ~~ c(1, NA)*Item_6 Item_7 ~~ c(1, NA)*Item_7 Item_8 ~~ c(1, NA)*Item_8 Item_9 ~~ c(1, NA)*Item_9 Item_10 ~~ c(1, NA)*Item_10 Item_11 ~~ c(1, NA)*Item_11 Item_12 ~~ c(1, NA)*Item_12 Item_13 ~~ c(1, NA)*Item_13 Item_14 ~~ c(1, NA)*Item_14 Item_15 ~~ c(1, NA)*Item_15 " # error when run, must be a result of lack of fit outConfigural2 <- cfa(configural2, data = dat, group="group",parameterization="theta", estimator="wlsmv") summary(outConfigural2,fit=T) weak2 <- " f1 =~ c(1, 1)*Item_1 + c(f2,f2)*Item_2 + c(f3,f3)*Item_3 + c(f4,f4)*Item_4 + c(f5,f5)*Item_5 + c(f6,f6)*Item_6 + c(f7,f7)*Item_7 + c(f8,f8)*Item_8 + c(f9,f9)*Item_9 + c(f10,f10)*Item_10 + c(f11,f11)*Item_11 + c(f12,f12)*Item_12 + c(f13,f13)*Item_13 + c(f14,f14)*Item_14 + c(f15,f15)*Item_15 Item_1 | c(t11, t11)*t1 Item_2 | c(t21, t21)*t1 Item_3 | c(t31, t31)*t1 Item_4 | c(t41, t41)*t1 Item_5 | c(t51, t51)*t1 Item_6 | c(t61, t61)*t1 Item_7 | c(t71, t71)*t1 Item_8 | c(t81, t81)*t1 Item_9 | c(t91,t91)*t1 Item_10 | c(t101, t101)*t1 Item_11 | c(t111, t111)*t1 Item_12 | c(t121, t121)*t1 Item_13 | c(t131, t131)*t1 Item_14 | c(t141, t141)*t1 Item_15 | c(t151, t151)*t1 f1 ~~ NA*f1 f1 ~ c(0, NA)*1 Item_1 ~~ c(1, NA)*Item_1 Item_2 ~~ c(1, NA)*Item_2 Item_3 ~~ c(1, NA)*Item_3 Item_4 ~~ c(1, NA)*Item_4 Item_5 ~~ c(1, NA)*Item_5 Item_6 ~~ c(1, NA)*Item_6 Item_7 ~~ c(1, NA)*Item_7 Item_8 ~~ c(1, NA)*Item_8 Item_9 ~~ c(1, NA)*Item_9 Item_10 ~~ c(1, NA)*Item_10 Item_11 ~~ c(1, NA)*Item_11 Item_12 ~~ c(1, NA)*Item_12 Item_13 ~~ c(1, NA)*Item_13 Item_14 ~~ c(1, NA)*Item_14 Item_15 ~~ c(1, NA)*Item_15 " outWeak2 <- cfa(weak2, data = dat, group = "group", parameterization="theta", estimator="wlsmv") summary(outWeak2,fit=T) strict2 <- " f1 =~ c(1, 1)*Item_1 + c(f2,f2)*Item_2 + c(f3,f3)*Item_3 + c(f4,f4)*Item_4 + c(f5,f5)*Item_5 + c(f6,f6)*Item_6 + c(f7,f7)*Item_7 + c(f8,f8)*Item_8 + c(f9,f9)*Item_9 + c(f10,f10)*Item_10 + c(f11,f11)*Item_11 + c(f12,f12)*Item_12 + c(f13,f13)*Item_13 + c(f14,f14)*Item_14 + c(f15,f15)*Item_15 Item_1 | c(t11, t11)*t1 Item_2 | c(t21, t21)*t1 Item_3 | c(t31, t31)*t1 Item_4 | c(t41, t41)*t1 Item_5 | c(t51, t51)*t1 Item_6 | c(t61, t61)*t1 Item_7 | c(t71, t71)*t1 Item_8 | c(t81, t81)*t1 Item_9 | c(t91,t91)*t1 Item_10 | c(t101, t101)*t1 Item_11 | c(t111, t111)*t1 Item_12 | c(t121, t121)*t1 Item_13 | c(t131, t131)*t1 Item_14 | c(t141, t141)*t1 Item_15 | c(t151, t151)*t1 f1 ~~ NA*f1 f1 ~ c(0, NA)*1 Item_1 ~~ c(1, 1)*Item_1 Item_2 ~~ c(1, 1)*Item_2 Item_3 ~~ c(1, 1)*Item_3 Item_4 ~~ c(1, 1)*Item_4 Item_5 ~~ c(1, 1)*Item_5 Item_6 ~~ c(1, 1)*Item_6 Item_7 ~~ c(1, 1)*Item_7 Item_8 ~~ c(1, 1)*Item_8 Item_9 ~~ c(1, 1)*Item_9 Item_10 ~~ c(1, 1)*Item_10 Item_11 ~~ c(1, 1)*Item_11 Item_12 ~~ c(1, 1)*Item_12 Item_13 ~~ c(1, 1)*Item_13 Item_14 ~~ c(1, 1)*Item_14 Item_15 ~~ c(1, 1)*Item_15 " outStrict2 <- cfa(strict2, data = dat, group = "group", parameterization="theta", estimator="wlsmv") summary(outConfigural2, fit = TRUE) summary(outWeak2, fit = TRUE) summary(outStrict2, fit = TRUE) lavTestLRT(outConfigural2, outWeak2) lavTestLRT(outWeak2, outStrict2) <file_sep>/Miscellaneous/520_lab8_IFA.Rmd --- title: "520_lab5_IRTintro" author: "<NAME>" date: "September 28, 2014" output: pdf_document --- This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>. First, load packages ```{r,eval=FALSE} library(ltm) # general IRT package library(mirt) # package specifically designed for multidimensional IRT library(lavaan) # general SEM, but can do Item Factor Analysis library(psych) # will be using the bfi dataset bfi.sub = bfi[,1:25] ``` You can also embed plots, for example: ```{r, echo=FALSE} plot(cars) ``` Switch to MH-RM when # of dimensions > 3-4. http://www2.uaem.mx/r-mirror/web/packages/mirt/vignettes/mirt-presentation-2012.pdf Mirt functions ```{r} coef() ; summary() plot ``` ```{r} bfi.explore = mirt(bfi,5,itemtype="graded",method="MHRM") ``` ```{r} bfi.mod <- mirt.model(' A = 1-5 C = 6-10 E = 11-15 N = 16-20 O = 21-25 COV = A*C*E*N*O ') # faster when subsetting dataset system.time(mod1 <- mirt(bfi.sub,bfi.mod,method="MHRM")) # time MHRM = 402 sec; system.time(mod2 <- mirt(bfi.sub,bfi.mod,method="EM")) # time EM = 164 summary(mod1) summary(mod2) ``` Get different estimates depending on method used Compare to lavaan -- much faster ML ```{r} bfi.mod.lav <- ' A =~ A1 + A2 + A3 + A4 + A5 C =~ C1 + C2 + C3 + C4 + C5 E =~ E1 + E2 + E3 + E4 + E5 N =~ N1 + N2 + N3 + N4 + N5 O =~ O1 + O2 + O3 + O4 + O5 ' fit.bfi.lav = cfa(bfi.mod.lav,bfi.sub, std.lv=T,missing="FIML") # much faster summary(fit.bfi.lav,fit.measures=T,standardized=T) ``` ```{r} bfi.ord <- data.frame(lapply(bfi.sub, as.ordered)) bfi.mod.cat <- ' A =~ A1 + A2 + A3 + A4 + A5 C =~ C1 + C2 + C3 + C4 + C5 E =~ E1 + E2 + E3 + E4 + E5 N =~ N1 + N2 + N3 + N4 + N5 O =~ O1 + O2 + O3 + O4 + O5 ' fit.bfi.cat = cfa(bfi.mod.cat,bfi.ord, std.lv=T,estimator="wlsmv") summary(fit.bfi.cat,fit.measures=T,standardized=T) ```<file_sep>/Lab1/520_Lab1_introR.R ######### Intro to learning R for the Psychometrics Class ######## ## <NAME> -- Fall 2014 # for other great talks on an introduction to R, check out archived lectures: # https://dornsife.usc.edu/psyc/GC3-lectures ### I strongly recommend the use of Rstudio as a GUI to R ###### makes R much easier to use and learn ##### install required packages for the labs ?install.packages install.packages('lavaan') install.packages('psych') install.packages("mirt") ### there is a way to automatically load packages each time you open up R, ### however it is somewhat complicated -- ask me or email if you want instructions # how to load packages that are already installed --won't work if not installed library(psych) # generally preferable to require(mirt) ##### more direct, is to download straight from Github when available ##### #if not installed already on your computer, install devtools install.packages('devtools') #load and install the package library(devtools) install_github('philchalmers/faoutlier') #reload into you workspace library(faoutlier) #### Also,package has to be loaded to get help files for specific files ####################### Ways to get general help ########################### help.search("histograms") # google type search through R documentation. ??histogram # same thing as help.search(). help.start() # general help. # Looking for a specific function? apropos("plot") # list all functions containing string plot # Help with specific functions help(plot) # same thing ?plot plot # or just type function #The great thing about the plot function, is that it changes depending upon what object is called. # Example of a "Generic function" # other generic functions: summary,anova, predict # list arguments within a function args(describe) methods(class = "lm") # notice the summary.lm -- this is what summary(lmobject) pulls from # Within packages or base R, this is how to get examples -- along with the code to produce them demo(colors) # get demos of what you are looking for example(lm) example(mirt) # for the purposes of this class, will demonstrate techniques with both dichotomous(binary) # and polytomous(likert) type responses # two options to get data -- read in your own or use data included in packages library(help = "datasets") # way to find built in datasets #### dichotomous data library(ltm) # general irt package that contains the LSAT dataset LSAT # prints entire dataset in console View(LSAT) # opens in new tab/window -- tempting for those coming from SPSS -- bad when big dataset head(LSAT,n=10) # head only prints first 10 rows of dataset -- default is 6 colnames(LSAT) # get column names colnames(LSAT) <- c("x1","x2","x3","x4","x5") # change column names -- multiple ways to do it ##### two good ways to describe the data you pull into r summary(LSAT) describe(LSAT) ## from psych package descript(LSAT) ## from ltm package dsc <- descript(LSAT) dsc plot(dsc) ### pull in data from external file #### ?read.table # best for .txt ?read.csv ### same as read.table, but makes defaults simpler such as sep = "," ?read.delim # .tsv ###### simulated dataset from Edwards 2009 # http://faculty.psy.ohio-state.edu/edwards/ # already downloaded on my computer data = read.table(file.choose(),sep="",header=T,na.strings="NA") # pop up finder to click on specified dataset #### important to know what the type of dataset is: # .dat sep="" -- just separated by space # .csv sep="," -- separated by comma summary(data) head(data) # easiest to assign missing now with na.strings="0" or "-99" # changes them to NA which is how R handles missing values data2 = read.table("/Users/RJacobucci/Documents/NCSsim/NCSsim.dat",sep="") ### a lot of times important to specify header=T if your dataset has column names #################### datasets from SPSS, SAS, or other software ######## # SPSS and Minitab, S, SAS, Stata, Systat, Weka, dBase library(foreign) ?read.spss # SAS library(sas7bdat) ?read.sas7bdat # Matlab library(R.matlab) ?readMat ##### more options: http://www.ats.ucla.edu/stat/r/faq/inputdata_R.htm # by column # dimensions ?dim ?length nrow() ncol() ########### find out more information about an object ######## ##### especially useful when trying to find data type of each item ?str out = lm(O5 ~ education, data=bfi) str(out) out$coefficients out$model$education #### reference parts of an object with either $(more common) or @; depends whether S3 or S4: str() will tell you head(bfi$O5) out = lm(O5 ~ education, data=bfi) head(out$residuals) ###### changing type of dataset ?matrix # has to be all of the same mode; e.g. all numeric # convert to matrix as.matrix() ?data.frame # can be different modes; easiest to just convert all read in data to data.frame data.df = data.frame(read.table(...)) ?mode # mode of object, not variable type mode(bfi) #### changing variable type ################## for items: almost always dealing with factor variables str(bfi) # all integers: depending on application, may be important to change to factor is.factor(bfi$O5) bfi$O5fac = as.factor(bfi$O5) str(bfi$O5fac) ?levels levels(bfi$O5fac) # change numeric to factor -- how you would artificially dichotomize an integer variable library(Hmisc); cut2() ?cut # factor variable to numeric bfi$O5num = as.numeric(as.character(bfi$O5fac)) str(bfi$O5num) # to integer -- notice as.character isn't needed -- one oddity about R bfi$O5int = as.integer(bfi$O5fac) str(bfi$O5int) ###### ## subsetting dataset # by row ?sample ?subset str(O5) attach(bfi) # so you don't have to always reference the dataset e.g. varname instead of data$varname str(O5) data[row,col] #### if using non-continuous indices of variables, must use c() combine head(bfi[,1:3,5:7]) # fail head(bfi[,c(1:3,5:7)]) # succeed # another way to pull only certain variables, using indices assigned to an object index = sapply(bfi,is.numeric) # usually just try all apply functions to see which one works new.data = bfi[index] #got rid of factor variables ### good tutorial on apply functions ### # http://nsaunders.wordpress.com/2010/08/20/a-brief-introduction-to-apply-in-r/ ##### myvars = c("O1","O2","O3","O4","O5") openness = bfi[myvars] # same as bfi[,21:25] colnames(bfi) #### rename only one variable in a dataset names(bfi)[5] = "newVar" ?c # combine ?cat # concatenate ############## missing data ################# ## !!!!!!!!!!! maybe the most important topic !!!!!!!!!!!!!!!!! ######## ###### problem is a lot of example datasets removed the missing values ######## library(psych) head(bfi) cor(bfi$A1,bfi$A2) # fails because of missing or NA values args(cor) # -- default in cor is complete cases cor(bfi$A1,bfi$A2,use="pairwise.complete.obs") ###### code -99's as NA ####### data.df[data.df==-99] <-NA # !!!!! ##### !!!!!!!! Different procedure for recoding NA's ##### # the previous procedure doesn't work bfi$education[bfi$education==NA] = -100 str(bfi) bfi$education[is.na(bfi$education)] = -99 str(bfi) ###### analyze missing data ########### sum(is.na(bfi)) # Do this to count the NA in whole dataset comp = sum(!complete.cases(bfi)) # Count of incomplete cases comp/nrow(bfi) # number of people/cases with atleast 1 missing value which(!complete.cases(bfi)) # Which cases (row numbers) are incomplete? ####### identify # misssing, select cases with less or equal to 6 M <- rowSums(is.na(bfi) ) # identify number of missing values per row good.rows <- which( M <= 6 ) bfi.sub <- bfi[ good.rows, ] dim(bfi) dim(bfi.sub) ########### have missing cases imputed with median (3)######################## data.sub[is.na(data.sub)] <- 3 str(data.sub) # number of missing per item colSums(is.na(bfi) ) # imputation ######### check each package's manual to see if there are built in options for imputation imputeMissing(x, Theta) # mirt package ?imputeMissing ###### PreProcessing for imputation ###### # can use the center, scale, or BoxCox if dealing with scales for factor analysis--not for items library(caret) ?preProcess # method = meadianImpute, bagImpute,knnImpute #### tons of packages: imputeR (I like), mice, mi, imputation, impute, amelia ###################################################################################### ################## An important topic not covered is plotting ######################## ############## check out a talk I gave last Spring in the GC3 ######################## ########### http://dornsife.usc.edu/psyc/20140326gc3 ################################ <file_sep>/Lab3/520_lab3_CFAintro.R ######################## 520 lab 3, <NAME> 9/10/14 ###################### ##################### make sure to load all of these packages ########## library(lavaan) library(psych) library(semPlot) ### not used before, make sure to install ####### ########################################## read in data ########################################### ##### change the path to where the file is on your computer ############## ptsd = read.table("/Users/RJacobucci/Dropbox/520/Week3/Week 3 Programs/PTSD_Models_2005/PTSD_17items.dat", header=F, sep=",") ################## add column names ####################### names = c("B1F","B1I","B2F","B2I","B3F","B3I","B4F","B4I","B5F","B5I", "C1F","C1I","C2F","C2I","C3F","C3I","C4F","C4I","C5F","C5I","C6F","C6I","C7F","C7I", "D1F","D1I","D2F","D2I","D3F","D3I","D4F","D4I","D5F","D5I", "B1","B2","B3","B4","B5","C1","C2","C3","C4","C5","C6","C7","D1","D2","D3","D4","D5", "CCP4S1PR","CCP4S2PR","CCP4S3PR","CCP4S4PR","CCP4S5PR","CCP4S6PR", "CCP4S7PR","CCP4S8PR","CCP4S9PR","CCP4S10P","CCP4S11P","CCP4S12P", "CCP4S13P","CCP4S14P","CCP4S15P","CCP4S16P","CCP4S17P","CCP4TOTF", "CCP4TOTI") colnames(ptsd) <- names ######################### meredith correlation matrix #################### meredith <- matrix(c( 1.00,.32,.48,.28,.26,.40,.42,.12,.23, .32, 1.00,.33,.01,.01,.26,.32,.05,-.04, .48,.33, 1.00,.06,.01,.10,.22,.03,.01, .28, .01, .06, 1.00,.75,.60,.15,-.08,-.05, .26, .01, .01, .75, 1.00,.63,.07,.06,.10, .40, .26, .10, .60, .63, 1.00,.36,.19,.24, .42, .32, .22, .15, .07, .36, 1.00,.29,.19, .12, .05, .03, -.08, .06, .19, .29, 1.00,.38, .23, -.04, .01, -.05, .10, .24, .19, .38, 1.00),nrow=9,ncol=9) meredith ################ assign row and col names because matrix ############## rownames(meredith)<-colnames(meredith)<-c( "pl_vis", "pl_cub", "pl_pap", "pl_inf", "pl_sen", "pl_wor", "pl_fig", "pl_obj", "pl_num") ######### take a look ###### meredith ######################## one way to read in cov or cor matrix from base R ####### spear2 <- diag(6) spear2[upper.tri(spear2)]<-c( .83, .78,.67, .70,.67,.64, .66,.65,.54,.45, .63,.57,.51,.51,.40) spear3 = t(spear2) ### assign rownames and colnames because it is a matrix as opposed to data.frame rownames(spear3)<-colnames(spear3)<- c("Classics", "French", "English", "Mathem", "PitDisc", "Music") # Name rows and columns spear3 ############################### an even easier way to read in a cov or cor matrix ?getCov # from lavaan spearman <- ' 1.0 .83 1.0 .78 .67 1.0 .70 .67 .64 1.0 .66 .65 .54 .45 1.0 .63 .57 .51 .51 .40 1.0' spear.cor <- getCov(spearman, names = c("Classics", "French", "English", "Mathem", "PitDisc", "Music")) spear.cor ############################################################################################ ##################################################################################################### ######## basic lavaan syntax ######### # latent variable definition =~ is measured by # regression ~ is regressed on # (residual) (co)variance ~~ is correlated with # intercept (mean) ~ 1 intercept # same as regressed, but with 1 ################## example of regression ################# HS = HolzingerSwineford1939 # take a dataset from lavaan and rename it ########## basic regression in R ###### lm.out = lm(x9 ~ 1 + x1 + x2 + x3,data=HS) # 1 = intercept summary(lm.out) ######## in lavaan ###### lm.mod <- ' x9 ~ x1 + x2 + x3 ' lm.lav = lavaan(lm.mod,data=HS) summary(lm.lav) ################ notice that the Beta's are the exact same ############# ###### the advantage of doing regression with lavaan is using full-information ML #### ###### talk about this more later in the class ######## ############################################## ############ Confirmatory Factor Analysis ############ ###### example model from the tutorial ####### HS.model <- ' visual =~ x1 + x2 + x3 textual =~ x4 + x5 + x6 speed =~ x7 + x8 + x9 ' fit <- cfa(HS.model, data = HolzingerSwineford1939) summary(fit, fit.measures = TRUE) quartz() semPaths(fit) ###################### the cfa() function is a wrapper for the lavaan() function ###### ##### a wraper is just a function that makes assumptions for you, so specify less code ### # same model using lavaan() HS.model2 <- ' visual =~ x1 + x2 + x3 textual =~ x4 + x5 + x6 speed =~ x7 + x8 + x9 # residual variances for each indicator x1~~x1 x2~~x2 x3~~x3 x4~~x4 x5~~x5 x6~~x6 x7~~x7 x8~~x8 x9~~x9 # factor variances visual~~visual textual~~textual speed~~speed # factor covariances visual~~textual # think no covariance between factors -- visual~~0*textual visual~~speed textual~~speed ' fit2 <- cfa(HS.model2, data = HolzingerSwineford1939) summary(fit2, fit.measures = TRUE) quartz() semPaths(fit2) # demonstrate correspondence between code and graphic ###### exact same answer, with a lot more code ######## #### parTable() creates a list of all of the parameters specified -- can run model directly on parTable(fit) parTable(fit2) # exact same as first ############# more advanced topics to be covered later ########## # 1. there are intercepts (means) in the model, but we don't need to specify them # 2. later we will play around with changing the estimator and missing specifications # 3. when comparing groups, or adding in more complicated parameters, lavaan() is usually best ########################################################################## ########################################################################## ################### testing specific model ################################ # CFA is designed to test specific hypotheses ## # therefore, the models we will test are only the ones that Jack has specified ########################## ptsd ################################# cfa_modelA = ' Fac1 =~ B1 + B2 + B3 + B4 + B5 Fac2 =~ C1 + C2 Fac3 =~ C3 + C4 + C5 + C6 + C7 Fac4 =~ D1 + D2 + D3 + D4 +D5 ' fit.ptsd = cfa(cfa_modelA, data=ptsd, missing="FIML") summary(fit.ptsd, fit.measures=T) semPaths(fit.ptsd,"std",intercepts=F) ###################################################################### #################### spearman ############################# spear.mod = ' General =~ Classics + French + English + Mathem + PitDisc + Music ' fit.spear = cfa(spear.mod, sample.cov=spear3,sample.nobs=101) summary(fit.spear,fit.measures=T,standardized=T) quartz() semPaths(fit.spear) ############################################################ #################### Meredith ################################ mere1 = ' General =~ pl_vis + pl_cub + pl_pap + pl_inf + pl_sen + pl_wor + pl_fig + pl_obj + pl_num ' fit.mere1 = cfa(mere1,sample.cov=meredith,sample.nobs=77) summary(fit.mere1,fit.measures=T,modindices = TRUE) fitMeasures(fit.mere1) semPaths(fit.mere1) ######################################################################### # EFA, compare to CFA above ----------------------------------- # because one factor, efa and cfa should be exact same -------- ?fa fa1 = fa(spear3,1,n.obs=101,fm="ml") fa1 # identical to cfa results above when standardized ########### changing interpretation of parameter estimates HS.model.demo <- ' visual =~ x1 + x2 + x3 x1~~x1 x2~~x2 x3~~x3 #visual~~1*visual visual~~1000*visual # fixing factor variance to 1000 ' fit.demo <- lavaan(HS.model.demo, data = HolzingerSwineford1939) summary(fit.demo, fit.measures = TRUE) quartz() semPaths(fit) ################ what happens when under-identified ################# HS.under <- ' visual =~ x1 + x2 ' fit.under <- cfa(HS.under, data = HolzingerSwineford1939) summary(fit.under, fit.measures = TRUE) quartz() semPaths(fit) str(fit.under) <file_sep>/Lab8/520_lab8_DIF.Rmd --- title: "lab8" author: "<NAME>" date: "October 19, 2014" output: pdf_document --- For this lab, we are going to look at ways of analyzing both differential item function (DIF) and differential test functioning (DTF) from both the IRT and FA perspectives ```{r,message=FALSE,warning=FALSE} library(mirt) library(lavaan) library(psych) ``` Create data set that exhibits bias -- taken directly from mirt documentation ```{r} #simulate data where group 2 has a smaller slopes and more extreme intercepts set.seed(12345) a1 <- a2 <- matrix(abs(rnorm(15,1,.3)), ncol=1) d1 <- d2 <- matrix(rnorm(15,0,.7),ncol=1) a2[1:2, ] <- a1[1:2, ]/3 d1[c(1,3), ] <- d2[c(1,3), ]/4 head(data.frame(a.group1 = a1, a.group2 = a2, d.group1 = d1, d.group2 = d2)) itemtype <- rep('dich', nrow(a1)) N <- 1000 dataset1 <- simdata(a1, d1, N, itemtype) dataset2 <- simdata(a2, d2, N, itemtype, mu = .1, sigma = matrix(1.5)) dat <- rbind(dataset1, dataset2) group <- c(rep('D1', N), rep('D2', N)) ``` ```{r} # note, for mirt, the grouping variable has to be separate, not in dataset # EX: # group <- bfi$gender # have to then remove all variables that aren't items # A <- bfi[,1:5] # Information matrix with crossprod model <- multipleGroup(dat, 1, group, SE = TRUE,verbose=F) #test whether adding slopes and intercepts constraints results in DIF. Plot items showing DIF resulta1d <- DIF(model, c('a1', 'd'), plotdif = TRUE,verbose=F) resulta1d ``` So by constraining both the slope and difficulty parameters, it shows the 3 items that were simulated to display DIF, to actually display DIF. Clear that items 1 and 2 show drastically different slopes Item 1 and 3 have different intercepts, which is harder to see. There are numerous other tests to use to detect DIF. I am not well-versed enough to recommend other than the defaults. ```{r} #same as above, but using Wald tests with Benjamini & Hochberg adjustment resulta1dWald <- DIF(model, c('a1', 'd'), Wald = TRUE, p.adjust = 'fdr',verbose=F) resulta1dWald # again shows just the first 3 round(resulta1dWald$adj_pvals, 4) ``` Now, only constraining the slope, which should just show items 1 & 2 ```{r} resulta1 <- DIF(model, 'a1', plotdif = TRUE,verbose=F) resulta1 ``` A little too powerful. This seems to be a theme, where if you test enough items with a large enough sample, there will show DIF just by chance unless the p-values are adjusted. One-way to reduce the type 1 error rate in identifying DIF is the use of anchor items. Anchor items are not allowed to vary in either slope or intercept (or both) across groups. This allows you to focus on items that you suspect to be different. This also helps scale the latent factor covariance and means. This can also be done in a two-step process. First, analyze DIF across all items. Then take items that showed very little likelihood of DIF, and constrain them to be the same across groups. Demonstrated below ```{r} itemnames <- colnames(dat) # constrain all but means and variance model_anchor <- multipleGroup(dat, model = 1, group = group, invariance = c(itemnames[4:15], 'free_means', 'free_var')) anchor <- DIF(model_anchor, c('a1', 'd'), items2test = 1:3) anchor ```` ------------------ Polytomous Example ------------------ ```{r} # create grouping variable group2 <- as.character(bfi$gender) # just use the 5 Agreeableness items A <- bfi[,1:5] # run 1 factor model model.A <- multipleGroup(A, 1, group2, SE = TRUE,verbose=F) ``` The question you have to ask yourself, is whether you care about differences in just the slope, or also the difficulty/thesholds? Model just constraining the slope -- show plot of the only item deemed to show DIF ```{r} res1 <- DIF(model.A, c('a1'), plotdif = TRUE,verbose=F) ``` LRT for each item ```{r} res1 # looking for p-values < 0.05 ``` Looks like item 5 is different between sexes: A5 Make people feel at ease. (q_1419) Anchor for polytomous: ```{r} itemnames2 <- colnames(A) model_anchor2 <- multipleGroup(A, model = 1, group = group2, invariance = c(itemnames2[1:4], 'free_means', 'free_var')) anchor <- DIF(model_anchor2, c('a1'), items2test = 5) anchor ``` Best to do the analyses sequentially, eventually adding anchor items. ```{r,eval=F} # Wald tests with Benjamini & Hochberg adjustment res3Wald <- DIF(model.A, c('a1'), Wald = TRUE, verbose=F,p.adjust = 'fdr') res3Wald round(res3Wald$adj_pvals, 4) ``` ------ Differential Test Functioning (DTF) ------ The mirt package contains a differential test functioning (DTF()), that There seems to be a distinction between the IRT and SEM fields, where DIF is emphasized more in IRT, and in SEM, tend to care more at the test level. When going about the steps of checking for invariance, that is only at the test level. Partial measurement invariance, which I think <NAME> will be talking about, allows for some items to not be constrained after the tests for invariance fail. ------------ With mirt Instead of using the "Constrain" in the model syntax, we can set it up very similar to with lavaan, by using the multipleGroup function and specifying invariance ```{r} mirt.mod <- mirt.model(' F = 1-15 ') config <- multipleGroup(dat, mirt.mod, group = group,verbose=F) equalslopes <- multipleGroup(dat, mirt.mod, group = group, verbose=F,invariance="slopes") anova(config,equalslopes) ``` Try with lavaan -- inital model Configural -- no constraints across groups ```{r} # set up dataset dat.df <- as.data.frame(dat) dat.df2 <- dat.df dat.df2$group <- as.factor(unlist(group)) dat.ord <- data.frame(lapply(dat.df, as.ordered)) dat.ord$group <- as.factor(unlist(group)) mod1 <- ' F =~ Item_1 + Item_2 + Item_3 + Item_4 + Item_5 + Item_6 + Item_7 + Item_8 + Item_9 + Item_10 + Item_11 + Item_12 + Item_13 + Item_14 + Item_15 ' fit1 <- cfa(mod1,dat.ord,group="group",parameterization="theta") summary(fit1,fit.measures=T,standardized=T) ``` -- Metric Start with fixing the loadings across groups ```{r} fit2 <- cfa(mod1,dat.ord,group="group", group.equal=c("loadings"),parameterization="theta") #summary(fit2,fit.measures=T,standardized=T) # WRMR spikes, but everything else "ok" residuals(fit2) # large residual covariance btw 1 & 2 lavTestLRT(fit1,fit2) ``` Went from perfect fit to some level of misfit A large jummp in the chi-square. I would suggest stopping here, as I don't think that these groups exhibit metric invariance. So we see there is a different at the test level, but which items are the culprits? -- the problem is, with this approach, we can only really test at the test level. It is hard to derive information at the item level. Notice really high residual btw Item_1 & Item_2 If there wasn't a difference between the first two models, we would move onto scalar invariance where the thresholds are fixed. ---------- partial measurement invariance ---------- Use group.partial to free the two factor loadings across the group ```{r} fit22 <- cfa(mod1,dat.ord,group="group", group.equal=c("loadings"),parameterization="theta", group.partial=c("F=~Item_1","F=~Item_2")) #summary(fit22,fit.measures=T,standardized=T) # WRMR spikes, but everything else "ok" lavTestLRT(fit2,fit22) ``` Big change by freeing those parameters across groups ----------- Conclusion ----------- In this lab, we probably went out of the ideal sequence. It seems more logical to test for differential functioning (invariance) at the test level first, as if the test demonstrates invariance across all of the levels, then there probably isn't anything significant going on at the item level. When problems occur in testing measurement invariance, then it is probably best to use IRT programs to test for DIF. This will show what are the problematic items, maybe leading you to discard them to achieve invariance at the test level. ------ extra stuff ------ !!!!! Problem There is a problem with fixing the thresholds. The chisquare actually decreases, which isn't possible when constraining Also, there should be something changed with parameterization Strong Invariance Fix thresholds ```{r,eval=FALSE} fit3 <- cfa(mod1,dat.ord,group="group",estimator="wlsmv", group.equal=c("loadings","thresholds"),parameterization="theta") summary(fit3,fit.measures=T,standardized=T) residuals(fit3) # don't really see anything, reduced 1 & 2 lavTestLRT(fit1,fit2,fit3) ``` ```{r,eval=F} library(semTools) measurementInvarianceCat(mod1, data = dat.ord, group = "group", parameterization="theta") ``` Interested in how to fully specify: https://dl.dropboxusercontent.com/u/51983777/Teaching/SEM/catInvariance/catInvariance5.R Good resource: http://www.myweb.ttu.edu/spornpra/catInvariance.html example of how to create group variable ```{r} A <- bfi[,1:5] g1 <- rep(1,nrow(A)/2) g2 <- rep(2,(nrow(A)-nrow(A)/2)) # just in case odd number group <- c(g1,g2) A$group <- group ``` <file_sep>/Lab3/Useful_Links.md [lavaan tutorial](http://lavaan.ugent.be/tutorial/tutorial.pdf) [Tutorial from <NAME>](http://pareonline.net/pdf/v18n4.pdf) [More in-depth overview of lavaan](http://users.ugent.be/~yrosseel/lavaan/lavaan_M3_2013.pdf) [lavaan Jstat](http://www.jstatsoft.org/v48/i02/paper) <file_sep>/Lab7/520_lab7_longIFA.Rmd --- title: "520_lab7_longIFA" author: "<NAME>" date: "Monday, October 13, 2014" output: pdf_document --- For the first part of this lab, we are going to look at how to check measurement invariance across groups or time points. The first thing we have to do is get the dataset set up to facilitate running the models. If you look at the Mplus code, it is quite a lot of constraints that you have to apply to the models. As this class does not focus solely on SEM, we are going to run the same analyses, but focus less on how to code the constraints and more on how to run the same analyses using shortcuts. This shortcut strategy would not work for partial measurement invariance (different constraints across items). Would have to write a lot of code Read in data and assign column names ```{r} name <- c("id", "sex", "hawaii", "c9_1", "c9_2","c9_3","c9_4","c9_5", "c9_6","c9_7","c9_8","c9_9","c9_10", "c9_11","c9_12","c9_13","c10_1", "c10_2","c10_3","c10_4","c10_5", "c10_6","c10_7","c10_8","c10_9", "c10_10","c10_11","c10_12","c10_13","c11_1", "c11_2","c11_3","c11_4","c11_5", "c11_6","c11_7", "c11_8","c11_9", "c11_10","c11_11","c11_12","c11_13","c12_1", "c12_2","c12_3","c12_4","c12_5", "c12_6","c12_7","c12_8","c12_9", "c12_10","c12_11","c12_12","c12_13","sexhaw") # this is how to read in .dat file and assign own column names cesd <- read.table("/Users/RJacobucci/Dropbox/520/Week8/cesd.dat",sep=" ", na.strings=".",col.names=name) ``` convert wide format to long ```{r} # all item names measure <- c("c9_1", "c9_2","c9_3","c9_4","c9_5", "c9_6","c9_7","c9_8","c9_9","c9_10", "c9_11","c9_12","c9_13","c10_1", "c10_2","c10_3","c10_4","c10_5", "c10_6" ,"c10_7","c10_8","c10_9", "c10_10","c10_11","c10_12","c10_13","c11_1", "c11_2","c11_3","c11_4","c11_5", "c11_6","c11_7","c11_8","c11_9", "c11_10","c11_11","c11_12","c11_13","c12_1", "c12_2","c12_3","c12_4", "c12_5","c12_6","c12_7","c12_8","c12_9", "c12_10","c12_11","c12_12","c12_13") # what we will call the items in the long dataset new2 =c("x1","x2","x3","x4","x5","x6","x7","x8","x9","x10","x11","x12","x13") cesd.long <- reshape(cesd, varying = measure, v.names = new2, times = c(1, 2, 3, 4), direction = "long") ``` Reliability across the two time points ```{r} cesd$sum1 <- rowSums(cesd[,6:18],) cesd$sum2 <- rowSums(cesd[,19:31]) cor(cesd$sum1,cesd$sum2,use="pairwise.complete.obs") ``` Plot ```{r} plot(cesd$sum1,cesd$sum2) ``` specify variables as ordinal ```{r} #cesd[,4:55] <- data.frame(lapply(cesd[,4:55], as.ordered)) cesd.Lord <- as.data.frame(cesd.long) cesd.Lord[,6:18] <- data.frame(lapply(cesd.long[,6:18], as.ordered)) # just 2 time points cesd.long2 <- subset(cesd.long,cesd.long$time ==1 | cesd.long$time == 2) cesd.Lord2 <- as.data.frame(cesd.long2) cesd.Lord2[,6:18] <- data.frame(lapply(cesd.Lord2[,6:18], as.ordered)) ``` For the first two models, we are just going to pretend like our variables aren't items just for demonstration purposes. One of the big problems with specifying variables as categorical, is there can't be empty cells for the response categories. By this I mean if an item has response options of 1,2,3,4, there have to be at least one response for each category. Items that are extremely hard or easy, as well as items with a lot of response categories tend to have problems with this. Neither lavaan nor Mplus will run if this occurs. Not sure what the best protocal is other than just collapsing the category. Run just the first two time points without specifying any constraints ```{r} library(lavaan) cesd.mod1 <- ' time9 =~ c9_1 + c9_2 + c9_3 + c9_4 + c9_5 + c9_6 + c9_7 + c9_8 + c9_9 + c9_10 + c9_11 + c9_12 + c9_13 time10 =~ c10_1 + c10_2 + c10_3 + c10_4 + c10_5 + c10_6 + c10_7 + c10_8 + c10_9 + c10_10 + c10_11 + c10_12 + c10_13 ' mod.fit1 <- cfa(cesd.mod1,cesd,std.lv=T) summary(mod.fit1,fit.measures=T,standardized=T) ``` Doesn't fit that well, but probably because using ML In the next model, we are fixing the factor loadings to be equal across time. This is done by using the same label for each item. (item 1: "l1" at each time) This will almost always fit worse (maybe not as the # of df increases) ```{r} cesd.mod2 <- ' time9 =~ l1*c9_1 + l2*c9_2 + l3*c9_3 + l4*c9_4 + l5*c9_5 + l6*c9_6 + l7*c9_7 + l8*c9_8 + l9*c9_9 + l10*c9_10 + l11*c9_11 + l12*c9_12 + l13*c9_13 time10 =~ l1*c10_1 + l2*c10_2 + l3*c10_3 + l4*c10_4 + l5*c10_5 + l6*c10_6 + l7*c10_7 + l8*c10_8 + l9*c10_9 + l10*c10_10 + l11*c10_11 + l12*c10_12 + l13*c10_13 # constrain threshold # c9_1 | a1*t1 + a2*t2 # c10_1 | a1*t1 + a2*t2 # constrain residuals # c9_1 ~~ r1*c9_1 # c10_1 ~~ r1*c10_1 ' mod.fit2 <- cfa(cesd.mod2,cesd,std.lv=T) summary(mod.fit2,fit.measures=T,standardized=T) # Likelihood ratio test lavTestLRT(mod.fit1,mod.fit2) ``` No significant difference With categorical data, don't constrain intercepts. Instead, thresholds https://groups.google.com/forum/#!topic/lavaan/iN7gJf9KAbQ We are going to use shortcuts to run the successive models. By creating a long data file, we only have to specify one factor, and tell lavaan that there are multiple groups. This should be the exact same thing as constraining the model across time. Types of Invariance configural invariance (model1) = structure weak (metric) invariance (model2) = structure, factor loadings strong (scalar) invariance (model3) = weak invariance + indicator intercepts strict (residual variance) invariance (model4) = strong invariance + indicator residual variances Configural ```{r} cesd.group <- ' time =~ x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 + x10 + x11 + x12 + x13 ' mod.fit1 <- cfa(cesd.group,cesd.Lord,std.lv=T, group="time") #summary(mod.fit1,fit.measures=T,standardized=T) ``` Weak (metric) ```{r} mod.fit2 <- cfa(cesd.group,cesd.Lord,std.lv=T, group="time", group.equal=c("loadings")) lavTestLRT(mod.fit1,mod.fit2) ``` Strong -- thresholds when dealing with categorical data ```{r} mod.fit3 <- cfa(cesd.group,cesd.Lord,std.lv=T, group="time", group.equal=c("loadings","thresholds")) lavTestLRT(mod.fit1,mod.fit2,mod.fit3) ``` Strict ```{r} mod.fit4 <- cfa(cesd.group,cesd.Lord,std.lv=T, group="time", group.equal=c("loadings","thresholds","residuals")) lavTestLRT(mod.fit1,mod.fit2,mod.fit3,mod.fit4) summary(mod.fit4,fit.measures=T,standardized=T) ``` Note, the reason why both strong and strict are the exact same is because with items, the categories collapse as the thresholds and residuals (uniqueness) are the same. Therefore, with items the last type of invariance is Scalar. From this, we can see that constraining the factor loadings to be the same across all 4 time points increases the model misfit significantly. For the third model, constraining the 3 thresholds for each item does not significantly increase the model misfit. Use semTools -- doesn't work ```{r} library(semTools) # measurementInvarianceCat(cesd.group, data = cesd.Lord, group = "time", # parameterization="theta") # if continuous variables # ?measurementInvariance # longitudinal -- have to be continuous # ?longInvariance ``` The concepts we learned today apply to both group and longitudinal invariance. Since this is not a course that focuses on longitudinal data analysis, there is no homework this week. However, the analyses we ran today will show up for next week's homework in addition to testing group differences in an IRT context. <file_sep>/Lab5/520_lab5_introIRT.Rmd --- title: "520_lab5_introIRT" output: pdf_document --- This lab will follow the outline of Edwards (2009) introduction to IRT paper and use the same dataset to reproduce the output. The paper and dataset can be downloaded from: http://faculty.psy.ohio-state.edu/edwards/ <NAME>. (2009). An introduction to item response thoery using the Need for Cognition Scale. Social and Personality Psychology Compass, 3, 507-529. ```{r} library(ltm) library(mirt) library(lavaan) library(psych) ``` Read in the simulated NCS dataset ```{r} #ncs.dat = read.table("C:/Users/jacobucc/Dropbox/NCSsim/NCSsim.dat",sep="") # just change path to where downloaded and extracted file is ncs.dat = read.table("/Users/Rjacobucci/Dropbox/NCSsim/NCSsim.dat",sep="") str(ncs.dat) # make sure read in correctly describe(ncs.dat) descript(ncs.dat) ``` For the example comparisons between the 1PL and 2PL models, we will simulate dichotomous data for the examples ```{r} # using mirt package set.seed(4634) a <- matrix(c( .5, 1.5, 2.5, 2, 0.2, 1),ncol=1,byrow=TRUE) d <- matrix(rnorm(6)) itemtype <- rep('dich',6) sim.dat <- data.frame(simdata(a,d,2000,itemtype)) str(sim.dat) ``` To produce Table 1 on p.509 using the GRM Remember, the grm is like running a 2PL model for every threshold ```{r} ncs.mirt1 = mirt(ncs.dat,1,itemtype="graded") coef(ncs.mirt1,IRTpars=T) # defaults to IFA parameters ncs.ltm1 = grm(ncs.dat) # takes longer than mirt summary(ncs.ltm1) # almost identical, Dscrmn = a parameter; Extrmt = b parameter ``` The Coefficients are nearly identical, any variation is probably due to the fact that we are using a simultated dataset You will notice in using different IRT/FA software packages that the output parameters can look drastically different. Generally, packages designed for MIRT/IFA will differ from UIRT (unidimensional IRT) packages To convert, many packages will have options to change output like with mirt above (IRTpars=T) McDonald talks about this on p.252 --- For thresholds, have to convert with inverse of -b/a Additionally, when using a SEM package, you have to convert the factor loadings to be equivalent to the "a" parameters in IRT Further equations for conversion can be found on McDonald p.259 This function will convert factor loadings: ```{r} ######################## how to convert ############################# # difficulty = threshold / loading # discrimination = loading / sqrt(denom) # denom = 1 - loading^2 # often estimate of discrimination needs to be multiplied by 1.7 (from probit to logit) convert <- function(loading){ denom = 1-loading^2 discrim = loading/sqrt(denom) return(discrim*1.7) } ``` Example comparing mirt vs lavaan vs. ltm ```{r} ##### ltm #### ncs.ltm2 = grm(ncs.dat,IRT.param=F) # changes values summary(ncs.ltm2) ##### mirt #### coef(ncs.mirt1) ``` For lavaan, switching to WLSMV estimator = Item Factor Analysis ---IRT models always have the theta mean = 0, variance = 1 ```{r} ##### lavaan #### # first convert data type ncs.ord <- data.frame(lapply(ncs.dat, as.ordered)) ncs.mod <-' fac =~ V1 + V2 + V3 + V4 + V5 + V6 + V7 + V8 + V9 + V10 + V11 + V12 + V13 + V14 + V15 + V16 + V17 + V18 ' fit <- cfa(ncs.mod, std.lv=T, data = ncs.ord) summary(fit) # item18, .612 from mirt convert(.333) # 0.6 -- t is usual to expect some discrepency across estimators ``` Reproduce figure 1 and figure 2 Plot first three items from the simulated data --- "a" slope = across items -- only "b" or difficulty varies ```{r} # mirt mmod1 = mirt(sim.dat,1,itemtype="Rasch") quartz() plot(mmod1, type = 'trace', which.items = 1:3, facet_items = FALSE) quartz() # ltm lmod1 <- ltm::rasch(sim.dat,IRT.param=F) plot(lmod1, items = 1:3,zrange = c(-6, 6)) ``` Plot first three items using 2PL -- "a" allowed to vary along with "b" ```{r} # mirt mmod2 = mirt(sim.dat,1) # mirt defaults to 2PL #### note the crossing trace lines -- can't get with Rasch/1PL plot(mmod2, type = 'trace', which.items=1:3, facet_items = FALSE) quartz() # ltm lmod2 <- ltm(sim.dat~z1,IRT.param=F) plot(lmod2, items = 1:3,zrange = c(-6, 6)) ``` NCS Items 10 and 13 Trace Lines ```{r} itemplot(ncs.mirt1, 10) itemplot(ncs.mirt1, 13) plot(ncs.ltm2, items = c(10,13),zrange = c(-6, 6)) ``` Then compare items 2 and 18 ```{r} itemplot(ncs.mirt1, 2) itemplot(ncs.mirt1, 18) ``` Check the unidimensionality assumption ```{r} fa.parallel(ncs.dat,fa="fa") ``` One of the clearer depictions of a unidimensional construct that you will ever see Summed Scores versus ability estimates ```{r} ncs.dat$sum = rowSums(ncs.dat) ncs.dat$theta = fscores(ncs.mirt1, full.scores = TRUE, scores.only = TRUE) windows() plot(ncs.dat$sum,ncs.dat$theta,xlim=c(55,61),ylim=c(-.6,.8)) ``` Item information from items 1,2,3 from the dichotomous items ```{r} plot(lmod2,items=1:3, type = "IIC", legend = TRUE, cx = "topright", lwd = 2, cex = 1.4) ``` IIC from NCS ```{r} plot(ncs.ltm2,items=c(1,9,18), type = "IIC", legend = TRUE, cx = "topright", lwd = 2, cex = 1.4) ``` Test information from 9 and 18 item NCS ```{r} # select items with highest slopes ncs.sub = ncs.dat[,c(1:5,10:12,14:15)] ncs.mirt3 = mirt(ncs.sub,1,itemtype="graded") coef(ncs.mirt3,IRTpars=T) # defaults to IFA parameters ncs.ltm3 = grm(ncs.sub) # takes longer than mirt summary(ncs.ltm3) # almost identical, Dscrmn = a parameter ``` Create Test information plots ```{r} # mirt -- not sure how to set Y range -- ylim doesn't work quartz() plot(ncs.mirt3,type="infoSE",theta_lim = c(-3, 3)) plot(ncs.mirt1,type="infoSE",theta_lim = c(-3, 3)) # ltm -- can't get SE ? plot(ncs.ltm1,items=0,type="IIC",zrange=c(-3,3)) ```<file_sep>/Lab2/520_lab2_CTT.R ######### Classical Test Theory for the Psychometrics Class ######## ## <NAME> -- Fall 2014 # for the purposes of this lab, we will make the implicit assumption that the # scale we are measuring is unidimensional. In later labs, we will test this # assumption directly through a number of methods library(psych) library(CTT) library(ltm) library(polycor) # technically not needed as it is a dependency for ltm pkg str(bfi) agree = bfi[,1:5] ######################## ways to get a general description ############ describe(agree) summary(agree) descript(agree) # plot only works for dichotomous items # summary statistics by group ?describeBy describeBy(bfi[,1],group=bfi$education) ########### one thing to be conscious of is which packages are loaded ########### if two packages have the same function name, problems can occur detach(package:ltm) library(ltm) ###### get a better feeling for the distribution of each item ######## ## okay to use attach(agree) head(A1) head(agree$A1) par(mfrow=c(3,2)) quartz() hist(A1,breaks=7); hist(A2,breaks=7);hist(A3,breaks=7);hist(A4,breaks=7);hist(A5,breaks=7) # or just do quartz() multi.hist(agree) par(mfrow=c(1,1)) # change by # 3D Scatterplot library(scatterplot3d) quartz() scatterplot3d(A1,A2, main="3D Scatterplot") # confusing cor.pear = round(cor(agree,use="pairwise.complete.obs",method="pearson"),3) # assumes bivariate normality library(corrplot) corrplot(cor.pear) # from psych scatter.hist(x=A1, y=A2, density=TRUE, ellipse=TRUE) ?scatter.hist pairs(agree) # more useful for continuous variables library(lavaan) HS=HolzingerSwineford1939 pairs(HS[,9:12]) densityBy(agree) # from psych ellipses(agree) #error.bars(agree) library(ggplot2) qplot(x4, x5, data=HS, size=I(3),colour=as.ordered(sex), xlab="item1", ylab="item2") qplot(x5,data=HS, geom="density", fill=as.ordered(school), alpha=I(.5)) #### many more options for cool plots ##### #### 3d distribution : http://stackoverflow.com/questions/19949435/3d-plot-of-bivariate-distribution-using-r-or-matlab ############################## calculate correlations #################### ## okay to use if interval or ratio ## count.pairwise(agree) # find effective sample size cor.pear = round(cor(agree,use="pairwise.complete.obs",method="pearson"),3) # assumes bivariate normality corFiml(agree) # full information ML -- handles missing data corr.test(agree) # find whether significant # because ordinal, lets see how attenuated the correlation is # ?polychor # polytomous ?tetrachor # binary ?hetcor # picks type of correlation based on variable type ## convert to ordinal -- link will come in handy later # http://lavaan.ugent.be/tutorial/cat.html ?as.ordered # works for one variable ############# general structure to convert ############## Data[,c("item1", "item2", "item3", "item4")] <- lapply(Data[,c("item1", "item2", "item3", "item4")], ordered) ############################################ # important for lavaan, not so important for many other packages agree.ord = data.frame(lapply(agree, ordered)) # put in data.frame, otherwise a list str(agree.ord) hetcor(agree.ord) poly = polychoric(agree) # from psych -- different than polychor() from polycor package round(poly$rho,3) # compare to cor.pear ################### clear attenuation attributed to violation of assumptions ##### ##### another example in the case of binary variables ##### round(cor(LSAT),2) round(tetrachoric(LSAT)$rho,2) #residual round(cor(LSAT),2) - round(tetrachoric(LSAT)$rho,2) ######################################################################### # in my opinion, this is one of the most important concepts of the course # traditionally, many techniques in psychometrics were based on something # similar to the pearson correlation. When used on either dichotomous or polytomous # items, this led to much weaker results as a result of violating assumptions. # It is for this reason that "newer" techniques such as IRT were created. #################################################################################### detach(package:psych) # overlap between CTT and psych packages ############################ CTT package ########################### library(CTT) ################### why reliability matters ####################### disattenuated.cor(0.6,c(0.7,0.8)) ?disattenuated.cor out = reliability(agree) str(out) out$alphaIfDeleted reliability(agree[,2:5]) # item 1 is bad reliability(LSAT) spearman.brown(0.431, input = 2, n.or.r = "n") # double the size of the scale spearman.brown(0.431, 0.8, "r") # factor to reach desired reliability 5*5.28 # 26 items # see the curve for a range of factors in Spearman Brown #vals = seq(from=1,to=20,by=0.1) rel = rep(0,191) for(i in 1:length(rel)){ vals = seq(from=1,to=20,by=0.1) rel[i] = spearman.brown(0.431, input =vals[i] , n.or.r = "n") } reliability = unlist(rel) quartz() plot(vals,reliability,xlim=c(1,20),ylim=c(0,1),xlab="factor") detach(package:CTT) ########################################################################## ################ psych package ####################### library(psych) correct.cor alpha(agree) ############### something changed ################## # reliability went from .431 to 0.7 # A1 should have been reverse-scored data(bfi) head(bfi$A1) # function to reverse score # reverse = function(x){ x = (max(x,na.rm=T) +1) - x } head(bfi$A1) head(reverse(bfi$A1)) # overwrite the variable # bfi$A1 = reverse(bfi$A1) agree=bfi[,1:5] library(CTT) reliability(agree) # now in agreement detach(package:CTT) #### for basic item analysis, reverse scoring the appropriate items is important #### when it comes to latent variable models, it won't affect fit but will interpretation # we will go over this in the FA labs omega(agree,nfactors=1) ?omega outlier(agree) outlier(LSAT) # want to great testlets? parcels(bfi[,1:25]) # dummy.code(A1) #logistic(); logit() phi.demo() x <- matrix(c(40,5,20,20),ncol=2) phi(x) ########### additional forms of reliability ############ splitHalf(cor.pear) # same as guttman tenberge(cor.pear) glb(cor.pear) glb.fa(cor.pear) spider(y=26:28,x=1:25,data=cor(bfi,use="pairwise"),fill=TRUE,scale=2) # test whether correlation is sig. n <- 30 r <- seq(0,.9,.1) rc <- matrix(r.con(r,n),ncol=2) r.test(n,r) ?rangeCorrection ?rescale ?scaling.fits # scoring a scale ?score.alpha ?score.irt ?score.multiple.choice ?scrub ?sim # simulate data from psych package ########### inter-rater reliability ################## cohen.kappa() #from psych package ICC() # psych<file_sep>/Lab6/520_lab6_introIRT2.Rmd --- title: "520_lab6_introIRT2" output: pdf_document --- This lab will present a basic overview of unidimensional IRT in R, with many of the code and process overlapping from the previous lab that was given inadequate time. ```{r,message=FALSE,warning=FALSE} library(ltm) # unidimensional IRT models library(mirt) # unidimensional and multidimensional IRT models library(lavaan) library(psych) ``` We will continue with using the bfi dataset from the psych package. -- for the unidimensional models, we will use just the agreeableness items ```{r} agree <- bfi[,1:5] ``` To test whether it is truly one factor truly accounts for the five items, we will use EFA to test the factor structure. ```{r} fa.parallel(agree,fa="fa") ``` The unidimensionality assumption for agree is pretty iffy. The algorithm suggest 3 factors and 1 component (from PCA). Let's try a different scale, conscientiousness, to see if it is cleaner for our purposes. ```{r} C.dat <- bfi[,6:10] fa.parallel(C.dat,fa="fa") ``` Let's try in a CFA and check the fit indices ```{r} C.mod <- ' C =~ C1 + C2 + C3 + C4 + C5 ' mod.fit1 <- cfa(C.mod,C.dat,std.lv=T) summary(mod.fit1,fit.measures=T,standardized=T) # number of values > 0.1 -- 0.1 is a general cutoff for poor fit residuals(mod.fit1)$cov ``` The fit is borderline, let's see if treating the data as categorical changes the fit Notice also in the factor loading matrix that there are negatively loaded items. These should have been reverse scored. ```{r} # reverse score source("/Users/RJacobucci/Github/Psychometrics_Labs/Miscellaneous/ReverseScore.R") C.dat2 = C.dat # create new dataset so we don't accidentally overwrite C.dat2$C4 <- as.integer(ReverseScore(C.dat$C4)) C.dat2$C5 <- as.integer(ReverseScore(C.dat$C5)) str(C.dat2) # make sure it is still a dataframe ``` Convert the data to ordinal, and run in lavaan using WLSMV estimator ```{r} C.ord <- data.frame(lapply(C.dat2, as.ordered)) str(C.ord) C.mod <- ' C =~ C1 + C2 + C3 + C4 + C5 ' mod.fit2 <- cfa(C.mod,C.ord,std.lv=T) summary(mod.fit2,fit.measures=T,standardized=T) # better residual variances than above model residuals(mod.fit2)$cov mi <- modindices(mod.fit2) mi[mi$op == "~~",] ``` Better fit for some indices (CFA,TLI), worse for others (RMSEA). Although it is borderline, I think for our purposes, it is safe to proceed. As an aside, in the last analysis, we conducted what would be termed Item Factor Analysis (IFA). McDonald writes about IRT from more of an IFA perspective, using the metric and terminology. We will use the mirt package to estimate a Graded Response model: ```{r,message=FALSE,warning=FALSE} C.mirt1 = mirt(C.dat2,1,itemtype="graded") # mirt only accepts integer values coef(C.mirt1,IRTpars=T) # defaults to IFA parameters residuals(C.mirt1) # look at upper triangle -- values > 0.1 are not good -- C1 biggest offender # this is simular to assessing mod indices above ``` Looking at the parameters, all 5 items look to be solid indicators of the latent variable. This is seen by examining the "a", or slope, parameters. The "b", or item difficulty (different term for personality), is harder to judge whether items measure best at the low end of Conscientiousness or better at the higher end. It is easiest to examine b's graphically --- because there are 5 trace lines for each item, you need to look at each item individually Item 1 ```{r} itemplot(C.mirt1, 1) ``` Item 2 ```{r} itemplot(C.mirt1, 2) ``` Item 3 ```{r} itemplot(C.mirt1, 3) ``` Item 4 ```{r} itemplot(C.mirt1, 4) ``` Item 5 ```{r} itemplot(C.mirt1, 5) ``` Interesting to note that categories 3 and 4 are somewhat worthless. In each item, either one of the categories isn't expected to be chosen at any ability level. --This is demonstrated in item 5 with the red distribution being completely covered by other category distributions. Let's see if anything changes when using the 1pl equivalent of GRM. ```{r,message=FALSE,warning=FALSE} # using mirt.model syntax, constrain all item slopes to be equal model <- mirt.model(' C = 1-5 CONSTRAIN = (1-5, a1)') Cmod_equalslopes <- mirt(C.dat2, model,itemtype="graded") coef(Cmod_equalslopes,IRTpars=T) anova(Cmod_equalslopes, C.mirt1) #significantly worse fit with almost all criteria residuals(Cmod_equalslopes) ``` Across all of the fit indices, the GRM with variable slopes fits significantly better Let's now assess where the scale assesses most of the information. ```{r} plot(C.mirt1) ``` For only having 5 items, the scale does a reasonably good job at assessing information across a wide range of ability levels (-3 to 2). If you wanted to test people at higher levels of conscientiousness, it would be advisable to add at least a couple items that measure best at higher proficiency levels. <file_sep>/Lab6/sim_data.R library(lavaan) #specify population model population.model <- ' f1 =~ 0.8*x1 + 0.8*x2 + 0.8*x3 + 0.8*x4 + 0.8*x5 + 0*x6 + 0*x7 + 0*x8 + 0*x9 + 0*x10 f2 =~ 0*x1 + 0*x2 + 0*x3 + 0.25*x4 + 0.25*x5 + 0.8*x6 + 0.8*x7 + 0.8*x8 + 0.8*x9 + 0.8*x10 f1~~0.5*f2 ' population.model <- ' f1 =~ 0.8*x1 + 0.8*x2 + 0.8*x3 + 0.8*x4 + 0.2*x5 + 0.1*x6 ' # generate data #set.seed(12345) myData <- simulateData(population.model,model.type="cfa", sample.nobs=10000L) #write.table(myData,"/Users/RJacobucci/Desktop/simDat_reg.dat",sep=" ",row.names=F,col.names=F) co <- round(cor(myData),2) write.table(co,"/Users/RJacobucci/Desktop/cor.dat",sep=" ",row.names=F,col.names=F) lower.tri(co, diag = FALSE) co[upper.tri(co)] mod <- ' f1 =~ x1 + x2 + x3 + x4 + x5 f2 =~ x6 + x7 + x8 + x9 + x10 ' mod.fit <- cfa(mod,myData,std.lv=T) summary(mod.fit,fit.measures=T) residuals(mod.fit) mi <- modindices(mod.fit) mi[mi$op == "~~",] simulateData fitted(sem(population.model)) # what contributes to misfit? # ESEM R <- ' 1 .686 1 .684 .682 1 .712 .714 .704 1 .710 .712 .704 .780 1 .457 .454 .454 .615 .620 1 .464 .468 .461 .622 .628 .781 1 .466 .463 .455 .616 .621 .781 .782 1 .469 .463 .458 .621 .624 .780 .782 .784 1 .460 .463 .455 .616 .621 .777 .779 .776 .780 1 ' R.esem1 <- getCov(R) R.esem1 R.Expl1 <- factanal(covmat=R.esem1, factors =2) R.Expl1 F <- matrix(R.Expl1$loadings[1:20],10,2) F F1 <- rbind(F[5,], F[3,]) F1 H <- solve(F1) %*% diag (sqrt(diag(F1 %*% t(F1)))) Rotated.F <- zapsmall (F %*% H) Rotated.F solve(H) %*% t(solve(H)) <file_sep>/Lab4/520_lab4_FA2.Rmd --- title: "520_lab4_FA2" output: pdf_document --- Load Packages: ```{r} library(lavaan) library(psych) library(semTools) library(semPlot) ``` For this lab, we will only be using the bfi dataset from the psych package. The dataset has 5 items, purported to measure each of the "big five" dimensions. ```{r, echo=FALSE} data = bfi[,1:25] describe(data) ``` CFA is a hypothesis testing procedure, as EFA is a hypothesis generating technique. Because we have a general idea about the factor structure, it is best to test this out before conducting any exploratory analyses. My hypothesis is that there are 5 orthogonal (uncorrelated) factors. If this fits well, we could be done with our analyses. However, if it doesn't, we will move into the exploratory phase. ```{r} bfi.mod1 <- ' A =~ A1 + A2 + A3 + A4 + A5 C =~ C1 + C2 + C3 + C4 + C5 E =~ E1 + E2 + E3 + E4 + E5 N =~ N1 + N2 + N3 + N4 + N5 O =~ O1 + O2 + O3 + O4 + O5 ' fit.bfi1 = cfa(bfi.mod1,data, std.lv=T, orthogonal=T,missing="fiml") #orthogonal is shortcut to specify uncorrelated factors summary(fit.bfi1,fit.measures=T,standardized=T) ``` To determine whether it is a good fit, I generally look for the RMSEA < .06 or .07, and CFI/TLI > .95. For this model, the RMSEA is "adequate", but the CFI and TLI are well below an adequate fit. This model fits poorly, and we will move into the exploratory phase. An additional source of misfit may be derived from fitting a model that assumes that the manifest variables are continuous scales. The model may fit better if we treat the variables as ordinal, and use an appropriate estimator. Lavaan defaults to the "wlsmv", meaning weighted least square, with mean and variance adjustment. This is the best estimatory to use when using binary or likert type items. First, change the data to ordered: ```{r} data.ord <- data.frame(lapply(data, as.ordered)) str(data.ord) # worked ``` The big problem with changing estimators, is that now we can't use full information maximum likelihood.To make sure the missing values are missing at random, I tried the first model we tried, specify missing="fiml", and removing this. The fit did not change, therefore, missing values shouldn't play a role in our interpretation. Although once you change the class of each item, lavaan defaults to wlsmv, its worth specifying just for reference. ```{r} bfi.mod.cat <- ' A =~ A1 + A2 + A3 + A4 + A5 C =~ C1 + C2 + C3 + C4 + C5 E =~ E1 + E2 + E3 + E4 + E5 N =~ N1 + N2 + N3 + N4 + N5 O =~ O1 + O2 + O3 + O4 + O5 ' fit.bfi.cat = cfa(bfi.mod.cat,data.ord, std.lv=T,orthogonal=T,estimator="wlsmv") summary(fit.bfi.cat,fit.measures=T,standardized=T) ``` Note: It is best to report the robust column: https://groups.google.com/forum/#!msg/lavaan/wYA9msIv5TI/YGP6DScGdMsJ With the wlsmv estimator, you get a new fit statistics, the WRMR. This is from Mplus, and you want values < 1. Changing the estimator did not change the fit of the model. Still horrible. Before moving into using EFA's, I want to note some alternative ideas I have. One is that the latent factors may be correlated, possibly with a higher order factor. Additionally, a bifactor model may fit better. ----------------------------------------------------- EFA Phase ------------------------------------------------- ```{r} unrotated.5 <- efaUnrotate(data, nf=5) summary(unrotated.5, std=TRUE) ``` Didn't really come up with a clean picture. First factor seems to be general, second a mix of N and E. Let see if we rotate the factors it comes up with a cleaner picture ```{r} ?orthRotate ?oblqRotate oblq.5 = oblqRotate(unrotated.5) summary(oblq.5) ``` Nicer output, and gives a pretty clean picture of the factor structure. Based on the patter, it looks like there really are 5 factors, and a number of the factors seem to be significantly correlated. Note, they are correlated, but not to a high degree. If the factor correlations were north of 0.50, I would try a higher order factor model. I don't think this will fit well but we can try it. From the EFA results, the part that I think is the most important is that factor loading matrix. Use these results to assign which items load onto which factors in the CFA. Generally, look for loadings > 0.30. When conducting EFA, you may be asked for the the proportion of variance (or eigenvalues) for each factor.This doesn't come with the lavaan output, but you can get it from fa() in the psych package ```{r} fa(data,5) # 5 factors account for 41% of variance ``` Back to the basics, try a 1 factor model. ```{r} bfi.1fac <- ' Pers =~ A1 + A2 + A3 + A4 + A5 + C1 + C2 + C3 + C4 + C5 + E1 + E2 + E3 + E4 + E5 + N1 + N2 + N3 + N4 + N5 + O1 + O2 + O3 + O4 + O5 ' fit.bfi.1fac = cfa(bfi.1fac,data, std.lv=T) summary(fit.bfi.1fac,fit.measures=T,standardized=T) modindices(fit.bfi.1fac) # lot of residual covariances ``` Horrible fit, with a number of the items loading < 0.3 1 factor does not work, and I see no evidence of anywhere from 2-4 factors. However, you could trying running separate EFA's, specifying differing numbers of factors. The difficulty is determining which items load on which factors. I suggest going back to the 5 factor model and first allowing the factors to correlate. Just remove the orthogonal=T ```{r} bfi.mod.cat2 <- ' A =~ A1 + A2 + A3 + A4 + A5 C =~ C1 + C2 + C3 + C4 + C5 E =~ E1 + E2 + E3 + E4 + E5 N =~ N1 + N2 + N3 + N4 + N5 O =~ O1 + O2 + O3 + O4 + O5 ' fit.bfi.cat2 = cfa(bfi.mod.cat2,data.ord, std.lv=T,estimator="wlsmv") #note, orthogonal=T gone summary(fit.bfi.cat2,fit.measures=T,standardized=T) modindices(fit.bfi.cat2) ``` Worth noting that the fit is slightly better when specifying the data as ordinal and changing the estimator. Also worth noting how high the factor inter-correlations are. This accounted for a significant amount of misfit in the first model we tested. Only one weak item: O4. With a factor loading of 0.168, it is candidate for removal. Look at the modindices: the highest mi suggest to let O4 load onto N. Therefore, lets try two models, one with O4 removed, and one with O4 loading onto N and O. ```{r} bfi.mod.cat3 <- ' A =~ A1 + A2 + A3 + A4 + A5 C =~ C1 + C2 + C3 + C4 + C5 E =~ E1 + E2 + E3 + E4 + E5 N =~ N1 + N2 + N3 + N4 + N5 O =~ O1 + O2 + O3 + O5 # O4 gone ' fit.bfi.cat3 = cfa(bfi.mod.cat3,data.ord, std.lv=T,estimator="wlsmv") #note, orthogonal=T gone summary(fit.bfi.cat3,fit.measures=T,standardized=T) ``` CFI from 0.824 to 0.846. Not that big of improvement ```{r} bfi.mod.cat4 <- ' A =~ A1 + A2 + A3 + A4 + A5 C =~ C1 + C2 + C3 + C4 + C5 E =~ E1 + E2 + E3 + E4 + E5 N =~ N1 + N2 + N3 + N4 + N5 + O4 #### O =~ O1 + O2 + O3 + O4 + O5 ' fit.bfi.cat4 = cfa(bfi.mod.cat4,data.ord, std.lv=T,estimator="wlsmv") #note, orthogonal=T gone summary(fit.bfi.cat4,fit.measures=T,standardized=T) ``` CFI = 0.837 Not big improvements. At this point, I would most likely resign myself to accepting that there will be no "good" or "adequate" fitting model. This is where substantive knowledge comes into play. It is generally well accepted that the five-factor model generally does not fit well, unless using exploratory structural equation modelling. You have to use Mplus for this. For fun, lets try a couple more complex models: Bifactor ```{r} bifactor <- ' Pers =~ A1 + A2 + A3 + A4 + A5 + C1 + C2 + C3 + C4 + C5 + E1 + E2 + E3 + E4 + E5 + N1 + N2 + N3 + N4 + N5 + O1 + O2 + O3 + O4 + O5 A =~ A1 + A2 + A3 + A4 + A5 C =~ C1 + C2 + C3 + C4 + C5 E =~ E1 + E2 + E3 + E4 + E5 N =~ N1 + N2 + N3 + N4 + N5 O =~ O1 + O2 + O3 + O4 + O5 ' fit.bifactor = cfa(bifactor,data.ord,orthogonal=T, std.lv=T) summary(fit.bifactor,fit.measures=T,standardized=T) windows() semPaths(fit.bifactor) ``` Doesn't fit that much better. How about a higher order model ```{r} higher <- ' A =~ A1 + A2 + A3 + A4 + A5 C =~ C1 + C2 + C3 + C4 + C5 E =~ E1 + E2 + E3 + E4 + E5 N =~ N1 + N2 + N3 + N4 + N5 O =~ O1 + O2 + O3 + O4 + O5 Pers =~ A + C + E + N + O ' fit.higher = cfa(higher,data.ord, std.lv=T) summary(fit.higher,fit.measures=T,standardized=T) windows() semPaths(fit.higher) ``` Not that much better How to estimate reliability from a factor model ```{r} ?semTools::reliability ?semTools::reliabilityL2 # second order model # McDonald's version of omega is omega3 semTools::reliability(fit.bfi.cat2) # reliability of higher order factors reliabilityL2(fit.higher,"Pers") # from psych, omega based on EFA -- no factor structure prespecified omega(data,nfactors=1) ``` How to plot likelihood vs df For the examples in this lab, plotting this is not appropriate, as the models tested are not similar. It is generally best to use this when testing small changes across models. ```{r,eval=FALSE} # extracting each model's chi-square and df quartz() chisq <- c(fitMeasures(fit.bfi.1fac, "chisq"), fitMeasures(fit.higher, "chisq"), fitMeasures(fit.bfi.cat3, "chisq")) df <- c(fitMeasures(fit.bfi.1fac, "df"), fitMeasures(fit.higher, "df"), fitMeasures(fit.bfi.cat3, "df")) # setting margins for plot par(mar = c(5, 5, 4, 2)) # scatter plot of chi-square as a function of df plot(chisq ~ 0 + df, xlim = c(230,290), ylim = c(4800, 11000), xlab = expression("Degrees of Freedom " (italic(df))), ylab = expression ("Chi-square " (chi^2)), family = "Helvetica", pch = 0:3) # adding penalty line abline(lm(chisq ~ 0 + df), lty = "dotted") # adding in legend legend(235, 11000, c("5 Factor", "Higher Order", "1 Factor"), pch = 0:3) ``` ```{r} library(random.polychor.pa) require(psych) data(bfi) raw.data.1<-as.matrix(bfi) raw.data.1 <- (raw.data.1[1:100,1:25]) for(i in 1:nrow(raw.data.1)) { if(raw.data.1[i,1]==2) raw.data.1[i,1]<-1} test.2<-random.polychor.pa(nrep=3, data.matrix=raw.data.1, q.eigen=.99) ```<file_sep>/Lab8/catPoly_invariance.R # invariance for polytomous items # works for a one factor model # more factors, follow steps on this site: # http://www.myweb.ttu.edu/spornpra/catInvariance.html library(lavaan) library(psych) A <- bfi[,1:5] for(i in 1:5) A[,i] <- ordered(A[,i]) A$gender <- factor(bfi[,26],labels = c("male","female")) configural5 <- " f1 =~ c(1, 1)*A1 + A2 + A3 + A4 + A5 A1 | c(t11, t11)*t1 + c(t12, t12)*t2 + t3 + t4 + t5 A2 | c(t21, t21)*t1 + t2 + t3 + t4 + t5 A3 | c(t31, t31)*t1 + t2 + t3 + t4 + t5 A4 | c(t41, t41)*t1 + t2 + t3 + t4 + t5 A5 | c(t51, t51)*t1 + t2 + t3 + t4 + t5 f1 ~~ NA*f1 f1 ~ c(0, NA)*1 A1 ~~ c(1, NA)*A1 A2 ~~ c(1, NA)*A2 A3 ~~ c(1, NA)*A3 A4 ~~ c(1, NA)*A4 A5 ~~ c(1, NA)*A5 " outConfigural5 <- cfa(configural5, data = A, group = "gender", parameterization="theta", estimator="wlsmv") summary(outConfigural5,fit=T) weak5 <- " f1 =~ c(1, 1)*A1 + c(f21, f21)*A2 + c(f31, f31)*A3 + c(f41, f41)*A4 + c(f51, f51)*A5 A1 | c(t11, t11)*t1 + c(t12, t12)*t2 + t3 + t4 + t5 A2 | c(t21, t21)*t1 + t2 + t3 + t4 + t5 A3 | c(t31, t31)*t1 + t2 + t3 + t4 + t5 A4 | c(t41, t41)*t1 + t2 + t3 + t4 + t5 A5 | c(t51, t51)*t1 + t2 + t3 + t4 + t5 f1 ~~ NA*f1 f1 ~ c(0, NA)*1 A1 ~~ c(1, NA)*A1 A2 ~~ c(1, NA)*A2 A3 ~~ c(1, NA)*A3 A4 ~~ c(1, NA)*A4 A5 ~~ c(1, NA)*A5 " outWeak5 <- cfa(weak5, data = A, group = "gender", parameterization="theta", estimator="wlsmv") summary(outWeak5,fit=T) anova(outConfigural5,outWeak5) strong5 <- " f1 =~ c(1, 1)*A1 + c(f21, f21)*A2 + c(f31, f31)*A3 + c(f41, f41)*A4 + c(f51, f51)*A5 A1 | c(t11, t11)*t1 + c(t12, t12)*t2 + c(t13, t13)*t3 + c(t14, t14)*t4 + c(t15, t15)*t5 A2 | c(t21, t21)*t1 + c(t22, t22)*t2 + c(t23, t23)*t3 + c(t24, t24)*t4 + c(t25, t25)*t5 A3 | c(t31, t31)*t1 + c(t32, t32)*t2 + c(t33, t33)*t3 + c(t34, t34)*t4 + c(t35, t35)*t5 A4 | c(t41, t41)*t1 + c(t42, t42)*t2 + c(t43, t43)*t3 + c(t44, t44)*t4 + c(t45, t45)*t5 A5 | c(t51, t51)*t1 + c(t52, t52)*t2 + c(t53, t53)*t3 + c(t54, t54)*t4 + c(t55, t55)*t5 f1 ~~ NA*f1 f1 ~ c(0, NA)*1 A1 ~~ c(1, NA)*A1 A2 ~~ c(1, NA)*A2 A3 ~~ c(1, NA)*A3 A4 ~~ c(1, NA)*A4 A5 ~~ c(1, NA)*A5 " outStrong5 <- cfa(strong5, data = A, group = "gender", parameterization="theta", estimator="wlsmv") summary(outStrong5,fit=T) anova(outConfigural5,outWeak5,outStrong5) strict5 <- " f1 =~ c(1, 1)*A1 + c(f21, f21)*A2 + c(f31, f31)*A3 + c(f41, f41)*A4 + c(f51, f51)*A5 A1 | c(t11, t11)*t1 + c(t12, t12)*t2 + c(t13, t13)*t3 + c(t14, t14)*t4 + c(t15, t15)*t5 A2 | c(t21, t21)*t1 + c(t22, t22)*t2 + c(t23, t23)*t3 + c(t24, t24)*t4 + c(t25, t25)*t5 A3 | c(t31, t31)*t1 + c(t32, t32)*t2 + c(t33, t33)*t3 + c(t34, t34)*t4 + c(t35, t35)*t5 A4 | c(t41, t41)*t1 + c(t42, t42)*t2 + c(t43, t43)*t3 + c(t44, t44)*t4 + c(t45, t45)*t5 A5 | c(t51, t51)*t1 + c(t52, t52)*t2 + c(t53, t53)*t3 + c(t54, t54)*t4 + c(t55, t55)*t5 f1 ~~ NA*f1 f1 ~ c(0, NA)*1 A1 ~~ c(1, 1)*A1 A2 ~~ c(1, 1)*A2 A3 ~~ c(1, 1)*A3 A4 ~~ c(1, 1)*A4 A5 ~~ c(1, 1)*A5 " outStrict5 <- cfa(strict5, data = A, group = "gender", parameterization="theta", estimator="wlsmv") summary(outStrict5,fit=T) summary(outConfigural5, fit = TRUE) summary(outWeak5, fit = TRUE) summary(outStrong5, fit = TRUE) summary(outStrict5, fit = TRUE) anova(outConfigural5, outWeak5) anova(outWeak5, outStrong5) anova(outStrong5, outStrict5) <file_sep>/Miscellaneous/ReverseScore.R #### from <NAME> -- 9/4/2014 ### ReverseScore=function(x, Min=sapply(x, min, na.rm=T), Max=sapply(x, max, na.rm=T), Subset=NULL){ #Leave Min and Max null. If you did Min=sapply(x, min), Max=sapply(x, max) then you would get error (potentially) before x is converted. x=as.data.frame(x) if(is.null(Subset)==F)x=subset(x, , select=Subset) rev.mat=matrix(,ncol=ncol(x), nrow=nrow(x)) if(length(Min) == 1 && ncol(x) >1)Min = rep(Min, ncol(x))#as long as it's on same line, don't need curly brackets. Only need brackets if going multiple lines. #Note 2: for T/F arguments, double ampersand (&&). Generally, always double. if(length(Max) == 1 && ncol(x) >1)Max = rep(Max, ncol(x)) else if(length(Min) != ncol(x) || length(Max) != ncol(x))stop("Min or Max must be length ncol(x), idiot!") ##OR is TWO pipes (||) for(i in 1:ncol(x)){ if(Min[i]>Max[i])stop("Max must be greater than min!") } for(i in 1:ncol(x)){ if(Min[i]>0){ rev.mat[,i]=(Max[i]+1)-x[,i] }else if(Min[i] == 0){ rev.mat[,i]=Max[i]-x[,i] }else if(Min[i] <0){ rev.mat[,i] = -1*x[,i] } } if(!is.null(colnames(x))) colnames(rev.mat)= paste(colnames(x), "Rev", sep=".") #change this part output=rev.mat output } <file_sep>/README.md Psychometrics_Labs ================== Fall 2014 PSYC 520 Fundamentals of Psychological Measurement TA: <NAME> (<EMAIL>) Every lab R script and HW doc posted in this repository will be concurrently posted on the blackboard page for this site. Additional resources, such as useful links or additional scripts for more advanced techniques, will be posted here but not on blackboard.
5fa1973189cd211cd1920997c5d7ece6243fd499
[ "RMarkdown", "Markdown", "R" ]
16
RMarkdown
Rjacobucci/Psychometrics_Labs
3594328c725ca0ab64b15cd1371caf1a50c998a9
92768208a020aebc564af1c402cbe22b428b51cd
refs/heads/master
<repo_name>jonkyops/ahk<file_sep>/Lib/Kerillian/dualsword.ahk #SingleInstance, Force SendMode Input SetWorkingDir, %A_ScriptDir% If (Career = "KerilliandualSword") { Elite := "KerilliandualSwordArmoredEliteMonster" ArmoredElite := "KerilliandualSwordArmoredEliteMonster" Monster := "KerilliandualSwordArmoredEliteMonster" ArmoredMonster := "KerilliandualSwordArmoredEliteMonster" HeavyDelay := 350 } KerilliandualSwordArmoredEliteMonster() { HeavyAttack(HeavyDelay) Sleep 500 BlockCancel() Sleep 200 ; Sleep 300 ; BlockCancel() Return } <file_sep>/Lib/actions.ahk #SingleInstance, Force SendMode Input SetWorkingDir, %A_ScriptDir% LightAttack(Delay:=50) { SetMouseDelay, Delay Click Return } AttackUp() { Click, Up Return } AttackDown() { Click, Down Return } SpecialAttack(Delay:=50) { Send {h down}{h up} Return } BlockCancel() { Click, Right Down Sleep 50 Click, Right up Return } BlockDown() { Click, Right Down Return } BlockUp() { Click, Right Up Return } HeavyAttack(Delay:=450) { Click, Down Sleep Delay Click, Up Return } ChainBashAttack(Delay) { BlockDown() AttackDown() Sleep Delay BlockUp() AttackUp() Sleep Delay } ChainLightHeavy(LightDelay, HeavyDelay) { LightAttack() BlockDown() Sleep Delay BlockUp() AttackUp() Sleep Delay }<file_sep>/Lib/lib.ahk #SingleInstance, Force SendMode Input SetWorkingDir, %A_ScriptDir% #Include %A_ScriptDir%\Lib\actions.ahk #Include %A_ScriptDir%\Lib\generic.ahk #Include %A_ScriptDir%\Lib\Saltzpyre\rapier.ahk #Include %A_ScriptDir%\Lib\Kruber\spearshield.ahk #Include %A_ScriptDir%\Lib\Bardin\hammershield.ahk #Include %A_ScriptDir%\Lib\Kerillian\2hsword.ahk #Include %A_ScriptDir%\Lib\Kerillian\dualsword.ahk varExist(ByRef v) { ; Requires 1.0.46+ return &v = &n ? 0 : v = "" ? 2 : 1 }<file_sep>/Lib/generic.ahk #SingleInstance, Force SendMode Input SetWorkingDir, %A_ScriptDir% GenericSpam() { global LightDelay LightAttack(LightDelay) Sleep 50 } GenericSpecial() { global SpecialDelay SpecialAttack(SpecialDelay) Sleep 100 Return } GenericHeavy() { global HeavyDelay HeavyAttack(HeavyDelay) Sleep 100 Return }<file_sep>/Lib/Kruber/spearshield.ahk #SingleInstance, Force SendMode Input SetWorkingDir, %A_ScriptDir% If (Career = "KruberSpearShield") { Horde := "KruberSpearShieldHorde" Elite := "KruberSpearShieldEliteMonster" ArmoredElite := "KruberSpearShieldEliteMonster" Monster := "KruberSpearShieldEliteMonster" ArmoredMonster := "KruberSpearShieldEliteMonster" Special := "KruberSpearShieldSpecial" } ; Kruber KruberSpearShieldHorde() { LightAttack(LightDelay) LightAttack(LightDelay) BlockCancel() Return } KruberSpearShieldSpecial() { BlockUp() While GetKeyState("XButton1","P") { SpecialAttack(SpecialDelay) } BlockDown() Return } KruberSpearShieldEliteMonster() { BlockUp() LightAttack(LightDelay) BlockDown() HeavyAttack(HeavyDelay) HeavyAttack(HeavyDelay) Return }<file_sep>/vt2.ahk #SingleInstance, Force #InstallKeybdHook SendMode Input #IfWinActive Vermintide 2 ahk_exe vermintide2.exe ; Bardin ; Kerillian ; Kruber ; Saltzpyre ; Sienna ; params ; global Hero := "Kerillian" ; global Weapon := "2hSword" global Hero := "Bardin" global Weapon := "HammerShield" global Career := Hero . Weapon ; Defaults global Horde := "GenericSpam" global Elite := "GenericHeavy" global ArmoredElite := "GenericHeavy" global Monster := "GenericSpam" global ArmoredMonster := "GenericHeavy" global Special := "GenericSpecial" global LightDelay := 25 global SpecialDelay := 50 global HeavyDelay := 450 global BlockDelay := 50 #include %A_ScriptDir%\Lib\lib.ahk oSpVoice := ComObjCreate("SAPI.SpVoice") StartVoiceLine := "Using " . Hero . " " . Weapon oSpVoice.Speak(StartVoiceLine) ^r::Reload ; Ctrl+Alt+R ^XButton1:: ^!XButton1:: !XButton1:: !+XButton1:: +XButton1:: +^XButton1:: XButton1:: While GetKeyState("XButton1","P") { shiftHeld := GetKeyState("LShift", "P") ctrlHeld := GetKeyState("LControl", "P") altHeld := GetKeyState("LAlt", "P") if (altHeld && ctrlHeld) %ArmoredMonster%() else if (shiftHeld && altHeld) %Monster%() else if (shiftHeld) %ArmoredElite%() else if (altHeld) %Elite%() else if (ctrlHeld) %Special%() else %Horde%() } Return <file_sep>/Lib/Bardin/hammershield.ahk #SingleInstance, Force SendMode Input SetWorkingDir, %A_ScriptDir% if (Career = "Bardin") { Horde := "BardinHammerShieldHorde" Elite := "BardinHammerShieldEliteMonster" ArmoredElite := "BardinHammerShieldEliteMonster" Monster := "BardinHammerShieldEliteMonster" ArmoredMonster := "BardinHammerShieldEliteMonster" } BardinHammerShieldEliteMonster() { ChainBashAttack(HeavyDelay) } BardinHammerShieldHorde() { LightAttack(LightDelay) Sleep 50 While GetKeyState("XButton1","P") { LightAttack(LightDelay) Sleep 50 HeavyAttack(HeavyDelay) Sleep 100 } Return }<file_sep>/Lib/Saltzpyre/rapier.ahk #SingleInstance, Force SendMode Input SetWorkingDir, %A_ScriptDir% If (Career = "SaltzpyreRapier") { Elite := "SaltzpyreRapierElite" ArmoredElite := "SaltzpyreRapierArmoredEliteMonster" Monster := "SaltzpyreRapierArmoredEliteMonster" ArmoredMonster := "SaltzpyreRapierArmoredEliteMonster" } SaltzpyreRapierElite() { HeavyAttack(550) Sleep 200 SpecialAttack(SpecialDelay) Sleep 600 Return } SaltzpyreRapierArmoredEliteMonster() { HeavyAttack(700) Return } ; Elite := "SaltzpyreRapierElite" ; ArmoredElite := "SaltzpyreRapierArmoredEliteMonster" ; Monster := "SaltzpyreRapierArmoredEliteMonster" ; ArmoredMonster := "SaltzpyreRapierArmoredEliteMonster" ; VoiceLine := "<NAME>"
feda65b3b084caecb03a899ca2ebd21de8a71d8a
[ "AutoHotkey" ]
8
AutoHotkey
jonkyops/ahk
b52c2d731ba4176a7760c994e65ee3aba29715bb
aeaf132a3b42c848fdec218a28e88b56341dbbff
refs/heads/master
<repo_name>vikas1055/vikas-openresty<file_sep>/README.md # vikas-openresty This is a puppet module to install openresty on Linux(RHEL-6).
dbb2edebd5b6dd0138a40e7a7cea1fcb7f4e07b9
[ "Markdown" ]
1
Markdown
vikas1055/vikas-openresty
f877248b581bbed966506da711230db3a3ada04c
fc53a341187f50bfab6fb4039f99714681f35502
refs/heads/master
<file_sep>// yarn add multer was used to install multer that is used to upload files import multer from 'multer'; import crypto from 'crypto'; // usada para gerar números aleatóreos import { extname, resolve } from 'path'; export default { storage: multer.diskStorage({ destination: resolve(__dirname, '..', '..', 'tmp', 'uploads'), // os uploads ficarão salvos na pasta tmp filename: (req, file, cb) => { // file contém todos os dados sobre o arquivo, nome, tamanho, etc // cb é a função de callback que deve ser chamada no final // cada arquivo de upload terá nome único crypto.randomBytes(16, (err, res) => { if (err) return cb(err); // caso ocorrar erro, retorna erro // ex: jndjlsfksf445j.png return cb(null, res.toString('hex') + extname(file.originalname)); // concatena o nome único aleatório com a extensão original }); }, }), }; <file_sep><strong>Olá, {{ host }}</strong> <p>The following user registered in your meetup:</p> <p> <strong>User: </strong> {{ user }} <br /> <strong>Email: </strong> {{ email }} <br /> <small> You may message this user if you need it. </small> </p> <file_sep>import { Op } from 'sequelize'; import Subscription from '../models/Subscription'; import Meetup from '../models/Meetup'; import User from '../models/User'; import File from '../models/File'; import Queue from '../../lib/Queue'; import SubscriptionMail from '../jobs/SubscriptionMail'; class SubscriptionController { async index(req, res) { const subscriptions = await Subscription.findAll({ where: { user_id: req.userId, }, attributes: ['id'], include: [ { model: Meetup, where: { date: { [Op.gt]: new Date(), // greater than (gt), somente datas que ainda não passaram }, }, required: true, include: [ { model: User, as: 'user', attributes: ['name', 'email'], }, { model: File, as: 'banner', attributes: ['id', 'url', 'path'], }, ], }, ], order: [[Meetup, 'date']], }); return res.json(subscriptions); } async store(req, res) { const meetup = await Meetup.findByPk(req.params.meetup_id); if (meetup.user_id === req.userId) { return res.status(400).json({ error: 'You cannot subscribe in this meetup because you are the host', }); } if (meetup.past) { return res .status(400) .json({ error: 'You cannot subscribe in past meetups' }); } const user = await User.findByPk(req.userId); const host = await User.findByPk(meetup.user_id); // check if the user already registered in a meetup with the same date and time const checkDate = await Subscription.findOne({ where: { user_id: req.userId, }, include: [ { model: Meetup, required: true, where: { date: meetup.date, }, }, ], }); if (checkDate) { return res .status(400) .json({ error: "Can't subscribe to two meetups at the same time" }); } const subscription = await Subscription.create({ user_id: req.userId, meetup_id: meetup.id, }); await Queue.add(SubscriptionMail.key, { user, host, }); return res.json({ subscription }); } async delete(req, res) { const subscription = await Subscription.findOne({ where: { id: req.params.id }, }); if (subscription.user_id !== req.userId) { return res .status(400) .json({ error: 'Not authorized to delete this subscription.' }); } await subscription.destroy(); return res.json({ Message: 'Subscription deleted.' }); } } export default new SubscriptionController(); <file_sep>// faz conexão com o banco de dados e importa os models import Sequelize from 'sequelize'; // importa os models import User from '../app/models/User'; import File from '../app/models/File'; import Meetup from '../app/models/Meetup'; import Subscription from '../app/models/Subscription'; import databaseConfig from '../config/database'; const models = [User, File, Meetup, Subscription]; // array com os models class Database { constructor() { this.init(); } init() { this.connection = new Sequelize(databaseConfig); models .map(model => model.init(this.connection)) .map(model => model.associate && model.associate(this.connection.models)); // somente os models que possuem o método associate } } export default new Database(); <file_sep>export default { secret: '<KEY>', expiresIn: '7d', };
bf167d00e00de789845810f1535a4fb03b1cc366
[ "Handlebars", "JavaScript" ]
5
Handlebars
djanlm/backEnd_MeetApp
0d2cc43709fbfbcc7e58f11a8676c8585914cf91
ebb1b0f761e9a9313862e9fdbc48a7409c3b8c97
refs/heads/master
<repo_name>lioialessandro/LyricsGramBot<file_sep>/src/Genius.ts import fetch from "node-fetch"; import cheerio from "cheerio"; export const Search = async ( query: string, token: string ): Promise<Array<SongSearch>> => { try { const response = await fetch(`https://api.genius.com/search?q=${query}`, { headers: { Authorization: `Bearer ${token}` }, }); const json = await response.json(); return json.response.hits.map(({ result }: any) => ({ id: result.id, title: result.title, url: result.url, artist: result.primary_artist.name, artist_url: result.primary_artist.url, song_art: result.song_art_thumbnail_url, })); } catch (error) { return error; } }; export const Scrape = async (id: string, token: string): Promise<Song> => { try { const response = await fetch(`https://api.genius.com/songs/${id}`, { headers: { Authorization: `Bearer ${token}` }, }); const json = await response.json(); const { song } = json.response; const media: Array<Media> = song.media.map((tempMedia: any) => ({ provider: ( tempMedia.provider[0].toUpperCase() + tempMedia.provider.slice(1) ).replace("_", " "), url: tempMedia.url, })); const body_response = await fetch(song.url); const html = await body_response.text(); const $ = cheerio.load(html); const lyrics = $("div.lyrics").text().trim(); return { media, lyrics, id: Number(id), title: song.title, url: song.url, artist: song.primary_artist.name, artist_url: song.primary_artist.url, }; } catch (error) { return error; } }; export interface SongSearch { id: number; title: string; url: string; artist: string; artist_url: string; song_art: string; } export interface Media { provider: string; url: string; } export interface Song { id: number; title: string; url: string; artist: string; artist_url: string; media: Array<Media>; lyrics: string; } <file_sep>/src/Chatbase.ts import fetch from "node-fetch"; export const UserMetrics = async ( type: string, command: string, user_id: number ) => { const { CHATBASE_TOKEN, NODE_ENV } = process.env; if (NODE_ENV !== "production" || !CHATBASE_TOKEN) { console.info(`${type} ${command} by ${user_id}`); return; } try { const headers = { "Cache-Control": "no-cache", "Content-Type": "application/json", }; const data = { api_key: CHATBASE_TOKEN, type: "user", platform: "telegram", message: command, intent: type, version: "1.0", user_id, }; await fetch("https://chatbase-area120.appspot.com/api/message", { headers, method: "POST", body: JSON.stringify(data), }); } catch (error) { console.error(error); } }; <file_sep>/src/lib/telegraf-ratelimit.d.ts declare module "telegraf-ratelimit"; <file_sep>/.env.example TELEGRAM_TOKEN= URL= GENIUS_TOKEN= CHATBASE_TOKEN= PAYPAL= <file_sep>/README.md # LyricsGramBot [LyricsGramBot](https://t.me/LyricsGramBot) - a bot to get the lyrics of any song If you want to help me, you can donate [here](https://paypal.me/lioialessandro) Created by <NAME> ## Getting Started - Create a `.env` file based on `.env.example` ## Running - NodeJS: ``` npm run build npm run start ``` - Docker: ``` docker build -t lyricsgrambot . docker run -it --env-file .env --rm lyricsgrambot ``` ## Push Change `$1` to the version ``` docker build -t lyricsgrambot . docker tag lyricsgrambot docker.pkg.github.com/lioialessandro/lyricsgrambot/lyricsgrambot:$1 docker push docker.pkg.github.com/lioialessandro/lyricsgrambot/lyricsgrambot:$1 ``` <file_sep>/Dockerfile # Build FROM node:lts-alpine AS build WORKDIR /usr/src/app COPY package*.json ./ RUN npm install COPY . . RUN npm run build # Run FROM node:lts-alpine WORKDIR /usr/src/app COPY package*.json ./ RUN npm ci --only=production COPY --from=build /usr/src/app/dist ./dist ENV NODE_ENV=production CMD ["node", "dist/index.js"] <file_sep>/src/index.ts import Telegraf, { Markup } from "telegraf"; import rateLimit from "telegraf-ratelimit"; import { InlineQueryResultArticle } from "telegraf/typings/telegram-types"; import { TelegrafContext } from "telegraf/typings/context"; import { CallbackButton, UrlButton } from "telegraf/typings/markup"; import express from "express"; import { UserMetrics } from "./Chatbase"; import { Search, Scrape } from "./Genius"; const { NODE_ENV } = process.env; if (NODE_ENV !== "production") require("dotenv").config(); const { TELEGRAM_TOKEN, PORT, URL, PAYPAL, GENIUS_TOKEN } = process.env; if (!TELEGRAM_TOKEN || !PAYPAL || !GENIUS_TOKEN) throw new Error("Environment variables can't be null"); const Bot = new Telegraf(TELEGRAM_TOKEN); const App = express(); Bot.use( rateLimit({ window: 1000, limit: 20, onLimitExceeded: (ctx: TelegrafContext) => ctx.reply("Rate limit exceeded. Please try again later."), }) ); const replyWithError = (ctx: TelegrafContext, error: any) => ctx.replyWithMarkdown( `There was an error: ${error}\nPlease forward this message to: @lioialessandro` ); const replyWithErrorCbQuery = (ctx: TelegrafContext, error: any) => { ctx.editMessageText( `There was an error: ${error}.\nPlease forward this to @lioialessandro.` ); return ctx.answerCbQuery("There was an error..."); }; Bot.start((ctx) => { const { message } = ctx; if (!message) return replyWithError(ctx, "`message` is not defined."); UserMetrics("Command", "Start", message.chat.id); return ctx.replyWithMarkdown( `Hello!\nWelcome to @LyricsGramBot\nYou can use this bot to fetch lyrics from any songs.\nIf you need help, just write /help\nIf you want, you can vote the bot here: [StoreBot](https://telegram.me/storebot?start=LyricsGramBot)\n\nIf you want to support me, you can donate [here](${PAYPAL})\n\nIT: Il bot è stato aggiunto alla lista di [Canali e Bot](https://t.me/canaliebot)\n\n\nSource code available [here](https://github.com/lioialessandro/LyricsGramBot)\n\n\nCreated by @lioialessandro`, { disable_web_page_preview: true, } ); }); Bot.command("help", async (ctx) => { const { message } = ctx; if (!message) return replyWithError(ctx, "`message` is not defined."); UserMetrics("Command", "Help", message.chat.id); return ctx .replyWithVideo( { source: "./Videos/TextMessage.mp4" }, { caption: "You can use this method in this chat" } ) .then((_) => ctx .replyWithVideo( { source: "./Videos/InlineQuery.mp4" }, { caption: "You can use this method in every chat" } ) .then((_) => ctx.reply( "If you still have any problems, please contact me personally: @lioialessandro." ) ) ); }); Bot.on("message", async (ctx) => { const { message } = ctx; if (!message) return replyWithError(ctx, "`message` is not defined."); const { text } = message; if (!text) return replyWithError(ctx, "`text` is not defined."); if (text.includes("genius.com")) return; UserMetrics("Message", "Text", message.chat.id); try { const songs = await Search(text, GENIUS_TOKEN); if (songs.length === 0) return ctx.reply( "Your search did not match any songs. Try a different song." ); const buttons: Array<Array<CallbackButton>> = songs.map((song) => [ { text: `${song.title} by ${song.artist}`, callback_data: song.id.toString(), hide: false, }, ]); return ctx.reply("Click the name of the song that you want the lyrics of", { reply_markup: Markup.inlineKeyboard(buttons), }); } catch (error) { return replyWithError(ctx, error); } }); Bot.on("inline_query", async (ctx) => { const { inlineQuery } = ctx; if (!inlineQuery) return replyWithError(ctx, "`inlineQuery` is not defined."); UserMetrics("Query", "Inline", inlineQuery.from.id); const { query } = inlineQuery; if (!query) return ctx.answerInlineQuery([]); try { const songs = await Search(query, GENIUS_TOKEN); const results: Array<InlineQueryResultArticle> = songs.map((song) => ({ id: song.id.toString(), type: "article", title: song.title, description: song.artist, thumb_url: song.song_art, thumb_width: 300, thumb_height: 300, input_message_content: { message_text: `[${song.title}](${song.url}) by [${song.artist}](${song.artist_url})\n\n_From genius.com_`, parse_mode: "Markdown", disable_web_page_preview: true, }, reply_markup: Markup.inlineKeyboard([ [ { text: "Click here to get the lyrics", callback_data: song.id.toString(), hide: false, }, ], ]), })); return ctx.answerInlineQuery(results); } catch (error) { return replyWithError(ctx, error); } }); const sendLyrics = async ( ctx: TelegrafContext, lyrics: Array<string>, index: number, id: number, buttons: Array<Array<UrlButton>> ) => { if (!lyrics[index]) return ctx.telegram.sendMessage(id, "Lyrics sent", { reply_markup: Markup.inlineKeyboard(buttons), }); return setTimeout(async () => { await ctx.telegram.sendMessage(id, `${index + 1}\n${lyrics[index]}`); sendLyrics(ctx, lyrics, ++index, id, buttons); }, 300); }; Bot.on("callback_query", async (ctx) => { const { callbackQuery } = ctx; if (!callbackQuery) return replyWithErrorCbQuery(ctx, "`callbackQuery` is not defined."); UserMetrics("Query", "Callback", callbackQuery.from.id); const { data } = callbackQuery; if (!data) return replyWithErrorCbQuery(ctx, "`data` is not defined."); try { const song = await Scrape(data, GENIUS_TOKEN); const buttons: Array<Array<UrlButton>> = [ [{ text: song.title, url: song.url }], [{ text: song.artist, url: song.artist_url }], ]; song.media.forEach((media) => buttons.push([{ text: media.provider, url: media.url }]) ); buttons.push([{ text: "Support me!", url: PAYPAL }]); if (song.lyrics.length < 4096) { ctx.editMessageText(song.lyrics, { reply_markup: Markup.inlineKeyboard(buttons), }); return ctx.answerCbQuery("Sending the lyrics..."); } const regex = song.lyrics.match(/[\s\S]{1,4080}/g); if (!regex) return replyWithErrorCbQuery(ctx, "`splitting` didn't work."); ctx.editMessageText("There lyrics was sent here: @LyricsGramBot."); sendLyrics(ctx, regex, 0, callbackQuery.from.id, buttons); return ctx.answerCbQuery("Sending the lyrics..."); } catch (error) { ctx.editMessageText( `There was an error: ${error.message}.\nPlease forward this to @lioialessandro.` ); return ctx.answerCbQuery("There was an error..."); } }); if (NODE_ENV !== "production") { console.info("Development environment"); Bot.startPolling(); } else { console.info("Production environment"); Bot.telegram.setWebhook(`${URL}/bot${TELEGRAM_TOKEN}`); App.use(Bot.webhookCallback(`/bot${TELEGRAM_TOKEN}`)); } App.get("/", (req, res) => { res.send("LyricsGramBot webpage."); }); App.listen(PORT, () => console.info(`Server running on ${PORT}`));
f08fb5c8fff89d9e6643a77b05c25d9fe5b6f807
[ "Markdown", "TypeScript", "Shell", "Dockerfile" ]
7
Markdown
lioialessandro/LyricsGramBot
242d536f141705c84e872b437974cc77b7b32152
0ff5cca8aecb092501c83620d1bd3dbc3735e232
refs/heads/main
<repo_name>szopian/page-animation<file_sep>/README.md # page-animation ## Animated with <a href="https://cdnjs.com/libraries/gsap">Gasp Libraries cdnjs</a></br></br>Hero section about London.. <img src="images/img1.png" />
f02fec07373efb6810dbdf0a2958fc88b773272d
[ "Markdown" ]
1
Markdown
szopian/page-animation
bebd2351430dda186c778527f79f1fc6cbce1640
fe435e4a9d1f70887313a957a57306e9e0b49d9e
refs/heads/main
<repo_name>jiyixia-tony/jiyixia-tony<file_sep>/README.md ### Hi there 👋 <!-- **jiyixia-tony/jiyixia-tony** is a ✨ _special_ ✨ repository because its `README.md` (this file) appears on your GitHub profile. --> Here are some ideas to get you started: - 🌱 MBA graduate with a focus on business analytics at the University of New Brunswick - 👯 Technical Skills: Excel, R, SQL, Tableau certified desktop specialist https://public.tableau.com/profile/tony.xia7580#!/ , alteryx - 📫 How to reach me: https://www.linkedin.com/in/jiyi-xia-900918/
a8680d4408042aeed482acb46e81fda2a2dbeb8b
[ "Markdown" ]
1
Markdown
jiyixia-tony/jiyixia-tony
184549564e1130d06e51117be82057ef49100c86
999e7a9909b66ba967b8fcb3dd1c262503272c27
refs/heads/master
<repo_name>imarkiew/CCM<file_sep>/main.py import pandas as pd from pandas import Series from matplotlib import pyplot as plt from statsmodels.graphics.tsaplots import plot_acf from statsmodels.tsa.seasonal import seasonal_decompose from statsmodels.tsa.stattools import ccf from statsmodels.tsa.arima_model import ARMA from scipy.signal import spectrogram import seaborn as sns import numpy as np from pandas.plotting import register_matplotlib_converters register_matplotlib_converters() # path to data PATH_TO_DATA = './data/PJMW_hourly.csv' # path to folder where we want to save the plots PATH_TO_PLOTS = './plots' # type of separator in data file SEPARATOR = ',' # header location HEADER = 0 # divide into a training and test set SPLIT_DATE = '2013-06-01' # the maximum order of the model MAX_P = 18 # number of phase to plot NR_OF_PHASES_TO_PLOT = 6 # sampling frequency (1/month) FS = 1.0 # other model parameters PARAMS = {'method': 'mle', 'solver': 'lbfgs', 'maxiter': 500, 'trend': 'c', 'transparams': True, 'disp': False} # function returns a list of dictionaries def get_k_roots_with_largest_radiuses(coeffs, k, fs): roots = np.roots(coeffs) are_original_radiuses_in_unit_circle = [] radiuses = [] phases = [] for original_root in roots: original_radius = np.abs(original_root) if original_radius > 1: are_original_radiuses_in_unit_circle.append(False) inversed_root = complex_inverse(original_root) radiuses.append(np.abs(inversed_root)) phases.append(convert_phase_to_freq(np.angle(inversed_root, deg=True), fs)) else: are_original_radiuses_in_unit_circle.append(True) radiuses.append(original_radius) phases.append(convert_phase_to_freq(np.angle(original_root, deg=True), fs)) roots = sorted([{'was_original_radius_in_unit_circle': was_original_radius_in_unit_circle, 'radius': radius, 'phase': phase} for was_original_radius_in_unit_circle, radius, phase in zip(are_original_radiuses_in_unit_circle, radiuses, phases)], key=lambda key: key['radius'], reverse=True) return roots[0:k] def complex_inverse(z): return 1.0 / np.conjugate(z) def convert_phase_to_freq(phase, fs): def convert_to_freq(phase, fs): return fs*phase / 360.0 if phase >= 180: return convert_to_freq(phase - 360.0, fs) else: return convert_to_freq(phase, fs) # reading the data series = Series.from_csv(PATH_TO_DATA, sep=SEPARATOR, header=HEADER) # changing raw index to DatetimeIndex series.index = pd.to_datetime(series.index, infer_datetime_format='True') # sorting series.sort_index(inplace=True) # group values by month in each year and then calculate mean series_monthly = series.groupby(pd.Grouper(freq='M')).mean() # plot a whole time series f = plt.figure() plt.plot(series_monthly) plt.gcf().set_size_inches(10, plt.gcf().get_size_inches()[1]) plt.title('Średnie zużycie energii elektrycznej w skali miesięcznej') plt.xlabel('Data') plt.ylabel('Zużycie [MW]') plt.grid() f.savefig(PATH_TO_PLOTS + '/timeSeries.pdf', bbox_inches='tight') plt.show() # plot autocorrelation f = plot_acf(series_monthly, unbiased=True, alpha=0.05) plt.title('Funkcja autokorelacja') plt.xlabel('Opóźnienie') plt.ylabel('Autokorelacja') plt.gcf().set_size_inches(10, plt.gcf().get_size_inches()[1]) f.savefig(PATH_TO_PLOTS + '/autocorrelation.pdf', bbox_inches='tight') plt.show() # plot spectrogram f = plt.figure() freq, t, Sxx = spectrogram(series_monthly.values, fs=FS, nfft=256, window=('tukey', 0.25), detrend='constant', nperseg=60, noverlap=30, scaling='density') plt.pcolormesh(t, freq, Sxx) plt.xlabel('Czas [mies]') plt.ylabel('Częstotliwość [1/mies]') plt.colorbar().set_label('Widmowa gęstość mocy [V^2/1/mies]') f.savefig(PATH_TO_PLOTS + '/spectrogram.pdf', bbox_inches='tight') plt.show() # signal decomposition = trend + seasonal + error decomposition = seasonal_decompose(series_monthly, model="additive") f = decomposition.plot() f.savefig(PATH_TO_PLOTS + '/decomposition.pdf', bbox_inches='tight') plt.show() # split train-test train = series_monthly.loc[series_monthly.index < SPLIT_DATE] test = series_monthly.loc[series_monthly.index >= SPLIT_DATE] print('Train size = {} %'.format(100*len(train)/len(series_monthly))) print('Test size = {} %'.format(100*len(test)/len(series_monthly))) f = plt.figure() plt.plot(train) plt.plot(test) plt.gcf().set_size_inches(10, plt.gcf().get_size_inches()[1]) plt.title('Podział na zbiór trenujący i testowy') plt.xlabel('Data') plt.ylabel('Zużycie [MW]') plt.legend(['train', 'test']) plt.grid() f.savefig(PATH_TO_PLOTS + '/timeSeriesTrainTest.pdf', bbox_inches='tight') plt.show() # check different lags aics = {} for p in range(1, MAX_P + 1): print('Model lag = {} from {}'.format(p, MAX_P)) model = ARMA(train, order=(p, 0)).fit(**PARAMS) aics[p] = model.aic # plot aic(lag) f = plt.figure() plt.plot(aics.keys(), aics.values(), 'bo') plt.title('AIC(Lag)') plt.xlabel('Lag') plt.ylabel('AIC') plt.xticks(range(1, len(aics) + 1)) plt.grid() f.savefig(PATH_TO_PLOTS + '/aicLag.pdf', bbox_inches='tight') plt.show() # find the lag with the smallest aic lag = min(aics, key=aics.get) print('Optimal lag = {}'.format(lag)) # train-test procedure using moving window series_len = len(series_monthly) train_len = len(train) test_len = len(test) y_pred = pd.Series([]) coefficients = [] confidence_intervals = [[], []] for i in range(test_len): print('Train - test iteration: i = {} from {}'.format(i + 1, test_len)) dynamic_train = series_monthly.iloc[i:i + train_len] model = ARMA(dynamic_train, order=(lag, 0)).fit(**PARAMS) results = model.forecast(1) confidence_intervals[0].extend([results[2][0][0]]) confidence_intervals[1].extend([results[2][0][1]]) y_pred = y_pred.append(pd.Series(results[0], index=[test.index[i]]), verify_integrity=True) coefficients.append(model.params) # plot test-predicted data f = plt.figure() plt.plot(test, color='blue') plt.plot(y_pred, color='orange') plt.fill_between(test.index, confidence_intervals[0], confidence_intervals[1], color='lightgrey') plt.gcf().set_size_inches(10, plt.gcf().get_size_inches()[1]) plt.title('Model AR') plt.xlabel('Data') plt.ylabel('Zużycie [MW]') plt.legend(['test', 'AR({})'.format(lag)]) plt.grid() f.savefig(PATH_TO_PLOTS + '/timeSeriesPredTest.pdf', bbox_inches='tight') plt.show() # plot crosscorrelation f = plt.figure() plt.plot(ccf(test, y_pred, unbiased=True)) plt.title('Korelacja wzajemna szeregów test i pred') plt.xlabel('Opóźnienie') plt.ylabel('Korelacja') plt.grid() f.savefig(PATH_TO_PLOTS + '/crosscorrelation.pdf', bbox_inches='tight') plt.show() # plot residues res = y_pred - test f = plt.figure() plt.plot(res) plt.gcf().set_size_inches(10, plt.gcf().get_size_inches()[1]) plt.title('Residua dla modelu AR({})'.format(lag)) plt.xlabel('Data') plt.ylabel('Residu*a') plt.grid() f.savefig(PATH_TO_PLOTS + '/residuum.pdf', bbox_inches='tight') plt.show() # plot box-plot for residues f = plt.figure() ax = sns.boxplot(y=res, palette='Set2') plt.title('Wykres pudełkowy residuów dla {} próbek zbioru testowego'.format(test_len)) plt.ylabel('Moc [MW]') f.savefig('./plots/boxplot.pdf', bbox_inches='tight') plt.show() # get coefficients without const coefficients_list = [[1] + [*d.values][1:] for d in coefficients] # get info about roots roots = [get_k_roots_with_largest_radiuses(r, NR_OF_PHASES_TO_PLOT, FS) for r in coefficients_list] # plot the phases (from -180 to 180 degrees) of polynomial roots over time (roots are sorted by non-increasing radius) f = plt.figure(figsize=(12, 12)) for i in range(NR_OF_PHASES_TO_PLOT): were_original_radiuses_in_unit_circle = [pred[i]['was_original_radius_in_unit_circle'] for pred in roots] phases = [pred[i]['phase'] for pred in roots] plt.subplot(NR_OF_PHASES_TO_PLOT, 1, i + 1) for j, (phase, was_original_radius_in_unit_circle) in enumerate(zip(phases, were_original_radiuses_in_unit_circle)): if was_original_radius_in_unit_circle: colour = 'bo' else: colour = 'ro' plt.plot(j + 1, phase, colour) plt.grid() plt.xticks(range(1, len(roots) + 1, 2)) plt.xlabel('Numer próbki') f.savefig('./plots/phases.pdf', bbox_inches='tight') plt.show()
9d6288c84597f6ec9f1ff39532fdae2399669854
[ "Python" ]
1
Python
imarkiew/CCM
06696a30be7da3d2f6a93b5e950efb228743124c
05f8580148d2eda4a2940f2305cf1e8da63b3c27
refs/heads/master
<file_sep>Issues Encountered - Couldn't figure out a way to better manipulate the flex-box for the grid - Couldn't combine the two text-utilities to make the text both centered and uppercase Resources - Capture screenshot through devtools https://umaar.com/dev-tips/151-screenshot-capture/
f756275b6707a8f4a6de9de6980cef7325659b2b
[ "Text" ]
1
Text
ruiz8098023/m2-hw2-ruiz-josselyn
9f3f808a60d7702625b2128a7c9fce0ed8302281
9c968ce5a72041ff74b15958ccf54849b64494f0
refs/heads/master
<file_sep>package by.java; public class Prose extends Composition { public Prose() { super(); } public Prose(String author, String name, String type, int pages) { super(author, name, type, pages); } @Override public String toString() { return "Это проза, ее автор " + getAuthor() + ", название " + getName() + ", это жанр " + getType() + ", страниц " + getPages(); } @Override public boolean equals(Object obj) { return super.equals(obj); } } <file_sep>package by.java; public enum Disсipline { PHYSICS, BIOLOGY, MATH, ASTRONOMY } <file_sep>package by.java; public class Factory { public static Composition createComposition(CompositionType compositionType, String author, String name, String type, int pages){ switch (compositionType) { case PROSE: return new Prose(author,name,type,pages); case POETRY: return new Poetry(author, name, type, pages); } return null; } public static Composition createScience(Disсipline disсipline, String author, String name, String type, int pages) { return new Science(author, name, type, pages, disсipline); } } <file_sep>package by.java; public class Science extends Composition { private Disсipline disсipline; public Science(){ } public Science(String author, String name, String type, int pages, Disсipline disсipline){ super(author, name, type, pages); this.disсipline = disсipline; } public void setDisсipline(Disсipline d) { this.disсipline = d; } public Disсipline getDisсipline() { return this.disсipline; } @Override public String toString() { return "Science{" + "disсipline=" + disсipline + "} " + super.toString(); } } <file_sep>package by.java; public class Main { public static void main(String[] args) { Composition creation1 = new Prose("AAa", "AAA", "ccc", 2); System.out.println(creation1); Composition creation2 = new Poetry("Лермонтов", "Утес", "Лирика", 1); System.out.println(creation2); System.out.println(creation1.equals(creation2)); Composition creation3 = Factory.createComposition(CompositionType.PROSE, "fghjhj", "ghghjhjhj", "bjhbjj", 1 ); System.out.println(creation3); Composition creation4 = Factory.createScience(Disсipline.ASTRONOMY, "ghgug", "ghghgjh", "hhhj", 6); System.out.println(creation4); } } <file_sep>package by.java; public class Poetry extends Composition{ public Poetry() { } public Poetry(String author, String name, String type, int pages) { super(author, name, type, pages); } @Override public String toString() { return "Это поэзия, ее автор " + getAuthor() + ", название " + getName() + ", это жанр " + getType() + ", страниц " + getPages(); } @Override public boolean equals(Object o) { return super.equals(o); } }
fec2faacf9a23b40798e992d1c5eac94e57adb8f
[ "Java" ]
6
Java
JulyaSamoilenko/lab4
655dae21390e1e4727d3f4e55f202ec46bb827aa
b00662bf0e29cb5802c08563db83b6fc3a04be3a
refs/heads/master
<file_sep># Patrones001Intro Ejemplos de patrones de diseño c# Solución donde tengo varios proyectos referentes a implementaciones sobre patrones de diseño
ad97b97e970e867c57b3656e9e59b630eaa3e2f4
[ "Markdown" ]
1
Markdown
vegasuay/Patrones001Intro
24036b2e1b9cb0b07ebb524e4ac75cca4744bbb1
5846a6e64edbe22e7448fcd39fef7d07bb0e3506
refs/heads/master
<file_sep><?php // Pour avoir acceder a mes fonctions require_once "../modeles/modele.php"; if (!empty($_POST["submit"])) { // Si les donnée en post on etait poster alors... $errors = array(); // VERIFICATION DU CHAMP UNSERNAME if (empty($_POST['username'])) { // Si le champ username n'as pas etait remplis alors $errors['username'] = "Saisissez votre pseudo"; } elseif (!preg_match('/^[a-zA-Z0-100_-]+$/', $_POST['username'])) { // Sinon si le champ username ne contient pas de ... $errors['username'] = "Votre pseudo peut contenir que des lettres allant de a-z des -,_ et des chiffre allant de 0 a 100"; } else { // Sinon ... $req = getbdd()->prepare("SELECT id FROM users WHERE username = ?"); $req->execute([$_POST['username']]); $user = $req->fetch(); if($user) { $errors["username"] = "Ce pseudo est deja pris"; } } // FIN DE LA VERIFICATION DU CHAMP UNSERNAME // VERIFICATION DU CHAMP EMAIL if (empty($_POST['email'])) { // Si le champ email n'as pas etait remplis alors $errors['email'] = "Saisissez une adresse email"; } elseif (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) { // Sinon si pour verifier le format de l'email jutilise filter_var en premier params je lui passe la variable et en seconde parametre je lui passe un entier qui determine le filtre a utiliser (FILTER...) ça retourne true si c'est bon et false sinon (en plus du type email) $errors['email'] = "Votre e-mail n'est pas valide"; } else { // Sinon $req = getbdd()->prepare("SELECT id FROM users WHERE email = ?"); $req->execute([$_POST['email']]); $user = $req->fetch(); if($user) { $errors["email"] = "Cette e-mail est déjà utilisé"; } } if (empty($_POST['password'])) { $errors['password'] = "<PASSWORD>"; } elseif ($_POST['password'] != $_POST['password_confirm']) { $errors2['password'] = "Vos mots de passe ne correspondent pas. Veuillez réessayer."; } if (empty($errors) && empty($errors2)) { // Si mon tableau d'erreurs et mon champ err 2 et vide cad si il n'y a pas d'err dans les diff champ alors ... $req = getbdd()->prepare("INSERT INTO users SET username = ?, password = ?, email = ?"); $password = password_hash($_POST['password'], PASSWORD_BCRYPT); $req->execute([$_POST['username'], $password, $_POST['email']]); } // debug($errors); } <file_sep>Index membre <a href="/membre/inscription_connexion.php">Inscription Connexion</a><file_sep><?php function getBdd() { // INITIALISATION DE LA CONNEXION A LA BDD return new PDO('mysql:host=localhost;dbname=projet_Final', 'root', '', [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]); } function debug($variable){ echo '<pre>' . print_r ($variable, true) . '</pre>'; } // A chaque nouveau modeles l'inclure ici // afin de pouvoir accéder a nos nouveau diff modele depuis n'importe qu'elle fichier. require_once "../modeles/articles.php"; require_once "../modeles/categories.php"; <file_sep><?php require_once "../traitements/inscription_connexion.php"; ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Loging Animation</title> <link rel="stylesheet" href="css/inscription.connexion.css" /> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" integrity="<KEY>" crossorigin="anonymous" /> </head> <body> <section> <div class="container"> <div class="user singinBx"> <div class="imgBx"> <img src="https://images.unsplash.com/photo-1519389950473-47ba0277781c?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1650&q=80" alt="" /> </div> <div class="formBx"> <form> <div class="center"><h2>Connexion</h2></div> <div class="inputBx"> <span>Pseudo</span> <input type="text" name="" placeholder="Username" /> </div> <div class="inputBx"> <span>Mot de passe</span> <input type="password" name="" placeholder="<PASSWORD>" /> </div> <div class="remember"> <label><input type="checkbox" name="" /> Remember me</label> </div> <div class="inputBx"> <input type="submit" value="Connexion" name="" /> </div> <p class="signup"> Vous n'êtes pas encore membre ? <a href="#" onclick="toggleForm();"> Rejoignez-nous.</a> </p> <h3>Login with social media</h3> <ul class="sci"> <li> <a href="#" ><i class="fa fa-facebook" aria-hidden="true"></i ></a> </li> <li> <a href=" #" ><i class="fa fa-twitter" aria-hidden="true"></i ></a> </li> <li> <a href="#" ><i class="fa fa-instagram" aria-hidden="true"></i ></a> </li> </ul> </form> </div> </div> <div class="user singupBx"> <div class="formBx"> <form method="POST"> <div class="center"><h2>Inscription</h2></div> <div class="inputBx"> <span>Pseudo</span> <input type="text" name="username" placeholder="Username" /> <?php if (!empty($errors)) {echo $errors["username"];} ?> </div> <div class="inputBx"> <span>Adresse e-mail</span> <input type="email" name="email" placeholder="Email Address" /> <?php if (!empty($errors)) {echo $errors["email"];} ?> </div> <div class="inputBx"> <span>Mot de passe</span> <input type="<PASSWORD>" name="password" placeholder="<PASSWORD>" /> <?php if (!empty($errors)) {echo $errors["password"];} ?> </div> <div class="inputBx"> <span>Confimez votre mot de passe</span> <input type="<PASSWORD>" name="password_confirm" placeholder="<PASSWORD>" /> <?php if (!empty($errors2)) {echo $errors2["password"];} ?> </div> <div class="inputBx"> <input type="submit" value="Rejoignez-nous" name="submit" /> </div> <p class="signup"> Deja membre ? <a href="#" onclick="toggleForm();"> Se Connecter.</a> </p> <h3>Login with social media</h3> <ul class="sci"> <li> <a href="#" ><i class="fa fa-facebook" aria-hidden="true"></i ></a> </li> <li> <a href=" #" ><i class="fa fa-twitter" aria-hidden="true"></i ></a> </li> <li> <a href="#" ><i class="fa fa-instagram" aria-hidden="true"></i ></a> </li> </ul> </form> </div> <div class="imgBx"> <img src="https://images.unsplash.com/photo-1519389950473-47ba0277781c?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1650&q=80" alt="" /> </div> </div> </div> </section> <script type="text/javascript"> function toggleForm() { var container = document.querySelector(".container"); container.classList.toggle("active"); } </script> </body> </html> <file_sep><?php if (!empty($_SESSION["idrole"]) && $_SESSION["idrole"] == 2) { header("location:admin/index.php"); } else { header("location:membre/index.php"); } // Explications mvc: // - Dossier modeles : Gérer les interractions SQL // - Dossier controleur : Gérer les traitement des données // - Dossier vue : Gérer l'affichage des pages // Le controleur traiteras les données // Le modeles feras les interactions SQL // La vue afficheras les pages // en fonctions des données // qui serons recup depuis le modeles // et traiter dans le controler // Nous pour l'instant: // modeles/-> Gérer nos interractions SQL (via des fonctions) // traitements/-> Gérer l'enregistrement de nos formulaires // /vues-> Gérer l'affichage des pages <file_sep><?php //===== Fonction créer un article function creerArticle($idarticle, $titre, $contenu, $categorie) { // $requete = getBdd()->prepare("INSERT INTO ..."); } //===== Fonction recuperer un article function recupererArticles() { // $requete = getBdd()->prepare("SELECT ..."); } //===== Fonction modifier un article function modifierArticle($idarticle, $titre, $contenu, $categorie) { // $requete = getBdd()->prepare("UPDATE ..."); }
d766223127726fcd261075e96bd9f07f99da8f28
[ "Hack", "PHP" ]
6
Hack
IL-Iliesse/Final_Projet
d5b2a81182493ac0ee133f79128a256f7bd031d2
222ce6fc0a2ba32461d1f98340ee7b3311c56b87
refs/heads/main
<repo_name>Zainulariffin/anak2uKindergarden<file_sep>/homeStack.js import {createStackNavigator} from 'react-navigation-stack'; import {createAppContainer} from 'react-navigation'; import Home from './components/Home'; import State from './components/State'; import Detail from './components/Detail'; const screens = { Home: { screen: Home }, State: { screen: State }, Detail: { screen: Detail } } const HomeStack = createStackNavigator(screens); export default createAppContainer(HomeStack);
738fcb65a89624cbdc691f410a7413a7484113bc
[ "JavaScript" ]
1
JavaScript
Zainulariffin/anak2uKindergarden
6e0d5f1cdec3302ff810df2ac23ada70ad0fe480
be876a534d866a21feeba9192c4bb11e083c3660
refs/heads/master
<file_sep>local normalizer = torch.class('normalizer') local paths = require 'paths' function normalizer:__init(cmd) self.cmd = cmd end function normalizer:normalize(lines) local input if type(lines) == "table" then input = table.concat(lines, "\n") else input = lines end local name = paths.tmpname () local f = io.open(name, "w") f:write(input) f:close() local fout = io.popen("cat " .. name .. " | " .. self.cmd) local out = {} while true do local line = fout:read("*l") if not line then break end table.insert(out, line) end fout:close() os.remove(name) if type(lines) == "table" then if #out ~= #lines then return nil end return out else if #out ~= 1 then return nil end return out[1] end end return normalizer <file_sep>local function norm(t) if type(t) == "table" then local v = {} local vrep = {} for _, tokt in ipairs(t) do local vt, vtrep vt, vtrep = norm(tokt) table.insert(v, vt) table.insert(vrep, vtrep) end return v, vrep end if t:sub(1, string.len('⦅')) == '⦅' then local p = t:find('⦆') assert(p, 'invalid placeholder tag: '..t) local tcontent = t:sub(string.len('⦅')+1, p-1) local fields = onmt.utils.String.split(tcontent, ':') return '⦅'..fields[1]..t:sub(p), fields[2] or fields[1] end return t end return { norm = norm }
413f9797deba65eb4eccc0b99fac5c00a91965bf
[ "Lua" ]
2
Lua
gwli/OpenNMT
c36543f1098e8f4586654d5da38d438c8e96d4bb
a83f53d6df05a646825ccb69be2b5246ec804388
refs/heads/master
<file_sep># Unity-SpaceShooter unity spaceshooter learn
96f4a6e2894be30fc90ef035a04d2c142f281580
[ "Markdown" ]
1
Markdown
wei780901/Unity-SpaceShooter
2b641232f1c9a4ef9dc1d698b953582ffdb93cdb
9b76507e702d84ed7af40a838d2c3712401608f6
refs/heads/master
<repo_name>prabhat47/distributed-downloading<file_sep>/server/config/main.js module.exports.dev = { db : 'mongodb://127.0.0.1:27017/pintrest', apiURI : 'http://127.0.0.1:3000/api' }; module.exports.production = { };<file_sep>/README.md # Distributed Downloading ## How to run ## Client ( Yet to be written ) ## Server Download node LTS from https://nodejs.org/en/ ### Setup Dependencies Run `npm install` inside /server to setup dependencies. ### Run Locally Run `npm start` inside /server to fire up the server, default port is 3000. call `localhost:3000/api` for api interactions.
feff02b9549a10cfbe2ebb8278ab4222b3d4a416
[ "Markdown", "JavaScript" ]
2
Markdown
prabhat47/distributed-downloading
2c4c52a8405cde36f07860de47364a5eddb88278
28bde4673a1263ec63a27ad6f9873f49574cb82d
refs/heads/main
<file_sep># TransparentWater This is a lightweight Water module for three.js. example: water = new TransparentWater( waterGeometry, { textureWidth: 512, textureHeight: 512, waterNormals: new THREE.TextureLoader().load( './textures/water/waternormals.jpg', function ( texture ) { texture.wrapS = texture.wrapT = THREE.RepeatWrapping; } ), eye: new THREE.Vector3( 0, -1, 0 ), intensity: 1.0, alpha: 0.7, sunDirection: new THREE.Vector3( 10, 400, 10 ), side: THREE.DoubleSide, distortionScale: 3.7, sunColor: 0x131818, baseColor: 0x232f2f, waterColor: 0x85888d, fog: scene.fog !== undefined } ); scene.add( water ); water.update({sunColor:0x131818,baseColor:0x232f2f,waterColor:0x85888d,alpha:0.85}); water.update({time:(1.0 / 90.0),intensity:(_intensity/2+0.5)});
2b35dfa575bc6a7aa2349dbf425e0c55e0534de0
[ "Markdown" ]
1
Markdown
skytrebol/TransparentWater
4b9bfd94755c3fcdae92e73a1dd4a48fb2c564ed
c0555dc48c7f11b98878aaab2e5ee97df5ef4fa8
refs/heads/main
<file_sep>// SQS import com.amazon.sqs.javamessaging._ import com.amazonaws.ClientConfiguration import com.amazonaws.retry.PredefinedBackoffStrategies.ExponentialBackoffStrategy import com.amazonaws.retry.RetryPolicy import com.amazonaws.services.sqs._ import scala.concurrent.duration.DurationInt // Gatling JMS DSL import io.gatling.jms.Predef._ import io.gatling.core.Predef._ class MessageDsl extends Simulation { val sqsClient = AmazonSQSAsyncClientBuilder.defaultClient() val jmsProtocol = jms.connectionFactory(new SQSConnectionFactory(new ProviderConfiguration(), sqsClient)) val scn = scenario("SQS Load Test") .exec(jms("SendMessage").send .queue("204892-Message-Simulation-POC") .textMessage("SomeText")) setUp( scn.inject( heavisideUsers(100000).during(60.seconds) ) ).protocols(jmsProtocol) after { sqsClient.shutdown(); } }
5f9aefc3e064ad550e598506fe4fbf79364ab6cf
[ "Scala" ]
1
Scala
Panyaprach/gatling-lab
b0616a8d9ebc03c12fd376d3429ccd0af2391307
2808d7e734911a6247cb821c658e796e4ec64ad7
refs/heads/master
<file_sep>FROM bitnami/minideb:stretch MAINTAINER <<EMAIL>> RUN echo "deb http://repo.pritunl.com/stable/apt stretch main" > /etc/apt/sources.list.d/pritunl.list && \ install_packages gnupg dirmngr && \ apt-key adv --keyserver hkp://keyserver.ubuntu.com --recv 7568D9BB55FF9E5287D586017AE645C0CF8E292A && \ apt-get update && \ install_packages pritunl iptables COPY start-pritunl /bin/start-pritunl EXPOSE 80 EXPOSE 443 EXPOSE 1194 EXPOSE 1194/udp ENTRYPOINT ["/bin/start-pritunl"] # CMD ["/usr/bin/tail", "-f","/var/log/pritunl.log"]
50bd8f24a34b695473644de5904331cbdce065b0
[ "Dockerfile" ]
1
Dockerfile
jalberto/docker-pritunl-1
8633184381aad1b825c64ffe575e1b4bbd5a846f
2be4fae2e6bc0cda58e5f7ffe1afaa1b29de0ab6
refs/heads/master
<file_sep>form(ng-submit="handler.check()") p textarea.form-control.input-lg(ng-model="model.text") button.btn.btn-default.btn-lg.btn-block(type="submit", ng-hide="model.showSolution") Verificar div(ng-show="model.showSolution") h4 Solução: div.bg-warning {{handler.exercise.solution}} <file_sep>form(ng-submit="handler.check()") .form .form-group.form-group-lg( ng-repeat="item in handler.exercise.solution", class="{{model.showSolution ? handler.isIncluded(model.values[$index], handler.exercise.solution) ? 'has-success' : 'has-error' : ''}}" ) .controls p.lead input.form-control( ng-model="model.values[$index]", ng-disabled="model.showSolution", ) button.btn.btn-default.btn-lg.btn-block(type="submit", ng-hide="model.showSolution") Verificar p.lead ul li( ng-repeat="item in handler.exercise.solution", ng-show="model.showSolution && !handler.isIncluded(item, model.values)" class="bg-danger" ) {{item}} <file_sep>.list-group-item { word-wrap: break-word; white-space: normal; } pl-complete img { max-width: 100%; } body { margin-bottom: 1em; }<file_sep> form(ng-submit="handler.check()") .form-group.form-group-lg.has-feedback( ng-repeat="phrase in handler.exercise.data" class="{{model.showSolution ? handler.isCorrect(model.text[$index], phrase.solution) ? 'has-success' : 'has-error' : ''}}" ) label {{phrase.phrase}} input.form-control.input-lg( ng-disabled="model.showSolution", ng-model="model.text[$index]" ) span.glyphicon.glyphicon-ok.form-control-feedback.input-lg( ng-show="model.showSolution && handler.isCorrect(model.text[$index], phrase.solution)" ) span.glyphicon.glyphicon-remove.form-control-feedback.input-lg( ng-show="model.showSolution && !handler.isCorrect(model.text[$index], phrase.solution)" ) div(ng-show="model.showSolution && !handler.isCorrect(model.text[$index], phrase.solution)") div.bg-success {{phrase.solution}} button.btn.btn-default.btn-lg.btn-block(type="submit", ng-hide="model.showSolution") Verificar <file_sep><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.2.3.RELEASE</version> </parent> <groupId>hu.mapro</groupId> <artifactId>patraolocal</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <properties> <guava.version>18.0</guava.version> <cargo.plugin.version>1.4.13</cargo.plugin.version> </properties> <dependencyManagement> <dependencies> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>${guava.version}</version> </dependency> </dependencies> </dependencyManagement> <build> <finalName>patraolocal</finalName> <pluginManagement> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-release-plugin</artifactId> <version>2.3</version> <configuration> <providerImplementations> <git>jgit</git> </providerImplementations> </configuration> <dependencies> <dependency> <groupId>org.apache.maven.scm</groupId> <artifactId>maven-scm-provider-jgit</artifactId> <version>1.9.2</version> </dependency> </dependencies> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-site-plugin</artifactId> <version>3.4</version> <dependencies> <dependency> <groupId>org.apache.maven.wagon</groupId> <artifactId>wagon-ssh</artifactId> <version>2.5</version> </dependency> </dependencies> <configuration> <skip>true</skip> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-javadoc-plugin</artifactId> <version>2.10.1</version> <configuration> <skip>true</skip> </configuration> </plugin> </plugins> </pluginManagement> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-source-plugin</artifactId> <executions> <execution> <goals> <goal>jar</goal> </goals> </execution> </executions> </plugin> <plugin> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-maven-plugin</artifactId> <version>${jetty.version}</version> <configuration> <daemon>false</daemon> </configuration> </plugin> <plugin> <groupId>org.codehaus.cargo</groupId> <artifactId>cargo-maven2-plugin</artifactId> <version>${cargo.plugin.version}</version> <configuration> <container> <containerId>jetty9x</containerId> <type>remote</type> </container> <configuration> <type>runtime</type> </configuration> <deployer> <type>remote</type> </deployer> </configuration> </plugin> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <executions> <execution> <goals> <goal>repackage</goal> </goals> </execution> </executions> </plugin> </plugins> </build> <distributionManagement> <repository> <id>cwatch-repo</id> <name>cwatch-repo-releases</name> <url>https://cwatch.org/repo/libs-release-local</url> </repository> <snapshotRepository> <id>cwatch-repo</id> <name>cwatch-repo-snapshots</name> <url>https://cwatch.org/repo/libs-snapshot-local</url> </snapshotRepository> </distributionManagement> <repositories> <repository> <id>cwatch-repo-releases</id> <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>false</enabled> </snapshots> <url>http://cwatch.org/repo/ext-release-local</url> </repository> <repository> <id>cwatch-repo-snapshots</id> <releases> <enabled>false</enabled> </releases> <snapshots> <enabled>true</enabled> </snapshots> <url>http://cwatch.org/repo/libs-snapshot-local</url> </repository> </repositories> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-logging</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-log4j</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <scope>provided</scope> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jetty</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> </dependency> <dependency> <groupId>hu.mapro.mfw</groupId> <artifactId>mfw-web</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency> <dependency> <groupId>org.yaml</groupId> <artifactId>snakeyaml</artifactId> </dependency> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> </dependency> </dependencies> </project><file_sep>p.lead {{handler.exercise.text}} .row.text-center(ng-if="handler.exercise.figure!==undefined") img( style="max-width: 100%;", ng-src="data/images/{{handler.exercise.figure}}", ) p.lead ng-include(src="handler.getTemplate()") button.btn.btn-lg.btn-block( ng-repeat="group in $storage.groups track by $index" ng-click="nextExercise($index)" ng-class="{'btn-info': $storage.groups[0][handler.exercise.checksum] == $index}" ) {{$index | alphabet | uppercase}}<file_sep> form(ng-submit="handler.check()") .form-group.form-group-lg.has-feedback( class="{{model.showSolution ? handler.isCorrect(model.text, handler.exercise.solution) ? 'has-success' : 'has-error' : ''}}" ) input.form-control.input-lg( ng-disabled="model.showSolution", ng-model="model.text" ) span.glyphicon.glyphicon-ok.form-control-feedback( ng-show="model.showSolution && handler.isCorrect(model.text, handler.exercise.solution)" ) span.glyphicon.glyphicon-remove.form-control-feedback( ng-show="model.showSolution && !handler.isCorrect(model.text, handler.exercise.solution)" ) button.btn.btn-default.btn-lg.btn-block(type="submit", ng-hide="model.showSolution") Verificar div(ng-show="model.showSolution && !handler.isCorrect(model.text, handler.exercise.solution)") h4 Solução: div.bg-success {{handler.exercise.solution}} <file_sep>package hu.mapro.patraolocal; import hu.mapro.mfw.web.MfwWebConfiguration; import hu.mapro.mfw.web.MfwWebConfigurer; import hu.mapro.mfw.web.MfwWebSettings; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; @Configuration @Import({MfwWebConfiguration.class}) public class PatraoLocalWebConfiguration { @Bean MfwWebConfigurer mfwWebConfigurer() { return new MfwWebConfigurer() { @Override public void configure(MfwWebSettings settings) { settings.setApplicationTitle("Patrao Local"); } }; } } <file_sep>button.btn.btn-default.btn-lg.btn-block(ng-click="handler.check()", ng-hide="model.showSolution") Verificar div(ng-show="model.showSolution") h4 Solução: div.bg-warning .row.text-center img( style="max-width: 100%;", ng-src="data/images/{{handler.exercise.solution}}", ) <file_sep>ul.list-group li.list-group-item.btn( ng-repeat="index in model.indexes", ng-click="handler.select($index)", ng-class="{'btn-default': handler.showDefault($index), 'btn-success': handler.showCorrect($index), 'btn-danger': handler.showIncorrect($index)}", ng-disabled="model.showSolution" ) div.lead(style="margin-bottom: 0px") b {{$index | alphabet | uppercase}}: pl-choice-item(data="model.elements[index]") <file_sep>X support figure: attribute X replace <img> tags with figure: X implement choice_multi X implement phrases X implment draw treat text: as html implement manobras29 as draw make it work on safari, check firefox implement learning process<file_sep>b | {{handler.reverse(index) | alphabet | uppercase}}<file_sep>div( ng-controller="MainCtrl" ng-busy="dataPromise" ) nav.navbar.navbar-default .container-fluid .navbar-header .navbar-brand <NAME> .navbar-text span( ng-repeat="group in $storage.groups" ) {{group.groupSize}}&nbsp;/&nbsp; {{exercises.length}} .container div(ui-view) <file_sep>form(ng-submit="handler.check()") p.lead pl-complete(data="handler.exercise.data") button.btn.btn-default.btn-lg.btn-block(type="submit", ng-hide="model.showSolution") Verificar <file_sep>ul.list-group li.list-group-item.btn.btn-default( ng-repeat="index in model.indexes" ng-click="handler.toggle($index)" ng-class="{ 'active': !model.showSolution && model.selection[$index], 'btn-success': model.showSolution && handler.isCorrect($index), 'btn-danger': model.showSolution && model.selection[$index] && !handler.isCorrect($index) }" ng-disabled="model.showSolution" ng-model="model.selection[$index]" ) div.lead(style="margin-bottom: 0px") input.pull-left(type="checkbox", ng-model="model.selection[$index]") {{model.elements[index]}} span.glyphicon.glyphicon-ok.pull-right( ng-if="model.showSolution && model.selection[$index] && handler.isCorrect($index)" ) span.glyphicon.glyphicon-minus.pull-right( ng-if="model.showSolution && model.selection[$index] && !handler.isCorrect($index)" ) span.glyphicon.glyphicon-plus.pull-right( ng-if="model.showSolution && !model.selection[$index] && handler.isCorrect($index)" ) button.btn.btn-default.btn-lg.btn-block( ng-click="handler.check()" ng-hide="model.showSolution" ) Verificar <file_sep>input.input-lg( style="font-family: monospace; text-align:center;", ng-model="value", size="{{value.length+1}}", ng-disabled="model.showSolution", class="{{model.showSolution ? handler.isCorrect(value, solution) ? 'bg-success' : handler.isStrict() ? 'bg-danger' : 'bg-warning' : ''}}" ) span( ng-show="model.showSolution && !handler.isCorrect(value, solution)", class="bg-success" ) {{solution}}
7caa334be709a7acb4f774bfaf6bd717fe0be7bb
[ "Pug", "Java", "Maven POM", "Text", "CSS" ]
16
Pug
maprohu/patraolocal
33fd016770c4b3303d4509e340c51787eb4a21f6
ac76347e1e020c994dec2e5747b6f2dd5a4cc99c
refs/heads/master
<repo_name>sallypanda/tencent-scf<file_sep>/CHANGELOG.md # Changelog All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. ### [3.0.8](https://github.com/serverless-components/tencent-scf/compare/v3.0.7...v3.0.8) (2020-04-23) ### Bug Fixes * tags unset bug ([f684789](https://github.com/serverless-components/tencent-scf/commit/f68478957037866031be65b26d7b2254b8162d4e)) ### [3.0.7](https://github.com/serverless-components/tencent-scf/compare/v3.0.6...v3.0.7) (2020-04-22) ### Bug Fixes * set tags FunctionId not found bug ([bfb1e72](https://github.com/serverless-components/tencent-scf/commit/bfb1e721f5eddd4085de1118dd3ec49dc38237bc)) ### [3.0.6](https://github.com/serverless-components/tencent-scf/compare/v3.0.5...v3.0.6) (2020-04-22) ### Features * add bind layer feature ([4d53786](https://github.com/serverless-components/tencent-scf/commit/4d53786924c65cda2d959e53e4df34b3d1917b4b)) ### [3.0.5](https://github.com/serverless-components/tencent-scf/compare/v3.0.1...v3.0.5) (2020-04-21) ### Bug Fixes * inputs.exclude bug ([f590fc0](https://github.com/serverless-components/tencent-scf/commit/f590fc0e98050d3970c7b4156efe5f10e793a018)) ### [3.0.1](https://github.com/serverless-components/tencent-scf/compare/v3.0.0...v3.0.1) (2020-03-12) ### Bug Fixes * apigw trigger output ([575f30a](https://github.com/serverless-components/tencent-scf/commit/575f30a5cae482984b31efae1158e609e11d38b7)) ### [2.1.4](https://github.com/serverless-components/tencent-scf/compare/v2.1.3...v2.1.4) (2020-03-09) ### Bug Fixes * namespace change or region change code not upload bug ([2b43614](https://github.com/serverless-components/tencent-scf/commit/2b436141be031a1133202dbd25c0cd7292792db2)) * remove unuse npm folder ([5d9c147](https://github.com/serverless-components/tencent-scf/commit/5d9c147b97c17edc1fa7edc60597ee8729cf5826)) ### [2.1.3](https://github.com/serverless-components/tencent-scf/compare/v2.1.1...v2.1.3) (2020-03-04) ### Bug Fixes * function name change need update code cos ([41119a3](https://github.com/serverless-components/tencent-scf/commit/41119a3a65ef92d94f5d69c76d726978151df46f)) * version ([8985349](https://github.com/serverless-components/tencent-scf/commit/8985349b515910937068227fdec87adaacda46d1)) * version ([85830ae](https://github.com/serverless-components/tencent-scf/commit/85830ae366984a968e34c40f8b6840eb385d8899)) ### [2.1.2](https://github.com/serverless-components/tencent-scf/compare/v2.1.1...v2.1.2) (2020-03-04) ### Bug Fixes * function name change need update code cos ([c546ba7](https://github.com/serverless-components/tencent-scf/commit/c546ba7178acc384df7c0ab79997abd7cb6e826f)) ### [2.1.1](https://github.com/serverless-components/tencent-scf/compare/v2.1.0...v2.1.1) (2020-02-27) ### Bug Fixes * apigateway not find ([a6046d2](https://github.com/serverless-components/tencent-scf/commit/a6046d26bb505e41cb8306b6169fdcb3e2a990dd)) ## [2.1.0](https://github.com/serverless-components/tencent-scf/compare/v2.0.0...v2.1.0) (2020-02-27) ### Features * add dir support for include option ([a270443](https://github.com/serverless-components/tencent-scf/commit/a270443ccd58f001036d6c5ea51ae04ec376713b)) * add standard-version ([6706551](https://github.com/serverless-components/tencent-scf/commit/6706551419bd934a89ccaaa48117efdb86572b93)) * add update function basement configuration ([e0be437](https://github.com/serverless-components/tencent-scf/commit/e0be4375cdda050113b115b37eaa2fd559827b4c)) * add upload process bar ([0f9e6f8](https://github.com/serverless-components/tencent-scf/commit/0f9e6f804180fd86e52aa1bb1bf7cb02f7cc36ac)) * Configure namespaces ([fcfb244](https://github.com/serverless-components/tencent-scf/commit/fcfb244a1e5465070f0d6a700b7a21b104262bfc)) * optimize func deploy flow ([9adc0bd](https://github.com/serverless-components/tencent-scf/commit/9adc0bd19edf124cf909ce5b6daede0d1a86110a)) ### Bug Fixes * code no change info ([8bffd6f](https://github.com/serverless-components/tencent-scf/commit/8bffd6f4b44c9da29c97a60fa52168fd353f87bf)) * optimize upload bar, remove unuse deps ([ab09770](https://github.com/serverless-components/tencent-scf/commit/ab09770bdcb6717867043abf1b08fbdf642ba95c)) * relative include folder bug ([33dd665](https://github.com/serverless-components/tencent-scf/commit/33dd665b02445eb2e3b4ae8b309382064ad621c7)) * update updateFunctionConf -> updateBaseConf ([fba0d09](https://github.com/serverless-components/tencent-scf/commit/fba0d09150a68bfceb36df095a52786a89b560b7)) <file_sep>/library/removeFunction.js const tencentcloud = require('tencentcloud-sdk-nodejs') const Abstract = require('./abstract') const models = tencentcloud.scf.v20180416.Models const util = require('util') class RemoveFunction extends Abstract { async remove(funcName, namespace = 'default') { const delFuncRequest = new models.DeleteFunctionRequest() delFuncRequest.FunctionName = funcName delFuncRequest.Namespace = namespace const handler = util.promisify(this.scfClient.DeleteFunction.bind(this.scfClient)) try { await handler(delFuncRequest) } catch (e) { throw e } } } module.exports = RemoveFunction <file_sep>/docs/configure.md # Configure document ## Complete configuration ```yml # serverless.yml myFunction: component: "@serverless/tencent-scf" inputs: name: myFunction1 enableRoleAuth: true # 默认写法,新建特定命名的 cos bucket 并上传 codeUri: ./code # 指定 bucket name 和文件的方式,直接上传 cos 中的文件部署云函数 codeUri: bucket: tinatest # bucket name,当前会默认在bucket name后增加 appid 后缀, e.g. bucketname-appid key: 'code.zip' # bucket key 指定存储桶内的文件 # 指定本地文件到 bucket codeUri: bucket: tinatest # bucket name path: # 可选,指定本地路径 handler: index.main_handler runtime: Nodejs8.9 region: ap-guangzhou description: My Serverless Function memorySize: 128 timeout: 20 layers: - name: layerTest version: 6 # src: ./node_modules # runtimes: # - Nodejs8.9 # - Nodejs10.15 # exclude: # - .bin exclude: - .gitignore - .git/** - node_modules/** - .serverless - .env include: - ./myFunction1.zip environment: variables: TEST: value vpcConfig: subnetId: '' vpcId: '' tags: key1: value1 key2: value2 # tags 的key value events: - timer: name: timer parameters: cronExpression: '*/5 * * * *' enable: true - apigw: name: serverless parameters: serviceId: service-8dsikiq6 protocols: - http serviceName: serverless description: the serverless service environment: release endpoints: - path: /users method: POST - path: /test/{abc}/{cde} apiId: api-id method: GET description: Serverless REST API enableCORS: TRUE responseType: HTML serviceTimeout: 10 param: - name: abc position: PATH required: 'TRUE' type: string defaultValue: abc desc: mytest - name: cde position: PATH required: 'TRUE' type: string defaultValue: abc desc: mytest function: isIntegratedResponse: TRUE functionQualifier: $LATEST usagePlan: usagePlanId: 1111 usagePlanName: slscmp usagePlanDesc: sls create maxRequestNum: 1000 auth: serviceTimeout: 15 secretName: secret secretIds: - <KEY>r7dE6HHaSuchJ - apigw: name: serverless_test parameters: serviceId: service-cyjmc4eg protocols: - http description: the serverless service environment: release endpoints: - path: /users method: POST - cos: name: cli-appid.cos.ap-beijing.myqcloud.com parameters: bucket: cli-appid.cos.ap-beijing.myqcloud.com filter: prefix: filterdir/ suffix: .jpg events: cos:ObjectCreated:* enable: true - cmq: name: cmq_trigger parameters: name: test-topic-queue enable: true - ckafka: name: ckafka_trigger parameters: name: ckafka-2o10hua5 topic: test maxMsgNum: 999 offset: latest enable: true ``` ## Configuration description Main param description | Param | Required/Optional | Default | Description | | --------------------------------------------- | :---------------: | :----------: | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | name | Required | | Name of the new function. The name: must be between 2 and 60 characters long; can contain any letters (both uppercase and lowercase) from a to z and any numbers from 0 through 9; can contain some special characters, including hyphen or dash, and underscore; must begin with a letter and be unique, and must not end with an underscore or a dash. | | codeUri | Required | | Function code path | | enableRoleAuth | Required | | Default `true`, enable role and policies for SCF to get access to related services | | handler | Required | | Name of the handler. A handler is a method that the runtime executes when your function is invoked. A handler name must be formatted as the function name following the file name with a period (.) between these two names, for example, FileName.FunctionName. Both file name and function name: must be between 2 and 60 characters long; can contain any letters (both uppercase and lowercase) from a to z and any numbers from 0 through 9, can contain some special characters, including hyphen or dash, and underscore; must begin and end with a letter. | | runtime | Required | | Runtime environment of the function; supported environment: Python2.7 (default), Python3.6, Nodejs6.10, PHP5, PHP7, Go1 and Java8. | | region | Optional | ap-guangzhou | | | description | Optional | | Description of the function. The description can be up to 1,000 characters long and can contain any letters (both uppercase and lowercase) from a to z, any numbers from 0 through 9, spaces, line breaks, commas and period. Chinese characters are also supported. | | memorySize | Optional | 128M | The size of memory size available to the function during execution. Specify a value between 128 MB (default) and 1,536 MB in 128 MB increments. | | timeout | Optional | 3S | The duration a function allowed to execute. Choose a value between 1 and 300 seconds; The default is 3 seconds. | | exclude | Optional | | exclude file | | include | Optional | | include file, if relative path, should relative to `serverless.yml` | | [environment](#environment-param-description) | Optional | | Function configure | | [vpcConfig](#vpcConfig-param-description) | Optional | | API-Gateway configure | | layers | Optional | | Bind layers for scf, it's a n array of [Layer object](#Layer) | ### environment param description | Param | Description | | --------- | :------------------------- | | variables | Environment variable array | ### vpcConfig param description | Param | Description | | -------- | :--------------- | | subnetId | ID of the VPC | | vpcId | ID of the subnet | - About trigger, you cloud [click here](./events) ### Layer Must setup one of `version` and `src`. | Param | Required/Optional | Type | Default | Description | | ------------ | ----------------- | ------- | ------- | ------------------------------------------------------------- | | name | Required | String | | Layer name | | version | Optional | String | | Layer version | | src | Optional | String | | Layer code folder | | forcePublish | Optional | Boolean | false | Whether layer change or exist, force to publish a new version |
75cdb083531e35370fd3682896c8146dbc605345
[ "Markdown", "JavaScript" ]
3
Markdown
sallypanda/tencent-scf
20aa1d7a031800a7480a63f1c18fe390278af1b3
4d1d2f7b81212b005c90ccebe7d32a654f37c5a3
refs/heads/master
<repo_name>keefu/ChattyApp<file_sep>/chatty_server/server.js // server.js const express = require('express'); const WebSocket = require('ws'); const uuidv4 = require('uuid/v4'); const PORT = 3001; // Create a new express server const server = express() // Make the express server serve static assets (html, javascript, css) from the /public folder. .use(express.static('public')) .listen(PORT, '0.0.0.0', 'localhost', () => console.log(`Listening on ${ PORT }`)); // Create the WebSockets server. const wss = new WebSocket.Server({ server }); let userCount = 0; // Set up a callback that will run when a client connects to the server. wss.on('connection', (ws) => { console.log('Client connected'); userCount++ ; wss.clients.forEach(client => { if (client.readyState === WebSocket.OPEN) { client.send( JSON.stringify({userCount: userCount, type: "incomingUserCount"}) ); } }); ws.on("message", (data) => { const {username, content, type} = JSON.parse(data); let sendToClient; //Check type of users connected. switch(type) { case "postNotification": sendToClient = { id: uuidv4(), content:content, type: "incomingNotification" } break; case "postMessage": sendToClient = { id:uuidv4(), username: username, content: content, type: "incomingMessage" } break; } //Send object for each client connected. wss.clients.forEach(client => { if (client.readyState === WebSocket.OPEN) { client.send(JSON.stringify(sendToClient)); } }); }); // Set up a callback for when a client closes the socket. ws.on('close', () => { console.log('Client disconnected'); userCount--; wss.clients.forEach(client => { client.send( JSON.stringify({userCount: userCount, type: "incomingUserCount"}) ); }); }); }); <file_sep>/README.md React Boilerplate ===================== A minimal and light dev environment for ReactJS. ### Description Single Page App Chat box where all users can connect and send messages. ### Final Project !["Chatty Single Page"](https://raw.githubusercontent.com/keefu/react-simple-boilerplate/master/docs/Screenshot%20from%202019-07-05%2014-23-58.png) !["Multiple Users and Chat Box"](https://raw.githubusercontent.com/keefu/react-simple-boilerplate/master/docs/Screenshot%20from%202019-07-05%2014-26-52.png) ### Dependencies * React * Webpack * [babel-loader](https://github.com/babel/babel-loader) * [webpack-dev-server](https://github.com/webpack/webpack-dev-server) <file_sep>/src/App.jsx import React, {Component} from 'react'; import ChatBar from "./Chatbar.jsx"; import MessageList from "./MessageList.jsx"; import Header from "./Header.jsx"; class App extends Component { constructor(props) { super(props) this.state = { userCount:0, currentUser: {name: "Jimmy"}, messages: [], } // Creating the connection to the Socket Server this.SocketServer = new WebSocket('ws://localhost:3001'); } updateStatus = status => { this.setState({ currentUser: { // spreading currentUser object properties ...this.state.currentUser, // overwriting the online key value online: status, }, }); }; handleOnOpen = event => { console.log('Connection to server established.'); // changing from offline to online this.updateStatus(true); }; addMessage = (event) => { if(event.key === 'Enter') { const newMessage = { username: this.state.currentUser.name, content: event.target.value, type: "postMessage", }; this.SocketServer.send(JSON.stringify(newMessage)); event.target.value = ""; } } // Will send a notification to the socket server sendNotification = msg => { const message = { content: msg, type: 'postNotification', }; this.SocketServer.send(JSON.stringify(message)); }; addUserName = (event) => { const notificationMsg = `${this.state.currentUser.name} has changed their name to ${event.target.value || "Anonymous"}`; //Check if username has change else do nothing if(event.target.value !== this.state.currentUser.name) { this.setState({currentUser: {name: event.target.value || "Anonymous"}}); this.sendNotification(notificationMsg); } } //Catch message from server handleOnMessage = (event) => { const newMessage = JSON.parse(event.data); if(newMessage.type !== "incomingUserCount"){ const newMessages = [...this.state.messages, newMessage] this.setState({messages: newMessages}) } else { this.setState({userCount: newMessage.userCount}) } } componentDidMount() { this.SocketServer.onopen = this.handleOnOpen; this.SocketServer.onmessage = this.handleOnMessage; } render() { return ( <div> <ChatBar currentUser={this.state.currentUser.name} addMessage={this.addMessage} addUserName={this.addUserName}/> <MessageList messages={this.state.messages}/> <Header userCount={this.state.userCount}/> </div> ) } } export default App;
04491ab7d958bb0527eb4eb5c4c64e2f690f8002
[ "Markdown", "JavaScript" ]
3
Markdown
keefu/ChattyApp
4f55026dd84728c1d5a8cd590ce570e23dfe05e7
8db8eff0aec2bf4ed3a1299b7b76cbc978ddf760
refs/heads/master
<repo_name>trokster/pouch-box<file_sep>/lib/ddoc.js module.exports = { _id: '_design/box', views: { receivers: { map: function(doc) { if (typeof doc.receivers === 'object') { for (var receiver in doc.receivers) { emit(receiver, null) } } }.toString(), reduce: '_count' } } }
c1d6ccea0964634a63c673ab7d52499008bf4fa4
[ "JavaScript" ]
1
JavaScript
trokster/pouch-box
e903dc5e09e259532dc8fb9644565194e8cfd0de
f86027ebacdf92d1f83390bd55ad97e3a5145143
refs/heads/master
<repo_name>maximeaubaret/dokku-sinopia-docker<file_sep>/Dockerfile FROM node:4.2.2 MAINTAINER <NAME> <<EMAIL>> RUN \ adduser --disabled-password --gecos "Sinopia NPM mirror" sinopia && \ npm install -g yapm && \ yapm install -g https://github.com/henkosch/sinopia/archive/master.tar.gz && \ mkdir -p /opt/sinopia && \ chown -R sinopia:sinopia /opt/sinopia WORKDIR /opt/sinopia USER sinopia ADD /config.yaml /opt/sinopia/config.yaml ADD /htpasswd /opt/sinopia/htpasswd EXPOSE 4873 CMD ["sinopia"] <file_sep>/README.md # dokku-sinopia-docker [WIP] A simple Sinopia docker image used to create a NPM registry. To create a new User, clone this repository and: > echo "user:(mkpasswd --method=sha-512 password)" >> htpasswd Then, you can re-build the image. # TODO - [ ] Backups
fd0104cd3d8c74ef6b82240536eb44c659cfe308
[ "Markdown", "Dockerfile" ]
2
Markdown
maximeaubaret/dokku-sinopia-docker
aa4e34c03ba4dab488efb141aad854a6f6631d57
ddaa4f2da220e7d6ac83edcff5c5b5408521a9cb
refs/heads/master
<repo_name>Georgi-Panchev/portfolio<file_sep>/readme.md # Portfolio This is my portfolio # Work This is my work
25f3ec27d9a6d98ef61066c9f2e6c70ab4c17edc
[ "Markdown" ]
1
Markdown
Georgi-Panchev/portfolio
2ca709a880e06eba1211db88d0ca149f728b987d
2b5e84333942cb91fc6a7885f3883074eee29ce1
refs/heads/master
<repo_name>luben3485/Data-mining-classification<file_sep>/README.md # Data-mining-classification
9f5dbff65db7630401ecfa2ef284dc14418adae2
[ "Markdown" ]
1
Markdown
luben3485/Data-mining-classification
f2512243a02f415aa9264aded5881a14a2a74ef0
1cf00c59bb2e9952dc543c32a00b123f4eed3315
refs/heads/master
<repo_name>kaustavkarmakar2/Angular-7-sratch-developement<file_sep>/src/app/login/login.component.ts import { Component, OnInit } from '@angular/core'; import { first } from 'rxjs/operators'; import { FormGroup, FormControl, Validators, FormBuilder } from '@angular/forms'; import {FormsModule,ReactiveFormsModule} from '@angular/forms'; import { Router, ActivatedRoute } from '@angular/router'; // import { AlertService, AuthenticationService } from '@/_services'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.css'] }) export class LoginComponent implements OnInit { newTaskForm: FormGroup; constructor(fb: FormBuilder) { this.newTaskForm = fb.group({ name: ["", Validators.required] }); } createNewTask() { console.log(this.newTaskForm.value) } ngOnInit() { } } <file_sep>/src/app/signup/signup.component.ts import { Component, OnInit } from '@angular/core'; import { FormGroup, Validators, FormBuilder } from '@angular/forms'; @Component({ selector: 'app-signup', templateUrl: './signup.component.html', styleUrls: ['./signup.component.css'] }) export class SignupComponent implements OnInit { newTaskForm: FormGroup; constructor(fb: FormBuilder) { this.newTaskForm = fb.group({ name: ["", Validators.required] }); } createNewTask() { console.log(this.newTaskForm.value) } ngOnInit() { } } <file_sep>/src/app/app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { AboutComponent } from './about/about.component'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { AppComponent } from './app.component'; import { NavComponent } from './nav/nav.component'; import {ContactComponent} from './contact/contact.component'; import { PortfolioComponent } from './portfolio/portfolio.component'; import { SomeworkComponent } from './somework/somework.component'; import { FooterComponent } from './footer/footer.component'; import { HomeComponent } from './home/home.component'; import {GalleryComponent} from './gallery/gallery.component'; import { LoginComponent } from './login/login.component'; import { CourasalComponent } from './courasal/courasal.component'; import { SignupComponent } from './signup/signup.component'; const appRoutes: Routes = [ { path: 'about', component: AboutComponent }, {path:'login',component: LoginComponent}, {path: '', component: HomeComponent }, {path:'portfolio', component:PortfolioComponent}, {path:'gallery', component:GalleryComponent}, {path:'contact', component:ContactComponent}, {path:'signup', component:SignupComponent}, ]; @NgModule({ declarations: [ AppComponent, NavComponent, AboutComponent , PortfolioComponent, SomeworkComponent, FooterComponent, HomeComponent, GalleryComponent, LoginComponent, CourasalComponent, ContactComponent, SignupComponent, ], imports: [ BrowserModule, FormsModule, ReactiveFormsModule, RouterModule.forRoot(appRoutes) ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>/src/app/somework/somework.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-somework', templateUrl: './somework.component.html', styleUrls: ['./somework.component.css'] }) export class SomeworkComponent implements OnInit { constructor() { } ngOnInit() { } }
d5f1fa14dab7269943cef6f8f7319bcdc3f8d1b1
[ "TypeScript" ]
4
TypeScript
kaustavkarmakar2/Angular-7-sratch-developement
1a68d4d8919c3ad429bc7e2a9dc627eea9927352
b7586f7c50fb85601bef8fcd1dbeabfc36f7d4d4
refs/heads/master
<repo_name>jjsmall009/totally-awesome-typing<file_sep>/readme.md # Time Attack Typing This is the repo for my typing game made in Python. Well, it's not so much of a game as it is a demo and general typing practice. One day I may gamify it more and add some better game features. ## Phase 1 - 7/30/19 - [x] Setup and initialze repo and dev enviornment. - [ ] Create main app window: - [ ] Title and difficutly button selections - [ ] Gather words and group them into text files according to their difficulty. ## Notes This "game" is just a time attack mode where you try and get the highest score possible within the time limit. The better you type the higher your combo gets so watch out for typos! Stuff.
644b4cdbbacc02953eb180f5ee3a37c187a2e58c
[ "Markdown" ]
1
Markdown
jjsmall009/totally-awesome-typing
ec036b5515833555d14ef28e79133c3d277bba25
85f71339cd2afbba2dbf573bd1ddf2d6b3ab9a71
refs/heads/master
<file_sep>var expect = require('chai').expect; // gamejs > module.exports = testVar; var testVar = require('../../public/src/game.js'); describe('client tests', function() { it('should pass a sanity test', function() { expect(true).to.be.true; }); it ('should find defined variables inside client files', function () { expect(testVar).to.equal('client var'); }); }); <file_sep>var Collider = pc.createScript('collider'); window.moveLock = false; Collider.prototype.initialize = function () { this.entity.collision.on('collisionstart', this.onCollisionStart, this); this.entity.collision.on('collisionstart', this.onBump, this); this.entity.collision.on('collisionstart', this.disableControls, this); }; Collider.prototype.onCollisionStart = function (result) { if (result.other.name === 'Other') { this.entity.sound.play('collide'); } }; Collider.prototype.onBump = function (result) { if (result.other.name === 'Other') { this.entity.lastCollision = result.other.id; } console.log(this.entity); console.log(this.entity.isLava); console.log(result.other); //LAvascript //if result.other.isLAva === true //you broadcast death }; Collider.prototype.disableControls = function(result) { if (result.other.name === 'Other') { window.moveLock = true; setTimeout(function() { window.moveLock = false; }, 1000); } }; <file_sep>var OtherSwitch = pc.createScript('otherSwitch'); // // Reference a list of textures that we can cycle through OtherSwitch.attributes.add("textures", {type: "asset", assetType: "texture", array: true, title: "Textures"}); // initialize code called once per entity OtherSwitch.prototype.initialize = function() { this.textureIndex = 1; }; // update code called every frame OtherSwitch.prototype.update = function(dt) { var ball = this; //var pos = ball.entity.getPosition();//may need later to trigger lava var lavaCheck = ball.entity.isLava; //console.log('is the ball made of Lava', lavaCheck); if (lavaCheck === false || lavaCheck === undefined) { if (this.app.keyboard.isPressed(pc.KEY_F)) { ball.changeToNextTexture(); ball.entity.isLava = true; setTimeout(function(){ ball.entity.isLava = false; ball.changeToNextTexture(); }, 10000); } } }; OtherSwitch.prototype.changeToNextTexture = function(dt) { this.textureIndex = (this.textureIndex + 1) % this.textures.length; var texture = this.textures[this.textureIndex].resource; var meshInstances = this.entity.model.meshInstances; for (var i = 0; i < meshInstances.length; ++i) { var mesh = meshInstances[i]; mesh.material.diffuseMap = texture; mesh.material.update(); } }; //<file_sep>language: node_js node_js: - 6.10.2 deploy: provider: heroku api_key: $HEROKU_API_KEY app: pond-game <file_sep>var GameStates = pc.createScript('gameStates'); GameStates.attributes.add('Game', {type: 'entity'}); GameStates.attributes.add('StartScreen', {type: 'entity'}); GameStates.prototype.initialize = function() { this.app.on('gamestart', function() { this.app.fire('game:gamestart'); this.Game.enabled = true; this.StartScreen.enabled = false; this.app.fire('player:text'); }, this); this.app.on('gameover', function() { this.app.fire('game:gameover'); this.Game.enabled = false; this.StartScreen.enabled = true; }, this); }; <file_sep>var Teleportable = pc.createScript('teleportable'); Teleportable.prototype.initialize = function() { this.lastTeleportFrom = null; this.lastTeleportTo = null; this.lastTeleport = Date.now(); this.startPosition = this.entity.getPosition().clone(); this.entity.script.on('destroy', function() { console.log('TELEPORTABLE DESTROYED'); }); }; Teleportable.prototype.update = function(dt) { var pos = this.entity.getPosition(); // when the player falls off: game over if (pos.y < -4 && this.entity.name === 'Player') { var targetDiv = document.querySelector('body > div.container'); targetDiv.style.display = 'block'; this.entity.sound.play('wilhelm'); this.app.fire('gameover'); //this is where we delete the dead player //send event to server from array window.socket.emit('deletePlayer', this.entity.id, this.entity.lastCollision); //socket player listener on server this.teleport(this.lastTeleportFrom, this.lastTeleportTo); window.clientCurrentPlayerReference = this.entity; //this.entity.destroy(); } else if (pos.y < -4 && this.entity.name !== 'Player') { console.log('this should never be run'); this.entity.destroy(); } }; Teleportable.prototype.teleport = function(from, to) { if (from && (Date.now() - this.lastTeleport) < 500) { return; } this.lastTeleport = Date.now(); // update object's teleport 'history' to reflect // teleport about to happen this.lastTeleportFrom = from; this.lastTeleportTo = to; var position; if (to) { position = to.getPosition(); position.y += 0.5; } else { // startPosition is the respawn point position = this.startPosition; } this.entity.rigidbody.teleport(position); // reset forces this.entity.rigidbody.linearVelocity = pc.Vec3.ZERO; this.entity.rigidbody.angularVelocity = pc.Vec3.ZERO; };<file_sep>## Heading ## Ballhalla! A multiplayer browser-based game. ## Sub-Heading ## A fun low commitment game that players can jump into and out of on the fly ## Summary ## Ballhalla! continues the tradition of many other socket-based games, of fun intuitive high action and quick learning curve games for casual players. Players take the form of a rolling, bouncing, and boosting ball, with the goal of staying on top of the hill and kicking other players off of the main platform and into the lava zone. As you bounce more and more players off of platform your score will rise and you will bounce to the top of the leaderboard. If you get knocked off no worries, just log back in and start from the bottom and work your way back to the top of Ballhalla! ## Problem ## Looking for something light hearted to do in between meetings other than just waiting for new posts in your social media feeds? Just visit pond-game.herokuapp.com, put in a user nickname and get started playing immediately! ## Solution ## Ballhalla! is a simple 3D physics-based game that anyone can pick up in no time! ## Quote from You ## "Ballhalla! is not only the game I've been waiting for but the game I've been waiting to build!" -<NAME> ## How to Get Started ## Ballhalla! is very easy to get started just visit [the live game](http://pond-game.herokuapp.com) enter in a user nickname, and you will be put into the middle of the action, controls are classic and simple utilizing the WASD keys and spacebar. ## Customer Quote ## One of our users said "Sometimes I don't have the time for a full round of Counterstrike so I'll just jump onto Ballhalla!, I found that after a few rounds of gameplay I could hold my own and in no time I'll be King of the Hill. ## Closing and Call to Action ## If you would like to find out more about Ballhalla! please feel free to leave feedback to the development team email <EMAIL> or visit pondgame-herokuapp.com to play the latest version. <file_sep>require('dotenv').config(); require('@risingstack/trace'); var express = require('express'); var app = express(); var server = require('http').createServer(app); var io = require('socket.io')(server); var port = process.env.PORT || 8081; app.use(express.static(__dirname + '/public')); var redis; if (process.env.REDISTOGO_URL) { console.log('theres a redis url, here we go'); var rtg = require('url').parse(process.env.REDISTOGO_URL); redis = require('redis').createClient(rtg.port, rtg.hostname); redis.auth(rtg.auth.split(':')[1]); } else { redis = require('redis').createClient(); } var scoreboardCallback = function(err, response) { if (err) {console.error(err);} }; var players = []; function Player (id) { this.id = id; this.x = 0; this.y = 0; this.z = 0; this.entity = null; this.lastCollision = null; } io.sockets.on('connection', function(socket) { socket.on('initialize', function(nickName) { var idNum = players.length; var newPlayer = new Player (idNum); newPlayer.nickName = nickName; players.push(newPlayer); redis.zadd('scoreboard', 0, '' + idNum + ' ' + nickName); socket.emit('playerData', {id: idNum, players: players}); socket.broadcast.emit('playerJoined', newPlayer); var initialCallback = function(err, res) { if (err) { console.log(err); } else { socket.emit('leaderboardUpdate', res); socket.broadcast.emit('leaderboardUpdate', res); } }; redis.zrevrangebyscore('scoreboard', '+inf', '-inf', 'WITHSCORES', initialCallback); }); socket.on('deletePlayer', function(id, lastCollision) { if (players[lastCollision]) { redis.zrem('scoreboard', '' + id + ' ' + players[id].nickName); var playerGettingPoint = '' + lastCollision + ' ' + players[lastCollision].nickName; if (players[lastCollision] !== 'dead') { redis.zincrby('scoreboard', 1, playerGettingPoint); } players[id] = 'dead'; var leaderboardCallback = function (err, res) { if (err) { console.log(err); } else { socket.broadcast.emit('leaderboardUpdate', res); } }; redis.zrevrangebyscore('scoreboard', '+inf', '-inf', 'WITHSCORES', leaderboardCallback); } }); socket.on('positionUpdate', function(data) { //----------------------------- if (players[data.id] && players[data.id] !== 'dead') { var dataKeys = Object.keys(data); dataKeys.map(function(curKey) { if (curKey !== 'id') { players[data.id][curKey] = data[curKey]; } }); socket.broadcast.emit('playerMoved', data); } }); // currently this emites 1 point which everyone takes per second // even though it sends an id, the clients currently always take the // point, even if it's not 'theirs' so that it mimics time-based scoring var randPlayerId; setInterval(function() { randPlayerId = 0; //console.log('emitting point', randPlayerId); socket.emit('pointScored', randPlayerId); }, 1000); }); console.log('server running on port ', port); server.listen(port); exports.players = players; exports.Player = Player; exports.app = app; <file_sep>var Billboard = pc.createScript('billboard'); var defVec = new pc.Vec3(0,1,0); var parentInverseQuat; var newPosition; Billboard.prototype.initialize = function () { this.camera = this.app.root.findByName('camera'); this.player = this.app.root.findByName('Player'); }; Billboard.prototype.update = function (dt) { this.entity.setRotation(this.camera.getRotation()); this.entity.rotateLocal(90, 0, 0); parentInverseQuat = this.entity.parent.getRotation().invert(); newPosition = parentInverseQuat.transformVector(defVec); this.entity.setLocalPosition(newPosition.x, newPosition.y, newPosition.z); //this.entity.translateLocal(0,1,0); };<file_sep>var Movement = pc.createScript('movement'); Movement.attributes.add('speed', { type: 'number', default: 0.1, min: 0.05, max: 1, precision: 2, description: 'Controls the movement speed' }); Movement.prototype.initialize = function() { this.force = new pc.Vec3(); }; Movement.prototype.update = function(dt) { var forceX = 0; var forceZ = 0; if (!window.moveLock) { // calculate force based on pressed keys if (this.app.keyboard.isPressed(pc.KEY_A)) { forceX = -this.speed; } if (this.app.keyboard.isPressed(pc.KEY_D)) { forceX += this.speed; } if (this.app.keyboard.isPressed(pc.KEY_W)) { forceZ = -this.speed; } if (this.app.keyboard.isPressed(pc.KEY_S)) { forceZ += this.speed; } // boost on space bar var curVelocity = this.entity.rigidbody.linearVelocity; if (this.app.keyboard.isPressed(pc.KEY_SPACE)) { if (curVelocity.data[0] !== 0) { var normalizer = Math.sqrt(Math.pow(curVelocity.data[0], 2) + Math.pow(curVelocity.data[2], 2)); var nx = curVelocity.data[0] / normalizer; var ny = curVelocity.data[2] / normalizer; this.entity.rigidbody.applyImpulse(0.3 * nx, 0, 0.3 * ny); } } } this.force.x = forceX; this.force.z = forceZ; // if we have some non-zero force if (this.force.length()) { // calculate force vector var rX = Math.cos(-Math.PI * 0.25); var rY = Math.sin(-Math.PI * 0.25); this.force.set(this.force.x * rX - this.force.z * rY, 0, this.force.z * rX + this.force.x * rY); // clamp force to the speed if (this.force.length() > this.speed) { this.force.normalize().scale(this.speed); } } // apply impulse to move the entity this.entity.rigidbody.applyImpulse(this.force); }; <file_sep>var Network = pc.createScript('network'); var self; Network.prototype.initialize = function() { console.log('in initialize', this.entity); self = this; this.player = this.entity; // this.app.root.findByName('Player'); //setting isLava for player??? this.player.isLava = false; this.player.trigerPower = false; this.other = this.app.root.findByName('Other'); this.other.isLava = false; if (window.socket === undefined) { window.socket = io('http://localhost:8081'); //window.socket = io('http://pond-game.herokuapp.com'); } this.socket = window.socket; this.socket.on('playerData', function(data) { self.initializePlayers(data); }); this.socket.on('playerJoined', function(data) { self.addPlayer(data); }); this.socket.on ('playerMoved', function (data) { self.movePlayer (data); }); }; Network.prototype.smrtInitialize = function() { this.socket = window.socket; this.socket.emit('initialize', self.player.nickName); }; Network.prototype.initializePlayers = function(data) { console.log('initializePlayers call ', data.id); // this.players = data.players.filter(function(cur){ // //console.log('cur: ', cur, cur.id); // return cur !== 'dead'; // }); this.players = data.players; window.players = this.players; this.id = data.id; this.player.id = data.id; console.log('players length: ', this.players.length, ' current playerId', this.player.id); for (var i = 0; i < this.players.length; i++) { if (i !== this.id && this.players[i] !== 'dead') { this.players[i].entity = this.createPlayerEntity (this.players[i]); } } this.initialized = true; }; Network.prototype.addPlayer = function(data) { console.log('addPlayer call'); // this.players[this.players.length - 1].entity = this.createPlayerEntity(data); data.entity = this.createPlayerEntity(data); this.players.push(data); }; Network.prototype.createPlayerEntity = function(data) { var doesIdExist = this.players.reduce(function(accum, cur) { if (cur.id === data.id) { accum = true; } return accum; }, false); console.log('want to create ball, id=', data.id, data !== undefined, data !== 'dead', doesIdExist === false, data.entity === null); if (data !== undefined && data !== 'dead' && (doesIdExist === false || data.entity === null)) { var newPlayer = this.other.clone(); newPlayer.enabled = true; newPlayer.id = data.id; newPlayer.nickName = data.nickName; //add isLava to new Player //newPlayer.isLava = false; newPlayer.lastCollision = null; this.other.getParent().addChild(newPlayer); if (data) { console.log('>>>teleporting created ball'); // console.log('data', data); // console.log('newPlayer', newPlayer); // console.log('newPLayer.rigidBody', newPlayer.rigidBody); // console.log(this.player); newPlayer.rigidbody.teleport(data.x, data.y, data.z); } return newPlayer; } }; Network.prototype.movePlayer = function (data) { console.log('movePlayer: ', data.id, this.initialized, this === self, this.players);//this.players[data.id], this.players[data.id].entity); if (this.initialized && this.players[data.id] && this.players[data.id].entity) { //console.log('movePlayer, actually moving: ', data.id); this.players[data.id].entity.rigidbody.teleport(data.x, data.y, data.z); this.players[data.id].entity.rigidbody.linearVelocity = new pc.Vec3(data.vx, data.vy, data.vz); this.players[data.id].entity.rigidbody.angularVelocity = new pc.Vec3(data.ax, data.ay, data.az); } }; Network.prototype.update = function(dt) { this.updatePosition (); }; Network.prototype.updatePosition = function () { if (this.initialized) { var pos = this.player.getPosition(); var lv = this.player.rigidbody.linearVelocity; var av = this.player.rigidbody.angularVelocity; if (self.id !== this.id) { console.log('id disparity in updatePosition'); } this.socket.emit ('positionUpdate', { id: this.id, x: pos.x, y: pos.y, z: pos.z, vx: lv.x, vy: lv.y, vz: lv.z, ax: av.x, ay: av.y, az: av.z }); } };<file_sep>var Text = pc.createScript('text'); Text.attributes.add('text', { type: 'string', default: 'Hello World'}); Text.prototype.initialize = function () { // Create a canvas to do the text rendering this.canvas = document.createElement('canvas'); this.canvas.height = 128; this.canvas.width = 512; this.context = this.canvas.getContext('2d'); this.texture = new pc.Texture(this.app.graphicsDevice, { format: pc.PIXELFORMAT_R8_G8_B8, autoMipmap: true }); this.texture.setSource(this.canvas); this.texture.minFilter = pc.FILTER_LINEAR_MIPMAP_LINEAR; this.texture.magFilter = pc.FILTER_LINEAR; this.texture.addressU = pc.ADDRESS_CLAMP_TO_EDGE; this.texture.addressV = pc.ADDRESS_CLAMP_TO_EDGE; this.updateText(); //var material = this.entity.model.meshInstances[0].material.clone(); var material = this.entity.model.material; material.emissiveMap = this.texture; material.opacityMap = this.texture; material.blendType = pc.BLEND_NORMAL; material.update(); this.app.on('player:text', this.updateText.bind(this)); }; Text.prototype.updateText = function (textVar, GUID) { textVar = this.entity.parent.nickName; console.log('updating text'); var ctx = this.context; var w = ctx.canvas.width; var h = ctx.canvas.height; // Clear the context to transparent ctx.fillStyle = 'black'; ctx.fillRect(0, 0, w, h); // Write white text ctx.fillStyle = 'white'; ctx.font = 'bold 70px Verdana'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; ctx.fillText(textVar, w / 2, h / 2); // Copy the canvas into the texture this.texture.upload(); };<file_sep># Ballhalla! A casual free-for-all king of the hill game with an easy learning curve and no sign up required. Team - Product Owner: <NAME> - Scrum Master: <NAME> - Developers: <NAME>, <NAME> ## Table of Contents 1. [Usage](https://github.com/DJJS/thesis-project/blob/master/README.md#usage) 2. [Tools](https://github.com/DJJS/thesis-project/blob/master/README.md#tools) 1. [Installing Dependencies](https://github.com/DJJS/thesis-project/blob/master/README.md#installing-dependencies) 2. [Running Locally](https://github.com/DJJS/thesis-project/blob/master/README.md#running-locally) 3. [Workflow](https://github.com/DJJS/thesis-project/blob/master/README.md#workflow) 1. [File Structure](https://github.com/DJJS/thesis-project/blob/master/README.md#file-structure) ## Usage Just visit the [website](http://ballhalla.herokuapp.com/), enter a nickname or optionally sign in, and click Play! ## Tools - Node.js - Socket.io - PlayCanvas - Redis - Mocha - Travis CI ### Installing Dependencies From within the root directory: ```sh npm install ``` ### Running Locally Create a `.env` file to hold the information for the Redis database. Make sure that the Network.js file points to your localhost, and then start `server.js` with node or equivalent program. ## Workflow Fork main PlayCanvas project to your own PlayCanvas profile. Develop features in the PlayCanvas editor. Export and download current fork and replace the contents of the public folder with teh exported download. You can then run the project locally by pointint Network.js to your localhost and opening mulitple tabs. From there you may make pull requests to the main repo on GitHub, from which the code will be deployed to Heroku, and optionally uploaded to the main PlayCanvas project. Run ```npm test``` to unit test scripts. When committing and making a pull request to the main repo on GitHub, Travis CI will run the test suite. ### File Structure Exporting from playcanvas packages each asset within an individually assigned file with associated individual numeric identifiers such as ex-> 8668841/1/ - these numbers will be reassigned on individuals forked projects within playcanvas, so some initial navigation will be required to build familiarity within public/files/assets/... Within the playcanvas editor, these numeric identifiers are abstracted, and much of your work will take place within the playcanvas editor. Below are some of the most important commonly used file locations. - Network.js - public/files/assets/8668841/... - this file sets up our socket.io - collider.js - public/files/assets/8668838/... - this file sets up our player collisions - teleportable.js - public/files/assets/8668839/... - this file puts players in the right spot on update - start-screen.js - public/files/assets/8658762/... - this creates a new player - movement.js - public/files/assets/8668840/... - this defines movevment of player and tracks other players <file_sep>var expect = require('chai').expect; // server.js > module.exports = testVar; var server = require('../../server.js'); var io = require('socket.io-client'); var socketURL = 'http://127.0.0.1:8081'; describe('Ballhalla Server', function() { beforeEach(function() { server.players = []; newPlayer = new server.Player(3); server.players.push(newPlayer); }); describe('Player initialization', function() { it ('should find defined variables inside server files', function () { expect(server.players).to.exist; }); it ('should initialize a player with the desired ID @ (0,0,0)', function () { newPlayer = new server.Player(13579); expect(newPlayer.id).to.equal(13579); }); }); describe('Socket.IO', function() { //before (function) it ('player list should be non-empty before connecting to socket', function() { expect(server.players.length).to.equal(1); }); describe ('basic socket event communication', function() { var socket = io(socketURL); var socket2 = io(socketURL); var firstId; it('have one player after both sockets connect, but one is initialized', function (done) { socket.emit('initialize'); socket.on('playerData', function (data) { firstId = data.id; expect(data.players.length).to.equal(1); expect(server.players.length).to.equal(1); done(); }); }); it('have two players after both sockets connect and init', function (done) { socket2.emit('initialize'); socket2.on('playerData', function (data) { expect(data.players.length).to.equal(2); done(); }); }); it('should handle player movement events properly between connections', function(done) { socket.emit('positionUpdate', { id: firstId, x: 1, y: 1, z: 1, vx: 2, vy: 2, vz: 2, ax: 3, ay: 3, az: 3 }); socket2.on('playerMoved', function (data) { expect(data.id).to.equal(firstId); expect(data.x).to.equal(1); expect(Object.keys(data).length).to.equal(10); done(); }); }); }); }); });
e43b701da5836ab83d511fad97cbee4b5a2741fb
[ "Markdown", "JavaScript", "YAML" ]
14
Markdown
daberry/ballhalla
31776dce1b3a964784cf3e0bee9b9bf53a48649b
d7305c6ce5904f80bce3edd15b1ffa58e4df0944
refs/heads/master
<repo_name>Ligament/Web-Dashboard-Client<file_sep>/README.md # Web-Dashboard-Client Home-Domotic-System Home domotic system
b554511c5a72bff034efbdaa71a791755887a51c
[ "Markdown" ]
1
Markdown
Ligament/Web-Dashboard-Client
6f5de51da94537e5be08785e17429e4ee9858634
b6c065e9dd93817ec1600190cfc239885db5026f
refs/heads/master
<repo_name>haronYunis/googleMap-api<file_sep>/js/app.js function initMap() { let options = { center: { lat: 42.4668, lng: -70.9495 }, zoom: 8 }; const map = new google.maps.Map(document.getElementById('map'), options); //Add a marker onclick google.maps.event.addListener(map, 'click', function (event) { // Add Marker addMarker({ coords: event.latLng }); }); // An Array holding all of my markers const markers = [ { coords: { lat: 42.4668, lng: -70.9495 }, iconImg:'http://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png', content: '<h1><NAME></h1>' }, { coords: { lat: 42.9668, lng: -70.9495 } } ]; // Looping through my markers array for (let i in markers) { addMarker(markers[i]); } // ADD MARKER FUNCTION // Props come from markers function above. function addMarker(props) { let marker = new google.maps.Marker({ position: props.coords, map: map, }); // If it has an iconImg prop use the data to set icon if (props.iconImg) { marker.setIcon(props.iconImg) } // If it has a content prop then display content when clicked. if (props.content) { let infoWindow = new google.maps.InfoWindow({ content: props.content }); // Listening for marker click marker.addListener('click', function () { infoWindow.open(map, marker); }) } } } document.getElementById('get_location').onclick = function(){ navigator.geolocation.getCurrentPosition(c); function c(pos){ var coordinate = { lat: pos.coords.latitude, long: pos.coords.longitude, coords = lat + ', ' + long } addMarker(pos.coords); console.log(coords); } return false; } <file_sep>/README.md # googleMap-api
6b251a0f938454eb35b2fc08b9829715db199351
[ "Markdown", "JavaScript" ]
2
Markdown
haronYunis/googleMap-api
80fcb817394ff42c7d0b6a1144a4b7b4b55d4a4a
9d8d9ba74878f80270eb9afba866a395cf5f0403
refs/heads/master
<file_sep>READ ME Testng to launch a plugin from another plugin
585af524f65fe093035fc914be00a1bdaea53aa0
[ "Markdown" ]
1
Markdown
KaspArno/TestLaunch
706a7dc118ab40b2ba86859ad62de743417e80f1
547f92bebe3c4d1e721ba899696af9d84105dd2b
refs/heads/master
<file_sep>doctype html html head title="Witaj!" body h2 Witaj #{user.displayName} p Zostałeś poprawnie zalogowany.<file_sep>doctype html html head title="Login" // tak z ciekawosci - czy mozna tu dodawac style.css? np jako include ../style.css body .container p Zaloguj się do naszego serwisu. a(href= '/auth/google') button(type="button") Zaloguj
1253a0e84a507ca30ca56e4d7602798729259abc
[ "Pug" ]
2
Pug
krzychu700/25.7-uwierzytelnianie-aplikacji
9cc6268238bd7edfe1314ac1c2730881e2ec600f
5e56019770e365cf8cfbc2616dabf8d57ae5b6b6
refs/heads/master
<file_sep>package com.ohrats.bbb.ohrats; import android.os.Bundle; import android.os.Environment; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; /** * fragment that handles uploading CSVs * Created by Matt on 10/6/2017. */ public class CSVFragment extends Fragment { private DatabaseReference mDatabase; private static final String TAG = "CSVFragment"; // easier to locate what buttons the activity has if not local @SuppressWarnings("FieldCanBeLocal") private Button addCSV; private int count; // helps locate and change file name if needed for debugging @SuppressWarnings("FieldCanBeLocal") private final String CSV_FILE_NAME = "Rat_Sightings.csv"; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_csv, container, false); addCSV = (Button) view.findViewById(R.id.raddcsv); //necessary for firebase //noinspection ChainedMethodCall mDatabase = FirebaseDatabase.getInstance().getReference(); addCSV.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { count = 0; writeSightingCSV(); } }); return view; } /** * Creates a RatSighting with the given data and uploads it to the database * * @param key : Unique Key * @param date : Created Date * @param locationType : Location Type * @param zip : Incident Zip * @param address : Incident Address * @param city : City * @param borough : Boroughs * @param latitude : Latitude * @param longitude : Longitude */ // necessary because rat sighting plain old java object has that many parameters @SuppressWarnings("MethodWithTooManyParameters") private void writeNewSighting(String key, String date, String locationType, String zip, String address, String city, String borough, double latitude, double longitude) { //------------------------------------------- RatSighting sighting = new RatSighting(key, date, locationType, zip, address, city, borough, latitude, longitude); // necessary for firebase //noinspection ChainedMethodCall,ChainedMethodCall mDatabase.child("sightings").child(key).setValue(sighting); count++; Log.d(TAG, "Count is " + count); // setPriority not entirely necessary with later versions of Firebase, but it may // be useful in some scenarios // removed currently; causes lagging when uploading csv //mDatabase.child("sightings").child(key).setPriority(Integer.parseInt(key)); } /** * Writes the data from the CSV file at the specified path and filename to the database * * User still needs to manually give app permission to read and edit files: * https://stackoverflow.com/a/38578137 * */ // method considered too complex to analyze but does not contain any bugs // switch statement inside for loop to find indices of fields followed by while to parse csv // code is long because it parses the csv and there a decent number of fields @SuppressWarnings({"ConstantConditions", "OverlyComplexMethod", "OverlyLongMethod"}) private void writeSightingCSV() { Log.v(TAG, "writeSightingCSV called"); String csvFileName = CSV_FILE_NAME; File dataFolder = Environment .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); //-------------------------------------------------------------------------- File csvFile = new File(dataFolder, csvFileName); Log.v(TAG, "dataFolder path: " + dataFolder.getPath()); Log.v(TAG, "does " + csvFileName + " exist?: " + csvFile.exists()); Log.v(TAG, ".canRead() " + csvFileName + "?: " + csvFile.canRead()); Log.v(TAG, ".canWrite() " + csvFileName + "?: " + csvFile.canWrite()); Log.v(TAG, "writeSightingCSV with path: " + csvFile.getPath()); BufferedReader br; String line; String splitBy = ","; FileInputStream fis; try { fis = new FileInputStream(csvFile); Log.v(TAG, "writeSightingCSV FileInputStream instantiated"); br = new BufferedReader(new InputStreamReader(fis)); Log.v(TAG, "writeSightingCSV BufferedReader instantiated"); line = br.readLine(); String[] sighting = line.split(splitBy); int[] fieldIndex = new int[9]; // This first loop finds the column position of each type of data // present in a rat sighting row for (int count = 0; count < sighting.length; count++) { switch (sighting[count]) { case "Unique Key": fieldIndex[0] = count; break; case "Created Date": fieldIndex[1] = count; break; case "Location Type": fieldIndex[2] = count; break; case "Incident Zip": fieldIndex[3] = count; break; case "Incident Address": fieldIndex[4] = count; break; case "City": fieldIndex[5] = count; break; case "Borough": fieldIndex[6] = count; break; case "Latitude": fieldIndex[7] = count; break; case "Longitude": fieldIndex[8] = count; break; default: break; } } // SimpleDateFormat americanGarbageDF = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss aa"); // String americanGarbageString; // This second loop grabs an individual row and uses the data at relevant indices // to make a call to writeNewSighting to write a RatSighting to the database // necessary to check whether there exists a next line while getting the line if exists //noinspection NestedAssignment while ((line = br.readLine()) != null) { sighting = line.split(splitBy); int sightingLength = sighting.length; String key = (fieldIndex[0] < sightingLength) ? sighting[fieldIndex[0]] : null; String date = (fieldIndex[1] < sightingLength) ? DateStandardsBuddy .garbageAmericanStringToISO8601ESTString(sighting[fieldIndex[1]]): null; String locationType = (fieldIndex[2] < sightingLength) ? sighting[fieldIndex[2]] : null; String zip = (fieldIndex[3] < sightingLength) ? sighting[fieldIndex[3]] : null; String address = (fieldIndex[4] < sightingLength) ? sighting[fieldIndex[4]] : null; String city = (fieldIndex[5] < sightingLength) ? sighting[fieldIndex[5]] : null; String borough = (fieldIndex[6] < sightingLength) ? sighting[fieldIndex[6]] : null; double latitude = (fieldIndex[7] < sightingLength) ? Double.parseDouble(sighting[fieldIndex[7]]) : 0; double longitude = (fieldIndex[8] < sightingLength) ? Double.parseDouble(sighting[fieldIndex[8]]) : 0; writeNewSighting(key, date, locationType, zip,address, city, borough, latitude, longitude); } // close the FileInputStream since we're now done with it fis.close(); } catch (Exception e) { e.getMessage(); e.getCause(); } } } <file_sep># CS-2340-Block-Beach-Boys (26) This is our main repository for the of CS2340 You must manually give the app file access permissions via Settings -> Apps -> OhRats -> Folder Access before a CSV can be uploaded ## Branch Structure Develop is for bleeding-edge but working code. Staging is for demo-ready code. Master is for finalized, tested code that is ready for submission. Personal Branches may be created off of the develop branch. Use personal branches to experiment. ## Standards Dates should be stored as strings in ISO 8601 format YYYY-MM-DDTHH:MM:SS Example: 2017-10-15T23:19:02 [ISO 8601 Information](https://en.wikipedia.org/wiki/ISO_8601) Use the strings.xml file to store/access files ## Conventions All methods should have javadocs ### Naming Conventions Activities: ________Activity Example: LoginActivity POJOs: ________POJO Example: UserPOJO Interfaces: ________Interface Example: ControllerInterface <file_sep>package com.ohrats.bbb.ohrats; import android.support.annotation.Nullable; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; /** * Created by mkrupczak on 11/12/2017. */ @SuppressWarnings("DefaultFileTemplate") // we do follow default for Android public class DateStandardsBuddyIngesterTest { // Tests the method garbageAmericanStringToISO8601ESTString in DateStandardsBuddy // Should return an ISO8601 String if the input was valid, empty string otherwise // For full coverage, we need to test: // Null input String // Empty input String // Malformed input String // Valid input String // private Date curDate1; @Nullable private String nullString; private String emptyString; private String badAmericanString; private String goodAmericanString; private String expectedGoodOutput; /** * Sets up the test * @throws Exception if an assertion fails */ @Before public void setUp() throws Exception { nullString = null; emptyString = ""; badAmericanString = "08232017123723PM"; // a string with bad data goodAmericanString = "08/23/2017 12:37:23 PM"; // assuming data given is in ET (EDT or EST) expectedGoodOutput = "2017-08-23T11:37:23"; // output should always be in EST } /** * Test with null input, expected empty String out * @throws Exception if an assertion fails */ @Test public void americanConverterNullInput() throws Exception { String iso8601Output = DateStandardsBuddy.garbageAmericanStringToISO8601ESTString(nullString); assertEquals(emptyString, iso8601Output); } /** * Test with empty String input, expected empty String out * @throws Exception if an assertion fails */ @Test public void americanConverterEmptyInput() throws Exception { String iso8601Output = DateStandardsBuddy.garbageAmericanStringToISO8601ESTString(emptyString); assertEquals(emptyString, iso8601Output); } /** * Test with malformed input * @throws Exception if an assertion fails */ @Test public void americanConverterBadInput() throws Exception { String iso8601Output = DateStandardsBuddy.garbageAmericanStringToISO8601ESTString(badAmericanString); assertEquals(emptyString, iso8601Output); } /** * Test with good input * @throws Exception if an assertion fails */ @Test public void americanConverterGoodInput() throws Exception { String iso8601Output = DateStandardsBuddy.garbageAmericanStringToISO8601ESTString(goodAmericanString); assertEquals(expectedGoodOutput, iso8601Output); } }<file_sep>package com.ohrats.bbb.ohrats; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; /** * a screen for adding rat sightings using singularly or through using a csv * * Created by Matt on 10/3/2017. */ @SuppressWarnings("CyclicClassDependency") public class AddSightingActivity extends AppCompatActivity{ //Keep a log for debugging @SuppressWarnings("unused") //this field is used in debugging so we keep it around private static final String TAG = "AddSightingActivity"; // --Commented out by Inspection START (11/13/2017 2:15 PM): // //Both of these could be local variables but it is better // //to have them as fields because they could be needed // //for additional methods to the code. Also, // //this is the convention for firebase // @SuppressWarnings("FieldCanBeLocal") // private SectionsPageAdapter mSectionPageAdapter; // --Commented out by Inspection STOP (11/13/2017 2:15 PM) @SuppressWarnings("FieldCanBeLocal") private ViewPager mViewPager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_addsighting); //mSectionPageAdapter = new SectionsPageAdapter(getSupportFragmentManager()); mViewPager = (ViewPager) findViewById(R.id.scontainer); setupViewPager(mViewPager); TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs); tabLayout.setupWithViewPager(mViewPager); } /** * takes view pager and adds fragments that will be the different tabs * @param viewPager - the viewpager object that the fragments will be added to */ private void setupViewPager(ViewPager viewPager) { SectionsPageAdapter adapter = new SectionsPageAdapter(getSupportFragmentManager()); adapter.addFragment(new SingleFragment(), "Single"); adapter.addFragment(new CSVFragment(), "CSV"); viewPager.setAdapter(adapter); } } <file_sep>package com.ohrats.bbb.ohrats; import android.annotation.SuppressLint; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; /** * Created by mkrupczak on 10/18/2017. */ // Suppressing warnings about this being a malformed "Utility" class // Essentially, this class only deals with SimpleDateFormats, Strings, Dates, and Timezones // and we don't necessarily care that it doesn't follow strict OOD guidelines b/c it's really // just an abstraction to help programmers deal with date formatting and not a thing that needs to // exist as its own object @SuppressWarnings({"UtilityClass", "DefaultFileTemplate"}) final class DateStandardsBuddy { // Suppressing warnings which tell us that we're not respecting the date format of the user's // locale. i.e. I know what I'm doing @SuppressLint("SimpleDateFormat") private static final DateFormat iso8601DF = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); @SuppressLint("SimpleDateFormat") private static final DateFormat garbageAmericanDF = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss aa"); @SuppressLint("SimpleDateFormat") private static final DateFormat iso8601SansTime = new SimpleDateFormat("yyyy-MM-dd"); @SuppressLint("SimpleDateFormat") private static final DateFormat iso8601SansDay = new SimpleDateFormat("yyyy-MM"); private static final TimeZone estTZ = TimeZone.getTimeZone("EST"); @SuppressLint("SimpleDateFormat") private static final DateFormat iso8601DFmax = new SimpleDateFormat("yyyy-MM-dd'T'23:59:59"); @SuppressLint("SimpleDateFormat") private static final DateFormat iso8601DFmin = new SimpleDateFormat("yyyy-MM-dd'T'00:00:00"); /** * Private constructor: class can not be instantiated */ private DateStandardsBuddy() { } /** * Return an ISO 8601 combined date and time string for current date/time * Thanks Joshua and kirstopherjohnson * * @return String with format "yyyy-MM-dd'T'HH:mm:ss" where the time is EST */ public static String getISO8601ESTStringForCurrentDate() { Date now = new Date(); return getISO8601ESTStringForDate(now); } /** * Return an ISO 8601 EST combined date and time string for specified date/time * * @param targetDate * Date * @return String with format "yyyy-MM-dd'T'HH:mm:ss" where the time is EST */ public static String getISO8601ESTStringForDate(Date targetDate) { if (targetDate == null) { return ""; } TimeZone tz = TimeZone.getTimeZone("EST"); DateFormat df = iso8601DF; df.setTimeZone(tz); return df.format(targetDate); } /** * Return an ISO 8601 EST String WITHOUT a time at the end * e.g. yyyy-MM-dd * * @param targetDate date object of which the output string will represent * @return String with format "yyyy-MM-dd" where the time is EST */ @SuppressWarnings("WeakerAccess") // Keeping this weaker to keep consistency with other methods public static String getISO8601ESTSansTimeStringForDate(Date targetDate) { if (targetDate == null) { return ""; } TimeZone tz = TimeZone.getTimeZone("EST"); DateFormat df = iso8601SansTime; df.setTimeZone(tz); return df.format(targetDate); } /** * Return an ISO 8601 EST String WITHOUT a specific Day nor time at the end (year and month) * e.g. yyyy-MM * * @param targetDate date object of which the output string will represent year and month of * @return String with the format "yyyy-MM" where the time alignment is EST */ public static String getISO8601ESTSansDayStringForDate(Date targetDate) { if (targetDate == null) { return ""; } TimeZone tz = TimeZone.getTimeZone("EST"); DateFormat df = iso8601SansDay; df.setTimeZone(tz); return df.format(targetDate); } /** * Given a full ISO8601 String, returns a String without the time at the end * * @param input8601 A string in the format "yyyy-MM-ddTHH:mm:ss" * @return A truncated date string i.e. "yyyy-MM-dd" * @throws ParseException if the input string is not of the mentioned format */ public static String truncateTimeFromISO8601ESTString(String input8601) throws ParseException { Date intermediaryDate = getDateFromISO8601ESTString(input8601); return getISO8601ESTSansTimeStringForDate(intermediaryDate); } // --Commented out by Inspection START (11/11/2017 1:48 PM): // /** // * Given a full ISO8601 String, returns a String without the specific Day nor time at the end // * // * @param input8601 A string in the format "yyyy-MM-ddTHH:mm:ss" // * @return A truncated date string i.e. "yyyy-MM" // * @throws ParseException if the input string is not of the mentioned format // */ // public static String truncateDayFromISO8601ESTString(String input8601) throws ParseException { // Date intermediaryDate = getDateFromISO8601ESTString(input8601); // return getISO8601ESTSansDayStringForDate(intermediaryDate); // } // --Commented out by Inspection STOP (11/11/2017 1:48 PM) /** * Given a target date, returns the maximum ISO8601 EST Date/Time String * * e.g. given any time of a particular day, will give the maximum ISO8601 date time of the same * day as the input Date * * Beware that method will probably maximize in terms of EST, so be careful * @param targetDate the target date/time to maximize * @return the maximum ISO8601 date/time string for the given date e.g. * "yyyy-MM-dd'T'23:59:59" * returns an empty string if the input Date is null */ public static String getISO8601MAXStringForDate(Date targetDate) { if (targetDate == null) { return ""; } DateFormat df = iso8601DFmax; df.setTimeZone(estTZ); return df.format(targetDate); } /** * Given a target date, returns the minimum ISO8601 EST Date/Time String * * e.g. given any time of a particular day, will give the minimum ISO8601 date time of the same * day as the input Date * * Beware that method will probably minimize in terms of EST, so be careful * @param targetDate the target date/time to minimize * @return the minimum ISO8601 date/time string for the given date e.g. * "yyyy-MM-dd'T'00:00:00" * returns an empty string if the input Date is null */ public static String getISO8601MINStringForDate(Date targetDate) { if (targetDate == null) { return ""; } DateFormat df = iso8601DFmin; df.setTimeZone(estTZ); return df.format(targetDate); } /** * Returns a java date from a given ISO8601 string in EST * @param iso8601String input string in ISO8601, assumed to be EST * @return a java date object of the corresponding date and time * @throws ParseException throws an exception if the assumption of the date format is incorrect */ public static Date getDateFromISO8601ESTString(String iso8601String) throws ParseException { DateFormat df = iso8601DF; df.setTimeZone(estTZ); return df.parse(iso8601String); } /** * Given a string in the garbage American format "MM/dd/yyyy hh:mm:ss aa" returns * one in the ISO8601 format "yyyy-MM-dd'T'HH:mm:ss" in EST * * If the input string is invalid or null, returns an empty string * * @param garbageAmericanString input String in the garbage American date format * @return a String representation of the date represented by the input, but in ISO8601 * where the time is in eastern standard time * */ public static String garbageAmericanStringToISO8601ESTString(String garbageAmericanString) { if ((garbageAmericanString == null) || garbageAmericanString.isEmpty()) { return ""; } else { Date intermediaryDate; try { intermediaryDate = garbageAmericanDF.parse(garbageAmericanString); } catch (ParseException e) { // parsing failed, input was likely invalid return ""; } return getISO8601ESTStringForDate(intermediaryDate); } } // --Commented out by Inspection START (11/11/2017 1:50 PM): // /** // * // * @param garbageAmericanString input String in the garbage American date format // * @return a Date in ISO8601 where the time is in eastern standard time // */ // public static Date garbageAmericanStringToISO8601ESTDate(String garbageAmericanString) { // if ((garbageAmericanString == null) || garbageAmericanString.isEmpty()) { // return null; // } else { // Date date = null; // try { // date = garbageAmericanDF.parse(garbageAmericanString); // } catch (ParseException e) { // // parsing failed, input was likely invalid // return null; // } // return date; // } // } // --Commented out by Inspection STOP (11/11/2017 1:50 PM) // --Commented out by Inspection START (11/11/2017 1:50 PM): // /** // * Gets a date format representing ISO8601 in the format "yyyy-MM-dd'T'HH:mm:ss" // * @return iso8601DF SimpleDateFormat // */ // public static DateFormat getIso8601DF() { // return iso8601DF; // } // --Commented out by Inspection STOP (11/11/2017 1:50 PM) // --Commented out by Inspection START (11/11/2017 1:51 PM): // /** // * Gets a date format representing the garbage american format // * i.e. "MM/dd/yyyy hh:mm:ss aa" // * @return garbageAmericanDF SimpleDateFormat // */ // public static DateFormat getGarbageAmericanDF() { // return garbageAmericanDF; // } // --Commented out by Inspection STOP (11/11/2017 1:51 PM) // --Commented out by Inspection START (11/11/2017 1:51 PM): // /** // * Gets a date format representing ISO8601 without a time at the end // * i.e. "yyyy-MM-dd" // * @return iso8601SansTime SimpleDateFormat // */ // public static DateFormat getIso8601SansTime() { return iso8601SansTime; } // --Commented out by Inspection STOP (11/11/2017 1:51 PM) // --Commented out by Inspection START (11/11/2017 1:51 PM): // /** // * Gets a date format representing the maximum ISO8601 date time for a given day // * i.e. "yyyy-MM-dd'T'23:59:59" // * @return iso8601DFmax date format which will format a date to maximum time in a ISO8601 day // */ // public static DateFormat getIso8601DFmax() { // return iso8601DFmax; // } // --Commented out by Inspection STOP (11/11/2017 1:51 PM) // --Commented out by Inspection START (11/11/2017 1:51 PM): // /** // * Gets a date format representing the minimum ISO8601 date time for a given day // * i.e. "yyyy-MM-dd'T'00:00:00" // * @return iso8601DFmin date format which will format a date to minimum time in a ISO8601 day // */ // public static DateFormat getIso8601DFmin() { // return iso8601DFmin; // } // --Commented out by Inspection STOP (11/11/2017 1:51 PM) }
f1363e8fd9be3b5e49c69c60060c8af47083b93f
[ "Java", "Markdown" ]
5
Java
josh75337/CS-2340-Block-Beach-Boys
22c2084a077746bb9ddda25a94e52c546dfd2c85
0ba6087247db069ef52ef0d9e0d2806712fb0dc3
refs/heads/master
<repo_name>cdepeuter/bioinfomatics<file_sep>/App-Directory/ui.R fluidPage( navlistPanel( tabPanel("Mapper", tags$head(tags$script(src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js")), tags$head(tags$script(src="cdp.js")), #includeCSS("www/style.css"), tags$head( tags$link( rel = "stylesheet", type = "text/css", href = "style.css" ) ), # headerPanel('Store Clusters'), # sidebarPanel( # numericInput('clusters', 'Cluster count', 3, # min = 1, max = 9) # ), mainPanel( plotOutput('mapperPlot'), tags$div(class="bhiResults", tableOutput('bhiTable') ) #tags$img(src = "/rplt.png") ) ), tabPanel("Gene Function Tables", mainPanel( tags$div(class="infoTables", tags$div(class="diffexpInfoTable", tags$div("Mapper Function"), tableOutput('diffExpTable') ), tags$div(class="clusterInfoTable", tags$div("H-Clust Functions"), tableOutput('hTable') ) ) ) ), tabPanel("Pathway Analysis", mainPanel( tableOutput('pathwayDisplayTable') ) ) # tags$head( # # tags$link( # # rel = "stylesheet", # # type = "text/css", # # href = "style.css" # # ) # # ), # forceNetworkOutput("force") # ) ) )<file_sep>/App-Directory/libs.R # source("https://bioconductor.org/biocLite.R"); ## try http:// if https:// URLs are not supported # biocLite("affy"); # biocLite("limma"); # biocLite("clValid") # biocLite("hopach") # biocLite("annotate") # biocLite("mygene") # biocLite("annotate") # biocLite("GO.db") # biocLite("moe430a.db") # biocLite("hgu133a.db") # biocLite("genefilter") #use unstable TDAMapper for up to date functions #use proxy for ubuntu bug https://github.com/hadley/devtools/issues/877 #with_config(use_proxy("172.16.17.32", 3128), devtools::install_github("paultpearson/TDAmapper")) library(affy); library(limma); library(GEOquery); library(mygene); library(annotate); library(tidyverse); library(cluster); library(TDAmapper); library(networkD3); library(HSAUR); library(shiny); library(igraph); library(scatterplot3d); library(annotate) library(moe430a.db) library(GO.db) library(Biobase) library(genefilter) library(clValid) library(annotate) library(hgu133a.db) library(GO.db) <file_sep>/App-Directory/BHIcomparison.R #how do we evaluate these results? #BHI starts here debug.print("BHI analysis") names(Genebelongstocluster)=names(unlist(allClustersGenes)) m1.bhi = BHI(Genebelongstocluster, annotation=annotation_file, names=names(Genebelongstocluster), category="all") hclusters.bhi = BHI(hclusters.clusts,annotation=annotation_file,names=names(hclusters.clusts),category = "all") kclust.bhi = BHI(kclust$cluster,annotation=annotation_file,names=names(hclusters.clusts),category = "all") m1.diffGenesInClust = Genebelongstocluster[which(names(Genebelongstocluster) %in% diff_genes)] hclusters.diffGenesInClusts = hclusters.clusts[which(names(hclusters.clusts) %in% diff_genes)] kclust.diffGenesInClusts = kclust$cluster[which(names(kclust$cluster) %in% diff_genes)] m1.bhiDiffGenes = BHI(m1.diffGenesInClust, annotation=annotation_file, names=names(m1.diffGenesInClust), category="all") hclusters.bhiDiffGenes = BHI(hclusters.diffGenesInClusts,annotation=annotation_file,names=names(hclusters.diffGenesInClusts),category="all") kclust.bhiDiffGenes = BHI(kclust.diffGenesInClusts,annotation=annotation_file,names=names(kclust.diffGenesInClusts),category="all") #write to table bhis <- c(m1.bhi, hclusters.bhi, kclust.bhi) names(bhis) <- c("MAPPER", "H-Clust", "K-means")<file_sep>/App-Directory/humanpathway.R #gonna explain what each variable is, feel free to change names as you please uni2 <- as.matrix(read.delim(file = "UniProt2Reactome.txt", header = F, sep = "\t")); #reading in pathway data uni2 = tbl_df(uni2) uni3 = count(uni2,V2) uni3 = uni3[((uni3$n>5) & (uni3$n<500)),] #filtering out the pathways with unacceptable occurences l3 = list() #this list shall be of the form where the first element in each sublist is the pathway, #and all the following elements are the genes in that pathway for(i in 1:length(uni3$V2)){ l3[[i]]=c(as.character(uni3$V2[i]),unlist(list(as.character(uni2$V1[uni2$V2 %in% uni3$V2[i]])))) } #reading in uniprot data u133a <- as.matrix(read.delim(file = "uniprot2U133A.txt", header = T, sep = "\t")); u133a = tbl_df(u133a) #function to map gene names to uniprot names genetouniprot <- function(geneid){return (u133a$Uniprot_ID[which(u133a$U133A_ID %in% geneid)])} uniprottogene = function(gene){return (u133a$U133A_ID[which(u133a$Uniprot_ID %in% gene)])} #changing diff gene names to their respective uniprot names diff_genes_uniprot <- unlist(lapply(diff_genes,genetouniprot)) #for BIOLOGICAL FUNCTIONS , just needs to be in the same form as l3 #function to calculate number of differentially expressed genes in each pathway numdiffgenesinpathway = function(pathwaygenes){return(length(which(pathwaygenes %in% diff_genes_uniprot)))} pathwaydiffcount=list()#this list has the number of differentially expressed genes for the pathway at the same index for(i in 1:length(l3)){ pathwaydiffcount[[i]]=numdiffgenesinpathway(l3[[i]][-1]) } diffgenesinpathway = function(pathwaygenes){return(unlist(pathwaygenes[which(pathwaygenes %in% diff_genes_uniprot)]))} pathwaydiffgenes=list()#this list has the number of differentially expressed genes for the pathway at the same index for(i in 1:length(l3)){ pathwaydiffgenes[[i]]=diffgenesinpathway(l3[[i]][-1]) } pathwaydiffcount=unlist(pathwaydiffcount) contingency=matrix(nrow=2,ncol=2); #function to execute fisher test for each pathway getpvaluefromfisher=function(i){ contingency[1,1]=pathwaydiffcount[i]; contingency[1,2]=length(l3[[i]][-1])-length(contingency[1,1]); contingency[2,1]=length(diff_genes)-length(contingency[1,1]); contingency[2,2]=length(rownames(affy_fil))-length(diff_genes)-length(contingency[1,2]); return(fisher.test(as.matrix(contingency),alternative = "greater")) } pvaluefromfisher=lapply(seq(from=1,to=2223),getpvaluefromfisher) #function to find false discovery rates deg_pathway_fdr_func <-function(i){return(p.adjust(pvaluefromfisher[[i]]$p.value,method="fdr"))} deg_pathway_fdr=unlist(lapply((seq(from=1,to=2223)),deg_pathway_fdr_func)) #get the pvalue for each pathway pvalue=vector() for(i in 1:length(pvaluefromfisher)){pvalue[i]=pvaluefromfisher[[i]]$p.value} #construct the resultant matrix which is of the form pathwayname,fdr,pvalue and order it by increasing p-values result_matrix=cbind(uni3$V2,pvalue,deg_pathway_fdr) colnames(result_matrix)=c('Pathway','P-value','FDR') deg_order=order(pvalue) result_matrix=result_matrix[deg_order,] goodpathways = unlist(result_matrix[1:10,1]) indexofgoodpathways = which(uni3$V2 %in% goodpathways) goodpathwaygenes = pathwaydiffgenes[indexofgoodpathways] clustersofgoodpathwaygenes = list() clustersofgoodpathwaygenesH = list() clustersofgoodpathwaygenesK = list() for(i in 1:length(goodpathwaygenes)){ goodpathwaygenes[i]=lapply(goodpathwaygenes[i],uniprottogene) } for(i in 1:length(goodpathwaygenes)){ clustersofgoodpathwaygenes[[i]] = unlist(lapply((goodpathwaygenes[[i]]),getVertexForGene)) clustersofgoodpathwaygenesH[[i]] = hclusters.clusts[which(names(hclusters.clusts) %in% goodpathwaygenes[[i]])] clustersofgoodpathwaygenesK[[i]] = kclust$cluster[which(names(kclust$cluster) %in% goodpathwaygenes[[i]])] } <file_sep>/App-Directory/loadData.R debug.debug=TRUE debug.print <- function(x){if(debug.debug){print(x)}} #gds_set_name <- "GDS5437" gds_set_name <- "GDS1439" #set columns for healthy/sick data if(gds_set_name == "GDS1439"){ gstats.healthy <- 1:6 gstats.sick <- 7:19 annotation_file <- "hgu133a.db" gstats.poapct <- .4 gstats.poanum <- 10.5 gstats.iqr <- 0 pval <- .01 pathwayFile <- "./humanpathway.R" }else if(gds_set_name == "GDS5437"){ gstats.healthy <- 10:14 gstats.sick <- 1:9 annotation_file <- "moe430a.db" gstats.poapct <- .2 gstats.poanum <- 7.5 gstats.iqr <- .25 pval <- .05 pathwayFile <- "./mousepath.R" } pval <- 0.01 max_diffexp <- 1000 gds <- getGEO(gds_set_name); eset <- GDS2eSet(gds,do.log2=TRUE); affy_exp <- as.matrix(eset); affy_exp_names <- rownames(affy_exp); featureData<-fData(eset) #do pre-filtering #poverA -> gene expression value above pct, in at least num samples f1 <- pOverA(gstats.poapct, gstats.poanum) filterFunction <- filterfun(f1) mask <- genefilter(affy_exp, filterFunction) f2 <- function(x){ IQR(x) > gstats.iqr } filterFunction2 <- filterfun(f2) mask2 <- genefilter(affy_exp, filterFunction2) affy_fil <- affy_exp[mask &mask2,] debug.print("Dimension of filtered data") debug.print(dim(affy_fil)) #do regular gene expression analysis, find differentially expressed genes disease_state<-as.character(pData(eset)[,2]) combn <- factor(disease_state); design <- model.matrix(~combn); fit <- lmFit(affy_fil,design); efit <- eBayes(fit); #get differentially expressed genes diff_gene_table <- topTable(efit, number = max_diffexp ,p.value = pval); diff_genes <- rownames(diff_gene_table) geneIds <- rownames(affy_fil) debug.print(paste("number diffexp genes ", length(diff_genes))) #get pairwise distance for mapper, count=0 filT = t(affy_fil) #corr = cor(filT,method="spearman") #TODO test different methods for correlation/distance debug.print("Getting distance/correlation") corr = cor(filT,method="pearson") #corr = cor(filT,method="spearman") dsy <- daisy(affy_fil) #do mapper, what clusters do the differentially expressed genes end up in #filter function for mapper benign.disease_state = factor("benign",levels=c("benign","primary","metastatic")) allpca = princomp(affy_fil) #principal components for benign data benign.data = affy_fil[,gstats.healthy] benign.pca = princomp(benign.data) benign.weights = loadings(benign.pca)[,1] reduced_dim_benign = benign.data %*% benign.weights benign.design = model.matrix(~benign.disease_state) benign.fit = lmFit(benign.design) coeff_benign = coefficients(benign.fit) #principal component analysis for disease data diseasedata = affy_fil[,gstats.sick] diseasepca = princomp(diseasedata) weights_disease = loadings(diseasepca)[,1] reduced_dim_disease = diseasedata %*% weights_disease modeled_disease_filter = reduced_dim_disease %*% coeff_benign filterforfil3 = modeled_disease_filter[geneIds,] <file_sep>/App-Directory/justPlot.R forceNetwork(Nodes = MapperNodes, Links = MapperLinks, Source = "Linksource", Target = "Linktarget", Value = "Linkvalue", NodeID = "Nodename", Group = "Nodegroup", opacity = 1, linkDistance = 10, charge = -400) ColourScale <- 'd3.scale.ordinal() .rank(pct_diffexp)/max(rank(pct_diffexp)) .range(["#FF6900", "#694489"]);' JS(ColourScale) <file_sep>/App-Directory/pathwayanalysis.R #gonna explain what each variable is, feel free to change names as you please uni2 <- as.matrix(read.delim(file = "UniProt2Reactome.txt", header = F, sep = "\t")); #reading in pathway data uni2 = tbl_df(uni2) uni3 = count(uni2,V2) uni3 = uni3[((uni3$n>5) & (uni3$n<500)),] #filtering out the pathways with unacceptable occurences l3 = list() #this list shall be of the form where the first element in each sublist is the pathway, #and all the following elements are the genes in that pathway for(i in 1:length(uni3$V2)){ l3[[i]]=c(as.character(uni3$V2[i]),unlist(list(as.character(uni2$V1[uni2$V2 %in% uni3$V2[i]])))) } #reading in uniprot data u133a <- as.matrix(read.delim(file = "uniprot2U133A.txt", header = T, sep = "\t")); u133a = tbl_df(u133a) #function to map gene names to uniprot names genetouniprot <- function(geneid){return (u133a$Uniprot_ID[which(u133a$U133A_ID %in% geneid)])} #changing diff gene names to their respective uniprot names diff_genes_uniprot <- unlist(lapply(diff_genes,genetouniprot)) #for BIOLOGICAL FUNCTIONS , just needs to be in the same form as l3 #function to calculate number of differentially expressed genes in each pathway numdiffgenesinpathway = function(pathwaygenes){return(length(which(pathwaygenes %in% diff_genes_uniprot)))} pathwaydiffcount=list()#this list has the number of differentially expressed genes for the pathway at the same index for(i in 1:length(l3)){ pathwaydiffcount[[i]]=numdiffgenesinpathway(l3[[i]][-1]) } pathwaydiffcount=unlist(pathwaydiffcount) contingency=matrix(nrow=2,ncol=2); #function to execute fisher test for each pathway getpvaluefromfisher=function(i){ contingency[1,1]=pathwaydiffcount[i]; contingency[1,2]=length(l3[[i]][-1])-length(contingency[1,1]); contingency[2,1]=length(diff_genes)-length(contingency[1,1]); contingency[2,2]=length(affy_fil[,1])-length(diff_genes)-length(contingency[1,2]); return(fisher.test(as.matrix(contingency),alternative = "greater")) } pvaluefromfisher=lapply(seq(from=1,to=2223),getpvaluefromfisher) #function to find false discovery rates deg_pathway_fdr_func <-function(i){return(p.adjust(pvaluefromfisher[[i]]$p.value,method="fdr"))} deg_pathway_fdr=unlist(lapply((seq(from=1,to=2223)),deg_pathway_fdr_func)) #get the pvalue for each pathway pvalue=vector() for(i in 1:length(pvaluefromfisher)){pvalue[i]=pvaluefromfisher[[i]]$p.value} #construct the resultant matrix which is of the form pathwayname,fdr,pvalue and order it by increasing p-values result_matrix=cbind(uni3$V2,pvalue,deg_pathway_fdr) colnames(result_matrix)=c('Pathway','P-value','FDR') deg_order=order(pvalue) result_matrix=result_matrix[deg_order,] pathwayDisplayTable <- tbl_df(result_matrix[1:15,])<file_sep>/App-Directory/results.R t1 <- read.table("results/gridResults1439Daisy_poa_4_10p5-pearsonSmallerParams.csv") t2 <- read.table("results/gridResults1439Daisy_poa_4_10p5_no_iqr_pearson.csv") t3 <-read.table("results//gridResults1439Daisy_poa_8_p6_iqr_75_pearson.csv") pearsonTable1439 <- rbind(t1,t2,t3) print(c(mean(pearsonTable1439$mapperBHI), mean(pearsonTable1439$hclustBHI), mean(pearsonTable1439$kclustBHI))) print(c(sd(pearsonTable1439$mapperBHI), sd(pearsonTable1439$hclustBHI), sd(pearsonTable1439$kclustBHI))) t4 <-read.table("results/gridResults1439Daisy_poa_45_9p5-spearman.csv", sep=",") t5 <- read.table("results/gridResults1439Daisy_poa_4_10p5_noiqr_spearman.csv") spearmanTable1439 <- rbind(t4,t5) allValues<- rbind(pearsonTable1439, pearsonTable1439) print(c(mean(spearmanTable1439$mapperBHI), mean(spearmanTable1439$hclustBHI), mean(spearmanTable1439$kclustBHI))) print(c(sd(spearmanTable1439$mapperBHI), sd(spearmanTable1439$hclustBHI), sd(spearmanTable1439$kclustBHI))) spearmanTable5437 <- read.table("results/5437_small_params_spearman_poa_8_p25_daisy.csv") print(c(mean(spearmanTable5437$mapperBHI), mean(spearmanTable5437$hclustBHI), mean(spearmanTable5437$kclustBHI))) print(c(sd(spearmanTable5437$mapperBHI), sd(spearmanTable5437$hclustBHI), sd(spearmanTable5437$kclustBHI))) colors<-rainbow(3) xrange <- range(allValues$num.verticies) yrange<-range(.2, max(max(allValues$mapperBHI), max(allValues$hclustBHI), max(allValues$kclustBHI))) sortedVerts <- sort(unique(allValues$num.verticies)) flattenMapperBHI <- unlist(lapply(sortedVerts, function(x){mean(allValues[allValues$num.verticies == x, "mapperBHI"])})) flattenHclustBHI <- unlist(lapply(sortedVerts, function(x){mean(allValues[allValues$num.verticies == x, "hclustBHI"])})) flattenKclustBHI <- unlist(lapply(sortedVerts, function(x){mean(allValues[allValues$num.verticies == x, "kclustBHI"])})) jump <- 5 plot(xrange, yrange, type="n", xlab="Num Vertices", ylab="BHI") colors<-rainbow(3) lines(sortedVerts, flattenMapperBHI, col = colors[1]) lines(sortedVerts, flattenHclustBHI, col = colors[2]) lines(sortedVerts, flattenKclustBHI, col = colors[3]) legend('bottomright', c("Mapper", "H Clust", "K Clust"), col=colors,text.width = 100, lty=c(1,1)) <file_sep>/README.md ## Topological Data analysis The purpose of this project is to compare the clustering of the TDA clustering method Mapper with K-Means and Hierarchical Clustering ### Run shiny app 1. Set working directory to App-Directory of this repo. 2. Source libs.R, make sure all load 3. Source loadData.R 4. Source analysis.R 5. `shiny::runApp()` ### To work with a new GDS file We have built this code with the idea of being able to insert other gene expression data with as few changes necessary as possible; however, if using a new GDS file a new condition will need to be added after those starting at line 10 in loadData.R, with the necessary variables filled in. ![alt text](https://github.com/cdepeuter/bioinfomatics/blob/master/App-Directory/mapperimgs/gds1437-15-17-17.png "Sample Mapper output") <file_sep>/App-Directory/genefunctions2.R names(genesandtheirfunctions) = rownames(affy_fil) genefunctionindex=function(genefunction){ l=list() for(i in 1:length(genesandtheirfunctions)){ if(genefunction %in% genesandtheirfunctions[[i]]){ l = c(l,i) } } return(unlist(l)) } a12 = lapply(listofgenefunctions,genefunctionindex) a22 =lapply(a12,function(x){return(rownames(affy_fil)[x])}) names(a22) = listofgenefunctions numdiffgenesingf = function(gfgenes){return(length(which(gfgenes %in% diff_genes)))} diffgenesingf = function(gfgenes){return(unlist(gfgenes[which(gfgenes %in% diff_genes)]))} gfdiffgenes =lapply(a22,diffgenesingf) gfdiffcount=list()#this list has the number of differentially expressed genes for the pathway at the same index for(i in 1:length(listofgenefunctions)){ gfdiffcount[[i]]=numdiffgenesingf(a22[[i]]) } gfdiffcount = unlist(gfdiffcount) contingency=matrix(nrow=2,ncol=2); #function to execute fisher test for each gf getpvaluefromfisher=function(i){ contingency[1,1]=gfdiffcount[i]; contingency[1,2]=length(a22[[i]])-length(contingency[1,1]); contingency[2,1]=length(diff_genes)-length(contingency[1,1]); contingency[2,2]=length(rownames(affy_fil))-length(diff_genes)-length(contingency[1,2]); return(fisher.test(as.matrix(contingency),alternative = "greater")) } pvaluefromfishergf=lapply(seq(from=1,to=length(listofgenefunctions)),getpvaluefromfisher) deg_gf_fdr_func <-function(i){return(p.adjust(pvaluefromfishergf[[i]]$p.value,method="fdr"))} deg_gf_fdr=unlist(lapply((seq(from=1,to=length(listofgenefunctions))),deg_gf_fdr_func)) #get the pvalue for each pathway pvaluegf=vector() for(i in 1:length(pvaluefromfishergf)){pvaluegf[i]=pvaluefromfishergf[[i]]$p.value} #construct the resultant matrix which is of the form pathwayname,fdr,pvalue and order it by increasing p-values result_matrix_gf=cbind(listofgenefunctions,pvaluegf,deg_gf_fdr) colnames(result_matrix_gf)=c('Gene Function','P-value','FDR') deg_order_gf=order(pvaluegf) result_matrix_gf=result_matrix_gf[deg_order_gf,] result_matrix_gf = tbl_df(result_matrix_gf) result_matrix_gf = result_matrix_gf[order(result_matrix_gf$`P-value`),] goodfunctions = unlist(result_matrix_gf[1:15,1]) indexofgoodfunctions = which(listofgenefunctions %in% goodfunctions) goodfunctiongenes = gfdiffgenes[indexofgoodfunctions] clustersofgoodgfgenes = list() clustersofgoodgfgenesH = list() clustersofgoodgfgenesK = list() for(i in 1:length(goodfunctiongenes)){ clustersofgoodgfgenes[[i]] = unlist(lapply((goodfunctiongenes[[i]]),getVertexForGene)) clustersofgoodgfgenesH[[i]] = hclusters.clusts[which(names(hclusters.clusts) %in% goodfunctiongenes[[i]])] clustersofgoodgfgenesK[[i]] = kclust$cluster[which(names(kclust$cluster) %in% goodfunctiongenes[[i]])] } <file_sep>/App-Directory/server.R function(input, output) { if(!exists("m1")){ source("./analysis.R") } # data <- eventReactive(input$go, { # rnorm(input$num) # }) vertexSizes <- 2 * totalInMapperClusters/(dim(affy_fil)[1]/m1$num_vertices) vertexSizes[vertexSizes < 3] <- 3 output$mapperPlot <- renderPlot({ par(mar = c(1, 1, 1, 1)) plot(g1, layout = layout.auto(g1), main = gds_set_name, vertex.color = colorRampPalette(c('blue', 'red'))(length(pct_diffexp))[rank(pct_diffexp)], #vertex.size = 7*totalInMapperClusters/(dim(affy_fil)[1]/m1$num_vertices) ) }) output$hTable <- renderTable(t(hclusters.tableData)) output$diffExpTable <- renderTable(t(m1.tableData)) output$bhiTable <- renderTable(as.table(bhis), digits=4, colnames = FALSE) output$pathwayDisplayTable <- renderTable(pathwayDisplayTable) ColourScale <- paste(cbind('d3.scale.ordinal().range(',jsColorString,');')) output$force <- renderForceNetwork({ forceNetwork(Nodes = MapperNodes, Links = MapperLinks, Source = "Linksource", Target = "Linktarget", Value = "Linkvalue", NodeID = "Nodename", colourScale = JS(ColourScale), Group = "pctdiffexp", opacity = 1, Nodesize = "Nodesize", linkDistance = 10, charge = -150, legend = TRUE) }) output$hclustPlot <-renderPlot({ plot(dend)}) }<file_sep>/writeups/bioPaper.tex \documentclass[preprint,10pt]{elsarticle} \makeatletter \def\ps@pprintTitle{% \let\@oddhead\@empty \let\@evenhead\@empty \def\@oddfoot{\centerline{\thepage}}% \let\@evenfoot\@oddfoot} \makeatother %% Use the option review to obtain double line spacing %% \documentclass[preprint,review,12pt]{elsarticle} %% Use the options 1p,twocolumn; 3p; 3p,twocolumn; 5p; or 5p,twocolumn %% for a journal layout: %% \documentclass[final,1p,times]{elsarticle} %% \documentclass[final,1p,times,twocolumn]{elsarticle} %% \documentclass[final,3p,times]{elsarticle} %% \documentclass[final,3p,times,twocolumn]{elsarticle} %% \documentclass[final,5p,times]{elsarticle} %% \documentclass[final,5p,times,twocolumn]{elsarticle} \usepackage{graphicx} \usepackage{amssymb} \usepackage[margin=2.5cm]{geometry} \usepackage{caption} \usepackage{subcaption} \setlength\parindent{12pt} \begin{document} \begin{frontmatter} \title{Applying Topological Methods to Gene Expression Analysis} \author{<NAME>, BS} \author{<NAME>, B.Tech} \address{Columbia University, New York, NY, USA} \begin{abstract} Finding differentially expressed genes from cancer microarrays is a common technique used in determining the causes of cancer, but extracting meaning from this set of genes is often not straightforward. Regular clustering methods routinely group genes that are not biologically related, thus it is hard to extract information from such analyses. Using a topological data analysis method known as Mapper in conjunction with data on gene functions as well as the pathways where these genes operate, we find evidence that clusterings produced by Mapper have more biological significance than regular clustering methods K-Means and Hierarchical Clustering. The functional clustering of these genes may provide insight for novel areas of investigation in determining the causes/prognosis for cancers. \end{abstract} \end{frontmatter} \section{Introduction} \subsection{Mapper/PAD} The Mapper method, introduced by Carlsson et. al. in 2007 \cite{mapper} formulated a novel topological approach to analysis of high-dimensional data sets. The idea is based on partial clustering of the data combined with a filtering function on the data to reduce its dimensionality. The method performs partial clustering on overlapping intervals of the data set with a graph output where vertices are the bins within each clustering. Because the intervals are overlapping a data point may end up in multiple clusters, if this happens an edge is drawn between these two clusters in the graph. With a well defined set of filters, Carlsson et. al. were able to show that relationships among data points persisted throughout the dimensional reduction that did not persist in regular clustering algorithms. In an approach termed Progression Analysis of Disease (PAD), Nicolau et al. applied the Mapper method to breast cancer microarray data in 2011 using a filter function referred to as Disease-Specific Genomic Analysis (DSGA) \cite{dsga}, and were able to identify a type of breast with unique gene profiles, and discovered that patients with this cancer had 100\% survival rates and no metastasis \cite{nicolau}. Previously, Mapper had been shown to provide structural insight into the folding of RNA \cite{RNA}. In this study we intend to provide further evidence of Mapper's ability to produce functionally significant clusterings. According to Carlsson et al.'s original paper on Mapper, the goal of the method is to build low-dimensional image of the data set which may indicate areas of interest. Applying this method to cancer data in a similar fashion to PAD, we would like to indicate areas of interest for studying two specific forms of cancer, as well as provide a general framework for similar studies in the future. \subsection{Benefits of Discovering Functionally Significant Clusters} The possible benefits of such a technique are clear. The ability to identify a subgroup of cancers with unique and consistent survival rates not only helps with patient prognosis, it may also provide insight into treatment methods. Unlike the PAD study we do not have access to the survival rates of the patients in the data set, we only have the gene expression data from the time it was taken. In lieu of this our final goal is not to find specific high or low survival rate cancers, but instead to develop a method which produces areas of interest for further study of these cancers by examining the functions of genes which end up clustered together, as well as the pathways where they operate. \section{Methods and Materials} \subsection{Data Sources} We used two data sets from the Gene Expression Omnibus. GDS5437 \cite{gds5437} compares 14 lung tissue samples of gene expression of healthy mice versus mice with non-metastatic and metastatic breast cancer tumors. These samples consisted of 5 healthy mice, 5 with non-metastatic tumors, and 4 with metastatic tumors. The original study for the data set was looking at the over-expression of the G-CSF glycoprotein in the lung tissue of mice with metastatic breast cancer, and showed that in the lung tissue of these mice only those with metastatic breast cancer showed over-expression of G-CSF. The second data set, GDS1439 \cite{gds1439}, compares 19 samples of prostate cancer tumors in humans which are benign (6), clinically localized (7), and metastatic (6). The original study for this data set looked to identify which proteins were altered in the different states of cancer and tried to identify a proteomic progression signature in prostate tumors. \subsection{Data Dimensioniality Reduction} Before clustering we reduced the number of genes in each data set in order to make hundreds of clusterings computationally feasible. We did this by removing genes which did not have a sufficient expression level across enough samples using the "genefilter" package in R \cite{genefilter}. We then fit a linear model to each of the data sets to identify which genes were differentially expressed. GDS1439 produced thousands of differentially expressed genes, so we took the ones with the top 1000 p-values. GDS5437 only produced 76 differentially expressed genes, so we took all of those. For both data sets we reduced each to around 7000 genes. The crux of the Mapper algorithm is a dimensionality reducing filter function which "reflects geometric properties of the data set" \cite{mapper}. The topological theory of the method is that if this filtering function relates to the areas of interest in the data set then the proximity of similar data points should persist through this dimensionality reduction. We used the same filter function from the PAD/DSGA method \cite{nicolau}, which isolates the diseased component of every data point/vector by removing the normal component from all points. They hypothesize that data from diseased tissue can be summarized into the following equation: $\vec{T} = Nc.\vec{T} + Dc\vec{T}$, and they would like to isolate $Dc\vec{T}$. If two genes perform a similar function in the context of a disease, then their gene expression data should remain close after this dimensionality reduction. After finding these genes and reducing the dimension we performed three types of cluster analysis on the data, using the Biological Homogeneity Index (BHI), a method introduced by Datta \& Datta in 2006 \cite{bhi}, to compare the functional significance of the clusters produced by Mapper, K-Means, and Hierarchical Clustering. To find the optimal clustering of the genes we performed a grid analysis across the parameters for Mapper: number of intervals, overlap between intervals, and number of bins to use when clustering in the intervals. Mapper also takes a point-wise distance matrix as an input, and for this we experimented with both the Pearson and Spearman metrics, finding optimal results with Pearson. For each set of parameters to Mapper we took the number of vertices in the outputted graph, and set that to k for K-Means, and cut the Hierarchical Clustering tree at the level which would produce that many clusters. By looking at the clustering which produced the optimal BHI for Mapper, which happened to be the clustering which had the highest difference in performance compared to the other two methods, we argue that the clustering produced by Mapper is more biologically significant than the other methods. To do so we continued with a more detailed analysis of the contents of the clusters. \section{Results} \subsection{General Mapper Comparison} Searching through hundreds of parameter combinations we found that for GDS1439, the BHI of Mapper's clustering was noticeably larger than that of either K-Means or Hierarchical Clustering, although not outside of a standard deviation. For the clusterings where hundreds of genes were placed in each cluster there was no noticeable difference, but once the number of clusters was past 100 the BHI's of the Mapper clusters had a noticeable improvement. This result seems somewhat intuitive if you accept the hypothesis that Mapper produces functionally significant clusters; with hundreds of genes in a single cluster there are bound to be many unrelated genes and thus a lot of noise. Once the number of genes in a single cluster is reasonably small the opportunity for a method specifically aimed at discovering functional significance to show its worth is realizable. Tables 1 \& 2 show the clusterings' BHI's, for all genes, as well as just the differentially expressed genes in each cluster. Figure 1 shows the relationship between BHI and number of clusters for each method. \begin{figure} \includegraphics[width=\linewidth]{plotTrend} \caption{As the number of clusters rises, the BHI of Mapper clusterings separates itself} \label{bhi-trend} \end{figure} \begin{table}[] \centering \caption{BHI's for GDS1439's clusters, as well as just the differentially expressed genes within a cluster. Error bars are standard deviations for each set of output BHI's} \label{table-bhi-1439} \begin{tabular}{llllllll} & Mapper & H-Clust & K-Means & Mapper-DEG & H-Clust-DEG & K-Means-DEG & Obs \\ Pearson & $.3429 \pm .030$ & $.3275 \pm .022$ & $.3240 \pm .025$ & $ .3516 \pm .016$ & $ .3370 \pm .010 $ & $ .3300 \pm .018 $ & 759 \\ Spearman & $.3538 \pm.013$ & $.3462 \pm .012$ & $.3396 \pm .038$ & $ .3139 \pm .039$ & $ .3285 \pm .032$ & $ .3400 \pm .038 $ & 520 \end{tabular} \end{table} \begin{table}[] \centering \caption{BHI's for GDS5437} \label{table-bhi-5437} \begin{tabular}{llllllll} & Mapper & H-Clust & K-Means & Mapper-DEG & H-Clust-DEG & K-Means-DEG & Obs \\ Pearson & $.3074 \pm .012$ & $.3266 \pm .017 $ & $ .2990 \pm .006$ & $ .3023 \pm .022$ & $ .3205 \pm .022$ & $ .3218 \pm .033$ & 264 \\ Spearman & $.3253 \pm .009$ & $ .3368 \pm.019 $ & $.2526 \pm .031$ & $ .2739 \pm .028$ & $ .2196 \pm .022$ & $ .2526 \pm .033$ & 550 \end{tabular} \end{table} While the results were promising for GDS1439, they were not for GDS5347. In the latter, hierarchical clustering produced the best BHI results for complete clusters, and K-Means did best for just differentially expressed genes. While BHI is a good metric for an at-glance look at the functional significance of each clustering method we believe more analysis is necessary before we can fully argue for the benefits of Mapper. To do so we go further into our analysis of GDS1439 with three types of analysis. We found the optimal Mapper parameters of overlap, intervals, and bins, to be 26, 20, and 35, which resulted in a BHI of .402 for Mapper, and 0.332 and 0.340 for H and K Clustering respectively. After choosing these parameters we compared the functions of the genes in each cluster, the pathways where those genes operate, as well as a Gold Standard analysis of the clustering destination of genes which are known to be related to prostate cancer. \subsection{Gold Standard Analysis} To analyze the clustering we compiled a gold standard of genes known to be related to prostate cancer from the Genetics Home Reference \cite{pcgenes}. On obtaining the optimal parameter combination of overlap, intervals and bins, for which the BHI values of Mapper are significantly higher than K-means and Hierarchical clustering, we analyzed where the gold standard genes for each data set end up in each method. We believe that if gold standard genes are clustered together by Mapper, but not by the other methods, this provides strong evidence that Mapper produces clusters of functional significance. The clustering destination of our gold standard genes is show in in Figure 2. \begin{figure} \centering \begin{subfigure}{.5\textwidth} \centering \includegraphics[width=1\linewidth]{goldstandard1.png} \label{fig:sub1} \end{subfigure}% \begin{subfigure}{.5\textwidth} \centering \includegraphics[width=1\linewidth]{goldstandard2.png} \label{fig:sub2} \end{subfigure} \caption{The clustering destination of the gold standard genes for each method.} \label{fig:test} \end{figure} On performing clustering analysis of the Gold Standard genes, we found that most of the genes end up between Mapper clusters 47-50, whereas no such pattern emerged in K-means or Hierarchical clustering. This is strong evidence that Mapper has the ability to discover biological significance between genes clustered together. Mapper's concepts of edges between clusters give it the ability to indicate inter-cluster similarity. Hierarchical clustering's tree encodes a similar concept. Clusters 47-50 in Mapper are connected together, so not only did most of the gold standard genes end up in three clusters, but those clusters are all neighbors and share common data points. In Hierarchical clustering the gold-standard genes did not end up anywhere close to each other on the tree. This is strong evidence for the benefits of Mapper. We believe this also provides evidence that other genes ending up in the significant Mapper clusters could be studied to check if they relate to prostate cancer. Since the genes we know are significant all end up in the same place, maybe genes whose significance is not yet known end up there as well. For GDS5437 we were not able to compile a Gold Standard of genes which are related to breast cancer in mice, thus we were not able to perform a similar analysis. \subsection{Gene Function Analysis} Using the feature data in the GDS file we mapped each gene to its biological functions. For each biological function we found the set of genes performing that function and performed an enrichment analysis on the differentially expressed genes performing each gene function, using Fisher's Exact test. For each clustering method, we took the gene functions with the 15 smallest p-values and analyzed the clusters in which these genes were placed. Table 3 shows the most significant functions that are differentially expressed. On performing a cluster analysis of these gene functions we observed that Mapper not only groups the genes performing the same gene function together, it also clusters genes performing significantly expressed gene functions together. Most of the clustering has happened between clusters 41-51. None of these patterns are observed in K-means or Hierarchical clustering. We believe these significant gene functions can be studied relating to their role in prostate cancer. \begin{table}[] \centering \caption{Significant gene functions} \label{my-label} \begin{tabular}{ll} Gene Function & P-Value \\ beta-2 adrenergic receptor binding & .0003 \\ actin filament binding & .0004 \\ corticotropin-releasing hormone receptor 1 binding & .0005 \\ ion channel binding & .0006 \\ growth factor activity & .0008 \\ iron ion binding & .001 \\ MHC class II receptor activity & .0013 \\ RNA polymerase II transcription & .0015 \\ phosphatidylinositol phospholipase C activity & .0017 \\ calcium ion transmembrane transporter activity & .0018 \end{tabular} \end{table} \subsection{Pathway Analysis} We used Reactome biological pathway database for our pathway analysis data. For each pathway, we found the set of genes acting in that pathway which were contained in our expression data. We then performed a pathway enrichment analysis using Fisher's Exact test. We concentrated our analysis on the pathways with the 10 smallest p-values, and identified which genes act in these pathways and which clusters these genes end up in. Table 4 shows the most significantly enriched pathways. \begin{table}[] \centering \caption{Significant pathway functions} \label{my-label} \begin{tabular}{ll} Pathway Name & P-Value \\ Cell-extracellular matrix interactions & .084 \\ Synthesis of Prostaglandins (PG) and Thromboxanes (TX) & .084 \\ Synthesis of 15-eicosatetraenoic acid derivatives & .124 \\ Activations of genes by ATF4 & .156 \\ eNOS activation & .156 \\ Scavenging by Class F Receptors & .156 \\ 02/CO2 exchange in erythrocytes & .189 \\ Uptake of Carbon Dioxide and Release of Oxygen by Erythrocytes & .189 \\ Uptake of Oxygen and Release of Carbon Dioxide by Erythrocytes & .189 \end{tabular} \end{table} The following pathways had their genes clustered in Mapper clusters 45,46,47 : Uptake of Oxygen and release of Carbon Dioxide by Erythrocytes, Uptake of Carbon Dioxide and release of Oxygen by Erythrocytes, Activation of genes by ATF4. There has been no previous interaction between the ATF4 Pathway and the other 2 pathways. Meaningful interactions between pathways can be discovered if the genes acting in those pathways are clustered together by Mapper. We believe this indicates these pathways warrant further investigating in relation to prostate cancer. It must be noted, however, that the P-values for the pathways are only of borderline significance, thus the proportion of differentially expressed genes operating in these pathways is of debatable significance. For GDS5437, only one differentially expressed gene was acting in some of the pathways, and the enrichment analysis failed to return significant p-values. Hence, no actual pathway analysis could be performed on this dataset. \section{Discussion} Our discoveries on GDS1439 were promising. All of our methods of analysis showed Mapper to be a superior method in terms of functional analysis. On the other hand, our preliminary analysis on GDS5437 did not give any indication of an advantage to Mapper, and we were not able to perform any further analysis data set. Our goal, however, is to show that Mapper can be used as a method to discover functional significance, not that it will always produce clusterings of functional significance. One thing we noticed when working with Mapper initially was that it is very sensitive to parameter choices. Even in the introductory example of uncovering the underlying structure of a data set of points shaped like a figure-8 changing the given parameters slightly caused the algorithm to produce an output that seemingly had no relation to the initial data set. We believe that when working with this method it is necessary to spend significant amount of time discovering the optimal parameters. Only after these parameters have been found is it worth deeply analyzing the contents of the output. It took hundreds of parameter combinations before we found the optimal output, but once we did the analysis showed great evidence of functionally significant clustering. For pathways, clusters 45, 46, and 47 were of note. For our gold standard genes they were very concentrated in clusters 47-50, and the important gene functions were all from genes in clusters 41-50. These clusters were all part of the same "level", Mapper's concept of a connected component. The fact that our significant pathways as well as gold standard genes and significant functions were all clustered in the same region, while this wasn't the case at all for any other clustering method, is strong evidence for Mapper's effectiveness of producing functionally significant clusters. We believe that a more biologically in depth study on prostate cancer would benefit by looking at the genes/functions/pathways contained in this connected component. \subsection{Limitations} Regardless of the lack of gene function/pathway/gold standard analysis on GDS5437 the BHI results were not promising. There was no general trend that favored Mapper's clustering, and Mapper's clustering was only better than the other two with a frequency expected by chance. One possible reason for this was that the gene expression data was taken from lung tissue sample for mice with breast cancer. It is possible that because the tissue samples were not taken from the same region as the cancer that the diseased component of the data points was less significant. When we saw these results and realized we would not be able to perform any of our further types on analyses on this data we focused our efforts on GDS1439. Taking more time to carefully select a second dataset through which we would have been able to perform the full analysis is where we could have improved this research most. \section{Conclusion} If we were to go deeper into this analysis we would analyze more data sets to see if we could produce similar results. Only two data sets were used in this study and only one was successful. While we are arguing for the general abilities of the Mapper method, a positive result on one dataset is not enough to fully confirm our hypothesis. We believe our method of analysis provides a good framework for extending this research, and can be applied to other datasets with limited effort. In addition, there is nothing specific to cancer about our analysis. We believe this method is easily transferrable to a wide range of diseases/disorders. In addition, we built the code base with the idea of being able to apply it to different gene expression data with as much ease as possible. We believe this provides a good framework for a quick look at areas of functional significance for a disease, and could serve as a tool to point researchers in the right direction for more in-depth study. %% The Appendices part is started with the command \appendix; %% appendix sections are then done as normal sections %% \appendix %% \section{} %% \label{} %% References %% %% Following citation commands can be used in the body text: %% Usage of \cite is as follows: %% \cite{key} ==>> [#] %% \cite[chap. 2]{key} ==>> [#, chap. 2] %% \citet{key} ==>> Author [#] %% References with bibTeX database: \section{Citations} \begin{thebibliography}{2} \bibitem{mapper} <NAME>, <NAME>, <NAME> (2007) in Eurographics Symposium on Point-Based Graphics, Topological methods for the analysis of high dimensional data sets and 3D object recognition, eds Botsch M, Pajarola R (Eurographics Association, Geneva), pp 91?100. \bibitem{dsga} <NAME>, <NAME>, <NAME>, <NAME>. Disease-specific genomic analysis: Identifying the signature of pathologic biology. Bioinformatics. 2007;23:957?965. \bibitem{nicolau}<NAME>, <NAME>, <NAME> \bibitem{RNA} <NAME>, et al. Structural insight into RNA hairpin folding intermediates. J Am Chem Soc. 2008;130:9676?9678. Proc. Natl. Acad. Sci. U. S. A., 108 (2011), pp. 7265?7270 \bibitem{gds5437}<NAME>, <NAME>, <NAME>, <NAME> et al. Granulocyte-colony stimulating factor promotes lung metastasis through mobilization of Ly6G+Ly6C+ granulocytes. Proc Natl Acad Sci U S A 2010 Dec 14;107(50):21248-55. PMID: 21081700 \bibitem{gds1439}<NAME>, <NAME>, <NAME>, Rhodes DR et al. Integrative genomic and proteomic analysis of prostate cancer reveals signatures of metastatic progression. Cancer Cell 2005 Nov;8(5):393-406. PMID: 16286247 \bibitem{genefilter} <NAME>, <NAME>, <NAME> and <NAME> (2016). genefilter: genefilter: methods for filtering genes from high-throughput experiments. R package version 1.54.2. \bibitem{pcgenes} Prostate cancer - Genetics Home Reference. (n.d.). Retrieved November 01, 2016, from https://ghr.nlm.nih.gov/condition/prostate-cancer \bibitem{clustereval} Chen, Gengxin. "Evaluation and comparison of clustering algorithms in analyzing es cell gene expression data." Statistica Sinica 12.1, A Special Issue on Bioinformatics (2002): 241-62. JSTOR. Web. 01 Nov. 2016. \bibitem{bhi} Methods for evaluating clustering algorithms for gene expression data using a reference set of functional classes. <NAME>, <NAME> BMC Bioinformatics. 2006; 7: 397. Published online 2006 Aug 31. doi: 10.1186/1471-2105-7-397 PMCID: PMC1590054 \end{thebibliography} %% Authors are advised to submit their bibtex database files. They are %% requested to list a bibtex style file in the manuscript if they do %% not want to use model1-num-names.bst. %% References without bibTeX database: %% \bibitem must have the following form: %% \bibitem{key}... %% % \bibitem{} \end{document} %% %% End of file `elsarticle-template-1-num.tex'.<file_sep>/App-Directory/goldStandardAnalysis.R goldStandardBreastCancer <- c('BRCA1', 'BRCA2', 'ATM', 'BARD1', 'BRIP1', 'CASP8', 'CDH1', 'CHEK2', 'CTLA4', 'CYP19A1','FGFR2', 'H19', 'LSP1', 'MAP3K1', 'MRE11', 'NBN', 'PALB2', 'PTEN', 'RAD51', 'RAD51C', 'STK11', 'TERT', 'TOX3', 'TP53', 'XRCC2', 'XRCC3') #goldStandardLungCancer <- c('ATK1', 'ALK', 'BRAF', 'DDR2', 'EGFR', 'ERBB2', 'KRAS', 'MAP2K1', 'NRAS', 'PIK3CA', 'PTEN', 'RET', 'RIT1', 'ROS1') goldStandardProstateCancer <- c('AR', 'BRCA1', 'BRCA2', 'CD82', 'CDH1', 'CHEK2', 'EHBP1', 'ELAC2', 'EP300', 'EPHB2', 'EZH2', 'FGFR2', 'FGFR4', 'GNMT', 'HNF1B', 'HOXB13', 'HPCX', 'IGF2', 'ITGA6', 'KLF6', 'LRP2', 'MAD1L1', 'MED12', 'MSMB', 'MSR1', 'MXI1', 'NBN', 'PCAP', 'PCNT', 'PLXNB1', 'PTEN', 'RNASEL', 'SRD5A2', 'STAT3', 'TGFBR1', 'WRN', 'WT1', 'ZFHX3') # # breastQuery <- queryMany(goldStandardBreastCancer, scopes="symbol", fields=c("uniprot", "ensembl.gene", "reporter"), species="human") # prostateQuery <- queryMany(goldStandardProstateCancer, scopes="symbol", fields=c("uniprot", "ensembl.gene", "reporter"), species="human")' # # # # why do these queries cme back with some info #### when done in batches but not one at a time # # thisGene <- featureData[1, "Gene ID"] # geneSearch <- getGene(thisGene) goldstandardprostateaffymapping = AnnotationDbi::select(hgu133a.db,keys=rownames(affy_exp),"SYMBOL") goldstandardprostateaffynames = goldstandardprostateaffymapping$PROBEID[which(goldstandardprostateaffymapping$SYMBOL %in% goldStandardProstateCancer)] goldstandardmappercluster = (lapply(goldstandardprostateaffynames,getVertexForGene)) names(goldstandardmappercluster) = goldstandardprostateaffynames goldstandardmappercluster = unlist(goldstandardmappercluster) goldstandardhcluster = hclusters.clusts[which(names(hclusters.clusts) %in% goldstandardprostateaffynames)] goldstandardkcluster = kclust$cluster[which(names(kclust$cluster) %in% goldstandardprostateaffynames)] <file_sep>/App-Directory/kmeans.R numcenters <- m1$num_vertices kclust <- kmeans(affy_fil, centers=numcenters, iter.max=50) bhikclust <- BHI(kclust$cluster, annotation="moe430a.db", names=names(kclust$cluster), category="all") #do pca for top 2 # tbpca <- tbl_df(pca[[2]]) # top2 <- tbpca[, 1:2] # pcaseach <- as.matrix(features[,4:length(features)]) %*% as.matrix(top2) # # # pcaMeans <- kmeans(pcaseach, input$clusters) # # output$plot1 <- renderPlot({ # par(mar = c(5.1, 4.1, 0, 1)) # plot(pcaseach, # col = clusters()$cluster, # pch = 20, cex = 3) # points(clusters()$centers, pch = 4, cex = 4, lwd = 4) # })<file_sep>/App-Directory/gridAnalysis.R gridSearch = TRUE #grid.overlap <- seq(from=10, to=30, by=2) grid.overlap <- c(5,10,15, 20) #grid.intervals <- c(18, 20, 22, 24, 26, 28) grid.intervals <- seq(from=10, to=30, by=2) grid.bins <- seq(from=10, to=20, by=1) grid.results <- data.frame() #build data frame #loop through all grid values, set them to mapper values, source analysis, add results to dataframe for(ovlp in grid.overlap){ m1.overlap = ovlp for(intv in grid.intervals){ m1.intervals = intv for(mbins in grid.bins){ m1.bins = mbins debug.print(paste("Doing mapper analysis with (overlap, intervals, bins)", ovlp, intv, mbins, sep="-")) #catch exceptions cuz mapper doesnt like some inputs were gonna give try({ source("./analysis.R"); results <- c(ovlp, intv, mbins, m1$num_vertices, length(diff_genes), m1.bhi, hclusters.bhi, kclust.bhi, m1.bhiDiffGenes, hclusters.bhiDiffGenes, kclust.bhiDiffGenes) grid.results <- rbind(grid.results, results) debug.print(results) }) } } } colnames(grid.results) <- c("overlap", "intervals", "bins", "num verticies","numDiffexp", "mapperBHI", "hclustBHI", "kclustBHI", "mapperDiffBHI", "hclustBHIDiff", "kclustBHIDiff") gridSearch = FALSE print(mean(grid.results$mapperBHI)) print(mean(grid.results$hclustBHI)) print(mean(grid.results$kclustBHI)) print(mean(grid.results$mapperDiffBHI)) print(mean(grid.results$hclustBHIDiff)) print(mean(grid.results$kclustBHIDiff))<file_sep>/App-Directory/mousepath.R uni2 <- as.matrix(read.delim(file = "pathways_summary.txt",skip=1,header=T,sep ="\t")) uni2 = tbl_df(uni2) uni2 = uni2[,-1] uni2 = uni2[,-2] mappingmouse = AnnotationDbi::select(moe430a.db,keys=diff_genes,"SYMBOL") genetosymbol = function(geneid){return(mappingmouse$SYMBOL[which(mappingmouse$PROBEID %in% geneid)[1]])} #filtering out the pathways with unacceptable occurences uni3 = count(uni2,PW.NAME) uni3 = uni3[((uni3$n>5) & (uni3$n<500)),] #function to map gene names to uniprot names l3 = list() #this list shall be of the form where the first element in each sublist is the pathway, #and all the following elements are the genes in that pathway colnames(uni3)=c("V2","n") colnames(uni2)=c("V1","V2") for(i in 1:length(uni3$V2)){ l3[[i]]=c(as.character(uni3$V2[i]),unlist(list(as.character(uni2$V1[uni2$V2 %in% uni3$V2[i]])))) } diff_genes_mouse = unlist(lapply(diff_genes,genetosymbol)) diff_genes_mouse = diff_genes_mouse[-which(is.na(diff_genes_mouse))] #for BIOLOGICAL FUNCTIONS , just needs to be in the same form as l3 #function to calculate number of differentially expressed genes in each pathway numdiffgenesinpathway = function(pathwaygenes){return(length(which(pathwaygenes %in% diff_genes_mouse)))} diffgenesinpathway = function(pathwaygenes){return(unlist(pathwaygenes[which(pathwaygenes %in% diff_genes_mouse)]))} pathwaydiffcount=list()#this list has the number of differentially expressed genes for the pathway at the same index for(i in 1:length(l3)){ pathwaydiffcount[[i]]=numdiffgenesinpathway(l3[[i]][-1]) } pathwaydiffgenes=list()#this list has the number of differentially expressed genes for the pathway at the same index for(i in 1:length(l3)){ pathwaydiffgenes[[i]]=diffgenesinpathway(l3[[i]][-1]) } pathwaydiffcount=unlist(pathwaydiffcount) contingency=matrix(nrow=2,ncol=2); #function to execute fisher test for each pathway getpvaluefromfisher=function(i){ contingency[1,1]=pathwaydiffcount[i]; contingency[1,2]=length(l3[[i]][-1])-length(contingency[1,1]); contingency[2,1]=length(diff_genes)-length(contingency[1,1]); contingency[2,2]=length(rownames(affy_fil))-length(diff_genes)-length(contingency[1,2]); return(fisher.test(as.matrix(contingency),alternative = "greater")) } pvaluefromfisher=lapply(seq(from=1,to=144),getpvaluefromfisher) #function to find false discovery rates deg_pathway_fdr_func <-function(i){return(p.adjust(pvaluefromfisher[[i]]$p.value,method="fdr"))} deg_pathway_fdr=unlist(lapply((seq(from=1,to=144)),deg_pathway_fdr_func)) #get the pvalue for each pathway pvalue=vector() for(i in 1:length(pvaluefromfisher)){pvalue[i]=pvaluefromfisher[[i]]$p.value} #construct the resultant matrix which is of the form pathwayname,fdr,pvalue and order it by increasing p-values result_matrix=cbind(uni3$V2,pvalue,deg_pathway_fdr) colnames(result_matrix)=c('Pathway','P-value','FDR') deg_order=order(pvalue) result_matrix=result_matrix[deg_order,] <file_sep>/App-Directory/geneFunctions.R geneFuncs <- featureData[, "GO:Function ID"] getFunctionIdsForGene <- function(gene){ theseFunctions <- as.character(featureData[gene, "GO:Function ID"]) return(unlist(strsplit(theseFunctions, "///"))) } getFunctionNamesForGene <- function(gene){ theseFunctions <- as.character(featureData[gene, "GO:Function"]) return(unlist(strsplit(theseFunctions, "///"))) } getFunctionsFromGeneList <- function(genes, max = length(genes)){ byGenes <- lapply(genes, getFunctionNamesForGene) return(sort(table(unlist(byGenes)),decreasing=TRUE)[1:max]) } stringifyData <- function(rw){ funcs <- names(rw) vals <- unname(rw) firstCollapse <- apply(t(rbind(funcs, vals)), 1, paste, collapse = ":") return(paste(firstCollapse, collapse = ", ")) } getFunctionsInAnalysisFormat <- function(genes, max = length(genes)){ byGenes <- lapply(genes, getFunctionNamesForGene) return(byGenes) } genesandtheirfunctions = lapply(rownames(affy_fil),getFunctionsInAnalysisFormat) genesandtheirfunctions = lapply(genesandtheirfunctions,unlist) listofgenefunctions = unique(unlist(genesandtheirfunctions)) debug.print("GENE FUNCTIONS") #what are the functions of the diff expressed genes functionDiffexpressedFrequency <- getFunctionsFromGeneList(diff_genes) #how many gene functions do we have #numFunctions <- length(unique(unlist(funcByGene))) #for mapper clusters, find their top function m1.clusterFunctions <- lapply(lapply(cluster_list, getGeneIdsByMapperCluster), getFunctionsFromGeneList) m1.topFunctionsByCluster <- lapply(lapply(cluster_list, getGeneIdsByMapperCluster), getFunctionsFromGeneList, 4) m1.topDiffexpFunctionsByCluster <- lapply(lapply(cluster_list, getGeneIdsByMapperCluster, justDiffexp=TRUE), getFunctionsFromGeneList, 10) #functions from all genes allFunctions <- getFunctionsFromGeneList(geneIds) allFunctions.total <- sum(allFunctions[complete.cases(allFunctions)]) hclusters.clusterFunctions <- lapply(hclusters.regularClusteredGenes, getFunctionsFromGeneList) hclusters.topHClusterFunctions <- lapply(hclusters.regularClusteredGenes, getFunctionsFromGeneList, 4) hclusters.topHClusterDiffexpFunctions <- lapply(hclusters.regularClusteredGenesDiffexp, getFunctionsFromGeneList, 10) #Gold standard genes, going to need to map these to affymetrix ids #write table for UI m1.topFunctionString <- lapply(m1.topFunctionsByCluster, stringifyData) m1.topDiffexpFunctionString <- lapply(m1.topDiffexpFunctionsByCluster, stringifyData) m1.tableData <- rbind(as.integer(cluster_list), pct_diffexp, num_diffexp, totalInMapperClusters, m1.topFunctionString, m1.topDiffexpFunctionString ) rownames(m1.tableData) <- c("cluster", "% diffexp", "num_diffexp", "total", "functions", "Diffexp functions"); hclusters.topHClustFunctionString <- lapply(hclusters.topHClusterFunctions, stringifyData) hclusters.topHClustDiffexpFunctionString <- lapply(hclusters.topHClusterDiffexpFunctions, stringifyData) hclusters.tableData <- rbind(as.integer(cluster_list), pct_diffexp_reg, num_diffexp_by_reg, hclusters.totalInCluster, hclusters.topHClustFunctionString, hclusters.topHClustDiffexpFunctionString) #what are the functions of just the differentially expressed genes debug.print("building mapper nodes") MapperNodes <- mapperVertices(m1, geneIds) MapperLinks <- mapperEdges(m1) rnk <- round(pct_diffexp*100) MapperNodes$pctdiffexp <- round(pct_diffexp*100) unq <- unique(rnk) colorRampMap <- colorRampPalette(c('blue', 'red'))(max(unq))[rank(unq)] jsColorString <- paste(paste("[\"", paste(colorRampMap, collapse="\",\"")), "\"]") <file_sep>/App-Directory/analysis.R #mapper inputs if(!exists("gridSearch") || !gridSearch ){ #these are not the optimal parameters from the study but they make a prettier graph m1.overlap = 15 m1.intervals = 16 m1.bins = 22 #optimal bhi params # m1.overlap = 26 # m1.intervals = 20 # m1.bins = 35 } debug.print("analysis run") if(!exists("affy_exp")){ debug.print("loading data") source("./loadData.R") } time1 <-proc.time() m1 <- mapper1D( distance_matrix = corr, filter_values = filterforfil3, num_intervals = m1.intervals, percent_overlap = m1.overlap, num_bins_when_clustering = m1.bins) g1 <- graph.adjacency(m1$adjacency, mode="undirected") cluster_list <- seq(from = 1, to = m1$num_vertices) time2 <- proc.time() debug.print(paste("mapper done", time2-time1)) #so what genes end up where, get colors for plot geneToMapperCluster = list() for(i in 1:max(m1$level_of_vertex)){ verts = m1$points_in_level[[i]]; for(p in verts){ geneToMapperCluster[p] = i; } } geneToMapperVertex = list() for(i in 1:m1$num_vertices){ verts = m1$points_in_vertex[[i]]; for(p in verts){ geneToMapperVertex[p] = i } } getVertexForGene <- function(gene){ indx <- which(geneIds == gene); return(unlist(geneToMapperVertex[indx])) } getClusterForGene <- function(gene){ indx <- which(geneIds == gene); return(unlist(geneToMapperCluster[indx])) } diff_exp_clusters <- unlist(lapply(diff_genes, getClusterForGene)) diff_exp_vertices <- unlist(lapply(diff_genes, getVertexForGene)) #which genes are differentially expressed by index diff_gene_nums <- lapply(diff_genes, function(gene){which(geneIds == gene)}) getPropDiffexp <- function(vert){ diff_expressed <- getNumDiff(vert) return(diff_expressed/length(m1$points_in_vertex[[vert]])) } getNumDiff<- function(vert){ return(sum(m1$points_in_vertex[[vert]] %in% diff_gene_nums)) } pct_diffexp <- unlist(lapply(cluster_list, getPropDiffexp)) num_diffexp <- unlist(lapply(cluster_list, getNumDiff)) #get actual gene name by geneId, get that by cluster dtt <- Table(gds) refToId <- data.frame(as.character(dtt$IDENTIFIER)) rownames(refToId) <- as.character(dtt$ID_REF) geneIdToName <- function(id){return(as.character(refToId[id, 1]))} getGeneIdByIndex <- function(indx){return(geneIds[indx])} getindexofgene<- function(geneinput){return(which(geneIds==geneinput))} getGeneIdsByMapperCluster <- function(cluster, justDiffexp = FALSE){ genes <- lapply(m1$points_in_vertex[[cluster]], getGeneIdByIndex); if(justDiffexp){ genes <- genes[unlist(genes) %in% diff_genes] } return(unlist(genes)) } getGeneNamesByCluster <-function(cluster){ return(unlist(lapply(getGeneIdsByMapperCluster(cluster),geneIdToName))) } allClustersGenes <- lapply(cluster_list, getGeneNamesByCluster) totalInMapperClusters <- unlist(lapply(allClustersGenes, length))# how does normal clustering do? # if multiple clusters, whys that # regardless of multiple or single, what genes were not significantly expressed # but are in the same cluster as the significantly expressed ones any significance to these #normal hierarchical clustering time3<-proc.time() debug.print(paste("staring h clust", time3-time2)) hclusters <- hclust(dsy) dend <- as.dendrogram(hclusters) #cut tree where clusters = num verticies for mapper hclusters.clusts <- cutree(hclusters, k=m1$num_vertices) geneToClusterReg <- list() for(i in 1:length(hclusters.clusts)){ geneToClusterReg[i] = as.numeric(hclusters.clusts[i]) } #number of diffexp genes in regular cluster getNum_reg <- function(clusternumber){ inThisCluster <- which( geneToClusterReg == clusternumber ); return(length(which(inThisCluster %in% diff_gene_nums ))); } #proportion diffexp genes reg cluster getPropDiffexp_reg <- function(clusternumber){ inThisCluster <- which( geneToClusterReg == clusternumber ); whatsDiffExp <- which( inThisCluster %in% diff_gene_nums ); return(length(whatsDiffExp)/length(inThisCluster)); } cluster_list <- seq(from = 1, to = m1$num_vertices) pct_diffexp_reg <- unlist(lapply(cluster_list, getPropDiffexp_reg)) num_diffexp_by_reg <-unlist(lapply(cluster_list, getNum_reg)) clusters <- lapply(cluster_list, function(clusternumber){ return(which(geneToClusterReg %in% clusternumber)) } ) hclusters.totalInCluster <- unlist(lapply(clusters, length)) getGenesInCluster <- function(list, justDiffexp = FALSE){ genes <- unlist(lapply(list, getGeneIdByIndex)) if(justDiffexp){ genes <- genes[unlist(genes) %in% diff_genes] } return(genes) } hclusters.regularClusteredGenes <- lapply(clusters, getGenesInCluster) hclusters.regularClusteredGenesDiffexp <- lapply(clusters, getGenesInCluster, justDiffexp = TRUE) Genebelongstocluster <- vector() for(i in 1:m1$num_vertices){ for(j in 1:length(m1$points_in_vertex[[i]])){ Genebelongstocluster = c(Genebelongstocluster,i) } } time4 <- proc.time() debug.print(paste("stariting k clust", time4-time3)) #do kmeans clustering source("./kmeans.R") #do gene function analysis source("./geneFunctions.R") source("./genefunctions2.R") #do BHI evaluation source("./BHIcomparison.R") #do pathway analysis source(pathwayFile) source("./pathwayAnalysis.R")
c00e815c3f3efe2ceb6881289e924460f8586b87
[ "Markdown", "R", "TeX" ]
18
Markdown
cdepeuter/bioinfomatics
bde29405f34a41d96d1da3d3da14a84117616233
b04028e3e741c662b059980c1ca15b5e4ab9411b
refs/heads/master
<file_sep>// // xibpageTests.h // xibpageTests // // Created by <NAME> on 13-6-12. // Copyright (c) 2013年 <NAME>. All rights reserved. // #import <SenTestingKit/SenTestingKit.h> @interface xibpageTests : SenTestCase @end <file_sep>// // xibpageTests.m // xibpageTests // // Created by <NAME> on 13-6-12. // Copyright (c) 2013年 <NAME>. All rights reserved. // #import "xibpageTests.h" @implementation xibpageTests - (void)setUp { [super setUp]; // Set-up code here. } - (void)tearDown { // Tear-down code here. [super tearDown]; } - (void)testExample { STFail(@"Unit tests are not implemented yet in xibpageTests"); } @end <file_sep>// // ViewController.m // xibpage // // Created by <NAME> on 13-6-12. // Copyright (c) 2013年 <NAME>. All rights reserved. // #import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; webview.delegate = self; NSString *resourcePath = [[NSBundle mainBundle] resourcePath]; NSLog(@"path %@",resourcePath); NSString *filePath =[resourcePath stringByAppendingPathComponent:@"index.html"]; NSLog(@"filepath %@",filePath); NSString *html = [[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil]; NSLog(@"html %@",html); [webview loadHTMLString:html baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle]bundlePath]]]; // Do any additional setup after loading the view, typically from a nib. } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } -(IBAction)goUrl:(id)sender{ url=[NSURL URLWithString:text.text]; req = [NSURLRequest requestWithURL:url]; [webview setScalesPageToFit:YES]; [webview setDelegate:self]; [webview loadRequest:req]; [text resignFirstResponder]; } - (void)backgroundTap:(id)sender{ [text resignFirstResponder]; } // webview delegate - (void) webViewDidStartLoad:(UIWebView *)webView { //创建UIActivityIndicatorView背底半透明View UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)]; [view setTag:108]; [view setBackgroundColor:[UIColor blackColor]]; [view setAlpha:0.5]; [self.view addSubview:view]; activityIndicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 32.0f, 32.0f)]; [activityIndicator setCenter:view.center]; [activityIndicator setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhite]; [view addSubview:activityIndicator]; [activityIndicator startAnimating]; NSLog(@"webview start load"); } - (void) webViewDidFinishLoad:(UIWebView *)webView { [activityIndicator stopAnimating]; UIView *view = (UIView*)[self.view viewWithTag:108]; [view removeFromSuperview]; href=[webview stringByEvaluatingJavaScriptFromString:@"document.location.href"]; NSLog(@"href: %@",href); NSLog(@"webview finish load"); } - (void) webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error { [activityIndicator stopAnimating]; UIView *view = (UIView*)[self.view viewWithTag:108]; [view removeFromSuperview]; NSLog(@"error: %@",error); } - (BOOL) webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{ NSLog(@"shouldStartLoadWithRequest %@",[[request URL]scheme]); if([[[request URL]scheme] isEqualToString:@"jsbridge"]){ [webview stopLoading]; [webview stringByEvaluatingJavaScriptFromString:@"window.showSomething('yes')"]; NSLog(@"url: %@",[request URL]); //[[UIApplication sharedApplication]openURL:[request URL]]; //[self.navigationController popViewControllerAnimated:YES]; return NO; }else{ return YES; } } @end <file_sep>// // ViewController.h // xibpage // // Created by <NAME> on 13-6-12. // Copyright (c) 2013年 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> @interface ViewController : UIViewController<UIWebViewDelegate>{ IBOutlet UIWebView *webview; IBOutlet UIButton *button; IBOutlet UITextField *text; NSURL *url; NSString *href; NSURLRequest *req; UIActivityIndicatorView *activityIndicator; //NSString *resourcePath; } -(IBAction)goUrl:(id)sender; -(IBAction)backgroundTap:(id)sender; @end
70054ee732306f22e536e252e4ba58fd4944e7e5
[ "Objective-C" ]
4
Objective-C
suboy/xibpage
a1a26ced580d15e23f3d038a8e931c491443f3b7
ff7b2575623fa725e3d3cf53ef687f562f74447d
refs/heads/main
<file_sep>import React, { useState } from 'react'; import filtro from '../assets/icones/filtro.svg'; export const Filtros = props => { const {periodoDe, periodoAte, status, setPeriodoDe, setPeriodoAte, setStatus} = props; const [showFiltros, setShowFiltro] = useState(false); return ( <div className="container-filtros"> <div className="title"> <span>Tarefas</span> <img src={filtro} alt="Filtrar tarefas" onClick={() => setShowFiltro(!showFiltros)} /> <div className="form"> <div> <label>Data prevista de conclusão de:</label> <input type="date" value={periodoDe} onChange={evento => setPeriodoDe(evento.target.value)}/> </div> <div> <label>até:</label> <input type="date" value={periodoAte} onChange={evento => setPeriodoAte(evento.target.value)}/> </div> <div className="line" /> <div> <label>Status:</label> <select value={status} onChange={evento => setStatus(evento.target.value)}> <option value={0}>Todas</option> <option value={1}>Ativas</option> <option value={2}>Concluídas</option> </select> </div> </div> </div> {showFiltros === true && ( <div className="filtrosMobile"> <div> <label>Período de:</label> <input type="date" /> </div> <div> <label>Período até:</label> <input type="date" /> </div> <div> <label>Status:</label> <select> <option value={0}>Todas</option> <option value={1}>Ativas</option> <option value={2}>Concluídas</option> </select> </div> </div> )} </div> ) }<file_sep>import axios from 'axios'; const URL =process.env.REACT_APP_API_URL+'/api/'; const instance = axios.create({ baseURL : URL, timeout: 30000 }); export const executaRequisicao = (endpoint, metodo, body) => { const accessToken = localStorage.getItem('accessToken'); let headers = {'Content-Type' : 'application/json'}; if(accessToken){ headers['Authorization'] = 'Bearer ' + accessToken; } console.log(`executando: ${URL}${endpoint}, metodo ${metodo}, body ${body}, headers ${headers}`); return instance.request({ url : endpoint, method: metodo, data : body? body : '', headers : headers }); }<file_sep>import React from 'react'; import adicionar from '../assets/icones/adicionar.svg'; export const Footer = props => { const {showModal} = props; return ( <div className="container-footer"> <button onClick={showModal}><img src={adicionar} alt="Adicionar tarefa" />Adicionar tarefa</button> <span>© Copyright {new Date().getFullYear()} Devaria. Todos os direitos reservados.</span> </div> ) }<file_sep>import React from 'react'; import logo from '../assets/icones/devaria-logo.svg'; import sair from '../assets/icones/exit.svg'; import sairDesktop from '../assets/icones/exit-desktop.svg'; export const Header = props => { const {showModal} = props; const nomeCompleto = localStorage.getItem('usuarioNome'); const primeiroNome = nomeCompleto?.split(' ')[0] || ''; return ( <div className="container-header"> <img className="logo" src={logo} alt="Logo Devaria" /> <button onClick={showModal}><span>+</span> Adicionar tarefa</button> <div className="mobile"> <span>{'Olá, ' + primeiroNome}</span> <img className="sair" src={sair} alt="Deslogar" onClick={props.sair} /> </div> <div className="desktop"> <span>{'Olá, ' + primeiroNome}</span> <img className="sair" src={sairDesktop} alt="Deslogar" onClick={props.sair} /> </div> </div> ) }<file_sep>import React from 'react'; import moment from 'moment'; import naoConcluido from '../assets/icones/not-checked.svg'; import concluido from '../assets/icones/checked.svg'; export const Item = props => { const { tarefa, selecionarTarefa } = props; const {dataConclusao, nome, dataPrevistaConclusao} = tarefa; const getDataTexto = (dtConclusao, dtPrevisaoConclusao) => { if(dtConclusao){ return `Concluído em: ${moment(dtConclusao).format('DD/MM/yyyy')}` }else{ return `Previsão de conclusão em: ${moment(dtPrevisaoConclusao).format('DD/MM/yyyy')}` } }; return ( <div className={"container-item " + (dataConclusao ? "" : "ativo")} onClick={() => dataConclusao ? null : selecionarTarefa(tarefa)}> <img src={dataConclusao ? concluido : naoConcluido} alt={dataConclusao ? "tarefa concluída" : "selecione a tarefa"} /> <div> <p className={dataConclusao? "concluido" : ""}>{nome}</p> <span>{getDataTexto(dataConclusao, dataPrevistaConclusao)}</span> </div> </div> ); }<file_sep>import React, { useState } from 'react'; import moment from 'moment'; import { Modal } from 'react-bootstrap'; import listaVazia from '../assets/icones/lista-vazia.svg'; import { Item } from './Item'; import { executaRequisicao } from '../services/api'; export const Listagem = props => { const { tarefas, getTarefasComFiltro } = props; const [ showModal, setShowModal ] = useState(false); // STATES DO CADASTRO const [erro, setErro] = useState(''); const [idTarefa, setIdTarefa] = useState(null); const [nomeTarefa, setNomeTarefa] = useState(''); const [dataPrevisaoTarefa, setDataPrevisaoTarefa] = useState(''); const [dataConclusao, setDataConclusao] = useState(''); const selecionarTarefa = tarefa =>{ setErro(''); setIdTarefa(tarefa.id); setNomeTarefa(tarefa.nome); setDataPrevisaoTarefa(moment(tarefa.dataPrevistaConclusao).format('yyyy-MM-DD')); setDataConclusao(tarefa.dataConclusao); setShowModal(true); } const atualizarTarefa = async () =>{ try{ if(!nomeTarefa || !dataPrevisaoTarefa){ setErro('Favor informar nome e data de previsão'); return; } const body = { nome : nomeTarefa, dataPrevistaConclusao : dataPrevisaoTarefa, dataConclusao: dataConclusao } await executaRequisicao('tarefa/'+idTarefa, 'put', body); await getTarefasComFiltro(); setNomeTarefa(''); setDataPrevisaoTarefa(''); setDataConclusao(''); setIdTarefa(null); setShowModal(false); }catch(e){ console.log(e); if(e?.response?.data?.erro){ setErro(e.response.data.erro); }else{ setErro('Não foi possível atualizar a tarefa, fale com o administrador.') } } } const excluirTarefa = async () =>{ try{ if(!idTarefa){ setErro('Favor informar a tarefa a ser excluída'); return; } await executaRequisicao('tarefa/'+idTarefa, 'delete'); await getTarefasComFiltro(); setNomeTarefa(''); setDataPrevisaoTarefa(''); setDataConclusao(''); setIdTarefa(null); setShowModal(false); }catch(e){ console.log(e); if(e?.response?.data?.erro){ setErro(e.response.data.erro); }else{ setErro('Não foi possível excluir a tarefa, fale com o administrador.') } } } return ( <> <div className={"container-listagem " + (tarefas && tarefas.length > 0 ? "" : "vazia")}> {tarefas && tarefas.length > 0 ? tarefas?.map(tarefa => <Item tarefa={tarefa} key={tarefa.id} selecionarTarefa={selecionarTarefa} />) : <> <img src={listaVazia} alt="Nenhuma atividade encontrada" /> <p>Você ainda não possui tarefas cadastradas!</p> </> } </div> <Modal show={showModal} onHide={() => setShowModal(false)} className="container-modal"> <Modal.Body> <p>Alterar uma tarefa</p> {erro && <p className="error">{erro}</p>} <input type="text" name="nome" placeholder="Nome da tarefa" className="col-12" value={nomeTarefa} onChange={evento => setNomeTarefa(evento.target.value)} /> <input type="text" name="dataPrevisao" placeholder="Data de previsão de conclusão" className="col-12" value={dataPrevisaoTarefa} onChange={evento => setDataPrevisaoTarefa(evento.target.value)} onFocus={evento => evento.target.type = 'date'} onBlur={evento => dataPrevisaoTarefa ? evento.target.type = 'date' : evento.target.type = 'text'} /> <input type="text" name="dataConclusao" placeholder="Data de conclusão" className="col-12" value={dataConclusao} onChange={evento => setDataConclusao(evento.target.value)} onFocus={evento => evento.target.type = 'date'} onBlur={evento => dataConclusao ? evento.target.type = 'date' : evento.target.type = 'text'} /> </Modal.Body> <Modal.Footer> <div className="buttons col-12"> <button onClick={atualizarTarefa}>Alterar</button> <span onClick={excluirTarefa}>Excluir tarefa</span> </div> </Modal.Footer> </Modal> </> ) }<file_sep>import React, { useState } from 'react'; import logo from '../assets/icones/devaria-logo.svg'; import mail from '../assets/icones/mail.svg'; import lock from '../assets/icones/lock.svg'; import { Input } from '../componentes/Input'; import { executaRequisicao } from '../services/api'; export const Login = props => { const [login, setLogin] = useState(''); const [senha, setSenha] = useState(''); const [msgErro, setMsgErro] = useState(''); const [isLoading, setLoading] = useState(false); const executaLogin = async evento => { try{ evento.preventDefault(); setLoading(true); setMsgErro(''); const body = { login, senha }; const resultado = await executaRequisicao('login', 'post', body); if(resultado?.data?.token){ localStorage.setItem('accessToken', resultado.data.token); localStorage.setItem('usuarioNome', resultado.data.nome); localStorage.setItem('usuarioEmail', resultado.data.email); props.setAccessToken(resultado.data.token); } }catch(e){ console.log(e); if(e?.response?.data?.erro){ setMsgErro(e.response.data.erro); }else{ setMsgErro('Não foi possível efetuar o login, fale com o administrador.') } } setLoading(false); } return ( <div className="container-login"> <img src={logo} alt="Logo Devaria" className="logo" /> <form> {msgErro && <p>{msgErro}</p>} <Input srcImg={mail} altImg={"Icone email"} inputType="text" inputName="login" inputPlaceholder="Informe seu email" value={login} setValue={setLogin} /> <Input srcImg={lock} altImg={"Icone senha"} inputType="password" inputName="senha" inputPlaceholder="Informe sua senha" value={senha} setValue={setSenha} /> <button onClick={executaLogin} disabled={isLoading}>{isLoading === true ? '...Carregando' : 'Entrar'}</button> </form> </div> ); }
af1166d9c5cd4fe4117f65051f30ac750bcc514d
[ "JavaScript" ]
7
JavaScript
Devaria-Oficial/gerenciador-tarefas-react
46192ab1b428249942e02e4d8a7b056aaedc30ec
2ecfbcb0fec3dfd3c0ec3f8d7a49f342492c267b
refs/heads/master
<file_sep>import cv2 import matplotlib.pyplot as plt import numpy as np import torch import torchvision import ffmpeg import math # points_color_palette='gist_rainbow', skeleton_color_palette='jet', # points_palette_samples=10, colors = np.round(np.array(plt.get_cmap('gist_rainbow')( np.linspace(0, 1, 16))) * 255).astype(np.uint8)[:, -2::-1].tolist() def joints_dict(): joints = { "coco": { "keypoints": { 0: "nose", 1: "left_eye", 2: "right_eye", 3: "left_ear", 4: "right_ear", 5: "left_shoulder", 6: "right_shoulder", 7: "left_elbow", 8: "right_elbow", 9: "left_wrist", 10: "right_wrist", 11: "left_hip", 12: "right_hip", 13: "left_knee", 14: "right_knee", 15: "left_ankle", 16: "right_ankle" }, "skeleton": [ # # [16, 14], [14, 12], [17, 15], [15, 13], [12, 13], [6, 12], [7, 13], [6, 7], [6, 8], # # [7, 9], [8, 10], [9, 11], [2, 3], [1, 2], [1, 3], [2, 4], [3, 5], [4, 6], [5, 7] # [15, 13], [13, 11], [16, 14], [14, 12], [11, 12], [5, 11], [6, 12], [5, 6], [5, 7], # [6, 8], [7, 9], [8, 10], [1, 2], [0, 1], [0, 2], [1, 3], [2, 4], [3, 5], [4, 6] [15, 13], [13, 11], [16, 14], [14, 12], [ 11, 12], [5, 11], [6, 12], [5, 6], [5, 7], [6, 8], [7, 9], [8, 10], [1, 2], [0, 1], [ 0, 2], [1, 3], [2, 4], # [3, 5], [4, 6] [0, 5], [0, 6] ] }, "mpii": { "keypoints": { 0: "right_ankle", 1: "right_knee", 2: "right_hip", 3: "left_hip", 4: "left_knee", 5: "left_ankle", 6: "pelvis", 7: "thorax", 8: "upper_neck", 9: "head top", 10: "right_wrist", 11: "right_elbow", 12: "right_shoulder", 13: "left_shoulder", 14: "left_elbow", 15: "left_wrist" }, "skeleton": [ # [5, 4], [4, 3], [0, 1], [1, 2], [3, 2], [13, 3], [12, 2], [13, 12], [13, 14], # [12, 11], [14, 15], [11, 10], # [2, 3], [1, 2], [1, 3], [2, 4], [3, 5], [4, 6], [5, 7] [5, 4], [4, 3], [0, 1], [1, 2], [3, 2], [ 3, 6], [2, 6], [6, 7], [7, 8], [8, 9], [13, 7], [12, 7], [13, 14], [12, 11], [14, 15], [11, 10], ] }, } return joints def draw_points_front(image, points, exercise_type, confidence_threshold=0.5): circle_size = max(1, min(image.shape[:2]) // 160) y0 = 0 y1 = 0 y2 = 0 ylw = points[9][0] yrw = points[10][0] yls = points[5][0] yrs = points[6][0] z0, z1, z2 = 0, 0, 0 for i, pt in enumerate(points): if pt[2] > confidence_threshold: image = cv2.circle(image, (int(pt[1]), int( pt[0])), circle_size, tuple(colors[i % len(colors)]), -1) font = cv2.FONT_HERSHEY_SIMPLEX org = (pt[1], pt[0]) fontScale = 1 color = (255, 255, 255) thickness = 2 # image = cv2.putText(image, str(i), org, font, # fontScale, color, thickness, cv2.LINE_AA) if exercise_type == 3: if i == 0: y0 = pt[0] z0 = pt[2] if i == 1: y1 = pt[0] z1 = pt[2] if i == 2: y2 = pt[0] z2 = pt[2] dist = distance(y0, y1, y2, z0, z1, z2, ylw, yrw) if exercise_type == 5: dist = distance_dumbell(yls, yrs, ylw, yrw) return image, dist def draw_points_one_side(image, points, exercise_type, confidence_threshold=0.5): # ToDo Shape it taking into account the size of the detection circle_size = max(1, min(image.shape[:2]) // 160) x1 = 0 y1 = 0 x2 = 0 y2 = 0 x3 = 0 y3 = 0 xn = points[0][1] xlh = points[11][1] xrh = points[12][1] if exercise_type == 1 or exercise_type == 4: if(xn < xlh or xn < xrh): a, b, c = 5, 7, 9 else: a, b, c = 6, 8, 10 elif exercise_type == 2: if(xn < xlh or xn < xrh): a, b, c = 11, 13, 15 else: a, b, c = 12, 14, 16 for i, pt in enumerate(points): if pt[2] > confidence_threshold: image = cv2.circle(image, (int(pt[1]), int( pt[0])), circle_size, tuple(colors[i % len(colors)]), -1) font = cv2.FONT_HERSHEY_SIMPLEX org = (int(pt[1]), int(pt[0])) fontScale = 1 color = (255, 255, 255) thickness = 2 image = cv2.putText(image, str(i), org, font, fontScale, color, thickness, cv2.LINE_AA) if i == a: x1 = pt[1] y1 = pt[0] #print(x1," ",y1) if i == b: x2 = pt[1] y2 = pt[0] #print(x2," ",y2) if i == c: x3 = pt[1] y3 = pt[0] #print(x3," ",y3) ang = angle(x1, y1, x2, y2, x3, y3) return image, ang def draw_skeleton(image, points, skeleton, person_index=0, confidence_threshold=0.5): """ Draws a `skeleton` on `image`. Args: image: image in opencv format points: list of points to be drawn. Shape: (nof_points, 3) Format: each point should contain (y, x, confidence) skeleton: list of joints to be drawn Shape: (nof_joints, 2) Format: each joint should contain (point_a, point_b) where `point_a` and `point_b` are an index in `points` person_index: index of the person in `image` Default: 0 confidence_threshold: only points with a confidence higher than this threshold will be drawn. Range: [0, 1] Default: 0.5 Returns: A new image with overlaid joints """ for i, joint in enumerate(skeleton): pt1, pt2 = points[joint] if pt1[2] > confidence_threshold and pt2[2] > confidence_threshold: image = cv2.line( image, (int(pt1[1]), int(pt1[0])), (int(pt2[1]), int(pt2[0])), tuple(colors[i % len(colors)]), 2 # tuple(colors[person_index % len(colors)]), 2 ) return image def draw_points_and_skeleton(image, points, skeleton, person_index=0, confidence_threshold=0.5, exercise_type=1): image = draw_skeleton(image, points, skeleton, person_index=person_index, confidence_threshold=confidence_threshold) # plt.imshow(image) # plt.show() if exercise_type == 1 or exercise_type == 2 or str(exercise_type)[0] == str(4): image, angle = draw_points_one_side( image, points, exercise_type, confidence_threshold=confidence_threshold) elif exercise_type == 3 or exercise_type == 5: image, angle = draw_points_front( image, points, exercise_type, confidence_threshold=confidence_threshold) return image, angle def save_images(images, target, joint_target, output, joint_output, joint_visibility, summary_writer=None, step=0, prefix=''): """ Creates a grid of images with gt joints and a grid with predicted joints. This is a basic function for debugging purposes only. If summary_writer is not None, the grid will be written in that SummaryWriter with name "{prefix}_images" and "{prefix}_predictions". Args: images (torch.Tensor): a tensor of images with shape (batch x channels x height x width). target (torch.Tensor): a tensor of gt heatmaps with shape (batch x channels x height x width). joint_target (torch.Tensor): a tensor of gt joints with shape (batch x joints x 2). output (torch.Tensor): a tensor of predicted heatmaps with shape (batch x channels x height x width). joint_output (torch.Tensor): a tensor of predicted joints with shape (batch x joints x 2). joint_visibility (torch.Tensor): a tensor of joint visibility with shape (batch x joints). summary_writer (tb.SummaryWriter): a SummaryWriter where write the grids. Default: None step (int): summary_writer step. Default: 0 prefix (str): summary_writer name prefix. Default: "" Returns: A pair of images which are built from torchvision.utils.make_grid """ # Input images with gt images_ok = images.detach().clone() images_ok[:, 0].mul_(0.229).add_(0.485) images_ok[:, 1].mul_(0.224).add_(0.456) images_ok[:, 2].mul_(0.225).add_(0.406) for i in range(images.shape[0]): joints = joint_target[i] * 4. joints_vis = joint_visibility[i] for joint, joint_vis in zip(joints, joints_vis): if joint_vis[0]: a = int(joint[1].item()) b = int(joint[0].item()) # images_ok[i][:, a-1:a+1, b-1:b+1] = torch.tensor([1, 0, 0]) images_ok[i][0, a - 1:a + 1, b - 1:b + 1] = 1 images_ok[i][1:, a - 1:a + 1, b - 1:b + 1] = 0 grid_gt = torchvision.utils.make_grid(images_ok, nrow=int( images_ok.shape[0] ** 0.5), padding=2, normalize=False) if summary_writer is not None: summary_writer.add_image(prefix + 'images', grid_gt, global_step=step) # Input images with prediction images_ok = images.detach().clone() images_ok[:, 0].mul_(0.229).add_(0.485) images_ok[:, 1].mul_(0.224).add_(0.456) images_ok[:, 2].mul_(0.225).add_(0.406) for i in range(images.shape[0]): joints = joint_output[i] * 4. joints_vis = joint_visibility[i] for joint, joint_vis in zip(joints, joints_vis): if joint_vis[0]: a = int(joint[1].item()) b = int(joint[0].item()) # images_ok[i][:, a-1:a+1, b-1:b+1] = torch.tensor([1, 0, 0]) images_ok[i][0, a - 1:a + 1, b - 1:b + 1] = 1 images_ok[i][1:, a - 1:a + 1, b - 1:b + 1] = 0 grid_pred = torchvision.utils.make_grid(images_ok, nrow=int( images_ok.shape[0] ** 0.5), padding=2, normalize=False) if summary_writer is not None: summary_writer.add_image( prefix + 'predictions', grid_pred, global_step=step) return grid_gt, grid_pred def angle(x1, y1, x2, y2, x3, y3): a = math.sqrt((x3-x2)**2+(y3-y2)**2) b = math.sqrt((x3-x1)**2+(y3-y1)**2) c = math.sqrt((x2-x1)**2+(y2-y1)**2) if a == 0 or c == 0: angle = 0 return angle else: term = (a**2+c**2-b**2)/(2*c*a) angle_rad = math.acos(term) angle = (180*angle_rad)/(math.pi) return angle def distance(y0, y1, y2, z0, z1, z2, ylw, yrw): t1, t2, t3 = 0, 0, 0 if(z0 > 0.5 and y0 > ylw and y0 > yrw): t1 = 1 if(z1 > 0.5 and y1 > ylw and y1 > yrw): t2 = 1 if(z2 > 0.5 and y2 > ylw and y2 > yrw): t3 = 1 if(t1 == 1 and t2 == 1): return 1 if(t1 == 1 and t3 == 1): return 1 if(t2 == 1 and t3 == 1): return 1 return -1 def distance_dumbell(yls, yrs, ylw, yrw): if (yrs > yrw): return 1 if (yls > ylw): return 1 return -1 <file_sep>from torchsummary import summary from models.hrnet import HRNet import sys import os import cv2 import matplotlib.pyplot as plt import torchprof import torch import numpy as np from model import SimpleHRNet from misc.visualization import draw_points_and_skeleton, joints_dict from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm fig = plt.figure(figsize=(8, 6)) ax = plt.subplot(111, projection='3d') ax.xaxis.pane.fill = False ax.xaxis.pane.set_edgecolor('white') ax.yaxis.pane.fill = False ax.yaxis.pane.set_edgecolor('white') ax.zaxis.pane.fill = False ax.zaxis.pane.set_edgecolor('white') ax.grid(False) # ax.w_zaxis.line.set_lw(0.) # ax.set_zticks([]) # model = HRNet(32, 17, 0.1).cuda() # y = model(torch.ones(1, 3, 384, 288).to('cuda')) # print(y.shape) # img = cv2.imread('frame.png') # cv2.imshow('img', img) # cv2.waitKey(0) # plt.imshow(img) # plt.show() frame = cv2.imread('demo/input.jpg') model = SimpleHRNet( 48, 17, 'weights/w48_384_288.pth', model_name='HRNet', resolution=(384, 288), multiperson=False, return_heatmaps=True, return_bounding_boxes=True, max_batch_size=16, device='cuda' ) pts = model.predict(frame) heatmap, boxes, pts = pts heatmap = np.squeeze(heatmap) heatmapx = np.zeros((heatmap.shape[1], heatmap.shape[2])) for i in range(17): heatmapx += heatmap[i, :, :] heatmap = heatmap[0, :, :] X, Y = np.meshgrid(np.linspace(0, 2, 72), np.linspace(0, 2, 96)) plot = ax.plot_surface(X=X, Y=Y, Z=heatmapx, cmap='viridis') # plt.imshow(heatmapx) plt.show() # print(pts) # for i, pt in enumerate(pts): # frame, angle = draw_points_and_skeleton(frame, pt, joints_dict()["coco"]['skeleton'], person_index=1, # points_color_palette='gist_rainbow', skeleton_color_palette='jet', # points_palette_samples=10, exercise_type=1) # cv2.imwrite('sanvi_output.jpeg', frame) # frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) # plt.imshow(frame) # plt.show() # frame = cv2.imread('frame.png') # plt.imshow(frame) # plt.show() # cv2.imshow('frame', frame) # cv2.waitKey(0) # start_point = (0, 0) # end_point = (int(frame.shape[1]*0.7), int(frame.shape[0]*0.1)) # colorr = (0, 0, 0) # thicknessr = -1 # frame = cv2.rectangle( # frame, start_point, end_point, colorr, thicknessr) # font = cv2.FONT_HERSHEY_SIMPLEX # org = (int(frame.shape[1]*0.01), int(frame.shape[0]*0.025)) # fontScale = frame.shape[0] * 0.0014 # color = (255, 255, 255) # thickness = 1 # frame = cv2.putText(frame, 'FPS: {:.3f}'.format(122.2131), org, font, # fontScale*0.35, color, thickness, cv2.LINE_AA) # org = (int(frame.shape[1]*0.01), int(frame.shape[0]*0.08)) # thickness = 2 # text = "PushUps Count="+str(10) # frame = cv2.putText(frame, text, org, font, # fontScale, color, thickness, cv2.LINE_AA) <file_sep>black==21.9b0 certifi==2021.5.30 charset-normalizer==2.0.6 click==8.0.1 colorlog==6.4.1 cycler==0.10.0 Cython==0.29.24 EasyProcess==0.3 entrypoint2==0.2.4 ffmpeg==1.4 Flask==2.0.1 idna==3.2 iso-639==0.4.5 iso3166==2.0.1 isodate==0.6.0 itsdangerous==2.0.1 jeepney==0.7.1 Jinja2==3.0.1 kiwisolver==1.3.2 lxml==4.6.3 MarkupSafe==2.0.1 matplotlib==3.4.3 mss==6.1.0 munkres==1.1.4 mypy-extensions==0.4.3 numpy==1.21.2 opencv-python==4.5.3.56 pafy==0.5.5 pathspec==0.9.0 Pillow==8.3.2 platformdirs==2.3.0 pycryptodome==3.10.1 pyparsing==2.4.7 pyscreenshot==3.0 PySocks==1.7.1 python-dateutil==2.8.2 pyzmq==22.3.0 regex==2021.8.28 requests==2.26.0 simplejpeg==1.6.2 six==1.16.0 streamlink==2.4.0 tomli==1.2.1 torch==1.9.0 torchvision==0.10.0 tqdm==4.62.2 typing-extensions==3.10.0.2 urllib3==1.26.6 uWSGI==192.168.127.12 vidgear==0.2.2 websocket-client==1.2.1 Werkzeug==2.0.1 youtube-dl==2021.6.6 <file_sep>Sample Video- https://www.youtube.com/watch?v=djHRAaRSIzs This projects counts the repetitions of common exercises. Here I have provided support for pushups, chinups, squats, dumbellcurls and dumbell-side-lateral. It can also tell whether you are doing a complete rep or an incomplete repetition. It can be extended to other exercises as well and they can be auto detected by just noting the angles between different joints. The model is also scalable to multi person estimation. Here I used pose_hrnet_w48_256*192 pretrained on COCO dataset with 17 joints. The model works irrespective of the direction of the camera except from the back side. The model works irrespective of the direction of the camera. For PushUps I used the angle formed by the elbow, for Squats the angle formed by the knees was used and distance between nose and wrists was considered for chin ups. This works only with video ### Run For running the web application go to [http://172.16.58.3/](http://172.16.31.107/). 1-Choose the file for which you need to count the reps<br/> 2-Choose the type of exercise.<br/> 3-Enter the mailId on which you want to receive the final video.<br/> The video takes some time to process, so wait for 5-10mins for the mail. Mail might get into spam so check it after 10mins. Video cannot be viewed on the browser, download the video from the link. <br/> For test purposes you can download a sample video from [google drive](https://drive.google.com/drive/folders/1GDE8TySO5LBN6doJtW9DvAbtu-av1ivI?usp=sharing). <br/> To run the application on local system, run start-count.py and give filename with type of exercise to be counted.(1 for pushUps, 2 for sitUps, 3 for chinUps). To run the application run start-count.py and give filename with type of exercise to be counted. 1-PushUps<br/> 2-SitUps<br/> 3-ChinUps<br/> 4-Dumbell Curl<br/> 5-Side Dumbell Lateral<br/> For running the application you need to add the weights folder in the main directory which can be downloaded from [google drive](https://drive.google.com/drive/folders/1GDE8TySO5LBN6doJtW9DvAbtu-av1ivI?usp=sharing). <br/> For eg. ```python main.py --filename test.mp4 --exercise_type 1 ``` ### examples Sample input video and weights for the pipeline can be found at <img src="https://github.com/akshatkaush/exercise-count/blob/master/New%20folder/chinups_sample.PNG?raw=true" > <img src="https://github.com/akshatkaush/exercise-count/blob/master/New%20folder/push_up_sample.PNG?raw=true" width="568.5" height="286.5"> <img src="https://github.com/akshatkaush/exercise-count/blob/master/New%20folder/push_up_sample2.PNG?raw=true" width="568.5" height="286.5"> <img src="https://github.com/akshatkaush/exercise-count/blob/master/New%20folder/frame.png?raw=true"> <img src="https://github.com/akshatkaush/exercise-count/blob/master/New%20folder/websample.PNG?raw=true" width="568.5" height="286.5"> <file_sep>from misc.utils import find_person_id_associations from misc.visualization import draw_points_and_skeleton, joints_dict from model import SimpleHRNet import ast import cv2 import torch from vidgear.gears import CamGear import numpy as np import os import time from flask import Flask, request, render_template, send_from_directory from werkzeug.utils import secure_filename from threading import Thread import datetime import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText app = Flask(__name__, static_url_path='') app.secret_key = os.urandom(42) OUTPUT_FOLDER = 'downloads' INPUT_FOLDER = 'uploads' SITE_URL = 'http://127.0.0.1/' SENDER_ADDRESS = '<EMAIL>' SENDER_PASS = '<PASSWORD>' session = smtplib.SMTP('smtp.gmail.com', 587) # use gmail with port session.starttls() # enable security session.login(SENDER_ADDRESS, SENDER_PASS) # login with mail_id and password def generate_output( input_filename="test.mp4", output_filename="output.mp4", exercise_type=1, email='<EMAIL>', camera_id=0, hrnet_weights="./weights/w32_256×192.pth", image_resolution="(256,192)", hrnet_j=17, hrnet_m="HRNet", hrnet_c=32, hrnet_joints_set="coco", single_person=True, use_tiny_yolo=False, disable_tracking=False, max_batch_size=16, disable_vidgear=False, save_video=True, video_format="MJPG", video_framerate=30, device=None, ): if device is not None: device = torch.device(device) else: if torch.cuda.is_available(): torch.backends.cudnn.deterministic = True device = torch.device("cuda") else: device = torch.device("cpu") image_resolution = ast.literal_eval(image_resolution) video_writer = None if input_filename is not None: video = cv2.VideoCapture(input_filename) assert video.isOpened() else: if disable_vidgear: video = cv2.VideoCapture(camera_id) assert video.isOpened() else: video = CamGear(camera_id).start() if use_tiny_yolo: yolo_model_def = "./models/detectors/yolo/config/yolov3-tiny.cfg" yolo_class_path = "./models/detectors/yolo/data/coco.names" yolo_weights_path = "./models/detectors/yolo/weights/yolov3-tiny.weights" else: yolo_model_def = "./models/detectors/yolo/config/yolov3.cfg" yolo_class_path = "./models/detectors/yolo/data/coco.names" yolo_weights_path = "./models/detectors/yolo/weights/yolov3.weights" model = SimpleHRNet( hrnet_c, hrnet_j, hrnet_weights, model_name=hrnet_m, resolution=image_resolution, multiperson=not single_person, return_heatmaps=False, return_bounding_boxes=not disable_tracking, max_batch_size=max_batch_size, yolo_model_def=yolo_model_def, yolo_class_path=yolo_class_path, yolo_weights_path=yolo_weights_path, device=device, ) if not disable_tracking: prev_boxes = None prev_pts = None prev_person_ids = None next_person_id = 0 flag = 0 prev_flag = flag counter = 0 data = 0 prev_data = data while True: t = time.time() if input_filename is not None or disable_vidgear: ret, frame = video.read() if not ret: break else: frame = video.read() if frame is None: break pts = model.predict(frame) if not disable_tracking: boxes, pts = pts if len(pts) > 0: if prev_pts is None and prev_person_ids is None: person_ids = np.arange( next_person_id, len(pts) + next_person_id, dtype=np.int32 ) next_person_id = len(pts) + 1 else: boxes, pts, person_ids = find_person_id_associations( boxes=boxes, pts=pts, prev_boxes=prev_boxes, prev_pts=prev_pts, prev_person_ids=prev_person_ids, next_person_id=next_person_id, pose_alpha=0.2, similarity_threshold=0.4, smoothing_alpha=0.1, ) next_person_id = max(next_person_id, np.max(person_ids) + 1) else: person_ids = np.array((), dtype=np.int32) prev_boxes = boxes.copy() prev_pts = pts.copy() prev_person_ids = person_ids else: person_ids = np.arange(len(pts), dtype=np.int32) for i, (pt, pid) in enumerate(zip(pts, person_ids)): frame, data = draw_points_and_skeleton( frame, pt, joints_dict()[hrnet_joints_set]["skeleton"], person_index=pid, exercise_type=exercise_type, ) frame = cv2.rectangle( frame, (0, 0), (int(frame.shape[1] * 0.7), int(frame.shape[0] * 0.1)), (0, 0, 0), -1, ) fps = 1.0 / (time.time() - t) font = cv2.FONT_HERSHEY_SIMPLEX org = (int(frame.shape[1] * 0.01), int(frame.shape[0] * 0.035)) fontScale = frame.shape[0] * 0.0014 color = (255, 255, 255) thickness = 1 frame = cv2.putText( frame, "FPS: {:.3f}".format(fps), org, font, fontScale * 0.35, color, thickness, cv2.LINE_AA, ) if exercise_type == 1: # for pushUps if len(pts) > 0: if data > 160: flag = 0 if data < 90: flag = 1 if prev_flag == 1 and flag == 0: counter = counter + 1 prev_flag = flag org = (int(frame.shape[1] * 0.01), int(frame.shape[0] * 0.08)) text = "PushUps Count=" + str(counter) frame = cv2.putText( frame, text, org, font, fontScale, color, thickness * 2, cv2.LINE_AA ) elif exercise_type == 2: # for Squats if len(pts) > 0: if data > 150: flag = 0 if data < 90: flag = 1 if prev_flag == 1 and flag == 0: counter = counter + 1 prev_flag = flag org = (int(frame.shape[1] * 0.01), int(frame.shape[0] * 0.08)) text = "Situps Count=" + str(counter) frame = cv2.putText( frame, text, org, font, fontScale, color, thickness * 2, cv2.LINE_AA ) elif exercise_type == 3: # for PullUps if len(pts) > 0: if data == -1 and prev_data == 1: counter = counter + 1 prev_data = data org = (int(frame.shape[1] * 0.01), int(frame.shape[0] * 0.08)) text = "PullUps Count=" + str(counter) frame = cv2.putText( frame, text, org, font, fontScale, color, thickness * 2, cv2.LINE_AA ) elif exercise_type == 4: # for dumbell curl if len(pts) > 0: if data > 110: flag = 0 if data < 65: flag = 1 if prev_flag == 1 and flag == 0: counter = counter + 1 prev_flag = flag org = (int(frame.shape[1] * 0.01), int(frame.shape[0] * 0.08)) text = "Dumbell Curl Count=" + str(counter) frame = cv2.putText( frame, text, org, font, fontScale, color, thickness * 2, cv2.LINE_AA ) elif exercise_type == 5: # for dumbell side lateral if len(pts) > 0: if data == -1 and prev_data == 1: counter = counter + 1 prev_data = data org = (int(frame.shape[1] * 0.01), int(frame.shape[0] * 0.08)) text = "Dumbell Side Count=" + str(counter) frame = cv2.putText( frame, text, org, font, fontScale, color, thickness * 2, cv2.LINE_AA ) if save_video: if video_writer is None: fourcc = cv2.VideoWriter_fourcc(*video_format) # video format video_writer = cv2.VideoWriter( output_filename, fourcc, video_framerate, (frame.shape[1], frame.shape[0]), ) video_writer.write(frame) if save_video: video_writer.release() print("Video processing complete") mail_content = f'''Hey, Your video has finished processing. You can view your video here : {SITE_URL}{output_filename} Thank You ''' message = MIMEMultipart() message['From'] = SENDER_ADDRESS message['To'] = email message['Subject'] = 'Exercise Counter Processing Finished' message.attach(MIMEText(mail_content, 'plain')) text = message.as_string() session.sendmail(SENDER_ADDRESS, email, text) print("email sent") @app.route('/assets/<path:path>') def send_asset(path): return send_from_directory('assets', path) @app.route(f'/{OUTPUT_FOLDER}/<path:path>') def download_video(path): return send_from_directory(f'{OUTPUT_FOLDER}', path) @app.route("/", methods=['GET', 'POST']) def index(): if request.method == 'GET': return render_template('index.html') else: try: uploaded_file = request.files['file'] exercise_type, email = request.form['exercise_type'], request.form['email'] filename = secure_filename( uploaded_file.filename) + '_' + str(int(datetime.datetime.now().timestamp())) uploaded_file.save(INPUT_FOLDER + '/' + filename + '.mp4') thread = Thread( target=generate_output, args=( f"{INPUT_FOLDER}/{filename}.mp4", f"{OUTPUT_FOLDER}/{filename}_output.mp4", int(exercise_type), email) ) thread.daemon = True thread.start() return render_template('message.html', message='Form submitted successfully.') except Exception as _: return render_template('message.html', messsage='An error occurred') if __name__ == "__main__": # generate_output(input_filename="uploads/pushup.mp4_1632031449.mp4", output_filename="output.mp4", exercise_type=1) app.run("127.0.0.1", 8000) <file_sep>run: python main.py --filename test.mp4 --exercise_type 1
3da2413d09b7dd4d675ec3b3a5332540252c872a
[ "Makefile", "Markdown", "Text", "Python" ]
6
Makefile
akshatkaush/exercise-count
56079bf94a505aeae86dd35ef329181a584f6dc4
605c6c425562d28d2b6ab2f7b50f86ad2991dec7
refs/heads/master
<file_sep>import {Component, Directive} from 'angular2/core'; import {ArtPicture} from '../art-picture/art-picture.component'; import {ArtImage} from './art-image/art-image.component'; import {Picture, Collection} from '../../../model/art-model'; @Component({ selector: 'art-images', directives: [ArtImage, ArtPicture], inputs: ['collection'], host: { class: 'images' }, styleUrls: ['app/components/art-app/art-images/art-images.component.css'], template: ` <art-picture [hidden]="isShown()" *ngFor="#picture of collection.pictures" [picture]="picture" [collection]="collection"></art-picture> <art-image [hidden]="!isShown()" [picture]="theSelected()" [collection]="collection"></art-image> ` }) export class ArtImages { collection: Collection; picture: Picture; isShown(): boolean { return this.collection.isDetailShown(); } theSelected(): Picture { return this.collection.selectedPicture; } }<file_sep>@import './resources/styles/gallery-app-common-variables'; p { /* Positioning */ position: static; top: 5px; left: 0; /* Display */ overflow: visible; display: block; float: none; z-index: 22; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; /* Box Model */ width: 200px; height: 100px; padding: 10px; border: 1px solid; border-radius: 5px; margin: 10px; /* Color */ background: #fff; color: #f00; border-color: blue; opacity: 0.5; /* Text */ font-family: Arial, Helvetica, sans-serif; font-size: 33px; line-height: 1.4; text-align: left; -o-text-overflow: ellipsis; text-overflow: ellipsis; /* Other */ cursor: pointer; /* transition * /* -webkit-transition: all 601ms cubic-bezier(0.68, -0.75, 0.265, 1.75); -moz-transition: all 601ms cubic-bezier(0.68, -0.75, 0.265, 1.75); -o-transition: all 601ms cubic-bezier(0.68, -0.75, 0.265, 1.75); transition: all 601ms cubic-bezier(0.68, -0.75, 0.265, 1.75); */ /* transform */ /* -webkit-transform: rotateX(0deg) rotateY(0deg) rotateZ(0deg) scaleX(1.5) scaleZ(1) translateX(0px) translateY(0px) translateZ(0px) skewX(0deg); transform: rotateX(0deg) rotateY(0deg) rotateZ(-3deg) scaleX(3) scaleZ(-4) translateX(16px) translateY(11px) translateZ(19px) skewX(0deg); -webkit-transform-origin: 50% 52% 21%; transform-origin: 50% 52% 21%; */ } <file_sep>import {Component, Directive} from 'angular2/core'; import {Picture, Collection} from '../../../model/art-model'; @Component({ selector: 'art-picture', inputs: ['picture', 'collection'], host: { class: 'pic' }, styleUrls: ['app/components/art-app/art-picture/art-picture.component.css'], template: ` <div class="view viewbeta"> <img [src]="getLink()"/> <div class="mask"> <h2>Hover {{picture.name}}</h2> <p>A wonderful serenity has taken this days</p> <a (click)="setPicture()" href="#" class="info">{{picture.link}}</a> </div> </div> ` }) export class ArtPicture { picture: Picture; collection: Collection; constructor() { this.picture = null; } setPicture(): void { this.collection.setImage('222'); } getLink(): string { return '../resources/images/' + this.picture.link; } }<file_sep>var gulp = require('gulp'); var sourcemaps = require('gulp-sourcemaps'); var tsc = require('gulp-typescript'); var tslint = require('gulp-tslint'); var sass = require('gulp-ruby-sass'); var tsProject = tsc.createProject('tsconfig.json'); var config = require('./gulp.config')(); var browserSync = require('browser-sync'); var superstatic = require('superstatic'); var del = require('del'); gulp.task('ts-lint', function() { return gulp.src(config.allTs) .pipe(tslint()) .pipe(tslint.report('prose', { emitError: false })); }) gulp.task('compile-ts', function() { var sourceTsFiles = [ config.allTs, config.allTypings ]; var tsResult = gulp .src(sourceTsFiles) .pipe(sourcemaps.init()) .pipe(tsc(tsProject)); return tsResult.js .pipe(sourcemaps.write('.')) .pipe(gulp.dest(config.destSrcPath)); }); gulp.task('scss-transpile', function() { return sass(config.allScss, { style: 'expanded' }) .pipe(gulp.dest(config.destSrcPath)); }); gulp.task('html-copy', function() { return gulp.src(config.allHtml) .pipe(gulp.dest(config.destSrcPath)); }); gulp.task('json-copy', function() { return gulp.src(config.allJson) .pipe(gulp.dest(config.destSrcPath)); }); gulp.task('resource-copy', function() { return gulp.src(config.allImages) .pipe(gulp.dest(config.destSrcPath)); }); gulp.task('lib-copy', function() { return gulp.src(config.extLibs) .pipe(gulp.dest(config.destLibPath)); }); gulp.task('watch', function(){ gulp.watch([config.allTs], ['ts-lint', 'compile-ts']); gulp.watch(config.allScss, ['scss-transpile', 'ts-lint', 'compile-ts']); gulp.watch([config.allHtml], ['html-copy', 'ts-lint', 'compile-ts']); gulp.watch([config.allJson], ['json-copy', 'ts-lint', 'compile-ts']); }) gulp.task('dev', ['ts-lint', 'compile-ts', 'html-copy', 'scss-transpile','json-copy', 'resource-copy', 'lib-copy']); gulp.task('serve', ['dev', 'watch'], function() { browserSync({ port: 3000, files: ['index.html', '**/*.js'], injectChanges: true, logFileChanges: false, logLevel: 'silent', notify: true, reloadDelay: 0, server: { baseDir: ['./dist-root'], middleware: superstatic({ debug: false}) } }); }); gulp.task('clean', function() { return del([config.destSrcPath]); }); gulp.task('default', ['serve']);<file_sep>/// <reference path="../../node_modules/angular2/typings/browser.d.ts" /> import {bootstrap} from 'angular2/platform/browser'; import {provide} from 'angular2/core'; import {ROUTER_PROVIDERS, HashLocationStrategy, LocationStrategy, RouteConfig} from 'angular2/router'; import {AppComponent} from './app.component'; bootstrap(AppComponent, [ROUTER_PROVIDERS, provide(LocationStrategy, {useClass: HashLocationStrategy})]);<file_sep>import {Component, Directive} from 'angular2/core'; import {Collection} from '../../../model/art-model'; @Component({ selector: 'art-control', inputs: ['collection'], styleUrls: ['app/components/art-app/art-control/art-control.component.css'], template: ` <div>Control</div> <div class="field"> <label for="link">Value:</label> <input type="number" #inputvalue> </div> <button (click)="plus()" class="button">+1 </button> <button (click)="minus()" class="button">-1 </button> <button (click)="plusVal(inputvalue.value)" class="button">add </button> ` }) export class ArtControl { collection: Collection; plus(): boolean { return false; } plusVal(val: number): void { this.collection.addPicture(val.toString(), 'no'); } minus(): boolean { return false; } } <file_sep># tiny-art-gallery <file_sep>@import '../../../../../resources/styles/common-variables'; $color-bg-default: #ffffff !default; $color-text-default: #000000 !default; $color-warning: #ff0000; $size-text-default: 14px; $radius-default: 5px;<file_sep>import {Component, Directive} from 'angular2/core'; import {RouteConfig} from 'angular2/router'; import {ArtApp} from './components/art-app/art-app.component'; import {ArtImages} from './components/art-app/art-images/art-images.component'; import {ArtImage} from './components/art-app/art-images/art-image/art-image.component'; import {GalleryPage} from './components/gallery-app/gallery-page/gallery-page.component'; import {GalleryApp} from './components/gallery-app/gallery-app.component'; @Component({ selector: 'app', styleUrls: ['app/app.component.css'], directives: [GalleryApp, ArtApp], template:` <h1 class="titel">Top</h1> <gallery-app></gallery-app> ` }) @RouteConfig([ {path: '/art', name: 'Art', component: ArtApp, useAsDefault: true}, {path: '/gallery/:id', name: 'Gallery', component: ArtApp}, {path: '/picture/:id', name: 'Picture', component: ArtApp}, {path: '/contacts/:id', name: 'Contacts', component: GalleryPage} ]) export class AppComponent {}; <file_sep>import {Component, Directive} from 'angular2/core'; import {Picture, Collection} from '../../../../model/art-model'; @Component({ selector: 'art-image', inputs: ['collection', 'picture'], styleUrls: ['app/components/art-app/art-images/art-image/art-image.component.css'], template: ` <div class="view viewbeta"> <img (click)="back()" [src]="link()" /> </div> ` }) export class ArtImage { collection: Collection; picture: Picture; link(): string { return '../../resources/images/' + this.picture.link; } back() { this.collection.setImage('e'); } }<file_sep>import {Component, Directive} from 'angular2/core'; import {RouteParams} from 'angular2/router'; @Component({ selector: 'gallery-page', template: ` <h1>myPage no: {{id}}</h1> ` }) export class GalleryPage { id: string; constructor(private routeParams: RouteParams) { this.id = routeParams.get('id'); } } <file_sep>import {Component, Directive} from 'angular2/core'; import {RouteConfig, ROUTER_DIRECTIVES} from 'angular2/router'; import {ArtApp} from '../../art-app/art-app.component'; @Component({ selector: 'gallery-nav', directives: [ArtApp, ROUTER_DIRECTIVES], styleUrls: ['app/components/gallery-app/gallery-nav/gallery-nav.component.css'], template: ` <a [routerLink]="['/Contacts', {id: 5}]">Contacts</a> <a [routerLink]="['/Art']">Art</a> ` }) export class GalleryNav { }<file_sep>@import '../resources/styles/gallery-app-common-variables'; /* route-link anchor tags */ a { padding: 5px; text-decoration: none; font-family: Arial, Helvetica, sans-serif; } a:visited, a:link { color: #444; } a:hover { color: white; background-color: #1171a3; } a.router-link-active { color: white; background-color: #52b9e9; }<file_sep>import {Component, Directive} from 'angular2/core'; import {ROUTER_DIRECTIVES} from 'angular2/router'; import {GalleryNav} from './gallery-nav/gallery-nav.component'; import {GalleryPage} from './gallery-page/gallery-page.component'; @Component({ selector: 'gallery-app', directives: [GalleryNav, GalleryPage, ROUTER_DIRECTIVES], styleUrls: ['app/components/gallery-app/gallery-app.component.css'], template:` <div class="Cmp"> <gallery-nav></gallery-nav> <router-outlet></router-outlet> </div> ` }) export class GalleryApp {} <file_sep>export class Picture { name: string; link: string; constructor(name: string, link: string) { this.name = name; this.link = link; } } interface Pictures { Name: string; Year: number; Length: number; High: number; } export class Collection { pictures: Picture[]; selectedPicture: Picture; responseText: string; obj: any; bla: Pictures[]; selected: number; showDetail: boolean; constructor() { this.pictures = [ new Picture('pink', 'picture_001.jpg'), new Picture('purple', 'picture_002.jpg'), new Picture('Blau23', 'picture_003.jpg') ]; this.selected = 0; this.showDetail = false; this.selectedPicture = this.pictures[0]; } addPicture(p_name: string, p_link: string) { this.pictures.push(new Picture(p_name, p_link)); function levelRequestListener() { this.bla = JSON.parse(this.responseText); console.log(this.bla); this.obj = this.bla[0].Name; } var request = new XMLHttpRequest(); request.onload = levelRequestListener; request.open('get', '/app/model/myart.json', true); request.send(); this.showDetail = !this.showDetail; this.pictures.push(new Picture(p_name, this.bla[0].Name)); this.selected = 2; } setImage(name: string) { this.showDetail = !this.showDetail; this.selectedPicture = this.pictures[1]; } getImage(): Picture { return this.pictures[this.selected]; } isDetailShown(): boolean { return this.showDetail; } }<file_sep>import {Component, Directive} from 'angular2/core'; import {ArtControl} from './art-control/art-control.component'; import {ArtImages} from './art-images/art-images.component'; import {Picture, Collection} from '../../model/art-model'; @Component({ selector: 'art-app', directives: [ArtImages, ArtControl], styleUrls: ['app/components/art-app/art-app.component.css'], template: ` <div class="View"> <art-images [collection]="collection"> ..images..</art-images> </div> <div class="Control"> <art-control [collection]="collection"> ..control..</art-control> </div> ` }) export class ArtApp { collection: Collection; constructor() { this.collection = new Collection(); } }
fdb926ce4ff3ac3cff9f3ba6048a868a16623ca6
[ "SCSS", "Markdown", "TypeScript", "JavaScript" ]
16
SCSS
ecodraw/tiny-art-gallery
72000896ff69f3a4757929feb7231dae08defb69
6099402b500e91fdb8187e191c68ad5e18e56031
refs/heads/master
<repo_name>b2evolution/blackorange_skin<file_sep>/style.less /* --------------------------- Font --------------------------- */ #skin_wrapper { font-family: 'Roboto', sans-serif; } /* --------------------- Style overrides ---------------------- */ #skin_wrapper { font-size: 15px; line-height: 1.7; } .navbar { border: none; border-radius: 2px; box-shadow: 0 0 6px rgba(0,0,0,0.03); margin-bottom: 30px; .navbar-collapse { border: none; padding: 0; .nav { margin: 0; li > a { font-weight: 700; text-transform: uppercase; } & > li:first-child a.selected { border-radius: 2px 0 0 2px; } } } &.navbar-default .navbar-toggle:focus, &.navbar-default .navbar-toggle:hover { background-color: transparent; } } .panel.panel-default, .results { border-radius: 2px; border: none; box-shadow: 0 0 6px rgba(0,0,0,0.03); margin-bottom: 30px; .panel-heading { padding: 20px; h4, h3 { font-weight: 700; text-transform: uppercase; } } .panel-body { padding: 20px; } .panel-footer { border-top: 0; border-radius: 2px; background-color: transparent; padding: 0 20px 20px; } &.panel-meta { margin: 0; .panel.panel-default { box-shadow: none; > .panel-body > .form-group { margin: 0; } } } .pagination { box-shadow: 0 0 6px rgba(0,0,0,0.1); margin: 20px 0 12px; } .page_size_selector { margin-bottom: 20px; } } main.panel, .disp_tags main { .panel-body { padding: 20px; } h2 { font-size: 16px; font-weight: 700; text-transform: uppercase; margin: 0 0 20px; } } .evo_item_meta_comments .panel-heading { font-weight: 700; text-transform: uppercase; } figure { margin: 0 0 1em; } .img-responsive, .form-control, .search_submit, .evo_comment img, .evo_content_block .evo_comment_avatar img, .popover img, .evo_widget img { border-radius: 2px; } #bCalendarToday { border: none; border-radius: 2px; } .evo_comment__list_title, input.preview, input.submit, .post_comments_link a { border-radius: 2px; box-shadow: 0 0 6px rgba(0,0,0,0.03); font-size: 12px; font-weight: 700; margin: 0 0 30px; text-transform: uppercase; } .post_comments_link { margin: 0; } .evo_comment__meta_info, .evo_post_comment_notification, .evo_post_feedback_feed_msg { padding: 0; a { border-radius: 2px; border: none; box-shadow: 0 0 6px rgba(0,0,0,0.03); line-height: 1.1; margin-bottom: 30px; } } .evo_comment__list_title, .evo_comment__meta_info a, .evo_post_comment_notification a, .evo_post_feedback_feed_msg a, input.preview, input.submit { padding: 15px; } a[rel~=nofollow]:not([class~=btn]):hover { background: transparent; } .evo_post_comment_notification, .evo_post_feedback_feed_msg { p { margin: 0; a { display: inline-block; white-space: inherit; span { color: inherit !important; } } } } .evo_post_feedback_feed_msg a:hover { text-decoration: none; } .evo_form__comment { .panel.panel-default { margin: 0; .panel-body { padding: 0; > .form-group { margin: 0; } } } } .well.evo_intro_post { border: none; border-radius: 2px; box-shadow: 0 0 6px rgba(0,0,0,0.03); padding: 20px; margin-bottom: 30px; & > .panel-heading, & > .panel-body { padding: 0; } .evo_post_title h2 { padding: 0; } } main { .evo_widget:not(.evo_layout_rwd):not(.evo_layout_flow), .widget_flow_blocks > div, .widget_rwd_blocks .widget_rwd_content, .disp_mediaidx_widget > h3 { border: none; border-radius: 2px; box-shadow: 0 0 6px rgba(0,0,0,0.03); padding: 20px; margin-bottom: 30px; } } .evo_widget { &.widget_core_coll_title { h1 { font-weight: 700; text-transform: uppercase; font-size: 30px; margin-bottom: 0; } } &.error_404 { margin: 0 0 30px; } h3 { font-size: 16px; font-weight: 700; text-transform: uppercase; margin: 0 0 20px; } &.widget_core_coll_featured_intro { padding: 0 !important; border-radius: 2px; .jumbotron { border-radius: 2px; .evo_post_title h2 { padding: 0; } .panel-heading, .panel-body { padding: 0; } } } } div.error_403, div.error_additional_content .widget_core_coll_tag_cloud, .deleted_thread_explanation { border: none; border-radius: 2px; box-shadow: 0 0 6px rgba(0,0,0,0.03); padding: 20px; margin: 0 0 30px; h2 { font-size: 16px; font-weight: 700; text-transform: uppercase; margin: 0 0 20px; } } div.error_additional_content { margin: 0; } form ul.token-input-list-facebook { border-radius: 2px; } /* --------------------- Disp Single ---------------------- */ .pager { margin: 0; li a { border-radius: 2px; border: none; box-shadow: 0 0 6px rgba(0,0,0,0.03); margin-bottom: 30px; padding: 15px; } } .evo_container__item_single { border-radius: 0 0 2px 2px; } .post_tags a { border-radius: 2px; } /* --------------------- Comments + disp ---------------------- */ .disp_comments { .evo_comment.panel .panel-heading { > h4.panel-title.pull-right, > .evo_comment_title { float: none !important; } } } .evo_comment { .panel-body { border-radius: 0 0 2px 2px; .evo_comment_avatar img { box-shadow: 0 0 6px rgba(0,0,0,0.03); } } } /* --------------------- Search disp ---------------------- */ .disp_search { main > h2 { border-radius: 2px 2px 0 0; box-shadow: 0 0 6px rgba(0,0,0,0.03); font-size: 16px; font-weight: 700; text-transform: uppercase; margin: 0; padding: 20px; } main .center .pagination { margin-bottom: 25px; } } // A search button input.search_field { margin-bottom: 0; display: inline-block; } form.search .search_options { width: 100%; .search_option input { margin-right: 5px; } .search_option label { margin-bottom: 0; margin-top: 5px; } } div.compact_search_form, div.extended_search_form { input.search_field { height: 49px; margin: 0; padding: 15px; width: 100%; } input.search_submit { margin: 0; } } div.extended_search_form { text-align: center; margin: 0 auto; max-width: 530px; .search_options { text-align: center; .search_option { display: inline-block; margin-right: 10px; } } } .search_result { border-radius: 2px; box-shadow: 0 0 6px rgba(0,0,0,0.03); padding: 20px; margin-bottom: 30px; .search_result_score { border-radius: 2px; display: block; float: none; font-size: 16px; font-weight: 700; line-height: auto; margin: 0 auto 20px; padding: 15px; text-align: center; width: 74px; } .search_content_wrap { margin: 0; .search_title { font-size: 16px; font-weight: 700; padding-bottom: 10px; text-transform: uppercase; a { text-decoration: none; &:hover { text-decoration: underline; } } } .result_content { padding-bottom: 10px; } & > .search_info { padding-bottom: 10px; &:last-child { padding: 0; } img.avatar_before_login { border-radius: 2px; vertical-align: middle; } } } } /* --------------------- Other disps ---------------------- */ .disp_access_denied main, .disp_tags main, .disp_threads main .panel, .disp_arcdir main { border-radius: 2px; border: none; box-shadow: 0 0 6px rgba(0,0,0,0.03); margin-bottom: 30px; padding: 20px 20px 10px; } .disp_posts main > p.msg_nothing { border-radius: 2px; border: none; box-shadow: 0 0 6px rgba(0,0,0,0.03); margin-bottom: 30px; padding: 20px 20px; } .disp_threads main .panel { padding: 0; & > h2 { border: none; border-radius: 2px 2px 0 0; box-shadow: 0 0 6px rgba(0,0,0,0.03); font-size: 16px; font-weight: 700; text-transform: uppercase; padding: 20px; margin: -20px -20px 30px; } .form_text_input { height: 49px; } label[for=thrd_title] { padding-top: 13px; } .SaveButton { border-radius: 2px; box-shadow: 0 0 6px rgba(0,0,0,0.03); font-size: 12px; font-weight: 700; margin: 0; padding: 10px 16px; text-transform: uppercase; } } .disp_catdir main .widget_core_coll_category_list > h3, .disp_arcdir main > h2 { border: none; border-radius: 2px 2px 0 0; box-shadow: 0 0 6px rgba(0,0,0,0.03); font-size: 16px; font-weight: 700; text-transform: uppercase; padding: 20px; margin: -20px -20px 20px; } .disp_sitemap main > h2, .disp_posts main > h2 { border: none; border-radius: 2px 2px 0 0; box-shadow: 0 0 6px rgba(0,0,0,0.03); font-size: 16px; font-weight: 700; text-transform: uppercase; padding: 20px; margin: 0 0 30px; } .disp_lostpassword .evo_form__login .panel .panel-body { padding-top: 0; } /* --------------------- Rest ---------------------- */ // Header .evo_container__header { margin-bottom: 30px; } .evo_container__page_top { margin-top: 30px; .ufld_icon_links { text-align: right; } } .nav.nav-tabs { margin-top: 0; } // Login widget form .widget_core_user_login { #login_form { .form-group { margin: 0; } label { text-align: left; width: 160px; padding-left: 0; } .controls { padding: 0; width: 100%; } .form_text_input.form-control { width: 100%; } } .submit { font-size: 12px; } .field_login_btn { .panel { margin: 0; border: none; border-radius: 0; box-shadow: none; .panel-body { padding-left: 0; padding-right: 0; padding-bottom: 0; #submit_login_form { margin-right: 10px; } } } } .register_link { display: block; padding-top: 10px; } } // Register widget form .widget_core_user_register { #register_form { .form-group { margin: 0; } label { text-align: left; width: 160px; padding-left: 0; } .controls { padding: 0; width: 100%; } .form_text_input.form-control { width: 100%; } } .submit { font-size: 12px; } .field_register_btn { .panel { margin: 0; border: none; border-radius: 0; box-shadow: none; .panel-body { padding-left: 0; padding-right: 0; padding-bottom: 0; #submit_login_form { margin-right: 10px; } } } } } // Profile tabs on ?disp=profile ul.profile_tabs { margin: 0 0 30px; position: relative; li { display: inline-block; list-style-type: none; margin: 10px 0; a { border-radius: 2px; box-shadow: 0 0 6px rgba(0,0,0,0.03); margin: 0 10px 10px 0; padding: 15px; &:hover { text-decoration: none; } } } } .disp_profile, .disp_pwdchange, .disp_subs { .panel-heading { font-size: 16px; font-weight: 700; line-height: 1.1; text-transform: uppercase; } .SaveButton { border-radius: 2px; box-shadow: 0 0 6px rgba(0,0,0,0.03); font-size: 12px; font-weight: 700; margin: 0 0 30px; padding: 15px; text-transform: uppercase; } } .profile_avatar { float: right; padding: 10px; margin-left: 10px; } // Use full width for all textarea .form-horizontal .controls textarea.form-control { width: 100%; } // Table for select categories of item table.catselect { input#new_category_name { width: 98% !important; } } // Form elements on item edit page label.control-label[for=post_title] { width: auto; } // A form to create a new message/thread textarea.message_text { width: 95%; } .evo_post { margin-bottom: 30px; .small.text-muted { margin: 4px 0 10px; a, a .glyphicon { color: inherit; } } } .evo_hasbgimg { background-repeat: no-repeat; background-size: cover; background-position: center; } div.bSideItem { background: #F7F5FA; border-radius: 5px; padding: 10px; margin-bottom: 10px; text-shadow: 0 1px 0 #FFFFFF; h4 { margin-top: 0; } } // Login/Register forms: .skin-form { .panel-body { .panel { border: none; box-shadow: none; } .panel-body { padding: 0; } } .fieldset { margin: 0; div.input { margin: 0; } } .control-buttons, div.input { padding: 0; width: 100%; text-align: center; } } .evo_panel__login, .evo_panel__lostpass, .evo_panel__register, .evo_panel__activation { min-width: 290px; margin: 1.5em auto auto; .panel { margin: 5px 0; .panel-body { padding: 20px 20px 10px; .input_text, .form_text_input { border-radius: 2px; height: 49px; } .btn-success, .btn-primary { border-radius: 2px; box-shadow: 0 0 6px rgba(0,0,0,0.03); font-size: 12px; font-weight: 700; margin: 0; text-transform: uppercase; } } } } .form-horizontal { .btn-success, .btn-primary { border-radius: 2px; box-shadow: 0 0 6px rgba(0,0,0,0.03); font-size: 12px; font-weight: 700; margin: 0; text-transform: uppercase; } } .evo_panel__login { max-width: 400px; } .evo_panel__lostpass { max-width: 480px; #ffield_x label { display: none; } } .evo_panel__activation { max-width: 530px; #activateinfo_form .control-buttons{ text-align: left; } } .evo_panel__register { max-width: 580px; .control-buttons{ text-align: left; } &.register-disabled { width: 350px; } .form-control { &#country, &#u { width: 100%; } } } .evo_form__login_links { padding: 0 5px; font-size: 92%; } .evo_form__login { fieldset { margin-bottom: 20px; } .controls { padding: 0; margin: 0; width: 100%; } .control-buttons { margin-left: 0; } input.form-control[type=text], input.form-control[type=password] { width: 100%; } .btn { margin-top: 5px; } } #login_form { .control-buttons { text-align: left; } } .standard_login_link { text-align: center; margin: 3em 0 1ex 0; } .form_footer_notes { margin-top: 0; } // Pagination .pagination { border-radius: 2px !important; margin: 0; li > a, li > span { border: 0; padding: 10px 14px; } &>li:first-child>a, &>li:first-child>span { border-top-left-radius: 2px !important; border-bottom-left-radius: 2px !important; } &>li:last-child>a, &>li:last-child>span { border-top-right-radius: 2px !important; border-bottom-right-radius: 2px !important; } } @media only screen and (min-width: 320px) { li.listnav_last>a { border-top-right-radius: 2px; border-bottom-right-radius: 2px; } } @media only screen and (min-width: 992px) { li.listnav_last>a { border-top-right-radius: 0; border-bottom-right-radius: 0; } } // Messages div.action_messages, div.log_container { margin: 0; } // Positions on the action buttons near page titles .item_single_header { padding: 8px 0 20px; } .evo_post_title { display: table; h1 { margin-bottom: 0; } h2 { display: table-cell; margin: 0; padding: 20px 0 0; } .btn-group { display: table-cell; // padding: 20px 0 10px 30px; padding: 5px 0 0 30px; vertical-align: middle; a { // Never override these colors color: #333 !important; background-color: #fff !important; border-color: #ccc !important; } } } // This skin needs this for disp=posts to separate from lower pagination footer.row { margin-top: 20px; } // Overrule predefined background-color style .avatar_main_frame { background-color: transparent; }<file_sep>/_body_header.inc.php <?php /** * This is the BODY header include template. * * For a quick explanation of b2evo 2.0 skins, please start here: * {@link http://b2evolution.net/man/skin-development-primer} * * This is meant to be included in a page template. * * @package evoskins */ if( !defined('EVO_MAIN_INIT') ) die( 'Please, do not access this page directly.' ); // ---------------------------- SITE HEADER INCLUDED HERE ---------------------------- // If site headers are enabled, they will be included here: siteskin_include( '_site_body_header.inc.php' ); // ------------------------------- END OF SITE HEADER -------------------------------- ?> <div class="container"> <header class="row"> <div class="coll-xs-12 coll-sm-12 col-md-4 col-md-push-8"> <div class="evo_container evo_container__page_top"> <?php // ------------------------- "Page Top" CONTAINER EMBEDDED HERE -------------------------- // Display container and contents: skin_container( NT_('Page Top'), array( // The following params will be used as defaults for widgets included in this container: 'block_start' => '<div class="evo_widget $wi_class$">', 'block_end' => '</div>', 'block_display_title' => false, 'list_start' => '<ul>', 'list_end' => '</ul>', 'item_start' => '<li>', 'item_end' => '</li>', ) ); // ----------------------------- END OF "Page Top" CONTAINER ----------------------------- ?> </div> </div><!-- .col --> <div class="coll-xs-12 col-sm-12 col-md-8 col-md-pull-4"> <div class="evo_container evo_container__header"> <?php // ------------------------- "Header" CONTAINER EMBEDDED HERE -------------------------- // Display container and contents: skin_container( NT_('Header'), array( // The following params will be used as defaults for widgets included in this container: 'block_start' => '<div class="evo_widget $wi_class$">', 'block_end' => '</div>', 'block_title_start' => '<h1>', 'block_title_end' => '</h1>', ) ); // ----------------------------- END OF "Header" CONTAINER ----------------------------- ?> </div> </div><!-- .col --> </header><!-- .row --> <nav class="navbar navbar-default"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <!--<a class="navbar-brand" href="#">Brand</a>--> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav"> <?php // ------------------------- "Menu" CONTAINER EMBEDDED HERE -------------------------- // Display container and contents: // Note: this container is designed to be a single <ul> list skin_container( NT_('Menu'), array( // The following params will be used as defaults for widgets included in this container: 'block_start' => '', 'block_end' => '', 'block_display_title' => false, 'list_start' => '', 'list_end' => '', 'item_start' => '<li class="evo_widget $wi_class$">', 'item_end' => '</li>', 'item_selected_start' => '<li class="active evo_widget $wi_class$">', 'item_selected_end' => '</li>', 'item_title_before' => '', 'item_title_after' => '', ) ); // ----------------------------- END OF "Menu" CONTAINER ----------------------------- ?> </ul> </div><!-- /.navbar-collapse --> </nav><file_sep>/README.md ## Lava Blog Skin ![Skinshot](skinshot.png)
81d5b11ebb75a19099b9ef48e8310416c2b9c4a1
[ "Markdown", "Less", "PHP" ]
3
Markdown
b2evolution/blackorange_skin
1efca4c62a74113cd4da3d29741f9bda366dcae2
cb4f7d5be76a64a7d3dfaa0dd32d8a300aeb4bc2
refs/heads/master
<repo_name>leaf-tr/front-end<file_sep>/src/components/ItemsProfiles/TextBlock.jsx import React from 'react' import Paragraph from '../Paragraph' export default function TextBlock({ accent, className, textElements, size, weight }) { return ( <div className={`mt-4 ${className}`}> { textElements.map((text, id) => ( <Paragraph key={id} accent={accent} size={size} weight={weight}> <span> {text.label} </span> {text.content} </Paragraph> )) } </div> ) }<file_sep>/src/components/Button/style.js export const ButtonSize = { sm: 'py-2 px-4 text-sm', md: 'py-2 px-4 text-base', lg: 'py-3 px-16 text-2xl' }; <file_sep>/src/components/Paragraph/index.jsx import React from 'react' export default function Paragraph({ accent = 'black', children, className, size = 'base', weight = 'normal' }) { return ( <div className={`text-${size} text-${accent} font-${weight} ${className}`}> { children } </div> ) }<file_sep>/src/components/Charts/CustomBarChart.jsx import React from 'react' import { Bar, BarChart, CartesianGrid, XAxis, YAxis } from 'recharts'; export default function CustomBarChart() { const data = [ { name: 'Jan', pv: 0, }, { name: 'Feb', pv: 1, }, { name: 'Mar', pv: 5, }, { name: 'Apr', pv: 1, }, { name: 'May', pv: 0, }, { name: 'Jun', pv: 0, }, { name: 'Jul', pv: 1, }, { name: 'Aug', pv: 2, }, { name: 'Sep', pv: 1, }, { name: 'Oct', pv: 3, }, { name: 'Nov', pv: 0, }, { name: 'Dec', pv: 1, }, ]; return ( <div> <BarChart width={900} height={250} data={data} barCategoryGap={'10%'} > <CartesianGrid strokeDasharray="3 3" /> <XAxis dataKey="name" /> <YAxis /> {/* <Legend /> */} <Bar dataKey="pv" fill="#8884d8" /> </BarChart> </div> ) }<file_sep>/Dockerfile FROM node:10-alpine # RUN mkdir -p /app WORKDIR /app COPY package.json /app RUN npm install COPY . /app # start app # CMD ["npm", "start"] <file_sep>/src/provider/externalApiRequests.js import axios from 'axios' import parser from 'fast-xml-parser' const GOODREADS = { BaseURL: 'https://www.goodreads.com', SearchURL: 'search/index.xml', DevKey: process.env.REACT_APP_GOODREADS_KEY, } const GOOGLEBOOKS = { BaseURL: 'https://www.googleapis.com/books/v1', DevKey: process.env.REACT_APP_GOOGLEBOOKS_KEY, } export const getBookDataByIsbn = async (isbn) => { // response.data.items[0].id const requestURL = `https://cors-anywhere.herokuapp.com/${GOOGLEBOOKS.BaseURL}/volumes?q=isbn:${isbn}&key=${GOOGLEBOOKS.DevKey}` try { const response = await axios.get(requestURL, { headers: { 'Content-type': 'application/json' } }) const volumeInfo = response.data.items[0].volumeInfo const bookData = { "title": volumeInfo.title, "authors": volumeInfo.authors, "genres": volumeInfo.categories, "imgUrl": volumeInfo.imageLinks.smallThumbnail, "publishedDate": volumeInfo.publishedDate, "publisher": volumeInfo.publisher, "description": volumeInfo.description, "pageCount": volumeInfo.pageCount, "isbn": isbn, } console.log("JSON", bookData) return bookData } catch (e) { console.log(e) } }<file_sep>/src/components/FlexBox/index.jsx import React from 'react' export default function FlexBox({ children, className, direction = 'row' }) { return ( <div className={`flex flex-${direction} ${className}`}> { children } </div> ) }<file_sep>/src/provider/containers.jsx /* eslint-disable react-hooks/rules-of-hooks */ import { useState } from 'react'; import { createContainer } from 'unstated-next'; function userData() { let [loggedIn, setLoggedIn] = useState(false) let [userData, setUserData] = useState({}); return { loggedIn, setLoggedIn, userData, setUserData } } export const UserContainer = createContainer(userData) <file_sep>/postcss.config.js //postcss.config.js const tailwindcss = require('tailwindcss') // const purgecss = require('@fullhuman/postcss-purgecss') module.exports = { plugins: [ require('postcss-import'), // for @import statements tailwindcss('./tailwind.js'), // css utility library config // require('autoprefixer'), // auto-add prefixes like --webkit // Purge and minify CSS only production builds only // ...(process.env.NODE_ENV === "production" // ? [purgecss, require("cssnano")] // : []), ], };<file_sep>/src/components/Sidebar.jsx import React from 'react'; import { NavLink, Link } from 'react-router-dom'; import { BookOpen, Clock, TrendingUp, } from 'react-feather'; import Button from './Button'; export default function Sidebar() { let sidebarItemClass = "flex items-center text-lightGreen-600 opacity-75 hover:opacity-100 py-4 pl-6" let activeSidebarItemClass = "bg-lightGreen-500 opacity-100" return ( <aside className="relative w-64 bg-white shadow-xl hidden sm:block"> <div className="pt-3"> <div className="flex items-center justify-center flex-shrink-0"> <img alt="Leaf logo" className="h-12 w-12 mr-2" src="https://image.flaticon.com/icons/svg/3095/3095108.svg" /> <span className="font-semibold text-black text-xl tracking-tight">Leaf</span> </div> </div> <nav className="pt-24 text-base font-semibold"> <NavLink to={"/dashboard"} className={sidebarItemClass} activeStyle={{color: "white"}} activeClassName={activeSidebarItemClass}> <TrendingUp /> <span className="ml-4">Dashboard</span> </NavLink> <NavLink to={"/reading-library"} className={sidebarItemClass} activeStyle={{color: "white"}} activeClassName={activeSidebarItemClass}> <BookOpen /> <span className="ml-4">Reading Library</span> </NavLink> <ul className="ml-16 text-lightGreen-500"> <Link to={"/reading-library/favorites"}> <li className="opacity-75 hover:opacity-100"> Favorites </li> </Link> <Link to={"/reading-library/to-be-read"}> <li className="opacity-75 hover:opacity-100"> To be read </li> </Link> </ul> <NavLink to={"/timeline"} className={sidebarItemClass} activeStyle={{color: "white"}} activeClassName={activeSidebarItemClass}> <Clock /> <span className="ml-4">Timeline</span> </NavLink> </nav> <div style={{ position: 'absolute', bottom: '5%' }}> <NavLink to={"/add-new-item"} className={sidebarItemClass}> <Button color="lightGreen" onClick={() => { console.log("add new item") }} outline > Add new item </Button> </NavLink> {/* <ToggleButton> */} <div className={sidebarItemClass} > <span className="mr-2">Dark Mode</span> <Button color="gray" onClick={() => { console.log("add new item") }} outline > </Button> </div> </div> </aside> ) }<file_sep>/src/components/Button/index.jsx import React from 'react'; import classNames from 'classnames'; import { ButtonSize } from './style'; export default function Button({ children, color, onClick, outline, size = 'md' }) { let btnColor = "" if (outline) { btnColor = `border-${color}-500 border-2 text-${color}-500 bg-white focus:outline-none hover:text-white hover:bg-${color}-500 ` } else { btnColor = `text-white bg-${color}-500 focus:outline-none hover:bg-${color}-600` } const btnClass = classNames('font-semibold items-center flex justify-center items-center rounded-lg ', btnColor, { [`${ButtonSize.sm}`]: (size === 'sm'), [`${ButtonSize.md}`]: (size === 'md'), [`${ButtonSize.lg}`]: (size === 'lg'), }); return ( <button className={btnClass} onClick={onClick}> {children} </button> ); }<file_sep>/src/pages/ItemProfile.jsx import React, {useEffect, useState} from 'react' import BookData from '../components/ItemsProfiles/BookData' // future: import JournalData from '../components/ItemsProfiles/JournalData' import DropDown from '../components/DropDown' import Editor from '../components/Editor' import FlexBox from '../components/FlexBox' // import object of reading progress options import { ReadingProgress } from '../provider/constants' import { getBookDataByIsbn } from '../provider/externalApiRequests' export default function ItemProfile({ id }) { const [bookData, setBookData] = useState({}) // on component mount fetch goodreads API // by book's ISBN given in the URL param as an id useEffect(() => { fetchBookByIsbn(id) }, []) const fetchBookByIsbn = async (id) => { let retrievedData = await getBookDataByIsbn(id) setBookData(retrievedData) console.log("BOOK DATA FROM GOODREADS", retrievedData) } return ( <div className="mx-20"> <FlexBox className="mt-20 mx-auto"> {/* left col w/ image, rating, and reading progress */} <FlexBox direction="col"> <img src={bookData.imgUrl} alt="" /> {/* <Rating></Rating> */} <DropDown options={Object.values(ReadingProgress)} /> </FlexBox> {/* right col w/ metadata */} <div className="flex-grow"> { Object.values(bookData).length && <BookData data={bookData} /> } </div> </FlexBox> <Editor /> </div> ) } <file_sep>/src/components/ItemsProfiles/BookData.jsx import React from 'react' import FlexBox from '../FlexBox' import Paragraph from '../Paragraph' import TextBlock from './TextBlock' export default function BookData({ data }) { return ( <FlexBox direction="col" className="ml-10 -mt-4"> <Paragraph size="4xl" weight="bold"> {data.title} </Paragraph> <Paragraph size="2xl"> {data.authors[0]} </Paragraph> {/* genres */} { data && data.genres && data.genres.map((genre, id) => ( <Paragraph key={id} className="mt-2" size="lg">{genre}</Paragraph> )) } <TextBlock textElements={[ { label: 'Date Published: ', content: data.publishedDate }, { label: 'Publisher: ', content: data.publisher }, { label: 'ISBN: ', content: data.isbn } ]} /> <TextBlock textElements={[ { label: 'Page Count: ', content: data.pageCount } ]} /> {/* date Started, date Finished from user library <div className="mt-4"> <Paragraph size="sm"> date Started: {data.} </Paragraph> <Paragraph size="sm"> date Finished: {data.} </Paragraph> </div> */} </FlexBox> ) } <file_sep>/src/App.js import React, { createContext, useState, useEffect } from 'react' import { Redirect, Route, Switch } from 'react-router-dom' import Header from './components/Header' import Sidebar from './components/Sidebar' import Dashboard from './pages/Dashboard' import Landing from './pages/Landing' import ReadingLibrary from './pages/ReadingLibrary' import ItemProfile from './pages/ItemProfile' import * as firebase from 'firebase' import firebaseConfig from './firebase.config' import { UserContainer } from './provider/containers' firebase.initializeApp(firebaseConfig) function App() { const container = UserContainer.useContainer() const { loggedIn, setLoggedIn, userData, setUserData } = container function readSession() { const user = window.sessionStorage.getItem( `firebase:authUser:${firebaseConfig.apiKey}:[DEFAULT]` ); if (user) { setLoggedIn(true) const json_data = JSON.parse(user) setUserData({ id: json_data.uid, data: { firstName: json_data.displayName.split(" ")[0], lastName: json_data.displayName.split(" ")[1], imgUrl: json_data.photoURL } }) } } useEffect(() => { readSession() }, []) return ( <> { loggedIn ? ( <div className="flex" style={{ height: '120vh' }}> <Sidebar /> <div className="mx-6 w-full flex flex-col h-screen"> <Header /> <Switch> <Route exact path="/" component={Dashboard}> <Redirect to="/dashboard" /> </Route> <Route path="/dashboard" component={Dashboard} /> <Route exact path="/reading-library" component={ReadingLibrary} /> <Route path="/reading-library/:id" render={({ match }) => (<ItemProfile id={match.params.id} />)} /> </Switch> </div> </div> ) : ( <> <Route exact path="/" component={Landing} /> {/* <Redirect to="/" /> */} </> ) } </> ) } export default App <file_sep>/src/components/Header.jsx import React from 'react'; import { UserContainer } from '../provider/containers' export default function Header({ user }) { const container = UserContainer.useContainer() const { userData, setUserData} = container return ( <> {/* <!-- Desktop Header --> */} <header className="w-full bg-white items-center py-4 px-6 hidden rounded-b-md shadow-xl sm:flex"> <div className="w-1/2"></div> <div className="relative w-1/2 flex justify-end items-center"> <button className="relative z-10 w-8 h-8 rounded-full overflow-hidden"> <img src={userData.data.imgUrl} alt="img profile" /> </button> <span className="ml-2">{userData.data.firstName}</span> {/* <div className="absolute w-32 bg-white rounded-lg shadow-lg py-2 mt-16"> <a href="#" className="block px-4 py-2 account-link hover:text-primary">Account</a> <a href="#" className="block px-4 py-2 account-link hover:text-primary">Support</a> <a href="#" className="block px-4 py-2 account-link hover:text-primary">Sign Out</a> </div> */} </div> </header> {/* <!-- Mobile Header & Nav --> */} {/* <header className="w-full bg-white py-5 px-6 sm:hidden"> <div className="flex items-center justify-between"> <a href="index.html" className="text-primary text-3xl font-semibold uppercase hover:text-gray-300">Admin</a> <button className="text-primary text-3xl focus:outline-none"> <i className="fas fa-bars"></i> <i className="fas fa-times"></i> </button> </div> {/* <!-- Dropdown Nav --> <nav className="flex flex-col pt-4"> <a href="index.html" className="flex items-center active-nav-link text-primary py-2 pl-4 nav-item"> <i className="fas fa-tachometer-alt mr-3"></i> Dashboard </a> </nav> </header> */} </> ) }<file_sep>/src/firebase.config.js export default { apiKey: "<KEY>", authDomain: "leaf-tr.firebaseapp.com", databaseURL: "https://leaf-tr.firebaseio.com", projectId: "leaf-tr", storageBucket: "leaf-tr.appspot.com", messagingSenderId: "757674002843", appId: "1:757674002843:web:2a8c198a998a955f61b93e", measurementId: "G-3CTQ4JYRXG" };<file_sep>/src/pages/Login.jsx import React, { useState } from 'react' import * as firebase from 'firebase' import { authenticateUser } from '../provider/apiRequests' import { UserContainer } from '../provider/containers' import Button from '../components/Button' export default function Login() { const [error, setErrors] = useState("") const container = UserContainer.useContainer() const { setUserData, setLoggedIn } = container const signInWithGoogle = async () => { const provider = new firebase.auth.GoogleAuthProvider(); firebase .auth() .setPersistence(firebase.auth.Auth.Persistence.SESSION) .then(() => { firebase .auth() .signInWithPopup(provider) .then(result => { // access API endpoint to authenticate the user // POST api/users let data = result authenticateUser(data) setUserData({ id: data.user.uid, data: { firstName: data.additionalUserInfo.profile.given_name, lastName: data.additionalUserInfo.profile.family_name, imgUrl: data.additionalUserInfo.profile.picture } }) // let user_db_data = await authenticateUser(data) // setUserData(user_db_data) setLoggedIn(true) }) .catch(e => setErrors(e.message)) }) } return ( <div> <h1>Login</h1> <Button color="orange" onClick={() => signInWithGoogle()} outline> <img className="w-6" src="https://upload.wikimedia.org/wikipedia/commons/5/53/Google_%22G%22_Logo.svg" alt="logo" /> <span className="ml-2"> Login With Google </span> </Button> </div> ) }
a6bcdb8d01618e65eadcd311ca5870cd3cff175e
[ "JavaScript", "Dockerfile" ]
17
JavaScript
leaf-tr/front-end
6db43623e30c9f433ff73046036852b2ec9737b6
9864ad08c12f6e159389de454f9c18adef546a27
refs/heads/master
<file_sep># hello-world hi,humans: Github here,I like java and python.
393add1df59a54fa13bcd319f1c04195e9e726b9
[ "Markdown" ]
1
Markdown
localhostX/hello-world
301e20d26d8c19b9a70d2962e43ec588a7244ec5
dc2a533ed47638f06eb0ad7ca6e94e1a97b0dc4a
refs/heads/master
<repo_name>albenK/shootThemDown<file_sep>/Enemies.pde /* CREATOR: <NAME> DATE CREATED: 7/6/2015 EMAIL: <EMAIL> PROJECT: SHOOT THEM DOWN */ // Make new class for enemies. class Enemies { private float enemyXposition,enemyYposition,enemyWdth,enemyHght,enemyYspeed; // declare variables. public Enemies(float eSpeed) // constructor. { enemyXposition = random(50,width - 51); enemyYposition = 25; enemyWdth = 50; enemyHght = 50; enemyYspeed = eSpeed; } private void displayEnemies() // create function to display enemy. { rectMode(CENTER); fill(255,0,0); noStroke(); rect(enemyXposition,enemyYposition,enemyWdth,enemyHght); // ellipse or rectangle. } private void moveEnemies() // creat function to move enemies. { enemyYposition += enemyYspeed; } private boolean enemyPassesBottomPartOfScreen() // create function to check enemies, if they go out of screen. { if(enemyYposition >= height + 25) { return true; } return false; } } <file_sep>/Spaceship.pde /* CREATOR: <NAME> DATE CREATED: 7/6/2015 EMAIL: <EMAIL> PROJECT: SHOOT THEM DOWN */ //create class for spaceship. class Spaceship { private float spaceshipXposition,spaceshipYposition,xSpeed; // declare variables. public Spaceship() // constructor. { spaceshipXposition = width/2; spaceshipYposition = height - 20; xSpeed = 6; upArrowKeyIsPressed = false; leftArrowKeyIsPressed = false; rightArrowKeyIsPressed = false; } private void displayShip() // create function to display the ship. { fill(0); noStroke(); triangle(spaceshipXposition-20,spaceshipYposition+20,spaceshipXposition+20,spaceshipYposition+20,spaceshipXposition,spaceshipYposition-20); } public void moveSpaceShipRight() { spaceshipXposition += xSpeed; } public void moveSpaceShipLeft() { spaceshipXposition -= xSpeed; } private void moveShip() // create function to move the ship. { // if(keyPressed) // { // if(keyCode == RIGHT) // move ship right. // { // rightArrowKeyIsPressed = true; // leftArrowKeyIsPressed = false; // spaceshipXposition += xSpeed; // if(spaceshipXposition > width-20) //ship cannot go past right side. // { // spaceshipXposition = 0; // } // } // if(keyCode == LEFT) // move ship left. // { // leftArrowKeyIsPressed = true; // rightArrowKeyIsPressed = false; // spaceshipXposition -= xSpeed; // if(spaceshipXposition < 20) //ship cannot go past left side. // { // spaceshipXposition = width; // } // } // } } private void loadBullet() // create function to add new bullets to bullets collection. { bullets.add(new Bullet()); } } <file_sep>/MainMenu.pde public class mainMenu { private String[] mainMenuOptions; private String play,instructions,exit; // menu options; private String playerSelection,titleOfGame; private int numberOfOptionsInMainMenu,currentlySelected,R,G,B; mainMenu() { titleOfGame = "SHOOT THEM DOWN"; numberOfOptionsInMainMenu = 3; mainMenuOptions = new String[numberOfOptionsInMainMenu]; play = "PLAY"; instructions = "INSTRUCTIONS"; exit = "EXIT"; playerSelection = play; mainMenuOptions[0] = play; mainMenuOptions[1] = instructions; mainMenuOptions[2] = exit; currentlySelected = 0; } public void displayMainMenu() { for(int index = 0; index < mainMenuOptions.length; index++) { if(currentlySelected == index) { R = 255; G = 0; B = 0; playerSelection = mainMenuOptions[index]; } else { R = 0; G = 0; B = 0; } fill(R,G,B); textSize(50); text(mainMenuOptions[index],width/4,(height/2)+(index*50)); textSize(30); fill(255,0,0); text(titleOfGame,width/4,height/4); } } public void checkForMainMenuOptionChanges() // checks for currently selected.. { if(keyPressed && keyCode == DOWN) { currentlySelected += 1; if(currentlySelected >= mainMenuOptions.length) {currentlySelected = 0;} } else if(keyPressed && keyCode == UP) { currentlySelected -= 1; if(currentlySelected < 0){currentlySelected = mainMenuOptions.length - 1;} } } public String getPlayerSelection() // returns player selection... { return playerSelection; } } <file_sep>/README.md # shootThemDown A simple spaceship shooting game created using Processing. How to run: 1. Go to https://processing.org/download/ 2. Download processing. *NOTE: This game was created in Procesing2, so please download version 2 and not version 3. Otherwise you may get some compilation errors.* 3. Once Processing2 is downloaded, open up the ".pde" files and then click the play button to run the game! Enjoy! How to play: Once the main menu screen appears, press enter while "Play" is highlighted. Some options dont do anything yet :( Use the LEFT and RIGHT arrow keys to move. Use the UP arrow key to shoot enemies coming down. Once "power up active" message appears, you may shoot and move at the same time! If any of the enemies pass the bottom part of the screen, it's game over. <file_sep>/Bullet.pde /* CREATOR: <NAME> DATE CREATED: 7/6/2015 EMAIL: <EMAIL> PROJECT: SHOOT THEM DOWN */ // Create class for bullet, to shoot enemies. class Bullet { private float bulletXposition, bulletYposition; // declare variables. private float bulletXspeed, bulletYspeed; public Bullet() // constructor. { bulletXposition = spaceship.spaceshipXposition; bulletYposition = spaceship.spaceshipYposition; bulletXspeed = 0; bulletYspeed = -5; } private void displayBullet() { strokeWeight(5); stroke(0); line(bulletXposition, bulletYposition + 5, bulletXposition,bulletYposition-5); } private void moveBullet() // create function to move bullet up. { bulletYposition += bulletYspeed; } private boolean bulletGoesOffScreen() // create function to check bullets, if they go out of screen. { if(bulletYposition <= -10) {return true;} return false; } } <file_sep>/shootThemDown_.pde /* CREATOR: <NAME> DATE CREATED: 7/6/2015 EMAIL: <EMAIL> PROJECT: SHOOT THEM DOWN */ /*-------------------------------- SHOOT THEM DOWN ---------------------------------------------------------------------- */ import java.io.FileNotFoundException; // Declare variables private Spaceship spaceship; private Enemies enemies; private float enemySpeed; private Bullet bullet; private boolean gameIsRunning; private boolean displayTheMenu; private int sizeX = 500; private int sizeY = 500; private ArrayList <Bullet> bullets = new ArrayList <Bullet>(); private ArrayList <Enemies> listEnemies = new ArrayList <Enemies>(); private mainMenu theMainMenu; private int score; private String highScore; private String[] highScoreList; public boolean upArrowKeyIsPressed,leftArrowKeyIsPressed,rightArrowKeyIsPressed; public boolean powerUpActivate; // Initialize variables void setup() { frameRate(60); size(sizeX, sizeY); //background = loadImage("earth.jpg"); spaceship = new Spaceship(); //enemies = new Enemies(); enemySpeed = 6; bullet = new Bullet(); score = 0; highScoreList = new String[1]; theMainMenu = new mainMenu(); displayTheMenu = true; upArrowKeyIsPressed = false; leftArrowKeyIsPressed = false; rightArrowKeyIsPressed = false; powerUpActivate = false; gameIsRunning = false; } //Run program void draw() { background(255); if(necessaryFilesAreHere()) // check if files are in directory. { if(gameIsRunning) { // println("left: "+spaceship.leftArrowKeyIsPressed // +" right: "+spaceship.rightArrowKeyIsPressed+ // " up: "+spaceship.upArrowKeyIsPressed+" END ");} if(frameCount % 45 == 0) {listEnemies.add(new Enemies(enemySpeed));} // add new enemies to collection. startPlayingGame(); } else if(!gameIsRunning && !displayTheMenu) // display game over message and score. { // println("its game over!!!!"); displayGameOverMessage(); } else // display the main menu. { theMainMenu.displayMainMenu(); } } else // game files are missing, so display error message. { displayErrorMessage(); } } public void resetGame() { listEnemies.clear(); bullets.clear(); upArrowKeyIsPressed = false; leftArrowKeyIsPressed = false; rightArrowKeyIsPressed = false; powerUpActivate = false; score = 0; } private boolean necessaryFilesAreHere() // method to make sure files are in directory. { try { getHighScore(); } catch(Exception e) // if game files are missing, then return false; { return false; } return true; } private void displayErrorMessage() // method to display error message. { textSize(15);fill(255,0,0);text(" ERROR: ONE OF THE GAME FILES IS MISSING :(",(width/4)-50,height/4); text("PLEASE DOWNLOAD THE GAME AGAIN FROM WEBSITE.",(width/4)- 50,(height/4) + 50); } private String getHighScore() // method to return the current high score. { String[] highScoreArray = loadStrings("data/highscore(2).cdt"); return highScoreArray[0]; } private void updateHighScore(int thisScore) // method to update the high score. { highScoreList[0] = str(thisScore); saveStrings("data/highscore(2).cdt",highScoreList); } void keyPressed() { if(gameIsRunning && !displayTheMenu) { if(key == CODED && keyCode == UP) { upArrowKeyIsPressed = true; } else if(key == CODED && keyCode == LEFT) { leftArrowKeyIsPressed = true; } else if(key == CODED && keyCode == RIGHT) { rightArrowKeyIsPressed = true; } } else if(keyCode == ENTER && !gameIsRunning && !displayTheMenu) { gameIsRunning = true; resetGame(); } else if(!gameIsRunning && displayTheMenu) { theMainMenu.checkForMainMenuOptionChanges(); if(theMainMenu.getPlayerSelection() == "PLAY" && keyCode == ENTER) { gameIsRunning = true; displayTheMenu = false; } if(theMainMenu.getPlayerSelection() == "EXIT" && keyCode == ENTER) { exit(); // exits the program.. } } } void keyReleased() { if(key == CODED && gameIsRunning && !displayTheMenu) //just double checking.. { if(keyCode == UP) { upArrowKeyIsPressed = false; } if(keyCode == LEFT) { leftArrowKeyIsPressed = false; } if(keyCode == RIGHT) { rightArrowKeyIsPressed = false; } } } private void displayGameOverMessage() // method to display game over and score. { textSize(30); text("GAME OVER!",(width/2) - 100, (height/4)/2); textSize(20); fill(0); text("YOUR SCORE IS: "+score,(width/2) - 100,height/4); text("THE HIGH SCORE ON THIS PC IS: "+getHighScore(),(width/2) - 170, height/3); fill(255,0,0); text("(Press the ENTER key to restart)", (width/2) - 150,height/2); } public void checkForSpaceShipMovement() { if(leftArrowKeyIsPressed) { spaceship.moveSpaceShipLeft(); if(spaceship.spaceshipXposition < 20) //ship cannot go past left side. { spaceship.spaceshipXposition = width; } } else if(rightArrowKeyIsPressed) { spaceship.moveSpaceShipRight(); if(spaceship.spaceshipXposition > width-20) //ship cannot go past right side. { spaceship.spaceshipXposition = 0; } } else if(upArrowKeyIsPressed) { spaceship.loadBullet(); // add new bullet to collection. } if(powerUpActivate) { if(leftArrowKeyIsPressed && upArrowKeyIsPressed) { //spaceship.moveSpaceShipLeft(); spaceship.loadBullet(); } if(rightArrowKeyIsPressed && upArrowKeyIsPressed) { //spaceship.moveSpaceShipRight(); spaceship.loadBullet(); } } } public void displayPowerUpNotification() { textSize(15); fill(0,0,255); text("POWER UP ACTIVE!",width/2,(height/2)+20); } //create function to run the game. private void startPlayingGame() { highScore = getHighScore(); spaceship.displayShip(); checkForSpaceShipMovement(); //spaceship.moveShip(); fill(0); textSize(30); text("SCORE: "+score,width/2,height/2); // dislpay current score. if(score > int(highScore)) {updateHighScore(score);} // update the high score. if(score > 0 && score % 100 == 0 && score % 200 != 0) { powerUpActivate = true; } else if(score % 200 == 0) { powerUpActivate = false; } if(powerUpActivate) { displayPowerUpNotification(); } for(int i = bullets.size() - 1; i > -1; i--) // display and move bullets. { Bullet b = bullets.get(i); b.displayBullet(); b.moveBullet(); if(b.bulletGoesOffScreen()) {bullets.remove(i);} // remove bullets if off screen. } for(int i = listEnemies.size() - 1; i > -1; i--) // display and move enemies. { Enemies e = listEnemies.get(i); e.displayEnemies(); e.moveEnemies(); if(e.enemyPassesBottomPartOfScreen()) // player looses game, so clear everything. { listEnemies.clear(); bullets.clear(); gameIsRunning = false; break; } } for(int i = bullets.size() - 1; i > -1; i--) { Bullet b = bullets.get(i); for(int j = listEnemies.size() - 1; j > -1; j--) { Enemies e = listEnemies.get(j); //if bullet hits enemy, then remove that enemy and bullet. if(b.bulletXposition >= e.enemyXposition-25 && b.bulletXposition <= e.enemyXposition+25 && b.bulletYposition <= e.enemyYposition + 25 && b.bulletYposition >= e.enemyYposition - 25) { bullets.remove(i); listEnemies.remove(j); score += 5; break; } } } }
69540baec2f6a507dec19908eac0aab3e4cdc378
[ "Processing", "Markdown" ]
6
Processing
albenK/shootThemDown
b4ac4afc2beef175a739d37106a69be2e6d519c6
9efc850f3f4eb89bd816c995a226037feb0b664e
refs/heads/master
<file_sep># liquidvoting.smartcontract Solidity Smart contract for Liquid Voting
0dec9d1d7644cf80b00c2168f616d958073c338a
[ "Markdown" ]
1
Markdown
Hackthings/liquidvoting.smartcontract
41a7bd16802d6b37dba07c6e8cb8fe2387957848
5834e306f4cf9b2a7b3f53027f867188df20dbef
refs/heads/master
<repo_name>namuan/apidocs-example<file_sep>/grails-app/domain/apidocs/example/Company.groovy package apidocs.example class Company { String name String address } <file_sep>/src/groovy/apidocs/example/Employee.groovy package apidocs.example class Employee { String name Date dateOfBirth Company employer } <file_sep>/grails-app/controllers/apidocs/example/GreetingsController.groovy package apidocs.example import com.imon.apidocs.annotations.Api import com.imon.apidocs.annotations.ApiOperation @Api(module="paymentMethod", description = "") class GreetingsController { @ApiOperation(value = "Hello world", responseClass = Employee.class) def hello(String name) { println "Hello world" } } <file_sep>/grails-app/controllers/apidocs/example/CompanyController.groovy package apidocs.example import com.imon.apidocs.annotations.Api import com.imon.apidocs.annotations.ApiOperation @Api(module="companyModule", description="Deals with company resource", href = "https://sites.google.com/home") class CompanyController { @ApiOperation(value="List all companies", notes="", responseClass=List) def list() { println "List" } @ApiOperation(value="Create a new company", notes="", responseClass=Company) def create() { println "Create" } @ApiOperation(value="Display details for given company", notes="", responseClass=Company) def show() { println "Show" } @ApiOperation(value="Delete company", notes="", responseClass=Company) def delete() { println "Delete" } @ApiOperation(value="Update company", notes="", responseClass=Company) def update() { println "Update" } }<file_sep>/grails-app/conf/UrlMappings.groovy class UrlMappings { static mappings = { name greetingModule: "/greetings/${name}"(controller: "greetings") { action = [GET: "hello"]} name companyModule: "/companies"(controller: "company") { action = [GET: "list", POST: "create"] } name companyModule: "/companies/${id}"(controller: "company") { action = [DELETE: "delete", PUT: "update", GET: "show"] } "/$controller/$action?/$id?"{ constraints { // apply constraints here } } "/"(view:"/index") "500"(view:'/error') } } <file_sep>/README.md apidocs-example =============== A sample application to use apidocs grails plugin
873496abc6a69c1c2d0fe2fd5ae4585257c01cd8
[ "Groovy", "Markdown" ]
6
Groovy
namuan/apidocs-example
60b269ef6e230c85ded9806e1e5ad946c1c4e431
7f4f4248569777a6e262ef234f81ba8aae9c0ba2
refs/heads/master
<file_sep>using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; namespace VenteExtension.Models { public class Client { //[DatabaseGenerated(DatabaseGeneratedOption.None)] public int clientID { get; set; } public string nomCl { get; set; } public string prenomCl { get; set; } public string tel { get; set; } public string mail { get; set; } public virtual ICollection<Commande> Commandes { get; set; } } }<file_sep>@model IEnumerable<VenteExtension.Models.Commande> @{ ViewBag.Title = "Index"; } <h2>Index</h2> <p> @Html.ActionLink("Create New", "Create") </p> <table class="table"> <tr> <th> @Html.DisplayNameFor(model => model.client.nomCl) </th> <th> @Html.DisplayNameFor(model => model.produit.NomExt) </th> <th> @Html.DisplayNameFor(model => model.quantCom) </th> <th> @Html.DisplayNameFor(model => model.prixTot) </th> <th> @Html.DisplayNameFor(model => model.dateCom) </th> <th></th> </tr> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.client.nomCl) </td> <td> @Html.DisplayFor(modelItem => item.produit.NomExt) </td> <td> @Html.DisplayFor(modelItem => item.quantCom) </td> <td> @Html.DisplayFor(modelItem => item.prixTot) </td> <td> @Html.DisplayFor(modelItem => item.dateCom) </td> <td> @Html.ActionLink("Edit", "Edit", new { id = item.commandeID }) | @Html.ActionLink("Details", "Details", new { id = item.commandeID }) | @Html.ActionLink("Delete", "Delete", new { id = item.commandeID }) </td> </tr> } </table> @ViewBag.error<file_sep>@{ ViewBag.Title = "Home Page"; } <div class="jumbotron"> <h1>Vente extension de cheveux</h1> </div> <div class="row"> <div class="col-md-4"> <h2>BIENVENUE SUR LE SITE DE VENTE D'EXTENSIONS DE CHEVEUX</h2> <p> Nous vous proposons des extensions de cheveux de tres hautes qualites à tres bons prix </p> </div> </div><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 VenteExtension.Models; //using VenteExtension.dal; //namespace VenteExtension.Controllers //{ // public class LignePanierController : Controller // { // private VenteContext db = new VenteContext(); // // GET: LignePanier // public ActionResult Index() // { // return View(db.LignePaniers.ToList()); // } // // GET: LignePanier/Details/5 // public ActionResult Details(int? id) // { // if (id == null) // { // return new HttpStatusCodeResult(HttpStatusCode.BadRequest); // } // LignePanier lignePanier = db.LignePaniers.Find(id); // if (lignePanier == null) // { // return HttpNotFound(); // } // return View(lignePanier); // } // // GET: LignePanier/Create // public ActionResult Create() // { // return View(); // } // // POST: LignePanier/Create // // Afin de déjouer les attaques par survalidation, activez les propriétés spécifiques auxquelles vous voulez établir une liaison. Pour // // plus de détails, consultez https://go.microsoft.com/fwlink/?LinkId=317598. // [HttpPost] // [ValidateAntiForgeryToken] // //public ActionResult Create([Bind(Include = "ID,IdProduit,q")] LignePanier lignePanier) // public ActionResult Create([Bind(Include = "ID,q")] LignePanier lignePanier) // { // if (ModelState.IsValid) // { // db.LignePaniers.Add(lignePanier); // db.SaveChanges(); // return RedirectToAction("Index"); // } // return View(lignePanier); // } // // GET: LignePanier/Edit/5 // public ActionResult Edit(int? id) // { // if (id == null) // { // return new HttpStatusCodeResult(HttpStatusCode.BadRequest); // } // LignePanier lignePanier = db.LignePaniers.Find(id); // if (lignePanier == null) // { // return HttpNotFound(); // } // return View(lignePanier); // } // // POST: LignePanier/Edit/5 // // Afin de déjouer les attaques par survalidation, activez les propriétés spécifiques auxquelles vous voulez établir une liaison. Pour // // plus de détails, consultez https://go.microsoft.com/fwlink/?LinkId=317598. // [HttpPost] // [ValidateAntiForgeryToken] // //public ActionResult Edit([Bind(Include = "ID,IdProduit,q")] LignePanier lignePanier) // public ActionResult Edit([Bind(Include = "ID,q")] LignePanier lignePanier) // { // if (ModelState.IsValid) // { // db.Entry(lignePanier).State = EntityState.Modified; // db.SaveChanges(); // return RedirectToAction("Index"); // } // return View(lignePanier); // } // // GET: LignePanier/Delete/5 // public ActionResult Delete(int? id) // { // if (id == null) // { // return new HttpStatusCodeResult(HttpStatusCode.BadRequest); // } // LignePanier lignePanier = db.LignePaniers.Find(id); // if (lignePanier == null) // { // return HttpNotFound(); // } // return View(lignePanier); // } // // POST: LignePanier/Delete/5 // [HttpPost, ActionName("Delete")] // [ValidateAntiForgeryToken] // public ActionResult DeleteConfirmed(int id) // { // LignePanier lignePanier = db.LignePaniers.Find(id); // db.LignePaniers.Remove(lignePanier); // db.SaveChanges(); // return RedirectToAction("Index"); // } // protected override void Dispose(bool disposing) // { // if (disposing) // { // db.Dispose(); // } // base.Dispose(disposing); // } // } //} <file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace VenteExtension.Models { public class Produit { [Key] public int ID { get; set; } public string NomExt { get; set; } [Range(0.01, double.MaxValue, ErrorMessage = "Le prix doit être positif.")] public decimal Prix_u { get; set; } public int quant { get; set; } public virtual ICollection<Commande> commandes { get; set; } //public virtual ICollection<LignePanier> lignePanier { get; set; } } }<file_sep>using Microsoft.Ajax.Utilities; using System; using System.Collections.Generic; using System.Linq; using System.Web; using VenteExtension.dal; namespace VenteExtension.Models { public class Commande { public int commandeID { get; set; } public int produitID { get; set; } public int clientID { get; set; } public int quantCom { get; set; } public decimal prixTot { get; set; } public DateTime dateCom { get; set; } = DateTime.Now; public virtual Produit produit { get; set; } public virtual Client client { get; set; } //public virtual LignePanier Ligne { get; set; } public decimal calculPrixTot() { //return prixTot = quantCom * (decimal)produit.Prix_u; //return prixTot; return prixTot = quantCom *produit.Prix_u; } public Boolean verifQuant() { if (quantCom > 0) { return true; } else return false; } } }<file_sep>namespace VenteExtension.Migrations { using System; using System.Data.Entity.Migrations; public partial class InitialCreate : DbMigration { public override void Up() { CreateTable( "dbo.Client", c => new { clientID = c.Int(nullable: false, identity: true), nomCl = c.String(), prenomCl = c.String(), tel = c.String(), mail = c.String(), }) .PrimaryKey(t => t.clientID); CreateTable( "dbo.Commande", c => new { commandeID = c.Int(nullable: false, identity: true), produitID = c.Int(nullable: false), clientID = c.Int(nullable: false), quantCom = c.Int(nullable: false), prixTot = c.Decimal(nullable: false, precision: 18, scale: 2), dateCom = c.DateTime(nullable: false), }) .PrimaryKey(t => t.commandeID) .ForeignKey("dbo.Client", t => t.clientID, cascadeDelete: true) .ForeignKey("dbo.Produit", t => t.produitID, cascadeDelete: true) .Index(t => t.produitID) .Index(t => t.clientID); CreateTable( "dbo.Produit", c => new { ID = c.Int(nullable: false, identity: true), NomExt = c.String(), Prix_u = c.Decimal(nullable: false, precision: 18, scale: 2), quant = c.Int(nullable: false), }) .PrimaryKey(t => t.ID); } public override void Down() { DropForeignKey("dbo.Commande", "produitID", "dbo.Produit"); DropForeignKey("dbo.Commande", "clientID", "dbo.Client"); DropIndex("dbo.Commande", new[] { "clientID" }); DropIndex("dbo.Commande", new[] { "produitID" }); DropTable("dbo.Produit"); DropTable("dbo.Commande"); DropTable("dbo.Client"); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using VenteExtension.dal; namespace VenteExtension.Models { public class LignePanier : IDisposable { public int ID { get; set; } public int IdProduit { get; set; } public int IdClient { get; set; } public int IdCommande { get; set; } public int q { get; set; } //public decimal montantCli { get; set; } public virtual ICollection<Produit> Produits { get; set; } public virtual Commande commande { get; set; } private VenteContext _context; public LignePanier(VenteContext context, int commandeID) { _context = context; IdCommande = commandeID; } public void ajout(int idProduit) { Commande com = _context.commandes.SingleOrDefault(s => s.commandeID == IdCommande && s.produitID == idProduit); if (com == null) { com = new Commande { commandeID = IdCommande, produitID = idProduit, quantCom = 1 }; _context.commandes.Add(com); } else { com.quantCom++; } _context.SaveChanges(); } public void supprimer(int comID) { Commande c = _context.commandes.SingleOrDefault(s => s.commandeID == comID); if (c != null) { _context.commandes.Remove(c); _context.SaveChanges(); } } public Commande ligne(int comID) { return _context.commandes.FirstOrDefault(p => p.commandeID == comID); } public IList<Commande> ligne() { IList<Commande> ls = (IList<Commande>)_context.commandes.Where(s => s.commandeID == IdCommande).Select(s => s.produitID).ToList(); return ls; } public decimal Total() { decimal T = _context.commandes.Where(s => s.commandeID == IdCommande).Select(s => s.produitID).Sum(); return T; } public int Nombre() { int n = _context.commandes.Where(s => s.commandeID == IdCommande).ToList().Count; return n; } public void Dispose() { if(_context != null) { _context.Dispose(); _context = null; } } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Diagnostics; using VenteExtension.Models; namespace VenteExtension.dal { public class VenteInitializer : System.Data.Entity.DropCreateDatabaseIfModelChanges<VenteContext> { protected override void Seed(VenteContext context) { var produits = new List<Produit> { new Produit{NomExt="Meche Liste noire",Prix_u=(decimal)75.50,quant=20}, new Produit { NomExt = "MecheListe blonde", Prix_u = (decimal)110, quant = 30 }, new Produit { NomExt = "MecheListe rouge", Prix_u = (decimal)90, quant = 30 }, }; produits.ForEach(s => context.produits.Add(s)); context.SaveChanges(); var clients = new List<Client> { new Client{nomCl="Dupond",prenomCl="jean",tel="0465/55/44/02",mail="<EMAIL>"}, new Client{nomCl="Dufour",prenomCl="marie",tel="0465/53/42/02",mail="<EMAIL>"}, new Client{nomCl="Durand",prenomCl="pierre",tel="0466/65/44/02",mail="<EMAIL>"}, new Client{nomCl="lefour",prenomCl="anne",tel="0467/00/04/55",mail="<EMAIL>"}, }; clients.ForEach(s => context.clients.Add(s)); context.SaveChanges(); var commandes = new List<Commande> { new Commande{produitID=1,clientID=1,quantCom=1, prixTot=(decimal)10.00,dateCom=DateTime.Today}, new Commande{produitID=2,clientID=1,quantCom=1, prixTot=(decimal)11.00,dateCom=DateTime.Today}, }; commandes.ForEach(s => context.commandes.Add(s)); context.SaveChanges(); } } }<file_sep>using System; using System.Collections.Generic; using System.Data.Entity; using System.Data.Entity.ModelConfiguration.Conventions; using System.Linq; using System.Web; using VenteExtension.Models; namespace VenteExtension.dal { public class VenteContext : DbContext { public VenteContext() : base("VenteContext") { } public DbSet<Produit> produits { get; set; } public DbSet<Commande> commandes { get; set; } public DbSet<Client> clients { get; set; } //public DbSet<Panier> panier { get; set; } //public DbSet<LignePanier> Ligne { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Conventions.Remove<PluralizingTableNameConvention>(); } //public System.Data.Entity.DbSet<VenteExtension.Models.LignePanier> LignePaniers { get; set; } } }<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 VenteExtension.Models; using VenteExtension.dal; namespace VenteExtension { public class CommandeController : Controller { private VenteContext db = new VenteContext(); // GET: Commande public ActionResult Index() { var commandes = db.commandes.Include(c => c.client).Include(c => c.produit); return View(commandes.ToList()); } // GET: Commande/Details/5 public ActionResult Details(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Commande commande = db.commandes.Find(id); if (commande == null) { return HttpNotFound(); } return View(commande); } // GET: Commande/Create public ActionResult Create() { ViewBag.clientID = new SelectList(db.clients, "clientID", "nomCl"); ViewBag.produitID = new SelectList(db.produits, "ID", "NomExt"); ViewBag.error = TempData["error"]; return View(); } // POST: Commande/Create // Afin de déjouer les attaques par survalidation, activez les propriétés spécifiques auxquelles vous voulez établir une liaison. Pour // plus de détails, consultez https://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] //public ActionResult Create([Bind(Include = "commandeID,produitID,clientID,quantCom,prixTot,dateCom")] Commande commande) public ActionResult Create([Bind(Include = "commandeID,produitID,clientID,quantCom,prixTot,dateCom")] Commande commande) { //int nbre=0;//c'est la variable qui me permets de recuperer la quantite commandee try { if (ModelState.IsValid) { // commande.dateCom = commande.dateDuJour(); commande.dateCom = commande.dateCom; Produit produit = db.produits.Find(commande.produitID); commande.produit = produit; /*Client client = db.clients.Find(commande.clientID); commande.client = client;*/ /*if ((commande.clientID.Equals(client.clientID))&&(commande.produitID.Equals(produit.ID))) { //commande = db.commandes.Find(commande.quantCom); commande = db.commandes.Find(commande.quantCom); nbre = commande.quantCom; commande.quantCom = commande.quantCom+ nbre; commande.prixTot = commande.calculPrixTot(); }*/ commande.prixTot = commande.calculPrixTot(); if (commande.verifQuant()) { db.commandes.Add(commande); db.SaveChanges(); } else { TempData["error"] = "il faut minimum un produit "; // ViewBag.error = "il faut minimum un produit "; //return View("Create"); return RedirectToAction("Create"); } //db.commandes.Add(commande); return RedirectToAction("Index"); } } catch (DataException) { ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator."); } ViewBag.clientID = new SelectList(db.clients, "clientID", "nomCl", commande.clientID); ViewBag.produitID = new SelectList(db.produits, "ID", "NomExt", commande.produitID); return View(commande); } // GET: Commande/Edit/5 public ActionResult Edit(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Commande commande = db.commandes.Find(id); if (commande == null) { return HttpNotFound(); } ViewBag.clientID = new SelectList(db.clients, "clientID", "nomCl", commande.clientID); ViewBag.produitID = new SelectList(db.produits, "ID", "NomExt", commande.produitID); ViewBag.error = TempData["error"]; return View(commande); } // POST: Commande/Edit/5 // Afin de déjouer les attaques par survalidation, activez les propriétés spécifiques auxquelles vous voulez établir une liaison. Pour // plus de détails, consultez https://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit([Bind(Include = "commandeID,produitID,clientID,quantCom,prixTot,dateCom")] Commande commande) { if (ModelState.IsValid) { //commande.dateCom = commande.dateDuJour(); commande.dateCom = commande.dateCom; Produit produit = db.produits.Find(commande.produitID); commande.produit = produit; commande.prixTot = commande.calculPrixTot(); if (commande.verifQuant()) { db.Entry(commande).State = EntityState.Modified; db.SaveChanges(); } else { TempData["error"] = "il faut minimum un produit "; // ViewBag.error = "il faut minimum un produit "; //return View("Create"); return RedirectToAction("Create"); } //db.Entry(commande).State = EntityState.Modified; //db.SaveChanges(); return RedirectToAction("Index"); } ViewBag.clientID = new SelectList(db.clients, "clientID", "nomCl", commande.clientID); ViewBag.produitID = new SelectList(db.produits, "ID", "NomExt", commande.produitID); return View(commande); } // GET: Commande/Delete/5 public ActionResult Delete(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Commande commande = db.commandes.Find(id); if (commande == null) { return HttpNotFound(); } return View(commande); } // POST: Commande/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public ActionResult DeleteConfirmed(int id) { Commande commande = db.commandes.Find(id); db.commandes.Remove(commande); db.SaveChanges(); return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data.Entity; using VenteExtension.Models; /*namespace VenteExtension.dal { public class ProduitContext : DbContext { public ProduitContext() : base("VenteExtension") { } public DbSet<Produit> produit { get; set; } public DbSet<Panier> panier { get; set; } } }*/<file_sep>namespace VenteExtension.Migrations { using System; using System.Collections.Generic; using System.Data.Entity; using System.Data.Entity.Migrations; using System.Linq; using VenteExtension.Models; internal sealed class Configuration : DbMigrationsConfiguration<VenteExtension.dal.VenteContext> { public Configuration() { AutomaticMigrationsEnabled = false; } protected override void Seed(VenteExtension.dal.VenteContext context) { // This method will be called after migrating to the latest version. // You can use the DbSet<T>.AddOrUpdate() helper extension method // to avoid creating duplicate seed data. var clients = new List<Client> { new Client { nomCl = "Carson", prenomCl = "Alexander", tel = "0467/550225" } }; clients.ForEach(s => context.clients.AddOrUpdate(p => p.nomCl, s)); context.SaveChanges(); var produits = new List<Produit> { new Produit {NomExt = "Indienne", Prix_u = 115 , quant=9 } }; produits.ForEach(s => context.produits.AddOrUpdate(p => p.NomExt, s)); context.SaveChanges(); var commandes = new List<Commande> { new Commande { clientID = clients.Single(s => s.nomCl == "Carson").clientID, produitID = produits.Single(c => c.NomExt == "Indienne" ).ID, quantCom = 1 , prixTot= 115, dateCom= DateTime.Now } }; foreach (Commande c in commandes) { var commandeInDataBase = context.commandes.Where( s => s.client.clientID == c.clientID && s.produit.ID == c.produitID).SingleOrDefault(); if (commandeInDataBase == null) { context.commandes.Add(c); } } context.SaveChanges(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data.Entity; using System.Data.Entity.SqlServer; namespace VenteExtension.dal { public class VenteConfiguration : DbConfiguration { public VenteConfiguration() { SetExecutionStrategy("System.Data.SqlClient", () => new SqlAzureExecutionStrategy()); } } }<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 VenteExtension.Models; using VenteExtension.dal; using PagedList; using System.Data.Entity.Infrastructure; namespace VenteExtension { public class ClientController : Controller { private VenteContext db = new VenteContext(); // GET: Client //public ActionResult Index() //{ // return View(db.clients.ToList().OrderBy(s=> s.nomCl)); //} public ViewResult Index(string sortOrder, string currentFilter, string searchString, int? page) { ViewBag.CurrentSort = sortOrder; ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "name_asc" : ""; if (searchString != null) { page = 1; } else { searchString = currentFilter; } ViewBag.CurrentFilter = searchString; var clients = from s in db.clients select s; if (!String.IsNullOrEmpty(searchString)) { clients = clients.Where(s => s.nomCl.Contains(searchString)); } clients = clients.OrderBy(s => s.nomCl); int pageSize = 3; int pageNumber = (page ?? 1); return View(clients.ToPagedList(pageNumber, pageSize)); // return View(clients.ToList()); //return View(db.clients.ToList().OrderBy(s => s.nomCl)); } // GET: Client/Details/5 public ActionResult Details(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Client client = db.clients.Find(id); if (client == null) { return HttpNotFound(); } return View(client); } // GET: Client/Create public ActionResult Create() { return View(); } // POST: Client/Create // Afin de déjouer les attaques par survalidation, activez les propriétés spécifiques auxquelles vous voulez établir une liaison. Pour // plus de détails, consultez https://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create([Bind(Include = "clientID,nomCl,prenomCl,tel,mail")] Client client) { try { if (ModelState.IsValid) { db.clients.Add(client); db.SaveChanges(); return RedirectToAction("Index"); } } catch (RetryLimitExceededException /* dex */) //catch (DataException) { ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator."); } return View(client); } // GET: Client/Edit/5 public ActionResult Edit(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Client client = db.clients.Find(id); if (client == null) { return HttpNotFound(); } return View(client); } // POST: Client/Edit/5 // Afin de déjouer les attaques par survalidation, activez les propriétés spécifiques auxquelles vous voulez établir une liaison. Pour // plus de détails, consultez https://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit([Bind(Include = "clientID,nomCl,prenomCl,tel,mail")] Client client) { if (ModelState.IsValid) { db.Entry(client).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } return View(client); } // GET: Client/Delete/5 public ActionResult Delete(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Client client = db.clients.Find(id); if (client == null) { return HttpNotFound(); } return View(client); } // POST: Client/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public ActionResult DeleteConfirmed(int id) { Client client = db.clients.Find(id); db.clients.Remove(client); db.SaveChanges(); return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } } }
a8a4c1c3be4845e42778a70e2155994569a32a72
[ "HTML+Razor", "C#" ]
15
HTML+Razor
riade2014/VenteExtension
4fe08dcf2b113f9e7c39211dadc2f531e15d871d
888f0dfd785cbee6ce29ed6e6b1da9a0d058233e
refs/heads/master
<repo_name>sachinkmr/bobcat<file_sep>/bb-aem-integration-tests/src/main/config/common/test.properties junit.reruns=3 <file_sep>/bobcat/pom.xml <?xml version="1.0" encoding="UTF-8"?> <!-- #%L Bobcat %% Copyright (C) 2016 Cognifide Ltd. %% 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. #L% --> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <artifactId>bobcat-parent</artifactId> <groupId>com.cognifide.qa.bb</groupId> <version>1.1.4-SNAPSHOT</version> </parent> <artifactId>bobcat</artifactId> <packaging>pom</packaging> <name>Bobcat</name> <licenses> <license> <name>The Apache License, Version 2.0</name> <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url> </license> </licenses> <modules> <module>bb-core</module> <module>bb-core-tests</module> <module>bb-junit</module> <module>bb-reports</module> <module>bb-cumber</module> <module>bb-email</module> <module>bb-traffic</module> <module>bb-aem-common</module> <module>bb-aem-classic</module> <module>bb-aem-touch-ui</module> <module>bb-annotations</module> </modules> <distributionManagement> <repository> <id>sonatype-nexus-staging</id> <name>Nexus Release Repository</name> <url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url> </repository> <snapshotRepository> <id>sonatype-nexus-snapshots</id> <name>Sonatype Nexus Snapshots</name> <url>https://oss.sonatype.org/content/repositories/snapshots/</url> </snapshotRepository> </distributionManagement> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <selenium.version>2.53.1</selenium.version> <guice.version>3.0</guice.version> <cucumber.version>1.2.3</cucumber.version> <version.logback>1.1.7</version.logback> </properties> <dependencyManagement> <dependencies> <dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> <version>${selenium.version}</version> <exclusions> <exclusion> <artifactId>gson</artifactId> <groupId>com.google.code.gson</groupId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-remote-driver</artifactId> <version>${selenium.version}</version> <exclusions> <exclusion> <artifactId>gson</artifactId> <groupId>com.google.code.gson</groupId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-htmlunit-driver</artifactId> <version>2.52.0</version> </dependency> <dependency> <groupId>io.appium</groupId> <artifactId>java-client</artifactId> <version>2.1.0</version> </dependency> <dependency> <groupId>net.lightbody.bmp</groupId> <artifactId>browsermob-core</artifactId> <version>2.1.0</version> <exclusions> <exclusion> <artifactId>slf4j-jdk14</artifactId> <groupId>org.slf4j</groupId> </exclusion> </exclusions> </dependency> <dependency> <groupId>com.github.detro.ghostdriver</groupId> <artifactId>phantomjsdriver</artifactId> <version>1.1.0</version> </dependency> <dependency> <groupId>com.google.inject</groupId> <artifactId>guice</artifactId> <version>${guice.version}</version> </dependency> <dependency> <groupId>com.google.inject.extensions</groupId> <artifactId>guice-assistedinject</artifactId> <version>${guice.version}</version> </dependency> <dependency> <groupId>com.google.inject.extensions</groupId> <artifactId>guice-multibindings</artifactId> <version>${guice.version}</version> </dependency> <dependency> <groupId>org.reflections</groupId> <artifactId>reflections</artifactId> <version>0.9.10</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.4</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-email</artifactId> <version>1.3.3</version> </dependency> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>17.0</version> </dependency> <dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.20</version> </dependency> <dependency> <groupId>javax.jcr</groupId> <artifactId>jcr</artifactId> <version>2.0</version> </dependency> <dependency> <groupId>org.apache.maven</groupId> <artifactId>maven-artifact</artifactId> <version>3.2.3</version> </dependency> <dependency> <groupId>info.cukes</groupId> <artifactId>cucumber-guice</artifactId> <version>${cucumber.version}</version> </dependency> <dependency> <groupId>info.cukes</groupId> <artifactId>cucumber-junit</artifactId> <version>${cucumber.version}</version> </dependency> <dependency> <groupId>org.apache.jackrabbit</groupId> <artifactId>jackrabbit-jcr2dav</artifactId> <version>2.9.0</version> </dependency> <!-- logging --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.4</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-core</artifactId> <version>${version.logback}</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>${version.logback}</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <exclusions> <exclusion> <artifactId>hamcrest-core</artifactId> <groupId>org.hamcrest</groupId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.hamcrest</groupId> <artifactId>hamcrest-core</artifactId> <version>1.3</version> </dependency> <dependency> <groupId>joda-time</groupId> <artifactId>joda-time</artifactId> <version>2.4</version> </dependency> <dependency> <groupId>org.assertj</groupId> <artifactId>assertj-core</artifactId> <version>3.2.0</version> <scope>test</scope> </dependency> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-core</artifactId> <version>1.10.19</version> <scope>test</scope> </dependency> <dependency> <groupId>com.googlecode.zohhak</groupId> <artifactId>zohhak</artifactId> <version>1.1.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-server</artifactId> <version>9.3.9.v20160517</version> <scope>test</scope> </dependency> <dependency> <groupId>com.icegreen</groupId> <artifactId>greenmail</artifactId> <version>1.5.0</version> <scope>test</scope> </dependency> </dependencies> </dependencyManagement> <build> <plugins> <plugin> <groupId>org.apache.rat</groupId> <artifactId>apache-rat-plugin</artifactId> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>properties-maven-plugin</artifactId> </plugin> <plugin> <groupId>com.github.ekryd.sortpom</groupId> <artifactId>sortpom-maven-plugin</artifactId> </plugin> <plugin> <groupId>org.jacoco</groupId> <artifactId>jacoco-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
49dc74b78e7810e385fd9ffcc77ae41c23de033c
[ "INI", "Maven POM" ]
2
INI
sachinkmr/bobcat
e2902c4f8f5ca620d1b81b61db58c0e85e6dfb23
8ffd2ba75c34d5e6ea0fdaaae48b7cc0f5555c57
refs/heads/master
<repo_name>Rajeev02/NavApp<file_sep>/README.md # NavApp Expandable Navigation Menu
d0ec758b74e6eb1660d64dd9de2c342763b0cf5d
[ "Markdown" ]
1
Markdown
Rajeev02/NavApp
83e346fb800d26bc7247afc4fc8c986269e9d1c8
26208dd69c9c72a53e3de8c6135d671c2c936984
refs/heads/master
<repo_name>ctuazon/form_project<file_sep>/includes/db_commands.php <?PHP require_once ('constants.php'); // There isn't much sterilization going on. Apparently, prepared statements are more than enough to protect against SQL injection // Use this to search for something in the database using its id function SelectBlog () { $count = 0; $array = ''; try { // First Connect to the database $pdo = new PDO("mysql:host=" . DB_SERVER . ";dbname=". DB_NAME . ";charset=utf8" , DB_USER, DB_PASS); } catch (PDOException $e) { echo "Error Connecting to Source:" . $e->getMessage(); } $pdo->exec("set names utf8"); // Added for security $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sth = $pdo->query("SELECT * FROM formdata"); $sth->setFetchMode(PDO::FETCH_ASSOC); $result = $sth->fetchAll(); return $result; // Everything in the array gets pushed to this return value } // This is used for SELECT, INSERT, UPDATE, DELETE operations function InsertBlog($name, $email, $numcards, $typecards, $rewardsgood, $oftencards, $comments) { // First Connect to the database $pdo = new PDO("mysql:host=" . DB_SERVER . ";dbname=". DB_NAME . ";charset=utf8" , DB_USER, DB_PASS); $pdo->exec("set names utf8"); // Added for security $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION ); $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); try { // Insert into the Blog Database $sth = $pdo->prepare("INSERT INTO formdata ( name, email, numcards, typecards, rewardsgood, oftencards, comments) VALUES(:name, :email, :numcards, :typecards, :rewardsgood, :oftencards, :comments)"); // The values $sth->execute(array( "name" => $name, "email" => $email, "numcards" => $numcards, "typecards" => $typecards, "rewardsgood" => $rewardsgood, "oftencards" => $oftencards, "comments" => $comments )); } catch(PDOException $e) { // Report an error echo $e->getMessage(); } // Clear everything $pdo = null; $sth = null; } function PreparedDeleteBlog ($ContentId) { // First Connect to the database $pdo = new PDO("mysql:host=" . DB_SERVER . ";dbname=". DB_NAME . ";charset=utf8" , DB_USER, DB_PASS); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); try { $sth = $pdo->prepare("DELETE FROM formdata WHERE id = :id") ; $sth->execute(array( "id" => $ContentId )); } catch(PDOException $e) { // Report an error echo $e->getMessage(); } // Clear Everything $pdo = null; $sth = null; } ?><file_sep>/processform.php <?PHP require_once ('includes/db_commands.php'); $name = $_POST['name1']; $email = $_POST['email1']; $numcard = $_POST['numcards1']; $typecards = $_POST['typecards1']; $rewardsgoods = $_POST['rewardsgoods1']; $oftencards = $_POST['oftencards1']; $comments = $_POST['comments1']; $myfile = fopen("newfile.txt", "w") or die("Unable to open file!"); fwrite($myfile, "name:".$name." email:".$email." numberCards: ".$numcard." typeCard:".$typecards." Rewards:". $rewardsgoods." often:".$oftencards." comments:".$comments); fclose($myfile); InsertBlog($name, $email, $numcard, $typecards, $rewardsgoods, $oftencards, $comments) ?><file_sep>/deleteuser.php <?PHP require_once ('includes/db_commands.php'); $id = $_POST['id1']; PreparedDeleteBlog($id); ?><file_sep>/outputdata.php <?PHP require_once ('includes/db_commands.php'); $id = ""; foreach (SelectBlog() as $output) { echo "<div id='users'>"; foreach ($output as $key => $out) { if ($key == 'id') { $id = $out; //echo "<div id='".$id."'>".$id."</div>"; } else { switch ($key) { case "name": $key = "Name"; break; case "email": $key = "Email"; break; case "numcards": $key = "Number Of Cards"; break; case "typecards": $key = "Type Of Cards"; break; case "rewardsgood": $key = "Are Rewards Good?"; break; case "oftencards": $key = "Do you use it Online?"; break; case "comments": $key = "Comments"; break; default: $key = "error"; } echo "<div id='values'>"; echo "<div id='left'>". $key ."</div><div id='right'> ".$out . "</div>"; echo "</div>"; } } echo "<div id ='deletetrigger'>"; echo '<a href="#" class="winter" id="'.$id.'">Delete</a>'; echo "</div>"; echo "</div>"; } ?> <script> $(document).ready(function() { // delete user $('.winter').click(function(event) { event.preventDefault(); var process = confirm("Do you wish to delete this user?"); var id = $(this).attr('id'); //if(id == '1') if (process) { $.ajax({ type: 'post', url: 'deleteuser.php', data: { id1:id }, success: function (response) { console.log("USER DEAD"); } }); } else { //redirect } }); }); </script><file_sep>/css/style.css h1, p { margin: 20px; } body { font-family: 'Roboto', sans-serif; margin: 0; } h2 { background-color: #af78ff; padding: 10px; width:60%; border-radius: 25px 0px 0px 0px; } section { background-color: #fff9b2; padding-bottom:15px; margin-bottom:30px; margin-left: 220px; margin-right: 220px; border-radius: 25px; } #content { display:grid; grid-template-columns: 45% 55%; } #intro { background-color: #f0f0f0; padding: 20px; margin-bottom: 20px; } label { margin-left:20px; } #left_side, #right_side { padding:10px; } #submit_button { margin-top:20px; background-color: #FFFFFF; padding: 20px; display: flex; justify-content: center; } #submit { height:60px; width:30%; align:center; } #left_side { text-align:right; } #right_side { display:grid; grid-template-columns: 100%; } #item { padding-bottom: 10px; } #name, #email { width: 70%; } footer { display: flex; justify-content: center; margin-top:20px; margin-bottom:20px; } #users { margin-bottom: 20px; } #values { display:flex; justify-content:space-between; }
bcd6163c8898784a1af3086fe772f5be7f5975d8
[ "CSS", "PHP" ]
5
CSS
ctuazon/form_project
f30bdb51d9869dac7195ddc6f38bd101a7e1f2b9
148e346f4325631c6d6f830e9010f76318fdf842
refs/heads/main
<repo_name>Lesi-Yang/hello-<file_sep>/README.md # hello- testing testing testing
eaec2ac0f0dab17f6b19a4819aa41341642eaf53
[ "Markdown" ]
1
Markdown
Lesi-Yang/hello-
71d914b89e6da54f24d289275023af42068b4550
7e8dfcb2939506605730883b466f2d773dca4b80
refs/heads/master
<repo_name>akshayadik/SystemDesign<file_sep>/SocialMedia/README.md # Social Media Application This is sample social media application design prototype. Prototype demonstrate the create new post, follow/unfollow another user and display 20 most recent post in users news feed. ## Getting started Project consist of 4 services - Gateway Service: This is gateway service which will connect to service discovery service and access functionality provided by User and News Feed service. Service is implemented in Spring Cloud API gateway and Eureka Client service. - Service Discovery Service: This is central service where all other services are registers as a client. Service discovery is implemented using Netflix Eureka server. - User Service: This service perform the operation such as create Post, follow/unfollow functionality. Data created by this service is stored in Redis in memory nosql database. - News Feed Service: This Service connects to User Service using Feign and pull the latest 20 latest post synchronously. This is idependent service and can be replaced with more reliable asychronous solution such as messaging queue using Kafka. Since data is in memory, retrieval is fast. ### Design & Data Model - Modular mircorservices design to minimise coupling and horizantal scaling - Microservices are self containtd and within bounded context - In order to have high availability, In memory nosql solution is used. This can be replaced or enhanced as part of future work - Load balancer and caching for better performance - Model used in User service: User, Post, UserFollow User -> userId, name, email, dateOfBirth, creationDate, lastLogin Post -> postId, description, creationDate, userId UserFollow -> userFollowId, userId, type, followers(User) - Model used in News Feed service: NewsFeed NewsFeed -> userId, description, creationDate - Container based deployment which can be enhanced to implement CI/CD ### TODO - Monitoring - can use Spring Atuators - Security - Internal service endpoints are not accessigble externally. Gaytway can be secured using JWT/OAuth ### Prerequisites - In order to run the application, user must have Docker installed - Install Redis - Postman for testing HTTP endpoint ``` docker run --name redis --hostname redis -p 6379:6379 -d redis ``` ### Installing Each project has Docker file. Below command can be used to start the service. Build project using maven command ``` mvn clean install ``` Start the service discovery service ``` docker build -t servicediscovery . [+] Building 9.5s (10/10) FINISHED => [internal] load build definition from Dockerfile 0.2s => => transferring dockerfile: 281B 0.0s => [internal] load .dockerignore 0.3s => => transferring context: 2B 0.0s => [internal] load metadata for docker.io/library/java:8-jdk-alpine 2.3s => CACHED [1/5] FROM docker.io/library/java:8-jdk-alpine@sha256:d49bf8c44670834d3dade17f8b84d709e7db47f1887f671a0e098bafa9bae49f 0.0s => [internal] load build context 0.2s => => transferring context: 92B 0.0s => [2/5] RUN mkdir /usr/app 1.5s => [3/5] COPY ./target/servicediscovery-0.0.1-SNAPSHOT.jar /usr/app 0.8s => [4/5] WORKDIR /usr/app 0.5s => [5/5] RUN sh -c 'touch servicediscovery-0.0.1-SNAPSHOT.jar' 2.0s => exporting to image 1.8s => => exporting layers 1.5s => => writing image sha256:6b69a40d01e4730d95e7069ba9cf1deb89f75e10cb059a903a99212e3443dc95 0.1s => => naming to docker.io/library/servicediscovery 0.1s ``` Verify the image in docker ``` docker images REPOSITORY TAG IMAGE ID CREATED SIZE servicediscovery latest 6b69a40d01e4 About a minute ago 234MB redis latest a617c1c92774 12 days ago 105MB ``` Run the docker container ``` docker run -p 9090:9090 servicediscovery . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.4.4) 2021-03-25 06:30:29,255 INFO [background-preinit] org.hibernate.validator.internal.util.Version: HV000001: Hibernate Validator 6.1.7.Final 2021-03-25 06:30:29,302 INFO [main] org.springframework.boot.StartupInfoLogger: Starting ServicediscoveryApplication v0.0.1-SNAPSHOT using Java 1.8.0_111-internal on 938204a8dff0 with PID 1 (/usr/app/servicediscovery-0.0.1-SNAPSHOT.jar started by root in /usr/app) 2021-03-25 06:30:29,334 INFO [main] org.springframework.boot.SpringApplication: No active profile set, falling back to default profiles: default 2021-03-25 06:30:34,805 INFO [main] org.springframework.cloud.context.scope.GenericScope: BeanFactory id=f3eb8a44-9013-3020-86f2-591ce7d0c459 2021-03-25 06:30:35,815 INFO [main] org.springframework.boot.web.embedded.tomcat.TomcatWebServer: Tomcat initialized with port(s): 9090 (http) 2021-03-25 06:30:35,878 INFO [main] org.apache.juli.logging.DirectJDKLog: Initializing ProtocolHandler ["http-nio-9090"] ``` Perform above steps for other project ``` mvn clean install docker build -t gateway . docker run -p 8888:8888 gateway docker build -t newsfeed . docker run -p 8126:8126 newsfeed docker build -t userservice . docker run -p 8125:8125 userservice ``` ## Running the tests Postman tool can be used to test the project. Test Create User service ``` localhost:8888/userservice/createuser?name=akshay&email=<EMAIL> Sample Output: { "userId": -8950636969097434627, "name": "akshay", "email": "<EMAIL>", "dateOfBirth": null, "creationDate": null, "lastLogin": null } ``` Test create post endpoint ``` ``` Test news feed endpoint ``` localhost:8888/newsfeed/newsfeed?userId=-8950636969097434627 Sample Output: [ { "newsFeedId": null, "userId": -8950636969097434627, "description": "hi", "creationDate": "2021-03-24T20:42:29.849" }, { "newsFeedId": null, "userId": -8950636969097434627, "description": "hi", "creationDate": "2021-03-24T21:53:41.059" }, { "newsFeedId": null, "userId": -8950636969097434627, "description": "hi%0Alocalhost:8888/userservice/createpost?userId=-8557533354400603078,hi%0Alocalhost:8888/userservice/createpost?userId=3890102191369401412,hi%0Alocalhost:8888/userservice/createpost?userId=3795187933465625350,hi%0Alocalhost:8888/userservice/createpost?userId=6796120783867310727,hi%0Alocalhost:8888/userservice/createpost?userId=-8950636969097434627,hi%0Alocalhost:8888/userservice/createpost?userId=-8950636969097434627,hi%0Alocalhost:8888/userservice/createpost?userId=-8950636969097434627,hi%0Alocalhost:8888/userservice/createpost?userId=-8557533354400603078,hi%0Alocalhost:8888/userservice/createpost?userId=3890102191369401412,hi%0Alocalhost:8888/userservice/createpost?userId=3795187933465625350,hi%0Alocalhost:8888/userservice/createpost?userId=-6796120783867310727,hi%0Alocalhost:8888/userservice/createpost?userId=-8950636969097434627,hi%0Alocalhost:8888/userservice/createpost?userId=-8557533354400603078,hi%0Alocalhost:8888/userservice/createpost?userId=3890102191369401412,hi%0Alocalhost:8888/userservice/createpost?userId=3795187933465625350,hi%0Alocalhost:8888/userservice/createpost?userId=6796120783867310727,hi%0Alocalhost:8888/userservice/createpost?userId=-8950636969097434627,hi%0Alocalhost:8888/userservice/createpost?userId=-8950636969097434627,hi", "creationDate": "2021-03-24T21:54:44.812" } ] ``` Test follow/unfollow user ``` localhost:8888/userservice/follow?followerId=-8950636969097434627&followeeId=6796120783867310727 or localhost:8888/userservice/unfollow?followerId=-8950636969097434627&followeeId=6796120783867310727 Sample Output: { "userFollowId": 7970501073134487700, "userId": -8950636969097434627, "type": "FRIEND", "followers": [ { "userId": 3890102191369401412, "name": "abhay", "email": "<EMAIL>", "dateOfBirth": null, "creationDate": "2021-03-24T21:40:56.275", "lastLogin": null }, { "userId": 3795187933465625350, "name": "pratap", "email": "<EMAIL>", "dateOfBirth": null, "creationDate": "2021-03-24T21:41:08.278", "lastLogin": null } ] } ``` ## Authors * **<NAME>** - *Initial work* ## License This project is created as part for educational purpose. ## Acknowledgments * Referred documentation related to Spring, Spring API gateway, Feign, Redis, Netflix Eureka etc. <file_sep>/SocialMedia/newsfeed/Dockerfile From java:8-jdk-alpine RUN mkdir /usr/app Copy ./target/newsfeed-0.0.1-SNAPSHOT.jar /usr/app WORKDIR /usr/app RUN sh -c 'touch newsfeed-0.0.1-SNAPSHOT.jar' ENTRYPOINT ["java","-jar", "newsfeed-0.0.1-SNAPSHOT.jar"]<file_sep>/SocialMedia/userservice/src/main/java/com/us/repository/PostRepository.java package com.us.repository; import com.us.model.Post; import com.us.model.UserFollow; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Slice; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.PagingAndSortingRepository; import java.util.List; public interface PostRepository extends PagingAndSortingRepository<Post,Long> { List<Post> findAllByUserId(Long userId, Pageable pageable); Slice<Post> findByUserId(Long userId, Pageable pageable); } <file_sep>/SocialMedia/servicediscovery/Dockerfile From java:8-jdk-alpine RUN mkdir /usr/app Copy ./target/servicediscovery-0.0.1-SNAPSHOT.jar /usr/app WORKDIR /usr/app RUN sh -c 'touch servicediscovery-0.0.1-SNAPSHOT.jar' ENTRYPOINT ["java","-jar", "servicediscovery-0.0.1-SNAPSHOT.jar"]<file_sep>/SocialMedia/userservice/Dockerfile From java:8-jdk-alpine RUN mkdir /usr/app Copy ./target/userservice-0.0.1-SNAPSHOT.jar /usr/app WORKDIR /usr/app RUN sh -c 'touch userservice-0.0.1-SNAPSHOT.jar' ENTRYPOINT ["java","-jar", "userservice-0.0.1-SNAPSHOT.jar"]<file_sep>/SocialMedia/userservice/src/main/java/com/us/model/User.java package com.us.model; import lombok.*; import org.springframework.data.annotation.Id; import org.springframework.data.redis.core.RedisHash; import org.springframework.data.redis.core.index.Indexed; import java.io.Serializable; import java.time.LocalDate; import java.time.LocalDateTime; @Getter @Setter @NoArgsConstructor @Builder @AllArgsConstructor @RedisHash("user") public class User implements Serializable { @Id Long userId; String name; @Indexed String email; LocalDate dateOfBirth; LocalDateTime creationDate; LocalDateTime lastLogin; public User(String name, String email){ this.name = name; this.email = email; this.creationDate = LocalDateTime.now(); } public User(String name, String email, String dateOfBirth){ this(name, email); //Default formatter is ISO_LOCAL_DATE (e.g. YYYY-mm-dd) this.dateOfBirth = LocalDate.parse(dateOfBirth); } @Override public boolean equals(Object o){ if(o == null) return false; if(o.getClass() != this.getClass()) return false; final User user = (User) o; if(Long.compare(user.getUserId(), this.userId) != 0 && !this.email.equals(user.getEmail())) return false; return true; } @Override public int hashCode() { int hash = 17; hash = 31 * hash + ((int) (this.userId ^ (this.userId >>> 32))); hash = 31 * hash + ((int) (this.email != null ? this.email.hashCode(): 0)); return hash; } } <file_sep>/SocialMedia/userservice/src/main/java/com/us/repository/UserFollowRepository.java package com.us.repository; import com.us.model.UserFollow; import org.springframework.data.repository.CrudRepository; public interface UserFollowRepository extends CrudRepository<UserFollow,Long> { UserFollow findByUserId(Long userId); } <file_sep>/SocialMedia/gateway/src/main/resources/application.yaml spring: application: name: api-gateway cloud: discovery: enabled: true gateway: discovery: locator: enabled: true lower-case-service-id: true routes: - id: userservice uri: http://localhost:8125/userservice/ predicates: - Path=/userservice/** - id: newsfeed uri: http://localhost:8126/newsfeed/ predicates: - Path=/newsfeed/** server: port: 8888 eureka: instance: hostname: localhost prefer-ip-address: true client: service-url: defaultZone: http://admin:admin@localhost:9090/eureka healthcheck: enabled: true lease: duration: 5 management: security: enabled: false logging: level: com.us: DEBUG<file_sep>/SocialMedia/userservice/src/main/java/com/us/model/UserFollow.java package com.us.model; import lombok.*; import org.springframework.data.annotation.Id; import org.springframework.data.redis.core.RedisHash; import org.springframework.data.redis.core.index.Indexed; import java.io.Serializable; import java.util.HashSet; import java.util.Set; @Getter @Setter @NoArgsConstructor @AllArgsConstructor @Builder @RedisHash("userfollow") public class UserFollow implements Serializable { @Id Long userFollowId; @Indexed Long userId; String type; Set<User> followers = new HashSet<>(); public UserFollow(long userId){ this.userId = userId; } @Override public boolean equals(Object o){ if(o == null) return false; if(o.getClass() != this.getClass()) return false; final UserFollow follow = (UserFollow) o; if(Long.compare(follow.getUserFollowId(), this.userFollowId) != 0 && Long.compare(follow.getUserId(), this.userId) != 0) return false; return true; } @Override public int hashCode() { int hash = 17; hash = 31 * hash + ((int) (this.userId ^ (this.userId >>> 32))); hash = 31 * hash + ((int) (this.userFollowId ^ (this.userFollowId >>> 32))); return hash; } } <file_sep>/SocialMedia/newsfeed/src/main/java/com/nf/service/impl/NewsFeedServiceImpl.java package com.nf.service.impl; import com.nf.model.NewsFeed; import com.nf.service.NewsFeedService; import com.nf.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class NewsFeedServiceImpl implements NewsFeedService{ @Autowired UserService userService; @Override public List<NewsFeed> getNewsFeed(Long userId) { return userService.getPostById(userId); } }
e17edb0156fd5791f30807f2aae342570765174c
[ "Java", "Markdown", "Dockerfile", "YAML" ]
10
Java
akshayadik/SystemDesign
db56c666737241211f85d37ba534354b0316b365
1246af7cd93f690e904eea164750913d9a8bd80c
refs/heads/master
<file_sep># Calculator ## This is a simple calculator written in Java. ![](https://github.com/jaimedantas/Calculator/blob/master/Imagem.png)
95b1c08441ae9ef76a6f0bbb83181612113bfb3b
[ "Markdown" ]
1
Markdown
jaimedantas/Calculator
c8ce0c48ad1076b0b4584435b1c8b45bbfec04e2
2d9131f071e8a2fefdc6539b84aaf46313eba9b4
refs/heads/master
<repo_name>VictorYou/jenkins_study<file_sep>/app_jenkins/credentials.groovy import hudson.util.Secret import org.jenkinsci.plugins.plaincredentials.impl.StringCredentialsImpl import com.cloudbees.jenkins.plugins.sshcredentials.impl.* import com.cloudbees.jenkins.plugins.plaincredentials.impl.* import com.cloudbees.plugins.credentials.common.* import com.cloudbees.plugins.credentials.impl.*; import com.cloudbees.plugins.credentials.*; import com.cloudbees.plugins.credentials.domains.*; import com.cloudbees.plugins.credentials.domains.Domain // user + password Credentials ca_fp_devops = (Credentials) new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "ca_fp_devops", "artifactory", "ca_fp_devops", "<PASSWORD>") Credentials netactadmin = (Credentials) new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "netactadmin", "NEAR", "netactadmin", "Fast-Pass") Credentials victoryou29 = (Credentials) new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "<EMAIL>", "github", "<EMAIL>", "Yh593267") Credentials gerrit_developer1 = (Credentials) new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "gerrit_developer1", "gerrit", "gerrit_developer1", "123456") Credentials ndap_admin = (Credentials) new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "ndap_admin", "ndap admin", "admin", "I8UP9NtIOTEUm8dNFgTxg1R7kCdoIB") SystemCredentialsProvider.getInstance().getStore().addCredentials(Domain.global(), ca_fp_devops) SystemCredentialsProvider.getInstance().getStore().addCredentials(Domain.global(), netactadmin) SystemCredentialsProvider.getInstance().getStore().addCredentials(Domain.global(), victoryou29) SystemCredentialsProvider.getInstance().getStore().addCredentials(Domain.global(), gerrit_developer1) SystemCredentialsProvider.getInstance().getStore().addCredentials(Domain.global(), ndap_admin) // user + key String private_key_text_gitlab = new File('/tmp/viyou_gitlab.pem').text def keyParametersGitlab = [ description: 'gitlab-viyou', id: 'gitlab-viyou', secret: '', userName: 'gitlab-viyou', key: new BasicSSHUserPrivateKey.DirectEntryPrivateKeySource(private_key_text_gitlab) ] def privateKeyGitlab = new BasicSSHUserPrivateKey( // define private key CredentialsScope.GLOBAL, keyParametersGitlab.id, keyParametersGitlab.userName, keyParametersGitlab.key, keyParametersGitlab.secret, keyParametersGitlab.description ) SystemCredentialsProvider.getInstance().getStore().addCredentials(Domain.global(),privateKeyGitlab) // user + key String private_key_text_host = new File('/tmp/root_host.pem').text def keyParametersHost = [ description: 'root host', id: 'root_host', secret: '', userName: 'root', key: new BasicSSHUserPrivateKey.DirectEntryPrivateKeySource(private_key_text_host) ] def privateKeyHost = new BasicSSHUserPrivateKey( // define private key CredentialsScope.GLOBAL, keyParametersHost.id, keyParametersHost.userName, keyParametersHost.key, keyParametersHost.secret, keyParametersHost.description ) SystemCredentialsProvider.getInstance().getStore().addCredentials(Domain.global(),privateKeyHost) // secret_text keyParametersHost = [ description: 'k8s secret', id: 'k8s_secret', ] def secret_text = new StringCredentialsImpl( CredentialsScope.GLOBAL, keyParametersHost.id, keyParametersHost.description, Secret.fromString(System.getenv("SECRET")), ) SystemCredentialsProvider.getInstance().getStore().addCredentials(Domain.global(), secret_text) <file_sep>/vars/gitLfsPull.groovy #! usr/bin/env groovy def call (Map params, modulePath) { container("${params.containerName}") { sshagent(credentials: [params.gerritCredentialsId]) { sh """ source /etc/profile 2>/dev/null cd "${env.WORKSPACE}/${modulePath}" ssh -o StrictHostKeyChecking=no -p ${params.gitLfsPort} ${params.gitLfsHostname} git-lfs-authenticate artifactory/dummy_repo download ${params.gitLfsFetchCommand} git lfs checkout """ } } } <file_sep>/project/Jenkinsfiletest #!/usr/bin/env groovy pipeline { environment { JENKINS_UID='ca_netact_jenkins' GERRIT_CREDENTIALS_ID='netact-gerrit' FE_ARTIFACTORY_PATH='netact-generic-releases/CI/fe_tools' GERRIT_SERVER='gerrite1.ext.net.nokia.com:8282' DOCKER_REPO='netact-docker-releases' CONTAINER_IMAGE='build_rh7_fe_tools' USER_NAME='projectc' API_KEY="<KEY>" JENKINS_URL="https://build10.cci.nokia.net/job/NM/job/NetAct/job/" template_path="https://build10.cci.nokia.net/job/NM/job/NetAct/job/CI/job/component_Migration/job/Job_Template" COPY_FROM_TEMPLATE_REVIEW="https://build10.cci.nokia.net/job/NM/job/NetAct/job/CI/job/component_Migration/job/Job_Template/job/Template_Job_Review" COPY_FROM_TEMPLATE_BRANCH="https://build10.cci.nokia.net/job/NM/job/NetAct/job/CI/job/component_Migration/job/Job_Template/job/Template_Job_Branch" FE_TOOLS_VERSION="3.0.20180806065056046" WORKSPACE="${workspace}" PARENT_DIRECTORY="NM/job/NetAct" CURL_AUTH="curl -k -s --user ${USER_NAME}:${API_KEY}" JENKINS_ROOT_URL="https://build10.cci.nokia.net/job" } agent { kubernetes { label "k8s-netact-${Calendar.getInstance().format('yyyyMMddHHmmss')}" inheritFrom 'k8s-build' containerTemplate { name 'repo-image' image "netact-docker-releases.repo.lab.pl.alcatel-lucent.com/build_rh7_fe_tools" workingDir '/home/jenkins' ttyEnabled true command 'cat' } } } options { timestamps() timeout(time: 150, unit: 'MINUTES') buildDiscarder(logRotator(daysToKeepStr: '30', artifactDaysToKeepStr: '2')) } stages { stage('Debug') { steps { container('repo-image') { sshagent (credentials: ["${GERRIT_CREDENTIALS_ID}"]) { sh ''' source /etc/profile 2>/dev/null GERRIT_URL=${GERRIT_SERVER%:*} GERRIT_PORT=${GERRIT_SERVER#*:} ssh -o StrictHostKeyChecking=no -p "${GERRIT_PORT}" "${JENKINS_UID}"@"${GERRIT_URL}" gerrit version GIT_LFS_SKIP_SMUDGE=1 git clone ssh://"${JENKINS_UID}"@"${GERRIT_URL}":"${GERRIT_PORT}"/"${REPO_NAME}" "${REPO_NAME}" && scp -p -P "${GERRIT_PORT}" "${JENKINS_UID}"@"${GERRIT_URL}":hooks/commit-msg "${REPO_NAME}"/.git/hooks/ ''' } } } } stage('Download FE Tools') { steps { container('repo-image') { sh ''' source /etc/profile 2>/dev/null cd ${REPO_NAME} curl -Ls "${ARTIFACTORY_HTTPS_URL}/${FE_ARTIFACTORY_PATH}/${FE_TOOLS_VERSION}/fe_tools-${FE_TOOLS_VERSION}.tar.gz" | tar xz ''' } } } stage('create project') { steps { container('repo-image') { sshagent (credentials: ["${GERRIT_CREDENTIALS_ID}"]) { sh ''' source /etc/profile 2>/dev/null env cd ${REPO_NAME} repo=${REPO_NAME##*/} export list_modules=$(.mpp/run list_all_modules) cd ${WORKSPACE}/project bash -x create.sh ''' } } } } } } <file_sep>/pipeline/environment_variable/Jenkinsfile def name = 'viyou' pipeline { agent any parameters { string(name: "GERRIT_HOST", defaultValue: "gerrit.ext.net.nokia.com", description: "") } environment { GERRIT_HOST = 'gerrite1.ext.net.nokia.com' GERRIT_PORT = '8282' NAME = '' } stages { stage ('prepare environmental variables') { steps { echo "GERRIT_HOST: ${GERRIT_HOST}" script { NAME = name } echo "NAME: ${NAME}" } } } } <file_sep>/job_dsl/generate_upload_global_env.gvy def init_script = freeStyleJob("upload_global_envs") { wrappers { preBuildCleanup() timeout { noActivity(300) failBuild() writeDescription('Build failed due to timeout') } } steps { shell('''#!/bin/bash -ex cd $WORKSPACE rm -f envVars.json cp /tmp/envVars.json . cat envVars.json''') systemGroovyCommand(''' import jenkins.model.* def validEnvKeys = [] def validateEnvVars(envVars, keys) { for (env in keys) { if(envVars.get(env) == null){ return false } } return true } instance = Jenkins.getInstance() globalNodeProperties = instance.getGlobalNodeProperties() envVarsNodePropertyList = globalNodeProperties.getAll(hudson.slaves.EnvironmentVariablesNodeProperty.class) newEnvVarsNodeProperty = null envVars = null if ( envVarsNodePropertyList == null || envVarsNodePropertyList.size() == 0 ) { newEnvVarsNodeProperty = new hudson.slaves.EnvironmentVariablesNodeProperty(); globalNodeProperties.add(newEnvVarsNodeProperty) envVars = newEnvVarsNodeProperty.getEnvVars() } else { envVars = envVarsNodePropertyList.get(0).getEnvVars() } def ws = build.getEnvVars()["WORKSPACE"] def jsontext = new File("${ws}/envVars.json").text parser=new groovy.json.JsonSlurper() def result = parser.parseText(jsontext) for ( e in result ) { k = e.Key validEnvKeys.add(k) println(k) if (e.Value != null) { v = e.Value println(v) } else { v = "" println(v) } envVars.put(k, v) } if(!validateEnvVars(envVars, validEnvKeys)) { println "You have to specify the listed keys in your input json file: " + validEnvKeys return false } instance.save() ''') } } <file_sep>/vars/gerritVerify.groovy #! usr/bin/env groovy def call (Map params) { container("${params.containerName}") { sshagent (credentials: [params.backendCredentialsId, params.gerritCredentialsId]) { sh """ source /etc/profile 2>/dev/null if [ "${params.gerritBuildVerifyVote}" = "true" ]; then .mpp/run gerrit review --verified +1 ${GERRIT_CHANGE_NUMBER},${GERRIT_PATCHSET_NUMBER} else echo "Skipping Verify +1" fi """ } } } <file_sep>/vars/buildModuleSandbox.groovy #!/usr/bin/env groovy def call (Map params, modulePath) { container("${params.containerName}") { sh """ source /etc/profile 2>/dev/null cd "${env.WORKSPACE}/${modulePath}" .mpp/build-sandbox """ } } <file_sep>/vars/publishNPM.groovy #!/usr/bin/env groovy def call (Map params) { container("${params.containerName}") { withCredentials([usernamePassword(credentialsId: params.artifactoryCredentialsId, passwordVariable: 'ART_PASSWORD', usernameVariable: 'ART_USERNAME')]) { sh """ curl -u${ART_USERNAME}:${ART_PASSWORD} ${ARTIFACTORY_HTTPS_URL}/api/npm/auth > ~/.npmrc """ } dir ("${env.WORKSPACE}/${params.buildModulePath}") { artifact_file_name = sh label: 'get-artifact-file-name', returnStdout: true, script: ''' source /etc/profile &>/dev/null npm pack ''' artifact_file_name = artifact_file_name.trim() if (params.buildModulePath != '.') { artifact_file_name = params.buildModulePath + '/' + artifact_file_name } artifact_file_path = sh label: 'get-artifact-file-path', returnStdout: true, script: ''' source /etc/profile &>/dev/null package_name=$(jq -r .name package.json) package_version=$(jq -r .version package.json) file_path="$package_name" echo "$package_name" | grep -q '^@' && file_path+='/-' file_path+="/$package_name-$package_version.tgz" echo -n "$file_path" ''' } script { // Lookup the Artifactory server from the global environment variable: // https://confluence.app.alcatel-lucent.com/display/AACTODEVOPS/Jenkins+environment+and+contract def artifactoryServer = Artifactory.server env.ARTIFACTORY_SERVER_ID artifactoryServer.credentialsId = params.artifactoryCredentialsId // Create Artifactory Build Info def packageJsonFile = readJSON file: "${params.buildModulePath}/package.json" def buildInfo = Artifactory.newBuildInfo() buildInfo.env.capture = true buildInfo.env.collect() buildInfo.name = packageJsonFile.name.replaceAll('@','').replaceAll('/','_') buildInfo.number = packageJsonFile.version def uploadSpec = """ { "files": [ { "pattern": "${artifact_file_name}", "target" : "${params.publishNPMRepo}/${artifact_file_path}" } ] } """ echo 'upload spec:' + uploadSpec // add buildInfo to artifact artifactoryServer.upload(uploadSpec, buildInfo) artifactoryServer.publishBuildInfo(buildInfo) } } } <file_sep>/collector_build/.mpp/.svn/pristine/e3/e364dd16b4f535c11429e9a7a9de0ced2cfdd7db.svn-base #!/bin/bash source `dirname $0`/build `dirname $0`/sandbox.properties $@ || exit 1 <file_sep>/collector_build/.mpp/run #!/bin/bash mpp_env=`env | grep "^mpp_" | sed 's|=|="|' | sed 's|$|"|'` source `dirname $0`/frontend || exit 1 eval "$mpp_env" $@ <file_sep>/vars/gerritPull.groovy #! usr/bin/env groovy def call (Map params) { container("${params.containerName}") { sshagent(credentials: [params.gerritCredentialsId]) { sh ''' source /etc/profile 2>/dev/null echo "Merging the workspace content with tip of the branch" .mpp/run config_git_user git pull --rebase origin ${GERRIT_BRANCH} REVIEW_HEAD=$(git rev-parse HEAD) .mpp/run gerrit_reply "REVIEW_HEAD:${REVIEW_HEAD}" ''' } } } <file_sep>/pipeline/jenkinsfile_test.gvy pipeline { agent any stages { stage ('prepare environmental variables') { steps { } script { VNFD_VER=readFile('version_file').trim() } } } } <file_sep>/job_dsl/update_product_txt.py import sys import json import re latest_product_txt=sys.argv[1] product_properties_json=sys.argv[2] new_version=sys.argv[3] new_product_txt=sys.argv[4] with open(latest_product_txt) as product_txt_file: product_txt = product_txt_file.read() product_txt_parsed = json.loads(product_txt) with open(product_properties_json) as product_properties_file: product_properties = product_properties_file.read() product_properties_parsed = json.loads(product_properties) new_version_product_txt = {} new_version_product_txt['display_name'] = product_txt_parsed['display_name'] new_version_product_txt['product_name'] = product_txt_parsed['product_name'] new_version_product_txt['version'] = new_version new_version_product_txt['artifacts'] = [] for artifact in product_properties_parsed["results"]: artifact_hash={} artifact_hash["filename"] = artifact["name"] artifact_hash["md5sum"] = artifact["actual_md5"] artifact_hash["sha256sum"] = artifact["sha256"] artifact_hash["type"] = artifact["type"] artifact_hash["version"] = re.search('\d+\.\d+\.\d+', artifact["name"]).group() new_version_product_txt['artifacts'].append(artifact_hash) new_file = open(new_product_txt, 'w') new_file.write(json.dumps(new_version_product_txt, indent=2, sort_keys=True)) new_file.close() product_txt_file.close() product_properties_file.close() <file_sep>/pipeline/jenkinsfile_scripted.gvy def REPOSITORY="fp-tvnf" properties([parameters([string(defaultValue: 'clab1997', description: '', name: 'REPOSITORY')])]) node { stage ('prepare environmental variables') { withCredentials([usernamePassword(credentialsId: 'ca_fp_devops', passwordVariable: 'GLOBAL_ARTIFACTORY_TOKEN', usernameVariable: 'GLOBAL_ARTIFACTORY_USERNAME')]) { sh 'echo "0.0.1" > version_file' } VNFD_VER=readFile('version_file').trim() echo "${VNFD_VER}" build job: 'test_job', parameters: [ string(name: "NAME", value: "${REPOSITORY}.${VNFD_VER}"), string(name: "AGE", value: "29") ] } } <file_sep>/vars/Jenkinsfile #!/usr/bin/env groovy @Library('netact-shared-lib') _ buildComponent( imageName: "build_rh7_fe_tools", gerritRepository: "NM/NETACT/CI/tools/shared-libs", buildModulePath: "./", ) <file_sep>/app_jenkins/kubernetes.groovy import hudson.model.* import jenkins.model.* import org.csanchez.jenkins.plugins.kubernetes.* kc = new KubernetesCloud('kubernetes') Jenkins.instance.clouds.add(kc) kc.setServerUrl('https://10.131.73.190:16443') kc.setSkipTlsVerify(true) kc.setCredentialsId('k8s_secret') <file_sep>/vars/buildModule.groovy #! usr/bin/env groovy def call (Map params, modulePath, configProperties="") { container("${params.containerName}") { sshagent(credentials: [params.backendCredentialsId, params.gerritCredentialsId]) { sh """ source /etc/profile 2>/dev/null cd "${env.WORKSPACE}/${modulePath}" .mpp/run config_ris_id "${params.buildModulePath}" "${params.testModulePath}" .mpp/build ${configProperties} """ } } } <file_sep>/app_jenkins/labels.groovy import jenkins.model.Jenkins import jenkins.model.JenkinsLocationConfiguration Jenkins j = Jenkins.instance JenkinsLocationConfiguration location = j.getExtensionList('jenkins.model.JenkinsLocationConfiguration')[0] oldLabels = j.getLabelString() if (oldLabels.contains('master docker')) { println "Default labels already set for the node: ${oldLabels}" } else { println "Default labels not set for the node, current labels are: ${oldLabels}" def defaultLabels = "master docker " def newLabels = "$defaultLabels$oldLabels" j.setLabelString(newLabels) j.save() location.save() } <file_sep>/app_jenkins/library.groovy import hudson.scm.SCM import jenkins.model.* import jenkins.model.Jenkins import jenkins.plugins.git.GitSCMSource import org.jenkinsci.plugins.workflow.libs.* import org.jenkinsci.plugins.workflow.libs.LibraryConfiguration import org.jenkinsci.plugins.workflow.libs.SCMSourceRetriever def globalLibrariesParameters = [ branch: "master", credentialId: "<EMAIL>", implicit: false, name: "netact", repository: "https://github.com/VictorYou/jenkins_study.git" ] GitSCMSource gitSCMSource = new GitSCMSource( "global-shared-library", globalLibrariesParameters.repository, globalLibrariesParameters.credentialId, "*", "", false ) SCMSourceRetriever sCMSourceRetriever = new SCMSourceRetriever(gitSCMSource) Jenkins jenkins = Jenkins.getInstance() def globalLibraries = jenkins.getDescriptor("org.jenkinsci.plugins.workflow.libs.GlobalLibraries") LibraryConfiguration libraryConfiguration = new LibraryConfiguration(globalLibrariesParameters.name, sCMSourceRetriever) libraryConfiguration.setDefaultVersion(globalLibrariesParameters.branch) libraryConfiguration.setImplicit(globalLibrariesParameters.implicit) globalLibraries.get().setLibraries([libraryConfiguration]) jenkins.save() <file_sep>/project/proj.sh function Auto_Jenkinsjob { ## Auto Create Jenkinsjob for the input Repo source .mpp/modules/pipeline # source .mpp/modules/pipeline CURL_AUTH="curl -k -s --user ${USER_NAME}:${API_KEY}" copy_template_to_tmp_dir create_folder for each_module in ${modules} do deploy_template create_job done } function copy_template_to_tmp_dir { ## Copy template from exisitng template job template_job_name="${COPY_FROM_TEMPLATE_BRANCH##*/} ${COPY_FROM_TEMPLATE_REVIEW##*/}" source_config_branch="/tmp/${COPY_FROM_TEMPLATE_BRANCH##*/}-config.xml" source_config_review="/tmp/${COPY_FROM_TEMPLATE_REVIEW##*/}-config.xml" for each_template in ${template_}; do ${CURL_AUTH} -X GET "${template_path}/job/${each_template}/api/json?tree=name" | grep "ERROR" && echo "Template not found" && exit 1 done echo "Copying templates to tmp dir" ${CURL_AUTH} ${COPY_FROM_TEMPLATE_BRANCH}/config.xml > "${source_config_branch}" ${CURL_AUTH} ${COPY_FROM_TEMPLATE_REVIEW}/config.xml > "${source_config_review}" } function create_folder { directories="${COPY_TO_IMPLEMENTATION_FOLDER} ${COPY_TO_INTERFACE_FOLDER}" for each_directory in ${directories} do ${CURL_AUTH} -X POST "${JENKINS_URL}$(get_component)/createItem?name=${each_directory}&mode=com.cloudbees.hudson.plugins.folder.Folder&from=&json={'name':'templates','mode':'com.cloudbees.hudson.plugins.folder.Folder','from':'','Submit':'OK'}&Submit=OK" -H 'Content-Type:application/x-www-form-urlencoded' done } function get_component { ## Get component from the given Repo COMPONENT="${REPO_NAME##*/}" COMPONENT="${COMPONENT^^}" echo "${COMPONENT}" } function get_module_name { ## Get module name module="${each_module#*$REPO_NAME/}" module_name="${module%/*}" module_name="${module_name%/interface*}" echo "${module_name}" } function get_module_type { ## get module type, impl for implementation; if for interface if is_implementation ${each_module}; then echo "impl" else echo "if" fi } function get_test_folder { ## test folder to be provided in job, which is used in jenkinsfile for auto-triggering once the commit is done if [[ $(get_module_type) == "if" ]]; then test_folder=' ' echo "${test_folder}" else test_folder="$(get_module_name)/test/**" echo "${test_folder}" fi } function get_job_name { ## Job name followed is component_modulename_moduletype if [[ $(get_module_type) == "if" ]] then module_name_interface=$(echo ${module///interface}| sed 's,/,_,g') job_name="$(get_component)_${module_name_interface}_$(get_module_type)" echo "${job_name}" else job_name="$(get_component)_$(get_module_name)_$(get_module_type)" echo "${job_name}" fi } function get_project_path { ## get the path where jobs to be pushed, two folders: implementation and interface if [[ "${module_type}" == "impl" ]] then echo "${JENKINS_URL}/${folder_name}/job/${copy_to_implementation_folder}" else echo "${JENKINS_URL}/${folder_name}/job/${copy_to_interface_folder}" fi } function get_script_path { if [[ ! -z ${each_module} ]]; then echo "${each_module#*$REPO_NAME/}/Jenkinsfile" else echo "please check the input parameters" exit 1 fi } function deploy_template { ## deploy template for the jobs new_config_branch="/tmp/$(get_module_name)-config1.xml" new_config_review="/tmp/$(get_module_name)-config2.xml" cp "${source_config_branch}" "${new_config_branch}" cp "${source_config_review}" "${new_config_review}" $(put_values) } function put_values { sedcmd="s|_TYPE_|$(get_module)|g;s|_REPO_|${REPO_NAME}|g;s|_BRANCH_|${branch_name}|g;s|_MODULE_|$(get_test_folder)|g;s|Jenkinsfile|$(get_jenkinsfile_path)|g" sed -i "${sedcmd}" "${new_config_branch}" sed -i "${sedcmd}" "${new_config_review}" } function create_job { ## Create jobs for the repo ${CURL_AUTH} -X XPOST -H 'Content-Type: application/xml' -d @"${new_config_branch}" "$(get_project_path)/createItem?name=$(get_job_name)-branch" ${CURL_AUTH} -X XPOST -H 'Content-Type: application/xml' -d @"${new_config_branch}" "$(get_project_path)/createItem?name=$(get_job_name)-review" } <file_sep>/vars/prepareBuild.groovy #! usr/bin/env groovy def call (Map params) { container("${params.containerName}") { sshagent(credentials: [params.gerritCredentialsId]) { sh """ source /etc/profile 2>/dev/null mkdir -p /var/mpp/jarsigning/keystore /root/.ssh/ cp ${env.JAR_SIGN_FILE} /var/mpp/jarsigning/keystore/nsnnetactkeystore chmod 400 /var/mpp/jarsigning/keystore/nsnnetactkeystore ssh-keyscan -p ${GERRIT_PORT} -t rsa ${GERRIT_HOST} >> /root/.ssh/known_hosts [[ -d "${env.WORKSPACE}/${params.buildModulePath}" ]] || { echo "buildModulePath folder is not present"; exit 1; } [[ -d "${env.WORKSPACE}/${params.testModulePath}" ]] || { echo "testModulePath folder is not present"; exit 1;} [[ -d "${env.WORKSPACE}/${params.buildModulePath}/.mpp" ]] || cp -r "${WORKSPACE}/.mpp" "${env.WORKSPACE}/${params.buildModulePath}/" [[ -z "${params.testModulePath}" ]] && { echo "testModulePath is unset"; exit 0; } [[ -d "${env.WORKSPACE}/${params.testModulePath}/.mpp" ]] || cp -r "${WORKSPACE}/.mpp" "${env.WORKSPACE}/${params.testModulePath}/" nohup bash -c "exec /usr/bin/Xvfb :1 -screen 0 1600x1200x24 &" """ } } } <file_sep>/pipeline/pipeline_model_converter.py import requests import json import sys import subprocess import os if len(sys.argv) == 1: print "filename needed" sys.exit() filename=sys.argv[1] with open(filename) as file: filetext = file.read() r = requests.post("http://127.0.0.1:7070/pipeline-model-converter/toJson", data={'jenkinsfile':filetext}, verify=False, auth=('admin', '<PASSWORD>')) print "result txt: {}".format(r.text) data = json.loads(r.text) print "result: {}".format(data['data']['result']) if data['data']['result'] == 'failure': sys.exit() parameters = json.loads(r.text)['data']['json']['pipeline']['parameters']['parameters'] output = "" for param in parameters: output += param['arguments'][0]['value']['value'] + "#"; output += param['arguments'][1]['value']['value'] + "#"; output += param['arguments'][2]['value']['value'] + "@"; print(output) <file_sep>/collector_build/.mpp/.svn/pristine/99/9985dde4cd622cd1b17bad7baa1c219be008dd87.svn-base #!/bin/bash source `readlink -f ${BASH_SOURCE[0]} | xargs dirname`/frontend || exit 1 exit_status=1 init_build_environment $@ # If mpp_backend_lab is defined.. [[ "${mpp_backend_lab:-}" ]] && { trap 'build_ended_notification $exit_status' EXIT build_started_notification } mpp_basic_init before_build build after_build exit_status=0 <file_sep>/collector_build/build_in_image.gvy node('agent_host') { stage ('cleanup workspace') { cleanWs() } stage ('check out codebase') { git(credentialsId: '<EMAIL>', branch: 'master', url: 'https://github.com/VictorYou/jenkins_study.git') } stage ('build app image') { dir('collector_build') { docker.image('netact-docker-releases.repo.lab.pl.alcatel-lucent.com/build_rh7_fe_tools:latest').inside { sh "hostname" sh ".mpp/build" } } } } <file_sep>/vars/README.md # NetAct Shared Library This Jenkins Shared Library is used to automate and simplify the creation of Jenkinsfiles for all NetAct components ## Pipelines |Pipeline name | Description| |--------------|------------| | Code Review | verifies change before it's merged | | Branch | verifies change after it's merged | ## Stages ###### Pipeline: Code Review |Stage name | Description| |-----------|------------| | Prepare Build | prepares environment for build | | Build Sandbox | executes module build in sandbox mode | | Functional Tests | executes functional tests | | Auto Submit | performs auto submit after all stages are successful | ###### Pipeline: Branch |Stage name | Description| |-----------|------------| | Prepare Build | prepares environment for build | | Build | executes module build | | Publish NPM | publishes artifacts to NPM repository | | Publish Artifacts | publishes artifacts to YUM, GENERIC repositories | | Create Tag | creates git tag | | Verification | runs in parallel stages: Functional Tests( Under this stage Component Upgrade and Interface Promotion will be executed sequentially), Release Upgrade, Scratch Installation | | Component Upgrade | executes component upgrade | | Interface Promotion | executes interface promotion| | Release Upgrade | executes release upgrade | | Scratch Installation | executes scratch installation | | Promote Artifacts | promote artifacts | ## Stages and related functions * Code Review : * Prepare Build : * showInfo * downloadFETools * prepareBuild * gitLfsPull * Build Sandbox : * buildModuleSandbox * Build : * gerritPull * buildModule (building module sources) * Functional Tests : * buildModule (building test directory with default mpp.properties file) * Auto Submit : * gerritVerify * autoSubmit * Branch : * Prepare Build : * showInfo * downloadFETools * prepareBuild * gitLfsPull * Build : * updateChangedSinceReview * buildModule * addCustomRisTag * Publish NPM * publishNPM * Publish Artifacts * publishArtifacts * Create Tag : * createTag * Verification : * Functional Tests : * Component Upgrade * buildModule (building test directory with default mpp.properties file) * Interface Promotion * invokeInterface (promotes new interface versions to clients) * Release Upgrade : * buildModule (building test directory with mpp.release file) * Scratch Installation : * buildModule (building test directory with mpp.install file) * Promote Artifacts : * promoteArtifacts ## Functions description |Function | Syntax | Required argument(s) | Optional argument(s) | Required environment variable(s) | Reguired credentials | Description | |---------------------------|-------------------------------------------------------------------|-------------------------------|-----------------------|-----------------------------------------------------------|-------------------------------------------|-------------------------------------------------------------------------------------------------------------------| |buildComponent | buildComponent {} |\<Map parameters> |\<Map parameters> |GERRIT_BRANCH, GERRIT_PATCHSET_REVISION, ARTIFACTORY_FQDN | - |executes review or branch pipelines based on job's name, takes as arguments mandatory properties used during build | |buildComponentBranch | buildComponentBranch(\<Map config>) |\<Map config> |- |GERRIT_EVENT_COMMENT_TEXT |netact-jarsign-file |executes branch pipeline | |buildComponentCodeReview | buildComponentCodeReview(\<Map config>) |\<Map config> |- |GERRIT_EVENT_COMMENT_TEXT |netact-jarsign-file |executes review pipeline | |buildModule | buildModule(\<Map config>, \<modulePath>, \<configProperties>) |\<Map config>, \<modulePath> |\<configProperties> |WORKSPACE |backendCredentialsId, gerritCredentialsId |executes module build | |buildModuleSandbox | buildModule(\<Map config>, \<modulePath>) |\<Map config>, \<modulePath> |- |WORKSPACE |- |executes module build in sandbox mode | |createTag | buildModule(\<Map config>, \<modulePath>) |\<Map config>, \<modulePath> |- |WORKSPACE |gerritCredentialsId |creates a gerrit tag based on mpp_ris_id | |downloadFETools | downloadFETools(\<Map config>) |\<Map config> |- |WORKSPACE |- |downloads FE Tools to project workspace | |gerritVerify | gerritVerify((\<Map config>) |\<Map config> |- |GERRIT_CHANGE_NUMBER,GERRIT_PATCHSET_NUMBER |gerritCredentialsId |adds Verified +1 to gerrit review | |autoSubmit | autoSubmit(\<Map config>) |\<Map config> |- |GERRIT_CHANGE_NUMBER,GERRIT_PATCHSET_NUMBER |gerritCredentialsId |submits the code review | |prepareBuild | prepareBuild(\<Map config>) |\<Map config> |- |GERRIT_PORT,GERRIT_HOST,JAR_SIGN_FILE |gerritCredentialsId |executes mandatory actions before the build | |showInfo | showInfo(\<Map config>) |\<Map config> |- |- |- |provide information concerning environment variables and config properties | |gerritPull | gerritPull(\<Map config>) |\<Map config> |- |GERRIT_BRANCH |gerritCredentialsId |merges tip of the branch with current workspace | |promoteArtifacts | promoteArtifacts(\<Map config>) |\<Map config> |- |ARTIFACTORY_SERVER_ID |artifactoryCredentialsId |promotes artifacts | |publishNPM | publishNPM(\<Map config>) |\<Map config> |- |ARTIFACTORY_SERVER_ID, WORKSPACE |artifactoryCredentialsId |publishes artifacts to NPM repository | |publishArtifacts | publishArtifacts(\<Map config>) |\<Map config> |- |ARTIFACTORY_SERVER_ID, WORKSPACE |artifactoryCredentialsId |publishes artifacts to YUM, GENERIC repositories | |gitLfsPull | gitLfsPull(\<Map config>, \<modulePath>) |\<Map config>, \<modulePath> |- |WORKSPACE |gerritCredentialsId |downloads any missing Git LFS content for the current commit | |promoteInterface | promoteInterface(\<Map config>, \<modulePath>) |\<Map config>, \<modulePath> |- |WORKSPACE |gerritCredentialsId |publish interface property across repositories | |updateChangedSinceReview | updateChangedSinceReview(\<Map config>) |\<Map config> |- |GERRIT_CHANGE_NUMBER,GERRIT_PATCHSET_NUMBER,GERRIT_SSH_USER|gerritCredentialsId |compares review revision with merge revision and updates variable changedSinceReview | |addCustomRisTag | addCustomRisTag(\<Map config>, \<modulePath>) |\<Map config>, \<modulePath> |- |WORKSPACE |backendCredentialsId |adds custom ris tag to RIS when component upgrade is skipped if no change since review build | ## buildComponent parameters ###### Mandatory parameters that need to be provided by component |Parameter| Description| |---------|------------| |imageName| name of docker image that will be used during build | ###### Optional parameters that can to be provided by component |Parameter| Description| |---------|------------| |buildModulePath | full path to component's implementation directory that contains **mpp.properties** files, default is repository root)| |testModulePath | full path to component's test directory that contains **mpp.properties** files | |junitTestReportPaths | string of comma separated file path patterns (ant syntax) to junit formatted (xml) report files, default is `**/target/surefire-reports/TEST-*.xml` | |releaseProperties | name of properties file that holds the configuration of clone pools used during release upgrade | |scratchProperties | name of properties file that holds the configuration of short lab pool used during scratch installation | |gerritTriggerFilePaths | list of file path patterns for gerrit trigger configuration, generated from buildModulePath and testModulePath by default | |feToolsVersion | name of FE Tools that need to be used during the build - **use only to test new features** | |gitLfsFetchCommand | git lfs fetch command to execute in gitLfsPull stage - default is ** git lfs fetch --all** | |mppDebug | if parameter contains any value like **true** build is run in debug mode - set -x| |autoPromoteArtifacts | auto promote artifacts to releases if variable is set **true**, default is **false** | |publishSnapshots | publish snapshots to Artifactory if parameter is set **true**, default is **false** | |stageFunctionalTests | if parameter set to **true** (default) executes Functional Test stage, to disable set to **false** | |stageComponentUpgrade | if parameter set to **true** (default) executes Component Upgrade stage, to disable set to **false** | |stageReleaseUpgrade | if parameter set to **true** executes Release Upgrade stage, to disable set to **false** (default) | |stageScratchInstallation | if parameter set to **true** executes Scratch Installation stage, to disable set to **false** (default) | |stagePublishNPM | publishes artifacts to NPM repository if variable is set **true**, default is **false** | |stagePublishArtifacts | publishes artifacts to YUM, GENERIC repositories if variable is set **true**, default is **false** | |stageInterfacePromotion | if parameter set to **true** executes Interface Promotion stage, to disable set to **false** (default) | |stageCreateTag | if parameter set to **true** (default) executes Create Tag, to disable set to **false** | |resourceRequestMemory | resource memory allocated for build agent. Default value is set to '2000Mi', restricting maximum value to '6000Mi' | |skipComponentUpgradeIfNoChange | if parameter set to **true** component upgrade will be skipped if no change since review build, default is **false** | ###### Parameters maintained by NetAct CI team |Parameter| Description| |---------|------------| |artifactoryCredentialsId | credential ID to use in pipeline for accessing Artifactory | |gerritCredentialsId | credential ID to use in pipeline for accessing Gerrit | |gerritSSHUser | username that is used by FE Tools to execute Gerrit commands | |gerritBranch | name of the Gerrit branch | |jobTimeout | time after which job will be canceled | |jobBuildHistory | build records are only kept up to this number of days | |jobArtifactsDaysToKeep | artifacts from builds older than this number of days will be deleted | |patchsetRevision | patchset revision of gerrit review | |imageRepoPrefix | repository name that stores docker images used during builds | |imageRepoDomain | URL of artifactory server| |imageTag | docker image tag used during builds, by default set to latest | |containerName | name of container used when executing shared library functions | |feToolsRepoPath | repository path to FE Tools | |stageGerritAutoSubmit | if set to false Auto Submit is disabled | |gerritBuildVerifyVote | if set to false verify +1 is disabled | #### Pipeline state properties |changedSinceReview | variable used to check if any changes since review build, default is **false** and value will be set to **true** by function updateChangedSinceReview if changes found since review build | ### Examples ##### Content of Jenkinsfile running shared library ``` #!/usr/bin/env groovy @Library('netact') _ buildComponent{ imageName: "build_rh7_fe_tools", buildModulePath: "moduleName/implementation", testModulePath: "moduleName/test" } ``` <file_sep>/vars/showInfo.groovy #! usr/bin/env groovy def call (Map params) { container("${params.containerName}") { env.global_config = params sh """ source /etc/profile 2>/dev/null echo "Job configuration: ${global_config}" echo -e "Environment variables:\n" env """ } }<file_sep>/app_jenkins/jobs.groovy import jenkins.model.* import jenkins.model.Jenkins import hudson.plugins.git.* import hudson.plugins.git.extensions.* import hudson.plugins.git.extensions.impl.* def create_job(name, description='', repo, branch, credential, workflow) { def jobParameters = [ name: name, description: description, repository: repo, branch: branch, credentialId: credential ] def branchConfig = [new BranchSpec(jobParameters.branch)] def userConfig = [new UserRemoteConfig(jobParameters.repository, null, null, jobParameters.credentialId)] def cleanBeforeCheckOutConfig = new CleanBeforeCheckout() def cloneConfig = new CloneOption(true, true, null, 3) def extensionsConfig = [cleanBeforeCheckOutConfig,cloneConfig] def scm = new GitSCM(userConfig, branchConfig, false, [], null, null, extensionsConfig) def flowDefinition = new org.jenkinsci.plugins.workflow.cps.CpsScmFlowDefinition(scm, workflow) flowDefinition.setLightweight(true) Jenkins jenkins = Jenkins.getInstance() def job = new org.jenkinsci.plugins.workflow.job.WorkflowJob(jenkins,jobParameters.name) job.definition = flowDefinition job.setDescription(jobParameters.description) jenkins.save() jenkins.reload() } // test jobs create_job('kubernetes_plugin', 'kubernetes plugin', 'https://github.com/VictorYou/jenkins_study.git', 'master', '<EMAIL>', 'pipeline/kubernetes/Jenkinsfile') create_job('environment_variable', 'environment variable', 'https://github.com/VictorYou/jenkins_study.git', 'master', '<EMAIL>', 'pipeline/environment_variable/Jenkinsfile') create_job('variable_scripted', 'variable', 'https://github.com/VictorYou/jenkins_study.git', 'master', '<EMAIL>', 'pipeline/variable/scripted') create_job('variable_declarative', 'variable', 'https://github.com/VictorYou/jenkins_study.git', 'master', '<EMAIL>', 'pipeline/variable/declarative') // build jobs create_job('build_ci_app_image', 'build ci app image', 'https://github.com/VictorYou/packer_study.git', 'build_ci', '<EMAIL>', 'ci/build/build_app_image.gvy') create_job('build_ci_microk8s', 'build ci microk8s', 'https://github.com/VictorYou/packer_study.git', 'build_ci', '<EMAIL>', 'ci/build/build_microk8s.gvy') create_job('deploy_ci', 'deploy ci', 'https://github.com/VictorYou/packer_study.git', 'build_ci', '<EMAIL>', 'ci/build/deploy.gvy') create_job('build_fp_tvnf', 'build fast pass tvnf', '<EMAIL>:fast-pass-devops/fastpass_package_deployment.git', 'build_tvnf', 'gitlab_viyou', 'tvnf/build/build_fp_tvnf.gvy') create_job('replicate_build', 'replicate latest build', '<EMAIL>:fast-pass-devops/fastpass_package_deployment.git', 'build_tvnf', 'gitlab_viyou', 'tvnf/build/replicate_build/Jenkinsfile') <file_sep>/app_jenkins/agent.groovy import jenkins.model.Jenkins import hudson.slaves.* import hudson.plugins.sshslaves.* import hudson.plugins.sshslaves.verifiers.* import jenkins.* import jenkins.model.* import hudson.* import hudson.model.* launcher = new hudson.plugins.sshslaves.SSHLauncher('127.0.0.1', 22, 'root_host') Slave agent = new DumbSlave("agent_host", "/home/viyou/data/jenkins", launcher) agent.nodeDescription = "host as agent node" agent.numExecutors = 1 agent.labelString = "agent_host" agent.mode = Node.Mode.NORMAL agent.retentionStrategy = new RetentionStrategy.Always() Jenkins.instance.addNode(agent) // Create a "Permanent Agent" <file_sep>/pipeline/gerrit_trigger/Jenkinsfile #!/usr/bin/env groovy //def repo = 'viyou_collector_build' def repo = 'viyou_test' def branch = 'na19' pipeline { // environment { // GERRIT_BRANCH = 'master' // GERRIT_HOST = 'gerrite1.ext.net.nokia.com' // GERRIT_PORT = '8282' // GERRIT_PATCHSET_REVISION = 'HEAD' // GERRIT_CHANGE_OWNER_EMAIL = '<EMAIL>' // GERRIT_CHANGE_URL = 'https://gerrite1.ext.net.nokia.com/1' // JAR_SIGN_FILE = credentials('netact-jarsign-file') // } agent any triggers { gerrit( commitMessageParameterMode: 'PLAIN', commentTextParameterMode: 'PLAIN', customUrl: '', gerritProjects: [[ branches: [[ compareType: 'PLAIN', pattern: branch ]], compareType: 'PLAIN', disableStrictForbiddenFileVerification: false, pattern: repo, // filePaths: [[ compareType: 'ANT', pattern: "${config.buildModulePath}/**" ]], ]], serverName: 'gerrite1', triggerOnEvents: [ changeMerged(), commentAddedContains('mytest') ] ) } stages { stage('Cleanup workspace') { steps { step([$class: 'WsCleanup']) } } stage('test') { steps { echo "it is OK" } } } } <file_sep>/project/project_create.sh #!/bin/sh ################################################################################ # # Author: <NAME> # # Summary: Jenkins Job Creation # # Description: # Creates a Jenkins job based on gerrit repo tree structure: # - Create two jenkins jobs for each module, one for CodeReview and one for Branch # - applies known job template existing in Jenkins to new job created # - Replaces the _TYPE_,_REPO_ ,_BRANCH_,_MODULE_,Jenkinsfile for the new_job created # ################################################################################ cd /home/jenkins/workspace/NM/NetAct/CI/component_Migration/test2 cd netact ls -al cd fm ls -al source .mpp/modules/pipeline function check_and_create_job { ## check if modules are there, if it is there auto create jobs echo "modules are present, initiating for job creation" Auto_Jenkinsjob } function Auto_Jenkinsjob { ## Auto Create Jenkinsjob for the input Repo CURL_AUTH="curl -s --user ${USER_NAME}:${API_KEY}" copy_template_to_tmp_dir create_folder for each_module in ${list_modules} do deploy_template create_job done } function copy_template_to_tmp_dir { ## Copy template from exisitng template job template_job_name="${COPY_FROM_TEMPLATE_BRANCH##*/} ${COPY_FROM_TEMPLATE_REVIEW##*/}" source_config_branch="/tmp/${COPY_FROM_TEMPLATE_BRANCH##*/}-config.xml" source_config_review="/tmp/${COPY_FROM_TEMPLATE_REVIEW##*/}-config.xml" for each_template in ${template_}; do ${CURL_AUTH} -X GET "${template_path}/job/${each_template}/api/json?tree=name" | grep "ERROR" && echo "Template not found" && exit 1 done echo "Copying templates to tmp dir" ${CURL_AUTH} ${COPY_FROM_TEMPLATE_BRANCH}/config.xml > "${source_config_branch}" ${CURL_AUTH} ${COPY_FROM_TEMPLATE_REVIEW}/config.xml > "${source_config_review}" } function create_folder { directories="${COPY_TO_IMPLEMENTATION_FOLDER} ${COPY_TO_INTERFACE_FOLDER}" for each_directory in ${directories} do ${CURL_AUTH} -X POST "${JENKINS_URL}$(get_component)/createItem?name=${each_directory}&mode=com.cloudbees.hudson.plugins.folder.Folder&from=&json={'name':'templates','mode':'com.cloudbees.hudson.plugins.folder.Folder','from':'','Submit':'OK'}&Submit=OK" -H 'Content-Type:application/x-www-form-urlencoded' done for each_module in ${list_modules} do deploy_template create_job done } function get_module { ## get module if each_module is present if [[ ! -z ${each_module} ]]; then echo "${each_module#*$REPO_NAME/}" else exit 1 fi } function get_component { ## get component provided the repo name COMPONENT="${REPO_NAME##*/}" COMPONENT="${COMPONENT^^}" echo ${COMPONENT} } function get_module_name { ## Get module name module="$(get_module)" module_name="${module%/*}" module_name="${module_name%/interface*}" echo "${module_name}" } function get_project_path { ## get the path where jobs to be pushed, two folders: implementation and interface if [[ "$(get_module_type)" == "impl" ]] then echo "${JENKINS_URL}/$(get_component)/job/${COPY_TO_IMPLEMENTATION_FOLDER}" else echo "${JENKINS_URL}/$(get_component)/job/${COPY_TO_INTERFACE_FOLDER}" fi } function deploy_template { ## deploy template for the jobs new_config_branch="/tmp/$(get_module_name)-config1.xml" new_config_review="/tmp/$(get_module_name)-config2.xml" cp "${source_config_branch}" "${new_config_branch}" cp "${source_config_review}" "${new_config_review}" $(put_values) } function get_jenkinsfile_path { ## to get the jenkinsfile path if [[ ! -z ${each_module} ]]; then echo "${each_module#*$REPO_NAME/}/Jenkinsfile" else echo "please check the input parameters" exit 1 fi } function get_test_folder { ## test folder to be provided in job, which is used in jenkinsfile for auto-triggering once the commit is done if [[ $(get_module_type) == "if" ]]; then test_folder=' ' echo "${test_folder}" else test_folder="$(get_module_name)/test/**" echo "${test_folder}" fi } function get_module_type { ## get module type, impl for implementation; if for interface if is_implementation ${each_module}; then echo "impl" else echo "if" fi } function get_job_name { ## Job name followed is component_modulename_moduletype if [[ $(get_module_type) == "if" ]] then module_interface="$(get_module)" module_name_interface=$(echo ${module_interface///interface}| sed 's,/,_,g') job_name="$(get_component)_${module_name_interface}_$(get_module_type)" echo "${job_name}" else job_name="$(get_component)_$(get_module_name)_$(get_module_type)" echo "${job_name}" fi } function create_job { ## Create jobs for the repo ${CURL_AUTH} -X XPOST -H 'Content-Type: application/xml' -d @"${new_config_branch}" "$(get_project_path)/createItem?name=$(get_job_name)-branch" ${CURL_AUTH} -X XPOST -H 'Content-Type: application/xml' -d @"${new_config_branch}" "$(get_project_path)/createItem?name=$(get_job_name)-review" } function put_values { if [[ ! -z $(get_module) ]] && [[ ! -z ${REPO_NAME} ]] && [[ ! -z ${branch_name} ]] && [[ ! -z $(get_test_folder) ]] &&[[ ! -z $(get_jenkinsfile_path) ]] then sedcmd="s|_TYPE_|$(get_module)|g;s|_REPO_|${REPO_NAME}|g;s|_BRANCH_|${branch_name}|g;s|_MODULE_|$(get_test_folder)|g;s|Jenkinsfile|$(get_jenkinsfile_path)|g" sed -i "${sedcmd}" "${new_config_branch}" sed -i "${sedcmd}" "${new_config_review}" else echo "some value is missing, please check" exit 1 fi } check_and_create_job <file_sep>/collector_build/.mpp/.svn/pristine/42/423e88cad4e2d09b1dae283cfe68c96b01ef66aa.svn-base set -a mpp_svn="sandbox_$mpp_svn" function sandbox_log { echo "[sandbox] $@" } # This function must only execute some svn commands in sandbox mode: commit, copy, import. All others # must be executed natively. This code assumes that the sandbox mode commands are always used with # option -m or --file function sandbox_svn { local must_call_svn_log=false command="svn $@" ( echo "$@" | grep -v -q " -m " ) || must_call_svn_log=true ( echo "$@" | grep -v -q " --file " ) || must_call_svn_log=true if [ $must_call_svn_log == true ]; then command="sandbox_log $command" fi $command } function ssh { sandbox_log ssh $@ } function scp { sandbox_log scp $@ } function rsync { sandbox_log rsync $@ } # for publish_tag to work even though tag was not created function last_changed_revision { rev=`$mpp_svn info $1 2> /dev/null | grep "Last Changed Rev: " | sed 's|Last Changed Rev: ||'` test -n "$rev" || rev=0 echo $rev } set +a <file_sep>/app_jenkins/ssh.groovy dir_name = '/var/jenkins_home/.ssh/' file = new File(dir_name) file.mkdir() def save_ssh_file(file, dir) { src = new File(file) filename = file.split('/')[-1] dst = new File(dir + filename) dst << src.text } save_ssh_file('/tmp/id_rsa', dir_name) save_ssh_file('/tmp/config', dir_name) key_file = dir_name + 'id_rsa' "chmod 600 ${key_file}".execute() <file_sep>/project/create.sh #!/bin/sh ################################################################################ # # Author: <NAME> # # Summary: Jenkins Job Creation # # Description: # Creates a Jenkins job based on gerrit repo tree structure: # - Create two jenkins jobs for each module, one for CodeReview and one for Branch # - applies known job template existing in Jenkins to new job created # - Replaces the _TYPE_,_REPO_ ,_BRANCH_,_MODULE_,Jenkinsfile for the new_job created # ################################################################################ function auto_jenkinsjob { ## Auto Create Jenkinsjob for the input Repo copy_template_to_tmp_dir create_parent_directory for each_module in ${list_modules} do deploy_template create_job done } function copy_template_to_tmp_dir { ## Copy template from exisitng template job template_job_name="${COPY_FROM_TEMPLATE_BRANCH##*/} ${COPY_FROM_TEMPLATE_REVIEW##*/}" source_config_branch="/tmp/${COPY_FROM_TEMPLATE_BRANCH##*/}-config.xml" source_config_review="/tmp/${COPY_FROM_TEMPLATE_REVIEW##*/}-config.xml" for each_template in ${template_job_name}; do ${CURL_AUTH} -X GET "${template_path}/job/${each_template}/api/json?tree=name" | grep "ERROR" && echo "Template not found" && exit 1 done echo "Copying templates to tmp dir" ${CURL_AUTH} ${COPY_FROM_TEMPLATE_BRANCH}/config.xml > "${source_config_branch}" ${CURL_AUTH} ${COPY_FROM_TEMPLATE_REVIEW}/config.xml > "${source_config_review}" ##Replace regex ".*" in the template jobs to the respective branch name passed sed -i "s|\.\*|${BRANCH_NAME}|g" "${source_config_branch}" sed -i "s|\.\*|${BRANCH_NAME}|g" "${source_config_review}" } function get_module { ## get module if each_module is present if [[ ! -z ${each_module} ]]; then echo "${each_module#*$REPO_NAME/}" else exit 1 fi } function get_component { ## get component provided the repo name COMPONENT="${REPO_NAME##*/}" COMPONENT="${COMPONENT^^}" echo ${COMPONENT} } function get_module_name { ## Get module name module="$(get_module)" module_name="${module%/*}" module_name="${module_name%/interface*}" echo "${module_name}" } function deploy_template { ## deploy template for the jobs get_module_name_multiple_path=$(echo $(get_module_name)| sed "s,/,_,g;s,-,_,g") new_config_branch="/tmp/${get_module_name_multiple_path}-config1.xml" new_config_review="/tmp/${get_module_name_multiple_path}-config2.xml" cp "${source_config_branch}" "${new_config_branch}" cp "${source_config_review}" "${new_config_review}" $(put_values) } function get_jenkinsfile_path { ## to get the jenkinsfile path if [[ ! -z ${each_module} ]]; then echo "${each_module#*$REPO_NAME/}/Jenkinsfile" else echo "please check the input parameters" exit 1 fi } function get_test_folder { ## test folder to be provided in job, which is used in jenkinsfile for auto-triggering once the commit is done if [[ $(get_module_type) == "if" ]]; then test_folder=' ' echo "${test_folder}" else test_folder="$(get_module_name)/test/**" echo "${test_folder}" fi } function get_module_type { ## get module type, impl for implementation; if for interface source ${WORKSPACE}/${REPO_NAME}/.mpp/modules/pipeline if is_implementation ${each_module}; then echo "impl" else echo "if" fi } function get_job_name { ## Job name followed is component_modulename_moduletype if [[ $(get_module_type) == "if" ]] then module_interface="$(get_module)" module_name_interface=$(echo ${module_interface///interface}| sed 's,/,_,g') job_name="$(get_component)_${module_name_interface}_${BRANCH_NAME}_$(get_module_type)" echo "${job_name}" else get_module_name_multiple_path=$(echo $(get_module_name)| sed "s,/,_,g;s,-,_,g") job_name="$(get_component)_${get_module_name_multiple_path}_${BRANCH_NAME}_$(get_module_type)" ## job_name="$(get_component)_$(get_module_name)_${BRANCH_NAME}_$(get_module_type)" echo "${job_name}" fi } function create_job { ## Create jobs for the repo ${CURL_AUTH} -X XPOST -H 'Content-Type: application/xml' -d @"${new_config_review}" "${JENKINS_ROOT_URL}/$(get_project_path)/createItem?name=$(get_job_name)-review" ${CURL_AUTH} -X XPOST -H 'Content-Type: application/xml' -d @"${new_config_branch}" "${JENKINS_ROOT_URL}/$(get_project_path)/createItem?name=$(get_job_name)-branch" } function put_values { if [[ ! -z $(get_module) ]] && [[ ! -z ${REPO_NAME} ]] && [[ ! -z ${BRANCH_NAME} ]] && [[ ! -z $(get_test_folder) ]] &&[[ ! -z $(get_jenkinsfile_path) ]] then sedcmd="s|_TYPE_|$(get_module)|g;s|_REPO_|${REPO_NAME}|g;s|_BRANCH_|${BRANCH_NAME}|g;s|_MODULE_|$(get_test_folder)|g;s|Jenkinsfile|$(get_jenkinsfile_path)|g" sed -i "${sedcmd}" "${new_config_branch}" sed -i "${sedcmd}" "${new_config_review}" else echo "some value is missing, please check" exit 1 fi } function create_parent_directory { ## Create the folder structure check_component_folder=${Create_folder%%/*} other_folders=${Create_folder#*/} echo "[INFO] Check if parent folder exists: ${check_component_folder}" ${CURL_AUTH} -X GET "${JENKINS_ROOT_URL}/${PARENT_DIRECTORY}/job/${check_component_folder}/api/json?tree=name" | grep "ERROR" && echo "folder ${check_component_folder} not found" && exit 1 echo "[INFO] ${check_component_folder} folder exists, creating ${other_folders} structures if not present" for each_folder in $(echo $Create_folder | tr "/" "\n") do ${CURL_AUTH} -X POST "${JENKINS_ROOT_URL}/${PARENT_DIRECTORY}/createItem?name=${each_folder}&mode=com.cloudbees.hudson.plugins.folder.Folder&from=&json={'name':'templates','mode':'com.cloudbees.hudson.plugins.folder.Folder','from':'','Submit':'OK'}&Submit=OK" -H 'Content-Type:application/x-www-form-urlencoded' PARENT_DIRECTORY="${PARENT_DIRECTORY}/job/${each_folder}" unset each_folder done ${CURL_AUTH} -X POST "${JENKINS_ROOT_URL}/${PARENT_DIRECTORY}/createItem?name=${COPY_TO_IMPLEMENTATION_FOLDER}&mode=com.cloudbees.hudson.plugins.folder.Folder&from=&json={'name':'templates','mode':'com.cloudbees.hudson.plugins.folder.Folder','from':'','Submit':'OK'}&Submit=OK" -H 'Content-Type:application/x-www-form-urlencoded' ${CURL_AUTH} -X POST "${JENKINS_ROOT_URL}/${PARENT_DIRECTORY}/createItem?name=${COPY_TO_INTERFACE_FOLDER}&mode=com.cloudbees.hudson.plugins.folder.Folder&from=&json={'name':'templates','mode':'com.cloudbees.hudson.plugins.folder.Folder','from':'','Submit':'OK'}&Submit=OK" -H 'Content-Type:application/x-www-form-urlencoded' } function get_project_path { ## get the path where jobs to be pushed, two folders: implementation and interface if [[ "$(get_module_type)" == "impl" ]] then echo "${PARENT_DIRECTORY}/job/${COPY_TO_IMPLEMENTATION_FOLDER}" else echo "${PARENT_DIRECTORY}/job/${COPY_TO_INTERFACE_FOLDER}" fi } auto_jenkinsjob <file_sep>/app_jenkins/executors.groovy import jenkins.model.* import jenkins.model.Jenkins // create jobs Jenkins.instance.setNumExecutors(3) <file_sep>/plugin/install_plugin.py import shutil import argparse import requests import os import yaml # python install_plugin.py -d /var/lib/jenkins/plugins/ -p jenkins_plugins.yml class PluginInstaller: def __init__(self): self.dest_folder = "" self.plugins_file = "" self.plugins_list = "" def __exit__(self, *r): pass def __del__(self): pass def __enter__(self): return self def load_plugin_list(self): with open(self.plugins_file, 'r') as data: try: self.plugins_list = yaml.load(data) except yaml.YAMLError as exc: print(exc) def create_plugin_folder(self): try: os.makedirs(self.dest_folder) except OSError: pass def download_plugins(self): for plugin, version in self.plugins_list.items(): print "plugin: {}".format(plugin) r = requests.get( "http://updates.jenkins-ci.org/download/plugins/" + plugin + "/" + str(version) + "/" + plugin + ".hpi", stream=True) if r.status_code == 200: file_name = plugin + ".hpi" with open(self.dest_folder + "/" + file_name, 'wb') as f: r.raw.decode_content = True shutil.copyfileobj(r.raw, f) print("success download: " + plugin + ":" + str(version)) else: print("This plugin can not be download: " + plugin + ":" + str(version)) def parse_arg(self): with PluginInstallArgParse() as ap: stored_values = ap.deploy_argv_parser() self.dest_folder = stored_values.dest_of_plugin self.plugins_file = stored_values.plugin_file class PluginInstallArgParse(argparse.ArgumentParser): def __init__(self): super(PluginInstallArgParse, self).__init__() pass def __enter__(self): return self def __exit__(self, *err): pass def __del__(self): pass def deploy_argv_parser(self): args = None self.description = 'python install_plugin.py -d <plugin_folder> -p <plugin_file>' self.add_argument('-d', '--dest_of_plugin', help='Destination folder of plugins', required=True) self.add_argument('-p', '--plugin_file', help='Jenkins plugins file', required=True) try: args = self.parse_args() except argparse.ArgumentError: pass return args if __name__ == "__main__": installer = PluginInstaller() installer.parse_arg() installer.load_plugin_list() installer.create_plugin_folder() installer.download_plugins() <file_sep>/job_dsl/generate_build_fp_tvnf.gvy def executeShell = '''#!/bin/bash -ex set -ex cp /tmp/function_build_fp_tvnf.sh . . /tmp/function_build_fp_tvnf.sh echo "====== check latest version ==========" latest_version=$(get_latest_version) new_version=$(get_next_version "$latest_version") echo "====== download product.txt for latest version ===============" latest_product_txt=$(get_product_txt "$latest_version") echo "====== handle artifacts to build =============" artifacts_to_build=$(get_artifacts_to_build) handle_artifacts_to_build "$artifacts_to_build" "$new_version" echo "====== handle other artifacts =============" handle_other_artifacts "$latest_product_txt" "$artifacts_to_build" "$new_version" echo "====== copy content.txt =========" copy_artifacts "$latest_version/METADATA/content.txt" "$new_version/METADATA/content.txt" echo "====== create product.txt for new version ========" properties_file=$(get_artifact_properties "$new_version") cp /tmp/update_product_txt.py . python update_product_txt.py "$latest_product_txt" "$properties_file" "$new_version" "product.txt" echo "====== upload product.txt for new version ========" upload_artifact "product.txt" "$new_version/METADATA/" exit 0 ''' def init_script = freeStyleJob("build_fp_tvnf") { wrappers { preBuildCleanup() timeout { noActivity(3600) failBuild() writeDescription('Build failed due to timeout') } credentialsBinding { usernamePassword('GLOBAL_ARTIFACTORY_USERNAME', 'GLOBAL_ARTIFACTORY_TOKEN', 'ca_fp_devops') } } steps { shell(executeShell) } } <file_sep>/job_dsl/function_build_fp_tvnf.sh #!/bin/bash -ex # compare version like 0.0.5 function compare_version() { version1=$1 version2=$2 OIFS=$IFS IFS='.'; for i in $version1; do head2=${version2%%.*} if [ "$i" -lt "$head2" ]; then echo smaller return elif [ "$i" -gt "$head2" ]; then echo bigger return fi version2=${version2#${head2}.} done echo "equal" IFS=$OIFS } # get latest version function get_latest_version() { curl -u$GLOBAL_ARTIFACTORY_USERNAME:$GLOBAL_ARTIFACTORY_TOKEN -X POST --header "content-type: text/plain" --data 'items.find({"repo":{"$eq":"netact-fast_pass-local"}, "type":{"$eq":"folder"}, "name":{"$eq":"METADATA"} }).include("*")' "$GLOBAL_ARTIFACTORY_SERVICENAME:$GLOBAL_ARTIFACTORY_PORT/artifactory/api/search/aql" -k > search_result.json latest_version="0.0.0" for version in $(cat search_result.json | jq -r '.results[]' | jq -r '.path' | grep fp-tvnf); do version=${version#*fp-tvnf/} compare=$(compare_version $version $latest_version) if [ "$compare" = "bigger" ]; then latest_version=$version fi done echo $latest_version } function get_artifact_properties() { local version=$1 local filename="artifact_properties.$version.json" local search_string='items.find({"repo":{"$eq":"netact-fast_pass-local"}, "path":{"$match":"fp-tvnf/VERSION"}, "type":{"$eq":"file"}}).include("*")' search_string=$(echo $search_string | sed -r "s|VERSION|$version|") curl -u$GLOBAL_ARTIFACTORY_USERNAME:$GLOBAL_ARTIFACTORY_TOKEN -X POST --header "content-type:text/plain" --data "$search_string" "$GLOBAL_ARTIFACTORY_SERVICENAME:$GLOBAL_ARTIFACTORY_PORT/artifactory/api/search/aql" > $filename echo "$filename" } # get new version function get_next_version() { local version=$1 version_tail=${version##*.} version_head=${version%${version_tail}} version_tail=$((version_tail+1)) echo $version_head$version_tail } function download_file() { local file=$1 local file_to_save=$2 curl -u$GLOBAL_ARTIFACTORY_USERNAME:$GLOBAL_ARTIFACTORY_TOKEN -X GET "$GLOBAL_ARTIFACTORY_SERVICENAME:$GLOBAL_ARTIFACTORY_PORT/artifactory/netact-fast_pass-local/fp-tvnf/$version/METADATA/$file" -k --output "$file_to_save" } # get product.txt for latest version function get_product_txt() { local version=$1 local filename="product.txt."$version download_file "product.txt" "$filename" echo "$filename" } # get content.txt function get_content_txt() { local version=$1 local filename="content.txt."$version download_file "content.txt" "$filename" echo "$filename" } # check artifacts under to_build folder function get_artifacts_to_build() { curl -u$GLOBAL_ARTIFACTORY_USERNAME:$GLOBAL_ARTIFACTORY_TOKEN -X POST --header "content-type: text/plain" --data 'items.find({"repo":{"$eq":"netact-fast_pass-local"}, "type":{"$eq":"file"}, "path":{"$eq":"fp-tvnf/to_build"} }).include("*")' "$GLOBAL_ARTIFACTORY_SERVICENAME:$GLOBAL_ARTIFACTORY_PORT/artifactory/api/search/aql" > search_result.json cat search_result.json | jq -r '.results[]' | jq -r '.name' | tr '\n' ',' | sed 's|,$||' } # copy artifacts to build to new version folder function copy_artifacts() { local file_from=$1 local file_to=$2 curl -u$GLOBAL_ARTIFACTORY_USERNAME:$GLOBAL_ARTIFACTORY_TOKEN -X POST "$GLOBAL_ARTIFACTORY_SERVICENAME:$GLOBAL_ARTIFACTORY_PORT/artifactory/api/copy/netact-fast_pass-local/fp-tvnf/$file_from?to=/netact-fast_pass-local/fp-tvnf/$file_to" } # move artifacts to artifacts folder for future use function move_artifacts() { local file_from=$1 local file_to=$2 curl -u$GLOBAL_ARTIFACTORY_USERNAME:$GLOBAL_ARTIFACTORY_TOKEN -X POST "$GLOBAL_ARTIFACTORY_SERVICENAME:$GLOBAL_ARTIFACTORY_PORT/artifactory/api/move/netact-fast_pass-local/fp-tvnf/$file_from?to=/netact-fast_pass-local/fp-tvnf/$file_to" } # upload artifacts function upload_artifact() { local file=$1 local path=$2 curl -u$GLOBAL_ARTIFACTORY_USERNAME:$GLOBAL_ARTIFACTORY_TOKEN -X PUT -T "$file" "$GLOBAL_ARTIFACTORY_SERVICENAME:$GLOBAL_ARTIFACTORY_PORT/artifactory/netact-fast_pass-local/fp-tvnf/$path/" } function handle_artifacts_to_build() { local artifacts_to_build=$1 local new_version=$2 if [ -z "$artifacts_to_build" ]; then echo "no artifacts to build, exiting" exit 0 fi OIFS=$IFS IFS=',' for artifact in $artifacts_to_build; do copy_artifacts "to_build/$artifact" "$new_version/$artifact" filename=$(echo $artifact | sed -r 's|(.*).[0-9]+.[0-9]+.[0-9]+.*|\1|') move_artifacts "to_build/$artifact" "artifacts/$filename/" done IFS=$OIFS } # get artifacts from product.txt of latest version function get_all_artifacts() { product_txt=$1 cat $product_txt | jq -r '.artifacts[]' | jq -r '.filename' | tr '\n' ',' | sed 's|,$||' } # remove artifacts to build from all artifacts function remove_artifact_from_list() { local artifact_list=$1 local artifacts_to_remove=$2 artifact_list=$artifact_list"," artifacts_to_remove=$artifacts_to_remove"," while [ ! -z "$artifacts_to_remove" ]; do artifact=${artifacts_to_remove%%,*} artifact_list=$(echo $artifact_list | sed -r "s|(.*)($artifact[^,]*,)(.*)|\1\3|") artifacts_to_remove=${artifacts_to_remove##${artifact},} done echo $artifact_list | sed 's|,$||' } # get artifact name from list function get_artifact_name() { local artifact_list=$1 artifact_list=$artifact_list"," name_list="" while [ ! -z "$artifact_list" ]; do artifact=${artifact_list%%,*} name=$(echo $artifact | sed -r 's|(.*).[0-9]+.[0-9]+.[0-9]+(.*)|\1|') name_list=$name_list","$name artifact_list=${artifact_list##${artifact},} done echo $name_list | sed 's|^,||' } # copy artifacts to new version folder and artifacts folder function handle_other_artifacts() { local product_txt=$1 local new_artifacts=$2 local new_version=$3 all_artifacts=$(get_all_artifacts $product_txt) new_artifact_names=$(get_artifact_name $new_artifacts) other_artifacts=$(remove_artifact_from_list $all_artifacts $new_artifact_names) OIFS=$IFS IFS=',' for artifact in $other_artifacts; do dirname=$(echo $artifact | sed -r 's|(.*).[0-9]+.[0-9]+.[0-9]+.*|\1|') copy_artifacts "artifacts/$dirname/$artifact" "$new_version/$artifact" done IFS=$OIFS } <file_sep>/collector_build/.mpp/admin/upgrade-to #!/bin/bash source `readlink -f $0 | xargs dirname | xargs dirname`/frontend || exit 1 release_root=http://svne1.access.nokiasiemensnetworks.com/isource/svnroot/oss_pp/tags/published-frontend # check local modifications local_modifications=`$mpp_svn st --ignore-externals $mpp_root_dir | grep -v "^?" | grep -v "^X" | tee` test -z "$local_modifications" || fail "Directory $mpp_root_dir can't have any uncommited changes before upgrade\n${local_modifications}\nYou need to get rid of the local changes above before you can continue." # check new version test 1 -eq $# || fail "Usage: $0 <version number>" exists_in_svn $release_root/$1 || fail "Version doesn't exists: $release_root/$1" # update .mpp locally log "Updating .mpp directory locally to $release_root/$1" $mpp_svn propget svn:externals $mpp_root_dir | grep -v "^$" | sed "s|\.mpp[[:space:]].*|.mpp $release_root/$1|" > $mpp_work_dir/upgrade-to $mpp_svn -q propset svn:externals $mpp_root_dir -F $mpp_work_dir/upgrade-to $mpp_svn -q update $mpp_root_dir/ # make automatic upgrade modifications log "Making automatic upgrade modifications" $mpp_root_dir/.mpp/admin/make-upgrade-modifications # commit the changes log "Commiting the changes" $mpp_svn -q commit $mpp_root_dir -m "Upgrading MPP build tools to version $1" log "Upgrade to $release_root/$1 was successful" <file_sep>/app_jenkins/rebuild.sh #!/bin/bash TOKEN=${1:-xxx} sudo docker stop myjenkins || true sudo docker rmi myjenkins_image sudo docker build -t myjenkins_image . sudo docker run -dit --rm -e SECRET="$TOKEN" --name myjenkins --network host myjenkins_image echo "waiting for myjenkins to start" I=0 while [ $(sudo docker inspect --format='{{json .State.Status}}' myjenkins | sed -r 's|"(.+)"|\1|' ) != "running" ]; do echo "waiting for myjeknins for $(expr $I '*' 5)s" if [ $I -gt 10 ]; then # alternatively, if [[ I -gt 10 ]]; then echo "myjenkins not started, exiting" exit 1 fi I=$((I+1)) sleep 5 done I=0 while ! sudo docker exec myjenkins cat /var/jenkins_home/secrets/initialAdminPassword ; do echo "waiting for password for $(expr $I '*' 5)s" if [ $I -gt 10 ]; then # alternatively, if [[ I -gt 10 ]]; then echo "cannot get password, exiting" exit 1 fi I=$((I+1)) sleep 5 done echo -n "password: " sudo docker exec myjenkins cat /var/jenkins_home/secrets/initialAdminPassword <file_sep>/app_jenkins/views.groovy import jenkins.model.Jenkins import hudson.model.ListView // get Jenkins instance Jenkins jenkins = Jenkins.getInstance() // create the new view jenkins.addView(new ListView('CI')) jenkins.addView(new ListView('TVNF')) jenkins.addView(new ListView('test')) // get the view ciView = hudson.model.Hudson.instance.getView('CI') tvnfView = hudson.model.Hudson.instance.getView('TVNF') testView = hudson.model.Hudson.instance.getView('test') // add a job by its name ciView.doAddJobToView('build_ci_app_image') ciView.doAddJobToView('build_ci_microk8s') ciView.doAddJobToView('deploy_ci') tvnfView.doAddJobToView('build_fp_tvnf') tvnfView.doAddJobToView('replicate_artifacts') testView.doAddJobToView('environment_variable') testView.doAddJobToView('kubernetes_plugin') testView.doAddJobToView('variable_scripted') testView.doAddJobToView('variable_declarative') // save current Jenkins state to disk jenkins.save() <file_sep>/vars/buildAdapCollector.groovy #!/usr/bin/env groovy /** * Function that builds a collector * Properties can be overwritten by end users */ def call(Map userConfig) { Map defaultConfig = [ backendCredentialsId: "netact-backend", containerName: 'build-image', feToolsRepoPath: "netact-generic-releases/CI/fe_tools", feToolsVersion: "", gerritCredentialsId: 'netact-gerrit', gerritProjectBranch: 'master', gitLfsFetchCommand: "git lfs fetch --all", gitLfsHostname: "esisoj70.emea.nsn-net.net", gitLfsPort: 8282, imageRepoPrefix: "netact-docker-releases", imageRepoDomain: "repo.lab.pl.alcatel-lucent.com", imageTag: 'latest', resourceRequestMemory: "2000Mi", ] Map config = defaultConfig + userConfig pipeline { environment { GERRIT_BRANCH = 'master' GERRIT_HOST = 'gerrite1.ext.net.nokia.com' GERRIT_PORT = '8282' GERRIT_PATCHSET_REVISION = 'HEAD' GERRIT_CHANGE_URL = 'NA' JAR_SIGN_FILE = credentials('netact-jarsign-file') } agent { kubernetes { label "k8s-netact-${UUID.randomUUID().toString()}" inheritFrom 'k8s-build' containerTemplate { name config.containerName image "${config.imageRepoPrefix}.${config.imageRepoDomain}/${config.imageName}:${config.imageTag}" resourceRequestMemory config.resourceRequestMemory alwaysPullImage true workingDir '/home/jenkins' ttyEnabled true command 'cat' } } } triggers { gerrit( commitMessageParameterMode: 'PLAIN', commentTextParameterMode: 'PLAIN', customUrl: '', gerritProjects: [[ branches: [[ compareType: 'PLAIN', pattern: config.gerritProjectBranch ]], compareType: 'PLAIN', disableStrictForbiddenFileVerification: false, pattern: config.repo, ]], serverName: 'nokia-gerrite1', triggerOnEvents: [ changeMerged(), ] ) } stages { stage('Cleanup workspace') { steps { step([$class: 'WsCleanup']) } } stage('Checkout code') { steps { git(credentialsId: 'netact-gerrit', branch: config.gerritProjectBranch, url: "ssh://ca_netact_jenkins@${GERRIT_HOST}:${GERRIT_PORT}/${config.repo}") } } stage('Prepare Build') { steps { script { showInfo(config) downloadFETools(config) prepareBuild(config) // gitLfsPull(config, config.buildModulePath) } } } stage('Build') { steps { script { container("${config.containerName}") { sshagent(credentials: [config.backendCredentialsId, config.gerritCredentialsId]) { sh """ source /etc/profile 2>/dev/null cd "${env.WORKSPACE}/${config.buildModulePath}" .mpp/run config_ris_id "${config.buildModulePath}" "${config.testModulePath}" export GERRIT_CHANGE_OWNER_EMAIL=`git log --no-merges -n1 --pretty=format:'%ce'` .mpp/build """ } } } } } } } } <file_sep>/vars/buildComponentBranch.groovy #! usr/bin/env groovy def call(Map config) { if (config.autoPromoteArtifacts == 'true' || config.publishSnapshots == 'true') { env.mpp_publish_artifactory = 'true' } pipeline { environment { //MPP_RIS_ID = "${config.mppRisId}" MPP_DEBUG = "${config.mppDebug}" GERRIT_SSH_USER = "${config.gerritSSHUser}" JAR_SIGN_FILE = credentials('netact-jarsign-file') NETACT_ARTIFACTORY_KEY = credentials("${config.artifactoryCredentialsId}") JENKINS_CREDS = credentials('ca-jenkins-readonly') } agent { kubernetes { label "k8s-netact-${UUID.randomUUID().toString()}" inheritFrom 'k8s-build' containerTemplate { name config.containerName image "${config.imageRepoPrefix}.${config.imageRepoDomain}/${config.imageName}:${config.imageTag}" resourceRequestMemory config.resourceRequestMemory alwaysPullImage true workingDir '/home/jenkins' ttyEnabled true command 'cat' } } } parameters { string(name: 'GERRIT_REFSPEC', defaultValue: 'refs/heads/master', description: 'Reference for "Build Now"') } triggers { gerrit( commitMessageParameterMode: 'PLAIN', commentTextParameterMode: 'PLAIN', customUrl: '', gerritProjects: [[ branches: [[ compareType: 'PLAIN', pattern: "${config.gerritBranch}" ]], compareType: 'PLAIN', disableStrictForbiddenFileVerification: false, pattern: env.GERRIT_PROJECT, filePaths: config.gerritTriggerFilePaths, ]], serverName: env.GERRIT_NAME, triggerOnEvents: [ changeMerged(), commentAddedContains('retrigger-component-upgrade'), commentAddedContains('retrigger-release-upgrade'), commentAddedContains('retrigger-scratch-installation') ] ) } options { timestamps() timeout(time: config.jobTimeout, unit: 'MINUTES') buildDiscarder(logRotator(daysToKeepStr: config.jobBuildHistory, artifactDaysToKeepStr: config.jobArtifactsDaysToKeep, numToKeepStr: config.jobBuildHistoryCount)) } stages { stage('Prepare Build') { steps { showInfo(config) downloadFETools(config) prepareBuild(config) gitLfsPull(config, config.buildModulePath) } } stage('Build') { steps { script { env.BUILD_PHASE = "branch" updateChangedSinceReview(config) } buildModule(config, config.buildModulePath) script { if(config.changedSinceReview == "false" && config.stageComponentUpgrade == "true" && config.skipComponentUpgradeIfNoChange == "true" && config.testModulePath) { config.stageComponentUpgrade = "false" addCustomRisTag(config, config.buildModulePath) } } } } stage('Publish NPM') { when { expression { config.stagePublishNPM == "true" } } steps { publishNPM(config) } } stage('Publish Artifacts') { when { expression { config.stagePublishArtifacts == "true" } } steps { publishArtifacts(config) } } stage('Verification') { parallel { stage('Functional Tests') { stages { stage('Component Upgrade') { when { expression { config.stageComponentUpgrade == "true" } expression { config.testModulePath } } steps { buildModule(config, config.testModulePath) } } stage('Interface Promotion') { when { expression { config.stageInterfacePromotion == "true" } } steps { promoteInterface(config, config.buildModulePath) } } } } stage('Release Upgrade'){ when { expression { config.stageReleaseUpgrade == "true" } expression { config.testModulePath } anyOf { expression { env.GERRIT_EVENT_TYPE == 'change-merged' } expression { env.GERRIT_EVENT_COMMENT_TEXT =~ /.*retrigger-release-upgrade.*/ } } } steps { buildModule(config, config.testModulePath, config.releaseProperties) } } stage('Scratch Installation') { when { expression { config.stageScratchInstallation == "true" } expression { config.testModulePath } anyOf { expression { env.GERRIT_EVENT_TYPE == 'change-merged' } expression { env.GERRIT_EVENT_COMMENT_TEXT =~ /.*retrigger-scratch-installation.*/ } } } steps { buildModule(config, config.testModulePath, config.scratchProperties) } } } } stage ('Promote Artifacts') { when { allOf { expression { config.autoPromoteArtifacts == "true" } expression { env.mpp_publish_artifactory == "true" } } } steps { promoteArtifacts(config) } } stage('Create Tag') { when { expression { config.stageCreateTag == "true" } } steps { createTag(config, config.buildModulePath) } } } post { always { junit allowEmptyResults: true, testResults: config.junitTestReportPaths } } } } <file_sep>/plugin/jenkins_plugins.yml ace-editor: "1.1" ant: "1.9" antisamy-markup-formatter: "1.5" apache-httpcomponents-client-4-api: "4.5.5-3.0" artifactory: "2.16.2" audit-trail: "2.2" authentication-tokens: "1.3" bouncycastle-api: "2.17" branch-api: "2.1.2" build-name-setter: "1.6.9" build-timeout: "1.19" command-launcher: "1.2" cloudbees-folder: "6.1.2" cobertura: "1.10" conditional-buildstep: "1.3.6" config-file-provider: "3.4.1" copyartifact: "1.41" credentials: "2.1.18" credentials-binding: "1.17" discard-old-build: "1.05" display-url-api: "2.3.0" docker-commons: "1.13" docker-java-api: "3.0.14" docker-plugin: "1.1.5" docker-workflow: "1.17" durable-task: "1.28" email-ext: "2.63" envinject: "2.1.6" envinject-api: "1.5" environment-script: "1.2.5" extended-choice-parameter: "0.76" exclusive-execution: "0.8" external-monitor-job: "1.7" git: "3.9.1" git-client: "2.7.4" git-server: "1.7" github: "1.29.3" github-api: "1.95" github-branch-source: "2.4.1" github-organization-folder: "1.6" gradle: "1.26" greenballs: "1.15" groovy: "2.0" handlebars: "1.1.1" icon-shim: "2.0.3" ivy: "1.28" jackson2-api: "2.9.8" javadoc: "1.4" jdk-tool: "1.2" job-dsl: "1.70" job-import-plugin: "3.0" jquery-detached: "1.2.1" jquery: "1.11.2-0" jsch: "0.1.54.2" junit: "1.26.1" ldap: "1.20" mailer: "1.22" mapdb-api: "1.0.9.0" matrix-auth: "2.3" matrix-project: "1.13" maven-plugin: "3.2" modernstatus: "1.2" momentjs: "1.1.1" multiple-scms: "0.6" multi-branch-project-plugin: "0.5.1" nodelabelparameter: "1.7.2" pam-auth: "1.4" parameterized-trigger: "2.35.2" pipeline-build-step: "2.7" pipeline-github-lib: "1.0" pipeline-graph-analysis: "1.9" pipeline-input-step: "2.9" pipeline-milestone-step: "1.3.1" pipeline-model-api: "1.3.4" pipeline-model-declarative-agent: "1.1.1" pipeline-model-definition: "1.3.4" pipeline-model-extensions: "1.3.4" pipeline-rest-api: "2.10" pipeline-stage-step: "2.3" pipeline-stage-tags-metadata: "1.3.4" pipeline-stage-view: "2.10" plain-credentials: "1.5" rebuild: "1.29" resource-disposer: "0.12" robot: "1.6.5" role-strategy: "2.9.0" run-condition: "1.2" scm-api: "2.3.0" script-security: "1.49" simple-theme-plugin: "0.5.1" ssh-credentials: "<PASSWORD>" ssh-slaves: "1.29.1" startup-trigger-plugin: "2.9.3" structs: "1.17" token-macro: "2.5" trilead-api: "1.0.0" urltrigger: "0.44" vncrecorder: "1.25" vncviewer: "1.5" windows-slaves: "1.4" workflow-aggregator: "2.5" workflow-api: "2.33" workflow-basic-steps: "2.13" workflow-cps: "2.61" workflow-cps-global-lib: "2.12" workflow-durable-task-step: "2.27" workflow-job: "2.31" workflow-multibranch: "2.20" workflow-scm-step: "2.7" workflow-step-api: "2.17" workflow-support: "2.24" ws-cleanup: "0.34" xvnc: "1.24" <file_sep>/job_dsl/generate_fp_run_ta.gvy def executeShell = '''#!/bin/bash -ex set -ex curl $GLOBAL_CURL_CA_CERT -f -X GET -u$GLOBAL_ARTIFACTORY_USERNAME:$GLOBAL_ARTIFACTORY_TOKEN "$GLOBAL_ARTIFACTORY_SERVICENAME:$GLOBAL_ARTIFACTORY_PORT/artifactory/api/archive/download/${GLOBAL_ARTIFACTORY_EXTRA_PATH}${JOB_DIRECTORY}devopstools/python-utils?archiveType=zip" --output python-utils.zip unzip -d ./python-utils python-utils.zip TEST_SERVER_IP=$(python3 python-utils/find_oamip_for_vnf_by_cbam.py --vnf_name ${VNF_NAME} --client_id Cbam_client --secret ${GLOBAL_CBAM_CLIENT_SECRET} --cbam_ip ${GLOBAL_CBAM_IP}) # wait for tvnf to initialize K=0 until ping "$TEST_SERVER_IP" -c 1 || [[ K -gt 100 ]] ; do echo "waiting for network connection for the $K time" sleep 5 K=$((K+1)) done if [[ K -gt 100 ]]; then echo "[DEBUG:] having waited for network connection for 500 seconds, exiting" exit -1 fi TVNF_JENKINS_URL="http://${TEST_SERVER_IP}:8080" # download jenkins cli K=0 until curl -OL ${TVNF_JENKINS_URL}/jnlpJars/jenkins-cli.jar || [[ K -gt 100 ]]; do echo "trying to download jenkins cli for $K time" sleep 5 K=$((K+1)) done if [[ K -gt 100 ]]; then echo "[DEBUG:] having waited for jenkins cli for 500 seconds, exiting" exit -1 fi # wait for jenkins job creation K=0 until java -jar jenkins-cli.jar -s ${TVNF_JENKINS_URL} -auth 'admin:123456' list-jobs | grep run_fast_pass_ta || [[ K -gt 100 ]] ; do echo "waiting for jenkins job creation for $K time" sleep 5 K=$((K+1)) done if [[ K -gt 100 ]]; then echo "[DEBUG:] having waited for jenkins job for 500 seconds, exiting" exit -1 fi # get parameters for ta job curl $GLOBAL_CURL_CA_CERT -f -X GET -u$GLOBAL_ARTIFACTORY_USERNAME:$GLOBAL_ARTIFACTORY_TOKEN "$GLOBAL_ARTIFACTORY_SERVICENAME:$GLOBAL_ARTIFACTORY_PORT/artifactory/init-fp-tvnf/deployment/fastpass_ta_parameters.json" --output fastpass_ta_parameters.json LAB_NAME=$(cat fastpass_ta_parameters.json | jq -r '.lab_name') NE_TYPE=$(cat fastpass_ta_parameters.json | jq -r '.ne_type') BROWSER=$(cat fastpass_ta_parameters.json | jq -r '.browser') # do not exit even if ta build fails set +e BUILD_RET=0 if ! java -jar jenkins-cli.jar -s ${TVNF_JENKINS_URL} -auth 'admin:123456' build run_fast_pass_ta -s -v -p DOCKER_IMAGE=neveexec -p LAB=${LAB_NAME} -p NE_TYPE=${NE_TYPE} -p BROWSER=${BROWSER}; then BUILD_RET=-1 fi set -e curl ${TVNF_JENKINS_URL}/job/run_fast_pass_ta/api/json -o job.json LAST_BUILD_URL=$(cat job.json | jq -r '.lastBuild.url') LAST_BUILD_URL=$(echo $LAST_BUILD_URL | sed "s/127.0.0.1/$TEST_SERVER_IP/g") mkdir -p ${BUILD_NUMBER} curl -o ${BUILD_NUMBER}/NeVe-TA_log.html -OL ${LAST_BUILD_URL}/robot/report/NeVe-TA_log.html curl -o ${BUILD_NUMBER}/NeVe-TA_report.html -OL ${LAST_BUILD_URL}/robot/report/NeVe-TA_report.html curl -o ${BUILD_NUMBER}/NeVe-TA_report.html -OL ${LAST_BUILD_URL}/robot/report/NeVe-TA_output.xml exit ${BUILD_RET} ''' def folderName = folder("${JOB_DIRECTORY}fp_tvnf_${GLOBAL_DEVOPS_SERVER_NAME}") { displayName("fp-tvnf_${GLOBAL_DEVOPS_SERVER_NAME}") description("Folder for Fast Pass Test VNF jobs") } def init_script = freeStyleJob("${JOB_DIRECTORY}fp_tvnf_${GLOBAL_DEVOPS_SERVER_NAME}/run-testcases") { parameters { stringParam("WEBUI_TASK_ID", "", "web ui task id") stringParam("TEST_CASES", "", "test cases") stringParam("VNF_NAME", "", "test vnf name") } wrappers { preBuildCleanup() timeout { noActivity(3600) failBuild() writeDescription('Build failed due to timeout') } credentialsBinding { usernamePassword('GLOBAL_CBAM_CLIENT_ID', 'GLOBAL_CBAM_CLIENT_SECRET', 'CBAM-Cbam_client') usernamePassword('GLOBAL_ARTIFACTORY_USERNAME', 'GLOBAL_ARTIFACTORY_TOKEN', 'ndap-artifactory-admin') } } steps { shell(executeShell) } } <file_sep>/vars/downloadFETools.groovy #!/usr/bin/env groovy def call (Map params) { container("${params.containerName}") { script { env.fe_repo_path = params.feToolsRepoPath env.fe_version = params.feToolsVersion } sh ''' source /etc/profile 2>/dev/null cd ${WORKSPACE} if [ -z "${fe_version}" ]; then fe_version=$(curl -sfk "${ARTIFACTORY_HTTPS_URL}/api/storage/${fe_repo_path}" \ | python -c 'import sys,json,re; \ data=json.load(sys.stdin); \ uris=map(lambda e: e["uri"][1:], data["children"]); \ uris=filter(lambda e: re.match(r"[0-9.]+$", e), uris); \ print(sorted(uris)[-1])') fi [[ -d "${WORKSPACE}/.mpp" ]] && { echo ".mpp folder already exists, please remove"; exit 1; } echo "downloading mpp frontend tools version $fe_version" curl -Ls "${ARTIFACTORY_HTTPS_URL}/${fe_repo_path}/${fe_version}/fe_tools-${fe_version}.tar.gz" | tar xz ''' } } <file_sep>/vars/publishArtifacts.groovy #!/usr/bin/env groovy def call(Map params) { container("${params.containerName}") { script { // Lookup the Artifactory server from the global environment variable: // https://confluence.app.alcatel-lucent.com/display/AACTODEVOPS/Jenkins+environment+and+contract def artifactoryServer = Artifactory.server env.ARTIFACTORY_SERVER_ID artifactoryServer.credentialsId = params.artifactoryCredentialsId // Get build number from fingerprint file def searchPattern = "**/${params.buildModulePath}/fingerprint*.txt" if (params.buildModulePath == '.') { searchPattern = '**/fingerprint*.txt' } def fingerprintFiles = findFiles glob: searchPattern if (!fingerprintFiles) { currentBuild.result = 'ABORTED' error "Fingerprint file not found with search pattern: ${searchPattern}" } def props = readProperties file: "${env.WORKSPACE}/${params.buildModulePath}/${fingerprintFiles[0].name}" // Create Artifactory Build Info def buildInfo = Artifactory.newBuildInfo() buildInfo.env.capture = true buildInfo.env.collect() buildInfo.name = env.GERRIT_PROJECT.replaceAll('/', '_') if (params.buildModulePath != '.') { buildInfo.name = (buildInfo.name + '/' + params.buildModulePath).replaceAll('/', '_') } buildInfo.number = props.mpp_build_number def uploadSpec = """ { "files": [ { "pattern": "${params.publishPattern}", "target" : "${params.publishRepo}/${buildInfo.name}/" } ] } """ // Publish to artifactory artifactoryServer.upload(uploadSpec, buildInfo) artifactoryServer.publishBuildInfo(buildInfo) } } } <file_sep>/pipeline/jenkinsfile_declarative.gvy pipeline { agent any parameters { string(name: "REPOSITORY", defaultValue: "init-fp-tvnf", description: "Repository name in Artifactory") } stages { stage ('prepare environmental variables') { steps { withCredentials([usernamePassword(credentialsId: 'ca_fp_devops', passwordVariable: 'GLOBAL_ARTIFACTORY_TOKEN', usernameVariable: 'GLOBAL_ARTIFACTORY_USERNAME')]) { sh 'echo "0.0.1" > version_file' } script { VNFD_VER=readFile('version_file').trim() } echo "${VNFD_VER}" build job: 'test_job', parameters: [ string(name: "NAME", value: "${REPOSITORY}.${VNFD_VER}"), string(name: "AGE", value: "38") ] } } } } <file_sep>/collector_build/.mpp/admin/make-upgrade-modifications #!/bin/bash source `readlink -f $0 | xargs dirname | xargs dirname`/frontend || exit 1 function replace { sed -i "s|$1|$2|g" $mpp_root_dir/mpp.properties } replace bamboo_build_number mpp_build_number replace mpp_tag_name mpp_build_number replace import_to_ris_new publish_to_ris replace "run_mpp -b action" trigger_action replace "run_mpp action" run_action <file_sep>/vars/updateChangedSinceReview.groovy #! usr/bin/env groovy def call (Map params) { container("${params.containerName}") { sshagent(credentials: [params.gerritCredentialsId]) { mergeHead = sh(script: '''source /etc/profile 2>/dev/null && git rev-parse HEAD''', returnStdout: true) reviewHead = sh(script: '''source /etc/profile 2>/dev/null && \ .mpp/run gerrit query --format JSON --comments change:"${GERRIT_CHANGE_NUMBER}" | sed 's/\"//g' | \ grep -Eo "username:${GERRIT_SSH_USER}},message:Patch Set ${GERRIT_PATCHSET_NUMBER}:[^}]+?REVIEW_HEAD:[0-9a-z]{40}" | \ tail -1 | cut -d":" -f5''', returnStdout: true) script { if(mergeHead == reviewHead) { sh """ source /etc/profile 2>/dev/null .mpp/run gerrit_reply "MERGE_HEAD:${mergeHead}, no change since review build" """ } else { params.changedSinceReview = "true" sh """ source /etc/profile 2>/dev/null .mpp/run gerrit_reply "MERGE_HEAD:${mergeHead}, changed since review build" """ } } } } } <file_sep>/vars/promoteArtifacts.groovy #!/usr/bin/env groovy def call(Map params) { container("${params.containerName}") { script { def artifactoryServer = Artifactory.server env.ARTIFACTORY_SERVER_ID artifactoryServer.credentialsId = params.artifactoryCredentialsId if (fileExists("${env.WORKSPACE}/${params.buildModulePath}/target/build-info.json")) { // Load the build info generated by the Maven Artifactory plugin def buildInfo = readJSON file: "${params.buildModulePath}/target/build-info.json" def promotionConfig = [ buildName : buildInfo.name, buildNumber : buildInfo.number, status : 'Released', targetRepo : buildInfo.properties['buildInfo.env.mpp_artifactory_repo_publish'], sourceRepo : buildInfo.properties['buildInfo.env.mpp_artifactory_repo'], includeDependencies: false, copy : true, // "copy" must be used because "move" requires delete permission failFast : true ] artifactoryServer.promote(promotionConfig) } else if (fileExists("${env.WORKSPACE}/${params.buildModulePath}/package.json")) { def buildInfo = readJSON file: "${params.buildModulePath}/package.json" def promotionConfig = [ buildName : buildInfo.name.replaceAll('@','').replaceAll('/','_'), buildNumber : buildInfo.version, status : 'Released', sourceRepo : params.publishNPMRepo, targetRepo : params.releaseNPMRepo, copy : true ] artifactoryServer.promote(promotionConfig) } else { // Get build number from fingerprint file def searchPattern = "**/${params.buildModulePath}/fingerprint*.txt" if (params.buildModulePath == '.') { searchPattern = '**/fingerprint*.txt' } def fingerprintFiles = findFiles glob: searchPattern if (!fingerprintFiles) { currentBuild.result = 'ABORTED' error "Fingerprint file not found with search pattern: ${searchPattern}" } def props = readProperties file: "${env.WORKSPACE}/${params.buildModulePath}/${fingerprintFiles[0].name}" def buildInfo = Artifactory.newBuildInfo() buildInfo.name = env.GERRIT_PROJECT.replaceAll('/', '_') if (params.buildModulePath != '.') { buildInfo.name = (buildInfo.name + '/' + params.buildModulePath).replaceAll('/', '_') } buildInfo.number = props.mpp_build_number def promotionConfig = [ buildName : buildInfo.name, buildNumber : buildInfo.number, status : 'Released', sourceRepo : params.publishRepo, targetRepo : params.releaseRepo, copy : true ] artifactoryServer.promote(promotionConfig) } } } } <file_sep>/collector_build/.mpp/.svn/pristine/95/959e46e66eede82520ba0401a6db715f540a3a76.svn-base #!/bin/bash source `readlink -f ${BASH_SOURCE[0]} | xargs dirname`/frontend || exit 1 init_build_environment $@ build <file_sep>/app_jenkins/sync.sh #!/bin/bash SRC_DIR='/home/viyou/github/packer_study/ci/app_jenkins/' cp $SRC_DIR/*.pem . for file in credentials.groovy executors.groovy kubernetes.groovy labels.groovy library.groovy plugins.txt Dockerfile; do cp $SRC_DIR/$file . done <file_sep>/vars/autoSubmit.groovy #! usr/bin/env groovy def call (Map params) { container("${params.containerName}") { sshagent(credentials: [params.gerritCredentialsId]) { sh """ source /etc/profile 2>/dev/null .mpp/run gerrit review \ --submit ${GERRIT_CHANGE_NUMBER},${GERRIT_PATCHSET_NUMBER} """ } } }<file_sep>/vars/buildComponent.groovy #!/usr/bin/env groovy /** * Function that defines global properties and launches proper pipeline based on job's name. * Properties can be overwritten by end users - for more information refer to README.md file */ def call(Map config) { def mandatoryKeys = ['imageName'] def gerritCommentRegex = ".*(retrigger-component-upgrade|retrigger-release-upgrade|retrigger-scratch-installation).*" Map defaultConfig = [ // Mandatory parameters that need to be provided by component imageName: "", // Optional parameters that can be provided by component buildModulePath: ".", testModulePath: "", junitTestReportPaths: '**/target/surefire-reports/TEST-*.xml', releaseProperties: "", scratchProperties: "", feToolsVersion: "", gitLfsFetchCommand: "git lfs fetch --all", gerritTriggerFilePaths: [], mppDebug: "", publishNPMRepo: "netact-npm-candidates", publishRepo: "netact-generic-candidates", releaseNPMRepo: "netact-npm-releases", releaseRepo: "netact-generic-releases", publishPattern: "", autoPromoteArtifacts: "false", publishSnapshots: "false", stagePublishArtifacts: "false", stagePublishNPM: "false", stageCreateTag: "true", resourceRequestMemory: "2000Mi", skipComponentUpgradeIfNoChange: "false", // Parameters maintained by NetAct CI team artifactoryCredentialsId: 'netact-artifactory', gerritCredentialsId: 'netact-gerrit', gerritSSHUser: 'ca_netact_jenkins', gerritBranch: "${env.GERRIT_BRANCH}", gerritBuildVerifyVote: "true", jobTimeout: 960, // 16 hours jobBuildHistory: '30', jobArtifactsDaysToKeep: '2', jobBuildHistoryCount: '200', patchsetRevision: "${env.GERRIT_PATCHSET_REVISION}", npmArtifactoryRegistry: "${env.ARTIFACTORY_HTTPS_URL}/api/npm", imageRepoPrefix: "netact-docker-releases", imageRepoDomain: "${env.ARTIFACTORY_FQDN}", imageTag: "latest", containerName: 'build-image', feToolsRepoPath: "netact-generic-releases/CI/fe_tools", stageGerritAutoSubmit: "true", stageFunctionalTests: "true", stageComponentUpgrade: "true", stageReleaseUpgrade: "false", stageScratchInstallation: "false", stageInterfacePromotion: "false", gitLfsPort: 8282, gitLfsHostname: "esisoj70.emea.nsn-net.net", buildNumber: Calendar.getInstance().format('yyyyMMddHHmmssSSS'), backendCredentialsId: "netact-backend", changedSinceReview: "false" ] // Merge and print config Map mergedConfig = defaultConfig + config echo "job config is ${mergedConfig}" // Check whether some mandatory properties are missing def missingKeys = [] for (key in mandatoryKeys) { if (mergedConfig.get(key) == "") { missingKeys << key } } if (missingKeys) { currentBuild.result = 'ABORTED' error("Following variables were not defined in global configuration: ${missingKeys.join(",")}") } if (!env.GERRIT_EVENT_TYPE) { currentBuild.result = 'ABORTED' error("Job does not support build directly") } // Define default file paths for gerrit trigger if not defined by user if (!mergedConfig.gerritTriggerFilePaths) { mergedConfig.gerritTriggerFilePaths << [ compareType: 'ANT', pattern: "${mergedConfig.buildModulePath}/**" ] if (mergedConfig.testModulePath) { mergedConfig.gerritTriggerFilePaths << [ compareType: 'ANT', pattern: "${mergedConfig.testModulePath}/**" ] } if (mergedConfig.buildModulePath == '.' || mergedConfig.testModulePath == '.') { mergedConfig.gerritTriggerFilePaths = [] } } if (env.GERRIT_EVENT_TYPE == 'change-merged' || env.GERRIT_EVENT_COMMENT_TEXT =~ /${gerritCommentRegex}/) { buildComponentBranch(mergedConfig) } else { buildComponentCodeReview(mergedConfig) } } <file_sep>/app_jenkins/Dockerfile FROM jenkins/jenkins # keys COPY root_host.pem /tmp/root_host.pem COPY viyou_gitlab.pem /tmp/viyou_gitlab.pem COPY viyou_gitlab.pem /tmp/id_rsa COPY gerrit.pem /tmp/gerrit.pem COPY config /tmp/config # plugins COPY plugins.txt /usr/share/jenkins/ref/ RUN /usr/local/bin/install-plugins.sh $(cat /usr/share/jenkins/ref/plugins.txt | tr '\n' ' ') # initialization script COPY executors.groovy /usr/share/jenkins/ref/init.groovy.d/executors.groovy COPY agent.groovy /usr/share/jenkins/ref/init.groovy.d/agent.groovy COPY labels.groovy /usr/share/jenkins/ref/init.groovy.d/labels.groovy COPY credentials.groovy /usr/share/jenkins/ref/init.groovy.d/credentials.groovy COPY jobs.groovy /usr/share/jenkins/ref/init.groovy.d/jobs.groovy COPY views.groovy /usr/share/jenkins/ref/init.groovy.d/views.groovy COPY ssh.groovy /usr/share/jenkins/ref/init.groovy.d/ssh.groovy COPY library.groovy /usr/share/jenkins/ref/init.groovy.d/library.groovy COPY kubernetes.groovy /usr/share/jenkins/ref/init.groovy.d/kubernetes.groovy <file_sep>/job_dsl/generate_upload_artifacts.gvy def executeShell = '''#!/bin/bash -ex mv ARTIFACT $ARTIFACT curl -u$GLOBAL_ARTIFACTORY_USERNAME:$GLOBAL_ARTIFACTORY_TOKEN -X PUT -T $ARTIFACT "$GLOBAL_ARTIFACTORY_SERVICENAME:$GLOBAL_ARTIFACTORY_PORT/artifactory/$ARTIFACTORY_PATH" -k --ftp-create-dirs ''' def init_script = freeStyleJob("upload_artifacts") { parameters { fileParam("ARTIFACT", "artifact to upload") stringParam("ARTIFACTORY_PATH", "netact-fast_pass-local/fp-tvnf/to_build/", "path to upload to") } wrappers { preBuildCleanup() timeout { noActivity(300) failBuild() writeDescription('Build failed due to timeout') } credentialsBinding { usernamePassword('GLOBAL_ARTIFACTORY_USERNAME', 'GLOBAL_ARTIFACTORY_TOKEN', '<PASSWORD>') } } steps { shell(executeShell) } }
1fcbbf1da4ff334287bdb8144d561ac4a2fa0358
[ "Shell", "Groovy", "Markdown", "Dockerfile", "YAML", "Java Properties", "Python" ]
56
Shell
VictorYou/jenkins_study
180cf12a2ab77a84cc54c862e0583d4819434aa7
b0cb623ae80d4f00fc3cdce23a13f29aa1b4c8c6
refs/heads/master
<file_sep>package edu.sjsu.cmpe275Project.service; import edu.sjsu.cmpe275Project.dao.ItinaryDAO; import edu.sjsu.cmpe275Project.models.Guest; import edu.sjsu.cmpe275Project.models.Itinary; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.sql.Date; /** * Created by dexterwei on 11/26/15. */ @Transactional @Service("itinaryservice") public class ItinaryServiceImpl implements ItinaryService{ @Autowired private SessionFactory sessionFactory; @Autowired private ItinaryDAO itidao; private Session getSession() { return sessionFactory.getCurrentSession(); } @Override public Itinary createItinary(long guestId, double discont, double payment, Date payDate) { Itinary iti = new Itinary(); iti.setGuest((Guest) getSession().get(Guest.class, guestId)); iti.setDiscount(discont); iti.setPayment(payment); iti.setPaymentDate(payDate); itidao.create(iti); return iti; } @Override public Itinary createItinary(Itinary i) { Itinary iti = new Itinary(); System.out.println("gestID is "+ i.getGuest().getId()); iti.setGuest((Guest) getSession().get(Guest.class, i.getGuest().getId())); iti.setDiscount(i.getDiscount()); iti.setPayment(i.getPayment()); iti.setPaymentDate(i.getPaymentDate()); itidao.create(iti); return iti; } @Override public Itinary findItinary(long itiId) { return itidao.findById(itiId); } // @Override // public Itinary addOccToItinary(long itiId, Occupancy newOcc) { // Itinary iti = findItinary(itiId); // iti.getOccupancies().add(newOcc); // itidao.update(itiId,iti); // return iti; // } } <file_sep>package edu.sjsu.cmpe275Project.dao; import edu.sjsu.cmpe275Project.models.Occupancy; /** * Created by dexterwei on 11/25/15. */ public interface OccupancyDAO { Occupancy create(Occupancy occ); Occupancy update(Long id, Occupancy occ); void delete(Long id); Occupancy findById(Long id); } <file_sep>package edu.sjsu.cmpe275Project.dao; import edu.sjsu.cmpe275Project.models.Guest; /** * Created by emy on 11/18/15. */ public interface guestDAO { Guest create(Guest guest); Guest update(Long id, Guest guest); void delete(Long id); Guest findById(Long id); } <file_sep>package edu.sjsu.cmpe275Project.dao; import edu.sjsu.cmpe275Project.models.Itinary; import edu.sjsu.cmpe275Project.models.Occupancy; /** * Created by dexterwei on 11/25/15. */ public interface ItinaryDAO { Itinary create(Itinary occ); Itinary update(Long id, Itinary occ); void delete(Long id); Itinary findById(Long id); } <file_sep>-- to test, execute these insertions INSERT INTO testing.room(roomId,price,roomNumber,properties,type) VALUES(1,100,"101","NSMK","K"); INSERT INTO testing.room(roomId,price,roomNumber,properties,type) VALUES(2,120,"102","SMK","K"); INSERT INTO testing.room(roomId,price,roomNumber,properties,type) VALUES(3,100,"103","NSMK","Q"); INSERT INTO testing.Occupancy(OCCUPANCYID,checkinDate,checkOutDate,roomNumber) VALUES(4,"2015-11-24","2015-11-25",1); INSERT INTO testing.Occupancy(OCCUPANCYID,checkinDate,checkOutDate,roomNumber) VALUES(5,"2015-11-26","2015-11-27",2); INSERT INTO testing.Occupancy(OCCUPANCYID,checkinDate,checkOutDate,roomNumber) VALUES(6,"2015-11-26","2015-11-27",1); <file_sep>package edu.sjsu.cmpe275Project.models; import javax.persistence.*; import java.io.Serializable; import java.sql.Date; /** * Created by dexterwei on 11/18/15. */ @Entity @Table(name="Occupancy") public class Occupancy implements Serializable { private static final long serialVersionUID = 15L; public Occupancy() { } @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name="OCCUPANCYID", nullable = false) private long occupancyID; @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="itinaryID") private Itinary itinary; @ManyToOne @JoinColumn(name = "roomNumber", referencedColumnName = "roomID") private Room room; private int NunOfPerson; // @Column(name="status", columnDefinition = "default 0") private int status; // 0:reserved 1:cheched-in 2:checked-out private Date checkInDate; private Date checkOutDate; public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public long getOccupancyID() { return occupancyID; } public Itinary getItinary() { return itinary; } public void setItinary(Itinary itinary) { this.itinary = itinary; } public Room getRoom() { return room; } public void setRoom(Room room) { this.room = room; } public int getNunOfPerson() { return NunOfPerson; } public void setNunOfPerson(int nunOfPerson) { NunOfPerson = nunOfPerson; } public Date getCheckInDate() { return checkInDate; } public void setCheckInDate(Date checkInDate) { this.checkInDate = checkInDate; } public Date getCheckOutDate() { return checkOutDate; } public void setCheckOutDate(Date checkOutDate) { this.checkOutDate = checkOutDate; } } <file_sep>package edu.sjsu.cmpe275Project.controller; import edu.sjsu.cmpe275Project.models.Itinary; import edu.sjsu.cmpe275Project.models.Occupancy; import edu.sjsu.cmpe275Project.service.ItinaryService; import edu.sjsu.cmpe275Project.service.occupancyService; import edu.sjsu.cmpe275Project.service.roomService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import java.sql.Date; /** * Created by dexterwei on 11/29/15. */ @Controller public class ServiceController { @Autowired private roomService roomservice; @Autowired private occupancyService occupancyservice; @Autowired private ItinaryService itinaryservice; //try this http://localhost:8080/room/search?checkinDate=2015-11-24&checkoutDate=2015-11-25&roomType=K&roomProp=SMK @RequestMapping(value = "/guest/search", method = RequestMethod.POST) public @ResponseBody ResponseEntity<?> SearchRoom( @RequestBody Occupancy occupancy ){ System.out.println("Get room type is "+ occupancy.getRoom()); return new ResponseEntity<>(occupancyservice.searchAvlRoom(occupancy), HttpStatus.OK); } //try this http://localhost:8080/room/report?date=2015-11-24 @RequestMapping(value = "/staff/report", method = RequestMethod.GET) public @ResponseBody ResponseEntity<?> SearchRoom( @RequestParam(value = "date", required = true) Date date ){ return new ResponseEntity<>(occupancyservice.RoomStatus(date), HttpStatus.OK); } //create a guest first //then try http://localhost:8080/staff/itinary?guestId=1&discount=0&payment=0&paymentDate=2015-11-27 @RequestMapping(value = "/staff/itinary", method = RequestMethod.POST) public @ResponseBody ResponseEntity<?> createItinary( @RequestBody Itinary iti ){ //return new ResponseEntity<>(itinaryservice.createItinary(guestId,discont,payment,payDate), HttpStatus.OK); return new ResponseEntity<>(itinaryservice.createItinary(iti), HttpStatus.OK); } @RequestMapping(value = "/staff/itinary/{id}", method = RequestMethod.GET) public @ResponseBody ResponseEntity<?> getItinary(@PathVariable("id") long id){ return new ResponseEntity<>(itinaryservice.findItinary(id), HttpStatus.OK); } //create a guest and an itinary first //then try http://localhost:8080/staff/occupancy?guestId=1&itinaryId=1&roomId=3&checkinDate=2015-11-22&checkoutDate=2015-11-24 @RequestMapping(value = "/staff/occupancy", method = RequestMethod.POST) public @ResponseBody ResponseEntity<?> createOcc( @RequestBody Occupancy occ ){ //return new ResponseEntity<>(occupancyservice.createOccupancy(guestId,itiId,roomId,num, inDate,outDate), HttpStatus.OK);} return new ResponseEntity<>(occupancyservice.createOccupancy(occ), HttpStatus.OK); } @RequestMapping(value = "/staff/occupancy/{id}", method = RequestMethod.GET) public @ResponseBody ResponseEntity<?> getOcc(@PathVariable("id") long id){ return new ResponseEntity<>(occupancyservice.findItinary(id), HttpStatus.OK); } } <file_sep>package edu.sjsu.cmpe275Project.dao; import edu.sjsu.cmpe275Project.models.Room; /** * Created by emy on 11/19/15. */ public interface roomDAO { Room create(Room room); Room update(Long id, Room room); void delete(Long id); Room findById(Long id); } <file_sep># cmpe275 Term Project <h2>Synopsis</h2> This project is an application for a Hotel Management system. Staffs include a service agent and administrator. A guest can search for room availability on the app or can be done on the fly. A service agent confirms the guest upon arrival date. Both service agent and administrator have similar roles except admin can room provisioning. <h3>Tools:</h3> <ul><li>Java</li> <li>Springboot framework</li> <li>maven</li> <li>html</li> <li>bootstrap</li></ul> <h3>Motivation</h3> <h3>Installation</h3> <p>Download project. Open up terminal and run the commands in the package folder:</p> mvn clean mvn compile mvn spring-boot:run Open up browser and enter http://localhost:8080/person to display login page for now. <h3>API Reference</h3> <h3>Test</h3> <h3>Contributors:</h3> <ol><li><NAME></li> <li><NAME></li> <li><NAME></li> <li><NAME></li> </ol> <file_sep>package edu.sjsu.cmpe275Project.models; import javax.persistence.*; import java.io.Serializable; import java.sql.Date; /** * Created by dexterwei on 11/18/15. */ @Entity @Table(name="Itinary") public class Itinary implements Serializable{ private static final long serialVersionUID = 20L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name="ITINARYID", nullable = false) private long itinaryID; @OneToOne(cascade = CascadeType.ALL) @JoinColumn(name="guestId", nullable = false) private Guest guest; // @OneToMany(cascade = CascadeType.ALL,fetch = FetchType.EAGER) // private Collection<Occupancy> occupancies = new ArrayList<Occupancy>(); private double payment; private double discount; private Date paymentDate; public long getItinaryID() { return itinaryID; } public void setItinaryID(long itinaryID) { this.itinaryID = itinaryID; } public Guest getGuest() { return guest; } public void setGuest(Guest guest) { this.guest = guest; } // public Collection<Occupancy> getOccupancies() { // return occupancies; // } // // public void setOccupancies(Collection<Occupancy> occupancies) { // this.occupancies = occupancies; // } public double getPayment() { return payment; } public void setPayment(double payment) { this.payment = payment; } public double getDiscount() { return discount; } public void setDiscount(double discount) { this.discount = discount; } public Date getPaymentDate() { return paymentDate; } public void setPaymentDate(Date paymentDate) { this.paymentDate = paymentDate; } } <file_sep>package edu.sjsu.cmpe275Project.service; import edu.sjsu.cmpe275Project.dao.roomDAO; import edu.sjsu.cmpe275Project.models.Occupancy; import edu.sjsu.cmpe275Project.models.Room; import java.util.Collection; import java.sql.Date; /** * Created by dexterwei on 11/26/15. */ public interface occupancyService { Collection<Room> searchAvlRoom(Date checkinD, Date checkoutD, String roomType, String roomProp); Occupancy createOccupancy( long guestId, long itiId, long roomId, int numPerson, Date checkInDate, Date checkOutDate ); Occupancy findItinary( long occId ); } <file_sep>package edu.sjsu.cmpe275Project.controller; import edu.sjsu.cmpe275Project.models.Room; import edu.sjsu.cmpe275Project.service.occupancyService; import edu.sjsu.cmpe275Project.service.roomService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.sql.Date; import java.util.Collection; /** * Created by yingzhu on 11/23/15. */ @Controller public class roomControllers { // @Autowired // private roomService roomservice; // // @RequestMapping(value="/room", method = RequestMethod.POST) // @ResponseBody // public Room addRoom(@RequestBody Room room){ // Room room1 = roomservice.create(room); // return room1; // } // // @RequestMapping(value="/testroom") // //@ResponseBody // public void test(){ // System.out.print("POST is allowed here"); // } // // // @RequestMapping(value="/room/update/{id}", method = RequestMethod.POST) // @ResponseBody // public Room updateRoom(@Valid @PathVariable("id") long id, @RequestBody Room room){ // Room room1 = roomservice.findById(id); // if(room1!=null) { // room.setId(id); // roomservice.update(id, room); // } // room1 = roomservice.findById(id); // return room1; // } // // @RequestMapping(value="/room/{id}", method = RequestMethod.GET) // @ResponseBody // public Room getRoom(@Valid @PathVariable("id") long id){ // Room room1 = roomservice.findById(id); // return room1; // } // // // @RequestMapping(value="/room/{id}", method = RequestMethod.DELETE) // @ResponseBody // public void deleteRoom(@Valid @PathVariable("id") long id){ // roomservice.delete(id); // } }
b6d8f9dea3b228b5d81c5180201ce394f54a5f71
[ "Java", "Markdown", "SQL" ]
12
Java
MiniHotelManagement/miniHotel
67d0736615a670480334aecefd16181dc2f993ae
5358253ecc2efc2c270380ceb7c8f63658ae1b4a
refs/heads/master
<repo_name>Wildhoney/Recipes.React<file_sep>/gulpfile.js (function() { var gulp = require('gulp'), jshint = require('gulp-jshint'), react = require('gulp-react'), clean = require('gulp-clean'), filename = 'Recipes.jsx', path = 'example/js/app/' + filename; gulp.task('jsx', function gulpJSX() { return gulp.src(path) .pipe(react()) .pipe(gulp.dest('tmp')); }); gulp.task('hint', ['jsx'], function gulpHint() { return gulp.src('tmp/' + filename) .pipe(jshint('.jshintrc')) .pipe(jshint.reporter('default')); }); gulp.task('clean', ['hint'], function gulpClean() { return gulp.src('tmp') .pipe(clean({force: true})); }); gulp.task('test', ['jsx', 'hint', 'clean']); gulp.task('default', ['test']); })();<file_sep>/example/js/app/Recipes.jsx /** @jsx React.DOM */ (function($react, $jquery, RecipesInterface) { "use strict"; /** * @property recipes * @type {window.RecipesInterface} */ var recipes = new RecipesInterface(); /** * @property Recipes * @type {Function} */ var Recipes = $react.createClass({ /** * @method getInitialState * @returns {Object} */ getInitialState: function getInitialState() { return { collection: [] }; }, /** * @method componentDidMount * @return {void} */ componentDidMount: function componentDidMount() { this.loadRecipes(); }, /** * @method recipeDidAdd * @param name {String} * @param description {String} * @return {void} */ recipeDidAdd: function recipeDidAdd(name, description) { console.log(this); this.loadRecipes(); }, /** * @method loadRecipes * @return {void} */ loadRecipes: function loadRecipes() { recipes.getRecipes().then(function then(response) { // Modify the state of the React component to include the collection of recipes. this.setState({ collection: collection._items }); }); }, /** * @method render * @return {XML} */ render: function() { return ( <div> <h1>Recipes</h1> <RecipeList collection={this.state.collection} /> <RecipeForm success={this.recipeDidAdd} /> </div> ); } }); /** * @property RecipeList * @type {Function} */ var RecipeList = $react.createClass({ /** * @method render * @return {XML} */ render: function render() { /** * @property recipeElements * @type {Array} */ var recipeElements = this.props.collection.map(function map(recipe) { recipe.text = ''; return ( <li> <Recipe name={recipe.name} ingredients={recipe.ingredients}> {recipe.text} </Recipe> </li> ); }); return ( <section> <h2>List of Recipes ({recipeElements.length})</h2> { this.props.collection.length ? <ul>{recipeElements}</ul> : <div>Loading...</div> } </section> ); } }); /** * @property Recipe * @type {Function} */ var Recipe = $react.createClass({ /** * @method render * @return {XML} */ render: function render() { return ( <section> <h3>{this.props.name} ({this.props.ingredients.length} ingredients)</h3> {this.props.children} </section> ); } }); /** * @property RecipeForm * @type {Function} */ var RecipeForm = $react.createClass({ /** * @method addRecipe * @param event {Object} * @return {Boolean} */ addRecipe: function addRecipe(event) { event.preventDefault(); // Associate the DOM references to local variables. var nameElement = this.refs.name.getDOMNode(), descriptionElement = this.refs.description.getDOMNode(); // Determine the values of the name and description. var name = nameElement.value.trim(), description = descriptionElement.value.trim(); if (!name || !description) { return false; } // Empty the values from the form fields. nameElement.value = ''; descriptionElement.value = ''; recipes.addRecipe(name, description, []).then(function then(response) { // Invoke the method on the parent so the recipe list can be updated. this.props.success(); }.bind(this)); }, /** * @method render * @return {XML} */ render: function render() { return ( <section> <h2>Submit Recipe</h2> <form onSubmit={this.addRecipe}> <input type="text" placeholder="Recipe name" ref="name" /> <textarea ref="description"></textarea> <input type="submit" value="Add Recipe" /> </form> </section> ); } }); $react.renderComponent( <Recipes url="http://learn-api.herokuapp.com/recipes" />, document.querySelector('recipes') ); })(window.React, window.jQuery, window.RecipesInterface);
7dae3a4c122d33c7a4ae7bd6f1e42542a12c9f14
[ "JavaScript" ]
2
JavaScript
Wildhoney/Recipes.React
a6a96d841fc991fa37d1825d2aca763fc48482a1
19d8dda31406e6c9f004dd31b2b929a93559e225
refs/heads/master
<file_sep># reservation-application A basic back-end application that allows the application owner to reserve it sproduct for the client in a specefic datetime. <file_sep>package br.com.reservation.court.controller; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import br.com.reservation.court.domain.ReservationDomain; import br.com.reservation.court.domain.ReservationRequestDomain; import br.com.reservation.court.service.ReservationService; @RestController public class ReservationController { @Autowired private ReservationService reservationService; @PostMapping(value="/makeReservation") public ResponseEntity<?> makeReservation (@RequestBody ReservationRequestDomain reservationRequest){ ReservationDomain reservation = new ReservationDomain(); try { reservation = reservationService.makeReservation(reservationRequest); }catch(Exception e) { return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST); } return new ResponseEntity<>(reservation, HttpStatus.OK); } @GetMapping(value="/retrieveReservations/{courtID}/{date}") public ResponseEntity<?> retrieveReservations (@PathVariable String courtID, @PathVariable String date){ List<ReservationDomain> reservationsOnCourtInTheDay = new ArrayList<ReservationDomain>(); try { reservationsOnCourtInTheDay = reservationService.retrieveReservations(courtID, date); }catch(Exception e) { return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST); } return new ResponseEntity<>(reservationsOnCourtInTheDay, HttpStatus.OK); } } <file_sep>package br.com.reservation.court.controller; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import br.com.reservation.court.domain.PlayerDomain; import br.com.reservation.court.domain.PlayerRequestDomain; import br.com.reservation.court.service.PlayerService; @RestController public class PlayerController { @Autowired private PlayerService playerService; @PostMapping(value="/registerPlayer") public ResponseEntity<?> registerPlayer(@Valid @RequestBody PlayerRequestDomain playerRequest) { PlayerDomain player = new PlayerDomain(); try { player = playerService.registerPlayer(playerRequest); }catch (Exception e) { return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST); } return new ResponseEntity<>(player, HttpStatus.OK); } } <file_sep>package br.com.reservation.court.domain; import java.util.ArrayList; import java.util.List; import javax.validation.constraints.NotNull; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; @Document(collection = "CourtCollection") public class CourtDomain { @Id private String courtID; @NotNull private String courtName; @NotNull private int courtNumber; private String imageUrl; private String sport; private List<ReservationDomain> reservations = new ArrayList<ReservationDomain>(); public String getCourtID() { return courtID; } public String getCourtName() { return courtName; } public void setCourtName(String courtName) { this.courtName = courtName; } public int getCourtNumber() { return courtNumber; } public void setCourtNumber(int courtNumber) { this.courtNumber = courtNumber; } public List<ReservationDomain> getReservations() { return reservations; } public String getImageUrl() { return imageUrl; } public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } public String getSport() { return sport; } public void setSport(String sport) { this.sport = sport; } }<file_sep>package br.com.reservation.court; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class CourtApplicationTests { @Test void contextLoads() { } } <file_sep>package br.com.reservation.court.domain; public class CourtRequestDomain { private String courtName; private int courtNumber; public String getCourtName() { return courtName; } public void setCourtName(String courtName) { this.courtName = courtName; } public int getCourtNumber() { return courtNumber; } public void setCourtNumber(int courtNumber) { this.courtNumber = courtNumber; } }
2eb73ab2201734e3140bae9557c3773d95e9320c
[ "Java", "Markdown" ]
6
Java
renansao/reservation-application
281fe9f3d565c9f92a497f6da1361f5f5679f263
1221906338c9cf1aa3782c6ed269e3a17dc5a48c
refs/heads/master
<repo_name>jisanjung/data-handler-app<file_sep>/README.md # Data Handling App This app takes data from a user and inserts into storage, and the data can be retrieved. This is intended for practice.<file_sep>/app.js var data = []; var counter = 0; var firstName = document.getElementById("first"); var lastName = document.getElementById("last"); var age = document.getElementById("age"); var email = document.getElementById("email"); var insertButton = document.getElementById("insert-btn"); var lookupButton = document.getElementById("lookup-btn"); var Person = function(first, last, age, email, id) { this.first = first; this.last = last; this.age = age; this.email = email; this.id = id; }; var addToData = function() { var id = document.querySelector(".id-number"); var success = document.getElementById("insert-success"); var incomplete = document.getElementById("incomplete"); if (firstName.value === "" || lastName.value === "" || age.value === "" || email.value === "") { incomplete.classList.remove("display-none"); } else { counter++; var user = new Person(firstName.value, lastName.value, age.value, email.value, counter); data.push(user); incomplete.classList.add("display-none"); success.classList.remove("display-none"); id.textContent = counter; } var deserializedObject = JSON.parse(localStorage.getItem(firstName.value)); return deserializedObject; }; insertButton.addEventListener("click", addToData); lookupButton.addEventListener("click", function() { var lookupID = document.getElementById("lookup-id"); var showID = document.querySelector(".show-id"); var lookupResults = document.querySelector(".lookup-results"); var collectionItems = document.getElementsByClassName("collection-item"); var noMatch = document.getElementById("no-match"); for (var i = 0; i < data.length; i++) { if (data[lookupID.value - 1] == data[i]) { showID.textContent = lookupID.value; lookupResults.classList.remove("display-none"); noMatch.classList.add("display-none"); collectionItems[0].textContent = data[lookupID.value - 1].first; collectionItems[1].textContent = data[lookupID.value - 1].last; collectionItems[2].textContent = data[lookupID.value - 1].age; collectionItems[3].textContent = data[lookupID.value - 1].email; } else { var collection = document.querySelector(".collection"); collection.classList.add("display-none"); noMatch.classList.remove("display-none"); } } });
6d5b17b6fe231843e886d13d9bb47158237b82c9
[ "Markdown", "JavaScript" ]
2
Markdown
jisanjung/data-handler-app
afc8fc7f671771c016f2dcc447cdb4aeece292ec
0583115a788999ae75e12f1841b04e3490bc58c4