TODO: To be compatible with CBL iOS, this method should move to Replicator.activeTaskInfo().
TODO: Reference: - (NSDictionary*) activeTaskInfo in CBL_Replicator.m
334461
private static Map<String, Object> getActivity(Replication replicator) {
        // For schema, see http://wiki.apache.org/couchdb/HttpGetActiveTasks
        Map<String, Object> activity = new HashMap<String, Object>();

        String source = replicator.getRemoteUrl().toExternalForm();
        String target = replicator.getLocalDatabase().getName();

        if (!replicator.isPull()) {
            String tmp = source;
            source = target;
            target = tmp;
        }
        int processed = replicator.getCompletedChangesCount();
        int total = replicator.getChangesCount();
        String status = String.format(Locale.ENGLISH, "Processed %d / %d changes", processed, total);
        if (!replicator.getStatus().equals(ReplicationStatus.REPLICATION_ACTIVE)) {
            //These values match the values for IOS.
            if (replicator.getStatus().equals(ReplicationStatus.REPLICATION_IDLE)) {
                status = "Idle";     // nonstandard
            } else if (replicator.getStatus().equals(ReplicationStatus.REPLICATION_STOPPED)) {
                status = "Stopped";
            } else if (replicator.getStatus().equals(ReplicationStatus.REPLICATION_OFFLINE)) {
                status = "Offline";  // nonstandard
            }
        }
        int progress = (total > 0) ? (int) 100 * processed / total : 0;

        activity.put("type", "Replication");
        activity.put("task", replicator.getSessionID());
        activity.put("source", source);
        activity.put("target", target);
        activity.put("status", status);
        activity.put("progress", progress);
        activity.put("continuous", replicator.isContinuous());

        //NOTE: Need to support "x_active_requests"

        if (replicator.getLastError() != null) {
            String msg = String.format(Locale.ENGLISH, "Replicator error: %s.  Repl: %s.  Source: %s, Target: %s",
                    replicator.getLastError(), replicator, source, target);
            Log.w(TAG, msg);
            Throwable error = replicator.getLastError();
            int statusCode = 400;
            if (error instanceof RemoteRequestResponseException) {
                statusCode = ((RemoteRequestResponseException) error).getCode();
            }
            Object[] errorObjects = new Object[]{statusCode, replicator.getLastError().toString()};
            activity.put("error", errorObjects);
        } else {
            // NOTE: Following two parameters: CBL iOS does not support. We might remove them in the future.
            activity.put("change_count", total);
            activity.put("completed_change_count", processed);
        }

        return activity;
    }
1159070
void replicationComplete() {
        reloadTasksFromModel();
        Toast.makeText(getApplicationContext(),
                R.string.replication_completed,
                Toast.LENGTH_LONG).show();
        dismissDialog(DIALOG_PROGRESS);
    }
1305090
private void replicateInstanceActionsToPeers(Action action, String appName,
                                                 String id, InstanceInfo info, InstanceStatus newStatus,
                                                 PeerEurekaNode node) {
        try {
            InstanceInfo infoFromRegistry = null;
            CurrentRequestVersion.set(Version.V2);
            switch (action) {
                case Cancel:
                    node.cancel(appName, id);
                    break;
                case Heartbeat:
                    InstanceStatus overriddenStatus = overriddenInstanceStatusMap.get(id);
                    infoFromRegistry = getInstanceByAppAndId(appName, id, false);
                    node.heartbeat(appName, id, infoFromRegistry, overriddenStatus, false);
                    break;
                case Register:
                    node.register(info);
                    break;
                case StatusUpdate:
                    infoFromRegistry = getInstanceByAppAndId(appName, id, false);
                    node.statusUpdate(appName, id, newStatus, infoFromRegistry);
                    break;
                case DeleteStatusOverride:
                    infoFromRegistry = getInstanceByAppAndId(appName, id, false);
                    node.deleteStatusOverride(appName, id, infoFromRegistry);
                    break;
            }
        } catch (Throwable t) {
            logger.error("Cannot replicate information to {} for action {}", node.getServiceUrl(), action.name(), t);
        }
    }
