Ensure we're not creating a device that already exists
        Runs only when the DeviceConnector object is created, not when is updated
347476
def _validate_duplicates(self):
        
        # if connector is being created right now
        if not self.id:
            duplicates = []
            self.netengine_dict = self.netengine.to_dict()
            # loop over interfaces and check mac address
            for interface in self.netengine_dict['interfaces']:
                # avoid checking twice for the same interface (often ifconfig returns duplicates)
                if interface['mac_address'] in duplicates:
                    continue
                # check in DB
                if Interface.objects.filter(mac__iexact=interface['mac_address']).count() > 0:
                    duplicates.append(interface['mac_address'])

            # if we have duplicates raise validation error
            if len(duplicates) > 0:
                mac_address_string = ', '.join(duplicates)
                raise ValidationError(_('interfaces with the following mac addresses already exist: %s') % mac_address_string)
539495
void lock(final DeviceProxy deviceProxy, final int validity) throws DevFailed {
        deviceProxy.import_admin_device("lock");

        final DevVarLongStringArray lsa = new DevVarLongStringArray();
        lsa.svalue = new String[1];
        lsa.lvalue = new int[1];
        lsa.svalue[0] = deviceProxy.get_name();
        lsa.lvalue[0] = validity;
        final DeviceData argin = new DeviceData();
        argin.insert(lsa);
        deviceProxy.getAdm_dev().command_inout("LockDevice", argin);

        addToRelockList(deviceProxy, validity);
    }
173443
def _initialize_system_sync(self):
        """"""
        connected_devices = self.bable.list_connected_devices()
        for device in connected_devices:
            context = {
                'connection_id': len(self.connections.get_connections()),
                'connection_handle': device.connection_handle,
                'connection_string': device.address
            }
            self.connections.add_connection(context['connection_id'], device.address, context)
            self.disconnect_sync(context['connection_id'])

        self.stop_scan()

        try:
            self.bable.set_advertising(enabled=False)
        except bable_interface.BaBLEException:
            # If advertising is already disabled
            pass
105616
def _lock(self):
        """"""
        if not self.locked:
            try:
                self.device.cu.lock()
                self.locked = True
            except JnprLockError as jle:
                raise LockError(py23_compat.text_type(jle))
257173
def device_not_active(self, addr):
        """"""
        self.aldb_device_handled(addr)
        for callback in self._cb_device_not_active:
            callback(addr)
236139
def get_device(self, device_id, refresh=False):
        """"""
        if self._devices is None:
            self.get_devices()
            refresh = False

        device = self._devices.get(device_id)

        if device and refresh:
            device.refresh()

        return device
335686
function saveDeviceInfo(deviceInfo) {
            debugDC('in saveDeviceInfo');
            var key = getDeviceKey(deviceInfo);
            var connectionTypes = [];
            var newConnectionTypes = getDeviceConnectionTypesData(deviceInfo);

            if(scannedData[key]) {
                // The data has already been added.
                connectionTypes = scannedData[key].connectionTypes;
            } else {
                // The data has not been added.  Object needs to be initialized.
                scannedData[key] = {};
            }

            // Append new connection types to the connectionTypes array.
            debugDC('Initial CTS', connectionTypes.length, newConnectionTypes.length);
            connectionTypes = appendDeviceConnectionTypesData(
                connectionTypes,
                newConnectionTypes,
                deviceInfo
            );
            debugDC('Appended CTS', connectionTypes.length);

            // Parse the connectionTypes array to populate a few remaining
            // variables.
            scannedData[key].numConnectionTypes = connectionTypes.length;
            scannedData[key].connectionTypeNames = connectionTypes.map(function(ct) {
                return ct.connectionTypeName;
            });

            // Determine what connections are and aren't verified.
            scannedData[key].unverifiedConnectionTypes = [];
            scannedData[key].unverifiedConnectionTypeNames = [];
            scannedData[key].verifiedConnectionTypeNames = [];
            connectionTypes.forEach(function(ct) {
                var ctn = ct.connectionTypeName;
                if(ct.isVerified) {
                    scannedData[key].verifiedConnectionTypeNames.push(ctn);
                } else {
                    scannedData[key].unverifiedConnectionTypes.push(ct);
                    scannedData[key].unverifiedConnectionTypeNames.push(ctn);
                }
            });

            // Save the connectionTypes array.
            scannedData[key].connectionTypes = connectionTypes;

            // Save the deviceInfo object to the scannedData object.
            var iKeys = Object.keys(deviceInfo);
            iKeys.forEach(function(iKey) {
                if(typeof(scannedData[key][iKey]) === 'undefined') {
                    scannedData[key][iKey] = deviceInfo[iKey];
                }
            });
        }
438494
def on(self):
        
        for device in self:
            if isinstance(device, (OutputDevice, CompositeOutputDevice)):
                device.on()
775767
def extract_new(cls) -> DevicesTypeUnbound:
        
        devices = cls.get_handlerclass()(*_selection[cls])
        _selection[cls].clear()
        return devices
