text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package paq_inventario;

import componentes.AsientoContable;
import framework.componentes.AutoCompletar;
import framework.componentes.Barra;
import framework.componentes.Boton;
import framework.componentes.Calendario;
import framework.componentes.Combo;
import framework.componentes.Etiqueta;
import framework.componentes.Grupo;
import framework.componentes.Link;
import framework.componentes.MenuPanel;
import framework.componentes.PanelTabla;
import framework.componentes.Tabla;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.event.ActionEvent;
import javax.faces.event.AjaxBehaviorEvent;
import org.primefaces.event.SelectEvent;
import servicios.inventario.ServicioInventario;
import servicios.inventario.ServicioProducto;
import sistema.aplicacion.Pantalla;

/**
 *
 * @author djacome
 */
public class pre_inventario extends Pantalla {

    private final MenuPanel mep_menu = new MenuPanel();
    private final Calendario cal_fecha_inicio = new Calendario();
    private final Calendario cal_fecha_fin = new Calendario();
    private Tabla tab_tabla;
    private final Combo com_bodega = new Combo();
    private AsientoContable asc_asiento = new AsientoContable();

    private Tabla tab_tabla2;

    @EJB
    private final ServicioInventario ser_inventario = (ServicioInventario) utilitario.instanciarEJB(ServicioInventario.class);
    @EJB
    private final ServicioProducto ser_producto = (ServicioProducto) utilitario.instanciarEJB(ServicioProducto.class);
    private AutoCompletar aut_productos;
    private String ide_incci_busca = null;

    public pre_inventario() {
        bar_botones.quitarBotonsNavegacion();
        bar_botones.quitarBotonEliminar();

        com_bodega.setId("com_bodega");
        com_bodega.setCombo("select ide_inbod,nombre_inbod from inv_bodega where nivel_inbod='HIJO' and ide_empr=" + utilitario.getVariable("ide_empr"));
        com_bodega.eliminarVacio();
        com_bodega.setMetodo("actualizarMovimientos");
        bar_botones.agregarComponente(new Etiqueta("BODEGA :"));
        bar_botones.agregarComponente(com_bodega);
        bar_botones.agregarSeparador();
        bar_botones.agregarComponente(new Etiqueta("FECHA DESDE :"));
        cal_fecha_inicio.setValue(utilitario.getFecha(utilitario.getAnio(utilitario.getFechaActual()) + "-01-01"));
        bar_botones.agregarComponente(cal_fecha_inicio);
        bar_botones.agregarComponente(new Etiqueta("FECHA HASTA :"));
        cal_fecha_fin.setFechaActual();
        bar_botones.agregarComponente(cal_fecha_fin);
        Boton bot_consultar = new Boton();
        bot_consultar.setMetodo("actualizarMovimientos");
        bot_consultar.setIcon("ui-icon-search");

        bar_botones.agregarBoton(bot_consultar);

        mep_menu.setMenuPanel("INVENTARIO", "22%");
        mep_menu.agregarItem("Lista de Comprobantes", "dibujarComprobantes", "ui-icon-note");//1
        mep_menu.agregarItem("Generar Asiento Contable", "dibujarComprobantesNoConta", "ui-icon-notice");//2
        mep_menu.agregarItem("Kardex", "dibujarKardex", "ui-icon-note");//3
        mep_menu.agregarItem("Saldos Productos", "dibujarSaldos", "ui-icon-note");//4

        agregarComponente(mep_menu);
        asc_asiento.setId("asc_asiento");
        asc_asiento.getBot_aceptar().setMetodo("guardar");
        agregarComponente(asc_asiento);

    }

    public void dibujarComprobantes() {
        Grupo gru_grupo = new Grupo();
        if (isBodegaSeleccionado()) {
            tab_tabla = new Tabla();
            tab_tabla.setNumeroTabla(6);
            tab_tabla.setId("tab_tabla");
            tab_tabla.setSql(ser_inventario.getSqlComprobantesInventario(String.valueOf(com_bodega.getValue()), cal_fecha_inicio.getFecha(), cal_fecha_fin.getFecha()));
            tab_tabla.getColumna("INGRESO").setEstilo("font-size: 13px;font-weight: bold");
            tab_tabla.getColumna("INGRESO").alinearDerecha();
            tab_tabla.getColumna("EGRESO").setEstilo("font-size: 13px;font-weight: bold");
            tab_tabla.getColumna("EGRESO").alinearDerecha();
            tab_tabla.setCampoPrimaria("cod");
            tab_tabla.getColumna("cod").setVisible(false);
            tab_tabla.getColumna("ide_incci").setNombreVisual("NUM. COMP.");
            tab_tabla.getColumna("ide_incci").setLink();
            tab_tabla.getColumna("ide_incci").setMetodoChange("cargarComprobante");
            tab_tabla.getColumna("ide_incci").alinearCentro();
            tab_tabla.getColumna("ide_inepi").setVisible(false);
            tab_tabla.getColumna("ide_geper").setVisible(false);
            tab_tabla.getColumna("fecha_trans_incci").setNombreVisual("FECHA");
            tab_tabla.getColumna("ide_cnccc").setFiltroContenido();
            tab_tabla.getColumna("ide_cnccc").setNombreVisual("N. ASIENTO.");
            tab_tabla.getColumna("IDE_CNCCC").setLink();
            tab_tabla.getColumna("IDE_CNCCC").setMetodoChange("abrirAsiento");
            tab_tabla.getColumna("IDE_CNCCC").alinearCentro();
            tab_tabla.getColumna("numero_incci").setNombreVisual("SECUENCIAL");
            tab_tabla.getColumna("numero_incci").setFiltroContenido();
            tab_tabla.getColumna("nombre_intti").setNombreVisual("TIPO TRANSACCIÓN");
            tab_tabla.getColumna("nom_geper").setNombreVisual("BENEFICIARIO");
            tab_tabla.getColumna("identificac_geper").setNombreVisual("IDENTIFICACIÓN");
            tab_tabla.setValueExpression("rowStyleClass", "fila.campos[1]  eq '0' ? 'text-red' : fila.campos[4] eq null  ? 'text-green' : null"); //poner variable anulado 0
            tab_tabla.setLectura(true);
            tab_tabla.setRows(25);
            tab_tabla.dibujar();
            PanelTabla pat_panel = new PanelTabla();
            pat_panel.setPanelTabla(tab_tabla);
            gru_grupo.getChildren().add(pat_panel);

            if (tab_tabla.isEmpty()) {
                tab_tabla.setEmptyMessage("No existen Comprobantes de Inventario");
            }
        }
        mep_menu.dibujar(1, "LISTADO DE COMPROBANTES DE INVENTARIO", gru_grupo);
    }

    public void dibujarComprobantesNoConta() {
        Grupo gru_grupo = new Grupo();
        if (isBodegaSeleccionado()) {
            Barra bar_menu = new Barra();
            bar_menu.setId("bar_menu");
            bar_menu.limpiar();
            Boton bot_asi = new Boton();
            bot_asi.setValue("Generar Asiento Contable");
            bot_asi.setMetodo("abrirGeneraAsiento");
            bar_menu.agregarComponente(bot_asi);
            bar_menu.agregarSeparador();

            tab_tabla = new Tabla();
            tab_tabla.setNumeroTabla(6);
            tab_tabla.setId("tab_tabla");
            tab_tabla.setSql(ser_inventario.getSqlComprobantesInventarioNoConta(String.valueOf(com_bodega.getValue()), cal_fecha_inicio.getFecha(), cal_fecha_fin.getFecha()));
            tab_tabla.getColumna("INGRESO").setEstilo("font-size: 13px;font-weight: bold");
            tab_tabla.getColumna("INGRESO").alinearDerecha();
            tab_tabla.getColumna("EGRESO").setEstilo("font-size: 13px;font-weight: bold");
            tab_tabla.getColumna("EGRESO").alinearDerecha();
            tab_tabla.setCampoPrimaria("ide_incci");
            tab_tabla.getColumna("ide_incci").setNombreVisual("NUM. COMP.");
            tab_tabla.getColumna("ide_inepi").setVisible(false);
            tab_tabla.getColumna("ide_geper").setVisible(false);
            tab_tabla.getColumna("fecha_trans_incci").setNombreVisual("FECHA");
            tab_tabla.getColumna("numero_incci").setNombreVisual("SECUENCIAL");
            tab_tabla.getColumna("numero_incci").setFiltroContenido();
            tab_tabla.getColumna("nombre_intti").setNombreVisual("TIPO TRANSACCIÓN");
            tab_tabla.getColumna("nom_geper").setNombreVisual("BENEFICIARIO");
            tab_tabla.getColumna("identificac_geper").setNombreVisual("IDENTIFICACIÓN");
            tab_tabla.setLectura(true);
            tab_tabla.setRows(25);
            tab_tabla.dibujar();
            PanelTabla pat_panel = new PanelTabla();
            pat_panel.setPanelTabla(tab_tabla);
            gru_grupo.getChildren().add(bar_menu);
            gru_grupo.getChildren().add(pat_panel);

            if (tab_tabla.isEmpty()) {
                tab_tabla.setEmptyMessage("No existen Comprobantes de Inventario para Contabilizar");
            }
        }
        mep_menu.dibujar(2, "COMPROBANTES DE INVENTARIO NO CONTABILIZADOS", gru_grupo);
    }

