auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public AccountGroupCollection(Collection<AccountGroup> groups) { <START> this.groups = groups; <END> }</code><technical_language>a bug this Collections.unmodifiableList something. Please fix while mucking code</technical_language>

Target:
public AccountGroupCollection(Collection<AccountGroup> groups) { this.groups = Collections.unmodifiableCollection(groups); }
Source:
<code>public void waitForInitialRemoteData_readOnlyTrue_throwsIfWrongServerSchema() { SyncCredentials credentials = SyncCredentials.usernamePassword(UUID.randomUUID().toString(), "password", true); SyncUser user = SyncUser.logIn(credentials, Constants.AUTH_URL); final SyncConfiguration configNew = configurationFactory.createSyncConfigurationBuilder(user, Constants.USER_REALM) .waitForInitialRemoteData() .readOnly() .schema(StringOnly.class) .build(); assertFalse(configNew.realmExists()); Realm realm = null; try { realm = Realm.getInstance(configNew); fail(); <START> } catch (RealmMigrationNeededException ignored) { <END> } finally { if (realm != null) { realm.close(); } user.logOut(); } }</code><technical_language>Hmm. this is confusing RealmMigrationNeededException sense in additive Sync schema scenario..</technical_language>

Target:
public void waitForInitialRemoteData_readOnlyTrue_throwsIfWrongServerSchema() { SyncCredentials credentials = SyncCredentials.usernamePassword(UUID.randomUUID().toString(), "password", true); SyncUser user = SyncUser.logIn(credentials, Constants.AUTH_URL); final SyncConfiguration configNew = configurationFactory.createSyncConfigurationBuilder(user, Constants.USER_REALM) .waitForInitialRemoteData() .readOnly() .schema(StringOnly.class) .build(); assertFalse(configNew.realmExists()); Realm realm = null; try { realm = Realm.getInstance(configNew); fail(); } catch (RealmMigrationNeededException ignore) { } finally { if (realm != null) { realm.close(); } user.logOut(); } }
Source:
<code>protected String buildGroupBySQL(List<String> aggregateFunctions) { String groupedColSql = Joiner.on(",").join(mGroupedColumns); String selectFuncSql = convertAggregateFunctionsToSql(aggregateFunctions.get(0)); for (int i = 1; i < aggregateFunctions.size(); i++) { <START> selectFuncSql += "," + convertAggregateFunctionsToSql(aggregateFunctions.get(i)); <END> } String sqlCmd = String.format("SELECT %s , %s FROM %s GROUP BY %s", selectFuncSql, groupedColSql, "{1}", groupedColSql); return sqlCmd; }</code><technical_language>Joiner is clearer? map join</technical_language>

Target:
protected String buildGroupBySQL(List<String> aggregateFunctions) throws DDFException { String groupedColSql = Joiner.on(",").join(mGroupedColumns); List<String> aggregationFuncSql = new ArrayList<String>(); for(String aggFunc: aggregateFunctions) { aggregationFuncSql.add(convertAggregateFunctionsToSql(aggFunc)); } String selectFuncSql = Joiner.on(",").join(aggregationFuncSql); return String.format("SELECT %s , %s FROM %s GROUP BY %s", selectFuncSql, groupedColSql, "{1}", groupedColSql); }
Source:
<code>public ItemStack[] getRemainingItems(InventoryCrafting inv) { <START> return ForgeHooks.defaultRecipeGetRemainingItems(inv); <END> }</code><technical_language>If this is copied PR, this part is incomplete. needs find drain correct amount containers</technical_language>

Target:
public ItemStack[] getRemainingItems(InventoryCrafting inv) { ItemStack[] ret = new ItemStack[inv.getSizeInventory()]; for (int i = 0; i < ret.length; i++) { if (drains[i] != 0) { ret[i] = inv.getStackInSlot(i); if (isEmpty(ret[i])) continue; ret[i] = setSize(ret[i].copy(), 1); if (drains[i] > 0) { ret[i].getCapability(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, null).drain(drains[i], true); } else { IFluidContainerItem fluidContainerItem = (IFluidContainerItem) ret[i].getItem(); fluidContainerItem.drain(ret[i], -drains[i], true); } ret[i] = makeSafe(ret[i]);; } else { ret[i] = ForgeHooks.getContainerItem(inv.getStackInSlot(i)); } } return ret; }
Source:
<code>public void testCommitId() { try { properties.load(getClass().getClassLoader().getResourceAsStream("git.properties")); } catch (IOException e) { <START> e.printStackTrace(); <END> } assertNotNull(properties.get("git.commit.id").toString()); assertEquals("b34a518cdcad80a7d750b714ce2fec18f029b489".length(),properties.get("git.commit.id").toString().length()); }</code><technical_language>throw counts a failure/error</technical_language>

