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 ec.edu.espe.tvserver.service;

import ec.edu.espe.tvserver.dao.Peticion;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 *
 * @author Jonathan
 */
public class ServerClient extends Thread {

    private Socket socket;
    private BufferedReader in;
    private PrintWriter out;
    private String rq = "";
    private String nombreCliente;

    public ServerClient(Socket socket) {
        try {
            this.socket = socket;
            in = new BufferedReader(new InputStreamReader(
                    socket.getInputStream()));
            out = new PrintWriter(socket.getOutputStream(), true);
            nombreCliente = in.readLine() + socket.getRemoteSocketAddress();
            System.out.println("Conexión entrante: " + nombreCliente);
        } catch (IOException ex) {
            System.err.println("Error");
        }
    }

    @Override
    public void run() {
        try {
            while ((rq = in.readLine()) != null) {
                System.out.println(nombreCliente + " dice: " + rq);
                String rs = transaccion(rq);
                if ("OUT".equals(rq.substring(33))) {
                    System.out.println("Conexión terminada: " + nombreCliente);
                    out.println(rs);
                    out.flush();
                    break;
                }
                out.println(rs);
                out.flush();
            }
        } catch (IOException es) {
            System.out.println(es.getMessage());
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
            }
        }
    }

    public String transaccion(String rq) {
        String codigoSolicitante = rq.substring(8, 13); //código del usuario que hace la petición
        String tipoPeticion = rq.substring(13, 19); //código de la petición del cliente
        String sistemaConectado = rq.substring(2, 8); //sistema que hace la petición
        String rs = null; //respuesta que enviará el servidor
        String cuerpo = rq.substring(33); //cuerpo del mensaje de la petición
        String[] datosCuerpo = cuerpo.split("\\|");
        Peticion p = new Peticion();

        Date date = new Date();
        DateFormat hourdateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String fecha = hourdateFormat.format(date);

        switch (tipoPeticion) {
            case "LOGIN0": //autenticación
                boolean hizoLogin = p.login(datosCuerpo[0], datosCuerpo[1]);
                if (hizoLogin) {
                    String codigoUsuario = p.getCodigoUsuario(datosCuerpo[0], datosCuerpo[1]);
                    //comprar codigo con las tablas para ver el tipo de ususari permitido en sistema
                    if (sistemaConectado.equals("SERVIC")) {
                        if (p.verificarAutorizacion(codigoUsuario)) {
                            String nombre = p.getNombreUsuario(codigoUsuario, sistemaConectado);
                            StringBuilder codigoUsuarioCabecera = concatenarCeros(codigoUsuario);
                            rs = "RS" + sistemaConectado + codigoSolicitante + tipoPeticion + fecha
                                    + "ACCEPT" + codigoUsuarioCabecera.toString() + nombre;
                        } else {
                            rs = "RS" + sistemaConectado + codigoSolicitante + tipoPeticion + fecha + "DENIEDN";
                        }
                    } else {
                        if (p.verificarAutorizacionEm(codigoUsuario)) {
                            String nombre = p.getNombreUsuario(codigoUsuario, sistemaConectado);
                            StringBuilder codigoUsuarioCabecera = concatenarCeros(codigoUsuario);
                            rs = "RS" + sistemaConectado + codigoSolicitante + tipoPeticion + fecha
                                    + "ACCEPT" + codigoUsuarioCabecera.toString() + nombre;
                        } else {
                            rs = "RS" + sistemaConectado + codigoSolicitante + tipoPeticion + fecha + "DENIEDN";
                        }
                    }

                } else {
                    rs = "RS" + sistemaConectado + codigoSolicitante + tipoPeticion + fecha + "DENIED";
                }
                System.err.println("Servidor responde: " + rs);
                break;

            case "CERSES": //cerrar sesión
                rs = "RS" + sistemaConectado + codigoSolicitante + tipoPeticion + fecha + "ACCEPT";
                System.err.println("Servidor responde: " + rs);
                break;

            case "REGCLI": //registro de cliente
                String guardado = p.registrarCliente(datosCuerpo, date);
                rs = "RS" + sistemaConectado + codigoSolicitante + tipoPeticion + fecha;
                switch (guardado) {
                    case "A":
                        rs = rs + "ACCEPT";
                        break;
                    case "Y":
                        rs = rs + "DENIEDY";
                        break;
                    default:
                        rs = rs + "DENIED";
                        break;
                }
                System.err.println("Servidor responde: " + rs);
                break;

            case "CLICED": //consulta de cliente por cedula, devuelve planes del cliente
                String datos = p.buscarCedula(cuerpo);
                if (datos != null) {
                    rs = "RS" + sistemaConectado + codigoSolicitante + tipoPeticion + fecha
                            + "ACCEPT" + datos;
                } else {
                    rs = "RS" + sistemaConectado + codigoSolicitante + tipoPeticion + fecha + "DENIED";
                }
                System.err.println("Servidor responde: " + rs);
                break;

            case "REGEQU": //registro nuevo equipo
                boolean nuevoEquipo = p.registroNuevoEquipo(datosCuerpo[0], datosCuerpo[1]);
                if (nuevoEquipo) {
                    rs = "RS" + sistemaConectado + codigoSolicitante + tipoPeticion + fecha
                            + "ACCEPT";
                } else {
                    rs = "RS" + sistemaConectado + codigoSolicitante + tipoPeticion + fecha + "DENIED";
                }
                System.err.println("Servidor responde: " + rs);
                break;

            case "REGCAN": //registro nuevo canal
                String nuevoCanal = p.registroNuevoCanal(datosCuerpo);
                rs = "RS" + sistemaConectado + codigoSolicitante + tipoPeticion + fecha;
                switch (nuevoCanal) {
                    case "A":
                        rs = rs + "ACCEPT";
                        break;
                    case "Y":
                        rs = rs + "DENIEDY";
                        break;
                    default:
                        rs = rs + "DENIED";
                        break;
                }
                System.err.println("Servidor responde: " + rs);
                break;

            case "REGPAN": //registro nuevo plan
                boolean nuevoPlan = p.registroNuevoPlan(datosCuerpo);
                if (nuevoPlan) {
                    rs = "RS" + sistemaConectado + codigoSolicitante + tipoPeticion + fecha
                            + "ACCEPT";
                } else {
                    rs = "RS" + sistemaConectado + codigoSolicitante + tipoPeticion + fecha + "DENIED";
                }
                System.err.println("Servidor responde: " + rs);
                break;

            case "ACTCLI": //actualización de nombre de usuario, y contraseña
                String cambioDatos = p.actualizarUserPass(datosCuerpo);
                rs = "RS" + sistemaConectado + codigoSolicitante + tipoPeticion + fecha;
                switch (cambioDatos) {
                    case "A":
                        rs = rs + "ACCEPT";
                        break;
                    case "Y":
                        rs = rs + "DENIEDY";
                        break;
                    default:
                        rs = rs + "DENIED";
                        break;
                }
                System.err.println("Servidor responde: " + rs);
                break;

            case "PANCLI": //consulta los planes del cliente
                String planes = p.consultaPlanesCliente(cuerpo);
                if (planes != null) {
                    rs = "RS" + sistemaConectado + codigoSolicitante + tipoPeticion + fecha
                            + "ACCEPT" + planes;
                } else {
                    rs = "RS" + sistemaConectado + codigoSolicitante + tipoPeticion + fecha + "DENIED";
                }
                System.err.println("Servidor responde: " + rs);
                break;

            case "EQUCLI": //consulta los equipos por plan de cliente
                String equipos = p.consultarEquiposCliente(cuerpo);
                if (equipos != null) {
                    rs = "RS" + sistemaConectado + codigoSolicitante + tipoPeticion + fecha
                            + "ACCEPT" + equipos;
                } else {
                    rs = "RS" + sistemaConectado + codigoSolicitante + tipoPeticion + fecha + "DENIED";
                }
                System.err.println("Servidor responde: " + rs);
                break;

            case "CONCAN": //consulta todos los canales
                String canales = p.consultaCanales();
                if (canales != null) {
                    rs = "RS" + sistemaConectado + codigoSolicitante + tipoPeticion + fecha
                            + "ACCEPT" + canales;
                } else {
                    rs = "RS" + sistemaConectado + codigoSolicitante + tipoPeticion + fecha + "DENIED";
                }
                System.err.println("Servidor responde: " + rs);
                break;

            case "CONPLA": //consulta todos los canales
                String planes2 = p.consultaPlanes();
                if (planes2 != null) {
                    rs = "RS" + sistemaConectado + codigoSolicitante + tipoPeticion + fecha
                            + "ACCEPT" + planes2;
                } else {
                    rs = "RS" + sistemaConectado + codigoSolicitante + tipoPeticion + fecha + "DENIED";
                }
                System.err.println("Servidor responde: " + rs);
                break;

            case "CONEQU": //consulta todos los canales
                String equipos2 = p.consultaEquipos();
                if (equipos2 != null) {
                    rs = "RS" + sistemaConectado + codigoSolicitante + tipoPeticion + fecha
                            + "ACCEPT" + equipos2;
                } else {
                    rs = "RS" + sistemaConectado + codigoSolicitante + tipoPeticion + fecha + "DENIED";
                }
                System.err.println("Servidor responde: " + rs);
                break;

            case "DATPAN": //consulta datos plan
                String planes3 = p.consultarPlanes(cuerpo);
                if (planes3 != null) {
                    rs = "RS" + sistemaConectado + codigoSolicitante + tipoPeticion + fecha
                            + "ACCEPT" + planes3;
                } else {
                    rs = "RS" + sistemaConectado + codigoSolicitante + tipoPeticion + fecha + "DENIED";
                }
                System.err.println("Servidor responde: " + rs);
                break;

            case "DATEQU": //consulta datos plan
                String equipos3 = p.consultarEquipos(cuerpo);
                if (equipos3 != null) {
                    rs = "RS" + sistemaConectado + codigoSolicitante + tipoPeticion + fecha
                            + "ACCEPT" + equipos3;
                } else {
                    rs = "RS" + sistemaConectado + codigoSolicitante + tipoPeticion + fecha + "DENIED";
                }
                System.err.println("Servidor responde: " + rs);
                break;

            case "DATCAN": //consulta datos plan
                String canales2 = p.consultarCanales(cuerpo);
                if (canales2 != null) {
                    rs = "RS" + sistemaConectado + codigoSolicitante + tipoPeticion + fecha
                            + "ACCEPT" + canales2;
                } else {
                    rs = "RS" + sistemaConectado + codigoSolicitante + tipoPeticion + fecha + "DENIED";
                }
                System.err.println("Servidor responde: " + rs);
                break;

            case "NUEPLA": //registro nuevo plan del cliente
                String nuevoPlan2 = p.registroPlanCliente(datosCuerpo);
                if (nuevoPlan2 != null) {
                    rs = "RS" + sistemaConectado + codigoSolicitante + tipoPeticion + fecha
                            + "ACCEPT" + nuevoPlan2;
                } else {
                    rs = "RS" + sistemaConectado + codigoSolicitante + tipoPeticion + fecha + "DENIED";
                }
                System.err.println("Servidor responde: " + rs);
                break;

            case "CEDUID": //consulta datos plan
                String ced = p.consultarCedulas();
                if (ced != null) {
                    rs = "RS" + sistemaConectado + codigoSolicitante + tipoPeticion + fecha
                            + "ACCEPT" + ced;
                } else {
                    rs = "RS" + sistemaConectado + codigoSolicitante + tipoPeticion + fecha + "DENIED";
                }
                System.err.println("Servidor responde: " + rs);
                break;

            case "CONPAG": //consulta datos plan
                String pagos = p.consultarFormasPago();
                if (pagos != null) {
                    rs = "RS" + sistemaConectado + codigoSolicitante + tipoPeticion + fecha
                            + "ACCEPT" + pagos;
                } else {
                    rs = "RS" + sistemaConectado + codigoSolicitante + tipoPeticion + fecha + "DENIED";
                }
                System.err.println("Servidor responde: " + rs);
                break;

            case "CONTOT": //pago de la factura
                String total = p.totalPago(cuerpo);
                if (total != null) {
                    rs = "RS" + sistemaConectado + codigoSolicitante + tipoPeticion + fecha
                            + "ACCEPT" + total;
                } else {
                    rs = "RS" + sistemaConectado + codigoSolicitante + tipoPeticion + fecha + "DENIED";
                }
                System.err.println("Servidor responde: " + rs);
                break;

            case "SERTEC": //registro nuevo plan
                boolean nuevoSoport = p.registroNuevoSoporte(datosCuerpo);
                if (nuevoSoport) {
                    rs = "RS" + sistemaConectado + codigoSolicitante + tipoPeticion + fecha
                            + "ACCEPT";
                } else {
                    rs = "RS" + sistemaConectado + codigoSolicitante + tipoPeticion + fecha + "DENIED";
                }
                System.err.println("Servidor responde: " + rs);
                break;

            case "CONADI": //consulta todos los servicios adicionales
                String adicional = p.consultaSerAdi();
                if (adicional != null) {
                    rs = "RS" + sistemaConectado + codigoSolicitante + tipoPeticion + fecha
                            + "ACCEPT" + adicional;
                } else {
                    rs = "RS" + sistemaConectado + codigoSolicitante + tipoPeticion + fecha + "DENIED";
                }
                System.err.println("Servidor responde: " + rs);
                break;

            case "CONPRE": //consulta todos los canales especial (premium)
                String canalespre = p.consultaCanalesPremium();
                if (canalespre != null) {
                    rs = "RS" + sistemaConectado + codigoSolicitante + tipoPeticion + fecha
                            + "ACCEPT" + canalespre;
                } else {
                    rs = "RS" + sistemaConectado + codigoSolicitante + tipoPeticion + fecha + "DENIED";
                }
                System.err.println("Servidor responde: " + rs);
                break;

            case "PAGFAC": //registro nuevo plan del cliente
                boolean nuevoPago = p.registroPagoCliente(datosCuerpo);
                if (nuevoPago) {
                    rs = "RS" + sistemaConectado + codigoSolicitante + tipoPeticion + fecha
                            + "ACCEPT";
                } else {
                    rs = "RS" + sistemaConectado + codigoSolicitante + tipoPeticion + fecha + "DENIED";
                }
                System.err.println("Servidor responde: " + rs);
                break;

            case "REGSOP": //registro nuevo tipo de servicio tecnico
                boolean nuevoServicio = p.registroNuevoServicioTec(datosCuerpo[0], datosCuerpo[1]);
                if (nuevoServicio) {
                    rs = "RS" + sistemaConectado + codigoSolicitante + tipoPeticion + fecha
                            + "ACCEPT";
                } else {
                    rs = "RS" + sistemaConectado + codigoSolicitante + tipoPeticion + fecha + "DENIED";
                }
                System.err.println("Servidor responde: " + rs);
                break;

            case "CLICOD": //consulta de cliente por cedula, devuelve planes del cliente
                String datos2 = p.buscarCodigoCliente(cuerpo);
                if (datos2 != null) {
                    rs = "RS" + sistemaConectado + codigoSolicitante + tipoPeticion + fecha
                            + "ACCEPT" + datos2;
                } else {
                    rs = "RS" + sistemaConectado + codigoSolicitante + tipoPeticion + fecha + "DENIED";
                }
                System.err.println("Servidor responde: " + rs);
                break;

            case "FACCON": //consulta de de facturas por contrato de cliente
                String datos3 = p.buscarFacturasPorContrato(cuerpo);
                if (datos3 != null) {
                    rs = "RS" + sistemaConectado + codigoSolicitante + tipoPeticion + fecha
                            + "ACCEPT" + datos3;
                } else {
                    rs = "RS" + sistemaConectado + codigoSolicitante + tipoPeticion + fecha + "DENIED";
                }
                System.err.println("Servidor responde: " + rs);
                break;

            case "DATFAC": //consulta de datos de la factura
                String datos4 = p.buscarDatosFactura(cuerpo);
                if (datos4 != null) {
                    rs = "RS" + sistemaConectado + codigoSolicitante + tipoPeticion + fecha
                            + "ACCEPT" + datos4;
                } else {
                    rs = "RS" + sistemaConectado + codigoSolicitante + tipoPeticion + fecha + "DENIED";
                }
                System.err.println("Servidor responde: " + rs);
                break;
        }

        return rs;
    }

    public StringBuilder concatenarCeros(String code) {
        char[] arrayChar = code.toCharArray();
        int cont = arrayChar.length;
        StringBuilder sb = new StringBuilder();

        while (sb.length() < 5 - cont) {
            sb.append("0");
        }

        return sb.append(code);
    }
}