    public void dibujarKardex() {
        Grupo gru_grupo = new Grupo();

        aut_productos = new AutoCompletar();
        aut_productos.setId("aut_productos");
        aut_productos.setAutoCompletar(ser_producto.getSqlProductosKardexCombo());
        aut_productos.setSize(75);
        aut_productos.setAutocompletarContenido(); // no startWith para la busqueda
        Barra bar_menu = new Barra();
        bar_menu.setId("bar_menu");
        bar_menu.limpiar();
        bar_menu.agregarComponente(new Etiqueta("PRODUCTO :"));
        bar_menu.agregarComponente(aut_productos);

        Boton bot_consultar = new Boton();
        bot_consultar.setValue("Consultar");
        bot_consultar.setMetodo("actualizarMovimientos");
        bot_consultar.setIcon("ui-icon-search");

        bar_menu.agregarComponente(bot_consultar);

        tab_tabla = new Tabla();
        tab_tabla.setNumeroTabla(-1);
        tab_tabla.setId("tab_tabla");
        tab_tabla.setSql(ser_producto.getSqlKardex("-1", cal_fecha_inicio.getFecha(), cal_fecha_fin.getFecha(), ""));
        tab_tabla.getColumna("ide_indci").setVisible(false);
        tab_tabla.getColumna("fecha_trans_incci").setNombreVisual("FECHA");
        tab_tabla.getColumna("nom_geper").setNombreVisual("CLIENTE / PROVEEDOR");
        tab_tabla.getColumna("nombre_intti").setNombreVisual("TIPO DE TRANSACCIÓN");
        tab_tabla.getColumna("CANT_INGRESO").setNombreVisual("CANT. INGRESO");
        tab_tabla.getColumna("VUNI_INGRESO").setNombreVisual("V/U INGRESO");
        tab_tabla.getColumna("VTOT_INGRESO").setNombreVisual("TOTAL INGRESO");
        tab_tabla.getColumna("CANT_EGRESO").setNombreVisual("CANT. EGRESO");
        tab_tabla.getColumna("VUNI_EGRESO").setNombreVisual("V/U EGRESO");
        tab_tabla.getColumna("VTOT_EGRESO").setNombreVisual("TOTAL EGRESO");
        tab_tabla.getColumna("CANT_SALDO").setNombreVisual("CANT. SALDO");
        tab_tabla.getColumna("VUNI_SALDO").setNombreVisual("V/U SALDO");
        tab_tabla.getColumna("VTOT_SALDO").setNombreVisual("TOTAL SALDO");

        tab_tabla.getColumna("CANT_INGRESO").alinearDerecha();
        tab_tabla.getColumna("VUNI_INGRESO").alinearDerecha();
        tab_tabla.getColumna("VTOT_INGRESO").alinearDerecha();
        tab_tabla.getColumna("CANT_EGRESO").alinearDerecha();
        tab_tabla.getColumna("VUNI_EGRESO").alinearDerecha();
        tab_tabla.getColumna("VTOT_EGRESO").alinearDerecha();
        tab_tabla.getColumna("CANT_SALDO").alinearDerecha();
        tab_tabla.getColumna("VUNI_SALDO").alinearDerecha();
        tab_tabla.getColumna("VTOT_SALDO").alinearDerecha();

        tab_tabla.getColumna("CANT_INGRESO").setLongitud(20);
        tab_tabla.getColumna("VUNI_INGRESO").setLongitud(20);
        tab_tabla.getColumna("VTOT_INGRESO").setLongitud(20);
        tab_tabla.getColumna("CANT_EGRESO").setLongitud(20);
        tab_tabla.getColumna("VUNI_EGRESO").setLongitud(20);
        tab_tabla.getColumna("VTOT_EGRESO").setLongitud(20);
        tab_tabla.getColumna("CANT_SALDO").setLongitud(20);
        tab_tabla.getColumna("VUNI_SALDO").setLongitud(20);
        tab_tabla.getColumna("VTOT_SALDO").setLongitud(20);

        tab_tabla.getColumna("CANT_SALDO").setEstilo("font-weight: bold;");
        tab_tabla.getColumna("VUNI_SALDO").setEstilo("font-weight: bold;");
        tab_tabla.getColumna("VTOT_SALDO").setEstilo("font-weight: bold;");

        tab_tabla.getColumna("nombre_intti").setFiltroContenido();
        tab_tabla.getColumna("nom_geper").setFiltroContenido();
        tab_tabla.setColumnaSuma("CANT_INGRESO,VTOT_INGRESO,CANT_EGRESO,VTOT_EGRESO,CANT_SALDO,VTOT_SALDO");
        tab_tabla.getColumna("CANT_SALDO").setSuma(false);
        tab_tabla.getColumna("VUNI_SALDO").setSuma(false);
        tab_tabla.getColumna("VTOT_SALDO").setSuma(false);
        tab_tabla.setOrdenar(false);
        tab_tabla.setLectura(true);
        tab_tabla.setScrollable(true);
        tab_tabla.setRows(25);
        tab_tabla.dibujar();
        PanelTabla pat_panel = new PanelTabla();
        pat_panel.setPanelTabla(tab_tabla);
        gru_grupo.getChildren().add(bar_menu);
        gru_grupo.getChildren().add(pat_panel);
        calculaKardex();
        mep_menu.dibujar(3, "KARDEX - PROMEDIO PONDERADO", gru_grupo);
    }

    public void dibujarComprobanteInv() {
        Grupo gru_grupo = new Grupo();
        tab_tabla = new Tabla();
        tab_tabla2 = new Tabla();
        tab_tabla.setId("tab_tabla");
        tab_tabla.setTabla("inv_cab_comp_inve", "ide_incci", 100);
        tab_tabla.getColumna("ide_usua").setValorDefecto(utilitario.getVariable("ide_usua"));
        tab_tabla.getColumna("ide_georg").setCombo("gen_organigrama", "ide_georg", "nombre_georg", "");
        tab_tabla.getColumna("ide_usua").setVisible(false);
        tab_tabla.getColumna("ide_geper").setCombo("gen_persona", "ide_geper", "nom_geper,identificac_geper", "nivel_geper='HIJO'");
        tab_tabla.getColumna("ide_geper").setAutoCompletar();
        tab_tabla.getColumna("ide_geper").setRequerida(true);
        tab_tabla.getColumna("ide_inepi").setCombo("inv_est_prev_inve", "ide_inepi", "nombre_inepi", "");
        tab_tabla.getColumna("ide_intti").setCombo("select ide_intti,nombre_intti,nombre_intci from inv_tip_tran_inve a\n"
                + "inner join inv_tip_comp_inve b on a.ide_intci=b.ide_intci\n"
                + "order by nombre_intci desc, nombre_intti");
        tab_tabla.getColumna("ide_inbod").setVisible(false);
        tab_tabla.getColumna("ide_intti").setRequerida(true);
        tab_tabla.getColumna("ide_inepi").setValorDefecto(utilitario.getVariable("p_inv_estado_normal"));
        tab_tabla.getColumna("fecha_trans_incci").setValorDefecto(utilitario.getFechaActual());
        tab_tabla.getColumna("fecha_siste_incci").setValorDefecto(utilitario.getFechaActual());
        tab_tabla.getColumna("hora_sistem_incci").setValorDefecto(utilitario.getHoraActual());
        tab_tabla.getColumna("numero_incci").setLectura(true);
        tab_tabla.getColumna("numero_incci").setNombreVisual("SECUENCIAL");
        tab_tabla.getColumna("observacion_incci").setRequerida(true);
        tab_tabla.getColumna("observacion_incci").setControl("AreaTexto");
        tab_tabla.getColumna("sis_ide_usua").setVisible(false);
        tab_tabla.getColumna("fecha_siste_incci").setVisible(false);
        tab_tabla.getColumna("hora_sistem_incci").setVisible(false);
        tab_tabla.getColumna("fec_cam_est_incci").setVisible(false);
        tab_tabla.getColumna("fecha_efect_incci").setVisible(false);
        tab_tabla.getColumna("ide_cnccc").setNombreVisual("N. ASIENTO.");
        tab_tabla.getColumna("IDE_CNCCC").setLink();
        tab_tabla.getColumna("IDE_CNCCC").setMetodoChange("abrirAsiento");
        tab_tabla.setTipoFormulario(true);
        tab_tabla.getGrid().setColumns(4);
        tab_tabla.agregarRelacion(tab_tabla2);
        tab_tabla.setRecuperarLectura(true);
        tab_tabla.setMostrarNumeroRegistros(false);
        if (ide_incci_busca == null) {
            tab_tabla.setCondicion("ide_incci=-1");
        } else {
            tab_tabla.setCondicion("ide_incci=" + ide_incci_busca);
        }
        tab_tabla.dibujar();
        if (ide_incci_busca == null) {
            tab_tabla.insertar();
            tab_tabla.setValor("ide_inbod", String.valueOf(com_bodega.getValue()));
        }
        PanelTabla pat_panel1 = new PanelTabla();
        pat_panel1.setPanelTabla(tab_tabla);
        pat_panel1.getMenuTabla().getItem_insertar().setRendered(false);
        pat_panel1.getMenuTabla().getItem_eliminar().setRendered(false);
        pat_panel1.getMenuTabla().getItem_actualizar().setRendered(false);
        pat_panel1.getMenuTabla().getItem_buscar().setRendered(false);
        tab_tabla2.setId("tab_tabla2");
        tab_tabla2.setTabla("inv_det_comp_inve", "ide_indci", 200);
        tab_tabla2.getColumna("ide_inarti").setCombo("inv_articulo", "ide_inarti", "nombre_inarti", "");
        tab_tabla2.getColumna("ide_inarti").setAutoCompletar();
        tab_tabla2.getColumna("cantidad1_indci").setVisible(false);
        tab_tabla2.getColumna("ide_inarti").setMetodoChange("cargarPrecio");
        tab_tabla2.getColumna("cantidad_indci").setMetodoChange("calcularTotalDetalles");
        tab_tabla2.getColumna("precio_indci").setMetodoChange("calcularTotalDetalles");
        tab_tabla2.getColumna("cantidad_indci").setRequerida(true);
        tab_tabla2.getColumna("precio_indci").setRequerida(true);
        tab_tabla2.getColumna("ide_inarti").setRequerida(true);
        tab_tabla2.getColumna("valor_indci").setRequerida(true);
        tab_tabla2.getColumna("valor_indci").setEtiqueta();
        tab_tabla2.getColumna("valor_indci").setEstilo("font-size:13px;font-weight: bold;");
        tab_tabla2.getColumna("referencia_indci").setVisible(false);
        tab_tabla2.getColumna("referencia1_indci").setVisible(false);
        tab_tabla2.setRows(10);
        tab_tabla2.getColumna("precio_promedio_indci").setVisible(false);
        tab_tabla2.setRecuperarLectura(true);
        if (ide_incci_busca == null) {
            tab_tabla2.getColumna("ide_cpcfa").setVisible(false);
            tab_tabla2.getColumna("ide_cccfa").setVisible(false);
        } else {
            tab_tabla2.getColumna("ide_cpcfa").setCombo("cxp_cabece_factur", "ide_cpcfa", "numero_cpcfa", "ide_cpcfa=-1");
            tab_tabla2.getColumna("ide_cpcfa").setLectura(true);
            tab_tabla2.getColumna("ide_cccfa").setCombo("cxc_cabece_factura", "ide_cccfa", "secuencial_cccfa", "ide_cccfa=-1");
            tab_tabla2.getColumna("ide_cccfa").setLectura(true);
        }
        tab_tabla2.dibujar();
        if (ide_incci_busca == null) {
            tab_tabla2.getColumna("ide_cpcfa").setCombo("cxp_cabece_factur", "ide_cpcfa", "numero_cpcfa", "ide_cpcfa=" + tab_tabla2.getValor("ide_cpcfa"));
            tab_tabla2.getColumna("ide_cccfa").setCombo("cxc_cabece_factura", "ide_cccfa", "secuencial_cccfa", "ide_cccfa=" + tab_tabla2.getValor("ide_cccfa"));
        }
        PanelTabla pat_panel2 = new PanelTabla();
        pat_panel2.setPanelTabla(tab_tabla2);
        if (ide_incci_busca != null) {
            pat_panel2.getMenuTabla().getItem_insertar().setDisabled(true);
            pat_panel2.getMenuTabla().getItem_eliminar().setDisabled(true);
        }
        pat_panel2.getMenuTabla().getItem_eliminar().setRendered(true);
        gru_grupo.getChildren().add(pat_panel1);
        gru_grupo.getChildren().add(pat_panel2);
        mep_menu.dibujar(5, "COMPROBANTE DE INVENTARIO", gru_grupo);
    }

    public void calcularTotalDetalles(AjaxBehaviorEvent evt) {
        tab_tabla2.modificar(evt);
        calcularDetalles();
    }

    public void cargarPrecio(SelectEvent evt) {
        tab_tabla2.modificar(evt);
        List<Double> lisSaldos = ser_producto.getSaldoPromedioProductoBodega(tab_tabla2.getValor("ide_inarti"), utilitario.getFechaActual(), String.valueOf(com_bodega.getValue()));
        double dou_precioi = lisSaldos.get(1);
        tab_tabla2.setValor("precio_indci", utilitario.getFormatoNumero(dou_precioi));
        utilitario.addUpdateTabla(tab_tabla2, "precio_indci", "");
        double dou_existencia = ser_producto.getCantidadProductoBodega(tab_tabla2.getValor("ide_inarti"), String.valueOf(com_bodega.getValue()));
        if (dou_existencia <= 0) {
            utilitario.agregarMensajeError("No hay existencia de " + tab_tabla2.getValorArreglo("ide_inarti", 1) + " en Bodega", "");
        }
    }