Target:
public void testCommitId() throws IOException { properties.load(getClass().getClassLoader().getResourceAsStream("git.properties")); assertNotNull(properties.get("git.commit.id").toString()); assertEquals("b34a518cdcad80a7d750b714ce2fec18f029b489".length(),properties.get("git.commit.id").toString().length()); }
Source:
<code><START> public Mono<Void> runAsync() { try { throw new IllegalArgumentException(); <END> } catch (Exception ex) { } return Mono.empty(); }</code><technical_language>Publishers return errors in error channel. This instead be: public Mono<Void> runAsync() { return Mono.error(new IllegalArgumentException(); }</technical_language>

Target:
public Mono<Void> runAsync() { return Mono.error(new IllegalArgumentException()); }
Source:
<code>public static void updateGoogleUserData(String token, User user) { GoogleCredential credential = new GoogleCredential().setAccessToken(token); try { Oauth2 oauth2; oauth2 = new Oauth2.Builder(GoogleNetHttpTransport.newTrustedTransport(), new JacksonFactory(), credential) .setApplicationName("").build(); Userinfoplus userinfoplus = oauth2.userinfo().get().execute(); updateUserFromGoogleUserinfoplus(userinfoplus, user); } catch (GeneralSecurityException | IOException e) { <START> throw new CustomWebApplicationException("Could not get Google profile.", HttpStatus.SC_BAD_REQUEST); <END> } }</code><technical_language>Add name of profile in message aid user debugging</technical_language>

Target:
public static void updateGoogleUserData(String token, User user) { GoogleCredential credential = new GoogleCredential().setAccessToken(token); try { Oauth2 oauth2; oauth2 = new Oauth2.Builder(GoogleNetHttpTransport.newTrustedTransport(), new JacksonFactory(), credential) .setApplicationName("").build(); Userinfoplus userinfoplus = oauth2.userinfo().get().execute(); updateUserFromGoogleUserinfoplus(userinfoplus, user); } catch (GeneralSecurityException | IOException e) { throw new CustomWebApplicationException("Could not get Google profile of " + user.getUsername() + ".", HttpStatus.SC_BAD_REQUEST); } }
Source:
<code>public FxSwapTrade trade(LocalDate valuationDate, MarketData marketData) { FxRate fxNearRate = marketData.getValue(fxNearKey); <START> double rate = fxNearRate.fxRate(fxNearKey.getPair()); <END> double fxPts = marketData.getValue(fxPtsKey); return template.toTrade(valuationDate, BuySell.BUY, 1d, rate, fxPts); }</code><technical_language>This needs convention's currency pair extract data ensure rate is right round</technical_language>

Target:
public FxSwapTrade trade(LocalDate valuationDate, MarketData marketData) { FxRate fxNearRate = marketData.getValue(fxNearKey); double rate = fxNearRate.fxRate(template.getCurrencyPair()); double fxPts = marketData.getValue(fxPtsKey); return template.toTrade(valuationDate, BuySell.BUY, 1d, rate, fxPts); }
Source:
<code>public DefaultDiffEngine() { <START> this.diffProcessor = new DiffBuilder(); <END> }</code><technical_language>call other constructor giving diff builder instance in parameter</technical_language>

Target:
public DefaultDiffEngine() { this(new DiffBuilder()); }
Source:
<code>protected boolean validate() { if (getParameters() == null || getParameters().getAgent() == null || getParameters().getAgent().getIp() == null || getParameters().getAgent().getHostId() == null || getParameters().getAgent().getPassword() == null || getParameters().getAgent().getType() == null || getParameters().getAgent().getUser() == null) { <START> return failValidation(EngineMessage.VDS_ADD_FENCE_AGENT_MANDATORY_PARAMETERS_MISSING); <END> } Guid vdsId = getParameters().getAgent().getHostId(); VDS vds = vdsDao.get(vdsId); Guid vdsClusterId = vds.getClusterId(); Cluster cluster = clusterDao.get(vdsClusterId); String clusterCompatibilityVersion = cluster.getCompatibilityVersion().toString(); if (!FenceConfigHelper.getValidFenceAgentTypes(clusterCompatibilityVersion) .contains(getParameters().getAgent().getType())) { return failValidation(EngineMessage.ACTION_TYPE_FAILED_AGENT_NOT_SUPPORTED); } return super.validate(); }</code><technical_language>I this validation correct for 'RemoveFence*' commands, extends 'FenceAgentCommandBase'</technical_language>

Target:
protected boolean validate() { if (getParameters() != null || getParameters().getAgent() != null || getParameters().getAgent().getHostId() != null || getParameters().getAgent().getType() != null) { Guid vdsId = getParameters().getAgent().getHostId(); VDS vds = vdsDao.get(vdsId); Guid vdsClusterId = vds.getClusterId(); Cluster cluster = clusterDao.get(vdsClusterId); String clusterCompatibilityVersion = cluster.getCompatibilityVersion().toString(); if (!FenceConfigHelper.getValidFenceAgentTypes(clusterCompatibilityVersion) .contains(getParameters().getAgent().getType())) { return failValidation(EngineMessage.ACTION_TYPE_FAILED_AGENT_NOT_SUPPORTED); } } return super.validate(); }
Source:
<code>private void markThisMessageAsRead(Message message) { try { int mID = message.getID(); <START> if (!startedFromFilter && zulipApp.getPointer() < mID) { <END> zulipApp.syncPointer(mID); } boolean isMessageRead = false; if (message.getMessageRead() != null) { isMessageRead = message.getMessageRead(); } if (!isMessageRead) { try { updateBuilder.where().eq(Message.ID_FIELD, message.getID()); updateBuilder.updateColumnValue(Message.MESSAGE_READ_FIELD, true); updateBuilder.update(); } catch (SQLException e) { ZLog.logException(e); } } zulipApp.markMessageAsRead(message); } catch (NullPointerException e) { Log.w("scrolling", "Could not find a location to scroll to!"); } }</code><technical_language>this !startedFromFilter moved L383</technical_language>

Target:
private void markThisMessageAsRead(Message message) { try { int mID = message.getID(); if (zulipApp.getPointer() < mID) { zulipApp.syncPointer(mID); } boolean isMessageRead = false; if (message.getMessageRead() != null) { isMessageRead = message.getMessageRead(); } if (!isMessageRead) { try { updateBuilder.where().eq(Message.ID_FIELD, message.getID()); updateBuilder.updateColumnValue(Message.MESSAGE_READ_FIELD, true); updateBuilder.update(); } catch (SQLException e) { ZLog.logException(e); } } zulipApp.markMessageAsRead(message); } catch (NullPointerException e) { Log.w("scrolling", "Could not find a location to scroll to!"); } }
Source:
<code>public IArtifactRepository read(URL location, InputStream input, IProgressMonitor monitor) throws ProvisionException { BufferedInputStream bufferedInput = null; try { try { bufferedInput = new BufferedInputStream(input); Parser repositoryParser = new Parser(Activator.getContext(), Activator.ID); repositoryParser.parse(input); IStatus result = repositoryParser.getStatus(); switch (result.getSeverity()) { case IStatus.CANCEL: throw new OperationCanceledException(); case IStatus.ERROR: throw new ProvisionException(result); case IStatus.WARNING: case IStatus.INFO: LogHelper.log(result); break; <START> default: <END> break; } SimpleArtifactRepository repository = repositoryParser.getRepository(); if (repository == null) throw new ProvisionException(new Status(IStatus.ERROR, Activator.ID, ProvisionException.REPOSITORY_FAILED_READ, Messages.io_parseError, null)); return repository; } finally { if (bufferedInput != null) bufferedInput.close(); } } catch (IOException ioe) { String msg = NLS.bind(Messages.io_failedRead, location); throw new ProvisionException(new Status(IStatus.ERROR, Activator.ID, ProvisionException.REPOSITORY_FAILED_READ, msg, ioe)); } }</code><technical_language>I guess is point in adding empty default statement other making findbugs happy. valid severities OK, ERROR, INFO ,WARNING, CANCEL OK is missing explicitly treated empty statement (break;). Then, default case throw IllegalStateException("unknown severity: " + result.getSeverity)</technical_language>

Target:
public IArtifactRepository read(URL location, InputStream input, IProgressMonitor monitor) throws ProvisionException { BufferedInputStream bufferedInput = null; try { try { bufferedInput = new BufferedInputStream(input); Parser repositoryParser = new Parser(Activator.getContext(), Activator.ID); repositoryParser.parse(input); IStatus result = repositoryParser.getStatus(); switch (result.getSeverity()) { case IStatus.CANCEL: throw new OperationCanceledException(); case IStatus.ERROR: throw new ProvisionException(result); case IStatus.WARNING: case IStatus.INFO: LogHelper.log(result); break; case IStatus.OK: break; default: throw new IllegalStateException("Not valid value for serverity: " + result.getSeverity()); } SimpleArtifactRepository repository = repositoryParser.getRepository(); if (repository == null) throw new ProvisionException(new Status(IStatus.ERROR, Activator.ID, ProvisionException.REPOSITORY_FAILED_READ, Messages.io_parseError, null)); return repository; } finally { if (bufferedInput != null) bufferedInput.close(); } } catch (IOException ioe) { String msg = NLS.bind(Messages.io_failedRead, location); throw new ProvisionException(new Status(IStatus.ERROR, Activator.ID, ProvisionException.REPOSITORY_FAILED_READ, msg, ioe)); } }
Source:
<code>public LogReplicationEntry resend() { LogReplicationEntry ack = null; boolean force = false; <START> log.info("processAcks and pendingMessage size {}", pendingCompletableFutureForAcks.keySet(), pendingMessages.getSize()); <END> if (pendingMessages.isEmpty()) { return null; } try { ack = processAcks(); } catch (Exception e) { log.warn("Caught a timeout exception ", e); force = true; } for (int i = 0; i < pendingMessages.getSize(); i++) { LogReplicationPendingEntry entry = pendingMessages.getList().get(i); if (entry.timeout(msgTimer) || force) { if (errorOnMsgTimeout && entry.retry >= maxRetry) { log.warn("Entry of type has been resent max times for timer {}.", entry.getData().getMetadata().getTimestamp(), entry.getData().getMetadata().getMessageMetadataType(), maxRetry, msgTimer); throw new LogEntrySyncTimeoutException("timeout"); } entry.retry(); log.info("Resend message {}", entry.getData().getMetadata()); CompletableFuture<LogReplicationEntry> cf = dataSender.send(entry.getData()); addCFToAcked(entry.getData(), cf); } else { log.info("Skip resending message with timer ", entry.getData().getMetadata(), msgTimer); } } return ack; }</code><technical_language>debug</technical_language>

Target:
public LogReplicationEntry resend() { LogReplicationEntry ack = null; boolean force = false; log.debug("processAcks and pendingMessage size {}", pendingCompletableFutureForAcks.keySet(), pendingMessages.getSize()); if (pendingMessages.isEmpty()) { return null; } try { ack = processAcks(); } catch (TimeoutException e) { log.warn("Caught a timeout exception ", e); force = true; } catch (ExecutionException | InterruptedException e ) { log.warn("Caught an exception.", e); } for (int i = 0; i < pendingMessages.getSize(); i++) { LogReplicationPendingEntry entry = pendingMessages.getList().get(i); if (entry.timeout(msgTimer) || force) { if (errorOnMsgTimeout && entry.retry >= maxRetry) { log.warn("Entry of type has been resent max times for timer {}.", entry.getData().getMetadata().getTimestamp(), entry.getData().getMetadata().getMessageMetadataType(), maxRetry, msgTimer); throw new LogEntrySyncTimeoutException("timeout"); } entry.retry(); log.debug("Resend message {}", entry.getData().getMetadata()); CompletableFuture<LogReplicationEntry> cf = dataSender.send(entry.getData()); addCFToAcked(entry.getData(), cf); } else { log.info("Skip resending message with timer ", entry.getData().getMetadata(), msgTimer); } } return ack; }
Source:
<code>public Void visitVariable(VariableTree node, Void p) { warnAboutTypeAnnotationsTooEarly(node, node.getModifiers()); Pair<Tree, AnnotatedTypeMirror> preAssCtxt = visitorState.getAssignmentContext(); visitorState.setAssignmentContext( Pair.of((Tree) node, atypeFactory.getAnnotatedType(node))); try { if (atypeFactory.getDependentTypesHelper() != null) { if (getCurrentPath().getParentPath() != null && getCurrentPath().getParentPath().getLeaf().getKind() == Tree.Kind.LAMBDA_EXPRESSION) { atypeFactory .getDependentTypesHelper() <START> .checkType(visitorState.getAssignmentContext().second, node); <END> } else { atypeFactory .getDependentTypesHelper() .checkType(atypeFactory.getAnnotatedTypeLhs(node), node); } } if (node.getInitializer() != null) { commonAssignmentCheck(node, node.getInitializer(), "assignment.type.incompatible"); } else { validateTypeOf(node); } return super.visitVariable(node, p); } finally { visitorState.setAssignmentContext(preAssCtxt); } }</code><technical_language>understand change in #2649: assignment context declared type? is, #2649 change this line getAnnotatedTypeLhs instead of assignment context? Is real problem assignment context set correctly declared type</technical_language>

Target:
public Void visitVariable(VariableTree node, Void p) { warnAboutTypeAnnotationsTooEarly(node, node.getModifiers()); Pair<Tree, AnnotatedTypeMirror> preAssCtxt = visitorState.getAssignmentContext(); AnnotatedTypeMirror variableType; if (getCurrentPath().getParentPath() != null && getCurrentPath().getParentPath().getLeaf().getKind() == Tree.Kind.LAMBDA_EXPRESSION) { variableType = atypeFactory.getAnnotatedType(node); } else { variableType = atypeFactory.getAnnotatedTypeLhs(node); } visitorState.setAssignmentContext(Pair.of(node, variableType)); try { if (atypeFactory.getDependentTypesHelper() != null) { atypeFactory.getDependentTypesHelper().checkType(variableType, node); } if (node.getInitializer() != null) { commonAssignmentCheck(node, node.getInitializer(), "assignment.type.incompatible"); } else { validateTypeOf(node); } return super.visitVariable(node, p); } finally { visitorState.setAssignmentContext(preAssCtxt); } }
Source:
<code>public RqWithoutHeader(final Request req, final CharSequence name) { super( new Request() { @Override @SuppressWarnings("unchecked") public Iterable<String> head() throws IOException { final String prefix = String.format( "%s:", name.toString().toLowerCase(Locale.ENGLISH) ); return new Concat<String>( req.head(), <START> Collections.EMPTY_LIST, <END> new Condition.LowerCase(prefix) ); } @Override public InputStream body() throws IOException { return req.body(); } } ); }</code><technical_language>@super132 I is Collections.emptyList() method instead of static field</technical_language>

Target:
public RqWithoutHeader(final Request req, final CharSequence name) { super( new Request() { @Override public Iterable<String> head() throws IOException { final String prefix = String.format( "%s:", name.toString().toLowerCase(Locale.ENGLISH) ); return new Select<String>( req.head(), new Condition<String>() { @Override public boolean fits(final String header) { return !header.toLowerCase(Locale.ENGLISH) .startsWith(prefix); } } ); } @Override public InputStream body() throws IOException { return req.body(); } } ); }
Source:
<code>public static String getVideoPath(Context context, DownloadEntry video) { String filepath = null; if (video.filepath != null && video.filepath.length() > 0) { if (video.isDownloaded()) { <START> File f = new File(video.filepath); <END> if (f.exists()) { filepath = video.filepath; } } } else { DownloadEntry de = (DownloadEntry) DatabaseFactory.getInstance(DatabaseFactory.TYPE_DATABASE_NATIVE) .getIVideoModelByVideoUrl( video.url, null); if (de != null) { if (de.filepath != null) { File f = new File(de.filepath); if (f.exists()) { filepath = de.filepath; } } } } if (TextUtils.isEmpty(filepath)) { filepath = video.getBestEncodingUrl(context); } return filepath; }</code><technical_language>final</technical_language>

Target:
public static String getVideoPath(Context context, DownloadEntry video) { String filepath = null; if (video.filepath != null && video.filepath.length() > 0) { if (video.isDownloaded()) { final File f = new File(video.filepath); if (f.exists()) { filepath = video.filepath; } } } else { final DownloadEntry de = (DownloadEntry) DatabaseFactory.getInstance(DatabaseFactory.TYPE_DATABASE_NATIVE) .getIVideoModelByVideoUrl( video.url, null); if (de != null) { if (de.filepath != null) { final File f = new File(de.filepath); if (f.exists()) { filepath = de.filepath; } } } } if (TextUtils.isEmpty(filepath)) { filepath = video.getBestEncodingUrl(context); } return filepath; }
Source:
<code>private boolean hasExcessiveAverageLineLength(File file) { long nbLines = 0; long nbCharacters = 0; HeaderCommentDetector detector = new HeaderCommentDetector(); try (BufferedReader reader = getReader(file)) { nbCharacters = reader.lines() .filter(line -> !detector.isLineInHeaderComment(line)) .mapToLong(line -> line.length()) .sum(); } catch (IOException e) { handleException(e, file); } try (BufferedReader reader = getReader(file)) { <START> nbLines = reader.lines().count(); <END> } catch (IOException e) { handleException(e, file); } nbLines -= detector.getNumberOfLinesInHeaderComment(); int averageLineLength = nbLines > 0 ? (int) (nbCharacters / nbLines) : -1; return averageLineLength > averageLineLengthThreshold; }</code><technical_language>@ivandalbosco read file twice</technical_language>

Target:
private boolean hasExcessiveAverageLineLength(File file) { int averageLineLength = new AverageLineLengthCalculator(file, encoding).getAverageLineLength(); return averageLineLength > averageLineLengthThreshold; }
Source:
<code>public void cancel() { if (addLogicalImageTask != null) { <START> thread.interrupt(); <END> addLogicalImageTask.cancelTask(); } }</code><technical_language>Is this necessary? saving thread in general</technical_language>

Target:
public void cancel() { if (addLogicalImageTask != null) { addLogicalImageTask.cancelTask(); } }
Source:
<code>public GraphQuery queryGraph(Graph graph, String queryString, Authorizations authorizations) { return new ElasticSearchParentChildGraphQuery( getClient(), getConfig().getIndicesToQuery(), graph, queryString, getAllPropertyDefinitions(), getConfig().getScoringStrategy(), <START> getConfig().getNameSubstitutionStrategy(), <END> authorizations); }</code><technical_language>this a field create time</technical_language>

Target:
public GraphQuery queryGraph(Graph graph, String queryString, Authorizations authorizations) { return new ElasticSearchParentChildGraphQuery( getClient(), getConfig().getIndicesToQuery(), graph, queryString, getAllPropertyDefinitions(), getConfig().getScoringStrategy(), this.nameSubstitutionStrategy, authorizations); }
Source:
<code>public int getItemCount() { switch (wiFiDirectActivity.mState) { case send: return 3; case submit: return 2; <START> } <END> return 1; }</code><technical_language>Switch is missing receive state</technical_language>

Target:
public int getItemCount() { switch (wiFiDirectActivity.mState) { case send: return 3; case submit: return 2; case receive: return 1; } return 0; }
Source:
<code>public boolean isValidPartitionKeyProperty() { <START> return !((this.partitionKeyExpression != null) && (this.partitionKeyExtractorClass != null)); <END> }</code><technical_language>simpler: return (this.partitionSelectorClass == null) || (this.partitionSelectorExpression == null);</technical_language>

Target:
public boolean isValidPartitionKeyProperty() { return (this.partitionKeyExpression == null) || (this.partitionKeyExtractorClass == null); }
Source:
<code>Mono<Response<RecognizeLinkedEntitiesResult>> recognizeLinkedEntitiesWithResponse(String text, String language, Context context) { return recognizeBatchLinkedEntitiesWithResponse( <START> Arrays.asList(new TextDocumentInput(Integer.toString(0), text, language)), null, context) <END> .flatMap(response -> { Iterator<RecognizeLinkedEntitiesResult> responseItem = response.getValue().iterator(); return Mono.just(new SimpleResponse<>(response, responseItem.next())); }); }</code><technical_language>"0"</technical_language>

Target:
Mono<Response<RecognizeLinkedEntitiesResult>> recognizeLinkedEntitiesWithResponse(String text, String language, Context context) { Objects.requireNonNull(text, "'text' cannot be null."); return recognizeBatchLinkedEntitiesWithResponse( Collections.singletonList(new TextDocumentInput("0", text, language)), null, context) .map(response -> new SimpleResponse<>(response, response.getValue().iterator().next())); }
Source:
<code>public void testGroupByOneColumnWithLiterallyFalseFilter() throws Exception { testQuery( "SELECT COUNT(*), MAX(cnt) FROM druid.foo WHERE 1 = 0 GROUP BY dim1", <START> CalciteTests.REGULAR_USER_AUTH_RESULT, <END> ImmutableList.of(), ImmutableList.of() ); }</code><technical_language>avoid clogging majority of tests, authorization result a parameter in "full" overload (the provide a planner config, context, etc). "basic" overload (sql, expectedQueries, expectedResults) stay same</technical_language>

Target:
public void testGroupByOneColumnWithLiterallyFalseFilter() throws Exception { testQuery( "SELECT COUNT(*), MAX(cnt) FROM druid.foo WHERE 1 = 0 GROUP BY dim1", ImmutableList.of(), ImmutableList.of() ); }
Source:
<code>protected void executeCommand() { final VDS vds = getVds(); try (EngineLock monitoringLock = acquireMonitorLock("Activate host")) { executionHandler.updateSpecificActionJobCompleted(vds.getId(), ActionType.MaintenanceVds, false); setSucceeded(setVdsStatus(VDSStatus.Unassigned).getSucceeded()); if (getSucceeded()) { TransactionSupport.executeInNewTransaction(() -> { List<Network> networks = networkDao.getAllForCluster(vds.getClusterId()); networkClusterHelper.setStatus(vds.getClusterId(), networks); return null; }); if (vds.getClusterSupportsGlusterService()) { runVdsCommand(VDSCommandType.ManageGlusterService, new GlusterServiceVDSParameters(vds.getId(), Arrays.asList("glusterd"), "restart")); <START> startVDOService(vds); <END> } } } }</code><technical_language>good check vdo service status action, like: boolean isVdoRunning = isVDORunning(vds); if (!isVdoRunning) { startVDOService(VDS vds); }</technical_language>

Target:
protected void executeCommand() { final VDS vds = getVds(); try (EngineLock monitoringLock = acquireMonitorLock("Activate host")) { executionHandler.updateSpecificActionJobCompleted(vds.getId(), ActionType.MaintenanceVds, false); setSucceeded(setVdsStatus(VDSStatus.Unassigned).getSucceeded()); if (getSucceeded()) { TransactionSupport.executeInNewTransaction(() -> { List<Network> networks = networkDao.getAllForCluster(vds.getClusterId()); networkClusterHelper.setStatus(vds.getClusterId(), networks); return null; }); if (vds.getClusterSupportsGlusterService()) { runVdsCommand(VDSCommandType.ManageGlusterService, new GlusterServiceVDSParameters(vds.getId(), Arrays.asList("glusterd"), "restart")); boolean isRunning = isVDORunning(vds); if (!isRunning) { log.info("VDO service is down in host : '{}' , starting VDO service", vds.getId()); startVDOService(vds); } } } } }
Source:
<code>public ResponseEntity postEvent(@PathVariable final String eventTypeName, @RequestBody final String event, final NativeWebRequest nativeWebRequest) { LOG.trace("Received event for event type {}", event, eventTypeName); try { final EventType eventType = eventTypeRepository.findByName(eventTypeName); try { <START> final Timer successfullyPublishedTimer = metricRegistry.timer(metricNameFor(eventTypeName, SUCCESS_METRIC_NAME)); <END> final Timer.Context successfullyPublishedTimerContext = successfullyPublishedTimer.time(); final JSONObject eventAsJson = parseJson(event); validateSchema(eventAsJson, eventType); String partitionId = applyPartitioningStrategy(eventType, eventAsJson); topicRepository.postEvent(eventTypeName, partitionId, event); successfullyPublishedTimerContext.stop(); return status(HttpStatus.CREATED).build(); } catch (Exception e) { metricRegistry.counter(metricNameFor(eventTypeName, FAILED_METRIC_NAME)).inc(); throw e; } } catch (NoSuchEventTypeException e) { LOG.debug("Could not process event.", e); return create(e.asProblem(), nativeWebRequest); } catch (final EventValidationException e) { LOG.debug("Event validation error: {}", e.getValidationError().getMessage()); return create(e.asProblem(), nativeWebRequest); } catch (final NakadiException e) { LOG.error("error posting to partition", e); return create(e.asProblem(), nativeWebRequest); } }</code><technical_language>this place. create object call? create time</technical_language>

Target:
public ResponseEntity postEvent(@PathVariable final String eventTypeName, @RequestBody final String event, final NativeWebRequest nativeWebRequest) { LOG.trace("Received event for event type {}", event, eventTypeName); try { final long startingTime = System.nanoTime(); final EventType eventType = eventTypeRepository.findByName(eventTypeName); return doWithMetrics(eventTypeName, startingTime, () -> { final JSONObject eventAsJson = parseJson(event); validateSchema(eventAsJson, eventType); String partitionId = applyPartitioningStrategy(eventType, eventAsJson); topicRepository.postEvent(eventTypeName, partitionId, event); return status(HttpStatus.CREATED).build(); }); } catch (NoSuchEventTypeException e) { LOG.debug("Could not process event.", e); return create(e.asProblem(), nativeWebRequest); } catch (final EventValidationException e) { LOG.debug("Event validation error: {}", e.getValidationError().getMessage()); return create(e.asProblem(), nativeWebRequest); } catch (final NakadiException e) { LOG.error("error posting to partition", e); return create(e.asProblem(), nativeWebRequest); } }
Source:
<code>protected void postAddNetwork(Guid providerId, String externalId) { ExternalSubnet externalSubnet = getParameters().getExternalSubnet(); if (externalSubnet != null) { AddExternalSubnetParameters subnetParameters = new AddExternalSubnetParameters( externalSubnet, providerId, externalId); getBackend().runInternalAction( <START> ActionType.AddSubnetToProvider, subnetParameters); <END> } }</code><technical_language>previously, failure (exception) in AddSubnetToProvider AddNetworkOnProviderCommand fail. command compensation added network remain in dc. pretty weird declare command failed rollback. consider adding compensation AddNetworkOnProviderCommand running AddSubnetToProvider in a separate thread (so failure affect caller command). achieved getBackend().runInternalMultipleActions</technical_language>

Target:
protected void postAddNetwork(Guid providerId, String externalId) { ExternalSubnet externalSubnet = getParameters().getExternalSubnet(); if (externalSubnet != null) { AddExternalSubnetParameters subnetParameters = new AddExternalSubnetParameters( externalSubnet, providerId, externalId); getBackend().runInternalMultipleActions( ActionType.AddSubnetToProvider, Arrays.asList(subnetParameters)); } }
Source:
<code>public void testEventTypeFilter() throws Exception { getMockEndpoint("mock:direct:fulltext.filter").expectedMessageCount(0); createContext(ENHANCEMENT_ROUTE); Map<String, Object> headers = createEvent(FILE_ID, EVENT_TYPES); <START> headers.put(EVENT_TYPE, "ResourceDeletion"); <END> template.sendBodyAndHeaders("", headers); assertMockEndpointsSatisfied(); }</code><technical_language>pass this event type createEvent instead of EVENT_TYPES. Also, event type EVENT_NS</technical_language>

Target:
public void testEventTypeFilter() throws Exception { getMockEndpoint("mock:direct:fulltext.filter").expectedMessageCount(0); createContext(ENHANCEMENT_ROUTE); Map<String, Object> headers = createEvent(FILE_ID); headers.put(EVENT_TYPE, "ResourceDeletion"); template.sendBodyAndHeaders("", headers); assertMockEndpointsSatisfied(); }
Source:
<code>protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home); ButterKnife.bind(this); navigationController = new HomepageFragmentController(getSupportFragmentManager(), R.id.container); navigationController.loadHomeInitially(); bottomSheetBehavior = BottomSheetBehavior.from(bottomSheet); bottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN); bottomSheetBehavior.setPeekHeight(0); bottomSheetBehavior.addBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() { @Override public void onStateChanged(@NonNull View bottomSheet, int newState) @Override public void onSlide(@NonNull View bottomSheet, float slideOffset) { if (slideOffset == 0) { bottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN); } bottomNavigation.onAddSheetSlideOffset(slideOffset); } }); bottomNavigation.setListener(this); PreferencesManager preferencesManager = new PreferencesManager(this); preferencesManager.increaseNumAppOpens(); if (preferencesManager.getNumAppOpens() == NUM_APP_OPENS_FOR_RATING_ASK) { showPleaseRateDialog(); } importFromCsv.setText(preferencesManager.isOnFreeVersion() ? <START> getString(R.string.import_from_csv_file_premium) : <END> getString(R.string.import_from_csv_file)); createListDialog = new CreateListDialog(this, this); dataSource = new DataSource(this); paymentManager = new PaymentManager(this, this); paymentManager.setUpAndCheckForPremium(); }</code><technical_language>TextView in a @StringRes directly, remove getString() for more compact code</technical_language>

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home); ButterKnife.bind(this); navigationController = new HomepageFragmentController(getSupportFragmentManager(), R.id.container); navigationController.loadHomeInitially(); bottomSheetBehavior = BottomSheetBehavior.from(bottomSheet); bottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN); bottomSheetBehavior.setPeekHeight(0); bottomSheetBehavior.addBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() { @Override public void onStateChanged(@NonNull View bottomSheet, int newState) @Override public void onSlide(@NonNull View bottomSheet, float slideOffset) { if (slideOffset == 0) { bottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN); } bottomNavigation.onAddSheetSlideOffset(slideOffset); } }); bottomNavigation.setListener(this); preferencesManager = new PreferencesManager(this); preferencesManager.increaseNumAppOpens(); if (preferencesManager.getNumAppOpens() == NUM_APP_OPENS_FOR_RATING_ASK) { showPleaseRateDialog(); } createListDialog = new CreateListDialog(this, this); dataSource = new DataSource(this); paymentManager = new PaymentManager(this, this); paymentManager.setUpAndCheckForPremium(); }
Source:
<code>public static boolean sleep(SleepCondition conn, int timeout, int minimumTimeout) { <START> long start = System.currentTimeMillis(); <END> while (!conn.isValid()) { if (start + timeout < System.currentTimeMillis()) { return false; } Time.sleep(50); } long t; if((t = System.currentTimeMillis() - start) < minimumTimeout) { Time.sleep((int)(minimumTimeout - t)); } return true; }</code><technical_language>call sleep method line 45 instead of replicating this code</technical_language>

