auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void onVertexStateUpdated(VertexStateUpdate stateUpdate) { Preconditions.checkArgument(VertexState.CONFIGURED.equals(stateUpdate.getVertexState()), "Received incorrect state notification : " + stateUpdate.getVertexState() + " for vertex: " + stateUpdate.getVertexName() + " in vertex: " + this.vertexName); Preconditions.checkArgument(srcVerticesConfigured.containsKey(stateUpdate.getVertexName()), "Received incorrect vertex notification : " + stateUpdate.getVertexState() + " for vertex: " + stateUpdate.getVertexName() + " in vertex: " + this.vertexName); LOG.info("Received configured notification: " + stateUpdate.getVertexState() + " for vertex: " + stateUpdate.getVertexName() + " in vertex: " + this.vertexName); srcVerticesConfigured.put(stateUpdate.getVertexName(), true); boolean checkAllSrcVerticesConfigured = true; for (Map.Entry<String, Boolean> entry : srcVerticesConfigured.entrySet()) { if (!entry.getValue()) { LOG.info("Waiting for vertex in vertex ", entry.getKey(), this.vertexName); checkAllSrcVerticesConfigured = false; break; } } allSrcVerticesConfigured = checkAllSrcVerticesConfigured; scheduleTasks(); }

Target:
public synchronized void onVertexStateUpdated(VertexStateUpdate stateUpdate) { VertexState state = stateUpdate.getVertexState(); String fromVertex = stateUpdate.getVertexName(); if (!srcVerticesConfigured.containsKey(fromVertex)) { throw new IllegalArgumentException("Not expecting state update from vertex:" + fromVertex + " in vertex: " + this.vertexName); } if (!VertexState.CONFIGURED.equals(state)) { throw new IllegalArgumentException("Received incorrect state notification : " + state + " from vertex: " + fromVertex + " in vertex: " + this.vertexName); } LOG.info("Received configured notification: " + state + " for vertex: " + fromVertex + " in vertex: " + this.vertexName); srcVerticesConfigured.put(fromVertex, true); boolean checkAllSrcVerticesConfigured = true; for (Map.Entry<String, Boolean> entry : srcVerticesConfigured.entrySet()) { if (!entry.getValue()) { LOG.info("Waiting for vertex in vertex ", entry.getKey(), this.vertexName); checkAllSrcVerticesConfigured = false; break; } } allSrcVerticesConfigured = checkAllSrcVerticesConfigured; scheduleTasks(); }
Source:
private Page getSelectedRows() { checkState(selectedRowPageBuilder.isPresent()); int rowNumberChannel = types.size() - 1; PageBuilder pageBuilder = selectedRowPageBuilder.get(); for (int currentPosition = 0; currentPosition < inputPage.getPositionCount(); currentPosition++) { long partitionId = getPartitionId(currentPosition); long rowCount = partitionRowCount.get(partitionId); if (rowCount == maxRowsPerPartition.get()) { continue; } pageBuilder.declarePosition(); for (int i = 0; i < outputChannels.length; i++) { int channel = outputChannels[i]; Type type = types.get(i); type.appendTo(inputPage.getBlock(channel), currentPosition, pageBuilder.getBlockBuilder(i)); } BIGINT.writeLong(pageBuilder.getBlockBuilder(rowNumberChannel), rowCount + 1); partitionRowCount.set(partitionId, rowCount + 1); } if (pageBuilder.isEmpty()) { return null; } Page page = pageBuilder.build(); pageBuilder.reset(); return page; }

Target:
private Page getSelectedRows() { verify(selectedRowPageBuilder.isPresent()); int rowNumberChannel = types.size() - 1; PageBuilder pageBuilder = selectedRowPageBuilder.get(); verify(pageBuilder.isEmpty()); for (int currentPosition = 0; currentPosition < inputPage.getPositionCount(); currentPosition++) { long partitionId = getPartitionId(currentPosition); long rowCount = partitionRowCount.get(partitionId); if (rowCount == maxRowsPerPartition.get()) { continue; } pageBuilder.declarePosition(); for (int i = 0; i < outputChannels.length; i++) { int channel = outputChannels[i]; Type type = types.get(i); type.appendTo(inputPage.getBlock(channel), currentPosition, pageBuilder.getBlockBuilder(i)); } BIGINT.writeLong(pageBuilder.getBlockBuilder(rowNumberChannel), rowCount + 1); partitionRowCount.set(partitionId, rowCount + 1); } if (pageBuilder.isEmpty()) { return null; } Page page = pageBuilder.build(); pageBuilder.reset(); return page; }
Source:
private DarkClusterStrategy createStrategy(String darkClusterName, DarkClusterConfig darkClusterConfig) { if (darkClusterConfig.hasMultiplierStrategyList()) { MultiplierStrategyTypeArray strategyList = darkClusterConfig.getMultiplierStrategyList(); for (com.linkedin.d2.multiplierStrategyType multiplierStrategyType : strategyList) { if (RELATIVE_TRAFFIC.equals(multiplierStrategyType) && darkClusterConfig.getMultiplier() > 0) { if (darkClusterConfig.getMultiplier() <= 0) { return new NoOpDarkClusterStrategy(); } BaseDarkClusterDispatcher baseDarkClusterDispatcher = new BaseDarkClusterDispatcherImpl(darkClusterName, _darkClusterDispatcher, _notifier, _verifierManager); return new RelativeTrafficMultiplierDarkClusterStrategy(_sourceClusterName, darkClusterName, darkClusterConfig.getMultiplier(), baseDarkClusterDispatcher, _notifier, _facilities.getClusterInfoProvider(), _random); } else if (CONSTANT_QPS.equals(multiplierStrategyType)) { } else { return new NoOpDarkClusterStrategy(); } } } return new NoOpDarkClusterStrategy(); }