    private void calcularDetalles() {
        double dou_cantidad = 0;
        double dou_precio = 0;
        double dou_valor = 0;
        try {
            dou_cantidad = Double.parseDouble(tab_tabla2.getValor("cantidad_indci"));
            dou_precio = Double.parseDouble(tab_tabla2.getValor("precio_indci"));
        } catch (Exception e) {
            dou_cantidad = 0;
            dou_precio = 0;
        }
        double dou_existencia = ser_producto.getCantidadProductoBodega(tab_tabla2.getValor("ide_inarti"), String.valueOf(com_bodega.getValue()));
        if (dou_cantidad > dou_existencia) {
            utilitario.agregarMensajeError("La cantidad ingresada es mayor a la existencia en Inventario", "Existencia actual de " + tab_tabla2.getValorArreglo("ide_inarti", 1) + " es :" + utilitario.getFormatoNumero(dou_existencia));
        }

        dou_valor = dou_cantidad * dou_precio;
        tab_tabla2.setValor("valor_indci", utilitario.getFormatoNumero(dou_valor));
        tab_tabla2.sumarColumnas();
        utilitario.addUpdateTabla(tab_tabla2, "valor_indci", "");
    }

    /**
     * Calcula los saldos del kardex
     */
    private void calculaKardex() {
        List<Double> lisSaldos = ser_producto.getSaldosInicialesKardex(aut_productos.getValor(), cal_fecha_inicio.getFecha(), "");

        double dou_canti = lisSaldos.get(0);
        double dou_precioi = lisSaldos.get(1);
        double dou_saldoi = lisSaldos.get(2);

        double dou_cantf = dou_canti; //acumula
        double dou_preciof = dou_precioi;//acumula
        double dou_saldof = dou_saldoi;//acumula

        for (int i = 0; i < tab_tabla.getTotalFilas(); i++) {
            double dou_cant_fila = 0;
            double dou_precio_fila = 0;
            double dou_saldo_fila = 0;

            if (tab_tabla.getValor(i, "VTOT_INGRESO") != null && tab_tabla.getValor(i, "VTOT_INGRESO").isEmpty() == false) {
                try {
                    dou_cant_fila = Double.parseDouble(tab_tabla.getValor(i, "CANT_INGRESO"));
                    dou_precio_fila = Double.parseDouble(tab_tabla.getValor(i, "VUNI_INGRESO"));
                    dou_saldo_fila = Double.parseDouble(tab_tabla.getValor(i, "VTOT_INGRESO"));
                } catch (Exception e) {
                }
                if (i == 0 && dou_saldof == 0) {
                    dou_cantf += dou_cant_fila;
                    dou_preciof = dou_precio_fila;
                    dou_saldof = dou_cant_fila * dou_precio_fila;
                } else {
                    dou_cantf += dou_cant_fila;
                    dou_saldof += dou_saldo_fila;
                    dou_preciof = dou_saldof / dou_cantf;
                }
            } else if (tab_tabla.getValor(i, "VTOT_EGRESO") != null && tab_tabla.getValor(i, "VTOT_EGRESO").isEmpty() == false) {
                try {
                    dou_cant_fila = Double.parseDouble(tab_tabla.getValor(i, "CANT_EGRESO"));
                    dou_precio_fila = Double.parseDouble(tab_tabla.getValor(i, "VUNI_EGRESO"));
                    dou_saldo_fila = Double.parseDouble(tab_tabla.getValor(i, "VTOT_EGRESO"));
                } catch (Exception e) {
                }
                if (i == 0 && dou_saldof == 0) {
                    dou_cantf -= dou_cant_fila;
                    dou_preciof = dou_precio_fila;
                    dou_saldof = dou_cant_fila * dou_precio_fila;
                } else {
                    dou_cantf -= dou_cant_fila;
                    dou_saldof -= dou_saldo_fila;
                    dou_preciof = dou_saldof / dou_cantf;
                }

            }
            tab_tabla.setValor(i, "CANT_SALDO", utilitario.getFormatoNumero(dou_cantf));
            tab_tabla.setValor(i, "VUNI_SALDO", utilitario.getFormatoNumero(dou_preciof));
            tab_tabla.setValor(i, "VTOT_SALDO", utilitario.getFormatoNumero(dou_saldof));
        }

        if (dou_saldoi != 0) {
            tab_tabla.setLectura(false);
            tab_tabla.insertar();
            tab_tabla.setValor("CANT_SALDO", utilitario.getFormatoNumero(dou_canti));
            tab_tabla.setValor("VUNI_SALDO", utilitario.getFormatoNumero(dou_precioi));
            tab_tabla.setValor("VTOT_SALDO", utilitario.getFormatoNumero(dou_saldoi));
            tab_tabla.setValor("nom_geper", "SALDO INICIAL AL " + cal_fecha_inicio.getFecha());
            tab_tabla.setValor("fecha_trans_incci", cal_fecha_inicio.getFecha());
            tab_tabla.setLectura(true);
        }
        tab_tabla.getColumna("CANT_SALDO").setTotal(dou_cantf);
        tab_tabla.getColumna("VUNI_SALDO").setTotal(dou_preciof);
        tab_tabla.getColumna("VTOT_SALDO").setTotal(dou_saldof);

    }

    public void dibujarSaldos() {
        Grupo gru_grupo = new Grupo();
        if (isBodegaSeleccionado()) {
            tab_tabla = new Tabla();
            tab_tabla.setNumeroTabla(6);
            tab_tabla.setId("tab_tabla");
            tab_tabla.setSql(ser_inventario.getSqlSaldoProductos(String.valueOf(com_bodega.getValue()), cal_fecha_fin.getFecha()));
            tab_tabla.getColumna("EXISTENCIA").setEstilo("font-size: 13px;font-weight: bold");
            tab_tabla.getColumna("EXISTENCIA").alinearDerecha();
            tab_tabla.getColumna("VALOR").setEstilo("font-size: 13px;font-weight: bold");
            tab_tabla.getColumna("VALOR").alinearDerecha();
            tab_tabla.setCampoPrimaria("ide_inarti");
            tab_tabla.getColumna("ide_inarti").setVisible(false);
            tab_tabla.getColumna("ARTICULO").setFiltroContenido();
            tab_tabla.setColumnaSuma("EXISTENCIA,VALOR");
            tab_tabla.setRows(25);
            tab_tabla.setLectura(true);
            tab_tabla.dibujar();
            PanelTabla pat_panel = new PanelTabla();
            pat_panel.setPanelTabla(tab_tabla);
            gru_grupo.getChildren().add(pat_panel);
        }
        mep_menu.dibujar(4, "SALDOS DE PRODUCTOS INVENTARIO", gru_grupo);
    }

    public void abrirGeneraAsiento() {
        if (tab_tabla.getFilasSeleccionadas() != null && tab_tabla.getFilasSeleccionadas().length() > 0) {
            asc_asiento.nuevoAsiento();
            asc_asiento.dibujar();
            asc_asiento.getTab_cabe_asiento().setValor("ide_geper", tab_tabla.getValor("ide_geper"));
            asc_asiento.getBot_aceptar().setMetodo("guardar");
        } else {
            utilitario.agregarMensajeInfo("Debe seleccionar almenos una Factura", "");
        }
    }

    public void actualizarMovimientos() {
        if (isBodegaSeleccionado()) {
            if (tab_tabla != null) {
                switch (mep_menu.getOpcion()) {
                    case 1:
                        tab_tabla.setSql(ser_inventario.getSqlComprobantesInventario(String.valueOf(com_bodega.getValue()), cal_fecha_inicio.getFecha(), cal_fecha_fin.getFecha()));
                        tab_tabla.ejecutarSql();
                        break;
                    case 2:
                        tab_tabla.setSql(ser_inventario.getSqlComprobantesInventarioNoConta(String.valueOf(com_bodega.getValue()), cal_fecha_inicio.getFecha(), cal_fecha_fin.getFecha()));
                        tab_tabla.ejecutarSql();
                        break;
                    case 3:
                        tab_tabla.setSql(ser_producto.getSqlKardex(aut_productos.getValor(), cal_fecha_inicio.getFecha(), cal_fecha_fin.getFecha(), ""));
                        tab_tabla.ejecutarSql();
                        calculaKardex();
                        break;
                    case 4:
                        tab_tabla.setSql(ser_inventario.getSqlSaldoProductos(String.valueOf(com_bodega.getValue()), cal_fecha_fin.getFecha()));
                        tab_tabla.ejecutarSql();
                        break;
                    default:
                        break;
                }
            }
        } else {
            mep_menu.limpiar();
        }
    }

    /**
     * Validacion para que se seleccione un Proveedor del Autocompletar
     *
     * @return
     */
    private boolean isBodegaSeleccionado() {
        if (com_bodega.getValue() == null) {
            utilitario.agregarMensajeInfo("Debe seleccionar una Bodega", "");
            return false;
        }
        return true;
    }

    /**
     * Abre el asiento contable seleccionado
     *
     * @param evt
     */
    public void abrirAsiento(ActionEvent evt) {
        Link lin_ide_cnccc = (Link) evt.getComponent();
        asc_asiento.setAsientoContable(lin_ide_cnccc.getValue().toString());
        tab_tabla.setFilaActual(lin_ide_cnccc.getDir());
        asc_asiento.dibujar();
    }

    public void cargarComprobante(ActionEvent evt) {
        Link lin_ide_cnccc = (Link) evt.getComponent();
        ide_incci_busca = lin_ide_cnccc.getValue().toString();
        dibujarComprobanteInv();
    }

    @Override
    public void insertar() {
        if (isBodegaSeleccionado()) {
            if (tab_tabla2 != null) {
                if (ide_incci_busca == null) {
                    if (utilitario.getTablaisFocus() != null && tab_tabla2.isFocus()) {
                        tab_tabla2.insertar();
                        return;
                    }
                }
            }
            ide_incci_busca = null;
            dibujarComprobanteInv();
        }

    }

    @Override
    public void guardar() {
        if (asc_asiento.isVisible()) {
            asc_asiento.guardar();
            if (asc_asiento.isVisible() == false) {
                dibujarComprobantes();
            }
        } else {

            if (tab_tabla.isFilaInsertada()) {
                if (validar()) {
                    tab_tabla.setValor("ide_inbod", String.valueOf(com_bodega.getValue()));
                    tab_tabla.setValor("numero_incci", ser_inventario.getSecuencialComprobanteInventario(String.valueOf(com_bodega.getValue())));
                } else {
                    return;
                }
            } else if (tab_tabla.isFilaModificada()) {
                if (!validar()) {
                    return;
                }
            }
            if (tab_tabla.guardar()) {
                String ide_incci = tab_tabla.getValor("ide_incci");
                if (tab_tabla2.guardar()) {
                    if (utilitario.getConexion().guardarPantalla().isEmpty()) {
                        dibujarComprobantes();
                        tab_tabla.setFilaActual(ide_incci);
                        ide_incci_busca = null;
                    }
                }
            }

        }

    }

