auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void validate() { if (!containsMacro("oracleServerPort") && oracleServerPort < 0) { throw new IllegalArgumentException("Port cannot be negative"); } if (!EnumUtils.isValidEnum(SeparatorFormat.class, format)) { throw new IllegalArgumentException( String.format("Invalid format '%s'. Must be one of %s", format, EnumSet.allOf(SeparatorFormat.class))); } <START> } <END></code><technical_language>want move validation of query add a semi-colon here</technical_language>

Target:
public void validate() { if (!containsMacro("oracleServerPort") && oracleServerSSHPort < 0) { throw new IllegalArgumentException("Port cannot be negative"); } if (!("password".equalsIgnoreCase(oracleServerSSHAuthMechanism) || "private key".equalsIgnoreCase(oracleServerSSHAuthMechanism))) { throw new IllegalArgumentException( String.format("Invalid authentication mechanism '%s'. Must be one of Private Key or Password", oracleServerSSHAuthMechanism)); } if ("password".equalsIgnoreCase(oracleServerSSHAuthMechanism) && Strings.isNullOrEmpty(oracleServerSSHPassword)) { throw new IllegalArgumentException("Password cannot be empty"); } else if ("private key".equalsIgnoreCase(oracleServerSSHAuthMechanism) && Strings.isNullOrEmpty(oracleServerSSHPrivateKey)) { throw new IllegalArgumentException("Private Key cannot be empty"); } try { SeparatorFormat.valueOf(format.toUpperCase()); } catch (IllegalArgumentException e) { throw new IllegalArgumentException( String.format("Invalid format '%s'. Must be one of %s", format, EnumSet.allOf(SeparatorFormat.class))); } String trimmedQuery = queryToExecute.trim(); if (!trimmedQuery.endsWith(";")) { queryToExecute = trimmedQuery + ';'; } }
Source:
<code>protected List<Object> identifyRemoveGarbage(Object locator, K key) { List<Object> garbage = new ArrayList<>(); <START> garbage.addAll(locatorStore.addUnsafe(key, (SMRRecordLocator) locator)); <END> return garbage; }</code><technical_language>here, List<Object> garbage = new ArrayList<>(locatorStore.addUnsafe(key, (SMRRecordLocator) locator));</technical_language>

Target:
protected List<Object> identifyRemoveGarbage(Object locator, K key) { return new ArrayList<>(locatorStore.addUnsafe(key, (SMRRecordLocator) locator)); }
Source:
<code>public static Frequency ofMonths(int months) { switch (months) { case 1: return P1M; case 2: return P2M; case 3: return P3M; case 4: return P4M; case 6: return P6M; case 12: return P12M; default: if (months > MAX_MONTHS) { <START> throw new IllegalArgumentException("Months must not exceed 12,000"); <END> } return new Frequency(Period.ofMonths(months)); } }</code><technical_language>of MAX_MONTHS in error message hard-coding 12,000</technical_language>

Target:
public static Frequency ofMonths(int months) { switch (months) { case 1: return P1M; case 2: return P2M; case 3: return P3M; case 4: return P4M; case 6: return P6M; case 12: return P12M; default: if (months > MAX_MONTHS) { throw new IllegalArgumentException(maxMonthMsg()); } return new Frequency(Period.ofMonths(months)); } }
Source:
<code>public Term parse(NonTerminal nt, int position) { NonTerminal startNt = new NonTerminal(new NonTerminalId("<start>"), new StateId("<start-entry>"), new State.OrderingInfo(Integer.MIN_VALUE), new StateId("<start-exit>"), new State.OrderingInfo(Integer.MAX_VALUE)); <START> State state = new NonTerminalState(new StateId("<start>"), startNt, new State.OrderingInfo(Integer.MAX_VALUE - 1), nt, true, null); <END> activateNtCall(s.getStateCall(new StateCall.Key(s.getNtCall(new NonTerminalCall.Key(nt, position)), position, state))); while (s.stateReturnWorkLists.top() != null) { StateReturn stateReturn = null; while ((stateReturn = s.stateReturnWorkLists.top().dequeue()) != null) { this.stateReturn(stateReturn); } s.stateReturnWorkLists.pop(); } Ambiguity result = new Ambiguity("K", new ArrayList<Term>()); for(StateReturn stateReturn : s.getNtCall(new NonTerminalCall.Key(nt,0)).exitStateReturns) { if (stateReturn.key.stateEnd == s.input.length()) { for (KList klist : stateReturn.postRuleFunction.applyToNull()) { result.getContents().add(klist); } } } return result; }</code><technical_language>this</technical_language>

Target:
public Term parse(NonTerminal nt, int position) { NonTerminal startNt = new NonTerminal(new NonTerminalId("<start>"), new StateId("<start-entry>"), new State.OrderingInfo(Integer.MIN_VALUE), new StateId("<start-exit>"), new State.OrderingInfo(Integer.MAX_VALUE)); State state = new NonTerminalState(new StateId("<start>"), startNt, new State.OrderingInfo(Integer.MAX_VALUE - 1), nt, true, null); activateNtCall(s.getStateCall(new StateCall.Key(s.getNtCall(new NonTerminalCall.Key(nt, position)), position, state))); while (s.stateReturnWorkLists.top() != null) { StateReturn stateReturn = null; while ((stateReturn = s.stateReturnWorkLists.top().dequeue()) != null) { this.stateReturn(stateReturn); } s.stateReturnWorkLists.pop(); } Ambiguity result = new Ambiguity(KSorts.K, new ArrayList<Term>()); for(StateReturn stateReturn : s.getNtCall(new NonTerminalCall.Key(nt,0)).exitStateReturns) { if (stateReturn.key.stateEnd == s.input.length()) { for (KList klist : stateReturn.postRuleFunction.applyToNull()) { result.getContents().add(klist); } } } return result; }
Source:
<code>synchronized Pattern sourceTopicPattern() { if (topicPattern == null) { final List<String> allSourceTopics = new ArrayList<>(); if (!nodeToSourceTopics.isEmpty()) { for (final List<String> topics : nodeToSourceTopics.values()) { <START> final List<String> filteredTopics = filterAndRemoveGlobalSourceTopics(topics); <END> allSourceTopics.addAll(maybeDecorateInternalSourceTopics(filteredTopics)); } } Collections.sort(allSourceTopics); topicPattern = buildPatternForOffsetResetTopics(allSourceTopics, nodeToSourcePatterns.values()); } return topicPattern; }</code><technical_language>calling allSourceTopics.removeAll(globalTopics); ? Also, do this for-loop</technical_language>

