working on it ...

Filters

Explore Public Snippets

Sort by

Found 610 snippets matching: interfaces

    public by micurs  748036  18  7  0

    JQuery typescript interface for $.ajax() callbacks

    To use JQuery $.ajax() you must define your callback functions with the following interfaces
    interface OnSuccessAjaxCallback {
      (data: any, textStatus?: string, jqXHR?: JQueryXHR): any;
    }
    interface OnErrorAjaxCallback {
      (jqXHR?: JQueryXHR, textStatus?: string, errorThrow?: string) : any;
    }
    

    public by lbottaro  6106  4  8  6

    Asynchronous processing using Future and Callable java interfaces

    Java Future and Callable interfaces allow to easily manage asynchronous run and elaboration for long time-consuming operations. Each MyCallableObject implements Callable interface, specifying the behavior of call() method. In this example, ExecutorService will execute the MyCallableObject processing routine using a pool of configurable threads, i
    import java.util.ArrayList;
    import java.util.List;
    import java.util.concurrent.Callable;
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.Future;
    
    public class CallableFutureTest {
    	private static final int NTHREDS = 5;
    
    	public static void main(String[] args) {
    
    		ExecutorService executor = Executors.newFixedThreadPool(NTHREDS);
    		List<Future<Long>> list = new ArrayList<Future<Long>>();
    		for (int i = 0; i < 100; i++) {
    			Callable<Long> worker = new MyCallableObject();
    			Future<Long> submit = executor.submit(worker);
    			list.add(submit);
    			System.out.println("Added future " + submit.toString());
    
    		}
    		long sum = 0;
    		try {
    			Thread.sleep(10000);
    		} catch (InterruptedException e1) {
    			// TODO Auto-generated catch block
    			e1.printStackTrace();
    		}
    		System.out.println(list.size());
    
    		// now retrieve the result
    		for (Future<Long> future : list) {
    			try {
    				System.out.println("Current future " + future.toString());
    				System.out.println("Future before get is " + future.isDone());
    				sum += future.get();
    				System.out.println("Future after get is " + future.isDone());
    			} catch (InterruptedException e) {
    				e.printStackTrace();
    			} catch (ExecutionException e) {
    				e.printStackTrace();
    			}
    		}
    		System.out.println(sum);
    		executor.shutdown();
    	}
    }

    public by emsity  2167  4  6  0

    RPi Static IP Address on 2 networks Network Interfaces file

    This is the network Interfaces file used to connect via cable to the primary network (192.168.0.12), or via wifi to the secondary network (192.168.169.15) with static ip address
    auto lo
    
    iface lo inet loopback
    iface eth0 inet static
    
    address 192.168.0.12
    netmask 255.255.255.0
    broadcast 192.168.0.255
    gateway 192.168.0.1
    
    
    allow-hotplug wlan0
    iface wlan0 inet manual
    wpa-roam /etc/wpa_supplicant/wpa_supplicant.conf
    iface default inet static
    
    address 192.168.169.15
    netmask 255.255.255.0
    broadcast 192.168.169.255
    gateway 192.168.169.1

    public by cghersi  2741  1  7  1

    How to detect the current IP addresses of local machine in Java

    This method checks the local network interfaces to discover the actual IP address associated, trying to skip the bogus addresses (localhost, virtual ones, etc.)
    private static ArrayList<String> retrieveLocalIPs(){
    	ArrayList<String> defaultStr = new ArrayList<String>(); 
    	try{
    		Enumeration<NetworkInterface> ni = NetworkInterface.getNetworkInterfaces();
    		while(ni.hasMoreElements()){
    			NetworkInterface currni = ni.nextElement();
    			if (!currni.isLoopback() && 	// no loopback addresses or interfaces
    				!currni.isVirtual() && 		// no virtual network interfaces
    				currni.isUp()) { 			// only active network interfaces are considered here
    				Enumeration<InetAddress> addresses = currni.getInetAddresses();
    				while(addresses.hasMoreElements()){
    					InetAddress address = addresses.nextElement();
    					if (!address.isLoopbackAddress() && 	// no loopback addresses here, please
    						!address.isMCSiteLocal() && 	  	// no multicast addressed	
    						(address.getHostName() != null) &&	// hostname should not be null        						        						
    						(address instanceof Inet4Address)) { 	  // only ipv4 addresses	    					
    						
    						//ok, we got the address: not we have to check if it is well formed:        					
    						if(address.toString().contains("/")){
    							/* address is something like mypc.domain/10.0.1.45, 
    							 * therefore we have to extract only the IP address: 
    							 */
    							String str2add = address.toString().split("\\/")[1];
    							if (validateIPv4Address(str2add)) {
    								defaultStr.add(str2add);
    							}else{
    								log.warn("skipping bogus ipv4 address " + str2add);
    							}
    						}else{								
    							if (validateIPv4Address(address.toString())) {
    								defaultStr.add(address.toString());
    							}else{
    								log.warn("skipping bogus ipv4 address " + address.toString());
    							}								
    						}
    					}	    				
    				}
    			}
    		}
    	}catch(Exception ex) {
    		return null;
    	}
    	return defaultStr;
    }
    
    private static boolean validateIPv4Address(String ipAddress) {
    	String[] parts = ipAddress.split( "\\." );
    
    	try{ 
    		if (parts.length != 4)
    			return false;
    
    		for (String s : parts) {
    			int i = Integer.parseInt(s);
    
    			if ((i < 0) || (i > 255)) 
    				return false;
    		}
    	}catch(Exception er){
    		return false;
    	}
    	return true;
    }

    public by msdn  1579  0  7  0

    TypeIsAssignableFromType: Verifies that an argument type is assignable from the provided type (meaning interfaces are implemented, or classes exist in the base class hierarchy).

    Verifies that an argument type is assignable from the provided type (meaning interfaces are implemented, or classes exist in the base class hierarchy). The argument type. The type it must be assignable from. The argument name.
    /// <summary>
    /// Verifies that an argument type is assignable from the provided type (meaning
    /// interfaces are implemented, or classes exist in the base class hierarchy).
    /// </summary>
    /// <param name="assignee">The argument type.</param>
    /// <param name="providedType">The type it must be assignable from.</param>
    /// <param name="argumentName">The argument name.</param>
    public static void TypeIsAssignableFromType(Type assignee, Type providedType, string argumentName)
    {
        if (!providedType.IsAssignableFrom(assignee))
        {
            throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, ExceptionMessages.TypeNotCompatible, assignee, providedType), argumentName);
        }
    }

    public by msdn  1081  0  7  0

    GetPropertyInfo: Get a property info based only on the interfaces that the type implements

    Get a property info based only on the interfaces that the type implements
    using System;
    using System.Reflection;
    using System.Text;
    using Microsoft.Example.MinimalCmof;
    using Microsoft.VisualStudio.Uml.Profiles;
    
    /// <summary>
    /// Get a property info based only on the interfaces that the type implements
    /// </summary>
    /// <param name="type"></param>
    /// <param name="name"></param>
    /// <returns></returns>
    internal static PropertyInfo GetPropertyInfo(System.Type type, string name)
    {
        foreach (var anInterface in type.FindInterfaces((i, j) => true, null))
        {
            PropertyInfo p = anInterface.GetProperty(name);
            if (p != null)
            {
                return p;
            }
        }
        return null;
    }

    public by msdn  1302  0  6  0

    CreateOptionSubclass

    // // Create the correct 'PrintSchemaOption' subclass, possibly exposing one of the these interfaces // 1. IPrintSchemaPageMediaSizeOption // 2. IPrintSchemaNUpOption //
    using System;
    using System.IO;
    using System.Collections;
    using System.Collections.Generic;
    using System.Runtime;
    using System.Runtime.InteropServices;
    using Microsoft.Samples.Printing.PrinterExtension.Types;
    
    //
    // Create the correct 'PrintSchemaOption' subclass, possibly exposing one of the these interfaces
    // 1. IPrintSchemaPageMediaSizeOption
    // 2. IPrintSchemaNUpOption
    //
    internal static IPrintSchemaOption CreateOptionSubclass(PrinterExtensionLib.IPrintSchemaOption option)
    {
        // IPrintSchemaNUpOption option
        if (option is PrinterExtensionLib.IPrintSchemaNUpOption)
        {
            return new PrintSchemaNUpOption(option);
        }
    
        // IPrintSchemaPageMediaSizeOption option
        if (option is PrinterExtensionLib.IPrintSchemaPageMediaSizeOption)
        {
            return new PrintSchemaPageMediaSizeOption(option);
        }
    
        return new PrintSchemaOption(option);
    }

    external by DavidWittman  497  0  3  0

    Checks to see if two interfaces are on the same network on Linux. Useful when bonding interfaces.

    Checks to see if two interfaces are on the same network on Linux. Useful when bonding interfaces.: check_peer_interfaces.py
    #!/usr/bin/env python
    
    # check_peer_interfaces.py
    # Author: David Wittman <david@wittman.com>
    #
    # Checks to see if two interfaces are on the same network by sending a
    # unique broadcast packet out of the first interface and listening for that
    # packet on the second interface.
    #
    # Assumes that you're running a Linux variant, and that both interfaces
    # provided are administratively up.
    #
    # Based on bonding.py by Matt Martz
    
    import fcntl
    import os
    import socket
    import struct
    import sys
    
    # asm/sockios.h
    SO_BINDTODEVICE = 25
    
    # Non DIX types (if_ether.h)
    ETH_P_ALL = 0x0003             # Every packet (be careful!!!)
    
    # sockios.h
    SIOCGIFFLAGS = 0x8913          # get flags
    SIOCSIFFLAGS = 0x8914          # set flags
    SIOCGIFHWADDR = 0x8927         # Get hardware address
    
    # net/if.h
    IFF_PROMISC = 0x100            # Receive all packets.
    
    
    def get_mac_addr(iface):
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        return fcntl.ioctl(
            s.fileno(),
            SIOCGIFHWADDR,
            struct.pack('256s', iface[:15])
        )[18:24]
    
    
    def are_peers(send_iface, recv_iface):
        # Create a unique payload to match against later
        identifier = 'IF%sIF' % send_iface
        payload = '%s%s' % (identifier, os.urandom(46 - len(identifier)))
    
        src_mac = get_mac_addr(send_iface)
        # broadcast address
        dest_mac = ('f' * 12).decode('hex')
        # use an unregistered ethertype for peer discovery
        frame_type = '\x50\x44'
    
        # Configure socket on send interface
        send_sock = socket.socket(
            socket.AF_PACKET, socket.SOCK_RAW,
            socket.htons(ETH_P_ALL)
        )
        send_sock.setsockopt(socket.SOL_SOCKET, SO_BINDTODEVICE, send_iface + '\0')
        send_sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
        send_sock.bind((send_iface, 0))
        send_sock.setblocking(0)
    
        # Configure socket on receive interface
        recv_sock = socket.socket(
            socket.AF_PACKET, socket.SOCK_RAW,
            socket.htons(ETH_P_ALL)
        )
        recv_sock.setsockopt(socket.SOL_SOCKET, SO_BINDTODEVICE, recv_iface + '\0')
        recv_sock.bind((recv_iface, 0))
        recv_sock.settimeout(0.5)
    
        # Put receive socket in promiscuous mode
        current_flags = 0
        ifreq = fcntl.ioctl(
            recv_sock.fileno(),
            SIOCGIFFLAGS,
            struct.pack('256s', recv_iface[:15])
        )
        (current_flags,) = struct.unpack('16xH', ifreq[:18])
        current_flags |= IFF_PROMISC
        ifreq = struct.pack('16sH', recv_iface, current_flags)
        fcntl.ioctl(recv_sock.fileno(), SIOCSIFFLAGS, ifreq)
    
        for _ in xrange(16):
            try:
                packet = ''.join([dest_mac, src_mac, frame_type, payload])
                send_sock.sendall(packet)
                data = recv_sock.recv(60)
            except (socket.timeout, socket.error):
                continue
    
            recv_frame_type = data[12:14]
            recv_payload = data[14:]
    
            if payload == recv_payload and frame_type == recv_frame_type:
                peers = True
                break
        else:
            peers = False
    
        # Take receiving interface out of promiscuous mode
        current_flags ^= IFF_PROMISC
        ifreq = struct.pack('16sH', recv_iface, current_flags)
        fcntl.ioctl(recv_sock.fileno(), SIOCSIFFLAGS, ifreq)
    
        recv_sock.close()
        send_sock.close()
    
        return peers
    
    
    def main():
        if len(sys.argv) != 3:
            sys.stderr.write("usage: %s <iface> <iface>\n" % sys.argv[0])
            sys.stderr.flush()
            sys.exit(2)
    
        send_iface = sys.argv[1]
        recv_iface = sys.argv[2]
    
        if are_peers(send_iface, recv_iface):
            print "SUCCESS! %s and %s are peers" % (send_iface, recv_iface)
        else:
            print "FAIL! %s and %s are not peers" % (send_iface, recv_iface)
            sys.exit(1)
    
    if __name__ == '__main__':
        main()
    
    

    external by Pedro Carriço  306  0  3  0

    Raspbian network interfaces configuration ("/etc/network/interfaces")

    Raspbian network interfaces configuration ("/etc/network/interfaces"): interfaces
    auto lo
    iface lo inet loopback
    
    auto eth0
    iface eth0 inet dhcp
    
    auto wlan0
    allow-hotplug wlan0
    iface wlan0 inet dhcp
            wpa-ssid "SSID"
            wpa-psk "PASSWORD"
    
    

    external by Gil Álvaro  227  0  3  0

    Defining custom types with interfaces. Interfaces is a way to tell TypeScript information about objects to help you catch more errors at build time, but don't ever rely on them being there at runtime.

    Defining custom types with interfaces. Interfaces is a way to tell TypeScript information about objects to help you catch more errors at build time, but don't ever rely on them being there at runtime.: custom_types_with_interfaces.ts
    interface Todo {
        name: string;
        completed?: boolean; //What this does is tells TypeScript not every Todo object needs to have a completed property in order to be a Todo. But, when it does have the completed property, that property needs to always be a boolean value.
    }
    
    interface ITodoService {
        add(todo: Todo): Todo;
        delete(todo: Todo): void;
        getAll(): Todo[];
        getById(todoId: number): Todo;
    }
    
    var todo: Todo = {
        name: "Pick up drycleaning"
    };
    
    
    • Public Snippets
    • Channels Snippets