    public boolean validar() {
        if (tab_tabla.getValor("ide_geper") == null || tab_tabla.getValor("ide_geper").isEmpty()) {
            utilitario.agregarMensajeInfo("No se pudo guardar", "Debe ingresar un Beneficiario");
            return false;
        }
        if (tab_tabla.getValor("ide_intti") == null || tab_tabla.getValor("ide_intti").isEmpty()) {
            utilitario.agregarMensajeInfo("No se pudo guardar", "Debe seleccionar un tipo de transacción");
            return false;
        }
        if (tab_tabla.getValor("fecha_trans_incci") == null || tab_tabla.getValor("fecha_trans_incci").isEmpty()) {
            utilitario.agregarMensajeInfo("No se pudo guardar", "debe ingresar la fecha de la transacción");
            return false;
        }
        if (tab_tabla.getValor("observacion_incci") == null || tab_tabla.getValor("observacion_incci").isEmpty()) {
            utilitario.agregarMensajeInfo("No se pudo guardar", "Debe ingresar la observación");
            return false;
        }
        if (tab_tabla2.getTotalFilas() == 0) {
            utilitario.agregarMensajeInfo("No se puede guardar", "Debe insertar información en el detalle");
            return false;
        }
        if (tab_tabla2.getValor("ide_inarti") == null || tab_tabla2.getValor("ide_inarti").isEmpty()) {
            utilitario.agregarMensajeInfo("No se puede guardar", "Debe ingresar un articulo");
            return false;
        }
        if (tab_tabla2.getValor("cantidad_indci") == null || tab_tabla2.getValor("cantidad_indci").isEmpty()) {
            utilitario.agregarMensajeInfo("No se puede guardar", "Debe ingresar la cantidad");
            return false;
        }
        if (tab_tabla2.getValor("precio_indci") == null || tab_tabla2.getValor("precio_indci").isEmpty()) {
            utilitario.agregarMensajeInfo("No se puede guardar", "Debe ingresar el precio");
            return false;
        }
        if (com_bodega.getValue() == null) {
            utilitario.agregarMensajeInfo("No se puede guardar", "Debe seleccionar una  bodega");
            return false;
        }
        return true;
    }

    @Override
    public void eliminar() {
        if (tab_tabla2 != null) {
            if (ide_incci_busca == null) {
                if (utilitario.getTablaisFocus() != null && tab_tabla2.isFocus()) {
                    tab_tabla2.eliminar();
                }
            }
        }
    }

    public Tabla getTab_tabla() {
        return tab_tabla;
    }

    public void setTab_tabla(Tabla tab_tabla) {
        this.tab_tabla = tab_tabla;
    }

    public AsientoContable getAsc_asiento() {
        return asc_asiento;
    }

    public void setAsc_asiento(AsientoContable asc_asiento) {
        this.asc_asiento = asc_asiento;
    }

    public AutoCompletar getAut_productos() {
        return aut_productos;
    }

    public void setAut_productos(AutoCompletar aut_productos) {
        this.aut_productos = aut_productos;
    }

    public Tabla getTab_tabla2() {
        return tab_tabla2;
    }

    public void setTab_tabla2(Tabla tab_tabla2) {
        this.tab_tabla2 = tab_tabla2;
    }

}


text:
<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>URLvsURI</groupId>
  <artifactId>URLvsURI</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.1</version>
        <configuration>
          <source>1.7</source>
          <target>1.7</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <dependencies>
  	<dependency>
  		<groupId>commons-io</groupId>
  		<artifactId>commons-io</artifactId>
  		<version>20030203.000550</version>
  	</dependency>
  	<dependency>
  		<groupId>org.apache.httpcomponents</groupId>
  		<artifactId>httpclient</artifactId>
  		<version>4.3</version>
  	</dependency>
  </dependencies>
</project>

redpajama_set_name: RedPajamaGithub


text:
import os, sys, math, subprocess
from collections import defaultdict
from optparse import OptionParser
from Bio import SeqIO
from Bio.SeqIO.QualityIO import FastqGeneralIterator

__doc__ = """
Calculate statistics for fasta files.

OUTPUT:
  bp_count
  sequence_count
  average_length
  standard_deviation_length
  length_min
  length_max
  average_gc_content
  standard_deviation_gc_content
  average_gc_ratio
  standard_deviation_gc_ratio
  ambig_char_count
  ambig_sequence_count
  average_ambig_chars
  sequence_type"""

def sum_map(aMap):
    total = 0
    for k, v in aMap.iteritems():
        total += (float(k) * v)
    return total

def seq_iter(file_hdl, stype):
    if stype == 'fastq':
        return FastqGeneralIterator(file_hdl)
    else:
        return SeqIO.parse(file_hdl, stype)

def split_rec(rec, stype):
    if stype == 'fastq':
        return rec[0].split()[0], rec[1].upper(), rec[2]
    else:
        return rec.id, str(rec.seq).upper(), None

def get_mean_stdev(count, data):
    total = sum_map(data)
    mean  = (total * 1.0) / count
    tmp   = 0
    for k, v in data.iteritems():
        for i in range(0, v):
            dev  = float(k) - mean
            tmp += (dev * dev)
    return mean, math.sqrt(tmp / count)

def get_seq_type(size, data):
    kset  = []
    total = sum( data.values() )
    for i in range(1, size+1):
        kset.append( sub_kmer(i, total, data) )
    # black box logic
    if (kset[15] < 9.8) and (kset[10] < 6):
        return "Amplicon"
    else:
        return "WGS"

def sub_kmer(pos, total, data):
    sub_data = defaultdict(int)
    entropy  = 0
    for kmer, num in data.iteritems():
        sub_data[ kmer[:pos] ] += num
    for skmer, snum in sub_data.iteritems():
        sratio = float(snum) / total
        entropy += (-1 * sratio) * math.log(sratio, 2)
    return entropy

def output_bins(data, outf):
    out_hdl = open(outf, "w")
    keys = data.keys()
    keys.sort(lambda a,b: cmp(float(a), float(b)))
    for k in keys:
        out_hdl.write("%s\t%d\n"%(k, data[k]))
    out_hdl.close()

usage = "usage: %prog [options] -i input_fasta" + __doc__

def main(args):
    parser = OptionParser(usage=usage)
    parser.add_option("-i", "--input", dest="input", default=None, help="Input sequence file")
    parser.add_option("-o", "--output", dest="output", default=None, help="Output stats file, if not called prints to STDOUT")
    parser.add_option("-t", "--type", dest="type", default="fasta", help="Input file type. Must be fasta or fastq [default 'fasta']")
    parser.add_option("-l", "--length_bin", dest="len_bin", metavar="FILE", default=None, help="File to place length bins [default is no output]")
    parser.add_option("-g", "--gc_percent_bin", dest="gc_bin", metavar="FILE", default=None, help="File to place % gc bins [default is no output]")
    parser.add_option("-f", "--fast", dest="fast", default=False, action="store_true", help="Fast mode, only calculate length stats")
    parser.add_option("-s", "--seq_type", dest="seq_type", default=False, action="store_true", help="Guess sequence type [wgs|amplicon] from kmer entropy")
    parser.add_option("-m", "--seq_max", dest="seq_max", default=100000, type="int", help="max number of seqs to process (for kmer entropy) [default 100000]")

    # check options
    (opts, args) = parser.parse_args()
    if not opts.input:
        sys.stderr.write("[error] missing input file\n")
        os._exit(1)
    if (opts.type != 'fasta') and (opts.type != 'fastq'):
        sys.stderr.write("[error] file type '%s' is invalid\n" %opts.type)
        os._exit(1)

    # set variables
    seqnum   = 0
    lengths  = defaultdict(int)
    gc_perc  = defaultdict(int)
    gc_ratio = defaultdict(int)
    ambig_char = 0
    ambig_seq  = 0
    kmer_len   = 16
    kmer_num   = 0
    prefix_map = defaultdict(int)
    in_hdl = open(opts.input, "rU")

    # parse sequences
    try:
        for rec in seq_iter(in_hdl, opts.type):
            head, seq, qual = split_rec(rec, opts.type)
            slen = len(seq)
            seqnum += 1
            lengths[slen] += 1

            if not opts.fast:
                char = {'A': 0, 'T': 0, 'G': 0, 'C': 0}
                for c in seq:
                    if c in char:
                        char[c] += 1
                atgc  = char['A'] + char['T'] + char['G'] + char['C']
                ambig = slen - atgc;
                gc_p  = "0"
                gc_r  = "0"
                if atgc > 0:
                    gc_p = "%.1f"%((1.0 * (char['G'] + char['C']) / atgc) * 100)
                if (char['G'] + char['C']) > 0:
                    gc_r = "%.1f"%(1.0 * (char['A'] + char['T']) / (char['G'] + char['C']))
                gc_perc[gc_p] += 1
                gc_ratio[gc_r] += 1
                if ambig > 0:
                    ambig_char += ambig
                    ambig_seq += 1
            if opts.seq_type and (slen >= kmer_len) and (kmer_num < opts.seq_max):
                prefix_map[ seq[:kmer_len] ] += 1
                kmer_num += 1
    except ValueError as e:
        sys.stderr.write("[error] possible file truncation: %s\n" %e)
        os._exit(1)

    # get stats
    if seqnum == 0:
        sys.stderr.write("[error] invalid %s file, unable to find sequence records\n"%opts.type)
        os._exit(1)
    len_mean, len_stdev = get_mean_stdev(seqnum, lengths)
    min_len   = min( lengths.iterkeys() )
    max_len   = max( lengths.iterkeys() )
    stat_text = [ "bp_count\t%d"%sum_map(lengths),
                  "sequence_count\t%d"%seqnum,
                  "average_length\t%.3f"%len_mean,
                  "standard_deviation_length\t%.3f"%len_stdev,
                  "length_min\t%d"%min_len,
                  "length_max\t%d"%max_len ]

    if not opts.fast:
        gcp_mean, gcp_stdev = get_mean_stdev(seqnum, gc_perc)
        gcr_mean, gcr_stdev = get_mean_stdev(seqnum, gc_ratio)
        stat_text.extend([ "average_gc_content\t%.3f"%gcp_mean,
                           "standard_deviation_gc_content\t%.3f"%gcp_stdev,
                           "average_gc_ratio\t%.3f"%gcr_mean,
                           "standard_deviation_gc_ratio\t%.3f"%gcr_stdev,
                           "ambig_char_count\t%d"%ambig_char,
                           "ambig_sequence_count\t%d"%ambig_seq,
                           "average_ambig_chars\t%.3f"%((ambig_char * 1.0) / seqnum) ])
    if opts.seq_type:
        seq_type_guess = get_seq_type(kmer_len, prefix_map)
        stat_text.append("sequence_type\t%s"%seq_type_guess)

    # output stats
    if not opts.output:
        sys.stdout.write( "\n".join(stat_text) + "\n" )
    else:
        out_hdl = open(opts.output, "w")
        out_hdl.write( "\n".join(stat_text) + "\n" )
        out_hdl.close()

    # get binned stats
    if opts.len_bin:
        output_bins(lengths, opts.len_bin)
    if opts.gc_bin and (not opts.fast):
        output_bins(gc_perc, opts.gc_bin)

    return 0

if __name__ == "__main__":
    sys.exit( main(sys.argv) )


text:
module.exports = {
  description: "",
  ns: "react-material-ui",
  type: "ReactNode",
  dependencies: {
    npm: {
      "material-ui/svg-icons/image/broken-image": require('material-ui/svg-icons/image/broken-image')
    }
  },
  name: "ImageBrokenImage",
  ports: {
    input: {},
    output: {
      component: {
        title: "ImageBrokenImage",
        type: "Component"
      }
    }
  }
}