Target:
public static boolean sleep(SleepCondition conn, int timeout, int minimumTimeout) { long start = System.currentTimeMillis(); if(!sleep(conn, timeout)) { return false; } long t; if((t = System.currentTimeMillis() - start) < minimumTimeout) { Time.sleep((int)(minimumTimeout - t)); } return true; }
Source:
<code>public URL getLibraryIndexLocation() { switch(getEntryKind()) { case IClasspathEntry.CPE_LIBRARY : if (SHARED_INDEX_LOCATION != null) { try { <START> String pathString = getPath().toOSString(); <END> CRC32 checksumCalculator = new CRC32(); checksumCalculator.update(pathString.getBytes()); String fileName = Long.toString(checksumCalculator.getValue()) + ".index"; return new URL("file", null, Paths.get(SHARED_INDEX_LOCATION, fileName).toString()); } catch (MalformedURLException e1) { Util.log(e1); } } break; case IClasspathEntry.CPE_VARIABLE : break; default : return null; } if (this.extraAttributes == null) return null; for (int i= 0; i < this.extraAttributes.length; i++) { IClasspathAttribute attrib= this.extraAttributes[i]; if (IClasspathAttribute.INDEX_LOCATION_ATTRIBUTE_NAME.equals(attrib.getName())) { String value = attrib.getValue(); try { return new URL(value); } catch (MalformedURLException e) { return null; } } } return null; }</code><technical_language>toOSString() platform dependent path - Consider case shared indexing platforms win/lin/mac - get a URL if is platform dependent - this toPortableString()</technical_language>