Target:
synchronized Pattern sourceTopicPattern() { if (topicPattern == null) { final List<String> allSourceTopics = new ArrayList<>(); if (!nodeToSourceTopics.isEmpty()) { for (final List<String> topics : nodeToSourceTopics.values()) { allSourceTopics.addAll(maybeDecorateInternalSourceTopics(topics)); } allSourceTopics.removeAll(globalTopics); } Collections.sort(allSourceTopics); topicPattern = buildPatternForOffsetResetTopics(allSourceTopics, nodeToSourcePatterns.values()); } return topicPattern; }
Source:
<code>public void sendNext(T element) { if (subscriber.isDefined()) subscriber.get().onNext(element); <START> else env.flop("Cannot sendNext before subscriber subscription"); <END> }</code><technical_language>slightly confusing wording, "Cannot sendNext a Subscriber" (also in following)</technical_language>

Target:
public void sendNext(T element) { if (subscriber.isCompleted()) { subscriber.value().onNext(element); } else { env.flop("Cannot sendNext before having a Subscriber"); } }
Source:
<code><START> public AbstractTreeElement getAttribute(String namespace, String name) { <END> return this.getAttribute(null, namespace, name); }</code><technical_language>this change necessary? downstream method returns a treeelement anyway</technical_language>

Target:
public TreeElement getAttribute(String namespace, String name) { return this.getAttribute(null, namespace, name); }
Source:
<code><START> private void selectCreatedDLines(ResourceSetChangeEvent event) { <END> if (EclipseUIUtil.getActiveEditor() == abstractDTableEditor) { final List<DLine> createdDLines = getCreatedDLines(event); if (!createdDLines.isEmpty()) { final Viewer viewer = abstractDTableEditor.getViewer(); if (viewer != null) { Display.getDefault().asyncExec(new Runnable() { @Override public void run() { viewer.setSelection(new StructuredSelection(createdDLines.toArray())); } }); } } } }</code><technical_language>This call DialectUIService.setSelection(); org.eclipse.sirius.table.ui.business.internal.dialect.TableDialectUIServices.setSelection(DialectEditor, List<DRepresentationElement>) do same</technical_language>

Target:
private void selectCreatedDLines(ResourceSetChangeEvent event) { if (EclipseUIUtil.getActiveEditor() == abstractDTableEditor) { final List<DLine> createdDLines = getCreatedDLines(event); if (!createdDLines.isEmpty()) { Viewer viewer = abstractDTableEditor.getViewer(); if (viewer != null) { Display.getDefault().asyncExec(new ChangeViewerSelectionRunnable(viewer, new StructuredSelection(createdDLines.toArray()), true)); } } } }
Source:
<code>protected void doTask() { final Set<Long> recordIDs = options.records.size() > 0 ? options.records : concourse.inventory(); Path path = createFile(); <START> final Iterable<Map<String, Object>> records = (options.criteria != null <END> ? concourse.get(options.criteria).entrySet().stream() .filter(r -> recordIDs.contains(r.getKey())) .map(Map.Entry::getValue) : concourse.describe(recordIDs).entrySet().stream() .map(e -> concourse.get(e.getValue(), e.getKey())) ).collect(Collectors.toList()); try { output(records, Files.newOutputStream(path)); } catch (IOException exception) { throw new RuntimeException( "Failed to create a stream for the file."); } }</code><technical_language>do concourse.select(records) concourse.select(ccl) instead of key/values</technical_language>

Target:
protected void doTask() { final Exporter exporter = new Exporter(concourse, !opts.hidePrimaryKey); String result; if(opts.criteria != null && opts.records.size() > 0) { result = exporter.perform(opts.records, opts.criteria); } else if(opts.criteria != null) { result = exporter.perform(opts.criteria); } else if(opts.records.size() > 0) { result = exporter.perform(opts.records); } else { result = exporter.perform(); } final OutputStream outputStream = getOutputStream(); final PrintStream printStream = new PrintStream(outputStream); printStream.println(result); }
Source:
<code>private void checkParamTagsOrder(final List<JavadocTag> tags, final List<DetailAST> allParams, final List<DetailAST> allTypeParams) { int paramPosition = 0; final int noOfTypeParams = allTypeParams.size(); for (JavadocTag tag : tags) { if (!tag.isParamTag()) { continue; } final String arg1 = tag.getFirstArg(); int actualPosition = indexOfParam(allParams, arg1) + noOfTypeParams; final boolean isTypeParam = CommonUtil.startsWithChar(arg1, '<') <START> && CommonUtil.endsWithChar(arg1, '>'); <END> if (isTypeParam) { actualPosition = indexOfTypeParameter(allTypeParams, arg1.substring(1, arg1.length() - 1)); } if (validateParameterOrder && actualPosition != paramPosition) { log(tag.getLineNo(), tag.getColumnNo(), MSG_INCORRECT_TAG_ORDER, PARAM_TAG, arg1); } paramPosition++; } }</code><technical_language>I clearer number instead of no</technical_language>