text:
{-- snippet testscript --}
import QC
import Prettify2
import Test.QuickCheck.Batch

options = TestOptions
      { no_of_tests         = 200
      , length_of_tests     = 1
      , debug_tests         = False }

main = do
    runTests "simple" options
        [ run prop_empty_id
        , run prop_char
        , run prop_text
        , run prop_line
        , run prop_double
        ]

    runTests "complex" options
        [ run prop_hcat
        , run prop_puncutate'
        , run prop_mempty_id
        ]
{-- /snippet testscript --}


text:
{% extends "base.html" %}

{% block content %}
   <form action="" method="POST">
        {% csrf_token %}
        {{form.as_ul}}
       <button type="submit">Send</button>
   </form>
{% endblock content %}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BtceApi.Services
{
    public enum CurrencyPair
    {
        [Description("btc_usd")]
        BtcUsd,
        [Description("btc_eur")]
        BtcEur,
        [Description("btc_rur")]
        BtcRur,
        [Description("ltc_btc")]
        LtcBtc,
        [Description("ltc_usd")]
        LtcUsd,
        [Description("ltc_rur")]
        LtcRur,
        [Description("nmc_btc")]
        NmcBtc,
        [Description("usd_rur")]
        UsdRur,
        [Description("eur_usd")]
        EurUsd
    }
}


text:
import sys, os
import contextlib
import subprocess

# find_library(name) returns the pathname of a library, or None.
if os.name == "nt":

    def _get_build_version():
        """Return the version of MSVC that was used to build Python.

        For Python 2.3 and up, the version number is included in
        sys.version.  For earlier versions, assume the compiler is MSVC 6.
        """
        # This function was copied from Lib/distutils/msvccompiler.py
        prefix = "MSC v."
        i = sys.version.find(prefix)
        if i == -1:
            return 6
        i = i + len(prefix)
        s, rest = sys.version[i:].split(" ", 1)
        majorVersion = int(s[:-2]) - 6
        minorVersion = int(s[2:3]) / 10.0
        # I don't think paths are affected by minor version in version 6
        if majorVersion == 6:
            minorVersion = 0
        if majorVersion >= 6:
            return majorVersion + minorVersion
        # else we don't know what version of the compiler this is
        return None

    def find_msvcrt():
        """Return the name of the VC runtime dll"""
        version = _get_build_version()
        if version is None:
            # better be safe than sorry
            return None
        if version <= 6:
            clibname = 'msvcrt'
        else:
            clibname = 'msvcr%d' % (version * 10)

        # If python was built with in debug mode
        import importlib.machinery
        if '_d.pyd' in importlib.machinery.EXTENSION_SUFFIXES:
            clibname += 'd'
        return clibname+'.dll'

    def find_library(name):
        if name in ('c', 'm'):
            return find_msvcrt()
        # See MSDN for the REAL search order.
        for directory in os.environ['PATH'].split(os.pathsep):
            fname = os.path.join(directory, name)
            if os.path.isfile(fname):
                return fname
            if fname.lower().endswith(".dll"):
                continue
            fname = fname + ".dll"
            if os.path.isfile(fname):
                return fname
        return None

if os.name == "ce":
    # search path according to MSDN:
    # - absolute path specified by filename
    # - The .exe launch directory
    # - the Windows directory
    # - ROM dll files (where are they?)
    # - OEM specified search path: HKLM\Loader\SystemPath
    def find_library(name):
        return name

if os.name == "posix" and sys.platform == "darwin":
    from ctypes.macholib.dyld import dyld_find as _dyld_find
    def find_library(name):
        possible = ['lib%s.dylib' % name,
                    '%s.dylib' % name,
                    '%s.framework/%s' % (name, name)]
        for name in possible:
            try:
                return _dyld_find(name)
            except ValueError:
                continue
        return None

elif os.name == "posix":
    # Andreas Degert's find functions, using gcc, /sbin/ldconfig, objdump
    import re, tempfile, errno

    def _findLib_gcc(name):
        expr = r'[^\(\)\s]*lib%s\.[^\(\)\s]*' % re.escape(name)
        fdout, ccout = tempfile.mkstemp()
        os.close(fdout)
        cmd = 'if type gcc >/dev/null 2>&1; then CC=gcc; elif type cc >/dev/null 2>&1; then CC=cc;else exit 10; fi;' \
              '$CC -Wl,-t -o ' + ccout + ' 2>&1 -l' + name
        try:
            f = os.popen(cmd)
            try:
                trace = f.read()
            finally:
                rv = f.close()
        finally:
            try:
                os.unlink(ccout)
            except OSError as e:
                if e.errno != errno.ENOENT:
                    raise
        if rv == 10:
            raise OSError('gcc or cc command not found')
        res = re.search(expr, trace)
        if not res:
            return None
        return res.group(0)

    if sys.platform == "sunos5":
        # use /usr/ccs/bin/dump on solaris
        def _get_soname(f):
            if not f:
                return None
            cmd = "/usr/ccs/bin/dump -Lpv 2>/dev/null " + f
            with contextlib.closing(os.popen(cmd)) as f:
                data = f.read()
            res = re.search(r'\[.*\]\sSONAME\s+([^\s]+)', data)
            if not res:
                return None
            return res.group(1)
    else:
        def _get_soname(f):
            # assuming GNU binutils / ELF
            if not f:
                return None
            cmd = 'if ! type objdump >/dev/null 2>&1; then exit 10; fi;' \
                  "objdump -p -j .dynamic 2>/dev/null " + f
            f = os.popen(cmd)
            dump = f.read()
            rv = f.close()
            if rv == 10:
                raise OSError('objdump command not found')
            res = re.search(r'\sSONAME\s+([^\s]+)', dump)
            if not res:
                return None
            return res.group(1)

    if sys.platform.startswith(("freebsd", "openbsd", "dragonfly")):

        def _num_version(libname):
            # "libxyz.so.MAJOR.MINOR" => [ MAJOR, MINOR ]
            parts = libname.split(".")
            nums = []
            try:
                while parts:
                    nums.insert(0, int(parts.pop()))
            except ValueError:
                pass
            return nums or [ sys.maxsize ]

        def find_library(name):
            ename = re.escape(name)
            expr = r':-l%s\.\S+ => \S*/(lib%s\.\S+)' % (ename, ename)
            with contextlib.closing(os.popen('/sbin/ldconfig -r 2>/dev/null')) as f:
                data = f.read()
            res = re.findall(expr, data)
            if not res:
                return _get_soname(_findLib_gcc(name))
            res.sort(key=_num_version)
            return res[-1]

    else:

        def _findSoname_ldconfig(name):
            import struct
            if struct.calcsize('l') == 4:
                machine = os.uname().machine + '-32'
            else:
                machine = os.uname().machine + '-64'
            mach_map = {
                'x86_64-64': 'libc6,x86-64',
                'ppc64-64': 'libc6,64bit',
                'sparc64-64': 'libc6,64bit',
                's390x-64': 'libc6,64bit',
                'ia64-64': 'libc6,IA-64',
                }
            abi_type = mach_map.get(machine, 'libc6')

            # XXX assuming GLIBC's ldconfig (with option -p)
            regex = os.fsencode(
                '\s+(lib%s\.[^\s]+)\s+\(%s' % (re.escape(name), abi_type))
            try:
                with subprocess.Popen(['/sbin/ldconfig', '-p'],
                                      stdin=subprocess.DEVNULL,
                                      stderr=subprocess.DEVNULL,
                                      stdout=subprocess.PIPE,
                                      env={'LC_ALL': 'C', 'LANG': 'C'}) as p:
                    res = re.search(regex, p.stdout.read())
                    if res:
                        return os.fsdecode(res.group(1))
            except OSError:
                pass

        def find_library(name):
            return _findSoname_ldconfig(name) or _get_soname(_findLib_gcc(name))

################################################################
# test code

def test():
    from ctypes import cdll
    if os.name == "nt":
        print(cdll.msvcrt)
        print(cdll.load("msvcrt"))
        print(find_library("msvcrt"))

    if os.name == "posix":
        # find and load_version
        print(find_library("m"))
        print(find_library("c"))
        print(find_library("bz2"))

        # getattr
##        print cdll.m
##        print cdll.bz2

        # load
        if sys.platform == "darwin":
            print(cdll.LoadLibrary("libm.dylib"))
            print(cdll.LoadLibrary("libcrypto.dylib"))
            print(cdll.LoadLibrary("libSystem.dylib"))
            print(cdll.LoadLibrary("System.framework/System"))
        else:
            print(cdll.LoadLibrary("libm.so"))
            print(cdll.LoadLibrary("libcrypt.so"))
            print(find_library("crypt"))

if __name__ == "__main__":
    test()


text:
  <title>Highcharts Venn Chart Test</title>

  <form id="form">
    A<input id="setA" type="number" value="368">
    B<input id="setB" type="number" value="601">
    C<input id="setC" type="number" value="0">
    AB<input id="intAB" type="number" value="21">
    BC<input id="intBC" type="number" value="000">
    AC<input id="intAC" type="number" value="000">
  </form>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SE.DSP.Foundation.DataAccess;
using SE.DSP.Pop.Entity;

namespace SE.DSP.Pop.Contract
{
    public interface IDistributionCabinetRepository : IRepository<DistributionCabinet, long>
    {
        long[] GetIdByGatewayId(long gatewayId);
    }
}


text:
'use strict';

var should = require('should'),
  request = require('supertest'),
  path = require('path'),
  mongoose = require('mongoose'),
  User = mongoose.model('User'),
  Company = mongoose.model('Company'),
  express = require(path.resolve('./config/lib/express'));

/**
 * Globals
 */
var app,
  agent,
  credentials,
  user,
  company;

/**
 * Company routes tests
 */