459970
def _PrintTasksInformation(self, storage_reader):
    
    table_view = views.ViewsFactory.GetTableView(
        self._views_format_type, title='Tasks')

    for task_start, _ in storage_reader.GetSessions():
      start_time = timelib.Timestamp.CopyToIsoFormat(
          task_start.timestamp)
      task_identifier = uuid.UUID(hex=task_start.identifier)
      task_identifier = '{0!s}'.format(task_identifier)
      table_view.AddRow([task_identifier, start_time])

    table_view.Write(self._output_writer)
1158438
def updateObj(self,event):
        """"""
        
        name=w.objList.get("active")
        w.SearchVar.set(name)
        w.ObjInfo.set(objInfoDict[name])
        return
1200429
LocatedBlocksWithMetaInfo updateDatanodeInfo(LocatedBlocks locatedBlocks)
      throws IOException {
    if (locatedBlocks.getLocatedBlocks().size() == 0)
      return new LocatedBlocksWithMetaInfo(locatedBlocks.getFileLength(),
          locatedBlocks.getLocatedBlocks(), false,
          DataTransferProtocol.DATA_TRANSFER_VERSION, getNamespaceId(),
          this.nameNode.getClientProtocolMethodsFingerprint());
    List<LocatedBlock> newBlocks = new ArrayList<LocatedBlock>();

    readLock();
    try {
      for (LocatedBlock locBlock: locatedBlocks.getLocatedBlocks()) {
        Block block = locBlock.getBlock();
        int numNodes = blocksMap.numNodes(block);
        int numCorruptNodes = countNodes(block).corruptReplicas();
        int numCorruptReplicas = corruptReplicas.numCorruptReplicas(block); 

        if (numCorruptNodes != numCorruptReplicas) {
          LOG.warn("Inconsistent number of corrupt replicas for " + 
                   block + "blockMap has " + numCorruptNodes + 
                   " but corrupt replicas map has " + numCorruptReplicas);
        }

        boolean blockCorrupt = numCorruptNodes == numNodes;
        int numMachineSet = blockCorrupt ? numNodes : (numNodes - numCorruptNodes);
        DatanodeDescriptor[] machineSet = new DatanodeDescriptor[numMachineSet];

        if (numMachineSet > 0) {
          numNodes = 0;
          for(Iterator<DatanodeDescriptor> it = blocksMap.nodeIterator(block); 
              it.hasNext();) {
            DatanodeDescriptor dn = it.next();
            boolean replicaCorrupt = corruptReplicas.isReplicaCorrupt(block, dn);
            if (blockCorrupt || (!blockCorrupt && !replicaCorrupt))
              machineSet[numNodes++] = dn;
          }
        }

        // We need to make a copy of the block object before releasing the lock
        // to prevent the state of block is changed after that and before the
        // object is serialized to clients, to avoid potential inconsistency.
        // Further optimization is possible to avoid some object copy. Since it
        // is so far not a critical path. We leave a safe approach here.
        //
        Block blockCopy  = null;
        if (block != null) {
          blockCopy = new Block(block);
        }
        LocatedBlock newBlock = new LocatedBlock(blockCopy, machineSet, 0,
            blockCorrupt);
  newBlocks.add(newBlock);
      }
    } finally {
      readUnlock();
    }

    return new LocatedBlocksWithMetaInfo(locatedBlocks.getFileLength(),
        newBlocks, false, DataTransferProtocol.DATA_TRANSFER_VERSION,
        getNamespaceId(), this.nameNode.getClientProtocolMethodsFingerprint());
  }
583733
private void noSuccessor() {
        if (compute == FRAMES) {
            Label l = new Label();
            l.frame = new Frame();
            l.frame.owner = l;
            l.resolve(this, code.length, code.data);
            previousBlock.successor = l;
            previousBlock = l;
        } else {
            currentBlock.outputStackMax = maxStackSize;
        }
        currentBlock = null;
    }