Target:
private void checkParamTagsOrder(final List<JavadocTag> tags, final List<DetailAST> allParams, final List<DetailAST> allTypeParams) { int paramPosition = 0; int actualPosition; final int noOfTypeParams = allTypeParams.size(); for (JavadocTag tag : tags) { if (!tag.isParamTag()) { continue; } final String arg1 = tag.getFirstArg(); if (CommonUtil.startsWithChar(arg1, '<') && CommonUtil.endsWithChar(arg1, '>')) { actualPosition = indexOfTypeParameter(allTypeParams, arg1.substring(1, arg1.length() - 1)); } else { actualPosition = indexOfParam(allParams, arg1) + noOfTypeParams; } if (!allowMissingParamTags && validateParameterOrder && actualPosition != paramPosition) { log(tag.getLineNo(), tag.getColumnNo(), MSG_INCORRECT_TAG_ORDER, PARAM_TAG, arg1); } paramPosition++; } }
Source:
<code>public Application remind(Application application) throws RemindAlreadySentException, ImpatientAboutApplicationForLeaveProcessException { LocalDate remindDate = application.getRemindDate(); if (remindDate == null) { LocalDate minDateForNotification = application.getApplicationDate() .plusDays(MIN_DAYS_LEFT_BEFORE_REMINDING_IS_POSSIBLE); <START> if (minDateForNotification.isAfter(ZonedDateTime.now(UTC).toLocalDate())) { <END> throw new ImpatientAboutApplicationForLeaveProcessException("It's too early to remind the bosses!"); } } if (remindDate != null && remindDate.isEqual(ZonedDateTime.now(UTC).toLocalDate())) { throw new RemindAlreadySentException("Reminding is possible maximum one time per day!"); } mailService.sendRemindBossNotification(application); application.setRemindDate(ZonedDateTime.now(UTC).toLocalDate()); applicationService.save(application); return application; }</code><technical_language>LocalDate.now(UTC)</technical_language>

Target:
public Application remind(Application application) throws RemindAlreadySentException, ImpatientAboutApplicationForLeaveProcessException { LocalDate remindDate = application.getRemindDate(); if (remindDate == null) { LocalDate minDateForNotification = application.getApplicationDate() .plusDays(MIN_DAYS_LEFT_BEFORE_REMINDING_IS_POSSIBLE); if (minDateForNotification.isAfter(LocalDate.now(UTC))) { throw new ImpatientAboutApplicationForLeaveProcessException("It's too early to remind the bosses!"); } } if (remindDate != null && remindDate.isEqual(LocalDate.now(UTC))) { throw new RemindAlreadySentException("Reminding is possible maximum one time per day!"); } mailService.sendRemindBossNotification(application); application.setRemindDate(LocalDate.now(UTC)); applicationService.save(application); return application; }
Source:
<code>public String getGID(URL url) throws MalformedURLException { Pattern p = Pattern.compile("^https?://myrule34.com/index.php/([a-zA-Z0-9-]*)$"); Matcher m = p.matcher(url.toExternalForm()); if (m.matches()) { return m.group(1); } <START> throw new MalformedURLException("Expected imgur.com URL format: " + <END> "myrule34.com/index.php/albumName - got " + url + " instead"); }</code><technical_language>Replace imgur.com</technical_language>

Target:
public String getGID(URL url) throws MalformedURLException { Pattern p = Pattern.compile("^https?://myrule34.com/index.php/([a-zA-Z0-9-]*)$"); Matcher m = p.matcher(url.toExternalForm()); if (m.matches()) { return m.group(1); } throw new MalformedURLException("Expected myrule34.com URL format: " + "myrule34.com/index.php/albumName - got " + url + " instead"); }
Source:
<code>private void applyValues(Address address, List<Object> keys, Response response) { if (response == null) { throw new CacheException("Did not get response from " + address); } else if (!response.isSuccessful()) { throw new CacheException("Response from " + address + " is unsuccessful: " + response); } InternalCacheValue[] values = (InternalCacheValue[]) ((SuccessfulResponse) response).getResponseValue(); if (values == null) { throw new IllegalStateException(); } for (int i = 0; i < keys.size(); ++i) { <START> Object key = keys.get(i); <END> InternalCacheValue icv = values[i]; if (icv == null) { continue; } PutKeyValueCommand put = commandsFactory.buildPutKeyValueCommand(key, icv.getValue(), icv.getMetadata(), STATE_TRANSFER_FLAGS); try { interceptorChain.invoke(icf.createSingleKeyNonTxInvocationContext(), put); } catch (Exception e) { if (!cache.getStatus().allowInvocations()) { log.debugf("Cache %s is shutting down, stopping state transfer", cacheName); break; } else { log.problemApplyingStateForKey(e.getMessage(), key, e); } } } }</code><technical_language>get exception if cache is stopped</technical_language>

Target:
private void applyValues(Address address, List<Object> keys, Response response) { if (response == null) { throw new CacheException("Did not get response from " + address); } else if (!response.isSuccessful()) { throw new CacheException("Response from " + address + " is unsuccessful: " + response); } InternalCacheValue[] values = (InternalCacheValue[]) ((SuccessfulResponse) response).getResponseValue(); if (values == null) { throw new IllegalStateException(); } for (int i = 0; i < keys.size(); ++i) { Object key = keys.get(i); InternalCacheValue icv = values[i]; if (icv == null) { continue; } PutKeyValueCommand put = commandsFactory.buildPutKeyValueCommand(key, icv.getValue(), keyPartitioner.getSegment(key), icv.getMetadata(), STATE_TRANSFER_FLAGS); try { interceptorChain.invoke(icf.createSingleKeyNonTxInvocationContext(), put); } catch (Exception e) { if (!cache.getStatus().allowInvocations()) { log.debugf("Cache %s is shutting down, stopping state transfer", cacheName); break; } else { log.problemApplyingStateForKey(e.getMessage(), key, e); } } } }
Source:
<code>public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) { if (parameterContext.getParameter().getType() == SoftAssertions.class) { return getStore(extensionContext).getOrComputeIfAbsent(SoftAssertions.class); } <START> return getStore(extensionContext).getOrComputeIfAbsent(BDDSoftAssertions.class); <END> }</code><technical_language>Done in latest commit: 21f5677</technical_language>

Target:
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) { return getStore(extensionContext).getOrComputeIfAbsent(parameterContext.getParameter().getType()); }
Source:
<code>public void testEquals() throws Exception { <START> assertTrue( <END> new Coordinate(1,"foo", "bar", "baz").equals(new Coordinate(1, "foo", "bar", "baz")) ); }</code><technical_language>exists assertEquals()</technical_language>