1209008
def update_from_devices(self):
        """"""
        # _LOGGER.warning("update from devices")
        try:
            rest = requests.get(URL_DEVICES.format(self._url))
            if rest.status_code != 200:
                _LOGGER.error("Devices returned %s", rest.status_code)
                return False
            self.devices.update_devices(rest.json())
            return True
        except requests.exceptions.ConnectionError as conn_err:
            _LOGGER.error("Could not connect: %s", conn_err)
        except Exception as err:  # pylint: disable=broad-except
            _LOGGER.error(err)
625340
protected void initializeAdbConnection() {
    // Get a device bridge instance. Initialize, create and restart.
    try {
      AndroidDebugBridge.init(false);
    } catch (IllegalStateException e) {
      if (!shouldKeepAdbAlive) {
        log.log(
            Level.WARNING,
            "AndroidDebugBridge may have been already initialized at this point. It is OK to proceed.",
            e);
      }
    }

    bridge = AndroidDebugBridge.getBridge();

    if (bridge == null) {
      bridge = AndroidDebugBridge.createBridge(adbPath, false);
    }
    IDevice[] devices = bridge.getDevices();

    AndroidDebugBridge.addDeviceChangeListener(this);

    // Add the existing devices to the list of devices we are tracking.
    if (devices.length > 0) {
      for (int i = 0; i < devices.length; i++) {
        deviceConnected(devices[i]);
        log.info("my devices: " + devices[i].getAvdName());
      }
    } else {
      long timeout = System.currentTimeMillis() + 2000;
      while ((devices = bridge.getDevices()).length == 0 && System.currentTimeMillis() < timeout) {
        try {
          Thread.sleep(50);
        } catch (InterruptedException e) {
          throw new RuntimeException(e);
        }
      }
      if (devices.length > 0) {
        for (int i = 0; i < devices.length; i++) {
          deviceConnected(devices[i]);
          log.info("my devices: " + devices[i].getAvdName());
        }
      }
    }

  }
884401
def _check_device_failover_status(self, device, status):
        '''
        '''

        sync_status = device.tm.cm.sync_status
        sync_status.refresh()
        current_status = (sync_status.entries[self.sync_status_entry]
                          ['nestedStats']['entries']['status']
                          ['description'])
        if status == current_status:
            return True
        return False
619260
def on_hid_pnp(self, hid_event = None):
        """"""
        # keep old reference for UI updates
        old_device = self.device

        if hid_event:
            print("Hey, a hid device just %s!" % hid_event)

        if hid_event == "connected":
            # test if our device is available
            if self.device:
                # see, at this point we could detect multiple devices!
                # but... we only want just one
                pass
            else:
                self.test_for_connection()
        elif hid_event == "disconnected":
            # the hid object is automatically closed on disconnection we just
            # test if still is plugged (important as the object might be
            # closing)
            if self.device and not self.device.is_plugged():
                self.device = None
                print("you removed my hid device!")
        else:
            # poll for devices
            self.test_for_connection()

        if old_device != self.device:
            # update ui
            pass
549989
def delete_instance_if_removed(self, port):
        """"""
        instance_type = self.get_instance_type(port)
        if not instance_type:
            return
        if not db_lib.instance_provisioned(port['device_id']):
            i_res = MechResource(port['device_id'], instance_type,
                                 a_const.DELETE)
            self.provision_queue.put(i_res)
707125
def newDevices(self, interface_id, dev_descriptions):
        """"""
        LOG.debug("RPCFunctions.newDevices: interface_id = %s, dev_descriptions = %s" % (
            interface_id, str(dev_descriptions)))
        remote = interface_id.split('-')[-1]
        if remote not in self._devices_raw:
            self._devices_raw[remote] = []
        if remote not in self._devices_raw_dict:
            self._devices_raw_dict[remote] = {}
        for d in dev_descriptions:
            self._devices_raw[remote].append(d)
            self._devices_raw_dict[remote][d['ADDRESS']] = d
        self.saveDevices(remote)
        self.createDeviceObjects(interface_id)
        if self.systemcallback:
            self.systemcallback('newDevices', interface_id, dev_descriptions)
        return True
472159
def _ensure_device_active(self, device):
        '''
        '''

        act = device.tm.cm.devices.device.load(
            name=get_device_info(device).name,
            partition=self.partition
        )
        if act.failoverState != 'active':
            msg = "A device in the cluster was not in the 'Active' state."
            raise UnexpectedDeviceGroupState(msg)
955608
function scheduleServerConnectivityChecks() {
        if (connectivityIntervalId === null) {
            connectivityIntervalId = asyncExecService.setInterval(function () {
                updateRegistrations();
                connectToServers();
            }, INTERVAL_BETWEEN_SERVER_CONNECTIVITY_CHECKS);
        }
        else {
            throw new Error("BUG ::: Attempt was made to start connectivity checks twice");
        }
    }