working on it ...

Filters

Explore Public Snippets

Sort by

Found 13k snippets matching: method

    public by fabio.nosenzo @ Amazon_AWS_Python_API modified Aug 1, 2013  588058  4  8  -1

    Amazon S3 Aws - S3Connection object from python boto API

    This snippet is about the S3Connection object provided by python boto package for Amazon AWS API. Here the __init__ method is listed with all its variables. The AWSAuthConnection object is initialized and it handles all the data for managing requests and response from Amazon AWS service. Path: [boto/s3/connection.py] Learn more about S3Con
    import boto.utils
    from boto.connection import AWSAuthConnection
    
    class S3Connection(AWSAuthConnection):
        DefaultHost = boto.config.get('s3', 'host', 's3.amazonaws.com')
        DefaultCallingFormat = boto.config.get('s3', 'calling_format', 'boto.s3.connection.SubdomainCallingFormat')
        QueryString = 'Signature=%s&Expires=%d&AWSAccessKeyId=%s'
    
        def __init__(self, aws_access_key_id=None, aws_secret_access_key=None,
                     is_secure=True, port=None, proxy=None, proxy_port=None,
                     proxy_user=None, proxy_pass=None,
                     host=DefaultHost, debug=0, https_connection_factory=None,
                     calling_format=DefaultCallingFormat, path='/',
                     provider='aws', bucket_class=Bucket, security_token=None,
                     suppress_consec_slashes=True, anon=False,
                     validate_certs=None):
            if isinstance(calling_format, str):
                calling_format=boto.utils.find_class(calling_format)()
            self.calling_format = calling_format
            self.bucket_class = bucket_class
            self.anon = anon
            AWSAuthConnection.__init__(self, host,
                    aws_access_key_id, aws_secret_access_key,
                    is_secure, port, proxy, proxy_port, proxy_user, proxy_pass,
                    debug=debug, https_connection_factory=https_connection_factory,
                    path=path, provider=provider, security_token=security_token,
                    suppress_consec_slashes=suppress_consec_slashes,
                    validate_certs=validate_certs)

    public by lbottaro modified Dec 10, 2014  476163  8  6  2

    JavaScript equivalent to C# String.format

    The code below is the Javascript equivalent to C# String.Format() for replacing elements like {0}, {1}, {2} with parameters. In this case the String prototype is modified, adding the new format() method to all string instances. How to use var mystring = "Hello {0}, how are you? My name is {1}. Bye {0}!" mystring.format("Alice", "Bob") //
    // First, checks if it isn't implemented yet.
    if (!String.prototype.format) {
      String.prototype.format = function() {
        var args = arguments;
        return this.replace(/{(\d+)}/g, function(match, number) { 
          return typeof args[number] != 'undefined'
            ? args[number]
            : match
          ;
        });
      };
    }            

    public by cghersi modified Jan 31, 2014  475121  5  7  0

    C#: Parse a comma separated string into a collection of numeric items

    This method can be used with any separator you need, just setting the 'separator' input
    public static List<long> ParseIntoListOfLongs(string content, char separator = ',')
    {
        List<long> ids = new List<long>();
    
        if (string.IsNullOrEmpty(content))
            return ids;
    
        string[] strIds = content.Split(separator);
        foreach (string str in strIds)
        {
            long id = -1;
            if (long.TryParse(str, out id))
            {
                if (id > 0)
                    ids.Add(id);
            }
        }
    
        return ids;
    }
    

    public by cghersi modified Aug 20, 2013  468572  7  8  2

    Load a SOAP endpoint with Apache CXF using JMS transport provided by Apache ActiveMQ

    This is an example on how to load a SOAP web service in order to be able to invoke its methods via JMS transport
    private JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
    public MyInterface loadEndPoint() {
    	//try to load from local, if available:
    	boolean loadOK = false;
    	MyInterface result = null;
    	try {
    		Class<?> c = Class.forName("MyImplClass");
    		Method fact = c.getMethod("get");
    		result = (MyInterface) fact.invoke(null);
    		loadOK = true;
    	} catch (ClassNotFoundException e) {
    		log.info("Cannot find MyImplClass, redirecting to  remote access...", e);		
    	} catch (Exception e) {
    		log.warn("Error searching MyImplClass, , redirecting to remote access. Exception is " + e, e);
    	}
    		
    	//load remote endpoint:
    	if (!loadOK) {
    		//detect transport protocol for web services:
    		String brokerAddr = "127.0.0.1"; //the right broker address
    		String queueName = "MyQueueName";
    		String address = "jms:jndi:dynamicQueues/" + queueName + "?jndiInitialContextFactory=org.apache.activemq.jndi.ActiveMQInitialContextFactory&jndiConnectionFactoryName=ConnectionFactory&jndiURL=" + brokerAddr;
    
    		log.info("Connecting to " + address);
    		String connString = "tcp://" + brokerAddr + ":61616";
    		ActiveMQConnectionFactory connFactory = new ActiveMQConnectionFactory("Myusername", "Mypassword", connString);
    
    		SoapBindingConfiguration conf = new SoapBindingConfiguration();
    		//MTOM not supported! .net does not interoperate with cxf mtom impl.
    //		conf.setMtomEnabled(true);
    		conf.setVersion(Soap12.getInstance());
    		factory.setBindingConfig(conf);
    
    		factory.setServiceClass(MyInterface.class);
    		factory.setAddress(address);
    		factory.getFeatures().add(new WSAddressingFeature());
    		factory.getFeatures().add(getJMSConfigFeature(queueName, connFactory, 10000)));
    		Object resObj = factory.create();
    		if ((resObj != null) && (resObj instanceof MyInterface))
    			result = (MyInterface) resObj;
    		}
    
    		return result;
    	}
    }
    
    public static JMSConfigFeature getJMSConfigFeature(String queueName, ActiveMQConnectionFactory connectionFactory, Long receiveTimeout) {
    	JMSConfigFeature jmsConfigFeature = new JMSConfigFeature();
    	JMSConfiguration jmsConfig = new JMSConfiguration();
    	jmsConfig.setUseJms11(true);
    	jmsConfig.setTargetDestination(queueName);
    	jmsConfig.setConnectionFactory(connectionFactory);
    	if (receiveTimeout != null)
    		jmsConfig.setReceiveTimeout(receiveTimeout);
    	jmsConfigFeature.setJmsConfig(jmsConfig);
    	return jmsConfigFeature;
    }

    public by lbottaro modified Mar 24, 2014  406498  1  7  9

    Simple CORBA java server

    This code shows an example of simple corba server in java. A CORBA server needs a local ORB object. The server instantiates an ORB and registers its servant objects so that the ORB can find the server when it receives an invocation for it. the server is a process that instantiates one or more servant objects. Each servant implements the
    // The package containing our stubs.
    import HelloApp.*;
    
    // HelloServer will use the naming service.
    import org.omg.CosNaming.*;
    
    // The package containing special exceptions thrown by the name service.
    import org.omg.CosNaming.NamingContextPackage.*;
    
    // All CORBA applications need these classes.
    import org.omg.CORBA.*;
    
    public class HelloServer 
    {
      public static void main(String args[])
      {
        try{
           // Create and initialize the ORB
          ORB orb = ORB.init(args, null);
          
          // Create the servant and register it with the ORB
          HelloServant helloRef = new HelloServant();
          orb.connect(helloRef);
          
          // Get the root naming context
        org.omg.CORBA.Object objRef = 
    orb.resolve_initial_references("NameService");
          NamingContext ncRef = NamingContextHelper.narrow(objRef);
          
          // Bind the object reference in naming
          NameComponent nc = new NameComponent("Hello", "");
          NameComponent path[] = {nc};
          ncRef.rebind(path, helloRef);
          
          // Wait for invocations from clients
          java.lang.Object sync = new java.lang.Object();
          synchronized(sync){
            sync.wait();
          }
              } catch(Exception e) {
            System.err.println("ERROR: " + e);
            e.printStackTrace(System.out);
          }  
      }
    }
    
    class HelloServant extends _HelloImplBase
    {
      public String sayHello()
      {
        return "\nHello world!!\n";
        }
    }
        

    public by cghersi modified Aug 5, 2014  290390  1  6  0

    How to simply compute the MD5 hash of a given string, being sure to have the same results retrieved by HASH method of MS SQL Server

    Returns the MD5 hash of the given string
    public static String computeMD5Hash(String input) {
    	if (isNullOrEmpty(input))
    		return "";
    	byte[] bytesOfMessage = null;
    	try {
    		bytesOfMessage = input.getBytes("UTF-16LE");
    	} catch (UnsupportedEncodingException e) {
    		log.error("Cannot support UTF-8 encoding due to " + e, e);
    		return "";
    	}
    	MessageDigest md = null;
    	try {
    		md = MessageDigest.getInstance("MD5");
    	} catch (NoSuchAlgorithmException e) {
    		log.error("Cannot support MD5 algorithm due to " + e, e);
    		return "";
    	}
    	byte[] thedigest = md.digest(bytesOfMessage);
    	return printHexByteArray(thedigest);
    }

    public by lbottaro modified Mar 23, 2014  294364  1  6  3

    Simple RMI Java client

    This is a simple RMI client implementation. Here the client program obtains a stub for the registry on the server's host, then looks up the remote object's stub by name in the registry. Finally invokes the sayHello method on the remote object using the stub. Here the client invokes the method exposes by Hello remote interface. Note that if no
    package example.hello;
    
    import java.rmi.registry.LocateRegistry;
    import java.rmi.registry.Registry;
    
    public class Client {
    
        private Client() {}
    
        public static void main(String[] args) {
    
    	String host = (args.length < 1) ? null : args[0];
    	try {
    	    Registry registry = LocateRegistry.getRegistry(host);
    	    Hello stub = (Hello) registry.lookup("Hello");
    	    String response = stub.sayHello();
    	    System.out.println("response: " + response);
    	} catch (Exception e) {
    	    System.err.println("Client exception: " + e.toString());
    	    e.printStackTrace();
    	}
        }
    }    

    public by lbottaro modified Mar 23, 2014  281492  2  6  3

    Simple RMI Java server

    This code shows a basic RMI server example. A "server" is the class which has a main method that creates an instance of the remote object implementation, exports the remote object and then binds that instance to a name in a RMI registry. Here the server implements the remote interface Hello. The class that contains this main method could be the
    package example.hello;
    	
    import java.rmi.registry.Registry;
    import java.rmi.registry.LocateRegistry;
    import java.rmi.RemoteException;
    import java.rmi.server.UnicastRemoteObject;
    	
    public class Server implements Hello {
    	
        public Server() {}
    
        public String sayHello() {
    	return "Hello, world!";
        }
    	
        public static void main(String args[]) {
    	
    	try {
    	    Server obj = new Server();
    	    Hello stub = (Hello) UnicastRemoteObject.exportObject(obj, 0);
    
    	    // Bind the remote object's stub in the registry
    	    Registry registry = LocateRegistry.getRegistry();
    	    registry.bind("Hello", stub);
    
    	    System.err.println("Server ready");
    	} catch (Exception e) {
    	    System.err.println("Server exception: " + e.toString());
    	    e.printStackTrace();
    	}
        }
    }    

    public by micheleaiello modified Jan 26, 2014  263093  0  6  1

    Mark methods as deprecated

    Mark a method (or a whole class) as deprecated. Works in Xcode v4.2 and higher.
    __attribute((deprecated("Use xxx: instead")))
    
    examples:
    
    @interface MyClass : NSObject
      - (void)myOldMethod:(id)param __attribute__((deprecated));
    @end
    
    __attribute__((deprecated))
    @interface MyOldClass : NSObject
    @end
    
    __attribute__((deprecated))
    void myOldFunction(...) {
    }

    public by zonaro modified Oct 23, 2015  205405  1  7  0

    Image toBase64 String

    Extension method to convert a System.Drawing.Image to Base64 String
    public static string toBase64(this System.Drawing.Image OriginalImage)
          {
              using (MemoryStream ms = new MemoryStream())
              {
                  OriginalImage.Save(ms, OriginalImage.RawFormat);
                  byte[] imageBytes = ms.ToArray();
                  return Convert.ToBase64String(imageBytes);
              }
          }
    
    • Public Snippets
    • Channels Snippets