As soon as an upstream sync happens, the file synced becomes the last synced version and must be stamped with its checksum to version it and the unsynced attribute must be removed
518405
function handlePatchAckResponse() {
    var syncedPath = data.content.path;

    function complete() {
      fsUtils.removeUnsynced(fs, syncedPath, function(err) {
        if(err && err.code !== 'ENOENT') {
          log.error('Failed to remove unsynced attribute for ' + syncedPath + ' in handlePatchAckResponse, complete()');
        }

        syncManager.syncNext(syncedPath);
      });
    }

    fs.lstat(syncedPath, function(err, stats) {
      if(err) {
        if(err.code !== 'ENOENT') {
          log.error('Failed to access ' + syncedPath + ' in handlePatchAckResponse');
          return fs.delaySync(function(delayErr, delayedPath) {
            if(delayErr) {
              log.error('Failed to delay upstream sync for ' + delayedPath + ' in handlePatchAckResponse');
            }
            onError(syncManager, err);
          });
        }

        // Non-existent paths usually due to renames or
        // deletes cannot be stamped with a checksum
        return complete();
      }

      if(!stats.isFile()) {
        return complete();
      }

      rsyncUtils.getChecksum(rawFs, syncedPath, function(err, checksum) {
        if(err) {
          log.error('Failed to get the checksum for ' + syncedPath + ' in handlePatchAckResponse');
          return fs.delaySync(function(delayErr, delayedPath) {
            if(delayErr) {
              log.error('Failed to delay upstream sync for ' + delayedPath + ' in handlePatchAckResponse while getting checksum');
            }
            onError(syncManager, err);
          });
        }

        fsUtils.setChecksum(rawFs, syncedPath, checksum, function(err) {
          if(err) {
            log.error('Failed to stamp the checksum for ' + syncedPath + ' in handlePatchAckResponse');
            return fs.delaySync(function(delayErr, delayedPath) {
              if(delayErr) {
                log.error('Failed to delay upstream sync for ' + delayedPath + ' in handlePatchAckResponse while setting checksum');
              }
              onError(syncManager, err);
            });
          }

          complete();
        });
      });
    });
  }
227185
def _sync(original, processed):
    
    for original_sample in original:
        original_sample[0]["peaks_files"] = {}
        for process_sample in processed:
            if dd.get_sample_name(original_sample[0]) == dd.get_sample_name(process_sample[0]):
                for key in ["peaks_files"]:
                    if process_sample[0].get(key):
                        original_sample[0][key] = process_sample[0][key]
    return original
362619
function(cb) {
            var lockFile = path.join(repoDir, '.git', 'index.lock');
            path.exists(lockFile, function(exists) {
                if (exists) {
                    fs.unlink(lockFile, function(err) {
                        if (err) {
                            log.warn('removing file ' + lockFile + ' failed with:', err);
                        }
                        else {
                            log.info('removed lock file: ' + lockFile);
                        }
                        cb(err, {removelock: 'remove git lock ' + lockFile + ', result ' + err});
                    });
                    return;
                }
                log.log('There is no lock file left, which is a good thing');
                cb(null, {removelock: 'no lock was present'});
            });
        }
151100
private void updateLastSynchronizationDate(Date syncDate, Integer subscriptionId) {
        TokenSyncDate tokenSyncDate = ocpiRepository.getTokenSyncDate(subscriptionId);

        if (tokenSyncDate == null) {
            tokenSyncDate = new TokenSyncDate();
            tokenSyncDate.setSubscriptionId(subscriptionId);
        }
        tokenSyncDate.setSyncDate(syncDate);

        ocpiRepository.insertOrUpdate(tokenSyncDate);
    }
103881
def _finalize_azure_file(self, sd, metadata, digest):
        # type: (SyncCopy, blobxfer.models.synccopy.Descriptor, dict,
        #        str) -> None
        
        # set file properties if required
        if (blobxfer.util.is_not_empty(digest) or
                sd.dst_entity.cache_control is not None):
            blobxfer.operations.azure.file.set_file_properties(
                sd.dst_entity, digest)
            if blobxfer.util.is_not_empty(sd.dst_entity.replica_targets):
                for ase in sd.dst_entity.replica_targets:
                    blobxfer.operations.azure.file.set_file_properties(
                        ase, digest)
        # set file metadata if needed
        if blobxfer.util.is_not_empty(metadata):
            blobxfer.operations.azure.file.set_file_metadata(
                sd.dst_entity, metadata)
            if blobxfer.util.is_not_empty(sd.dst_entity.replica_targets):
                for ase in sd.dst_entity.replica_targets:
                    blobxfer.operations.azure.file.set_file_metadata(
                        ase, metadata)