Target:
public URL getLibraryIndexLocation() { switch(getEntryKind()) { case IClasspathEntry.CPE_LIBRARY : if (SHARED_INDEX_LOCATION != null) { try { String pathString = getPath().toPortableString(); CRC32 checksumCalculator = new CRC32(); checksumCalculator.update(pathString.getBytes()); String fileName = Long.toString(checksumCalculator.getValue()) + ".index"; return new URL("file", null, Paths.get(SHARED_INDEX_LOCATION, fileName).toString()); } catch (MalformedURLException e1) { Util.log(e1); } } break; case IClasspathEntry.CPE_VARIABLE : break; default : return null; } if (this.extraAttributes == null) return null; for (int i= 0; i < this.extraAttributes.length; i++) { IClasspathAttribute attrib= this.extraAttributes[i]; if (IClasspathAttribute.INDEX_LOCATION_ATTRIBUTE_NAME.equals(attrib.getName())) { String value = attrib.getValue(); try { return new URL(value); } catch (MalformedURLException e) { return null; } } } return null; }
Source:
<code><START> public void setCommodity(@NonNull String currencyCode){ <END> mCommodity = Commodity.getInstance(currencyCode); }</code><technical_language>pr this caught eye. Money objects meant immutable, Java Strings. change this private Money.withCurrency() relevant places instead</technical_language>