Target:
private DarkClusterStrategy createStrategy(String darkClusterName, DarkClusterConfig darkClusterConfig) { if (darkClusterConfig.hasDarkClusterStrategyPrioritizedList()) { DarkClusterStrategyNameArray strategyList = darkClusterConfig.getDarkClusterStrategyPrioritizedList(); for (com.linkedin.d2.DarkClusterStrategyName darkClusterStrategyName : strategyList) { switch(darkClusterStrategyName) { case RELATIVE_TRAFFIC: if (RelativeTrafficMultiplierDarkClusterStrategy.isValidConfig(darkClusterConfig)) { BaseDarkClusterDispatcher baseDarkClusterDispatcher = new BaseDarkClusterDispatcherImpl(darkClusterName, _darkClusterDispatcher, _notifier, _verifierManager); return new RelativeTrafficMultiplierDarkClusterStrategy(_sourceClusterName, darkClusterName, darkClusterConfig.getMultiplier(), baseDarkClusterDispatcher, _notifier, _facilities.getClusterInfoProvider(), _random); } break; case CONSTANT_QPS: break; default: break; } } } return new NoOpDarkClusterStrategy(); }
Source:
public List<InputAnchor> getAllInputs() { return Arrays.asList(r,g,b); }

Target:
public List<InputAnchor> getAllInputs() { return ImmutableList.of(r,g,b); }
Source:
public void schedule(I id) { Duration timeout = this.expiration.getTimeout(); if (expirationTracker != null) { expirationTracker.trackExpiration(id); if (expireTask == null) { InfinispanEjbLogger.ROOT_LOGGER.tracef("Scheduling stateful session bean %s to expire in %s", id, timeout); Runnable task = new ExpirationTask(); synchronized (this) { expireTask = this.expiration.getExecutor().schedule(task, timeout.toMillis(), TimeUnit.MILLISECONDS); } } } }

Target:
public void schedule(I id) { BeanEntry<I> entry = this.factory.findValue(id); if (entry != null) { this.schedule(id, entry); } }
Source:
private ItemStack getCooked(final ItemStack is) { ItemStack cooked = new ItemStack(Material.AIR); final Material material = is.getType(); switch (material) { case BEEF: cooked = new ItemStack(Material.COOKED_BEEF); break; case COD: cooked = new ItemStack(Material.COOKED_COD); break; case CHICKEN: cooked = new ItemStack(Material.COOKED_CHICKEN); break; case PORKCHOP: cooked = new ItemStack(Material.COOKED_PORKCHOP); break; case POTATO: cooked = new ItemStack(Material.BAKED_POTATO); break; case MUTTON: cooked = new ItemStack(Material.COOKED_MUTTON); break; case RABBIT: cooked = new ItemStack(Material.COOKED_RABBIT); break; case SALMON: cooked = new ItemStack(Material.COOKED_SALMON); break; case KELP: cooked = new ItemStack(Material.DRIED_KELP); break; case CHORUS_FRUIT: cooked = new ItemStack(Material.POPPED_CHORUS_FRUIT); break; case WHEAT: cooked = new ItemStack(Material.BREAD); break; case WET_SPONGE: cooked = new ItemStack(Material.SPONGE); break; case STICK: cooked = bPlayer.canUseSubElement(SubElement.BLUE_FIRE) ? new ItemStack(Material.SOUL_TORCH) : new ItemStack(Material.TORCH); default: break; } return cooked; }

Target:
private ItemStack getCooked(final ItemStack is) { ItemStack cooked = new ItemStack(Material.AIR); final Material material = is.getType(); switch (material) { case BEEF: cooked = new ItemStack(Material.COOKED_BEEF); break; case COD: cooked = new ItemStack(Material.COOKED_COD); break; case CHICKEN: cooked = new ItemStack(Material.COOKED_CHICKEN); break; case PORKCHOP: cooked = new ItemStack(Material.COOKED_PORKCHOP); break; case POTATO: cooked = new ItemStack(Material.BAKED_POTATO); break; case MUTTON: cooked = new ItemStack(Material.COOKED_MUTTON); break; case RABBIT: cooked = new ItemStack(Material.COOKED_RABBIT); break; case SALMON: cooked = new ItemStack(Material.COOKED_SALMON); break; case KELP: cooked = new ItemStack(Material.DRIED_KELP); break; case CHORUS_FRUIT: cooked = new ItemStack(Material.POPPED_CHORUS_FRUIT); break; case WET_SPONGE: cooked = new ItemStack(Material.SPONGE); break; case STICK: cooked = bPlayer.canUseSubElement(SubElement.BLUE_FIRE) ? new ItemStack(Material.SOUL_TORCH) : new ItemStack(Material.TORCH); default: break; } return cooked; }
Source:
public static Guid getGuidValue(Guid id) { return id == null ? null : id; }

Target:
public static Guid getGuidValue(Guid id) { return id; }
Source:
public void registered_device_with_x509cert_to_server_with_x509cert() throws NonUniqueSecurityInfoException { helper.createServerWithX509Cert(helper.trustedCertificates); helper.server.start(); helper.createX509CertClient(helper.clientPrivateKeyFromCert, helper.trustedCertificates); helper.server.getSecurityRegistry().add(SecurityInfo.newX509CertInfo(helper.getCurrentEndpoint())); helper.client.start(); helper.waitForRegistration(1); assertEquals(1, helper.server.getRegService().getAllRegistrations().size()); assertNotNull(helper.getCurrentRegistration()); }

Target:
public void registered_device_with_x509cert_to_server_with_x509cert() throws NonUniqueSecurityInfoException { helper.createServerWithX509Cert(helper.trustedCertificates); helper.server.start(); helper.createX509CertClient(helper.clientPrivateKeyFromCert, helper.trustedCertificates); helper.server.getSecurityRegistry().add(SecurityInfo.newX509CertInfo(helper.getCurrentEndpoint())); helper.client.start(); helper.waitForRegistration(1); assertEquals(1, helper.server.getRegistrationService().getAllRegistrations().size()); assertNotNull(helper.getCurrentRegistration()); }
Source:
public void addHeaders(HttpURLConnection connection) { if (this.headers == null) { return; } boolean hasAcceptHeader = false; for (KeyValuePair pair : this.headers) { String key = pair.key.toString(); connection.addRequestProperty(key, pair.value.toString()); if (key.toLowerCase().contentEquals("Accept-Encoding")) { hasAcceptHeader = true; } } if (!hasAcceptHeader) { connection.addRequestProperty("Accept-Encoding", "gzip"); } }

