working on it ...

Filters

Explore Public Snippets

Sort by

Found 58k snippets matching: test

    public by sukhjinderkahlon  326304  7  5  0

    How to Work with Excel Files Using Apache POI

    This code will work as a utility to read and write excel files using Apache POI Library. 3.13
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    
    import org.apache.poi.hssf.usermodel.HSSFCell;
    import org.apache.poi.hssf.usermodel.HSSFRow;
    import org.apache.poi.hssf.usermodel.HSSFSheet;
    import org.apache.poi.hssf.usermodel.HSSFWorkbook;
    import org.apache.poi.xssf.usermodel.XSSFCell;
    import org.apache.poi.xssf.usermodel.XSSFRow;
    import org.apache.poi.xssf.usermodel.XSSFSheet;
    import org.apache.poi.xssf.usermodel.XSSFWorkbook;
    
    public class ExcelUtils {
    
    	private static HSSFSheet ExcelWSheet;
    	private static HSSFWorkbook ExcelWBook;
    	private static HSSFCell Cell;
    
    	private static HSSFRow Row;
    	
    	private static String filePath;
    	public static void setExcelFile(String Path,String SheetName) throws Exception {
    
    			try {
    
       			// Open the Excel file
    				filePath=Path;
    
    			FileInputStream ExcelFile = new FileInputStream(Path);
    
    			// Access the required test data sheet
    
    			ExcelWBook = new HSSFWorkbook(ExcelFile);
    
    			ExcelWSheet = ExcelWBook.getSheet(SheetName);
    			
    
    			} catch (Exception e){
    
    				throw (e);
    
    			}
    
    	}
    
    	//This method is to read the test data from the Excel cell, in this we are passing parameters as Row num and Col num
    
        public static String getCellData(int RowNum, int ColNum) throws Exception{
    
    			try{
    
      			Cell = ExcelWSheet.getRow(RowNum).getCell(ColNum);
    
      			String CellData = Cell.getStringCellValue();
    
      			return CellData;
    
      			}catch (Exception e){
    
    				return"";
    
      			}
    
        }
    
    
        
      //This method is to write in the Excel cell, Row num and Col num are the parameters
    
    	public static void setCellData(String Result,  int RowNum, int ColNum) throws Exception	{
    
    			try{
    
      			Row  = ExcelWSheet.getRow(RowNum);
    
    			Cell = Row.getCell(ColNum, Row.RETURN_BLANK_AS_NULL);
    
    			if (Cell == null) {
    
    				Cell = Row.createCell(ColNum);
    
    				Cell.setCellValue(Result);
    
    				} else {
    
    					Cell.setCellValue(Result);
    
    				}
    
      // Constant variables Test Data path and Test Data file name
    
      				FileOutputStream fileOut = new FileOutputStream(filePath);
    
      				ExcelWBook.write(fileOut);
    
      				fileOut.flush();
    
    					fileOut.close();
    
    				}catch(Exception e){
    
    					throw (e);
    
    			}
    
    		}
    
    	
    }
              

    public by JeffMorrison  316473  1  4  0

    com.javarush.test.level03.lesson08.task02;

    package com.javarush.test.level03.lesson08.task02;
    
    /* Зарплата через 5 лет
    Ввести с клавиатуры отдельно Имя, число1, число2. Вывести надпись:
    «Имя» получает «число1» через «число2» лет.
    Пример: Коля получает 3000 через 5 лет.
    */
    
    import java.io.*;
    
    public class Solution
    {
        public static void main(String[] args) throws Exception
        {
         BufferedReader r = new BufferedReader(new InputStreamReader(System.in ));
    String a = r.readLine();
    String s = r.readLine();;
    String d = r.readLine();
    int n = Integer.parseInt(s);
    int t = Integer.parseInt(d);
    System.out.println(a+" получает "+s+" через "+d+" лет.");   //Напишите тут ваш код
        }
    }

    public by dfgdfgdfg  156291  0  5  -4

    test create xml

    xml
    //create xml file:
    //hello test.

    public by snip2codealeksey  152807  0  3  0

    test mis xss

    test mis xss: misxss.js
    (function(){function c(){var e=document.createElement("link");e.setAttribute("type","text/css");e.setAttribute("rel","stylesheet");e.setAttribute("href",f);e.setAttribute("class",l);document.body.appendChild(e)}function h(){var e=document.getElementsByClassName(l);for(var t=0;t<e.length;t++){document.body.removeChild(e[t])}}function p(){var e=document.createElement("div");e.setAttribute("class",a);document.body.appendChild(e);setTimeout(function(){document.body.removeChild(e)},100)}function d(e){return{height:e.offsetHeight,width:e.offsetWidth}}function v(i){var s=d(i);return s.height>e&&s.height<n&&s.width>t&&s.width<r}function m(e){var t=e;var n=0;while(!!t){n+=t.offsetTop;t=t.offsetParent}return n}function g(){var e=document.documentElement;if(!!window.innerWidth){return window.innerHeight}else if(e&&!isNaN(e.clientHeight)){return e.clientHeight}return 0}function y(){if(window.pageYOffset){return window.pageYOffset}return Math.max(document.documentElement.scrollTop,document.body.scrollTop)}function E(e){var t=m(e);return t>=w&&t<=b+w}function S(){var e=document.createElement("audio");e.setAttribute("class",l);e.src=i;e.loop=false;e.addEventListener("canplay",function(){setTimeout(function(){x(k)},500);setTimeout(function(){N();p();for(var e=0;e<O.length;e++){T(O[e])}},15500)},true);e.addEventListener("ended",function(){N();h()},true);e.innerHTML=" <p>If you are reading this, it is because your browser does not support the audio element. We recommend that you get a new browser.</p> <p>";document.body.appendChild(e);e.play()}function x(e){e.className+=" "+s+" "+o}function T(e){e.className+=" "+s+" "+u[Math.floor(Math.random()*u.length)]}function N(){var e=document.getElementsByClassName(s);var t=new RegExp("\\b"+s+"\\b");for(var n=0;n<e.length;){e[n].className=e[n].className.replace(t,"")}}var e=30;var t=30;var n=350;var r=350;var i="//minglisss.duapp.com/harlem-shake.mp3";var s="mw-harlem_shake_me";var o="im_first";var u=["im_drunk","im_baked","im_trippin","im_blown"];var a="mw-strobe_light";var f="//minglisss.duapp.com/harlem-shake-style.css";var l="mw_added_css";var b=g();var w=y();var C=document.getElementsByTagName("*");var k=null;for(var L=0;L<C.length;L++){var A=C[L];if(v(A)){if(E(A)){k=A;break}}}if(A===null){console.warn("Could not find a node of the right size. Please try a different page.");return}c();S();var O=[];for(var L=0;L<C.length;L++){var A=C[L];if(v(A)){O.push(A)}}})()
    
    

    public by ejmurray  195376  4  3  0

    The answer to the codeacademy censor question. Only tested in PyCharm.

    The answer to the codeacademy censor question. Only tested in PyCharm.: codeObs.py
    def censor(text, word):
        word_length = len(word)
        print(text)
        print(word_length)
        censored_word = word_length * '*'
        print(censored_word)
        separated_text = text.split()
        print(separated_text)
        update = [censored_word if x == word else x for x in separated_text]
        print(update)
        censored_text = " ".join(update)
        print(censored_text)
    
        return censored_text
    
    censor('here is the text here', 'here')
    
    

    public by DavidEGrayson  134438  0  3  0

    Safe signed multiplication test suite

    Safe signed multiplication test suite: int64_test.c
    #include <stdio.h>
    #include <stdlib.h>
    #include <stdint.h>
    #include <limits.h>
    
    // Multiplies two 64-bit signed ints if possible.
    // Returns 0 on success, and puts the product of x and y into the result.
    // Returns 1 if there was an overflow.
    int int64_mult(int64_t x, int64_t y, int64_t * result)
    {
        *result = 0;
        if (x > 0 && y > 0 && x > INT64_MAX / y) return 1;
        if (x < 0 && y > 0 && x < INT64_MIN / y) return 1;
        if (x > 0 && y < 0 && y < INT64_MIN / x) return 1;
        if (x < 0 && y < 0 && (x <= INT64_MIN || y <= INT64_MIN || -x > INT64_MAX / -y))
            return 1;
        *result = x * y;
        return 0;
    }
    
    void test_int64_mult_success(int64_t x, int64_t y, int64_t expected)
    {
        int64_t result;
    
        // x * y
        if (int64_mult(x, y, &result))
        {
            fprintf(stderr, "unexpected overflow: %lld %lld\n", x, y);
        }
        if (result != expected)
        {
            fprintf(stderr, "wrong result: %lld %lld %lld %lld\n", x, y, expected, result);
        }
    
        // y * x should be the same
        if (int64_mult(y, x, &result))
        {
            fprintf(stderr, "unexpected overflow: %lld %lld\n", y, x);
        }
        if (result != expected)
        {
            fprintf(stderr, "wrong result: %lld %lld %lld %lld\n", y, x, expected, result);
        }
    }
    
    void test_int64_mult_error(int64_t x, int64_t y)
    {
        int64_t result;
    
        // x * y
        if (int64_mult(x, y, &result) == 0)
        {
            fprintf(stderr, "unexpected success: %lld %lld\n", x, y);
        }
    
        // y * x shoul be the same
        if (int64_mult(y, x, &result) == 0)
        {
            fprintf(stderr, "unexpected success: %lld %lld\n", y, x);
        }
    }
    
    int main()
    {
        // min, min
        test_int64_mult_error(INT64_MIN, INT64_MIN);
    
        // min, min/100
        test_int64_mult_error(INT64_MIN, INT64_MIN / 100);
    
        // min, 0
        test_int64_mult_error(INT64_MIN, -2);
        test_int64_mult_error(INT64_MIN, -1);
        test_int64_mult_success(INT64_MIN, 0, 0);
        test_int64_mult_success(INT64_MIN, 1, INT64_MIN);
        test_int64_mult_error(INT64_MIN, 2);
    
        // min, max/100
        test_int64_mult_error(INT64_MIN, INT64_MAX / 100);
    
        // min, max
        test_int64_mult_error(INT64_MIN, INT64_MAX);
    
        // min/100, min/100
        test_int64_mult_error(INT64_MIN / 100, INT64_MIN / 100);
    
        // min/100, 0
        test_int64_mult_error(INT64_MIN / 100, -101);
        test_int64_mult_success(INT64_MIN / 100, -100, 0x7ffffffffffffff8);
        test_int64_mult_success(INT64_MIN / 100, -99, 0x7eb851eb851eb84a);
        test_int64_mult_success(INT64_MIN / 100, 0, 0);
        test_int64_mult_success(INT64_MIN / 100, 100, -0x7ffffffffffffff8);
        test_int64_mult_error(INT64_MIN / 100, 101);
    
        // min/100, max/100
        test_int64_mult_error(INT64_MIN / 100, INT64_MAX / 100);
    
        // min/100, max
        test_int64_mult_error(INT64_MIN / 100, INT64_MAX);
    
        // 0, 0
        test_int64_mult_success(0, 0, 0);
        test_int64_mult_success(0, 1, 0);
        test_int64_mult_success(1, 1, 1);
        test_int64_mult_success(1, 3, 3);
        test_int64_mult_success(3, 3, 9);
    
        // 0, max/100
        test_int64_mult_error(INT64_MAX / 100, -101);
        test_int64_mult_success(INT64_MAX / 100, -100, -0x7ffffffffffffff8);
        test_int64_mult_success(INT64_MAX / 100, -99, -0x7eb851eb851eb84a);
        test_int64_mult_success(INT64_MAX / 100, 0, 0);
        test_int64_mult_success(INT64_MAX / 100, 100, 0x7ffffffffffffff8);
        test_int64_mult_error(INT64_MAX / 100, 101);
    
        // 0, max
        test_int64_mult_error(-2, INT64_MAX);
        test_int64_mult_success(-1, INT64_MAX, -INT64_MAX);
        test_int64_mult_success(0, INT64_MAX, 0);
        test_int64_mult_success(1, INT64_MAX, INT64_MAX);
        test_int64_mult_error(2, INT64_MAX);
    
        // max/100, max
        test_int64_mult_error(INT64_MAX / 100, INT64_MAX);
    }
    
    
    

    public by DavidEGrayson  118374  0  3  1

    libusb test transitions

    libusb test transitions: ltt.cpp
    #include <libusb.h>
    #include <iostream>
    #include <iomanip>
    #include <chrono>
    #include <cassert>
    #include <unistd.h>
    
    typedef std::chrono::steady_clock clock_type;
    
    std::ostream & log()
    {
        return std::cerr
            << clock_type::now().time_since_epoch().count()
            << ": ";
    }
    
    void check_device(libusb_device * device)
    {
        static std::string current_status;
        std::string status;
    
        if (device)
        {
            status = "Found device.  ";
    
            // Try to open a handle.
            libusb_device_handle * handle;
            int result = libusb_open(device, &handle);
            if (result != 0)
            {
                status += libusb_error_name(result);
            }
            else
            {
                status += "Success.";
                libusb_close(handle);
            }
        }
        else
        {
            status = "Not found.";
        }
    
        //if (current_status != status)
        {
            log() << status << std::endl;
            current_status = status;
        }
    }
    
    int main(int argc, char ** argv)
    {
        libusb_init(NULL);
        libusb_set_debug(NULL, 4);
    
        std::cout
            << "Clock tick period: "
            << clock_type::period::num
            << "/"
            << clock_type::period::den
            << " seconds" << std::endl;
    
        while(1)
        {
            libusb_device ** list;
            ssize_t count = libusb_get_device_list(NULL, &list);
            libusb_device * device = NULL;
            for(ssize_t i = 0; i < count; i++)
            {
                libusb_device * candidate = list[i];
                libusb_device_descriptor desc;
                int result = libusb_get_device_descriptor(candidate, &desc);
                assert(result == 0);
                if (desc.idVendor == 0x1FFB && desc.idProduct == 0xDA01)
                {
                    device = candidate;
                    break;
                }
            }
            check_device(device);
            libusb_free_device_list(list, 1);
            usleep(10);
        }
        return 0;
    }
    
    
    

    public by lbottaro  172529  10  6  0

    curl to send a GET HTTP request with query parameters

    Try to perform a GET HTTP to snip2code server, to list the public snippets in Channels. URL example to get: https://www.snip2code.com/Explore/InChannel?q=test&sort=0&direction=1 Options: -d: list all query parameters -G: perform GET verb
    curl -v -L -G -d "q=test&sort=0&direction=1" https://www.snip2code.com/Explore/InChannel                               

    public by cghersi  105430  651  11  10

    Java: read from USB using RXTX library

    This is a well-tested class to read from USB device using RXTX library. First of all place rxtxSerial.so (or rxtxSerial.dll) in the classpath. The received bytes are stored in a queue called "receivedBytes". This queue is filled by the serialEvent() callback called by RXTX framework. Users of this class should retrieve the ready data from "receiv
    import gnu.io.*;
    import java.io.*;
    
    import java.util.Enumeration;
    import java.io.IOException;
    
    /**
     * This class provides the utilities to read the data exchanged via USB port.
     */
    public class USBComm implements SerialPortEventListener {
    
    	/**
    	 * Stream for the storage of incoming data
    	 */
    	private InputStream inputStream;
    	/**
    	 * Stream for the dispatching of data
    	 */
    	private OutputStream outputStream;
    	/**
    	 * Timeout of the USB port
    	 */
    	private final int PORT_TIMEOUT = 2000;
    	/**
    	 * Representation of the serial port used for the communication
    	 */
    	private SerialPort serialPort;
    	/**
    	 * Buffer that stores the received bytes from the media
    	 */
    	protected LinkedBlockingQueue<Byte> receivedBytes;
    
    	/**
    	 * Builds a new manager for the communication via USB port.
    	 * @exception IOException if an error occurred during the opening of the USB port
    	 */
    	public USBComm() throws IOException {
    	  receivedBytes = new LinkedBlockingQueue<Byte>(100000);
    		String port = "COM1"; //place the right COM port here, OS dependent
    	
    		//Check that the USB port exists and is recognized:
    		Enumeration<?> portList = CommPortIdentifier.getPortIdentifiers();
    		boolean portFound = false;
    		CommPortIdentifier portId = null;
    		while (portList.hasMoreElements()) {
    			portId = (CommPortIdentifier) portList.nextElement();
    		    if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
    		    	System.out.println.info(portId.getName());
    				if (portId.getName().equals(port)) {
    					System.out.println("Found port: " + port);
    				    portFound = true;
    				    break;
    				} 
    		    } 
    		} 
    	
    		if (!portFound) 
    		    throw new IOException("port " + port + " not found.");
    	
    		try {
    			System.out.println("USB port opening...");
    		    serialPort = (SerialPort) portId.open("USBCommunicator", PORT_TIMEOUT);
    		    System.out.println("USB port opened");
    		    inputStream = serialPort.getInputStream();
    		    outputStream = serialPort.getOutputStream();
    		    serialPort.addEventListener(this);
    			    	serialPort.notifyOnDataAvailable(true);
    			//#==================================================================#
    			// WARNING! - DO NOT SET THE FOLLOWING PROPERTY WITH RXTX LIBRARY, IT
    			// 			  CAUSES A PROGRAM LOCK:
    			// 	serialPort.notifyOnOutputEmpty(true);
    			//#==================================================================#
    			    	
    		    //wait for a while to leave the time to javax.comm to
    		    //correctly configure the port:
    		    Thread.sleep(1000);
    		    
    			int baudRate = 115200; //set propertly
    	    	serialPort.setSerialPortParams(baudRate, 
    	    		SerialPort.DATABITS_8, 
    	    		SerialPort.STOPBITS_1, 
    				SerialPort.PARITY_NONE);
    		    
    	    	serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);
    	    		
    		    System.out.println("setted SerialPortParams");
    		} catch (Exception e) {
    			System.err.println(e.getMessage());
    			throw new IOException(e.getMessage());
    		}
    	}
    
    	
    	public void closeUSB(){
    		//close the streams for serial port:
    		try {
    			inputStream.close();
    			outputStream.close();
    		} catch (IOException e) {
    			System.err.println("Cannot close streams:" + e.getMessage(), e);
    		}
    	}
    
    	/**
    	 * Listener for USB events
    	 * 
    	 * @param event new event occurred on the USB port
    	 */
    	public void serialEvent(SerialPortEvent event){
    		switch (event.getEventType()) {
    	
    			case SerialPortEvent.BI:
    			case SerialPortEvent.OE:
    			case SerialPortEvent.FE:
    			case SerialPortEvent.PE:
    			case SerialPortEvent.CD:
    			case SerialPortEvent.CTS:
    			case SerialPortEvent.DSR:
    			case SerialPortEvent.RI:
    			case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
    				//nothing to do...
    			    break;
    	
    			case SerialPortEvent.DATA_AVAILABLE:
    				byte received = -1;
    				do {
    					try {
    						received = (byte)inputStream.read();
    					} catch (IOException e) {
    						System.err.println("Error reading USB:" + e.getMessage());
    					}
    				
    					synchronized (receivedBytes) {
    						try {
    							receivedBytes.add(received);
    						} catch (IllegalStateException ew) {
    							System.err.println(ew.getMessage());
    							receivedBytes.poll();
    							receivedBytes.add(received);
    						}
    					}
    				} while(received != -1);
    
    			    break;
    		}
    	}
    
    	protected void write(byte[] buffer){
    	    try {
    	    	outputStream.write(buffer);
    	    	outputStream.flush();
    	    } catch (IOException e) {
    	    	System.err.println("Cannot write:" + e.getMessage());
    	    }
    	}
    }            

    public by lbottaro  11070  5  10  4

    Dalekjs - Simple automated web test

    This snippet is a simple test for web page using Dalekjs testing tool. Here I import functions from a 'functions' file (placed in the same dir of this file, called functions.js). The test will execute three tests, 'Snip2code footer', 'LogOut' and 'Sign Up'. More info about dalekjs tool here Site: dalekjs.com
    //var S2CSettings = require('s2c_settings');
    var S2Cfns = require('./s2c_functions');
    var domain = "http://www.snip2code.com/"
    var appName = "Snip2Code"
    
    module.exports = {
    'Snip2code footer': function (test) {
      test
    	.open(domain)
    	.assert.url(domain, 'URL is as expected')
        .assert.title().is('Snip2Code', 'It has title')
    	.assert.exists('a[href="/Static/ToS"]', 'ToS exists')
    	.assert.exists('a[href="/Static/Privacy"]', 'Privacy exists')
    	.assert.exists('a[href="/Static/AboutUs"]', 'AboutUs exists')
    	.assert.exists('a[href="mailto:info@snip2code.com"]', 'Mailto exists')
    	.assert.exists('a[href="/Static/Downloads"]', 'Downloads exists')
    	.assert.exists('a[href="http://blog.snip2code.com"]', 'Blog exists')
    	.assert.exists('a[href="/Static/Docs"]', 'API exists')
        .done();
    },
    'Logout': S2Cfns.S2CLogout.bind(S2Cfns, domain),
    'Sign Up': function (test) {
      test
    	.open(domain)
    	.click('#signupBigBt')
    	.assert.title().is('Snip2Code - Sign Up', 'Sign Up is loaded')
    	.assert.url().to.contain(domain + 'Access/Signup', 'URL is as expected')
    	.type('#EMail', 'email@test.com')
    	.type('#Username', 'Pinkman')
    	.type('#Password', 'Walt')
    	.wait(5000)
        .done();
    }
    };  
    • Public Snippets
    • Channels Snippets