Target:
private void setCommodity(@NonNull String currencyCode){ mCommodity = Commodity.getInstance(currencyCode); }
Source:
<code>public void testEscapingTakesPlace() { final PrintWriterComparator comparator = new PrintWriterComparator(); final ColumnFormatter formatter = new ColumnFormatter(comparator.getPrintWriter(), "\t"); formatter.addColumn("foo"); <START> formatter.addColumn("a multi-line\ntext with a null character: \u0000"); <END> formatter.nextLine(); formatter.finish(); comparator.assertEquals( "foo\ta multi-line\\ntext with a null character: \\x00\n"); }</code><technical_language>useful column separator character a column text check escaped</technical_language>

Target:
public void testEscapingTakesPlace() { final PrintWriterComparator comparator = new PrintWriterComparator(); final ColumnFormatter formatter = new ColumnFormatter(comparator.getPrintWriter(), "\t"); formatter.addColumn("foo"); formatter.addColumn( "\tan indented multi-line\ntext with a null character: \u0000"); formatter.nextLine(); formatter.finish(); comparator.assertEquals( "foo\t\\tan indented multi-line\\ntext with a null character: \\x00\n"); }
Source:
<code>public static Track getAirhornTrack() { if (airhornTrack == null) { <START> airhornTrack = new Track("/Users/daveystruijk/Documents/FEESJE/Samples/Random - airhorn1.mp3"); <END> } return airhornTrack; }</code><technical_language>This work for other people</technical_language>