Target:
public void addHeaders(HttpURLConnection connection) { if (this.headers == null) { return; } boolean hasAcceptHeader = false; for (KeyValuePair pair : this.headers) { String key = pair.key.toString(); connection.addRequestProperty(key, pair.value.toString()); if (key.toLowerCase().contentEquals("accept-encoding")) { hasAcceptHeader = true; } } if (!hasAcceptHeader) { connection.addRequestProperty("Accept-Encoding", "gzip"); } }
Source:
public byte[] decrypt(byte[] cipherTextBytes, String algorithm, String internalCryptoProviderType) throws CryptoException { failIfEncryptDecryptInputsAreInvalid(cipherTextBytes,algorithm,internalCryptoProviderType); byte[] decryptedValue; try { CryptoService cryptoService = CarbonCoreDataHolder.getInstance().getCryptoService(); if (cryptoService == null) { throw new CryptoException("A crypto service implementation has not been registered."); } CipherMetaDataHolder cipherMetaDataHolder = cipherTextToCipherMetaDataHolder(cipherTextBytes); if (cipherMetaDataHolder != null) { if (log.isDebugEnabled()) { log.debug( String.format("Cipher text is in self contained format. Retrieve the actual cipher from " + "the self contained cipher text.")); } cipherTextBytes = cipherMetaDataHolder.getCipherBase64Decoded(); } if (cipherTextBytes.length == 0) { decryptedValue = StringUtils.EMPTY.getBytes(); if (log.isDebugEnabled()) { log.debug("Ciphertext is empty. An empty array will be used as the plaintext bytes."); } } else { decryptedValue = cryptoService.decrypt(cipherTextBytes, algorithm, CRYPTO_API_PROVIDER_BC, internalCryptoProviderType); } return decryptedValue; } catch (Exception e) { throw new CryptoException("An error occurred while decrypting data.", e); } }

Target:
public byte[] decrypt(byte[] cipherTextBytes, String algorithm, String internalCryptoProviderType) throws CryptoException { failIfEncryptDecryptInputsAreInvalid(cipherTextBytes, algorithm, internalCryptoProviderType); byte[] decryptedValue; try { CryptoService cryptoService = CarbonCoreDataHolder.getInstance().getCryptoService(); if (cryptoService == null) { throw new CryptoException("A crypto service implementation has not been registered."); } CipherMetaDataHolder cipherMetaDataHolder = cipherTextToCipherMetaDataHolder(cipherTextBytes); if (cipherMetaDataHolder != null) { if (log.isDebugEnabled()) { log.debug( String.format("Cipher text is in self contained format. Retrieve the actual cipher from " + "the self contained cipher text.")); } cipherTextBytes = cipherMetaDataHolder.getCipherBase64Decoded(); algorithm = cipherMetaDataHolder.getTransformation(); } if (cipherTextBytes.length == 0) { decryptedValue = StringUtils.EMPTY.getBytes(); if (log.isDebugEnabled()) { log.debug("Ciphertext is empty. An empty array will be used as the plaintext bytes."); } } else { decryptedValue = cryptoService.decrypt(cipherTextBytes, algorithm, CRYPTO_API_PROVIDER_BC, internalCryptoProviderType); } return decryptedValue; } catch (org.wso2.carbon.crypto.api.CryptoException e) { throw new CryptoException("An error occurred while decrypting data.", e); } }
Source:
public Number apply(List<Expr> args, Expr.ObjectBinding bindings) { if (args.size() != 2) { throw new RuntimeException("function '" + name() + "' needs 2 argument"); } Expr expr1 = args.get(0); Expr expr2 = args.get(1); return eval(expr1.eval(bindings), expr2.eval(bindings)); }

Target:
public ExprEval apply(List<Expr> args, Expr.ObjectBinding bindings) { if (args.size() != 2) { throw new IAE("function '%s' needs 2 arguments", name()); } Expr expr1 = args.get(0); Expr expr2 = args.get(1); return eval(expr1.eval(bindings), expr2.eval(bindings)); }
Source:
public static Guid GetEntityGuid(Object entity) { if (entity instanceof VM) { return ((VM) entity).getId(); } else if (entity instanceof storage_pool) { return ((storage_pool) entity).getId(); } else if (entity instanceof VDSGroup) { return ((VDSGroup) entity).getId(); } else if (entity instanceof VDS) { return ((VDS) entity).getId(); } else if (entity instanceof storage_domains) { return ((storage_domains) entity).getId(); } else if (entity instanceof VmTemplate) { return ((VmTemplate) entity).getId(); } else if (entity instanceof vm_pools) { return ((vm_pools) entity).getvm_pool_id(); } else if (entity instanceof DbUser) { return ((DbUser) entity).getuser_id(); } else if (entity instanceof Quota) { return ((Quota) entity).getId(); } else if (entity instanceof DiskImage) { return ((DiskImage) entity).getId(); } else if (entity instanceof GlusterVolumeEntity) { return ((GlusterVolumeEntity) entity).getId(); } else if (entity instanceof NetworkView) { return ((NetworkView) entity).getNetwork().getId(); } return new Guid(); }

Target:
public static Guid GetEntityGuid(Object entity) { if (entity instanceof VM) { return ((VM) entity).getId(); } else if (entity instanceof storage_pool) { return ((storage_pool) entity).getId(); } else if (entity instanceof VDSGroup) { return ((VDSGroup) entity).getId(); } else if (entity instanceof VDS) { return ((VDS) entity).getId(); } else if (entity instanceof storage_domains) { return ((storage_domains) entity).getId(); } else if (entity instanceof VmTemplate) { return ((VmTemplate) entity).getId(); } else if (entity instanceof vm_pools) { return ((vm_pools) entity).getvm_pool_id(); } else if (entity instanceof DbUser) { return ((DbUser) entity).getuser_id(); } else if (entity instanceof Quota) { return ((Quota) entity).getId(); } else if (entity instanceof DiskImage) { return ((DiskImage) entity).getId(); } else if (entity instanceof GlusterVolumeEntity) { return ((GlusterVolumeEntity) entity).getId(); } else if (entity instanceof Network) { return ((Network) entity).getId(); } else if (entity instanceof NetworkView) { return ((NetworkView) entity).getNetwork().getId(); } return new Guid(); }
Source:
protected void doExecute() { DslCommonPlugin.PROFILER.startWork(SiriusTasksKey.CLEANING_REMOVEDANGLING_KEY); for (EObject eObject : toRemoveXRefFrom) { modelAccessor.eDelete(eObject, xReferencer, isReferenceToIgnorePredicate); TreeIterator<EObject> eAllContents = eObject.eAllContents(); while (eAllContents.hasNext()) { EObject child = eAllContents.next(); modelAccessor.eRemoveCrossReferences(child, xReferencer, isReferenceToIgnorePredicate); } } DslCommonPlugin.PROFILER.stopWork(SiriusTasksKey.CLEANING_REMOVEDANGLING_KEY); toRemoveXRefFrom.clear(); modelAccessor = null; xReferencer = null; }