1024404
function writeATSEntries (config) {
    var pObj = processAccessAndAllowNavigationEntries(config);

    var ats = {};

    for (var hostname in pObj) {
        if (pObj.hasOwnProperty(hostname)) {
            var entry = pObj[hostname];

            // Guiding principle: we only set values if they are available

            if (hostname === '*') {
                // always write this, for iOS 9, since in iOS 10 it will be overriden if
                // any of the other three keys are written
                ats['NSAllowsArbitraryLoads'] = true;

                // at least one of the overriding keys is present
                if (entry.NSAllowsArbitraryLoadsInWebContent) {
                    ats['NSAllowsArbitraryLoadsInWebContent'] = true;
                }
                if (entry.NSAllowsArbitraryLoadsForMedia) {
                    ats['NSAllowsArbitraryLoadsForMedia'] = true;
                }
                if (entry.NSAllowsLocalNetworking) {
                    ats['NSAllowsLocalNetworking'] = true;
                }

                continue;
            }

            var exceptionDomain = {};

            for (var key in entry) {
                if (entry.hasOwnProperty(key) && key !== 'Hostname') {
                    exceptionDomain[key] = entry[key];
                }
            }

            if (!ats['NSExceptionDomains']) {
                ats['NSExceptionDomains'] = {};
            }

            ats['NSExceptionDomains'][hostname] = exceptionDomain;
        }
    }

    return ats;
}
377499
public void callExecuteTaskAsync(SimpleClientResponseAdapter.Callback cb, byte[] params) throws IOException {
        final String procedureName = "@ExecuteTask";
        Config procedureConfig = SystemProcedureCatalog.listing.get(procedureName);
        Procedure proc = procedureConfig.asCatalogProcedure();
        StoredProcedureInvocation spi = new StoredProcedureInvocation();
        spi.setProcName(procedureName);
        spi.setParams(params);
        spi.setClientHandle(m_executeTaskAdpater.registerCallback(cb));
        if (spi.getSerializedParams() == null) {
            spi = MiscUtils.roundTripForCL(spi);
        }
        synchronized (m_executeTaskAdpater) {
            m_dispatcher.createTransaction(m_executeTaskAdpater.connectionId(), spi,
                    proc.getReadonly(), proc.getSinglepartition(), proc.getEverysite(),
                    new int[] { 0 } /* Can provide anything for multi-part */,
                    spi.getSerializedSize(), System.nanoTime());
        }
    }