Target:
public static Track getAirhornTrack() { if (airhornTrack == null) { airhornTrack = new Track(AirhornProcessor.class.getClass() .getResource("/samples/airhorn.mp3").getPath()); } return airhornTrack; }
Source:
<code>private boolean clusterPresentInTopology(TopologyDescriptor topology) { localClusterDescriptor = topology.getClusterDescriptor(localEndpoint); if (localClusterDescriptor != null) { <START> localNodeDescriptor = localClusterDescriptor.getNode(localEndpoint); return true; <END> } return false; }</code><technical_language>localClusterDescriptor.getNode return null, need check</technical_language>

Target:
private boolean clusterPresentInTopology(TopologyDescriptor topology) { localClusterDescriptor = topology.getClusterDescriptor(localEndpoint); if (localClusterDescriptor != null) { localNodeDescriptor = localClusterDescriptor.getNode(localEndpoint); localCorfuEndpoint = getCorfuEndpoint(getLocalHost(), localClusterDescriptor.getCorfuPort()); } return localClusterDescriptor != null && localNodeDescriptor != null; }
Source:
<code>private String extractHosts(String uri) { <START> return new String {}; <END> }</code><technical_language>Missing codes</technical_language>

Target:
private String extractHosts(String uri) { return new String[] {ConnectionInfo.fromURI(uri).host}; }
Source:
<code>public void onNext(final AggregationMessage aggregationMessage) { final AvroClockMsg avroClockMsg = codec.decode(aggregationMessage.getData().array()); switch (avroClockMsg.getType()) { case ReplyInitClockMsg: globalMinimumClock = avroClockMsg.getReplyInitClockMsg().getGlobalMinClock(); workerClock = avroClockMsg.getReplyInitClockMsg().getInitClock(); initLatch.countDown(); break; case BroadcastMinClockMsg: globalMinimumClock = avroClockMsg.getBroadcastMinClockMsg().getGlobalMinClock(); <START> globalMinClockLatch.countDown(); <END> globalMinClockLatch = new CountDownLatch(1); break; default: throw new RuntimeException("Unexpected message type: " + avroClockMsg.getType().toString()); } }</code><technical_language>this line effect? in next line reinitialized a new latch.. I guess want release waiting threads bound latch assigning a new latch</technical_language>

