working on it ...

Filters

Explore Public Snippets

Sort by

Found 17k snippets matching: users

    public by cghersi modified Jan 29, 2016  104531  568  11  11

    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 cghersi modified Feb 16, 2014  3068  0  7  1

    Create a complete user for SQL Server security

    This is a useful script to correctly create a user able to access SQL Server instance with an SQL account. Make sure to create the login and THEN the user!
    IF  EXISTS (SELECT * FROM sys.database_principals WHERE name = N'MyLoginName')
    	DROP USER [MyLoginName]
    GO
    
    IF  EXISTS (SELECT * FROM sys.syslogins WHERE name = N'MyLoginName')
    BEGIN
        EXEC sp_change_users_login 'Auto_Fix', 'MyLoginName', NULL, 'mystrongpsw';
    END
    ELSE
    BEGIN
        CREATE LOGIN [MyLoginName] WITH PASSWORD=N'mystrongpsw', DEFAULT_LANGUAGE=[us_english], CHECK_EXPIRATION=OFF, CHECK_POLICY=OFF
    END
    
    CREATE USER [MyLoginName] FROM LOGIN [MyLoginName]
    GO 

    public by cghersi @ MailUp API DEV modified Aug 29, 2018  1744  8  5  0

    MailUp REST API - How to retrieve information of SMTP+ Users

    This snippet takes advantage of the MailUp .NET SDK to setup the secure communication towards the server. The credentials of the SMTP+ user are passed as parameter in the body of the request. You can optionally specify a username as third parameter in order to filter the resulting list.
    public static void GetUserInfo()
    {
      // 1) Required values
      string username = "<your_username>";
    	string password = "<your_password>";
    
    	string clientid = "<your_clientid>";
    	string clientsecret = "<your_clientsecret>";
    
    	string smtpplus_username = "<your_smtpplus_username>";
    	string smtpplus_password = "<your_smtpplus_password>";
      
      // 2) Setup the MailUp Client:
    	MailUpClient client = new MailUpClient(clientid, clientsecret);
    	client.RetrieveAccessToken( username, password );
    
      // 3) Invoke the web method:
      List<UserInfoDTO> result = null;
      try
      {
        result = client.ListUserInfo(smtpplus_username, smtpplus_password);
      }
      catch (Exception ex)
      {
        Console.WriteLine("Cannot perform the operation due to " + ex.Message);
        return;
      }
    
      // 4) Print results:
      if (result != null)
        Console.WriteLine("Retrieved users total:" + result.Count);
      else
        Console.WriteLine("An error occurred while retrieving users.");
    }
    																		

    public by markcl modified Aug 11, 2013  2694  0  5  0

    Laravel 4 Sentry Redirect Users to Dasboard Snippet

    $jobseekers = Sentry::getGroupProvider()->findByName('Jobseekers');
    $employers = Sentry::getGroupProvider()->findByName('Employers');
    	if($user->inGroup($jobseekers))
    	    return Redirect::to('employerDashboard');
    	// If user is in employers group, go to Jobhunter's Dashboard
    	if($user->inGroup($employers))
    	    return Redirect::to('employerDashboard');

    public by scotsman2k modified Dec 29, 2014  1905  2  5  1

    change users password in non interactive one line of code

    as root change users password, can be used in following script form
    echo "linuxpassword" | passwd --stdin username
    Or to change passwords in a list of servers;
    # for ((i=1;i<=100;i++)); do ssh 10.1.0.$i 'echo -e "linuxpassword\nlinuxpassword" | passwd linuxuser'; done;
    
    

    public by jewie1000 modified Jul 20, 2018  567  9  4  1

    Best Forty Aimbot/ESP Users | CB:RO Hackers

    DanielTCZ#0768
    ! Yu_riTCZ#2291
    fire#1443
    krump#8883
    x0hs#9452
    Frost#7467
    DaveTCZ#1966
    Arkey#9403
    Duke101#1210
    FallenGrim#8461
    GhOoOsT_T#4768
    ugunszelis#7328
    Milooue#6934
    tristris#3368
    floppib#2082
    mightybaseplate#0001
    Kroucher#7634
    remm#1160
    ItsFergLad#0761
    Wood#4408
    Paragon#7930
    Foamy#2227
    XexerTV(RipX)#4660
    ProToType#9739
    MaxNero#9511
    𝓀𝑒𝓋𝒾𝓂𝑒𝒽𝒢𝓂#7092
    Flaming#4421
    Lun4rSpy#3839
    Khayso#3875
    gnome#0962
    oRq_z#6991
    Corn#0505
    Cold#1621
    EU | βœͺ EzGamingTv12#8168
    StatTrakDoggo#7793
    Ziovixx#5012
    γƒ¬γ‚€γƒγ‚§γƒ«γƒ»γ‚¬γƒΌγƒ‰γƒŠ#0890
    DeclaredTruth#3896
    J0sh#4948
    ο½—ο½—ο½—#8902												

    public by sTiLL-iLL @ SniPitz-KND modified Sep 21, 2014  2302  3  7  20

    Disable the console...

    keep your users honest!
    
    (function() {
        try {
            var $_console$$ = console;
            Object.defineProperty(window, "console", {
                get: function() {
                    if ($_console$$._commandLineAPI) {
                        throw "Sorry, for security reasons, the script console is deactivated on netflix.com";
                    }
                    return $_console$$
                },
                set: function($val$$) {
                    $_console$$ = $val$$
                }
            });
        }
        catch ($ignore$$) {
        }
    })();

    public by micurs modified Dec 23, 2013  3184  1  7  0

    QueryString in Javascript

    This function allow to access a parameter in the url of a page. The original post in StackOverflow: http://stackoverflow.com/questions/3788125/jquery-querystring The solution is by Guffa http://stackoverflow.com/users/69083/guffa
    function querystring(key) {
       var re=new RegExp('(?:\\?|&)'+key+'=(.*?)(?=&|$)','gi');
       var r=[], m;
       while ((m=re.exec(document.location.search)) !== null) r.push(m[1]);
       return r;
    }
    

    public by cghersi modified Feb 21, 2014  3223  1  8  1

    LINQ: How to retrieve an IEnumerable collection with simple query

    This is a simple query in Linq to retrieve the list of Users that have some specified condition (in this case Active == true). Please note the == operator in the where clause (and in general all C# operators apply). Linq is excellent in writing fast and effective in-memory query on lists, dictionaries, etc.
    ICollection<User> users = new List<User>();
    users.Add(new User("Tom"));
    users.Add(new User("Mark"));
    
    IEnumerable<User> result = (
    	from user in users 
    	where user.Active == true 
    	select user); 

    public by Geometry modified Aug 7, 2016  904  0  5  0

    FreeUnusedMemory: Force freeing unused memory.

    Force freeing unused memory. Frees and removes from cache memory blocks, which are not used by users. Returns number of freed memory blocks.
    private static List<CacheBlock> memoryBlocks = new List<CacheBlock>( );
    // current cache size
    private static int currentCacheSize = 0;
    // amount of cached memory
    private static int cachedMemory = 0;
    
    /// <summary>
    /// Force freeing unused memory.
    /// </summary>
    /// 
    /// <remarks>Frees and removes from cache memory blocks, which are not used by users.</remarks>
    /// 
    /// <returns>Returns number of freed memory blocks.</returns>
    /// 
    public static int FreeUnusedMemory( )
    {
        lock ( memoryBlocks )
        {
            int freedBlocks = 0;
    
            // free all unused memory
            for ( int i = currentCacheSize - 1; i >= 0; i-- )
            {
                if ( memoryBlocks[i].Free )
                {
                    Marshal.FreeHGlobal( memoryBlocks[i].MemoryBlock );
                    cachedMemory -= memoryBlocks[i].Size;
                    memoryBlocks.RemoveAt( i );
                    freedBlocks++;
                }
            }
            currentCacheSize -= freedBlocks;
    
            return freedBlocks;
        }
    }
    • Public Snippets
    • Channels Snippets