Target:
protected void doExecute() { DslCommonPlugin.PROFILER.startWork(SiriusTasksKey.CLEANING_REMOVEDANGLING_KEY); for (EObject eObject : toRemoveXRefFrom) { modelAccessor.eDelete(eObject, xReferencer, isReferenceToIgnorePredicate); } DslCommonPlugin.PROFILER.stopWork(SiriusTasksKey.CLEANING_REMOVEDANGLING_KEY); toRemoveXRefFrom.clear(); modelAccessor = null; xReferencer = null; }
Source:
public URLClassLoader getClassLoader(ObjectId rulesId) { String filePath = ""; File cacheFolder = site.resolve( config.getString("cache", null, "directory")); if (cacheFolder != null) { filePath = cacheFolder.getPath(); } File jarFile = null; if (rulesId != null) { jarFile = new File(filePath + "/rules/rules-" + rulesId.getName() + ".jar"); } ClassLoader defaultLoader = getClass().getClassLoader(); if(cacheFolder != null && jarFile != null && jarFile.exists()) { URL url; try { url = jarFile.toURI().toURL(); } catch (MalformedURLException e) { return null; } URL[] urls = new URL[]{url}; return new URLClassLoader(urls, defaultLoader); } else { return null; } }

Target:
public ClassLoader getClassLoader(ObjectId rulesId) { Reference<? extends ClassLoader> ref = referMap.get(rulesId); if (ref != null) { ClassLoader cl = ref.get(); if (cl != null) { return cl; } synchronized(lock) { referMap.remove(rulesId); } ref.enqueue(); } cleanMap(); if (rulesId == null || rulesDir == null) { return null; } File jarFile = new File(rulesDir, "rules-" + rulesId.getName() + ".jar"); if (!jarFile.isFile()) { return null; } ClassLoader defaultLoader = getClass().getClassLoader(); URL url; try { url = jarFile.toURI().toURL(); } catch (MalformedURLException e) { return null; } URL[] urls = new URL[]{url}; ClassLoader urlLoader = new URLClassLoader(urls, defaultLoader); LoaderRef lRef = new LoaderRef(rulesId, urlLoader); synchronized(lock) { referMap.put(rulesId, lRef); } return urlLoader; }
Source:
public ThingStatusInfoBuilder withStatusDetail(ThingStatusDetail statusDetail) throws IllegalArgumentException { this.statusDetail = statusDetail; return this; }

Target:
public ThingStatusInfoBuilder withStatusDetail(ThingStatusDetail statusDetail) { this.statusDetail = statusDetail; return this; }
Source:
public Response act(final Request req) throws IOException { final Inbox inbox = new RqAlias(this.base, req).alias().inbox(); final long number = inbox.start(); final Bout bout = inbox.bout(number); final StringBuilder msg = new StringBuilder( String.format("new bout #%d started", number) ); final Href href = new RqHref.Base(req).href(); final Iterator<String> invite = href.param("invite").iterator(); while (invite.hasNext()) { final String friend = invite.next(); try { bout.friends().invite(friend); } catch (final Friends.UnknownAliasException ex) { throw new RsFailure(ex); } msg.append(String.format(", \"%s\" invited", friend)); } final Iterator<String> post = href.param("post").iterator(); if (post.hasNext()) { try { bout.messages().post(post.next()); } catch (final Messages.BrokenPostException ex) { throw new RsFailure(ex); } msg.append(", message posted"); } throw new RsForward( new RsFlash(msg.toString()), new RqHref.Smart(new RqHref.Base(req)).home().path("b").path( Long.toString(number) ) ); }

Target:
public Response act(final Request req) throws IOException { final Inbox inbox = new RqAlias(this.base, req).alias().inbox(); final long number = inbox.start(); final Bout bout = inbox.bout(number); final StringBuilder msg = new StringBuilder( String.format("new bout #%d started", number) ); final Href href = new RqHref.Base(req).href(); final Iterator<String> invite = href.param("invite").iterator(); while (invite.hasNext()) { final String friend = invite.next(); try { bout.friends().invite(friend); } catch (final Friends.UnknownAliasException ex) { this.discard(bout); throw new RsFailure(ex); } msg.append(String.format(", \"%s\" invited", friend)); } final Iterator<String> post = href.param("post").iterator(); if (post.hasNext()) { try { bout.messages().post(post.next()); } catch (final Messages.BrokenPostException ex) { this.discard(bout); throw new RsFailure(ex); } msg.append(", message posted"); } throw new RsForward( new RsFlash(msg.toString()), new RqHref.Smart(new RqHref.Base(req)).home().path("b").path( Long.toString(number) ) ); }
Source:
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { switch (viewType) { case VIEW_TYPE_HEADER: return new HeaderViewHolder(LayoutInflater.from(parent.getContext()) .inflate(R.layout.new_site_creation_domain_header, parent, false)); case VIEW_TYPE_INPUT: return new InputViewHolder(LayoutInflater.from(parent.getContext()) .inflate(R.layout.new_site_creation_domain_input, parent, false)); case VIEW_TYPE_ITEM: return new DomainViewHolder(LayoutInflater.from(parent.getContext()) .inflate(R.layout.new_site_creation_domain_item, parent, false)); default: throw new RuntimeException("Unknown view type " + viewType); } }

Target:
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { switch (viewType) { case VIEW_TYPE_HEADER: return new HeaderViewHolder(LayoutInflater.from(parent.getContext()) .inflate(R.layout.site_creation_domain_header, parent, false)); case VIEW_TYPE_INPUT: return new InputViewHolder(LayoutInflater.from(parent.getContext()) .inflate(R.layout.site_creation_domain_input, parent, false)); case VIEW_TYPE_ITEM: return new DomainViewHolder(LayoutInflater.from(parent.getContext()) .inflate(R.layout.site_creation_domain_item, parent, false)); default: throw new RuntimeException("Unknown view type " + viewType); } }
Source:
public void unlockDiskStore(String diskStoreName) { if (diskStoreLatches.get(diskStoreName) != null) { diskStoreLatches.get(diskStoreName).countDown(); } }

