Are you looking for customized advices? Click here to contact the expert!
Want to advertise here? Contact us!
cghersi
cghersi
Reputation Top 1%
Cristiano Ghersi
Great passion for Software Engineering, mostly coding in Java and C#, I enjoy creating modular and reusable code for everybody!
170 Snippets  (1st place)
Published
13 Channels
Created
54 Channels
Following
2 hours ago
Last Visit
May 5, 2012
Registered
5231 points  (1st place)
Reputation
Top 5% Publisher
Junior Code Generator
Serious Code Generator
Senior Code Generator
Master Code Generator
Guru Code Generator
Junior Publisher
Serious Publisher
Senior Publisher
Master Publisher
Guru Publisher
Master Topic Creator
Guru Topic Creator
Junior Topic Hub
Serious Topic Hub
Senior Topic Hub
Master Topic Hub
Junior Trend Maker
Serious Trend Maker
Senior Trend Maker
Senior Team Manager
Junior Influencer
Serious Influencer
Senior Influencer
Junior Commenter
Serious Commenter
Senior Commenter
Master Commenter
Junior Judge
Serious Judge
Senior Judge
Master Judge
Junior Popular Coder
Serious Popular Coder
Senior Popular Coder
Master Popular Coder
Guru Popular Coder
Junior Autobiographer
Serious Autobiographer
Senior Autobiographer
Master Autobiographer
Junior Snip2Coder
Serious Snip2Coder
Senior Snip2Coder
Junior Geek Aggregator
Serious Geek Aggregator
Senior Geek Aggregator
Junior Famous Coder

Recent Snippets See all snippets by cghersi

public by cghersi modified Oct 14, 2014  1  3  3

How to prettify a number with thousands or millions

Prepares a pretty version of the given number, with the ability to match the right plural/singular form for English text
public static string PaintNumber(int number, string followingText = "", bool numberInBold = false)
{
  string content = String.Format("{0:N0}", number);
  if (number >= 10000)
  {
    double numberInThousands = number / 1000.0;
    if (numberInThousands < 100)
      content = String.Format("{0:N0}k", numberInThousands);
    else
      content = String.Format("{0:0.#}M", numberInThousands / 1000.0);
  }
  if (number >= 1000000)
  {
    double numberInMillions = number / 1000000.0;
    if (numberInMillions < 100)
      content = String.Format("{0:N0}M", numberInMillions);
    else
      content = String.Format("{0:0.#}B", numberInMillions / 1000.0);
  }

  if (numberInBold)
    content = "<b>" + content + "</b>";

  if (!string.IsNullOrEmpty(followingText))
    content += " " + followingText + (number != 1 ? "s" : "");

  return content;
}

public by cghersi modified Oct 2, 2014  3683  10  3

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
usb
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) {
		    	log.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 cghersi modified Oct 1, 2014  1  3  2

C#: Read the output parameter of a stored procedure

fetch the output parameter of the given SP and try to read it
static public string ReadOutputParam(this SqlCommand sqlCmd, string outputParamName, string defaultValue = "")
{
  object outputValue = defaultValue;
  if (!string.IsNullOrEmpty(outputParamName))
    outputValue = sqlCmd.Parameters[outputParamName].Value;

  if ((outputValue == null) || (outputValue.Equals(DBNull.Value)))
    return defaultValue;
  else
    return outputValue.ToString();
}

public by cghersi modified Sep 26, 2014  1  3  2

XOR in C#

Given that technically there isn't a XOR conditional operator (like &&, ||, etc.), the best way to perform a XOR in a conditional statement is to use != operator, because it evaluates to a boolean
bool a = true;
bool b = false;
if (a != b)
  return true;
else
  return false;

public by cghersi @ Snip2CodeDev modified Sep 19, 2014  4  3  4

Snip2Code Value Proposition

Here there's a depict of how Snip2Code could help companies in improving their performance in the software development activities
public static void checkEfficiency() {		
	//let the company adopt Snip2Code:
	Company acme = new Company(Goal.FASTER_TIME_TO_MARKET);
	acme.adoptSnip2Code();
	
	//check how a coder become more efficient with the use of Snip2Code tools:
	Coder alice = acme.getCoder();
	Results[] aliceResults = alice.getOptimizations();
	
	//check results:
	if ((aliceResults[0] == Results.EFFICIENT_CODE_FIND) &&
		(aliceResults[1] == Results.REUSE_CODE) &&
		(aliceResults[2] == Results.PRESERVE_KNOWLEDGE) &&
		(aliceResults[3] == Results.SHARE_KNOWLEDGE)) {
		
		print("Yes, this is what you can get from Snip2Code!");			
	} else {			
		print("This is not an option!");			
	}
}