describe('Company CRUD tests', function () {

  before(function (done) {
    // Get application
    app = express.init(mongoose);
    agent = request.agent(app);

    done();
  });

  beforeEach(function (done) {
    // Create user credentials
    credentials = {
      username: 'username',
      password: 'M3@n.jsI$Aw3$0m3'
    };

    // Create a new user
    user = new User({
      firstName: 'Full',
      lastName: 'Name',
      displayName: 'Full Name',
      email: 'test@test.com',
      username: credentials.username,
      password: credentials.password,
      provider: 'local'
    });

    // Save a user to the test db and create new Company
    user.save(function () {
      company = {
        name: 'Company name'
      };

      done();
    });
  });

  it('should be able to save a Company if logged in', function (done) {
    agent.post('/api/auth/signin')
      .send(credentials)
      .expect(200)
      .end(function (signinErr, signinRes) {
        // Handle signin error
        if (signinErr) {
          return done(signinErr);
        }

        // Get the userId
        var userId = user.id;

        // Save a new Company
        agent.post('/api/companies')
          .send(company)
          .expect(200)
          .end(function (companySaveErr, companySaveRes) {
            // Handle Company save error
            if (companySaveErr) {
              return done(companySaveErr);
            }

            // Get a list of Companies
            agent.get('/api/companies')
              .end(function (companiesGetErr, companiesGetRes) {
                // Handle Companies save error
                if (companiesGetErr) {
                  return done(companiesGetErr);
                }

                // Get Companies list
                var companies = companiesGetRes.body;

                // Set assertions
                (companies[0].user._id).should.equal(userId);
                (companies[0].name).should.match('Company name');

                // Call the assertion callback
                done();
              });
          });
      });
  });

  it('should not be able to save an Company if not logged in', function (done) {
    agent.post('/api/companies')
      .send(company)
      .expect(403)
      .end(function (companySaveErr, companySaveRes) {
        // Call the assertion callback
        done(companySaveErr);
      });
  });

  it('should not be able to save an Company if no name is provided', function (done) {
    // Invalidate name field
    company.name = '';

    agent.post('/api/auth/signin')
      .send(credentials)
      .expect(200)
      .end(function (signinErr, signinRes) {
        // Handle signin error
        if (signinErr) {
          return done(signinErr);
        }

        // Get the userId
        var userId = user.id;

        // Save a new Company
        agent.post('/api/companies')
          .send(company)
          .expect(400)
          .end(function (companySaveErr, companySaveRes) {
            // Set message assertion
            (companySaveRes.body.message).should.match('Please fill Company name');

            // Handle Company save error
            done(companySaveErr);
          });
      });
  });

  it('should be able to update an Company if signed in', function (done) {
    agent.post('/api/auth/signin')
      .send(credentials)
      .expect(200)
      .end(function (signinErr, signinRes) {
        // Handle signin error
        if (signinErr) {
          return done(signinErr);
        }

        // Get the userId
        var userId = user.id;

        // Save a new Company
        agent.post('/api/companies')
          .send(company)
          .expect(200)
          .end(function (companySaveErr, companySaveRes) {
            // Handle Company save error
            if (companySaveErr) {
              return done(companySaveErr);
            }

            // Update Company name
            company.name = 'WHY YOU GOTTA BE SO MEAN?';

            // Update an existing Company
            agent.put('/api/companies/' + companySaveRes.body._id)
              .send(company)
              .expect(200)
              .end(function (companyUpdateErr, companyUpdateRes) {
                // Handle Company update error
                if (companyUpdateErr) {
                  return done(companyUpdateErr);
                }

                // Set assertions
                (companyUpdateRes.body._id).should.equal(companySaveRes.body._id);
                (companyUpdateRes.body.name).should.match('WHY YOU GOTTA BE SO MEAN?');

                // Call the assertion callback
                done();
              });
          });
      });
  });

  it('should be able to get a list of Companies if not signed in', function (done) {
    // Create new Company model instance
    var companyObj = new Company(company);

    // Save the company
    companyObj.save(function () {
      // Request Companies
      request(app).get('/api/companies')
        .end(function (req, res) {
          // Set assertion
          res.body.should.be.instanceof(Array).and.have.lengthOf(1);

          // Call the assertion callback
          done();
        });

    });
  });

  it('should be able to get a single Company if not signed in', function (done) {
    // Create new Company model instance
    var companyObj = new Company(company);

    // Save the Company
    companyObj.save(function () {
      request(app).get('/api/companies/' + companyObj._id)
        .end(function (req, res) {
          // Set assertion
          res.body.should.be.instanceof(Object).and.have.property('name', company.name);

          // Call the assertion callback
          done();
        });
    });
  });

  it('should return proper error for single Company with an invalid Id, if not signed in', function (done) {
    // test is not a valid mongoose Id
    request(app).get('/api/companies/test')
      .end(function (req, res) {
        // Set assertion
        res.body.should.be.instanceof(Object).and.have.property('message', 'Company is invalid');

        // Call the assertion callback
        done();
      });
  });

  it('should return proper error for single Company which doesnt exist, if not signed in', function (done) {
    // This is a valid mongoose Id but a non-existent Company
    request(app).get('/api/companies/559e9cd815f80b4c256a8f41')
      .end(function (req, res) {
        // Set assertion
        res.body.should.be.instanceof(Object).and.have.property('message', 'No Company with that identifier has been found');

        // Call the assertion callback
        done();
      });
  });

  it('should be able to delete an Company if signed in', function (done) {
    agent.post('/api/auth/signin')
      .send(credentials)
      .expect(200)
      .end(function (signinErr, signinRes) {
        // Handle signin error
        if (signinErr) {
          return done(signinErr);
        }

        // Get the userId
        var userId = user.id;

        // Save a new Company
        agent.post('/api/companies')
          .send(company)
          .expect(200)
          .end(function (companySaveErr, companySaveRes) {
            // Handle Company save error
            if (companySaveErr) {
              return done(companySaveErr);
            }

            // Delete an existing Company
            agent.delete('/api/companies/' + companySaveRes.body._id)
              .send(company)
              .expect(200)
              .end(function (companyDeleteErr, companyDeleteRes) {
                // Handle company error error
                if (companyDeleteErr) {
                  return done(companyDeleteErr);
                }

                // Set assertions
                (companyDeleteRes.body._id).should.equal(companySaveRes.body._id);

                // Call the assertion callback
                done();
              });
          });
      });
  });

  it('should not be able to delete an Company if not signed in', function (done) {
    // Set Company user
    company.user = user;

    // Create new Company model instance
    var companyObj = new Company(company);

    // Save the Company
    companyObj.save(function () {
      // Try deleting Company
      request(app).delete('/api/companies/' + companyObj._id)
        .expect(403)
        .end(function (companyDeleteErr, companyDeleteRes) {
          // Set message assertion
          (companyDeleteRes.body.message).should.match('User is not authorized');

          // Handle Company error error
          done(companyDeleteErr);
        });

    });
  });

  it('should be able to get a single Company that has an orphaned user reference', function (done) {
    // Create orphan user creds
    var _creds = {
      username: 'orphan',
      password: 'M3@n.jsI$Aw3$0m3'
    };

    // Create orphan user
    var _orphan = new User({
      firstName: 'Full',
      lastName: 'Name',
      displayName: 'Full Name',
      email: 'orphan@test.com',
      username: _creds.username,
      password: _creds.password,
      provider: 'local'
    });

    _orphan.save(function (err, orphan) {
      // Handle save error
      if (err) {
        return done(err);
      }

      agent.post('/api/auth/signin')
        .send(_creds)
        .expect(200)
        .end(function (signinErr, signinRes) {
          // Handle signin error
          if (signinErr) {
            return done(signinErr);
          }

          // Get the userId
          var orphanId = orphan._id;

          // Save a new Company
          agent.post('/api/companies')
            .send(company)
            .expect(200)
            .end(function (companySaveErr, companySaveRes) {
              // Handle Company save error
              if (companySaveErr) {
                return done(companySaveErr);
              }

              // Set assertions on new Company
              (companySaveRes.body.name).should.equal(company.name);
              should.exist(companySaveRes.body.user);
              should.equal(companySaveRes.body.user._id, orphanId);

              // force the Company to have an orphaned user reference
              orphan.remove(function () {
                // now signin with valid user
                agent.post('/api/auth/signin')
                  .send(credentials)
                  .expect(200)
                  .end(function (err, res) {
                    // Handle signin error
                    if (err) {
                      return done(err);
                    }

                    // Get the Company
                    agent.get('/api/companies/' + companySaveRes.body._id)
                      .expect(200)
                      .end(function (companyInfoErr, companyInfoRes) {
                        // Handle Company error
                        if (companyInfoErr) {
                          return done(companyInfoErr);
                        }

                        // Set assertions
                        (companyInfoRes.body._id).should.equal(companySaveRes.body._id);
                        (companyInfoRes.body.name).should.equal(company.name);
                        should.equal(companyInfoRes.body.user, undefined);

                        // Call the assertion callback
                        done();
                      });
                  });
              });
            });
        });
    });
  });

  afterEach(function (done) {
    User.remove().exec(function () {
      Company.remove().exec(done);
    });
  });
});


text:
/**
 * @description Añade todos los archivos de java script para el cliente
 * @author Mateo Morales García
 */

/**
 * Añade un script a la pagina principal
 * @param {String} ruta ruta del script
 */
function addScript (ruta) {
    var nuevoScript = document.createElement("script");
    nuevoScript.setAttribute("src", ruta);
    document.body.appendChild(nuevoScript);
};
/**
 * Lista de Scripts que se añaden
 */
addScript("/js/ui_changes/general.js");
addScript("/js/chat.js");
addScript("/js/ui_changes/concreto.js");


text:
require File.dirname(__FILE__) + '/../test_helper'
require 'ebay/responses/get_ebay_official_time'
require 'ebay/responses/verify_add_item'

class EbayMappingTest < Test::Unit::TestCase
  include Ebay::Responses

	def setup
		@ebay_time = GeteBayOfficialTime.load_from_file(response_file_path('official_time_success'))
	  @valid = VerifyAddItem.load_from_file(response_file_path('verify_add_item'))
  end

	def test_reference
	  assert_valid_abstract_response(@ebay_time)
	end

	def assert_valid_abstract_response(response)
    timestamp = '2006-07-05T14:23:03.399Z'
	  ack = 'Success'
	  version = '467'
	  build = 'e467_core_Bundled_3145691_R1'
    assert_equal Time.parse(timestamp), response.timestamp
    assert_equal ack, response.ack
    assert_equal version, response.version
    assert_equal build, response.build
	end
end


text:
namespace MyLog.XYZ_Desktop
{
    partial class SignInForm
    {
        /// <summary>
        /// Обязательная переменная конструктора.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Освободить все используемые ресурсы.
        /// </summary>
        /// <param name="disposing">истинно, если управляемый ресурс должен быть удален; иначе ложно.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Код, автоматически созданный конструктором форм Windows

        /// <summary>
        /// Требуемый метод для поддержки конструктора — не изменяйте
        /// содержимое этого метода с помощью редактора кода.
        /// </summary>
        private void InitializeComponent()
        {
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(SignInForm));
            this.usernameTextBox = new System.Windows.Forms.TextBox();
            this.passwordTextBox = new System.Windows.Forms.TextBox();
            this.signInButton = new System.Windows.Forms.Button();
            this.usernameLabel = new System.Windows.Forms.Label();
            this.passwordLabel = new System.Windows.Forms.Label();
            this.logoPictureBox = new System.Windows.Forms.PictureBox();
            ((System.ComponentModel.ISupportInitialize)(this.logoPictureBox)).BeginInit();
            this.SuspendLayout();
            //
            // usernameTextBox
            //
            this.usernameTextBox.Location = new System.Drawing.Point(130, 28);
            this.usernameTextBox.Name = "usernameTextBox";
            this.usernameTextBox.Size = new System.Drawing.Size(100, 20);
            this.usernameTextBox.TabIndex = 0;
            //
            // passwordTextBox
            //
            this.passwordTextBox.Location = new System.Drawing.Point(130, 67);
            this.passwordTextBox.Name = "passwordTextBox";
            this.passwordTextBox.PasswordChar = '*';
            this.passwordTextBox.Size = new System.Drawing.Size(100, 20);
            this.passwordTextBox.TabIndex = 1;
            //
            // signInButton
            //
            this.signInButton.Location = new System.Drawing.Point(85, 106);
            this.signInButton.Name = "signInButton";
            this.signInButton.Size = new System.Drawing.Size(75, 23);
            this.signInButton.TabIndex = 2;
            this.signInButton.Text = "Sign in";
            this.signInButton.UseVisualStyleBackColor = true;
            this.signInButton.Click += new System.EventHandler(this.signInButton_Click);
            //
            // usernameLabel
            //
            this.usernameLabel.AutoSize = true;
            this.usernameLabel.Location = new System.Drawing.Point(127, 12);
            this.usernameLabel.Name = "usernameLabel";
            this.usernameLabel.Size = new System.Drawing.Size(55, 13);
            this.usernameLabel.TabIndex = 3;
            this.usernameLabel.Text = "Username";
            //
            // passwordLabel
            //
            this.passwordLabel.AutoSize = true;
            this.passwordLabel.Location = new System.Drawing.Point(127, 51);
            this.passwordLabel.Name = "passwordLabel";
            this.passwordLabel.Size = new System.Drawing.Size(53, 13);
            this.passwordLabel.TabIndex = 4;
            this.passwordLabel.Text = "Password";
            //
            // logoPictureBox
            //
            this.logoPictureBox.Image = ((System.Drawing.Image)(resources.GetObject("logoPictureBox.Image")));
            this.logoPictureBox.Location = new System.Drawing.Point(12, 12);
            this.logoPictureBox.Name = "logoPictureBox";
            this.logoPictureBox.Size = new System.Drawing.Size(109, 75);
            this.logoPictureBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
            this.logoPictureBox.TabIndex = 5;
            this.logoPictureBox.TabStop = false;
            //
            // SignInForm
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(240, 141);
            this.Controls.Add(this.logoPictureBox);
            this.Controls.Add(this.passwordLabel);
            this.Controls.Add(this.usernameLabel);
            this.Controls.Add(this.signInButton);
            this.Controls.Add(this.passwordTextBox);
            this.Controls.Add(this.usernameTextBox);
            this.Name = "SignInForm";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.Text = "Sign in - MyLog.XYZ Account";
            ((System.ComponentModel.ISupportInitialize)(this.logoPictureBox)).EndInit();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.TextBox usernameTextBox;
        private System.Windows.Forms.TextBox passwordTextBox;
        private System.Windows.Forms.Button signInButton;
        private System.Windows.Forms.Label usernameLabel;
        private System.Windows.Forms.Label passwordLabel;
        private System.Windows.Forms.PictureBox logoPictureBox;
    }
}