Target:
public void unlockDiskStore(String diskStoreName) { doUnlockDiskStore(diskStoreName); }
Source:
private void updateReceivedHUs( final IHUContext huContext, final Collection<I_M_HU> hus) { ppOrderProductAttributeBL.updateHUAttributes(hus, getPpOrderId()); if (lotNumber != null || bestBeforeDate != null) { final IAttributeStorageFactory huAttributeStorageFactory = huContext.getHUAttributeStorageFactory(); for (final I_M_HU hu : hus) { final IAttributeStorage huAttributes = huAttributeStorageFactory.getAttributeStorage(hu); setLotNumberAttribute(hu, huAttributes); setBestBeforeDateAttribute(huAttributes); huAttributes.saveChangesIfNeeded(); } } setAssignedHUs(hus); }

Target:
private void updateReceivedHUs( final IHUContext huContext, final Collection<I_M_HU> hus) { ppOrderProductAttributeBL.updateHUAttributes(hus, getPpOrderId()); if (lotNumber != null || bestBeforeDate != null) { final IAttributeStorageFactory huAttributeStorageFactory = huContext.getHUAttributeStorageFactory(); for (final I_M_HU hu : hus) { final IAttributeStorage huAttributes = huAttributeStorageFactory.getAttributeStorage(hu); setAttributes(hu, huAttributes); } } setAssignedHUs(hus); }
Source:
private Map<QName, String> collectUnknownAttributesFrom(StartElement element) { Map<QName, String> otherAttributes = new HashMap<>(); Iterator<?> attributes = element.getAttributes(); while (attributes.hasNext()) { Attribute currentAttribute = (Attribute) attributes.next(); QName attributeQName = currentAttribute.getName(); if (attributeQName == null || DEFAULT_KNOWN_LOCAL_ATTRIBUTE_NAMES.contains(attributeQName.getLocalPart())) { continue; } String attributeValue = currentAttribute.getValue(); otherAttributes.put(attributeQName, attributeValue); if (LOGGER.isTraceEnabled()) { LOGGER.trace("Adding attribute " + attributeQName + " with value " + attributeValue); } } return otherAttributes; }

Target:
private static Map<QName, String> collectUnknownAttributesFrom(StartElement element) { Map<QName, String> otherAttributes = new HashMap<>(); Iterator<?> attributes = element.getAttributes(); while (attributes.hasNext()) { Attribute currentAttribute = (Attribute) attributes.next(); QName attributeQName = currentAttribute.getName(); if (attributeQName == null || DEFAULT_KNOWN_ATTRIBUTE_NAMES.contains(attributeQName)) { continue; } String attributeValue = currentAttribute.getValue(); otherAttributes.put(attributeQName, attributeValue); if (LOGGER.isTraceEnabled()) { LOGGER.trace(String.format("Adding attribute %s with value %s", attributeQName, attributeValue)); } } return otherAttributes; }
Source:
public Pair<String, String[]> next(ITmfEvent event, Map<String, TmfXmlTest> tests, TmfXmlScenarioInfo scenarioInfo) { boolean matched = false; TmfXmlStateTransition stateTransition = null; TmfXmlState state = NonNullUtils.checkNotNull(fStatesMap.get(scenarioInfo.getActiveState())); for (int i = 0; i < state.getTransitionList().size() && !matched; i++) { stateTransition = state.getTransitionList().get(i); matched = stateTransition.validate(event, scenarioInfo, tests); } return getNextStep(stateTransition, matched, scenarioInfo.getActiveState()); }

Target:
public @Nullable Pair<String, List<String>> next(ITmfEvent event, Map<String, TmfXmlTest> tests, TmfXmlScenarioInfo scenarioInfo) { boolean matched = false; TmfXmlStateTransition stateTransition = null; TmfXmlState state = NonNullUtils.checkNotNull(fStatesMap.get(scenarioInfo.getActiveState())); for (int i = 0; i < state.getTransitionList().size() && !matched; i++) { stateTransition = state.getTransitionList().get(i); matched = stateTransition.validate(event, scenarioInfo, tests); } return matched ? getNextStep(stateTransition, scenarioInfo.getActiveState()) : null; }
Source:
protected Set<TokenRangeDiagnostic> generateTokenRangeDiagnostics(TokenMap tokenMap) { Set<TokenRangeDiagnostic> reports = new HashSet<>(); for (TokenRange range : tokenMap.getTokenRanges()) { Set<Node> allReplicas = tokenMap.getReplicas(keyspace.getName(), range); Set<Node> aliveReplicas = allReplicas.stream().filter(this::isAlive).collect(Collectors.toSet()); TokenRangeDiagnostic report = generateTokenRangeDiagnostic(range, aliveReplicas); reports.add(report); } return reports; }

Target:
protected Set<TokenRangeDiagnostic> generateTokenRangeDiagnostics(TokenMap tokenMap) { Set<TokenRange> tokenRanges = tokenMap.getTokenRanges(); Set<TokenRangeDiagnostic> reports = Sets.newHashSetWithExpectedSize(tokenRanges.size()); for (TokenRange range : tokenRanges) { Set<Node> allReplicas = tokenMap.getReplicas(keyspace.getName(), range); TokenRangeDiagnostic report = generateTokenRangeDiagnostic(range, allReplicas); reports.add(report); } return reports; }
Source:
public String getCreationSQL() { final StringBuilder sbSQL = new StringBuilder(100); sbSQL.append("ALTER TABLE "); sbSQL.append(PgDiffUtils.getQuotedName(getTableName())); sbSQL.append(System.getProperty("line.separator")); sbSQL.append("\tADD CONSTRAINT "); sbSQL.append(PgDiffUtils.getQuotedName(getName())); sbSQL.append(' '); sbSQL.append(getDefinition()); sbSQL.append(';'); if (comment != null && !comment.isEmpty()) { sbSQL.append(System.getProperty("line.separator")); sbSQL.append(System.getProperty("line.separator")); sbSQL.append("COMMENT ON CONSTRAINT "); sbSQL.append(PgDiffUtils.getQuotedName(name)); sbSQL.append(" ON "); sbSQL.append(PgDiffUtils.getQuotedName(tableName)); sbSQL.append(" IS "); sbSQL.append(comment); sbSQL.append(';'); } return sbSQL.toString(); }