1356072
function markDirtyIfOnPush(node) {
    // Because data flows down the component tree, ancestors do not need to be marked dirty
    if (node.data && !(node.data[FLAGS] & 2 /* CheckAlways */)) {
        node.data[FLAGS] |= 4 /* Dirty */;
    }
}
224500
private function doCleanup($unchecked)
    {
        $tracker = $this->tracker;
        /* @var \PhpGuard\Listen\Resource\TrackedObject $tracked */
        foreach($unchecked as $id=>$tracked){
            $origin = $tracked->getResource();
            if(!$origin->isExists()){
                $tracker->addChangeSet($tracked,FilesystemEvent::DELETE);
                $tracker->remove($tracked);
            }
            unset($unchecked[$id]);
        }
    }
996429
def sync_out(self, file_name=None, force=False):
        """"""
        self.log('---- Sync Out ----')
        from ambry.bundle.files import BuildSourceFile

        self.dstate = self.STATES.BUILDING

        for f in self.build_source_files.list_records():

            if (f.sync_dir() == BuildSourceFile.SYNC_DIR.RECORD_TO_FILE or f.record.path == file_name) or force:
                self.log('Sync: {}'.format(f.record.path))
                f.record_to_fs()

        self.commit()
619123
protected void removeCleanupAndDestroyAllFreeConnections() { // removed iterator code
        // This method is called within a synchronize block
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.entry(this, tc, "removeCleanupAndDestroyAllFreeConnections");
        }
        int mcWrapperListIndex = mcWrapperList.size() - 1;
        for (int i = mcWrapperListIndex; i >= 0; --i) {
            MCWrapper mcw = (MCWrapper) mcWrapperList.remove(i);
            mcw.setPoolState(0);
            --numberOfConnectionsAssignedToThisFreePool;
            cleanupAndDestroyMCWrapper(mcw);
            pm.totalConnectionCount.decrementAndGet();
        }
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.exit(this, tc, "removeCleanupAndDestroyAllFreeConnections");
        }
    }
688796
def process_check(pool,model,field,version):
  ""
  try: syncable=model[field]
  except pg.FieldError: return ['?field']
  if not isinstance(syncable,syncschema.Syncable): return ['here',None,syncable]
  if syncable.version()>version: # this includes version=None. this is the load case as well as update.
    return ['here',syncable.version(),syncable.generate()] # 'here' as in 'here, take this' or 'here you go'
  elif syncable.version()==version: return ['ok',version]
  elif syncable.version()<version: return ['upload',syncable.version()]
  else: raise RuntimeError("shouldn't get here")
192399
def needs_sync(self):
        """"""

        affected_attributes = [
            'css_files', 'js_files',
            'scss_files', 'widgets']

        for attr in affected_attributes:
            if len(getattr(self, attr)) > 0:
                return True
        return False
66670
def remove(self, filename):
        """"""
        if self.list.pop(filename, None):
            self.modified_list = True
        if self.target.peer:  # otherwise `scan` command
            if self.target.is_local():
                remote_target = self.target.peer
                if remote_target.get_id() in self.dir["peer_sync"]:
                    rid = remote_target.get_id()
                    self.modified_sync = bool(
                        self.dir["peer_sync"][rid].pop(filename, None)
                    )
        return
576845
public static void invalidate() {
        final SharedMappedFilesCache oldCache;
        synchronized (syncObject) {
            oldCache = SharedMappedFilesCache.theCache;
            SharedMappedFilesCache.theCache = null;
        }
        if (oldCache != null) {
            for (final SharedMappedByteBuffer buffer : oldCache.cache.values()) {
                buffer.close();
            }
        }
    }
6069
def finish_synchronize
      return self if synchronized?
      synced = Source.new(@code, filename)
      if synced.parsed?
        synced.version = version
        return synced
      end
      synced = Source.new(@repaired, filename)
      synced.error_ranges.concat (error_ranges + last_updater.changes.map(&:range))
      synced.code = @code
      synced.synchronized = true
      synced.version = version
      synced
    end