text:
package com.spun.util.database;

import java.sql.ResultSet;
import java.sql.SQLException;
import com.spun.util.DatabaseUtils;
import com.spun.util.ObjectUtils;

public class SQLUtils
{
  /***********************************************************************/
  public static String createInSQLStatement(DatabaseObject from[])
  {
    from = (from == null) ? new DatabaseObject[0] : from;
    Integer[] array = new Integer[from.length];
    for (int i = 0; i < from.length; i++)
    {
      array[i] = from[i].getPkey();
    }
    return createInSQLStatement((Object[]) array);
  }
  /***********************************************************************/
  public static String createInSQLStatement(String values[])
  {
    return createInSQLStatement((Object[]) values);
  }
  /***********************************************************************/
  public static String createInSQLStatement(Object values[])
  {
    if (values == null || values.length == 0) { return "(null)"; }
    StringBuffer sql = new StringBuffer("(");
    for (int i = 0; i < values.length; i++)
    {
      sql.append(DatabaseUtils.formatNullableObject(values[i]));
      sql.append(", ");
    }
    sql.setLength(sql.length() - 2);
    sql.append(") ");
    return sql.toString();
  }
  /***********************************************************************/
  /**
   * Done via Reflection.
   * They should all be the same Type of object!
   * And the method signature should have empty arguments!
   **/
  public static String createInSQLStatement(Object from[], String methodName)
  {
    Object[] array = ObjectUtils.extractArray(from, methodName);
    return createInSQLStatement(array);
  }
  /***********************************************************************/
  public static String loadInSQLStatement(ResultSet rs) throws SQLException
  {
    StringBuffer sql = new StringBuffer("(");
    while (rs.next())
    {
      sql.append(DatabaseUtils.formatNullableObject(rs.getObject(1)));
      sql.append(", ");
    }
    if (sql.length() == 1) { return null; }
    sql.setLength(sql.length() - 2);
    sql.append(") ");
    return sql.toString();
  }
  /***********************************************************************/
  public static String createSQLBetween(String lowerValue, String betweenVariable, String upperValue)
  {
    return "(" + DatabaseUtils.formatNullableObject(lowerValue) + " <= " + betweenVariable + " AND " + betweenVariable + " < " + DatabaseUtils.formatNullableObject(upperValue) + ")";
  }
  /***********************************************************************/
  public static String compareBy(ColumnMetadata metadata, String alias, String compareBy, Object value)
  {
    String sql = null;
    if (value == null && "=".equals(compareBy))
    {
      sql = metadata.getNameWithPrefix(alias) + " IS NULL";
    }
    else if (value == null && "!=".equals(compareBy))
    {
      sql = metadata.getNameWithPrefix(alias) + " IS NOT NULL";
    }
    else
    {
      sql = metadata.getNameWithPrefix(alias) + " " + compareBy + " " + DatabaseUtils.formatNullableObject(value);
    }
    return sql;
  }
  /***********************************************************************/
  public static String compareBy(ColumnMetadata metadata, String alias, String compareBy, boolean value)
  {
    return metadata.getNameWithPrefix(alias) + " " + compareBy + " " + DatabaseUtils.formatBoolean(value);
  }
  /***********************************************************************/
  public static String compareByEquals(ColumnMetadata metadata, String alias, Object value)
  {
    return compareBy(metadata, alias, "=", value);
  }
  /***********************************************************************/
  public static String createInSQLStatement(ColumnMetadata metadata, String alias, Object[] values)
  {
    return createInSQLStatement(metadata, alias, false, values);
  }
  /***********************************************************************/
  public static String createInSQLStatement(ColumnMetadata metadata, String alias, boolean not, Object[] values)
  {
      String sql = null;
      String in = not ? " NOT IN " : " IN ";
      if (values == null)
      {
        sql = compareBy(metadata, alias,not ? "!=" : "=",  null);
      }
      else if (values.length == 1)
      {
        sql = compareBy(metadata, alias,not ? "!=" : "=", values[0]);
      }
      else if (values instanceof DatabaseObject[])
      {
        sql = metadata.getNameWithPrefix(alias) + in + createInSQLStatement((DatabaseObject[]) values);
      }
//      else if (values.length < 5)
//      {
//        return createOrOptimizedInSqlStatement(metadata, alias, not, values);
//      }
      else
      {
        sql = metadata.getNameWithPrefix(alias) + in + createInSQLStatement(values);
      }
      return sql;
  }
  /***********************************************************************/
  private static String createOrOptimizedInSqlStatement(ColumnMetadata metadata, String alias, boolean not, Object[] values)
  {
    StringBuffer buffer = new StringBuffer("(");
    String compare = not ? "!=" : "=";
    for (int i = 0; i < values.length; i++)
    {
      buffer.append(compareBy(metadata, alias,compare, values[i])).append(" OR ");
    }
    buffer.setLength(buffer.length() - 4);
    buffer.append(")");
    return buffer.toString();
  }
  /***********************************************************************/
  /***********************************************************************/
}


text:
var http = require('http');
var fs = require('fs')
var url = require('url')

require('./build') // build the bundles

var server = http.createServer(function (request, res) {
    try {
        var requestUrl = url.parse(request.url)
        var path = requestUrl.pathname

        if(path !== '/favicon.ico') {
            console.log("got request for: "+path)

            if(path === '/') {
                path = '/test/testStackinfo.html'
            }

            res.writeHead(200)
            res.write(fs.readFileSync(__dirname+path))
        }
    } catch(e) {
        console.log(e.message)
        res.writeHead(400)
    } finally {
        res.end()
    }
})

var port = 8100
server.listen(port)
console.log("listening on port "+port)


text:
import datetime
import decimal
import uuid
from functools import lru_cache
from itertools import chain

from django.conf import settings
from django.core.exceptions import FieldError
from django.db import DatabaseError, NotSupportedError, models
from django.db.backends.base.operations import BaseDatabaseOperations
from django.db.models.expressions import Col
from django.utils import timezone
from django.utils.dateparse import parse_date, parse_datetime, parse_time
from django.utils.duration import duration_microseconds
from django.utils.functional import cached_property