Target:
public String getCreationSQL() { final StringBuilder sbSQL = new StringBuilder(100); sbSQL.append("ALTER TABLE "); sbSQL.append(PgDiffUtils.getQuotedName(getTableName())); sbSQL.append(System.getProperty("line.separator")); sbSQL.append("\tADD CONSTRAINT "); sbSQL.append(PgDiffUtils.getCreateIfNotExists()); sbSQL.append(PgDiffUtils.getQuotedName(getName())); sbSQL.append(' '); sbSQL.append(getDefinition()); sbSQL.append(';'); if (comment != null && !comment.isEmpty()) { sbSQL.append(System.getProperty("line.separator")); sbSQL.append(System.getProperty("line.separator")); sbSQL.append("COMMENT ON CONSTRAINT "); sbSQL.append(PgDiffUtils.getQuotedName(name)); sbSQL.append(" ON "); sbSQL.append(PgDiffUtils.getQuotedName(tableName)); sbSQL.append(" IS "); sbSQL.append(comment); sbSQL.append(';'); } return sbSQL.toString(); }
Source:
private String getLsRegisterOutput() throws Exception { if (lsRegisterOutput != null) { return lsRegisterOutput; } long beforeCallLsRegister = System.currentTimeMillis(); lsRegisterOutput = processExecutor.execute(LSREGISTER, DUMP); long afterCallLsRegister = System.currentTimeMillis(); System.out.println("Call to lsregister took :" + (afterCallLsRegister - beforeCallLsRegister)); return lsRegisterOutput; }

Target:
private String getLsRegisterOutput() throws Exception { if (this.lsRegisterOutput != null) { return this.lsRegisterOutput; } this.lsRegisterOutput = processExecutor.execute(LSREGISTER, DUMP); return this.lsRegisterOutput; }
Source:
public void verifySingleValue() { final PortValue portValue = new PortValue("5"); assertThat(portValue.getPorts(), Matchers.hasItems(5)); assertThat(portValue.matches(5), Matchers.is(true)); assertThat(portValue.matches(1), Matchers.is(false)); }

Target:
public void verifySingleValue() { final PortValue portValue = new PortValue("5"); assertThat(portValue.getPorts(), hasItems(5)); assertThat(portValue.matches(5), is(true)); assertThat(portValue.matches(1), is(false)); }
Source:
public void saveResourceWithNoOptions() throws IOException, SAXException, ParserConfigurationException { final EClass class1 = setupClass("package1", "class1"); final URI resourceURI = URI.createURI("MyResource.xmi"); final XMIResource resource = new XMIResourceImpl(resourceURI); resource.getContents().add(class1); resource.save(null); final ResourceSet resourceSet = new ResourceSetImpl(); resourceSet.getResources().add(resource); class1.setName("test"); Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder() .parse("MyResource.xmi"); assertEquals(document.getDocumentElement().getAttribute("name"), "class1"); ResourceSetHelpers.save(resourceSet, null); document = DocumentBuilderFactory.newInstance().newDocumentBuilder() .parse("MyResource.xmi"); assertEquals(document.getDocumentElement().getAttribute("name"), "test"); }

Target:
public void saveResourceWithNoOptions() throws IOException, SAXException, ParserConfigurationException { final EClass class1 = setupClass("package1", "class1"); final URI resourceURI = URI.createURI("MyResource.xmi"); final XMIResource resource = createResource(resourceURI); resource.getContents().add(class1); resource.save(null); final ResourceSet resourceSet = new ResourceSetImpl(); resourceSet.getResources().add(resource); Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder() .parse("MyResource.xmi"); assertEquals(document.getDocumentElement().getAttribute("name"), "class1"); class1.setName("test"); ResourceSetHelpers.save(resourceSet, null); document = DocumentBuilderFactory.newInstance().newDocumentBuilder() .parse("MyResource.xmi"); assertEquals(document.getDocumentElement().getAttribute("name"), "test"); }
Source:
private List<Branch> getBranchesOfCommit(RevCommit commit, ListMode mode) throws GitAPIException { List<Branch> branchList = new ArrayList<Branch>(); List<Ref> branches = getGit().branchList() .setListMode(mode) .setContains(commit.getName()) .call(); branches.forEach(ref->branchList.add(newDto(Branch.class).withName(ref.getName()))); return branchList; }

Target:
private List<Branch> getBranchesOfCommit(RevCommit commit, ListMode mode) throws GitAPIException { List<Ref> branches = getGit().branchList() .setListMode(mode) .setContains(commit.getName()) .call(); return branches.stream() .map(branch -> newDto(Branch.class).withName(branch.getName())) .collect(Collectors.toList()); }
Source:
public T value() { if (m_value == null) { m_value = restoreParameter(); } else if(!isPerInstance()) { m_value = restoreParameter(); } return (m_value!=null)? m_value : m_defaultValue; }

Target:
public T value() { if (m_value == null) { m_value = restoreParameter(); } else if(!isPerInstance()) { m_value = restoreParameter(); } return (m_value == null)? m_defaultValue : m_value; }
Source:
@Override public boolean process(Set<? extends TypeElement> types, RoundEnvironment env) { if (!env.processingOver()) { for (Element e : env.getElementsAnnotatedWith(Module.class)) { if (!(e instanceof TypeElement)) { error("@Module applies to a type, " + e.getSimpleName() + " is a " + e.getKind(), e); continue; } delayedModuleNames.add(((TypeElement) e).getQualifiedName().toString()); } return true; } Set<Element> modules = new LinkedHashSet<Element>(); for (String moduleName : delayedModuleNames) { modules.add(processingEnv.getElementUtils().getTypeElement(moduleName)); } for (Element element : modules) { Map<String, Object> annotation = CodeGen.getAnnotation(Module.class, element); if (!annotation.get("complete").equals(Boolean.TRUE)) { continue; } TypeElement moduleType = (TypeElement) element; Map<String, Binding<?>> bindings = processCompleteModule(moduleType); try { new ProblemDetector().detectProblems(bindings.values()); } catch (IllegalStateException e) { error("Graph validation failed: " + e.getMessage(), moduleType); continue; } try { writeDotFile(moduleType, bindings); } catch (IOException e) { processingEnv.getMessager() .printMessage(Diagnostic.Kind.WARNING, "Graph visualization failed. Please report this as a bug.\n\n" + e, moduleType); } } return true; }