text:
using System.Collections.Generic;
using System.Linq;
using Framework.Models;

namespace Framework
{
    using System.Security;
    using System.Web.Http.Controllers;
    using System.Web.Routing;

    public static class ApiRouteExtensions
    {

        public static IEnumerable<RouteModel> ToRouteModel(this IEnumerable<RouteBase> routes)
        {
            return routes.Select(BuildModel)
                .GroupBy(r => r.Url).Select(x =>
                    new RouteModel() {
                        Url = x.Key,
                        Methods = x.SelectMany(y => y.Methods).Distinct().ToList()
            });
        }

        private static RouteModel BuildModel(RouteBase routeBase)
        {
            RouteModel model = new RouteModel();
            Route route = routeBase as Route;

            if (route != null)
            {
                model.Url = route.Url;

                List<string> methods = new List<string>();
                if (route.DataTokens != null)
                {
                    object obj;
                    if (route.DataTokens.TryGetValue("actions", out obj))
                    {
                        ReflectedHttpActionDescriptor[] descriptors = obj as ReflectedHttpActionDescriptor[];

                        if (descriptors != null)
                        {
                            foreach (var descriptor in descriptors)
                            {
                                if (descriptor.SupportedHttpMethods != null)
                                {
                                    methods.AddRange(descriptor.SupportedHttpMethods.Select(x => x.Method));
                                }
                            }
                        }
                    }

                    if (route.DataTokens.TryGetValue("action", out obj))
                    {
                        ReflectedHttpActionDescriptor[] descriptors = obj as ReflectedHttpActionDescriptor[];

                        if (descriptors != null)
                        {
                            foreach (var descriptor in descriptors)
                            {
                                if (descriptor.SupportedHttpMethods != null)
                                {
                                    methods.AddRange(descriptor.SupportedHttpMethods.Select(x => x.Method));
                                }
                            }
                        }
                    }
                }

                model.Methods = methods;
            }

            return model;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
module.exports = {
    init: init
};

function init(action, utils, config) {
    var options = {
        name: 'charcount',
        help: 'Usage: !charcount some message. Counts the number of characters and words in the message',
        help_on_empty: true
    };

    action(options, charcount);
}

function charcount(bot, from, to, text, message, utils, config) {
    var wordCount = 0;
    text.split(' ').forEach((word) => {
        if(word.trim()) wordCount++;
    });

    bot.sayDirect(from, to, 'Character count: ' + text.length + '. Word count: ' + wordCount);
}


text:
cask :v1 => 'pycharm-ce' do
  version '4.0.6'
  sha256 '9f70338eb6dc45071f11cb3ac7bc11cd7191df8d9f8f84fd31903d2c8daa6a72'

  url "https://download.jetbrains.com/python/pycharm-community-#{version}.dmg"
  name 'PyCharm'
  name 'PyCharm Community Edition'
  name 'PyCharm CE'
  homepage 'http://www.jetbrains.com/pycharm'
  license :apache

  app 'PyCharm CE.app'

  caveats <<-EOS.undent
    #{token} requires Java 6 like any other IntelliJ-based IDE.
    You can install it with

      brew cask install caskroom/homebrew-versions/java6

    The vendor (JetBrains) doesn't support newer versions of Java (yet)
    due to several critical issues, see details at
    https://intellij-support.jetbrains.com/entries/27854363
  EOS
end


text:
package voldemort.serialization.json;

import java.io.IOException;
import java.io.Writer;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Writes JSON Objects as String recognized by {@link JsonReader}
 *
 *
 */
public class JsonWriter {

    private final Writer writer;

    public JsonWriter(Writer writer) {
        this.writer = writer;
    }

    @SuppressWarnings("unchecked")
    public void write(Object o) {

        try {
            if(null == o) {
                writer.write("null");
            } else if(o instanceof Map) {
                writeMap((Map<String, Object>) o);
            } else if(o instanceof List) {
                writeList((List<Object>) o);
            } else if(o instanceof Date) {
                writeDate((Date) o);
            } else if(o instanceof String) {
                writer.write('"');
                writer.write((String) o);
                writer.write('"');
            } else {
                writer.write(o.toString());
            }
        } catch(Exception e) {
            throw new RuntimeException("JsonWriter failed to write Object(" + o + ")  as String", e);
        }
    }

    public void writeMap(Map<String, Object> values) throws IOException {
        writer.write('{');
        Set<Map.Entry<String, Object>> entrySet = values.entrySet();
        int index = 0;
        for(Map.Entry<String, Object> entry: entrySet) {
            writer.write('"');
            writer.write(entry.getKey());
            writer.write('"');

            writer.write(':');

            // write Object
            write(entry.getValue());

            if(++index < entrySet.size()) {
                writer.write(", ");
            }
        }
        writer.write('}');
    }

    public void writeList(List<Object> list) throws IOException {
        writer.write('[');
        int index = 0;
        for(Object entry: list) {
            write(entry);

            if(++index < list.size()) {
                writer.write(", ");

            }
        }
        writer.write(']');
    }

    public void writeDate(Date date) throws IOException {
        writer.write("" + date.getTime());
    }
}


text:
package main

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"os"
	"sync"
	"time"
)

const (
	topStoriesUrl = "https://hacker-news.firebaseio.com/v0/topstories.json"
	itemUrl       = "https://hacker-news.firebaseio.com/v0/item/%d.json"

	runInterval   = 15 * time.Minute // Interval at which we fetch the items
	maxTopStories = 150              // Maximum top stories fetched per cycle
)

var (
	config = loadConfig()
	Logger = log.New(os.Stdout, "  ", log.LstdFlags|log.Lshortfile)
)

func main() {
	initDb() // Will panic on failure
	setupHandlers()

	// set up a goroutine that will periodically call run()
	go func() {
		run()
		ticker := time.NewTicker(runInterval)
		for {
			select {
			case <-ticker.C:
				run() // TODO: Consider executing run() in a separate goroutine
			}
		}
	}()

	Logger.Printf("Listening on %s...\n", config.Addr)
	Logger.Fatal(http.ListenAndServe(config.Addr, nil))
}

// Item represents a HN story.
type Item struct {
	By    string // unused
	Id    int
	Kids  []int64 // unused
	Score int
	Time  int64 // unused
	Title string
	Type  string // unused
	Url   string
}

// run fetches the top HN stories and sends notifications according to each user's score threshold.
// The channel fan-in approach is fully inspired by the example in http://blog.golang.org/pipelines.
func run() {
	Logger.Println("Notifier started...")
	t0 := time.Now()
	db := newDatabase()
	defer db.close()

	// Single http.Client concurrently used by all goroutines
	client := &http.Client{}

	ids, err := getTopStories(client)
	if err != nil {
		Logger.Println(err)
		return // Just wait till the next cycle.
	}
	if len(ids) > maxTopStories {
		ids = ids[:maxTopStories]
	}

	// fetcher runs a goroutine to fetch the item. Once completed, the result
	// will be inserted in the returned channel, and the channel closed.
	fetchItem := func(id int) chan Item {
		out := make(chan Item)
		go func() {
			item, err := getItem(client, id)
			if err != nil {
				Logger.Println(err)
			} else if id == item.Id { // Guard against null responses, coerced into an empty Item
				out <- item
			}
			close(out)
		}()
		return out
	}

	// Fetch items concurrently. Each channel will just hold one item.
	cs := make([]chan Item, len(ids))
	for i, id := range ids {
		cs[i] = fetchItem(id)
	}

	for item := range merge(cs...) {
		if users := db.findUsersForItem(item); len(users) > 0 {
			emails := make([]string, len(users)) // Create a slice with all the recipients for this item.
			for i, u := range users {
				emails[i] = u.Email
			}

			// Send the email.
			if err := sendItem(item.Id, item.Title, item.Url, emails); err != nil {
				Logger.Println("Error sending mail: ", err)
				continue
			}
			Logger.Printf("Item %d sent to users: %v\n", item.Id, emails)

			// Update items set.
			if err := db.updateSentItems(emails, item.Id); err != nil {
				Logger.Println("Error: updateItems() - ", err)
			}
		}
	}

	Logger.Printf("Notifier finished - Total time: %s\n", time.Now().Sub(t0).String())
}

// getTopStories reads the top stories IDs from the API.
func getTopStories(client *http.Client) ([]int, error) {
	req, err := http.NewRequest("GET", topStoriesUrl, nil)
	if err != nil {
		return nil, err
	}
	req.Close = true

	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	res := struct {
		Items []int
	}{}

	err = json.NewDecoder(resp.Body).Decode(&res.Items)
	return res.Items, err
}

// getItem reads the HN story item from the API.
func getItem(client *http.Client, id int) (item Item, err error) {
	var req *http.Request
	req, err = http.NewRequest("GET", fmt.Sprintf(itemUrl, id), nil)
	if err != nil {
		return
	}
	req.Close = true

	var resp *http.Response
	resp, err = client.Do(req)
	if err != nil {
		return
	}
	defer resp.Body.Close()

	err = json.NewDecoder(resp.Body).Decode(&item)
	return item, err
}

// merge converts a list of channels to a single channel.
func merge(cs ...chan Item) <-chan Item {
	var wg sync.WaitGroup
	out := make(chan Item)

	// Start an output goroutine for each input channel in cs. output
	// copies values from c to out until c is closed, then calls wg.Done.
	output := func(c <-chan Item) {
		for n := range c {
			out <- n
		}
		wg.Done()
	}
	wg.Add(len(cs))
	for _, c := range cs {
		go output(c)
	}

	// Start a goroutine to close out once all the output goroutines are
	// done. This must start after the wg.Add call.
	go func() {
		wg.Wait()
		close(out)
	}()
	return out
}


text:
/**
 * Example 117 - A Generic Method in a Generic Class
 *
 * TODO: Senthil Kumaran - Implement a complete Linked List
 * http://www2.hawaii.edu/~esb/2008fall.ics211/LinkedList.java.html
 * http://www.csie.ntu.edu.tw/~cyy/courses/oop/13summer/chap15java5th.pdf
 *
 */

import java.util.Iterator;

interface MyList<T> extends Iterable<T> {
    int getCount(); // Number of elements
    T get(int i);   // Get element at index i
    void set(int i, T item);    // Set element at index i
    void add(T item);   // Add element at end
    void insert(int i, T item); // Insert element at index i
    void removeAt(int i);   // Remove element at index i
    <U> MyList<U> map(Mapper<T, U> f); // Map f over all elements
}

interface Mapper<A, R> {
    R call(A x);
}

class MyLinkedList<T> implements MyList<T> {