Target:
public void onNext(final AggregationMessage aggregationMessage) { final AvroClockMsg avroClockMsg = codec.decode(aggregationMessage.getData().array()); switch (avroClockMsg.getType()) { case ReplyInitClockMsg: globalMinimumClock = avroClockMsg.getReplyInitClockMsg().getGlobalMinClock(); workerClock = avroClockMsg.getReplyInitClockMsg().getInitClock(); initLatch.countDown(); break; case BroadcastMinClockMsg: updateGlobalMinimumClock(avroClockMsg.getBroadcastMinClockMsg().getGlobalMinClock()); break; default: throw new RuntimeException("Unexpected message type: " + avroClockMsg.getType().toString()); } }
Source:
<code>private Rp sync(Rp rp) { if (!shouldSync(rp)) return rp; try { final RegisterResponse response = getClientMetadataFromOP(rp.getClientRegistrationClientUri(), rp.getClientRegistrationAccessToken()); <START> if (RegisterResponseMapper.hasClientMetadataChangedAtOp(rp, response)) { <END> persistenceService.update(rp); } LOG.debug("Successfully synced Rp object from OP. Rp: " + rp.toString()); return rp; } catch (Exception e) { LOG.error("Error in sync Rp object from OP: ", e); return rp; } }</code><technical_language>I code in this PR for hasClientMetadataChangedAtOp. Please add</technical_language>