Target:
@Override public boolean process(Set<? extends TypeElement> types, RoundEnvironment env) { if (!env.processingOver()) { for (Element e : env.getElementsAnnotatedWith(Module.class)) { if (!(e instanceof TypeElement)) { error("@Module applies to a type, " + e.getSimpleName() + " is a " + e.getKind(), e); continue; } delayedModuleNames.add(((TypeElement) e).getQualifiedName().toString()); } return true; } Set<Element> modules = new LinkedHashSet<Element>(); for (String moduleName : delayedModuleNames) { modules.add(processingEnv.getElementUtils().getTypeElement(moduleName)); } for (Element element : modules) { Map<String, Object> annotation = CodeGen.getAnnotation(Module.class, element); if (!annotation.get("complete").equals(Boolean.TRUE)) { continue; } TypeElement moduleType = (TypeElement) element; Map<String, Binding<?>> bindings = processCompleteModule(moduleType); try { new ProblemDetector().detectProblems(bindings.values()); } catch (IllegalStateException e) { error("Graph validation failed: " + e.getMessage(), moduleType); continue; } try { writeDotFile(moduleType, bindings); } catch (IOException e) { StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); processingEnv.getMessager() .printMessage(Diagnostic.Kind.WARNING, "Graph visualization failed. Please report this as a bug.\n\n" + sw, moduleType); } } return true; }
Source:
private void placeCursorAtActualKey( PageCursor cursor, int pos, Type type ) { int keyPosOffset = keyPosOffset( pos, type ); cursor.setOffset( keyPosOffset ); int keyOffset = readKeyOffset( cursor ); if ( keyOffset > pageSize ) { cursor.setCursorException( "Tried to read key on offset " + keyOffset + ". Page size is " + pageSize ); } cursor.setOffset( keyOffset ); }

Target:
private void placeCursorAtActualKey( PageCursor cursor, int pos, Type type ) { int keyPosOffset = keyPosOffset( pos, type ); cursor.setOffset( keyPosOffset ); int keyOffset = readKeyOffset( cursor ); if ( keyOffset > pageSize || keyOffset < 0 ) { cursor.setCursorException( "Tried to read key on offset " + keyOffset + ". Page size is " + pageSize ); } cursor.setOffset( keyOffset ); }
Source:
protected String retrieveAPISwaggerFromRegistry(API api, String requestURI) throws RegistryException { String resourcePath = api.getSwaggerResourcePath(); if (resourcePath == null) { StringBuilder resourcePathBuilder = new StringBuilder(); resourcePathBuilder.append(SwaggerConstants.DEFAULT_SWAGGER_REGISTRY_PATH).append(api.getAPIName()); if (!(api.getVersionStrategy() instanceof DefaultStrategy)) { resourcePathBuilder.append(":v").append(api.getVersion()); } resourcePathBuilder.append("/swagger.json"); resourcePath = CONFIG_REG_PREFIX + resourcePathBuilder.toString(); } return SwaggerUtils.fetchSwaggerFromRegistry(requestURI, resourcePath); }

Target:
protected String retrieveAPISwaggerFromRegistry(API api, String requestURI) throws RegistryException { String resourcePath = api.getSwaggerResourcePath(); if (resourcePath == null) { StringBuilder resourcePathBuilder = new StringBuilder(); resourcePathBuilder.append(SwaggerConstants.DEFAULT_SWAGGER_REGISTRY_PATH).append(api.getAPIName()); if (!(api.getVersionStrategy() instanceof DefaultStrategy)) { resourcePathBuilder.append(":v").append(api.getVersion()); } resourcePathBuilder.append("/swagger.json"); resourcePath = SwaggerProcessorConstants.CONFIG_REG_PREFIX + resourcePathBuilder.toString(); } return SwaggerUtils.fetchSwaggerFromRegistry(requestURI, resourcePath); }
Source:
public static InputClauseLiteralExpression wbFromDMN(final org.kie.dmn.model.api.LiteralExpression dmn) { if (dmn == null) { return null; } Id id = new Id(dmn.getId()); Description description = DescriptionPropertyConverter.wbFromDMN(dmn.getDescription()); QName typeRef = QNamePropertyConverter.wbFromDMN(dmn.getTypeRef(), dmn); Text text = new Text(dmn.getText()); ImportedValues importedValues = ImportedValuesConverter.wbFromDMN(dmn.getImportedValues()); InputClauseLiteralExpression result = new InputClauseLiteralExpression(id, description, typeRef, text, importedValues); if (importedValues != null) { importedValues.setParent(result); } return result; }

Target:
public static InputClauseLiteralExpression wbFromDMN(final org.kie.dmn.model.api.LiteralExpression dmn) { if (dmn == null) { return null; } final Id id = new Id(dmn.getId()); final Description description = DescriptionPropertyConverter.wbFromDMN(dmn.getDescription()); final QName typeRef = QNamePropertyConverter.wbFromDMN(dmn.getTypeRef(), dmn); final Text text = new Text(dmn.getText()); final ImportedValues importedValues = ImportedValuesConverter.wbFromDMN(dmn.getImportedValues()); final InputClauseLiteralExpression result = new InputClauseLiteralExpression(id, description, typeRef, text, importedValues); if (importedValues != null) { importedValues.setParent(result); } return result; }
Source:
private void testUpdateWhenNearlyOutOfMemory() throws Exception { if (config.memory) { return; } deleteDb("outOfMemory"); String url = getURL("outOfMemory", true); / Child.main(url); try (Connection conn = getConnection("outOfMemory")) { Statement stat = conn.createStatement(); ResultSet rs = stat.executeQuery("SELECT count(*) FROM stuff"); assertTrue(rs.next()); assertEquals(3000, rs.getInt(1)); rs = stat.executeQuery("SELECT * FROM stuff WHERE id = 3000"); assertTrue(rs.next()); String text = rs.getString(2); assertFalse(rs.wasNull()); assertEquals(1004, text.length()); } finally { deleteDb("outOfMemory"); } }