class DatabaseOperations(BaseDatabaseOperations):
    cast_char_field_without_max_length = 'text'
    cast_data_types = {
        'DateField': 'TEXT',
        'DateTimeField': 'TEXT',
    }
    explain_prefix = 'EXPLAIN QUERY PLAN'

    def bulk_batch_size(self, fields, objs):
        """
        SQLite has a compile-time default (SQLITE_LIMIT_VARIABLE_NUMBER) of
        999 variables per query.

        If there's only a single field to insert, the limit is 500
        (SQLITE_MAX_COMPOUND_SELECT).
        """
        if len(fields) == 1:
            return 500
        elif len(fields) > 1:
            return self.connection.features.max_query_params // len(fields)
        else:
            return len(objs)

    def check_expression_support(self, expression):
        bad_fields = (models.DateField, models.DateTimeField, models.TimeField)
        bad_aggregates = (models.Sum, models.Avg, models.Variance, models.StdDev)
        if isinstance(expression, bad_aggregates):
            for expr in expression.get_source_expressions():
                try:
                    output_field = expr.output_field
                except (AttributeError, FieldError):
                    # Not every subexpression has an output_field which is fine
                    # to ignore.
                    pass
                else:
                    if isinstance(output_field, bad_fields):
                        raise NotSupportedError(
                            'You cannot use Sum, Avg, StdDev, and Variance '
                            'aggregations on date/time fields in sqlite3 '
                            'since date/time is saved as text.'
                        )
        if (
            isinstance(expression, models.Aggregate) and
            expression.distinct and
            len(expression.source_expressions) > 1
        ):
            raise NotSupportedError(
                "SQLite doesn't support DISTINCT on aggregate functions "
                "accepting multiple arguments."
            )

    def date_extract_sql(self, lookup_type, field_name):
        """
        Support EXTRACT with a user-defined function django_date_extract()
        that's registered in connect(). Use single quotes because this is a
        string and could otherwise cause a collision with a field name.
        """
        return "django_date_extract('%s', %s)" % (lookup_type.lower(), field_name)

    def date_interval_sql(self, timedelta):
        return str(duration_microseconds(timedelta))

    def format_for_duration_arithmetic(self, sql):
        """Do nothing since formatting is handled in the custom function."""
        return sql

    def date_trunc_sql(self, lookup_type, field_name):
        return "django_date_trunc('%s', %s)" % (lookup_type.lower(), field_name)

    def time_trunc_sql(self, lookup_type, field_name):
        return "django_time_trunc('%s', %s)" % (lookup_type.lower(), field_name)

    def _convert_tznames_to_sql(self, tzname):
        if settings.USE_TZ:
            return "'%s'" % tzname, "'%s'" % self.connection.timezone_name
        return 'NULL', 'NULL'

    def datetime_cast_date_sql(self, field_name, tzname):
        return 'django_datetime_cast_date(%s, %s, %s)' % (
            field_name, *self._convert_tznames_to_sql(tzname),
        )

    def datetime_cast_time_sql(self, field_name, tzname):
        return 'django_datetime_cast_time(%s, %s, %s)' % (
            field_name, *self._convert_tznames_to_sql(tzname),
        )

    def datetime_extract_sql(self, lookup_type, field_name, tzname):
        return "django_datetime_extract('%s', %s, %s, %s)" % (
            lookup_type.lower(), field_name, *self._convert_tznames_to_sql(tzname),
        )

    def datetime_trunc_sql(self, lookup_type, field_name, tzname):
        return "django_datetime_trunc('%s', %s, %s, %s)" % (
            lookup_type.lower(), field_name, *self._convert_tznames_to_sql(tzname),
        )

    def time_extract_sql(self, lookup_type, field_name):
        return "django_time_extract('%s', %s)" % (lookup_type.lower(), field_name)

    def pk_default_value(self):
        return "NULL"

    def _quote_params_for_last_executed_query(self, params):
        """
        Only for last_executed_query! Don't use this to execute SQL queries!
        """
        # This function is limited both by SQLITE_LIMIT_VARIABLE_NUMBER (the
        # number of parameters, default = 999) and SQLITE_MAX_COLUMN (the
        # number of return values, default = 2000). Since Python's sqlite3
        # module doesn't expose the get_limit() C API, assume the default
        # limits are in effect and split the work in batches if needed.
        BATCH_SIZE = 999
        if len(params) > BATCH_SIZE:
            results = ()
            for index in range(0, len(params), BATCH_SIZE):
                chunk = params[index:index + BATCH_SIZE]
                results += self._quote_params_for_last_executed_query(chunk)
            return results

        sql = 'SELECT ' + ', '.join(['QUOTE(?)'] * len(params))
        # Bypass Django's wrappers and use the underlying sqlite3 connection
        # to avoid logging this query - it would trigger infinite recursion.
        cursor = self.connection.connection.cursor()
        # Native sqlite3 cursors cannot be used as context managers.
        try:
            return cursor.execute(sql, params).fetchone()
        finally:
            cursor.close()

    def last_executed_query(self, cursor, sql, params):
        # Python substitutes parameters in Modules/_sqlite/cursor.c with:
        # pysqlite_statement_bind_parameters(self->statement, parameters, allow_8bit_chars);
        # Unfortunately there is no way to reach self->statement from Python,
        # so we quote and substitute parameters manually.
        if params:
            if isinstance(params, (list, tuple)):
                params = self._quote_params_for_last_executed_query(params)
            else:
                values = tuple(params.values())
                values = self._quote_params_for_last_executed_query(values)
                params = dict(zip(params, values))
            return sql % params
        # For consistency with SQLiteCursorWrapper.execute(), just return sql
        # when there are no parameters. See #13648 and #17158.
        else:
            return sql

    def quote_name(self, name):
        if name.startswith('"') and name.endswith('"'):
            return name  # Quoting once is enough.
        return '"%s"' % name

    def no_limit_value(self):
        return -1

    def __references_graph(self, table_name):
        query = """
        WITH tables AS (
            SELECT %s name
            UNION
            SELECT sqlite_master.name
            FROM sqlite_master
            JOIN tables ON (sql REGEXP %s || tables.name || %s)
        ) SELECT name FROM tables;
        """
        params = (
            table_name,
            r'(?i)\s+references\s+("|\')?',
            r'("|\')?\s*\(',
        )
        with self.connection.cursor() as cursor:
            results = cursor.execute(query, params)
            return [row[0] for row in results.fetchall()]

    @cached_property
    def _references_graph(self):
        # 512 is large enough to fit the ~330 tables (as of this writing) in
        # Django's test suite.
        return lru_cache(maxsize=512)(self.__references_graph)

    def sql_flush(self, style, tables, sequences, allow_cascade=False):
        if tables and allow_cascade:
            # Simulate TRUNCATE CASCADE by recursively collecting the tables
            # referencing the tables to be flushed.
            tables = set(chain.from_iterable(self._references_graph(table) for table in tables))
        # Note: No requirement for reset of auto-incremented indices (cf. other
        # sql_flush() implementations). Just return SQL at this point
        return ['%s %s %s;' % (
            style.SQL_KEYWORD('DELETE'),
            style.SQL_KEYWORD('FROM'),
            style.SQL_FIELD(self.quote_name(table))
        ) for table in tables]

    def adapt_datetimefield_value(self, value):
        if value is None:
            return None

        # Expression values are adapted by the database.
        if hasattr(value, 'resolve_expression'):
            return value

        # SQLite doesn't support tz-aware datetimes
        if timezone.is_aware(value):
            if settings.USE_TZ:
                value = timezone.make_naive(value, self.connection.timezone)
            else:
                raise ValueError("SQLite backend does not support timezone-aware datetimes when USE_TZ is False.")

        return str(value)

    def adapt_timefield_value(self, value):
        if value is None:
            return None

        # Expression values are adapted by the database.
        if hasattr(value, 'resolve_expression'):
            return value

        # SQLite doesn't support tz-aware datetimes
        if timezone.is_aware(value):
            raise ValueError("SQLite backend does not support timezone-aware times.")

        return str(value)

    def get_db_converters(self, expression):
        converters = super().get_db_converters(expression)
        internal_type = expression.output_field.get_internal_type()
        if internal_type == 'DateTimeField':
            converters.append(self.convert_datetimefield_value)
        elif internal_type == 'DateField':
            converters.append(self.convert_datefield_value)
        elif internal_type == 'TimeField':
            converters.append(self.convert_timefield_value)
        elif internal_type == 'DecimalField':
            converters.append(self.get_decimalfield_converter(expression))
        elif internal_type == 'UUIDField':
            converters.append(self.convert_uuidfield_value)
        elif internal_type in ('NullBooleanField', 'BooleanField'):
            converters.append(self.convert_booleanfield_value)
        return converters

    def convert_datetimefield_value(self, value, expression, connection):
        if value is not None:
            if not isinstance(value, datetime.datetime):
                value = parse_datetime(value)
            if settings.USE_TZ and not timezone.is_aware(value):
                value = timezone.make_aware(value, self.connection.timezone)
        return value

    def convert_datefield_value(self, value, expression, connection):
        if value is not None:
            if not isinstance(value, datetime.date):
                value = parse_date(value)
        return value

    def convert_timefield_value(self, value, expression, connection):
        if value is not None:
            if not isinstance(value, datetime.time):
                value = parse_time(value)
        return value

    def get_decimalfield_converter(self, expression):
        # SQLite stores only 15 significant digits. Digits coming from
        # float inaccuracy must be removed.
        create_decimal = decimal.Context(prec=15).create_decimal_from_float
        if isinstance(expression, Col):
            quantize_value = decimal.Decimal(1).scaleb(-expression.output_field.decimal_places)

            def converter(value, expression, connection):
                if value is not None:
                    return create_decimal(value).quantize(quantize_value, context=expression.output_field.context)
        else:
            def converter(value, expression, connection):
                if value is not None:
                    return create_decimal(value)
        return converter

    def convert_uuidfield_value(self, value, expression, connection):
        if value is not None:
            value = uuid.UUID(value)
        return value

    def convert_booleanfield_value(self, value, expression, connection):
        return bool(value) if value in (1, 0) else value

    def bulk_insert_sql(self, fields, placeholder_rows):
        return " UNION ALL ".join(
            "SELECT %s" % ", ".join(row)
            for row in placeholder_rows
        )

    def combine_expression(self, connector, sub_expressions):
        # SQLite doesn't have a ^ operator, so use the user-defined POWER
        # function that's registered in connect().
        if connector == '^':
            return 'POWER(%s)' % ','.join(sub_expressions)
        elif connector == '#':
            return 'BITXOR(%s)' % ','.join(sub_expressions)
        return super().combine_expression(connector, sub_expressions)

    def combine_duration_expression(self, connector, sub_expressions):
        if connector not in ['+', '-']:
            raise DatabaseError('Invalid connector for timedelta: %s.' % connector)
        fn_params = ["'%s'" % connector] + sub_expressions
        if len(fn_params) > 3:
            raise ValueError('Too many params for timedelta operations.')
        return "django_format_dtdelta(%s)" % ', '.join(fn_params)

    def integer_field_range(self, internal_type):
        # SQLite doesn't enforce any integer constraints
        return (None, None)

    def subtract_temporals(self, internal_type, lhs, rhs):
        lhs_sql, lhs_params = lhs
        rhs_sql, rhs_params = rhs
        params = (*lhs_params, *rhs_params)
        if internal_type == 'TimeField':
            return 'django_time_diff(%s, %s)' % (lhs_sql, rhs_sql), params
        return 'django_timestamp_diff(%s, %s)' % (lhs_sql, rhs_sql), params

    def insert_statement(self, ignore_conflicts=False):
        return 'INSERT OR IGNORE INTO' if ignore_conflicts else super().insert_statement(ignore_conflicts)


text:
package io.yun.dao;

import io.unicall.dao.BaseDao;
import io.yun.entity.TYunMarketingEntity;
import org.apache.ibatis.annotations.Param;

import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 营销(活动)表
 *
 * @author zc
 * @email chao.zhou@unicall.net.cn
 * @date 2017-07-07 11:07:41
 */
public interface TYunMarketingDao extends BaseDao<TYunMarketingEntity> {

    List<Map<String,Integer>> queryStatus(Map<String, Object> params);

    void saveMerchandise(@Param(value = "marketingId")String marketingId, @Param(value = "merchandiseId")String merchandiseId);

    void deleteMerchandise(@Param(value = "marketingId")String marketingId, @Param(value = "merchandiseIds")Set<String> merchandiseIds);

    void deleteAllMerchandise(String marketingId);
}


text:
<!DOCTYPE HTML>

  <meta charset="utf-8">

  <title>Publications | ASD</title>
  <meta name="author" content="Another Software Developer">

  <meta name="description" content="Network programming">

  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

  <meta property="og:title" content="Publications"/>
  <meta property="og:site_name" content="ASD"/>

    <meta property="og:image" content="undefined"/>

    <link href="/favicon.png" rel="icon">

  <link rel="stylesheet" href="/css/themes/spacelab.css" media="screen" type="text/css">
  <link rel="stylesheet" href="/css/font-awesome.css" media="screen" type="text/css">
  <link rel="stylesheet" href="/css/style.css" media="screen" type="text/css">
  <link rel="stylesheet" href="/css/responsive.css" media="screen" type="text/css">
  <link rel="stylesheet" href="/css/highlight.css" media="screen" type="text/css">
  <link rel="stylesheet" href="/css/google-fonts.css" media="screen" type="text/css">
  <link rel="stylesheet" href="/css/custom.css" media="screen" type="text/css">

      <button type="button" class="navbar-header navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
	Toggle navigation

      </button>
       ASD

			  Works

			  Publications

			  Archives

			  About

 Publications

Here you can see a list of publications on other web-resources, blogs and thematic sites. Besides articles, there are few books, booklets which have been written by myself and were based on personal observations in specific topics.

English

    1. Angular.js recipes: viewing around - Little book which exposes the common principles of constructing the application architecture.

Russian

  © 2017 Another Software Developer

  ▲

<link rel="stylesheet" href="/fancybox/jquery.fancybox.css" media="screen" type="text/css">


text:
package zx.common.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class HelloServlet extends HttpServlet {

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	public void init(ServletConfig config) throws ServletException {
		super.init(config);

		config.getInitParameter("");
	}

	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		HttpSession ses = req.getSession();

		ServletContext appContext = super.getServletContext();

		//客户端跳转
//		resp.sendRedirect(req.getContextPath() + "/jsp/login/login_success.jsp");

		RequestDispatcher rd = req.getRequestDispatcher("/jsp/login/login_success.jsp");
		rd.forward(req, resp);
	}

	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		PrintWriter outPrintWriter = resp.getWriter();
		outPrintWriter.println(" 33 ff");
		outPrintWriter.close();

	}

}