285145
boolean updateTaskTrackerStatus(String trackerName,
                                  TaskTrackerStatus status) {
    TaskTracker tt = getTaskTracker(trackerName);
    TaskTrackerStatus oldStatus = (tt == null) ? null : tt.getStatus();

    // update the total cluster capacity first

    if (status != null) {
      // we have a fresh tasktracker status
      if (!faultyTrackers.isBlacklisted(status.getHost())) {
        // if the task tracker host is not blacklisted - then
        // we update the cluster capacity with the capacity
        // reported by the tasktracker
        updateTotalTaskCapacity(status);
      } else {
        // if the tasktracker is blacklisted - then it's capacity
        // is already removed and will only be added back to the
        // cluster capacity when it's unblacklisted
      }
    } else {
      if (oldStatus != null) {
        // old status exists - but no new status. in this case
        // we are removing the tracker from the cluster.

        if (!faultyTrackers.isBlacklisted(oldStatus.getHost())) {

          // we update the total task capacity based on the old status
          // this seems redundant - but this call is idempotent - so just
          // make it. the danger of not making it is that we may accidentally
          // remove something we never had
          updateTotalTaskCapacity(oldStatus);
          removeTaskTrackerCapacity(oldStatus);

        } else {
          // if the host is blacklisted - then the tracker's capacity
          // has already been removed and there's nothing to do
        }
      }
    }


    if (oldStatus != null) {
      totalMaps -= oldStatus.countMapTasks();
      totalReduces -= oldStatus.countReduceTasks();
      occupiedMapSlots -= oldStatus.countOccupiedMapSlots();
      occupiedReduceSlots -= oldStatus.countOccupiedReduceSlots();
      getInstrumentation().decRunningMaps(oldStatus.countMapTasks());
      getInstrumentation().decRunningReduces(oldStatus.countReduceTasks());
      getInstrumentation().decOccupiedMapSlots(oldStatus.countOccupiedMapSlots());
      getInstrumentation().decOccupiedReduceSlots(oldStatus.countOccupiedReduceSlots());
      if (status == null) {
        taskTrackers.remove(trackerName);
        Integer numTaskTrackersInHost =
          uniqueHostsMap.get(oldStatus.getHost());
        if (numTaskTrackersInHost != null) {
          numTaskTrackersInHost --;
          if (numTaskTrackersInHost > 0)  {
            uniqueHostsMap.put(oldStatus.getHost(), numTaskTrackersInHost);
          }
          else {
            uniqueHostsMap.remove(oldStatus.getHost());
          }
        }
      }
    }
    if (status != null) {
      totalMaps += status.countMapTasks();
      totalReduces += status.countReduceTasks();
      occupiedMapSlots += status.countOccupiedMapSlots();
      occupiedReduceSlots += status.countOccupiedReduceSlots();
      getInstrumentation().addRunningMaps(status.countMapTasks());
      getInstrumentation().addRunningReduces(status.countReduceTasks());
      getInstrumentation().addOccupiedMapSlots(status.countOccupiedMapSlots());
      getInstrumentation().addOccupiedReduceSlots(status.countOccupiedReduceSlots());

      boolean alreadyPresent = false;
      TaskTracker taskTracker = taskTrackers.get(trackerName);
      if (taskTracker != null) {
        alreadyPresent = true;
      } else {
        taskTracker = new TaskTracker(trackerName);
      }

      taskTracker.setStatus(status);
      taskTrackers.put(trackerName, taskTracker);

      if (LOG.isDebugEnabled()) {
        int runningMaps = 0, runningReduces = 0;
        int commitPendingMaps = 0, commitPendingReduces = 0;
        int unassignedMaps = 0, unassignedReduces = 0;
        int miscMaps = 0, miscReduces = 0;
        List<TaskStatus> taskReports = status.getTaskReports();
        for (Iterator<TaskStatus> it = taskReports.iterator(); it.hasNext();) {
          TaskStatus ts = (TaskStatus) it.next();
          boolean isMap = ts.getIsMap();
          TaskStatus.State state = ts.getRunState();
          if (state == TaskStatus.State.RUNNING) {
            if (isMap) { ++runningMaps; }
            else { ++runningReduces; }
          } else if (state == TaskStatus.State.UNASSIGNED) {
            if (isMap) { ++unassignedMaps; }
            else { ++unassignedReduces; }
          } else if (state == TaskStatus.State.COMMIT_PENDING) {
            if (isMap) { ++commitPendingMaps; }
            else { ++commitPendingReduces; }
          } else {
            if (isMap) { ++miscMaps; }
            else { ++miscReduces; }
          }
        }
        LOG.debug(trackerName + ": Status -" +
                  " running(m) = " + runningMaps +
                  " unassigned(m) = " + unassignedMaps +
                  " commit_pending(m) = " + commitPendingMaps +
                  " misc(m) = " + miscMaps +
                  " running(r) = " + runningReduces +
                  " unassigned(r) = " + unassignedReduces +
                  " commit_pending(r) = " + commitPendingReduces +
                  " misc(r) = " + miscReduces);
      }

      if (!alreadyPresent)  {
        Integer numTaskTrackersInHost =
          uniqueHostsMap.get(status.getHost());
        if (numTaskTrackersInHost == null) {
          numTaskTrackersInHost = 0;
        }
        numTaskTrackersInHost ++;
        uniqueHostsMap.put(status.getHost(), numTaskTrackersInHost);
      }
    }
    getInstrumentation().setMapSlots(totalMapTaskCapacity);
    getInstrumentation().setReduceSlots(totalReduceTaskCapacity);
    return oldStatus != null;
  }