Target:
public void testEquals() throws Exception { assertEquals( new Coordinate(1,"foo", "bar", "baz"), new Coordinate(1, "foo", "bar", "baz") ); }
Source:
<code>public void updateFromItem(final LocalItem localItem, HistoryRecordManager historyRecordManager, final DateFormat dateFormat) { if (!(localItem instanceof PlaylistRemoteEntity)) return; final PlaylistRemoteEntity item = (PlaylistRemoteEntity) localItem; itemTitleView.setText(item.getName()); itemStreamCountView.setText(String.valueOf(item.getStreamCount())); itemUploaderView.setText(Localization.concatenateStrings(item.getUploader(), NewPipe.getNameOfService(item.getServiceId()))); <START> if (item.getUploader() == null) { <END> itemUploaderView.setText(NewPipe.getNameOfService(item.getServiceId())); } itemBuilder.displayImage(item.getThumbnailUrl(), itemThumbnailView, ImageDisplayConstants.DISPLAY_PLAYLIST_OPTIONS); super.updateFromItem(localItem, historyRecordManager, dateFormat); }</code><technical_language>suggestion if (item.getUploader() != null) { itemUploaderView.setText(Localization.concatenateStrings(item.getUploader(), NewPipe.getNameOfService(item.getServiceId()))); } else {</technical_language>

Target:
public void updateFromItem(final LocalItem localItem, HistoryRecordManager historyRecordManager, final DateFormat dateFormat) { if (!(localItem instanceof PlaylistRemoteEntity)) return; final PlaylistRemoteEntity item = (PlaylistRemoteEntity) localItem; itemTitleView.setText(item.getName()); itemStreamCountView.setText(String.valueOf(item.getStreamCount())); if (!TextUtils.isEmpty(item.getUploader())) { itemUploaderView.setText(Localization.concatenateStrings(item.getUploader(), NewPipe.getNameOfService(item.getServiceId()))); } else { itemUploaderView.setText(NewPipe.getNameOfService(item.getServiceId())); } itemBuilder.displayImage(item.getThumbnailUrl(), itemThumbnailView, ImageDisplayConstants.DISPLAY_PLAYLIST_OPTIONS); super.updateFromItem(localItem, historyRecordManager, dateFormat); }
Source:
<code>public void userRefresh() throws URISyntaxException, JSONException { Token t = SyncTestUtils.createTestUser().getSyncUser().getUserToken(); <START> AuthenticateRequest request = AuthenticateRequest.userRefresh(t, new URI("realm://objectserver/" + t.value() + "/default")); <END> JSONObject obj = new JSONObject(request.toJson()); assertTrue(obj.has("path")); assertEquals(t.value(), obj.get("data")); assertEquals("realm", obj.get("provider")); }</code><technical_language>I thought identity here</technical_language>

Target:
public void userRefresh() throws URISyntaxException, JSONException { Token t = SyncTestUtils.createTestUser().getSyncUser().getUserToken(); AuthenticateRequest request = AuthenticateRequest.userRefresh(t, new URI("realm://objectserver/" + t.identity() + "/default")); JSONObject obj = new JSONObject(request.toJson()); assertTrue(obj.has("path")); assertEquals(t.value(), obj.get("data")); assertEquals("realm", obj.get("provider")); }
Source:
<code>private void initVmTemplate() { OvfHelper ovfHelper = new OvfHelper(); ovfEntityData = getUnregisteredOVFDataDao().getByEntityIdAndStorageDomain(getParameters().getContainerId(), getParameters().getStorageDomainId()); if (ovfEntityData != null) { try { vmTemplateFromConfiguration = ovfHelper.readVmTemplateFromOvf(ovfEntityData.getOvfData()); vmTemplateFromConfiguration.setVdsGroupId(getParameters().getVdsGroupId()); setVmTemplate(vmTemplateFromConfiguration); getParameters().setVmTemplate(vmTemplateFromConfiguration); getParameters().setDestDomainId(ovfEntityData.getStorageDomainId()); getParameters().setSourceDomainId(ovfEntityData.getStorageDomainId()); if (getParameters().getDiskTemplateMap() != null) { ArrayList imageList = new ArrayList<>(getParameters().getDiskTemplateMap().values()); vmTemplateFromConfiguration.setDiskList(imageList); ensureDomainMap(imageList, getParameters().getDestDomainId()); } } catch (OvfReaderException e) { <START> log.error("failed to parse a given ovf configuration: \n{}", ovfEntityData.getOvfData()); <END> log.error("Exception", e); } } setVdsGroupId(getParameters().getVdsGroupId()); setStoragePoolId(getVdsGroup().getStoragePoolId()); }</code><technical_language>space \n</technical_language>

Target:
private void initVmTemplate() { OvfHelper ovfHelper = new OvfHelper(); ovfEntityData = getUnregisteredOVFDataDao().getByEntityIdAndStorageDomain(getParameters().getContainerId(), getParameters().getStorageDomainId()); if (ovfEntityData != null) { try { vmTemplateFromConfiguration = ovfHelper.readVmTemplateFromOvf(ovfEntityData.getOvfData()); vmTemplateFromConfiguration.setVdsGroupId(getParameters().getVdsGroupId()); setVmTemplate(vmTemplateFromConfiguration); getParameters().setVmTemplate(vmTemplateFromConfiguration); getParameters().setDestDomainId(ovfEntityData.getStorageDomainId()); getParameters().setSourceDomainId(ovfEntityData.getStorageDomainId()); if (getParameters().getDiskTemplateMap() != null) { ArrayList imageList = new ArrayList<>(getParameters().getDiskTemplateMap().values()); vmTemplateFromConfiguration.setDiskList(imageList); ensureDomainMap(imageList, getParameters().getDestDomainId()); } } catch (OvfReaderException e) { log.error("Failed to parse a given ovf configuration:\n{}", ovfEntityData.getOvfData()); log.error("Exception", e); } } setVdsGroupId(getParameters().getVdsGroupId()); setStoragePoolId(getVdsGroup().getStoragePoolId()); }
Source:
<code>private void checkBonusPoolQuantities(Map<String, PoolQuantity> poolQuantities, Map<String, Entitlement> entitlements) { Set<String> excludePoolIds = new HashSet<String>(); Map<String, Entitlement> subEntitlementMap = new HashMap<String, Entitlement>(); for (Entry<String, PoolQuantity> entry : poolQuantities.entrySet()) { Pool pool = entry.getValue().getPool(); subEntitlementMap.put(pool.getSubscriptionId(), entitlements.get(entry.getKey())); excludePoolIds.add(pool.getId()); } List<Pool> overConsumedPools = poolCurator.lookupOversubscribedBySubscriptionIds(subEntitlementMap); List<Pool> derivedPools = new ArrayList<Pool>(); for (Pool pool : overConsumedPools) { if (!excludePoolIds.contains(pool.getId()) && pool.getQuantity() != -1) <START> { <END> derivedPools.add(pool); } } deleteExcessEntitlements(derivedPools); }</code><technical_language>Incorrect brace position</technical_language>

Target:
private void checkBonusPoolQuantities(Map<String, PoolQuantity> poolQuantities, Map<String, Entitlement> entitlements) { Set<String> excludePoolIds = new HashSet<String>(); Map<String, Entitlement> subEntitlementMap = new HashMap<String, Entitlement>(); for (Entry<String, PoolQuantity> entry : poolQuantities.entrySet()) { Pool pool = entry.getValue().getPool(); subEntitlementMap.put(pool.getSubscriptionId(), entitlements.get(entry.getKey())); excludePoolIds.add(pool.getId()); } List<Pool> overConsumedPools = poolCurator.lookupOversubscribedBySubscriptionIds(subEntitlementMap); List<Pool> derivedPools = new ArrayList<Pool>(); for (Pool pool : overConsumedPools) { if (pool.getQuantity() != -1 && !excludePoolIds.contains(pool.getId())) { derivedPools.add(pool); } } deleteExcessEntitlements(derivedPools); }
Source:
<code>public void onMessage(Message message) { try { if (message != null) { if (log.isDebugEnabled()) { log.debug("Event received in JMS Event Receiver - " + message); } Topic jmsDestination = (Topic) message.getJMSDestination(); if (message instanceof MapMessage) { MapMessage mapMessage = (MapMessage) message; Map<String, Object> map = new HashMap<String, Object>(); Enumeration enumeration = mapMessage.getMapNames(); while (enumeration.hasMoreElements()) { String key = (String) enumeration.nextElement(); map.put(key, mapMessage.getObject(key)); } if (APIConstants.TopicNames.TOPIC_NOTIFICATION.equalsIgnoreCase(jmsDestination.getTopicName())) { if (map.get(APIConstants.EVENT_TYPE) != null) { if (debugEnabled) { log.debug("Event received from the topic of " + jmsDestination.getTopicName()); } handleNotificationMessage((String) map.get(APIConstants.EVENT_TYPE), (Long) map.get(APIConstants.EVENT_TIMESTAMP), (String) map.get(APIConstants.EVENT_PAYLOAD)); } } } else { log.warn("Event dropped due to unsupported message type " + message.getClass()); } } else { log.warn("Dropping the empty/null event received through jms receiver"); } <START> } catch (JMSException | ArtifactSynchronizerException e) { <END> log.error("JMSException occurred when processing the received message ", e); } }</code><technical_language>handle this before? in handleNotificationMessage method</technical_language>

Target:
public void onMessage(Message message) { try { if (message != null) { if (log.isDebugEnabled()) { log.debug("Event received in JMS Event Receiver - " + message); } Topic jmsDestination = (Topic) message.getJMSDestination(); if (message instanceof MapMessage) { MapMessage mapMessage = (MapMessage) message; Map<String, Object> map = new HashMap<String, Object>(); Enumeration enumeration = mapMessage.getMapNames(); while (enumeration.hasMoreElements()) { String key = (String) enumeration.nextElement(); map.put(key, mapMessage.getObject(key)); } if (APIConstants.TopicNames.TOPIC_NOTIFICATION.equalsIgnoreCase(jmsDestination.getTopicName())) { if (map.get(APIConstants.EVENT_TYPE) != null) { if (debugEnabled) { log.debug("Event received from the topic of " + jmsDestination.getTopicName()); } handleNotificationMessage((String) map.get(APIConstants.EVENT_TYPE), (Long) map.get(APIConstants.EVENT_TIMESTAMP), (String) map.get(APIConstants.EVENT_PAYLOAD)); } } } else { log.warn("Event dropped due to unsupported message type " + message.getClass()); } } else { log.warn("Dropping the empty/null event received through jms receiver"); } } catch (JMSException e) { log.error("JMSException occurred when processing the received message ", e); } }
Source:
<code>private static String key() { <START> return "key-" + ThreadLocalRandom.current().nextLong(recordCount); <END> }</code><technical_language>prefix this 00s</technical_language>

Target:
private static String key() { return "key-" + String.format("%19d", ThreadLocalRandom.current().nextLong(recordCount)); }
Source:
<code>private CategoryProviderFactory() { IExtensionPoint point = Platform.getExtensionRegistry().getExtensionPoint(POINT_ID); for (IConfigurationElement element : point.getConfigurationElements()) { String name = element.getAttribute("name"); String uri = element.getAttribute("uri"); Class<? extends ICategoryFilter> categoryFilterClass = getCategoryFilterClass(element); Class<? extends IPropertySetViewer> propertySetViewerClass = getPropertySetViewerClass(element); <START> knownDescriptors.add(new CategoryDescriptor(name, uri, categoryFilterClass, propertySetViewerClass)); <END> } }</code><technical_language>Is name url is required? If of null/empty check if of attribute is set/correct log if not. in case of broken extension properties view crashing</technical_language>

Target:
private CategoryProviderFactory() { IExtensionPoint point = Platform.getExtensionRegistry().getExtensionPoint(POINT_ID); for (IConfigurationElement element : point.getConfigurationElements()) { String name = element.getAttribute("name"); if(name == null){ WebUiPlugin.getDefault().logError("Attribute \"name\" should be defined in extension point " + element.getNamespaceIdentifier()); } String uri = element.getAttribute("uri"); if(uri == null){ WebUiPlugin.getDefault().logError("Attribute \"uri\" should be defined in extension point " + element.getNamespaceIdentifier()); } Class<? extends IPropertySetViewer> propertySetViewerClass = getPropertySetViewerClass(element); if(propertySetViewerClass == null){ WebUiPlugin.getDefault().logError("Attribute \"property-set-viewer-class\" should be defined in extension point " + element.getNamespaceIdentifier()); } Class<? extends ICategoryFilter> categoryFilterClass = getCategoryFilterClass(element); if(name != null && uri != null && propertySetViewerClass != null){ knownDescriptors.add(new CategoryDescriptor(name, uri, categoryFilterClass, propertySetViewerClass)); } } }
Source:
<code>private Path getWorkingDir(String workingDir){ if(workingDir!= null){ return Paths.get("file://"+workingDir); } <START> else{ <END> return null; } }</code><technical_language>please remove else, code more readable; follow KIE code style</technical_language>

Target:
private Path getWorkingDir(String workingDir){ if(workingDir!= null){ return Paths.get("file://"+workingDir); } return null; }
Source:
<code>public void schedule(ServiceExecution serviceExecution) throws ServiceExecutionSchedulerException { if (serviceExecution == null) throw new ServiceExecutionSchedulerException("Could not schedule service execution: ServiceExecution is null"); <START> if (serviceExecution.getService() == null) <END> throw new ServiceExecutionSchedulerException("Could not schedule service execution: No IService defined in ServiceExecution"); if (serviceExecution.getTrigger() == null) throw new ServiceExecutionSchedulerException("Could not schedule service execution: No Trigger defined in ServiceExecution"); log.debug("Scheduling new Service Execution for service [" + serviceExecution.getService().getClass().getName() + "]"); try { JobDetail jobDetail = new JobDetailBuilder().withExecutionService(executionService).withServiceExecution(serviceExecution) .withServiceExecutionCallback(serviceExecutionCallback).build(); Trigger trigger = new TriggerBuilder().usingTrigger(serviceExecution.getTrigger()).build(); quartzScheduler.scheduleJob(jobDetail, trigger); scheduledJobs.put(serviceExecution, jobDetail.getKey()); } catch (SchedulerException e) { log.error("Could not schedule service execution: ", e); throw new ServiceExecutionSchedulerException(e); } log.info("Service Execution scheduled for service [" + serviceExecution.getService().getClass().getName() + "]"); }</code><technical_language>Move checks of ServiceExecution constructor throw InvalidArgumentException</technical_language>

Target:
public void schedule(ServiceExecution serviceExecution) throws ServiceExecutionSchedulerException { if (serviceExecution == null) throw new IllegalArgumentException("Could not schedule service execution: ServiceExecution is null"); log.debug("Scheduling new Service Execution for service [" + serviceExecution.getService().getClass().getName() + "]"); try { JobDetail jobDetail = new JobDetailBuilder().withExecutionService(executionService).withServiceExecution(serviceExecution) .withServiceExecutionCallback(serviceExecutionCallback).build(); Trigger trigger = new TriggerBuilder().usingTrigger(serviceExecution.getTrigger()).build(); quartzScheduler.scheduleJob(jobDetail, trigger); scheduledJobs.put(serviceExecution, jobDetail.getKey()); } catch (SchedulerException e) { log.error("Could not schedule service execution: ", e); throw new ServiceExecutionSchedulerException(e); } log.info("Service Execution scheduled for service [" + serviceExecution.getService().getClass().getName() + "]"); }
Source:
<code>public IVdsAsyncCommand RemoveAsyncRunningCommand(Guid vmId) { <START> IVdsAsyncCommand command = null; <END> if (_asyncRunningCommands.containsKey(vmId)) { command = _asyncRunningCommands.remove(vmId); } return command; }</code><technical_language>for of contains</technical_language>

Target:
public IVdsAsyncCommand RemoveAsyncRunningCommand(Guid vmId) { return _asyncRunningCommands.remove(vmId); }
Source:
<code>private static void assertAllParentShardsAreClosed(Set<String> inconsistentShardIds) throws KinesisClientLibIOException { if (!inconsistentShardIds.isEmpty()) { String ids = ""; for (String id : inconsistentShardIds) { ids += " " + id; } <START> throw new KinesisClientLibIOException(String.valueOf(inconsistentShardIds.size()) + " open child shards (" + ids + ") are inconsistent." <END> + "This can happen due to a race condition between describeStream and a reshard operation."); } }</code><technical_language>This cleaner String.format</technical_language>

Target:
private static void assertAllParentShardsAreClosed(Set<String> inconsistentShardIds) throws KinesisClientLibIOException { if (!inconsistentShardIds.isEmpty()) { String ids = StringUtils.join(inconsistentShardIds, ' '); throw new KinesisClientLibIOException(String.format("%d open child shards (%s) are inconsistent. " + "This can happen due to a race condition between describeStream and a reshard operation.", inconsistentShardIds.size(), ids)); } }
Source:
<code>public void tryEnableCancelPolicyShouldInvokeMethodOnExecutor() { ScheduledThreadPoolExecutor executor = spy(new ScheduledThreadPoolExecutor(1)); boolean result = NewThreadWorker.tryEnableCancelPolicy(executor); assertTrue(result); <START> verify(executor).setRemoveOnCancelPolicy(true); <END> verifyNoMoreInteractions(executor); }</code><technical_language>This fail a Java 6 build if people build RxJava source Java 6. I do is subclass ScheduledThreadPoolExecutor add setRemoveOnCancelPolicy(boolean) method. For Java 7+, this count a simple override</technical_language>

Target:
public void tryEnableCancelPolicyShouldInvokeMethodOnExecutor() { ScheduledExecutorServiceWithSetRemoveOnCancelPolicy executor = mock(ScheduledExecutorServiceWithSetRemoveOnCancelPolicy.class); boolean result = NewThreadWorker.tryEnableCancelPolicy(executor); assertTrue(result); verify(executor).setRemoveOnCancelPolicy(true); verifyNoMoreInteractions(executor); }
Source:
<code>public FontManager getFontManager() { <START> return this.getFontManager(); <END> }</code><technical_language>Erm, add a recursive call</technical_language>

Target:
public FontManager getFontManager() { return this.mEngine.getFontManager(); }
Source:
<code>protected Object process(Object inputData) { long detectedObjectCount; if (inputData instanceof Object[]) { Object[] arguments = (Object[]) inputData; if (arguments.length == 2) { if (arguments[0] instanceof String && arguments[1] instanceof String) { String imageHex = (String) arguments[0]; String cascadeFilePath = (String) arguments[1]; detectedObjectCount = this.detectObjects(imageHex, cascadeFilePath); } else { throw new IllegalArgumentException( "2 String arguments of the hex string of the image and the cascade " + "path is expected."); } } else { throw new IllegalArgumentException( "2 String arguments of the hex string of the image and the cascade path " + "is expected."); } } else { throw new IllegalArgumentException( "2 String arguments of the hex string of the image and the cascade path is " + "expected."); <START> } <END> return detectedObjectCount; }</code><technical_language>Pass context (inputs ) in exceptions</technical_language>

Target:
protected Object process(Object inputData) { long detectedObjectCount; if (inputData instanceof Object[]) { Object[] arguments = (Object[]) inputData; if (arguments.length == 2) { if (arguments[0] instanceof String && arguments[1] instanceof String) { String imageHex = (String) arguments[0]; String cascadeFilePath = (String) arguments[1]; detectedObjectCount = this.detectObjects(imageHex, cascadeFilePath); } else { throw new IllegalArgumentException( "2 String arguments of the hex string of the image and the cascade " + "path is expected. The received arguments are not String objects."); } } else { throw new IllegalArgumentException( "2 String arguments of the hex string of the image and the cascade path " + "is expected. Did not receive 2 arguments."); } } else { throw new IllegalArgumentException( "2 String arguments of the hex string of the image and the cascade path is " + "expected. But received a non-object array."); } return detectedObjectCount; }
Source:
<code>public OMElement serialize(OMElement parent) { OMElement endpoint = fac.createOMElement("endpoint", synNS); if (name != null && !"".equals(name)) { endpoint.addAttribute(fac.createOMAttribute( "name", nullNS, getName())); } OMElement loadbalance = fac.createOMElement("loadbalance", synNS); loadbalance.addAttribute(fac.createOMAttribute("algorithm", nullNS, algorithmClassName)); if (isBuildMessage()) { <START> loadbalance.addAttribute(fac.createOMAttribute("buildMessage", nullNS, Boolean.toString(true))); <END> } if (sessionType != null) { OMElement session = fac.createOMElement("session", synNS); session.addAttribute(fac.createOMAttribute( "type", nullNS, sessionType)); OMElement sessionTimeout = fac.createOMElement("sessionTimeout", synNS); sessionTimeout.setText(String.valueOf(getSessionTimeout())); session.addChild(sessionTimeout); endpoint.addChild(session); } if (properties != null && properties.length() != 0) { String[] props = properties.split("::"); for (String s : props) { String[] elements = s.split(","); OMElement property = fac.createOMElement("property", synNS); property.addAttribute(fac.createOMAttribute("name", nullNS, elements[0])); property.addAttribute(fac.createOMAttribute("value", nullNS, elements[1])); property.addAttribute(fac.createOMAttribute("scope", nullNS, elements[2])); endpoint.addChild(property); } } endpoint.addChild(loadbalance); serializeChildren(loadbalance, getList()); if (parent != null) { parent.addChild(endpoint); } return endpoint; }</code><technical_language>define "buildMessage" a constant ? explain hardcode</technical_language>

Target:
public OMElement serialize(OMElement parent) { OMElement endpoint = fac.createOMElement("endpoint", synNS); if (name != null && !"".equals(name)) { endpoint.addAttribute(fac.createOMAttribute( "name", nullNS, getName())); } OMElement loadbalance = fac.createOMElement("loadbalance", synNS); loadbalance.addAttribute(fac.createOMAttribute("algorithm", nullNS, algorithmClassName)); if (buildMessage) { loadbalance.addAttribute(fac.createOMAttribute("buildMessage", nullNS, Boolean.toString(true))); } if (sessionType != null) { OMElement session = fac.createOMElement("session", synNS); session.addAttribute(fac.createOMAttribute( "type", nullNS, sessionType)); OMElement sessionTimeout = fac.createOMElement("sessionTimeout", synNS); sessionTimeout.setText(String.valueOf(getSessionTimeout())); session.addChild(sessionTimeout); endpoint.addChild(session); } if (properties != null && properties.length() != 0) { String[] props = properties.split("::"); for (String s : props) { String[] elements = s.split(","); OMElement property = fac.createOMElement("property", synNS); property.addAttribute(fac.createOMAttribute("name", nullNS, elements[0])); property.addAttribute(fac.createOMAttribute("value", nullNS, elements[1])); property.addAttribute(fac.createOMAttribute("scope", nullNS, elements[2])); endpoint.addChild(property); } } endpoint.addChild(loadbalance); serializeChildren(loadbalance, getList()); if (parent != null) { parent.addChild(endpoint); } return endpoint; }
Source:
<code>public boolean include(T object) { boolean include = false; for (Filter<T> f : filters) { if (!f.include(object)) { <START> if (f.toString().contains("IncludeRegExpPaths") && include) { <END> continue; } return false; } include = true; } return true; }</code><technical_language>@hemanik explain is rationale this check</technical_language>

Target:
public boolean include(T object) { if (filters.isEmpty()) { return true; } for (Filter<T> filter : filters) { if (!filter.include(object)) { return false; } } return true; }
Source:
<code>public void testPrefixWithoutTrailingSlash() throws Exception { writeTrashFile("baz", "a file"); writeTrashFile("foo/bar", "another file"); git.add().addFilepattern("baz").call(); git.add().addFilepattern("foo").call(); git.commit().setMessage("sample commit").call(); final byte[] result = CLIGitCommand.rawExecute( "git archive --prefix=my- --format=zip master", db); <START> String[] expect = { "my-baz", "my-foo/bar" }; <END> String[] actual = listZipEntries(result); Arrays.sort(expect); Arrays.sort(actual); assertArrayEquals(expect, actual); }</code><technical_language>Glad wrote a test, want this behavior</technical_language>

Target:
public void testPrefixWithoutTrailingSlash() throws Exception { commitBazAndFooSlashBar(); byte[] result = CLIGitCommand.rawExecute( "git archive --prefix=my- --format=zip master", db); String[] expect = { "my-baz", "my-foo/bar" }; String[] actual = listZipEntries(result); Arrays.sort(expect); Arrays.sort(actual); assertArrayEquals(expect, actual); }
Source:
<code>public JournalContext createJournalContext() throws UnavailableException { LockResource sharedLockResource; try { sharedLockResource = mMasterContext.getStateLockManager().lockShared(); } catch (InterruptedException e) { <START> throw new UnavailableException("Failed to acquire state-lock in shared mode."); <END> } return new StateChangeJournalContext(mJournal.createJournalContext(), sharedLockResource); }</code><technical_language>this backup is in progress? more in message</technical_language>

Target:
public JournalContext createJournalContext() throws UnavailableException { LockResource sharedLockResource; try { sharedLockResource = mMasterContext.getStateLockManager().lockShared(); } catch (InterruptedException e) { throw new UnavailableException( "Failed to acquire state-lock due to ongoing backup activity."); } return new StateChangeJournalContext(mJournal.createJournalContext(), sharedLockResource); }
Source:
<code>private static Map<ProgramInterface, List<String>> processAdditionalArguments(final List<String> arguments) { final Map<ProgramInterface, List<String>> map = new HashMap<>(); final Pattern pattern = Pattern.compile("(?<program>.*)::(?<argumentAndValue>.+?)( +(?<optionalValue>.+))?"); for (String str : arguments) { final Matcher matcher = pattern.matcher(str); if (!matcher.matches()) { <START> throw new IllegalArgumentException("couldn't understand EXTRA_ARGUMENT " + str + " it doesn't conform to the regular expression given by " + pattern.pattern()); <END> } final String programName = matcher.group("program"); final ProgramInterface program; try { program = Program.valueOf(programName); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("Couldn't find program with value " + programName, e); } final String argumentAndValue = matcher.group("argumentAndValue"); map.computeIfAbsent(program, (k)->new ArrayList<>()).add(argumentAndValue); final String optionalValue = matcher.group("optionalValue"); if (optionalValue!=null && !optionalValue.equals("")) { map.get(program).add(optionalValue); } } return map; }</code><technical_language>CommandLineException</technical_language>

Target:
private static Map<ProgramInterface, List<String>> processAdditionalArguments(final List<String> arguments) { final Map<ProgramInterface, List<String>> map = new HashMap<>(); final Pattern pattern = Pattern.compile("(?<program>.*)::(?<argumentAndValue>.+?)( +(?<optionalValue>.+))?"); for (String str : arguments) { final Matcher matcher = pattern.matcher(str); if (!matcher.matches()) { throw new CommandLineException("couldn't understand EXTRA_ARGUMENT " + str + " it doesn't conform to the form '<PROGRAM>::<ARGUMENT_AND_VALUE>'."); } final String programName = matcher.group("program"); final ProgramInterface program; try { program = Program.valueOf(programName); } catch (IllegalArgumentException e) { throw new CommandLineException("Couldn't find program with value " + programName, e); } final String argumentAndValue = matcher.group("argumentAndValue"); map.computeIfAbsent(program, (k) -> new ArrayList<>()).add(argumentAndValue); final String optionalValue = matcher.group("optionalValue"); if (!StringUtils.isEmpty(optionalValue)) { map.get(program).add(optionalValue); } } return map; }
Source:
<code>public LocalityManager(Config config, MetricsRegistry metricsRegistry, Serde<String> keySerde, Serde<String> valueSerde) { this.config = config; <START> MetadataStoreFactory metadataStoreFactory = Util.getObj(new JobConfig(config).getMetadataStoreFactory(), MetadataStoreFactory.class); <END> this.metadataStore = metadataStoreFactory.getMetadataStore(SetContainerHostMapping.TYPE, config, metricsRegistry); this.keySerde = keySerde; this.valueSerde = valueSerde; this.taskAssignmentManager = new TaskAssignmentManager(config, metricsRegistry, keySerde, valueSerde); }</code><technical_language>Is serde required? More specific - need a part of store</technical_language>

Target:
LocalityManager(Config config, MetricsRegistry metricsRegistry, Serde<String> keySerde, Serde<String> valueSerde) { this.config = config; MetadataStoreFactory metadataStoreFactory = Util.getObj(new JobConfig(config).getMetadataStoreFactory(), MetadataStoreFactory.class); this.metadataStore = metadataStoreFactory.getMetadataStore(SetContainerHostMapping.TYPE, config, metricsRegistry); this.metadataStore.init(config, metricsRegistry); this.keySerde = keySerde; this.valueSerde = valueSerde; this.taskAssignmentManager = new TaskAssignmentManager(config, metricsRegistry, keySerde, valueSerde); }
Source:
<code>public static Optional<List<Symbol>> pruneInputs(Collection<Symbol> availableInputs, Collection<Expression> expressions) { <START> List<Symbol> prunedInputs = availableInputs.stream() <END> .filter(DependencyExtractor.extractUnique(expressions)::contains) .collect(toImmutableList()); if (prunedInputs.size() == availableInputs.size()) { return Optional.empty(); } return Optional.of(prunedInputs); }</code><technical_language>I streams smart avoid calling extractUnique for symbol. want retrieve pass stream-processor</technical_language>

Target:
public static Optional<List<Symbol>> pruneInputs(Collection<Symbol> availableInputs, Collection<Expression> expressions) { Set<Symbol> available = new HashSet<>(availableInputs); Set<Symbol> required = SymbolsExtractor.extractUnique(expressions); Set<Symbol> used = Sets.intersection(required, available); if (used.size() == available.size()) { return Optional.empty(); } return Optional.of(ImmutableList.copyOf(used)); }
Source:
<code>private CloudMachineNamer getCloudMachineNamer(ConfigBag config) { String namerClass = config.get(LocationConfigKeys.CLOUD_MACHINE_NAMER_CLASS); if (namerClass != null) { try { return (CloudMachineNamer) getManagementContext().getCatalog().getRootClassLoader().loadClass(namerClass) .getDeclaredConstructor(ConfigBag.class).newInstance(config); } catch (Exception e) { throw Exceptions.propagate(e); } } else { <START> return new JcloudsMachineNamer(getAllConfigBag()); <END> } }</code><technical_language>This call getAllConfigBag(). config passed in, lose local values passed in obtain() method. Do agree</technical_language>

Target:
private CloudMachineNamer getCloudMachineNamer(ConfigBag config) { String namerClass = config.get(LocationConfigKeys.CLOUD_MACHINE_NAMER_CLASS); if (namerClass != null) { try { return (CloudMachineNamer) getManagementContext().getCatalog().getRootClassLoader().loadClass(namerClass) .getDeclaredConstructor(ConfigBag.class).newInstance(config); } catch (Exception e) { throw Exceptions.propagate(e); } } else { return new JcloudsMachineNamer(config); } }