Target:
private void testUpdateWhenNearlyOutOfMemory() throws Exception { if (config.memory) { return; } deleteDb(DB_NAME); ProcessBuilder processBuilder = buildChild( DB_NAME + ";MAX_OPERATION_MEMORY=1000000", MyChild.class, "-XX:+UseParallelGC", "-Xmx128m"); / List<String> args = processBuilder.command(); for (Iterator<String> iter = args.iterator(); iter.hasNext(); ) { String arg = iter.next(); if(arg.equals(MyChild.class.getName())) { iter.remove(); break; } iter.remove(); } MyChild.main(args.toArray(new String[0])); try (Connection conn = getConnection(DB_NAME)) { Statement stat = conn.createStatement(); ResultSet rs = stat.executeQuery("SELECT count(*) FROM stuff"); assertTrue(rs.next()); assertEquals(3000, rs.getInt(1)); rs = stat.executeQuery("SELECT * FROM stuff WHERE id = 3000"); assertTrue(rs.next()); String text = rs.getString(2); assertFalse(rs.wasNull()); assertEquals(1004, text.length()); rs = stat.executeQuery("SELECT sum(length(text)) FROM stuff"); assertTrue(rs.next()); int totalSize = rs.getInt(1); if (3010893 > totalSize) { TestBase.logErrorMessage("Durability failure - expected: 3010893, actual: " + totalSize); } } finally { deleteDb(DB_NAME); } }
Source:
public HostMetrics(TaggedMetricRegistry registry, String serviceName, String hostname) { informational = registry.meter(name(serviceName, hostname, "1xx")); successful = registry.meter(name(serviceName, hostname, "2xx")); redirection = registry.meter(name(serviceName, hostname, "3xx")); clientError = registry.meter(name(serviceName, hostname, "4xx")); serverError = registry.meter(name(serviceName, hostname, "5xx")); other = registry.meter(name(serviceName, hostname, "other")); }

Target:
public HostMetrics(TaggedMetricRegistry registry, String serviceName, String hostname) { informational = registry.meter(name(serviceName, hostname, INFORMATIONAL)); successful = registry.meter(name(serviceName, hostname, SUCCESSFUL)); redirection = registry.meter(name(serviceName, hostname, REDIRECTION)); clientError = registry.meter(name(serviceName, hostname, CLIENT_ERROR)); serverError = registry.meter(name(serviceName, hostname, SERVER_ERROR)); other = registry.meter(name(serviceName, hostname, OTHER)); }
Source:
public void eventsControllerTest() throws Exception { Event event = new Event( "Test", "test", "test", 10, 10, "path/to/files", LocalDateTime.now(), LocalDateTime.now().plusHours(1), "Short description" ); when(eventService.getByKey(event.getKey())).thenReturn(event); mockMvc.perform(get("/sales/stats/event/" + event.getKey())) .andExpect(status().isOk()) .andExpect(view().name("sales/stats/event/index")) .andExpect(model().attributeExists("event", "moneyEarned", "ticketsSold", "orders", "key")); }

Target:
public void eventsControllerTest() throws Exception { Event event = createEvent(); mockMvc.perform(get("/sales/stats/event/" + event.getKey())) .andExpect(status().isOk()) .andExpect(view().name("sales/stats/event/index")) .andExpect(model().attributeExists("event", "moneyEarned", "ticketsSold", "orders")); }
Source:
private void init() { if (jp == null) { try { long timeLeftMillis = timeoutAt - System.currentTimeMillis(); if (hasTimeout && timeLeftMillis < 1) { throw new TimeoutException(); } InputStream is = hasTimeout ? future.get(timeLeftMillis, TimeUnit.MILLISECONDS) : future.get(); if (responseHandler != null && responseHandler.getStatus() != HttpServletResponse.SC_OK) { throw new RE( "Unexpected response status [%s] description [%s] from request url [%s]", responseHandler.getStatus(), responseHandler.getDescription(), url ); } if (is == null) { throw new QueryInterruptedException( new ResourceLimitExceededException( "query[%s] url[%s] timed out or max bytes limit reached.", query != null ? query.getId() : null, url ), host ); } else { jp = objectMapper.getFactory().createParser(is); } final JsonToken nextToken = jp.nextToken(); if (nextToken == JsonToken.START_OBJECT) { QueryInterruptedException cause = jp.getCodec().readValue(jp, QueryInterruptedException.class); throw new QueryInterruptedException(cause, host); } else if (nextToken != JsonToken.START_ARRAY) { throw new IAE("Next token wasn't a START_ARRAY, was[%s] from url [%s]", jp.getCurrentToken(), url); } else { jp.nextToken(); objectCodec = jp.getCodec(); } } catch (TimeoutException ignored) { throw new QueryInterruptedException( new ResourceLimitExceededException( "query[%s] url[%s] timed out.", query != null ? query.getId() : null, url ), host ); } catch (IOException | InterruptedException | ExecutionException e) { throw new RE( e, "Failure getting results for query[%s] url[%s] because of [%s]", query == null ? null : query.getId(), url, e.getMessage() ); } catch (CancellationException e) { throw new QueryInterruptedException(e, host); } } }

Target:
private void init() { if (jp == null) { try { long timeLeftMillis = timeoutAt - System.currentTimeMillis(); if (hasTimeout && timeLeftMillis < 1) { throw new TimeoutException(StringUtils.format("url[%s] timed out", url)); } InputStream is = hasTimeout ? future.get(timeLeftMillis, TimeUnit.MILLISECONDS) : future.get(); if (responseHandler != null && responseHandler.getStatus() != HttpServletResponse.SC_OK) { interruptQuery( new RE( "Unexpected response status [%s] description [%s] from request url[%s]", responseHandler.getStatus(), responseHandler.getDescription(), url ) ); } if (is != null) { jp = objectMapper.getFactory().createParser(is); } else { interruptQuery( new ResourceLimitExceededException( "url[%s] timed out or max bytes limit reached.", url ) ); } final JsonToken nextToken = jp.nextToken(); if (nextToken == JsonToken.START_ARRAY) { jp.nextToken(); objectCodec = jp.getCodec(); } else if (nextToken == JsonToken.START_OBJECT) { interruptQuery(jp.getCodec().readValue(jp, QueryInterruptedException.class)); } else { interruptQuery( new IAE("Next token wasn't a START_ARRAY, was[%s] from url[%s]", jp.getCurrentToken(), url) ); } } catch (IOException | InterruptedException | ExecutionException | CancellationException | TimeoutException e) { interruptQuery(e); } } }