455408
function removeExisting ()
{
    if (fs.existsSync("web/assets"))
    {
        var stat = fs.lstatSync("web/assets");

        if (stat.isFile() || stat.isSymbolicLink())
        {
            fs.unlinkSync("web/assets");
        }
        else
        {
            wrench.rmdirSyncRecursive("web/assets");
        }
    }
}
1309520
function unlinkIfExistsSync(filePath: string) {
  try {
    fs.unlinkSync(filePath);
  } catch (error) {
    if (error.code === 'ENOENT') {
      return;
    }
    throw error;
  }
}
342579
public void commitBlockSynchronization(Block lastblock,
                                  long newgenerationstamp, long newlength,
                                  boolean closeFile, boolean deleteblock, DatanodeID[] newtargets
  ) throws IOException {
    LOG.info("commitBlockSynchronization(lastblock=" + lastblock
      + ", newgenerationstamp=" + newgenerationstamp
      + ", newlength=" + newlength
      + ", newtargets=" + Arrays.asList(newtargets)
      + ", closeFile=" + closeFile
      + ", deleteBlock=" + deleteblock
      + ")");
    String src = null;
    writeLock();
    try {
      if (isInSafeMode()) {
        throw new SafeModeException("Cannot commitBlockSynchronization "
          + lastblock, safeMode);
      }      
      Block blockWithWildcardGenstamp = new Block(lastblock.getBlockId());
      final BlockInfo oldblockinfo = blocksMap.getStoredBlock(blockWithWildcardGenstamp);
      if (oldblockinfo == null) {
        throw new IOException("Block (=" + lastblock + ") not found");
      }
      if (!deleteblock
          && lastblock.getGenerationStamp() != oldblockinfo
              .getGenerationStamp()
          && oldblockinfo.getGenerationStamp() >= newgenerationstamp) {
        throw new IOException("Try to update block " + oldblockinfo
            + " to generation stamp " + newgenerationstamp);
      }
      INodeFile iFile = oldblockinfo.getINode();
      if (!iFile.isUnderConstruction()) {
        throw new IOException("Unexpected block (=" + lastblock
          + ") since the file (=" + iFile.getLocalName()
          + ") is not under construction");
      }
      INodeFileUnderConstruction pendingFile = (INodeFileUnderConstruction) iFile;
      // Fail the request if the block being synchronized is not the last block
      // of the file.
      pendingFile.checkLastBlockId(lastblock.getBlockId());

      // Remove old block from blocks map. This always have to be done
      // because the generation stamp of this block is changing.
      blocksMap.removeBlock(oldblockinfo);

      if (deleteblock) {
        pendingFile.removeBlock(lastblock);
      } else {
        // update last block, construct newblockinfo and add it to the blocks map
        lastblock.set(lastblock.getBlockId(), newlength, newgenerationstamp);
        final BlockInfo newblockinfo = 
            blocksMap.addINode(lastblock, pendingFile, 
                               pendingFile.getReplication());

        // find the DatanodeDescriptor objects
        // There should be no locations in the blocksMap till now because the
        // file is underConstruction
        DatanodeDescriptor[] descriptors = null;
        List<DatanodeDescriptor> descriptorsList =
          new ArrayList<DatanodeDescriptor>(newtargets.length);
        for(int i = 0; i < newtargets.length; i++) {
          // We don't use getDatanode here since that method can
          // throw. If we were to throw an exception during this commit
          // process, we'd fall out of sync since DNs have already finalized
          // the block with the new GS.
          DatanodeDescriptor node =
            datanodeMap.get(newtargets[i].getStorageID());
          if (node != null) {
            if (closeFile) {
              // If we aren't closing the file, we shouldn't add it to the
              // block list for the node, since the block is still under
              // construction there. (in getAdditionalBlock, for example
              // we don't add to the block map for the targets)
              node.addBlock(newblockinfo);
            }
            descriptorsList.add(node);
          } else {
          LOG.error("commitBlockSynchronization included a target DN " +
            newtargets[i] + " which is not known to NN. Ignoring.");
          }
        }
        if (!descriptorsList.isEmpty()) {
          descriptors = descriptorsList.toArray(new DatanodeDescriptor[0]);
        }
        // add locations into the INodeUnderConstruction
        pendingFile.setLastBlock(newblockinfo, descriptors);
      }

      // Get the file's full name; make sure that the file is valid
      src = pendingFile.getFullPathName();
      
      // If this commit does not want to close the file, persist
      // blocks only if append is supported and return
      if (!closeFile) {
        // persist the blocks if we support appends, 
        // or the block was deleted from the file and we need to persist it
        if (supportAppends || persistBlocks) {
          dir.persistBlocks(src, pendingFile);
        }
      } else {
        // remove lease, close file
        // this will persist the blocks
        finalizeINodeFileUnderConstruction(src, pendingFile);
      }
    } finally {// end of synchronized section
      writeUnlock();
    }

    if (closeFile || supportAppends) {
      getEditLog().logSync();
    }
    LOG.info("commitBlockSynchronization(newblock=" + lastblock
      + ", file=" + src + ") successful");
  }