working on it ...

Filters

Explore Public Snippets

Sort by

Found 140 snippets

    public by waxmiguel  2760  0  5  1

    tortouise

    # TortoiseGit 
    
    $Global:TortoiseGitSettings = new-object PSObject -Property @{
      TortoiseGitPath = "C:\Program Files\TortoiseGit\bin\TortoiseProc.exe"
    }
    
    function tgit {
       if($args) {
        if($args[0] -eq "help") {
          # Replace the built-in help behaviour with just a list of commands
          $tortoiseGitCommands
          return    
        }
    
        $newArgs = @()
        $newArgs += "/command:" + $args[0]
        
        $cmd = $args[0]
        
        if($args.length -gt 1) {
          $args[1..$args.length] | % { $newArgs += $_ }
        }
          
        & $Global:TortoiseGitSettings.TortoiseGitPath $newArgs
      }
    }
    
    $tortoiseGitCommands = @(
    "about",
    "log",
    "commit",
    "add",
    "revert",
    "cleanup" ,
    "resolve",
    "switch",
    "export",
    "merge",
    "settings",
    "remove",
    "rename",
    "diff",
    "conflicteditor",
    "help",
    "ignore",
    "blame",
    "cat",
    "createpatch",
    "pull",
    "push",
    "rebase",
    "stashsave",
    "stashapply",
    "subadd",
    "subupdate",
    "subsync",
    "reflog",
    "refbrowse",
    "sync"
    ) | sort
    

    public by cghersi  2369  11  5  3

    How to write bytes into file in Java

    Efficient way to write strings or bytes onto a file.
      import java.nio.file.Files;
      import java.nio.file.Paths;
    
      public static void writeFile(String path, String content) throws Exception {
    		if (isNullOrEmpty(path) || isNullOrEmpty(content)) {
    			return;
    		}
    		Files.write(Paths.get(path), content.getBytes());
    	}                     

    public by cghersi  2600  3  5  0

    Read file in Java

    Efficient way to read file in Java using Files class
      import java.nio.file.Files; 
      import java.nio.file.Paths;
    
      public static String readFile(String path) throws Exception {
    		if (isNullOrEmpty(path)) {
    			return "";
    		}
    		return new String(Files.readAllBytes(Paths.get(path)));
    	}      

    public by cghersi  289896  2  8  0

    How to read a file into a string in Java

    This simple snippet reads a file and put the content into a returned string
    private static String readFileAsString(String filePath) throws java.io.IOException{
    
    	StringBuffer fileData = new StringBuffer(1000);
    	BufferedReader reader = new BufferedReader(new FileReader(filePath));
    	char[] buf = new char[1024];
    	int numRead=0;
    	while((numRead=reader.read(buf)) != -1){
    		String readData = String.valueOf(buf, 0, numRead);
    		fileData.append(readData);
    		buf = new char[1024];
    	}
    
    	reader.close();
    	return fileData.toString();
    }            

    public by cghersi  2323  5  6  0

    How to post an HTTP Request

    just consume a RESTful API via POST request
    public String sendPostReq(String url, String data, boolean addAccessToken) {
    		// Create a new client:
    		DefaultHttpClient httpClient = createHttpClient(url.startsWith("https"));
    		HttpPost httppost = new HttpPost(url);
    		httppost.setHeader("Content-Type", "application/x-www-form-urlencoded");
    		httppost.setHeader("Charset", "UTF-8");
    		httppost.setHeader("Accept", m_requestFormat.getMimeType());
    		httppost.setHeader(S2C_HEADER, S2C_HEADER_VALUE);
    
    		//access the secured service with the authorization cookie
    		if (addAccessToken && !Utils.isNullOrEmpty(m_accessToken)) {
    			addAccessTokenToCookies();
    		}
    		httpClient.setCookieStore(m_cookies);
    		try {
    			httppost.setEntity(new StringEntity(data, "UTF-8"));
    		} catch (UnsupportedEncodingException e1) {
    			log.error("Cannot encode data: " + data + " due to " + e1);
    			return "";
    		}
    
    		HttpResponse response = null;
    		String res = "";
    		try {
    			response = httpClient.execute(httppost);
    			res = readStreamData(response.getEntity().getContent());
    			log.info("Response:" + res);
    		} catch (org.apache.http.conn.HttpHostConnectException e) {
    			log.error("Cannot receive response due to " + e);
    			if (url.contains(LOGIN_URL))
    				res = TIMEOUT_RESP;
    		} catch (IOException e) {
    			log.error("Cannot parse incoming response due to " + e);
    		} finally {
    			httpClient.getConnectionManager().shutdown();
    		}
    		
    		m_cookies = httpClient.getCookieStore(); //save cookies for the next secured run		
    		return res;
    	}

    public by lauhin  5292  3  7  1

    Count chars in a String in Java

    Count chars in Strings or letters in words in Java using the Spring framework
    import org.springframework.util.StringUtils;
    
    int occurance = StringUtils.countOccurrencesOf("012405802569015014", "0"); //returns 5
    int occurance = StringUtils.countOccurrencesOf("hello world", "l"); //returns 3

    public by lauhin  4563  11  5  0

    Java date to String

    this code converts a java date to a String
    //this code converts a java date to a string
    DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
    String reportDate = df.format(today);

    public by lauhin  4878  1  5  0

    Interator to stream in Java 8

    makes a java 8 stream from an iterator
    //this method converts a iterator to a stream. This can only be used in Java 8
    public static <T> Stream<T> iteratorToStream(final Iterator<T> iterator, final boolean parallell) {
      Iterable<T> iterable = () -> iterator;
      return StreamSupport.stream(iterable.spliterator(), parallell);
    }
    
    //here I show you how to use this method. You need this try arround it so Java will close the stream automatically after using it.
    try (Stream<???> stream = Utils.<???>iteratorToStream(anIterator, true)) {
      
    }

    public by cghersi  105428  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 sTiLL-iLL @ SniPitz-KND  4041  3  7  18

    mark out your sites, this labels the most visited link from your browser!

    get MVLinkage.js
    //  this makes a "most visited" link element.  //
    //-------------------------------------------------//
      
    function spawnMVLink(params, href, title, text, direction, provider) {
      
      var styles = getMostVisitedStyles(params, !!text),
          link = document.createElement('a');
          link.style.color = styles.color;
          link.style.fontSize = styles.fontSize + 'px';
          
      if (styles.fontFamily) {
          link.style.fontFamily = styles.fontFamily;
        }
        
      if (styles.textAlign) {
          link.style.textAlign = styles.textAlign;
        }
        
      if (styles.textFadePos) {
        var dir = /^rtl$/i.test(direction) ? 'to left' : 'to right';
        var mask = 'linear-gradient(' + dir + ', rgba(0,0,0,1),' +
            'rgba(0,0,0,1) ' + styles.textFadePos + 'px, rgba(0,0,0,0))';
            
        link.style.textOverflow = 'clip';
        link.style.webkitMask = mask;
      }
      
      link.href = href;
      link.title = title;
      link.target = 'top';
      link.tabIndex = '0';
      
      if (text) { 
        link.textContent = text;
      }
      link.addEventListener('focus', function() {
        window.parent.postMessage('linkFocused', DOMAIN_ORIGIN);
      });
      
      link.addEventListener('blur', function() {
        window.parent.postMessage('linkBlurred', DOMAIN_ORIGIN);
      });
      
      var navigate = function doNav(e) {
        
        var isFrmSrvr = 'url' in params;
        if (isFrmSrvr && params.ping) {
          ping(DOMAIN_ORIGIN + params.ping);
        }
        
        var handle = location;
        if ('pos' in params && isFinite(params.pos)) {
          handle.logMV(parseInt(params.pos, 10), provider || '');
        }
        
        if (!isFrmSrvr) {
          e.preventDefault();
          handle.navigateContentWindow(href, getEventDisposition(e));
        }
      };
      
      link.addEventListener('click', navigateFunction);
      
      link.addEventListener('keydown', function(event) {
          if (event.keyCode == 46 || event.keyCode == 8 ) {
            event.preventDefault();
            window.parent.postMessage('tileBlacklisted,' + params.pos, DOMAIN_ORIGIN);
          } 
          else if (event.keyCode == 13 || event.keyCode == 32 ) {
            navigate(event);
          }
      });
      return link;
    }            
    • Public Snippets
    • Channels Snippets