    protected int size; // Number of elements in the
    protected Node<T> first, last;

    protected static class Node<U> {
        public Node<U> prev, next;
        public U item;

        Node(U item) {
            this.item = item;
        }

    }

    public MyLinkedList() {
        first = last = null;
        size = 0;
    }

    public MyLinkedList(T... arr) { }

    @Override
    public int getCount() {
        return 0;
    }

    @Override
    public T get(int i) {
        return null;
    }

    @Override
    public void set(int i, T item) {

    }

    public void add(T item) {
        insert(size, item);
    }

    public void insert(int i, T item) {

    }

    @Override
    public void removeAt(int i) {

    }

    /** Map f over all elements */
    @Override
    public <U> MyList<U> map(Mapper<T, U> f) {
        MyLinkedList<U> res = new MyLinkedList<U>();
        for(T x: this)
            res.add(f.call(x));
        return res;
    }

    public boolean equals(Object that) {
        return equals((MyList<T>)that);
    }

    public boolean equals(MyList<T> that) {
        return this == that;
    }

    @Override
    public Iterator<T> iterator() {
        return null;
    }
}

class GenericMethodGenericClass {
    public static void main(String[] args) {
        MyLinkedList.Node<String> item = new MyLinkedList.Node<String>("Senthil");
        MyLinkedList<MyLinkedList.Node> linkedList = new MyLinkedList<MyLinkedList.Node>();

    }
}


text:
package com.temple.geo.web.converter;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

import com.temple.geo.model.geonames.Feature;

/**
 * TODOC
 * @author flominou
 */
public class FeatureConverter implements Converter {

	@Override
	public Object getAsObject(FacesContext arg0, UIComponent arg1, String arg2) {
		return Feature.valueOf(arg2);
	}

	@Override
	public String getAsString(FacesContext arg0, UIComponent arg1, Object arg2) {
		return arg2.toString();
	}
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Movie Ticket Reservation Registration Form</title>
    <meta name="keywords" content="example, JavaScript Form Validation, Sample registration form" />
    <meta name="description" content="This document is an example of JavaScript Form Validation using a sample registration form. " />
    <link rel='stylesheet' href='js-form-validation.css' type='text/css' />

<text id="regform">|Registration Form|

Use tab keys to move from one input field to the next.

    <form name='registration' onSubmit="return formValidation();">

Username

<input type="text" name="userid" size="12" />

Password

<input type="password" name="passid" size="12" />

Full Name

<input type="text" name="username" size="50" />

Home Address

<input type="text" name="address" size="50" />

ZIP Code

<input type="text" name="zip" />

E-mail Address

<input type="text" name="email" size="50" />

Gender

<input type="radio" name="msex" value="Male" />Male

<input type="radio" name="fsex" value="Female" />Female

Language

<input type="checkbox" name="en" value="en" checked />English

<input type="checkbox" name="nonen" value="noen" />Non English

<input id="sub" type="submit" name="submit" value="Submit" />

	Copyright © 2015 Cruz-Mesina Movie Ticket Reservation

    </form>


text:
using System;
namespace YouDaoAssistant
{
    public class Word : IComparable
    {
        public string WordName
        {
            get;
            set;
        }

        public string Meaning
        {
            get;
            set;
        }