1304734
def touch(name = nil)
      now = DateTime.now
      self.updated_at = now
      attributes[name] = now if name
      save
    end
325955
def _list_and_update(self):
        
        initial_resources = getattr(self.api, self.list_method_name)(
            self.namespace,
            label_selector=self.label_selector,
            field_selector=self.field_selector,
            _request_timeout=self.request_timeout,
        )
        # This is an atomic operation on the dictionary!
        self.resources = {p.metadata.name: p for p in initial_resources.items}
        # return the resource version so we can hook up a watch
        return initial_resources.metadata.resource_version
1077130
def copy(self):
        

        metadata = {}
        # grab all the keys into a list so if something is added
        # in another thread it probably doesn't stomp on our loop
        for key in list(self.metadata.keys()):
            try:
                metadata[key] = copy.deepcopy(self.metadata[key])
            except RuntimeError:
                # multiple threads
                log.warning('key {} changed during copy'.format(key))

        # copy the core data
        copied = type(self)(entities=copy.deepcopy(self.entities),
                            vertices=copy.deepcopy(self.vertices),
                            metadata=metadata)

        cache = {}
        # try to copy the cache over to the new object
        try:
            # save dict keys before doing slow iteration
            keys = list(self._cache.cache.keys())
            # run through each key and copy into new cache
            for k in keys:
                cache[k] = copy.deepcopy(self._cache.cache[k])
        except RuntimeError:
            # if we have multiple threads this may error and is NBD
            log.debug('unable to copy cache')
        except BaseException:
            # catch and log errors we weren't expecting
            log.error('unable to copy cache', exc_info=True)
        copied._cache.cache = cache
        copied._cache.id_set()

        return copied
28064
def save_task_status(self, task_id,
                         task_action,
                         comment,
                         delegate_id=''):
        
        magic = self._magic_json(
            action=TouchWorksMagicConstants.ACTION_SAVE_TASK_STATUS,
            parameter1=task_id,
            parameter2=task_action,
            parameter3=delegate_id,
            parameter4=comment)
        response = self._http_request(TouchWorksEndPoints.MAGIC_JSON, data=magic)
        result = self._get_results_or_raise_if_magic_invalid(
            magic,
            response,
            TouchWorksMagicConstants.RESULT_SAVE_TASK_STATUS)
        return result
417679
def as_json(only: nil, except: nil, context: {})
      execute(Introspection::INTROSPECTION_QUERY, only: only, except: except, context: context).to_h
    end
1351431
def create_dictionary_representation
      dict = { storyboards: [],
               table_cells: [],
               collection_cells: [],
               view_controllers: [],
               segues: [],
               prefix: @config.prefix }

      @project.resources.each do |group|
        dict[:storyboards] << group.storyboard
        dict[:table_cells] += group.table_cells
        dict[:collection_cells] += group.collection_cells
        dict[:view_controllers] += group.view_controllers
        dict[:segues] += group.segues
      end

      # Build up flags.
      dict[:has_table_cells] = (dict[:table_cells].count > 0)
      dict[:has_collection_cells] = (dict[:collection_cells].count > 0)
      dict[:has_segues] = (dict[:segues].count > 0)

      dict
    end
988147
function info (cb) {
  var data = {
    name: pjson.name,
    message: 'pong',
    version: pjson.version,
    node_env: process.env.NODE_ENV,
    node_ver: process.versions.node,
    timestamp: Date.now(),
    hostname: os.hostname(),
    uptime: process.uptime(),
    loadavg: os.loadavg()[0]
  };

  cb(null, data);
}