Target:
private Rp sync(Rp rp) { if (!shouldSync(rp)) return rp; try { final RegisterResponse response = readClientFromRp(rp.getClientRegistrationClientUri(), rp.getClientRegistrationAccessToken()); boolean isRpUpdated = RegisterResponseMapper.fillRp(rp, response); if (isRpUpdated) { rp.setLastSynced(new Date()); persistenceService.update(rp); LOG.debug("Successfully synced Rp object from OP. Rp: " + rp.toString()); } return rp; } catch (Exception e) { LOG.error("Error in sync Rp object from OP: ", e); return rp; } }
Source:
<code>protected Result convert(DocumentToConceptIds source) { if (CollectionUtils.isNotEmpty(source.getConcepts())) { Result result = new Result(); result.setId(source.getDocumentId().toString()); List<Context> contexts = new ArrayList<Context>(source.getConcepts().size()); for (Concept concept : source.getConcepts()) { Context context = new Context(); context.setId(concept.getId().toString()); <START> context.setDataInfo(Arrays.asList(buildInferenceForTrustLevel(StaticConfigurationProvider.ACTION_TRUST_0_9))); <END> contexts.add(context); } result.setContext(contexts); return result; } else { return null; } }</code><technical_language>IDE Collections.singletonList</technical_language>

Target:
protected Result convert(DocumentToConceptIds source) { if (CollectionUtils.isNotEmpty(source.getConcepts())) { Result result = new Result(); result.setId(source.getDocumentId().toString()); List<Context> contexts = new ArrayList<Context>(source.getConcepts().size()); for (Concept concept : source.getConcepts()) { Context context = new Context(); context.setId(concept.getId().toString()); context.setDataInfo(Collections.singletonList(buildInferenceForTrustLevel(StaticConfigurationProvider.ACTION_TRUST_0_9))); contexts.add(context); } result.setContext(contexts); return result; } else { return null; } }
Source:
<code>public void setCommitId(String commitId) { <START> ModelNode node = this.getNode(); <END> ModelNode git = new ModelNode(); ModelNode author = new ModelNode(); ModelNode committer = new ModelNode(); ModelNode commit = new ModelNode(commitId); git.get(AUTHOR).set(author); git.get(COMMITTER).set(committer); git.get(COMMIT).set(commit); ModelNode revision = new ModelNode(); revision.get(GIT).set(git); revision.get(TYPE).set(BIGGIT); node.get(REVISION).set(revision); }</code><technical_language>helper methods here</technical_language>

Target:
public void setCommitId(String commitId) { set(REVISION_TYPE, BIGGIT); set(REVISION_GIT_COMMIT, commitId); }
Source:
<code>protected void precommitCheckPendingFiles( final JobContext context, final ActiveCommit pending) throws IOException { FileSystem sourceFS = pending.getSourceFS(); try (DurationInfo ignored = new DurationInfo(LOG, "Preflight Load of pending files")) { Tasks.foreach(pending.getSourceFiles()) .stopOnFailure() <START> .executeWith(buildThreadPool(context)) <END> .run(path -> PendingSet.load(sourceFS, path)); } }</code><technical_language>this explicitly call throwFailureWhenFinished()? I typically call suppressFailures() is obvious reader error is handled</technical_language>

Target:
protected void precommitCheckPendingFiles( final JobContext context, final ActiveCommit pending) throws IOException { FileSystem sourceFS = pending.getSourceFS(); try (DurationInfo ignored = new DurationInfo(LOG, "Preflight Load of pending files")) { Tasks.foreach(pending.getSourceFiles()) .stopOnFailure() .suppressExceptions(false) .executeWith(buildThreadPool(context)) .run(path -> PendingSet.load(sourceFS, path)); } }
Source:
<code>public void transform(NodeType node) { if (ComponentUtilities.getNodeProperty(node, name) == null) { ComponentUtilities.addNodeProperty(node, name, field); <START> ComponentUtilities.setNodeValue(node, name, "false"); <END> } }</code><technical_language>true ? (legacy SQL for jobs)</technical_language>

Target:
public void transform(NodeType node) { if (ComponentUtilities.getNodeProperty(node, name) == null) { ComponentUtilities.addNodeProperty(node, name, field); ComponentUtilities.setNodeValue(node, name, "true"); } }