        public int CompareTo(object obj)
        {
            Word word = obj as Word;
            return string.CompareOrdinal(WordName, word.WordName);
        }
    }
}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
Agaricus cepistipes var. cretaceus (Bull.) Pers., 1801

### Remarks
null


text:
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>6 | Alberto Parmiggiani</title>
    <link>https://miggia.github.io/it/publication-type/6/</link>
      <atom:link href="https://miggia.github.io/it/publication-type/6/index.xml" rel="self" type="application/rss+xml" />
    <description>6</description>
    <generator>Wowchemy (https://wowchemy.com)</generator><language>it</language><lastBuildDate>Wed, 01 Jan 2020 00:00:00 +0000</lastBuildDate>
    <image>
      <url>https://miggia.github.io/media/icon_hu0b7a4cb9992c9ac0e91bd28ffd38dd00_9727_512x512_fill_lanczos_center_2.png</url>
      <title>6</title>
      <link>https://miggia.github.io/it/publication-type/6/</link>
    </image>

    <item>
      <title>Tactile Sensors</title>
      <link>https://miggia.github.io/it/publication/parmiggiani-20-tactile/</link>
      <pubDate>Wed, 01 Jan 2020 00:00:00 +0000</pubDate>
      <guid>https://miggia.github.io/it/publication/parmiggiani-20-tactile/</guid>
      <description></description>
    </item>

    <item>
      <title>Design and Control of a Passive Noise Rejecting Variable Stiffness Actuator</title>
      <link>https://miggia.github.io/it/publication/fiorio-19-design/</link>
      <pubDate>Tue, 01 Jan 2019 00:00:00 +0000</pubDate>
      <guid>https://miggia.github.io/it/publication/fiorio-19-design/</guid>
      <description></description>
    </item>

    <item>
      <title>Comparison of Workspace Analysis for Different Spherical Parallel Mechanisms</title>
      <link>https://miggia.github.io/it/publication/shah-18-comparison/</link>
      <pubDate>Mon, 01 Jan 2018 00:00:00 +0000</pubDate>
      <guid>https://miggia.github.io/it/publication/shah-18-comparison/</guid>
      <description></description>
    </item>

    <item>
      <title>Sensorimotor Coordination in a Humanoid Robot: Building Intelligence on the iCub</title>
      <link>https://miggia.github.io/it/publication/natale-14-sensorimotor/</link>
      <pubDate>Wed, 01 Jan 2014 00:00:00 +0000</pubDate>
      <guid>https://miggia.github.io/it/publication/natale-14-sensorimotor/</guid>
      <description></description>
    </item>

  </channel>
</rss>


text:
define([
  'lodash',
  'backbone',
  'models/song'
], function(_, Backbone, SongModel) {
	var SongsCollection = Backbone.Collection.extend({
	    defaults: {
	      songs: []
	    },

	    model: SongModel,

	    url: function() {
	    	return '/album/getSongs';
	    },

	    initialize: function(){
	    	console.log("SongsCollection init...");
	    }
	});

	return SongsCollection;
});


text:
package de.i3mainz.ls.sparql;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import de.i3mainz.ls.Config.Config;
import de.i3mainz.ls.rdfutils.SesameConnect;
import de.i3mainz.ls.rdfutils.exceptions.Logging;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.simple.JSONObject;

/**
 * SERVLET send a log triple to the triplestore
 *
 * @author Florian Thiery M.Sc.
 * @author i3mainz - Institute for Spatial Information and Surveying Technology
 * @version 18.02.2015
 */
public class InputLog extends HttpServlet {

	protected void processRequest(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException, NullPointerException {
		PrintWriter out = response.getWriter();
		try {
			String user = null;
			if (request.getParameter("user") != null) {
				user = request.getParameter("user");
			}
			if (user == null) {
				throw new NullPointerException();
			}
			// GET DATE
			Calendar cal = Calendar.getInstance();
			Date time = cal.getTime();
			DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
			String d = formatter.format(time);
			// SEND INPUT
			String update = "INSERT DATA { "
					+ Config.Instance("log", d, true) + " "
					+ Config.getPrefixItemOfOntology("ls", "login", true) + " "
					+ "\"" + user + "\" . }";
			SesameConnect.SPARQLupdate("labelingsystem", update);
			// OUTPUT
			JSONObject jsonobj_query = new JSONObject(); // {}
			jsonobj_query.put("logged", d);
			// pretty print JSON output (Gson)
			Gson gson = new GsonBuilder().setPrettyPrinting().create();
			out.print(gson.toJson(jsonobj_query));
			response.setStatus(200);
		} catch (Exception e) {
			response.setStatus(500);
			out.print(Logging.getMessageJSON(e, getClass().getName()));
		} finally {
			response.setContentType("application/json;charset=UTF-8");
			response.setHeader("Access-Control-Allow-Origin", "*");
			response.setCharacterEncoding("UTF-8");
			out.close();
		}
	}

	// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
	/**
	 * Handles the HTTP POST method.
	 *
	 * @param request servlet request
	 * @param response servlet response
	 * @throws ServletException if a servlet-specific error occurs
	 * @throws IOException if an I/O error occurs
	 */
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		processRequest(request, response);
	}

	/**
	 * Returns a short description of the servlet.
	 *
	 * @return a String containing servlet description
	 */
	@Override
	public String getServletInfo() {
		return "Short description";
	}// </editor-fold>

}


text:
'use strict'
/* global describe, it */
const assert = require('assert')
const supertest = require('supertest')
const _ = require('lodash')
const discounts = require('../../../fixtures/discounts')

describe('Admin User DiscountController', () => {
  let adminUser, userID, customerID, discountID

  before((done) => {

    adminUser = supertest.agent(global.app.packs.express.server)
    // Login as Admin
    adminUser
      .post('/auth/local')
      .set('Accept', 'application/json') //set header for this test
      .send({username: 'admin', password: 'admin1234'})
      .expect(200)
      .end((err, res) => {
        assert.ok(res.body.user.id)
        assert.ok(res.body.user.current_customer_id)
        userID = res.body.user.id
        customerID = res.body.user.current_customer_id
        done(err)
      })
  })
  it('should exist', () => {
    assert(global.app.api.controllers['DiscountController'])
  })
  it('should create a discount', (done) => {
    const discount = discounts[0]
    adminUser
      .post('/discount')
      .send(discount)
      .expect(200)
      .end((err, res) => {
        discountID = res.body.id
        assert.ok(res.body)
        assert.equal(res.body.name, discount.name)
        assert.equal(res.body.description, discount.description)
        assert.equal(res.body.code, discount.code)
        assert.equal(res.body.discount_type, discount.discount_type)
        assert.equal(res.body.discount_rate, discount.discount_rate)
        assert.equal(res.body.status, discount.status)
        assert.equal(res.body.minimum_order_amount, discount.minimum_order_amount)
        assert.equal(res.body.usage_limit, discount.usage_limit)
        assert.equal(res.body.applies_compound, true)

        done(err)
      })
  })
  it('should update a discount', (done) => {
    const discount = discounts[0]

    adminUser
      .post(`/discount/${discountID}`)
      .send({
        applies_compound: false
      })
      .expect(200)
      .end((err, res) => {
        // console.log('Admin User DiscountController',res.body)
        assert.ok(res.body)
        assert.equal(res.body.name, discount.name)
        assert.equal(res.body.description, discount.description)
        assert.equal(res.body.code, discount.code)
        assert.equal(res.body.discount_type, discount.discount_type)
        assert.equal(res.body.discount_rate, discount.discount_rate)
        assert.equal(res.body.status, discount.status)
        assert.equal(res.body.minimum_order_amount, discount.minimum_order_amount)
        assert.equal(res.body.usage_limit, discount.usage_limit)
        assert.equal(res.body.applies_compound, false)
        done(err)
      })
  })
  it('should destroy a discount', (done) => {
    const discount = discounts[0]

    adminUser
      .del(`/discount/${discountID}`)
      .expect(200)
      .end((err, res) => {
        // console.log('Admin User DiscountController',res.body)
        assert.equal(res.body.name, discount.name)
        assert.equal(res.body.description, discount.description)
        assert.equal(res.body.code, discount.code)
        assert.equal(res.body.discount_type, discount.discount_type)
        assert.equal(res.body.discount_rate, discount.discount_rate)
        assert.equal(res.body.status, discount.status)
        assert.equal(res.body.minimum_order_amount, discount.minimum_order_amount)
        assert.equal(res.body.usage_limit, discount.usage_limit)
        assert.equal(res.body.applies_compound, false)
        done(err)
      })
  })
  it('should get discounts', (done) => {
    adminUser
      .get('/discounts')
      .expect(200)
      .end((err, res) => {
        assert.ok(res.headers['x-pagination-total'])
        assert.ok(res.headers['x-pagination-pages'])
        assert.ok(res.headers['x-pagination-page'])
        assert.ok(res.headers['x-pagination-limit'])
        assert.ok(res.headers['x-pagination-offset'])
        assert.ok(res.headers['x-pagination-sort'])

        assert.equal(_.isNumber(parseInt(res.headers['x-pagination-total'])), true)
        assert.equal(_.isNumber(parseInt(res.headers['x-pagination-offset'])), true)
        assert.equal(_.isNumber(parseInt(res.headers['x-pagination-limit'])), true)
        assert.equal(_.isNumber(parseInt(res.headers['x-pagination-page'])), true)
        assert.equal(_.isNumber(parseInt(res.headers['x-pagination-pages'])), true)

        assert.ok(res.body)
        done(err)
      })
  })
  it('should create a discount without any applicable items', (done) => {
    const discount = discounts[1]
    adminUser
      .post('/discount')
      .send(discount)
      .expect(200)
      .end((err, res) => {
        discountID = res.body.id
        assert.ok(res.body)
        assert.equal(res.body.name, discount.name)
        assert.equal(res.body.description, discount.description)
        assert.equal(res.body.code, discount.code)
        assert.equal(res.body.discount_type, discount.discount_type)
        assert.equal(res.body.discount_rate, discount.discount_rate)
        assert.equal(res.body.status, discount.status)
        assert.equal(res.body.minimum_order_amount, discount.minimum_order_amount)
        assert.equal(res.body.usage_limit, discount.usage_limit)
        assert.equal(res.body.applies_compound, true)

        done(err)
      })
  })
  it('should add product to discount', (done) => {
    const discount = discounts[1]

    adminUser
      .post(`/discount/${discountID}/product/1`)
      .expect(200)
      .end((err, res) => {
        assert.ok(res.body)
        done(err)
      })
  })
  it('should get discount\'s products', (done) => {
    adminUser
      .get(`/discount/${discountID}/products`)
      .expect(200)
      .end((err, res) => {
        assert.ok(res.headers['x-pagination-total'])
        assert.ok(res.headers['x-pagination-pages'])
        assert.ok(res.headers['x-pagination-page'])
        assert.ok(res.headers['x-pagination-limit'])
        assert.ok(res.headers['x-pagination-offset'])
        assert.ok(res.headers['x-pagination-sort'])

        assert.equal(_.isNumber(parseInt(res.headers['x-pagination-total'])), true)
        assert.equal(_.isNumber(parseInt(res.headers['x-pagination-offset'])), true)
        assert.equal(_.isNumber(parseInt(res.headers['x-pagination-limit'])), true)
        assert.equal(_.isNumber(parseInt(res.headers['x-pagination-page'])), true)
        assert.equal(_.isNumber(parseInt(res.headers['x-pagination-pages'])), true)
        assert.ok(res.body)
        done(err)
      })
  })
  it('should remove product from discount', (done) => {
    const discount = discounts[1]

    adminUser
      .del(`/discount/${discountID}/product/1`)
      .expect(200)
      .end((err, res) => {
        assert.ok(res.body)
        done(err)
      })
  })

  it('should add customer to discount', (done) => {
    const discount = discounts[1]

    adminUser
      .post(`/discount/${discountID}/customer/1`)
      .expect(200)
      .end((err, res) => {
        assert.ok(res.body)
        done(err)
      })
  })
  it('should get discount\'s customers', (done) => {
    adminUser
      .get(`/discount/${discountID}/customers`)
      .expect(200)
      .end((err, res) => {
        assert.ok(res.headers['x-pagination-total'])
        assert.ok(res.headers['x-pagination-pages'])
        assert.ok(res.headers['x-pagination-page'])
        assert.ok(res.headers['x-pagination-limit'])
        assert.ok(res.headers['x-pagination-offset'])
        assert.ok(res.headers['x-pagination-sort'])

        assert.equal(_.isNumber(parseInt(res.headers['x-pagination-total'])), true)
        assert.equal(_.isNumber(parseInt(res.headers['x-pagination-offset'])), true)
        assert.equal(_.isNumber(parseInt(res.headers['x-pagination-limit'])), true)
        assert.equal(_.isNumber(parseInt(res.headers['x-pagination-page'])), true)
        assert.equal(_.isNumber(parseInt(res.headers['x-pagination-pages'])), true)

        assert.ok(res.body)
        done(err)
      })
  })
  it('should remove customer from discount', (done) => {
    const discount = discounts[1]

    adminUser
      .del(`/discount/${discountID}/customer/1`)
      .expect(200)
      .end((err, res) => {
        assert.ok(res.body)
        done(err)
      })
  })

  it('should add cart to discount', (done) => {
    const discount = discounts[1]

    adminUser
      .post(`/discount/${discountID}/cart/1`)
      .expect(200)
      .end((err, res) => {
        assert.ok(res.body)
        done(err)
      })
  })
  it('should get discount\'s carts', (done) => {
    adminUser
      .get(`/discount/${discountID}/carts`)
      .expect(200)
      .end((err, res) => {
        assert.ok(res.headers['x-pagination-total'])
        assert.ok(res.headers['x-pagination-pages'])
        assert.ok(res.headers['x-pagination-page'])
        assert.ok(res.headers['x-pagination-limit'])
        assert.ok(res.headers['x-pagination-offset'])
        assert.ok(res.headers['x-pagination-sort'])

        assert.equal(_.isNumber(parseInt(res.headers['x-pagination-total'])), true)
        assert.equal(_.isNumber(parseInt(res.headers['x-pagination-offset'])), true)
        assert.equal(_.isNumber(parseInt(res.headers['x-pagination-limit'])), true)
        assert.equal(_.isNumber(parseInt(res.headers['x-pagination-page'])), true)
        assert.equal(_.isNumber(parseInt(res.headers['x-pagination-pages'])), true)

        assert.ok(res.body)
        done(err)
      })
  })
  it('should remove cart from discount', (done) => {
    const discount = discounts[1]

    adminUser
      .del(`/discount/${discountID}/cart/1`)
      .expect(200)
      .end((err, res) => {
        assert.ok(res.body)
        done(err)
      })
  })
})


text:
Ceos = new Mongo.Collection("ceos");

Router.map(function() {
    this.route('home', {path: '/'});
    this.route('ceo_view', {
        path: '/file/:slug',
        data: function () {
            console.log("looking for ceo: " + this.params.slug);
            h = Ceos.findOne({ ceo: this.params.slug });
            console.log(h);
            if (h) {
                // for some reason {{ceo}} was undefined in the template.
                h["file_ceo"] = h["ceo"];
                return h;
            }
        }
    });
})

if (Meteor.isClient) {
    Template.leaderboard.ceos = function () {
        return Ceos.find({}, {limit: 20, sort: {votes: -1}});
    };

    function submitCeo (template, vote) {
        url = template.find("input[name=url]")
        first = template.find("input[name=first]")
        last = template.find("input[name=last]")

        submitVote(first.value, last.value, url.value, vote)
    }

    function submitVote(first, last, url, vote) {
        Meteor.call("addCeo", first, last, url, vote, function (error) {
            if (!error) {
                console.log("Added (ceo, vote): "
                    + "(" + url.value + ", " + vote);
                url.value = ""
            } else {
                console.log(error)
                console.log("Didn't add anything.");
            }
        });
    }

    Template.leaderboard.voteForCeo = function (url) {
        submitVote(null, null, url, 1)

    }

    Template.submit_ceo.events({
        'click #sexy' : function(event, template) { submitCeo(template, 1); },
    });
}

if (Meteor.isServer) {
    Meteor.methods({
        addCeo : function (first, last, url, vote) {
            var thing = Ceos.findOne( {"url": url} );
            if (thing) {
                console.log("Updating CEO (votes): " + url + ", ");
                Ceos.update( thing, { $inc: {votes: vote }})
            } else {
                console.log("Adding CEO (votes): (" + url + ", ")
                Ceos.insert({ first:first, last:last, url: url, votes: vote});
            }

            return false;
        },

        // findCeo: function (ceo) {
        //     return Ceos.findOne({ url: url });
        // }
    });

    Meteor.startup(function () {
        if (Ceos.find().count() === 0) {
            // initial Ceos that are sexy.
            var ceos = ["http://thebacklabel.com/wp-content/uploads/2014/05/bill-gates-desk-picture.jpg",
            ];
            for (var i = 0; i < Ceos.length; i++) {
                Ceos.insert({ceo: Ceos[i], votes: 1});
            }
        }
    });
}


text:
package com.emistoolbox.server.excelMerge.impl;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.poi.hssf.model.HSSFFormulaParser;
import org.apache.poi.hssf.usermodel.HSSFEvaluationWorkbook;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.formula.EvaluationWorkbook;
import org.apache.poi.ss.formula.FormulaParser;
import org.apache.poi.ss.formula.FormulaParsingWorkbook;
import org.apache.poi.ss.formula.FormulaRenderer;
import org.apache.poi.ss.formula.FormulaRenderingWorkbook;
import org.apache.poi.ss.formula.FormulaType;
import org.apache.poi.ss.formula.ptg.OperationPtg;
import org.apache.poi.ss.formula.ptg.Ptg;
import org.apache.poi.ss.formula.ptg.RefPtgBase;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFEvaluationWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.emistoolbox.common.excelMerge.CellPosition;
import com.emistoolbox.common.excelMerge.ExcelMergeConfig;
import com.emistoolbox.common.excelMerge.ExcelMergeConfig.MergeDirection;
import com.emistoolbox.common.excelMerge.ExcelMergeConfig.CellType;
import com.emistoolbox.server.excelMerge.ExcelMergeDataSource;
import com.emistoolbox.server.excelMerge.ExcelTemplate;

public abstract class ExcelTemplateBaseImpl implements ExcelTemplate
{
    private List<ExcelMergeConfig> configs = new ArrayList<ExcelMergeConfig>();

    public List<ExcelMergeConfig> getMergeConfigs()
    { return configs; }

    public void setMergeConfigs(List<ExcelMergeConfig> configs)
    { this.configs = configs; }

    public Set<String> getGlobalVariables()
    { return getVariables(CellType.GLOBAL_VARIABLE); }

    public Set<String> getLoopVariables()
    { return getVariables(CellType.LOOP_VARIABLE); }

    private Set<String> getVariables(CellType type)
    {
        Set<String> result = new HashSet<String>();
        for (ExcelMergeConfig config : configs)
        {

            for (int i = 0; i < config.getCellCount(); i++)
            {
                if (config.getCellType(i) == type)
                    result.add(config.getCellValue(i));
            }
        }

        return result;
    }

    protected abstract Workbook getExcelTemplate()
        throws IOException;

    public void saveMergedDocument(OutputStream out, ExcelMergeDataSource dataSource)
        throws IOException
    {
        Workbook wb = getExcelTemplate();
        replace(wb, dataSource);
        wb.write(out);
    }

    private void replace(Workbook wb, ExcelMergeDataSource dataSource)
        throws IOException
    {
        List<Sheet> sheets = new ArrayList<Sheet>();
        for (ExcelMergeConfig config : configs)
            sheets.add(wb.getSheet(config.getSheetName()));

        Map<String, Object> globalVars = dataSource.getGlobals();
        EvaluationWorkbook evalWorkbook = getEvaluatingWorkbook(wb);
        List<Cell[]> topRows = new ArrayList<Cell[]>();
        for (ExcelMergeConfig config : configs)
            topRows.add(new Cell[config.getCellCount()]);

        int dataIndex = 0;
        Iterator<Map<String, Object>> iter = dataSource.getLoop();
        while (iter.hasNext())
        {
            Map<String, Object> localVars = iter.next();
            for (int i = 0; i < configs.size(); i ++)
            {
                ExcelMergeConfig config = configs.get(i);
                Sheet sheet = sheets.get(i);
                int sheetIndex = wb.getSheetIndex(config.getSheetName());
                replace(dataIndex, config, sheet, globalVars, localVars, topRows.get(i), evalWorkbook, sheetIndex);
            }

            dataIndex++;
        }
    }

    private void replace(int dataIndex, ExcelMergeConfig config, Sheet sheet, Map<String, Object> globals, Map<String, Object> data, Cell[] topRow, EvaluationWorkbook evalWorkbook, int sheetIndex)
        throws IOException
    {
        for (int cellIndex = 0; cellIndex < config.getCellCount(); cellIndex++)
            setCell(config.getCellType(cellIndex), config.getCellValue(cellIndex), getCell(sheet, dataIndex, cellIndex, config), globals, data, config.getDirection(), dataIndex, cellIndex, topRow, evalWorkbook, sheetIndex);
    }

    private void setCell(CellType cellType, String value, Cell c, Map<String, Object> globals, Map<String, Object> locals, MergeDirection dir, int dataIndex, int cellIndex, Cell[] topRow, EvaluationWorkbook evalWorkbook, int sheetIndex)
        throws IOException
    {
        switch (cellType)
        {
        case CONSTANT:
            c.setCellType(Cell.CELL_TYPE_STRING);
            c.setCellValue(value);
            break;

        case COPY:
            if (dataIndex == 0)
            {
                // Remember cells in first row
                topRow[cellIndex] = c;
            }
            else
            {
                Cell topCell = topRow[cellIndex];
                c.setCellType(topCell.getCellType());

                // Copies value from first row (adjust formulae if necessary)
                switch (topCell.getCellType())
                {
                case Cell.CELL_TYPE_FORMULA:
                    c.setCellFormula(getOffsetFormula(topCell.getCellFormula(), evalWorkbook, sheetIndex, dir == MergeDirection.COLUMNS ? dataIndex  : 0, dir == MergeDirection.ROWS ? dataIndex : 0));
                    break;

                case Cell.CELL_TYPE_BOOLEAN:
                    c.setCellValue(topCell.getBooleanCellValue());
                    break;

                case Cell.CELL_TYPE_NUMERIC:
                    c.setCellValue(topCell.getNumericCellValue());
                    break;

                case Cell.CELL_TYPE_STRING:
                    c.setCellValue(topCell.getStringCellValue());
                    break;
                }
            }

            break;

        case EMPTY:
            c.setCellType(Cell.CELL_TYPE_BLANK);
            break;

        case GLOBAL_VARIABLE:
            setValue(c, globals.get(value));
            break;

        case LOOP_VARIABLE:
            setValue(c, locals.get(value));
            break;

        case ORIGINAL:
            break;

        default:
            break;
        }
    }

    private String getOffsetFormula(String formula, EvaluationWorkbook evalWorkbook, int sheetIndex, int rowOffset, int colOffset)
    {
        Ptg[] parts = FormulaParser.parse(formula, (FormulaParsingWorkbook) evalWorkbook, FormulaType.CELL, sheetIndex);
        for (int i = 0; i < parts.length; i++)
        {
            if (parts[i] instanceof RefPtgBase)
            {
                RefPtgBase ref = (RefPtgBase) parts[i];
                if (ref.isColRelative())
                    ref.setColumn(ref.getColumn() + colOffset);

                if (ref.isRowRelative())
                    ref.setRow(ref.getRow() + rowOffset);
            }
        }

        return FormulaRenderer.toFormulaString((FormulaRenderingWorkbook) evalWorkbook, parts);
    }

    private EvaluationWorkbook getEvaluatingWorkbook(Workbook wb)
    {
        if (wb instanceof HSSFWorkbook)
            return HSSFEvaluationWorkbook.create((HSSFWorkbook) wb);
        else if (wb instanceof XSSFWorkbook)
            return XSSFEvaluationWorkbook.create((XSSFWorkbook) wb);

        return null;
    }

    private void setValue(Cell c, Object value)
        throws IOException
    {
        if (value == null)
            c.setCellType(Cell.CELL_TYPE_BLANK);
        else if (value instanceof String)
        {
            c.setCellType(Cell.CELL_TYPE_STRING);
            c.setCellValue((String) value);
        }
        else if (value instanceof Integer)
        {
            c.setCellType(Cell.CELL_TYPE_NUMERIC);
            c.setCellValue((Integer) value);
        }
        else if (value instanceof Double)
        {
            Double dbl = (Double) value;
            if (Double.isNaN(dbl))
                c.setCellType(Cell.CELL_TYPE_BLANK);
            else
            {
                c.setCellType(Cell.CELL_TYPE_NUMERIC);
                c.setCellValue((Double) value);
            }
        }
        else if (value instanceof Float)
        {
            c.setCellType(Cell.CELL_TYPE_NUMERIC);
            c.setCellValue((Float) value);
        }
        else
            throw new IOException("Unsupported data type: " + value.getClass());
    }

    private Cell getCell(Sheet s, int dataRow, int dataCol, ExcelMergeConfig config)
    {
        if (config.getDirection() == MergeDirection.ROWS)
            return getCell(s, new CellPosition(config.getTopLeft(), dataCol, dataRow));
        else
            return getCell(s, new CellPosition(config.getTopLeft(), dataRow, dataCol));
    }

    private Cell getCell(Sheet s, CellPosition pos)
    {
        Row row = s.getRow(pos.getRowIndex());
        if (row == null)
            row = s.createRow(pos.getRowIndex());

        Cell c = row.getCell(pos.getColumnIndex());
        if (c == null)
            c = row.createCell(pos.getColumnIndex());

        return c;
    }
}


text:
__author__ = 'Spoony'
__version__  = 'version 0.0.1'
__license__  = 'Copyright (c) 2015 NXEZ.COM'

#sys.path.append(sys.path[0] + "/entities/")
#from entities import *
import RPi.GPIO as GPIO
from .sakspins import SAKSPins as PINS
from sakshat import entities

class SAKSHAT(object):
    '''
    SAKS HAT class, some useful function are declared.
    '''
    #appRoot = sys.path[0]
    buzzer = None
    ledrow = None
    ds18b20 = None
    digital_display = None
    dip_switch = None
    tactrow = None

    def saks_gpio_init(self):
        #print 'saks_gpio_init'
        GPIO.setwarnings(False)
        GPIO.cleanup()
        GPIO.setmode(GPIO.BCM)

        GPIO.setup(PINS.BUZZER, GPIO.OUT)
        GPIO.output(PINS.BUZZER, GPIO.HIGH)

        for p in [PINS.BUZZER, PINS.TACT_RIGHT, PINS.TACT_LEFT, PINS.DIP_SWITCH_1, PINS.DIP_SWITCH_2]:
            GPIO.setup(p, GPIO.OUT)
            GPIO.output(p, GPIO.HIGH)

        for p in PINS.LEDS + PINS.DIGITAL_DISPLAY + PINS.DIGITAL_DISPLAY_SELECT:
            GPIO.setup(p, GPIO.OUT)
            GPIO.output(p, GPIO.HIGH)

        for p in [PINS.TACT_RIGHT, PINS.TACT_LEFT, PINS.DIP_SWITCH_1, PINS.DIP_SWITCH_2]:
            GPIO.setup(p, GPIO.IN, pull_up_down = GPIO.PUD_UP)
            #GPIO.setup(p, GPIO.IN)

        #由于SAKS的蓝色LED和数码管共享引脚,此处将数码管位选关闭,只让信号作用于LED
        #GPIO.setup(17, GPIO.OUT, initial = GPIO.HIGH)
        #GPIO.setup(27, GPIO.OUT, initial = GPIO.HIGH)
        #GPIO.setup(22, GPIO.OUT, initial = GPIO.HIGH)
        #GPIO.setup(10, GPIO.OUT, initial = GPIO.HIGH)

    def __init__(self):
        self.saks_gpio_init()
        self.buzzer = entities.Buzzer(PINS.BUZZER, GPIO.LOW)
        self.ledrow = entities.LedRow(PINS.LEDS, GPIO.LOW)
        self.ds18b20 = entities.DS18B20(PINS.DS18B20)
        self.digital_display = entities.DigitalDisplay({'seg': PINS.DIGITAL_DISPLAY, 'sel': PINS.DIGITAL_DISPLAY_SELECT}, GPIO.LOW)
        self.dip_switch = entities.DipSwitch2Bit([PINS.DIP_SWITCH_1, PINS.DIP_SWITCH_2], GPIO.LOW)
        self.dip_switch.register(self)
        self.tactrow = entities.TactRow([PINS.TACT_LEFT, PINS.TACT_RIGHT], GPIO.LOW)
        for t in self.tactrow.items:
            t.register(self)

        #print('self.dip_switch.register(self)')

    dip_switch_status_changed_handler = None
    def on_dip_switch_2bit_status_changed(self, status):
        #print('on_dip_switch_2bit_status_changed')
        if self.dip_switch_status_changed_handler is not None:
            self.dip_switch_status_changed_handler(status)

    tact_event_handler = None
    def on_tact_event(self, pin, status):
        #print('on_tact_event')
        if self.tact_event_handler is not None:
            self.tact_event_handler(pin, status)


text:
package com.visionarts.powerjambda.events;

import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.visionarts.powerjambda.AbstractRouter;
import com.visionarts.powerjambda.ApplicationContext;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public abstract class AbstractEventHandler<EventT, EventResultT, RouterRequestT>
    implements RequestHandler<EventT, EventResultT>, EventRequestReader<EventT, RouterRequestT> {

    protected final Logger logger = LogManager.getLogger(this.getClass());
    protected final ApplicationContext applicationContext;

    public AbstractEventHandler(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    /**
     * The entry method for handling events.

     *

     *
     */
    @Override
    public EventResultT handleRequest(EventT event, Context context) {
        return handleEvent(event, context);
    }

    protected abstract EventResultT handleEvent(EventT event, Context context);

    /**
     * Convenient method forms pass through to

     * {@link AbstractRouter#apply(Object, Context)}
     *
     * @param request The incoming request
     * @param context The Lambda Context object passed by the AWS Lambda environment
     * @return The response returned by the action class
     */
    protected final AwsEventResponse actionRouterHandle(AwsEventRequest request, Context context) {
        return new EventActionRouter(applicationContext)
                    .apply(request, context);
    }

}


text:
<!DOCTYPE html>
<meta charset=utf-8>
<title>Redirecting...</title>
<link rel=canonical href="../子/index.html">
<meta http-equiv=refresh content="0; url='../子/index.html'">

Redirecting...

Click here if you are not redirected.


text:
date: 2016-01-20T14:13:06-04:00
title: "Puppet DSC module is now supported!"
subtitle: "Puppet DSC module is now supported!"
summary: "Puppet DSC module is now supported!"
aliases: [
  "/blog/dsc/puppet/puppet-dsc-module-released",
  "2016-01-20-puppet-dsc-module-released",
]
thumbnail: img/Puppet-Logo-Amber-White-lg.jpg
featureImage: img/Puppet-Logo-Amber-White-lg.jpg
tags: [ dsc, puppet ]
---

The new Puppet module I've been working so hard on is finally released as [supported](https://forge.puppetlabs.com/puppetlabs/dsc)! It was alot of hard work to get to here and now. Working closely with my coworkers and Microsoft to make this happen was the best learning experience and the most interesting thing I've done in a long time.

There are a host of improvements to the module since the first unsupported release, but the one I'm most excited about is the speed improvements. Instead of starting a PowerShell process for each reasource being executed, we only start one PowerShell process instance and continue to use it for the duration of the Puppet run. This results in a huge speed improvement as well as a decrease in system utilization. you can read more about what was done [here](https://puppetlabs.com/blog/powershell-dsc-module-now-supported).


text:
require('./modules/config');
require('./modules/controllers');
require('./modules/services');
let initialized = false;

function constructQuery(path, query, attribute){
  var value = path.split("/").slice(-1).pop();
  query.equalTo(attribute, value);
  return query
}

const app = angular.module('Kinvey', [
  'ionic',
  'kinvey',
  'config',
  'controllers',
  'services'
]);

app.config(function($logProvider) {
  'ngInject';

  // Enable log
  $logProvider.debugEnabled(true);
});

app.config(function($stateProvider) {
  'ngInject';

  // Setup the states
  $stateProvider
    .state('welcome', {
      url: '',
      templateUrl: 'views/welcome.html',
      data: {
        requiresAuthorization: false
      },
      controller: 'WelcomeCtrl as vm'
    })
    .state('logout', {
      url: '/logout',
      data: {
        requiresAuthorization: true
      },
      controller: function($state, Auth) {
        'ngInject';

        Auth.logout().then(function() {
          $state.go('welcome');
        });
      }
    })
    .state('app', {
      url: '/app',
      abstract: true,
      templateUrl: 'views/menu.html',
      controller: 'MenuCtrl as vm'
    })
    .state('books', {
      parent: 'app',
      url: '/library',
      views: {
        content: {
          templateUrl: 'views/library.html',
          controller: 'BooksCtrl as vm',
          resolve: {
            books: function(DataStore) {
              'ngInject';
              return DataStore.find('books');
            }
          }
        }
      },
      data: {
        requiresAuthorization: true
      }
    })
    .state('pages', {
      parent: 'app',
      url: '/read/:bookId',
      views: {
        content: {
          templateUrl: 'views/read.html',
          controller: 'PagesCtrl as vm',
          resolve: {
            pages: function(DataStore, $kinvey, $location) {
              'ngInject';
              return DataStore.find('pages', constructQuery($location.path(), new $kinvey.Query(), 'bookId'));
            },
            book: function(DataStore, $kinvey, $location) {
              return DataStore.find('books', constructQuery($location.path(), new $kinvey.Query(), '_id'));
            }
          }
        }
      },
      data: {
        requiresAuthorization: true
      }
    });
});

app.run(function($ionicPlatform, $kinvey, $rootScope, $state, KinveyConfig, Auth) {
  'ngInject';

  $rootScope.$on('$stateChangeStart', function(event, toState, toParams) {
    toState.data = toState.data || {};

    if (!initialized) {
      event.preventDefault();

      // Initialize Kinvey
      $kinvey.init(KinveyConfig).then(function() {
        initialized = true;
        $state.go(toState.name, toParams);
      });
    } else if (toState.data.requiresAuthorization && !$kinvey.getActiveUser()) {
      event.preventDefault();

      // Login
      Auth.login().then(function() {
        $state.go(toState.name, toParams);
      });
    }
  });

  $ionicPlatform.ready(function() {
    const cordova = window.cordova;
    const StatusBar = window.StatusBar;

    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
    // for form inputs)
    if (cordova && cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
      cordova.plugins.Keyboard.disableScroll(true);
    }

    if (StatusBar) {
      StatusBar.styleDefault();
    }
  });

  $state.go('welcome');
});


text:
<?php
/**
 * TOP API: taobao.shop.remainshowcase.get request
 *
 * @author auto create
 * @since 1.0, 2011-09-29 15:36:21
 */
class TopLinker_Request_ShopRemainshowcaseGet extends TopLinker_Request_Abstract
{
}


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xunit;

namespace System.IO.FileSystem.Tests
{
    public static class FSAssert
    {
        public static void ThrowsSharingViolation(Action testCode)
        {
            Exception e = Assert.ThrowsAny<Exception>(testCode);
            Assert.True(e is UnauthorizedAccessException || e is IOException, "Exception should be either UnauthorizedAccessException or IOException: " + e.ToString());
        }

        public static void CompletesSynchronously(Task task, bool permitFaultedTask = false)
        {
            // The purpose of this method is to try and ensure that a task does a particular
            // piece of work (like return a result or throw) synchronously.

            // We cannot use Task's IAsyncResult implementation since it doesn't set
            // CompletedSynchronously to anything but false.

            TaskStatus status = task.Status;

            if (status == TaskStatus.Faulted)
            {
                // If an API is expected to return a faulted task instead of throwing synchronously
                // then permit this.
                if (permitFaultedTask)
                {
                    // Could have happened synchronously. Don't assert but trigger the exception
                    task.GetAwaiter().GetResult();
                }
                else
                {
                    Assert.True(false, "Should throw synchronously, but instead returned faulted task");
                }
            }
            else if (status == TaskStatus.Canceled)
            {
                // Could have happened synchronously. Don't assert but trigger the exception
                task.GetAwaiter().GetResult();
            }
            else if (status != TaskStatus.RanToCompletion)
            {
                // first wait for the task to complete without throwing
                ((IAsyncResult)task).AsyncWaitHandle.WaitOne();

                // now assert, we ignore the result of the task intentionally
                Assert.True(false, "Should complete synchronously");
            }

            return;
        }

        public static T CompletesSynchronously<T>(Task<T> task, bool permitFaultedTask = false)
        {
            CompletesSynchronously((Task)task, permitFaultedTask);

            // this should not throw or wait since we waited above and threw
            // when it didn't complete synchronously.
            return task.Result;
        }

        public static void IsCancelled(Task task, CancellationToken ct)
        {
            Assert.True(task.IsCanceled);
            OperationCanceledException tce = Assert.ThrowsAny<OperationCanceledException>(() => task.GetAwaiter().GetResult());
            Assert.NotNull(tce);
            Assert.Equal(ct, tce.CancellationToken);
        }
    }
}


text:
const {createAddColumnMigration} = require('../../utils');

module.exports = createAddColumnMigration('products', 'visible', {
    type: 'boolean',
    nullable: false,
    defaultTo: false
});

module.exports.up = async () => {
    // noop - column will be replaced with `visibility` instead
};


text:
package org.kivadoc.tools;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Set;

import org.apache.commons.io.FileUtils;
import org.kivadoc.DocRepository;
import org.kivadoc.FullDocumentParser;
import org.kivadoc.TargetExtractor;
import org.kivadoc.KivaDocument;
import org.kivadoc.Uri;
import org.kivadoc.utils.UtfUtils;

public class DirectoryDocRepository implements DocRepository {
	private File inputPath;
	private HashMap<File, KivaDocument> parseMap = new HashMap<File, KivaDocument>();

	public DirectoryDocRepository(File inputPath) {
		this.inputPath = inputPath;
	}

	public KivaDocument getParsed(File f) throws IOException {
		if (!parseMap.containsKey(f)) {
			FullDocumentParser parser = new FullDocumentParser();
			byte[] fileBytes = FileUtils.readFileToByteArray(f);
			parseMap.put(f, parser.parse(UtfUtils.decode(fileBytes)));
		}
		return parseMap.get(f);
	}

	@Override
	public String getTitle(String uri) {
		try {
			return getParsed(getDocFile(uri)).getTitle();
		} catch (IOException e) {
		}
		return Uri.baseName(uri);
	}

	@Override
	public boolean doesResourceExist(String uri) {
		return new File(inputPath, uri).exists();
	}

	@Override
	public Set<String> getAllTargets(String uri) {
		try {
			return TargetExtractor.extract(getParsed(getDocFile(uri)).getBody());
		} catch (IOException e) {
			return null;
		}
	}

	private File getDocFile(String uri) {
		return new File(inputPath, uri + ".txt");
	}

}


text:
<?xml version='1.0' encoding='UTF-8'?>
<Document>
  <Header>
    <SchemaName>Location</SchemaName>
    <Identifier>location_geonames_2752430</Identifier>
    <DocumentState>public</DocumentState>
    <TimeStamp>1390753462903</TimeStamp>
    <SummaryFields>
      <Title>NL > North Brabant > Korenmaaien</Title>
    </SummaryFields>
  </Header>
  <Body>
    <Location>
      <GeopoliticalHierarchy>NL,North Brabant,Korenmaaien</GeopoliticalHierarchy>
      <LocationName>
        <Appelation>Korenmaaien</Appelation>
        <LocationNameType>locality</LocationNameType>
        <Comments></Comments>
      </LocationName>
      <Coordinates>
        <Longitude>4.85511</Longitude>
        <Latitude>51.482890000000005</Latitude>
      </Coordinates>
      <GeonamesURI>http://www.geonames.org/2752430</GeonamesURI>
      <WikipediaLink/>
      <DbpediaLink/>
    </Location>
  </Body>
</Document>


text:
from fft_web import fft_web
from gnuradio import eng_notation
from gnuradio import gr
from gnuradio import uhd
from gnuradio.eng_option import eng_option
from gnuradio.filter import firdes
from optparse import OptionParser
import time

class usrp_fft(gr.top_block):

    def __init__(self, freq=2.49e9, samp_rate=1e6, gain=0, fft_size=1024, frame_rate=10, power_min=-100, power_max=0, port=7000, ip_address="srvwww.cortexlab.fr", antenna="TX/RX", bandwidth=0):
        gr.top_block.__init__(self, "Usrp Fft")

        ##################################################
        # Parameters
        ##################################################
        self.freq = freq
        self.samp_rate = samp_rate
        self.gain = gain
        self.fft_size = fft_size
        self.frame_rate = frame_rate
        self.power_min = power_min
        self.power_max = power_max
        self.port = port
        self.ip_address = ip_address
        self.antenna = antenna
        self.bandwidth = bandwidth

        ##################################################
        # Blocks
        ##################################################
        self.uhd_usrp_source_0 = uhd.usrp_source(
        	",".join(("addr=192.168.10.2", "")),
        	uhd.stream_args(
        		cpu_format="fc32",
        		channels=range(1),
        	),
        )
        self.uhd_usrp_source_0.set_clock_source("internal", 0)
        self.uhd_usrp_source_0.set_samp_rate(samp_rate)
        self.uhd_usrp_source_0.set_center_freq(freq, 0)
        self.uhd_usrp_source_0.set_gain(gain, 0)
        self.uhd_usrp_source_0.set_antenna(antenna, 0)
        self.fft_web_1 = fft_web(
            fft_size=fft_size,
            power_max=power_max,
            power_min=power_min,
            port=port,
            frame_rate=frame_rate,
            sample_rate=samp_rate,
            ip_address=ip_address,
        )

        ##################################################
        # Connections
        ##################################################
        self.connect((self.uhd_usrp_source_0, 0), (self.fft_web_1, 0))

    def get_freq(self):
        return self.freq

    def set_freq(self, freq):
        self.freq = freq
        self.uhd_usrp_source_0.set_center_freq(self.freq, 0)

    def get_samp_rate(self):
        return self.samp_rate

    def set_samp_rate(self, samp_rate):
        self.samp_rate = samp_rate
        self.uhd_usrp_source_0.set_samp_rate(self.samp_rate)
        self.fft_web_1.set_sample_rate(self.samp_rate)

    def get_gain(self):
        return self.gain

    def set_gain(self, gain):
        self.gain = gain
        self.uhd_usrp_source_0.set_gain(self.gain, 0)

    def get_fft_size(self):
        return self.fft_size

    def set_fft_size(self, fft_size):
        self.fft_size = fft_size
        self.fft_web_1.set_fft_size(self.fft_size)

    def get_frame_rate(self):
        return self.frame_rate

    def set_frame_rate(self, frame_rate):
        self.frame_rate = frame_rate
        self.fft_web_1.set_frame_rate(self.frame_rate)

    def get_power_min(self):
        return self.power_min

    def set_power_min(self, power_min):
        self.power_min = power_min
        self.fft_web_1.set_power_min(self.power_min)

    def get_power_max(self):
        return self.power_max

    def set_power_max(self, power_max):
        self.power_max = power_max
        self.fft_web_1.set_power_max(self.power_max)

    def get_port(self):
        return self.port

    def set_port(self, port):
        self.port = port
        self.fft_web_1.set_port(self.port)

    def get_ip_address(self):
        return self.ip_address

    def set_ip_address(self, ip_address):
        self.ip_address = ip_address
        self.fft_web_1.set_ip_address(self.ip_address)

    def get_antenna(self):
        return self.antenna

    def set_antenna(self, antenna):
        self.antenna = antenna
        self.uhd_usrp_source_0.set_antenna(self.antenna, 0)

    def get_bandwidth(self):
        return self.bandwidth

    def set_bandwidth(self, bandwidth):
        self.bandwidth = bandwidth
        self.uhd_usrp_source_0.set_bandwidth(self.bandwidth, 0)

if __name__ == '__main__':
    parser = OptionParser(option_class=eng_option, usage="%prog: [options]")
    parser.add_option("-F", "--freq", dest="freq", type="eng_float", default=eng_notation.num_to_str(2.49e9),
        help="Set freq [default=%default]")
    parser.add_option("-R", "--samp-rate", dest="samp_rate", type="eng_float", default=eng_notation.num_to_str(1e6),
        help="Set samp_rate [default=%default]")
    parser.add_option("-G", "--gain", dest="gain", type="eng_float", default=eng_notation.num_to_str(0),
        help="Set gain [default=%default]")
    parser.add_option("-S", "--fft-size", dest="fft_size", type="intx", default=1024,
        help="Set fft_size [default=%default]")
    parser.add_option("-H", "--frame-rate", dest="frame_rate", type="intx", default=10,
        help="Set frame_rate [default=%default]")
    parser.add_option("-A", "--power-min", dest="power_min", type="eng_float", default=eng_notation.num_to_str(-100),
        help="Set power_min [default=%default]")
    parser.add_option("-B", "--power-max", dest="power_max", type="eng_float", default=eng_notation.num_to_str(0),
        help="Set power_max [default=%default]")
    parser.add_option("-P", "--port", dest="port", type="intx", default=7000,
        help="Set port [default=%default]")
    parser.add_option("-I", "--ip-address", dest="ip_address", type="string", default="srvwww.cortexlab.fr",
        help="Set ip address [default=%default]")
    parser.add_option("-T", "--antenna", dest="antenna", type="string", default="TX/RX",
        help="Set TX/RX [default=%default]")
    parser.add_option("-W", "--bandwidth", dest="bandwidth", type="eng_float", default=eng_notation.num_to_str(0),
        help="Set bandwidth [default=%default]")
    (options, args) = parser.parse_args()
    tb = usrp_fft(freq=options.freq, samp_rate=options.samp_rate, gain=options.gain, fft_size=options.fft_size, frame_rate=options.frame_rate, power_min=options.power_min, power_max=options.power_max, port=options.port, ip_address=options.ip_address, antenna=options.antenna, bandwidth=options.bandwidth)
    tb.start()
    tb.wait()


text:
using System;
using System.Collections.Generic;
using System.Linq;

public class ManipulationWithNumbers
{
    public static void Main()
    {
        //Input
        var listOfNumbers = new List<int>(Console.ReadLine().Split(' ').Select(int.Parse).ToList());

        //Logic
        int[] operations = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
        var manipulatedNumbers = new List<int>();

        for (int index = 0; index < operations[0]; index++)
        {
            manipulatedNumbers.Add(listOfNumbers[index]);
        }

        listOfNumbers.RemoveRange(0, operations[0]);
        manipulatedNumbers.RemoveRange(0, operations[1]);

        for (int i = 0; i < manipulatedNumbers.Count; i++)
        {
            listOfNumbers.Insert(i, manipulatedNumbers[i]);
        }

        if (listOfNumbers.Contains(operations[2]))
        {
            Console.WriteLine("YES!");
        }
        else
        {
            Console.WriteLine("NO!");
        }

    }
}


text:
package de.cinovo.cloudconductor.server.dao.hibernate;

import de.cinovo.cloudconductor.server.dao.IRepoMirrorDAO;
import de.cinovo.cloudconductor.server.model.ERepo;
import de.cinovo.cloudconductor.server.model.ERepoMirror;
import de.taimos.dvalin.jpa.EntityDAOHibernate;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * Copyright 2013 Cinovo AG

 *

 *
 * @author psigloch
 */
@Repository("RepoMirrorDAOHib")
public class RepoMirrorDAOHib extends EntityDAOHibernate<ERepoMirror, Long> implements IRepoMirrorDAO {

	@Override
	public List<ERepoMirror> findByIds(Set<Long> ids) {
		if (ids == null || !ids.isEmpty()) {
			return new ArrayList<>();
		}
		// language=HQL
		return this.findListByQuery("FROM ERepoMirror AS m WHERE m.id IN ?1", ids);
	}

	@Override
	public List<ERepoMirror> findForRepo(ERepo repo) {
		// language=HQL
		return this.findListByQuery("FROM ERepoMirror AS m WHERE m.repoId = ?1", repo.getId());
	}

	@Override
	public void deleteForRepo(ERepo repo) {
		if (repo == null) {
			return;
		}
		// language=HQL
		this.entityManager.createQuery("DELETE FROM ERepoMirror AS m WHERE m.repoId = ?1").setParameter(1, repo.getId()).executeUpdate();
	}

	@Override
	public Long countForRepo(Long id) {
		// language=HQL
		return this.entityManager.createQuery("SELECT COUNT(m) FROM ERepoMirror AS m WHERE m.repoId = ?1", Long.class).setParameter(1, id).getSingleResult();
	}

	@Override
	public Class<ERepoMirror> getEntityClass() {
		return ERepoMirror.class;
	}

}


text:
var fs = require("fs")
var treeFile = process.argv[2], branchMultiplier = process.argv[3] || 1
var tree = fs.readFileSync (treeFile, 'utf8')

tree = tree.replace (/:([\d\.]+)/g, function (str, p1, offset, s) {
    return ':' + (p1 * branchMultiplier)
})

process.stdout.write (tree)


text:
'''
Created on Jan 7, 2015

@author: ekondrashev
'''
import BashastBaseListener
class Listener(BashastBaseListener):
    def __init__(self, print_fn):
        BashastBaseListener.__init__(self)
        self.print_fn = print_fn

    def enterFirst_line_comment(self, ctx):
        self.print_fn("Enter first line comment")

    def enterFor_expr(self, ctx):
        self.print_fn("Enter for expr")

    def enterWspace(self, ctx):
        self.print_fn("Enter wspace")

    def enterBrace_expansion(self, ctx):
        self.print_fn("Enter Brace_expansion")

    def enterRange(self, ctx):
        self.print_fn("Enter range")

    def enterVariable_reference(self, ctx):
        self.print_fn("Enter variable_reference")

    def enterName(self, ctx):
        self.print_fn("Enter name: %s" % ctx.getText())

    def enterCommand(self, ctx):
        self.print_fn("Enter command: %s" % ctx.getText())


text:
"""
GPX IO and manipulation (UNDER DEVELOPMENT)

Overview
--------

`GPX` represents a GPX document that can be written to or read from

To do:
    - XML namespaces aren't really handled properly
    - metadata node not addressed
"""

import collections
import xml.etree.ElementTree as ET
from xml.etree.ElementTree import ElementTree, Element
from xml.dom import minidom

Point = collections.namedtuple("Point", ["lonlat", "properties", "extensions"])
Trkseg = collections.namedtuple("Trkseg", ["trkpts", "properties", "extensions"])
Track = collections.namedtuple("Track", ["trksegs", "properties", "extensions"])
Route = collections.namedtuple("Route", ["rtepts", "properties", "extensions"])

ET.register_namespace("", "http://www.topografix.com/GPX/1/1")
ns = "{http://www.topografix.com/GPX/1/1}"

VALID_PROPERTIES = ("ele", "time", "magvar", "geoidheight", "name", "cmt",
                    "desc", "src", "link", "sym", "type", "fix", "sat", "hdop",
                    "vdop", "pdop", "ageofdgpsdata", "dgpsid")

def strip_namespace(s):
    return s[s.index("}")+1:]

class GPX(object):
    """ Represents a GPX document, with an internal representation of
    waypoints, tracks, and route that loosely approximates the XML structure.
    Provides methods to easily add Point-like and Line-like objects as GPX
    types. """

    def __init__(self, f=None, waypoints=None, tracks=None, routes=None):
        """ Create a GPX object, either from a GPX file or from lists of
        waypoints, tracks, and routes. """

        self.waypts = []
        self.tracks = []
        self.routes = []

        if f is not None:
            self.fromfile(f)

        else:
            if waypoints is not None:
                for waypt in waypoints:
                    self.add_waypoint(waypt)
            if tracks is not None:
                for track in tracks:
                    self.add_track(track)
            if routes is not None:
                for route in routes:
                    self.add_route(route)
        return

    @staticmethod
    def _readextensions(node):
        extensions = {}
        try:
            for ext in node.find(ns + "extensions"):
                extensions[strip_namespace(ext.tag)] = ext.text
        except TypeError:
            pass
        return extensions

    @staticmethod
    def _readproperties(node, exclude=()):
        properties = {}
        for subnode in node:
            tag = strip_namespace(subnode.tag)
            if tag not in exclude:
                properties[tag] = subnode.text
        return properties

    def _readwpt(self, wpt):
        properties = self._readproperties(wpt, exclude=("extensions",))
        extensions = self._readextensions(wpt)
        lon = round(float(wpt.attrib["lon"]), 6)
        lat = round(float(wpt.attrib["lat"]), 6)
        return Point((lon, lat), properties, extensions)

    @staticmethod
    def _dict2gpx(parent, properties):
        for p in properties:
            sub = Element(ns + p)
            sub.text = str(properties[p])
            parent.append(sub)
        return parent

    def _extensions2gpx(self, parent, extensions):
        ext = Element(ns + "extensions")
        ext = self._dict2gpx(ext, extensions)
        parent.append(ext)
        return parent

    def _build_gpx_wpt(self, waypt, tag="wpt"):
        """ Build <wpt> node. """
        wpt = Element(ns + tag, lon=str(waypt.lonlat[0]), lat=str(waypt.lonlat[1]))
        wpt = self._dict2gpx(wpt, waypt.properties)
        wpt = self._extensions2gpx(wpt, waypt.extensions)
        return wpt

    def _build_gpx_trk(self, track):
        """ Build "trk" nodes. """
        trk = Element(ns + "trk")
        trk = self._dict2gpx(trk, track.properties)
        trk = self._extensions2gpx(trk, track.extensions)

        for segment in track.trksegs:
            trkseg = Element(ns + "trkseg")
            trkseg = self._dict2gpx(trkseg, segment.properties)
            trkseg = self._extensions2gpx(trkseg, segment.extensions)

            for trackpt in segment.trkpts:
                trkpt = self._build_gpx_wpt(trackpt, tag="trkpt")
                trkseg.append(trkpt)

            trk.append(trkseg)
        return trk

    def _build_gpx_rte(self, route):
        rte = Element(ns + "rte")
        rte = self._dict2gpx(rte, route.properties)
        rte = self._extensions2gpx(rte, route.extensions)
        for routept in route.rtepts:
            rte.append(self._build_gpx_wpt(routept, tag="rtept"))
        return rte

    def fromfile(self, f):
        """ Read a GPX document from *f*, which may be a filename or a
        file-like object. """

        gpxtree = ElementTree(file=f)
        self.gpx = gpxtree.getroot()

        for node in self.gpx.findall(ns + "wpt"):
            self.parse_wpt(node)

        for node in self.gpx.findall(ns + "trk"):
            self.parse_trk(node)

        for node in self.gpx.findall(ns + "rte"):
            self.parse_rte(node)
        return

    def parse_wpt(self, wpt):
        """ Parse a <wpt> node, updating self.waypoints. """
        point = self._readwpt(wpt)
        name = wpt.properties.get("name", "waypoint_" + str(len(self.waypoints)))
        self.waypoints[name] = point
        return

    def parse_trk(self, trk):
        """ Parse a <trk> node, updating self.tracks. """
        segments = []
        trkproperties = self._readproperties(trk, exclude=("trkseg",))
        trkextensions = self._readextensions(trk)

        for trkseg in trk.findall(ns + "trkseg"):

            points = [self._readwpt(trkpt) for trkpt in trkseg.findall(ns + "trkpt")]
            properties = self._readproperties(trkseg, exclude=("trkpt",))
            extensions = self._readextensions(trkseg)
            segments.append(Trkseg(points, properties, extensions))

        self.tracks.append(Track(segments, trkproperties, trkextensions))
        return

    def parse_rte(self, rte):
        properties = self._readproperties(rte, exclude=("rtept",))
        extensions = self._readextensions(rte)
        points = [self._readwpt(rtept) for rtept in rte.findall(ns + "rtept")]
        self.routes.append(Route(points, properties, extensions))
        return

    def add_waypoint(self, waypoint):
        """ Add a Point-like object as a waypoint. Properties and extension
        types are taken from waypoint.properties attribute. """
        properties = {}
        extensions = {}
        for key in waypoint.properties:
            if key in VALID_PROPERTIES:
                properties[key] = str(waypoint.properties[key])
            else:
                extensions[key] = str(waypoint.properties[key])
        waypt = Point(waypoint.vertex(), properties, extensions)
        self.waypts.append(waypt)
        return

    def add_track(self, *tracks, **kw):
        """ Add Multipoint-like objects as segments of a track. Dictionaries of
        properties and extension types for the track are accepted as keyword
        arguments.

        Properties and extension types for the track segments are taken from
        the `properties` attribute of each Multipoint-like object.

        Properties and extensions types for each track point are taken from the
        `data` attribute of each Multipoint-like object.

        INCOMPLETE:

        Needs to distinguish between properties and extensions at the trkseg
        and trkpt levels

        Needs to properly add and <ele> property for Lines of rank 3
        """
        segments = []
        properties = {}
        extensions = {}

        attributes = kw.get("attributes", None)
        if attributes is not None:
            for key in attributes:
                if key in VALID_PROPERTIES:
                    properties[key] = str(attributes[key])
                else:
                    properties[key] = str(attributes[key])

        for line in tracks:
            points = []
            sg_properties = {}
            sg_extensions = {}

            for key in line.properties:
                if key in VALID_PROPERTIES:
                    sg_properties[key] = str(line.properties[key])
                else:
                    sg_extensions[key] = str(line.properties[key])

            if line.data is not None:
                pt_properties = [k for k in line.data.fields if k in VALID_PROPERTIES]
                pt_extensions = [k for k in line.data.fields if k not in VALID_PROPERTIES]
            else:
                pt_properties = []
                pt_extensions = []

            for i, xy in enumerate(line.vertices()):

                ptprop = {}
                ptexte = {}
                for key in pt_properties:
                    ptprop[key] = line.d[key][i]
                    if len(xy) == 3:
                        ptprop["ele"] = xy[2]
                for key in pt_extensions:
                    ptexte[key] = line.d[key][i]

                points.append(Point((xy[0], xy[1]), ptprop, ptexte))

            segments.append(Trkseg(points, sg_properties, sg_extensions))

        self.tracks.append(Track(segments, properties, extensions))
        return

    def add_route(self, route):
        """ Add a Multipoint-like object as a route. Properties and extension
        types for the route are taken from the `properties` attribute of the
        Multipoint-like object.

        Properties and extensions types for each route point are taken from the
        `data` attribute of each Line-like object.

        INCOMPLETE:

        Needs to distinguish between properties and extensions at the trkseg
        and trkpt levels

        Needs to properly add and <ele> property for Lines of rank 3
        """
        points = []
        for i, vertex in enumerate(route.vertices()):
            prop = {}
            if route.data is not None:
                for k in route.data.fields:
                    prop[k] = route.data[k][i]
            points.append(Point((vertex[0], vertex[1]), prop, {}))
        self.routes.append(Route(points, route.properties, {}))
        return

    def as_string(self, waypts=True, tracks=True, routes=True):
        """ Write GPX object to a string. Writes all waypoints, tracks, and
        routes by default, which can be changed by changing the kwargs to
        False. """
        gpx = Element(ns + "gpx", version="1.1", creator="karta")

        if waypts:
            for waypt in self.waypts:
                gpx.append(self._build_gpx_wpt(waypt))
        if tracks:
            for track in self.tracks:
                gpx.append(self._build_gpx_trk(track))
        if routes:
            for route in self.routes:
                gpx.append(self._build_gpx_rte(route))

        xmlstring = ET.tostring(gpx).decode("ascii")
        return xmlstring

    def writefile(self, fnm, **kw):
        with open(fnm, "w") as f:
            f.write(self.as_string(**kw))
        return