auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void saveOrUpdateShouldNotDeleteOldestPasswordWhenPasswordHistoryShorterThanLimit() { List<PasswordHistoryEntity> passwordHistoryEntityList = getPasswordHistoryEntitylistWithElements(PASSWORD_HISTORY_LIMIT - 1); given(this.userRepository.findOne(USER_ID)).willReturn(userEntityWithId); given(this.passwordHistoryRepository.save(passwordHistoryEntityWithUserEntity)).willReturn(passwordHistoryEntityWithUserEntity); given(this.passwordHistoryRepository.findByUserEntity(userEntityWithId)).willReturn(passwordHistoryEntityList); <START> given(this.passwordHistoryRepository.findOldestPassword(USER_ID)).willReturn(passwordHistoryEntityList.get(0)); <END> this.passwordChangeService.saveOrUpdate(passwordHistoryDtoWithUserId); then(this.passwordHistoryRepository).should(never()).delete(passwordHistoryEntityList.get(0)); }</code><technical_language>This unnecessary</technical_language>

Target:
public void saveOrUpdateShouldNotDeleteOldestPasswordWhenPasswordHistoryShorterThanLimit() { List<PasswordHistoryEntity> passwordHistoryEntityList = getPasswordHistoryEntitylistWithElements(PASSWORD_HISTORY_LIMIT - 1); given(this.userRepository.findOne(USER_ID)).willReturn(userEntityWithId); given(this.passwordHistoryRepository.save(passwordHistoryEntityWithUserEntity)).willReturn(passwordHistoryEntityWithUserEntity); given(this.passwordHistoryRepository.findByUserEntity(userEntityWithId)).willReturn(passwordHistoryEntityList); this.passwordChangeService.saveOrUpdate(passwordHistoryDtoWithUserId); then(this.passwordHistoryRepository).should(never()).delete(passwordHistoryEntityList.get(0)); then(this.userRepository).should().findOne(USER_ID); then(this.passwordHistoryRepository).should().save(passwordHistoryEntityWithUserEntity); then(this.passwordHistoryRepository).should().findByUserEntity(userEntityWithId); }
Source:
<code>private String getLabelProviderContextForTreeFillingConfiguration(final Table table, final Object listenObject) { <START> if (listenObject instanceof EStructuralFeature) { <END> return Constants.HEADER_LABEL_PROVIDER_TREE_FILLING_FEATURE_CONFIGURATION_CONTEXT; } else if (listenObject instanceof EOperation) { return Constants.HEADER_LABEL_PROVIDER_TREE_FILLING_OPERATION_CONFIGURATION_CONTEXT; } else { return ""; } }</code><technical_language>Multi return is avoid</technical_language>

Target:
private String getLabelProviderContextForTreeFillingConfiguration(final Table table, final Object listenObject) { String result = ""; if (listenObject instanceof EStructuralFeature) { result = Constants.HEADER_LABEL_PROVIDER_TREE_FILLING_FEATURE_CONFIGURATION_CONTEXT; } else if (listenObject instanceof EOperation) { result = Constants.HEADER_LABEL_PROVIDER_TREE_FILLING_OPERATION_CONFIGURATION_CONTEXT; } return result; }
Source:
<code>public static Account create(String userName, String fullName, String firstName, String lastName, String emailAddress, List<RoleType> roles, AccountPhoneNumber phone, String department, String customDefined1, String customDefined2, AccountOrganization organization, String state) { return builder().userName(userName).fullName(fullName).firstName(firstName).lastName(lastName) .emailAddress(emailAddress) <START> .roles(roles == null ? ImmutableList.<RoleType>of() : ImmutableList.copyOf(roles)).phone(phone) <END> .department(department).customDefined1(customDefined1).customDefined2(customDefined2) .organization(organization).state(state).build(); }</code><technical_language>pass list parameter, move immutability logic builder [this pattern](<LINK_0></technical_language>

Target:
public static Account create(String userName, String fullName, String firstName, String lastName, String emailAddress, List<RoleType> roles, AccountPhoneNumber phone, String department, String customDefined1, String customDefined2, AccountOrganization organization, String state) { return builder().userName(userName).fullName(fullName).firstName(firstName).lastName(lastName) .emailAddress(emailAddress).roles(roles).phone(phone).department(department).customDefined1(customDefined1) .customDefined2(customDefined2).organization(organization).state(state).build(); }
Source:
<code>public void should_get_labels_json() throws Exception { HttpRequest request = server.client().GET("/api/i18n/labels.json"); assertThat(request.code()).isEqualTo(200); <START> assertThat(replaceNewLine(request.body())).isEqualTo("{\n" + <END> " \"key1\" : \"value1\",\n" + " \"key2\" : \"hello {{test}}\"\n" + "}\n"); }</code><technical_language>I String.format("%n") for platform specific line separators instead of introducing a new replaceNewLine() method alters "code test". => transform code : assertThat(request.body()).isEqualTo(String.format("{%n" + " \"key1\" : \"value1\",%n" + " \"key2\" : \"hello {{test}}\"%n" + "}%n")); WDYT</technical_language>

Target:
public void should_get_labels_json() throws Exception { HttpRequest request = server.client().GET("/api/i18n/labels.json"); assertThat(request.code()).isEqualTo(200); assertThat(request.body()).isEqualTo(String.format("{%n" + " \"key1\" : \"value1\",\n" + " \"key2\" : \"hello {{test}}\"\n" + "}%n")); }
Source:
<code>protected void dispatchToEntity(I id, Message eventMessage, EventContext context) { final P projection = loadOrCreate(id); projection.handle(eventMessage, context); store(projection); final Timestamp eventTime = context.getTimestamp(); <START> if (ongoingOperation != null && ongoingOperation.isInProgress()) { <END> scheduledStore(projection, eventTime); } else { immediateStore(projection, eventTime); } standFunnel.post(projection); }</code><technical_language>This line fully tested. Please check</technical_language>

Target:
protected void dispatchToEntity(I id, Message eventMessage, EventContext context) { final P projection = loadOrCreate(id); projection.handle(eventMessage, context); final Timestamp eventTime = context.getTimestamp(); if (isBulkWriteInProgress()) { storePostponed(projection, eventTime); } else { storeNow(projection, eventTime); } standFunnel.post(projection); }
Source:
<code>private CompletableFuture<Boolean> detect(Detector detector, InetAddress inetAddress, String location) { CompletableFuture<Boolean> future = new CompletableFuture<>(); try { Map<String, String> attributes = detector.getParameters().stream() .collect(Collectors.toMap(Parameter::getKey, Parameter::getValue)); CompletableFuture<Boolean> result = getLocationAwareDetectorClient().detect() .withAddress(inetAddress) .withClassName(detector.getClassName()) .withLocation(location) .withAttributes(attributes) .execute(); result.whenComplete((response, ex) -> { if (ex != null) { LOG.error("Exception while detecting service on IP Address at location ", detector.getName(), inetAddress.getHostAddress(), location, ex); future.complete(false); } else { <START> LOG.info("Detected service on IP Address at location {}", <END> detector.getName(), inetAddress.getHostAddress(), location); future.complete(response); } }); } catch (Exception e) { LOG.error("Exception while detecting service on IP Address at location ", detector.getName(), inetAddress.getHostAddress(), location, e); future.complete(false); } return future; }</code><technical_language>Detected is misleading here, result false</technical_language>

Target:
private CompletableFuture<Boolean> detect(Detector detector, InetAddress inetAddress, String location) { CompletableFuture<Boolean> future = new CompletableFuture<>(); try { LOG.info("Attemping to detect '{}' service on IP Address at location {}", detector.getName(), inetAddress.getHostAddress(), location); Map<String, String> attributes = detector.getParameters().stream() .collect(Collectors.toMap(Parameter::getKey, Parameter::getValue)); CompletableFuture<Boolean> result = getLocationAwareDetectorClient().detect() .withAddress(inetAddress) .withClassName(detector.getClassName()) .withLocation(location) .withAttributes(attributes) .execute(); result.whenComplete((response, ex) -> { Logging.withPrefix(Discovery.getLoggingCategory(), new Runnable() { @Override public void run() { if (ex != null) { LOG.error("Exception while detecting '{}' service on IP Address at location ", detector.getName(), inetAddress.getHostAddress(), location, ex); future.complete(false); } else { LOG.info("Service Detection for service '{}' on IP Address at location {}", response ? "succeeded" : "failed", detector.getName(), inetAddress.getHostAddress(), location); future.complete(response); } } }); }); } catch (Exception e) { LOG.error("Exception while detecting service on IP Address at location ", detector.getName(), inetAddress.getHostAddress(), location, e); future.complete(false); } return future; }
Source:
<code><START> public Counter counter(String metricName) { <END> return new CounterImpl(registry.counter(prefix + metricName)); }</code><technical_language>calls a null check check string .. I in this case if metricName null successfully concatenate string</technical_language>

Target:
public Counter counter(String metricName) { validateName(metricName); return new CounterImpl(registry.counter(prefix + metricName)); }
Source:
<code>public ReadBuffer(ByteBuffer byteBuffer) { <START> this(byteBuffer, byteBuffer.position() + byteBuffer.capacity()); <END> }</code><technical_language>If position() other 0 this give a LimitReachedException it? capacity - position</technical_language>

Target:
public ReadBuffer(ByteBuffer byteBuffer) { this(byteBuffer, byteBuffer.remaining()); }
Source:
<code>private RepositoryGroup getSelectedGroup(ExecutionEvent event) throws ExecutionException { List<RepositoryTreeNode> elements = getSelectedNodes(event); if (elements.size() == 1 && elements.get(0) instanceof RepositoryGroupNode) { return ((RepositoryGroupNode) elements.get(0)).getGroup(); } else { throw new ExecutionException( <START> "can rename only a single repository group"); END> } }</code><technical_language>Needs localizable</technical_language>

Target:
private RepositoryGroup getSelectedGroup(ExecutionEvent event) throws ExecutionException { List<RepositoryTreeNode> elements = getSelectedNodes(event); if (elements.size() == 1 && elements.get(0) instanceof RepositoryGroupNode) { return ((RepositoryGroupNode) elements.get(0)).getGroup(); } else { throw new ExecutionException( UIText.RepositoriesView_RepoGroup_Rename_IllegalSelection); } }
Source:
<code>private static void verifyDomainGettersSetters(TraceDomainComponent domain) { DomainEnum tmpDomain = domain.getDomain(); domain.setDomain(DomainEnum.KERNEL); assertEquals(domain.getDomain(), DomainEnum.KERNEL); domain.setDomain(DomainEnum.UST); assertEquals(domain.getDomain(), DomainEnum.UST); domain.setDomain(DomainEnum.JUL); assertEquals(domain.getDomain(), DomainEnum.JUL); <START> <END> ITraceControlComponent[] children = domain.getChildren(); TraceChannelComponent[] channels = domain.getChannels(); assertEquals(children.length, channels.length); for (int i = 0; i < channels.length; i++) { assertEquals(channels[i].getName(), children[i].getName()); } String nodeName = domain.getTargetNode().getName(); assertEquals(TARGET_NODE_NAME, nodeName); domain.setDomain(tmpDomain); }</code><technical_language>add other cases</technical_language>

Target:
private static void verifyDomainGettersSetters(TraceDomainComponent domain) { DomainEnum tmpDomain = domain.getDomain(); domain.setDomain(DomainEnum.KERNEL); assertEquals(domain.getDomain(), DomainEnum.KERNEL); domain.setDomain(DomainEnum.UST); assertEquals(domain.getDomain(), DomainEnum.UST); domain.setDomain(DomainEnum.JUL); assertEquals(domain.getDomain(), DomainEnum.JUL); domain.setDomain(DomainEnum.LOG4J); assertEquals(domain.getDomain(), DomainEnum.LOG4J); domain.setDomain(DomainEnum.PYTHON); assertEquals(domain.getDomain(), DomainEnum.PYTHON); domain.setDomain(DomainEnum.UNKNOWN); assertEquals(domain.getDomain(), DomainEnum.UNKNOWN); ITraceControlComponent[] children = domain.getChildren(); TraceChannelComponent[] channels = domain.getChannels(); assertEquals(children.length, channels.length); for (int i = 0; i < channels.length; i++) { assertEquals(channels[i].getName(), children[i].getName()); } String nodeName = domain.getTargetNode().getName(); assertEquals(TARGET_NODE_NAME, nodeName); domain.setDomain(tmpDomain); }
Source:
<code>public void init() { <START> super.init(); <END> if(userLayerDbService == null) { setUserLayerDbService(OskariComponentManager.getComponentOfType(UserLayerDbService.class)); } }</code><technical_language>Calling super.init(); is unnecessary, ActionHandlers implementation is empty</technical_language>

Target:
public void init() { userLayerDbService = OskariComponentManager.getComponentOfType(UserLayerDbService.class); }
Source:
<code>private InputStream simulateSendAndReceive(ByteArrayOutputStream baos) throws IOException { byte[] bytes = baos.toByteArray(); baos.reset(); <START> int testMessageNo = 1; <END> PacketFormat format = new PacketFormat(testMessageNo, bytes); format.serialize(baos); return new ByteArrayInputStream(baos.toByteArray()); }</code><technical_language>is this hardcoded? is 1 0</technical_language>

Target:
private InputStream simulateSendAndReceive(ByteArrayOutputStream baos) throws IOException { return new ByteArrayInputStream(baos.toByteArray()); }
Source:
<code>public void deserialize(byte[] message, Collector<RowData> out) throws IOException { GenericRowData row = (GenericRowData) jsonDeserializer.deserialize(message); GenericRowData payload; if (schemaInclude) { payload = (GenericRowData) row.getField(0); } else { payload = row; } GenericRowData before = (GenericRowData) payload.getField(0); GenericRowData after = (GenericRowData) payload.getField(1); String op = payload.getField(2).toString(); if (OP_CREATE.equals(op) && after != null) { after.setRowKind(RowKind.INSERT); out.collect(after); } else if (OP_UPDATE.equals(op) && (before != null && after != null)) { before.setRowKind(RowKind.UPDATE_BEFORE); after.setRowKind(RowKind.UPDATE_AFTER); out.collect(before); out.collect(after); } else if (OP_DELETE.equals(op) && before != null) { before.setRowKind(RowKind.DELETE); out.collect(before); } else { if (!ignoreParseErrors) { throw new IOException(format("Failed to deserialize Debezium JSON '%s'.", new String(message))); <START> } <END> } }</code><technical_language>Give more detailed message deserialization fails</technical_language>

Target:
public void deserialize(byte[] message, Collector<RowData> out) throws IOException { try { GenericRowData row = (GenericRowData) jsonDeserializer.deserialize(message); GenericRowData payload; if (schemaInclude) { payload = (GenericRowData) row.getField(0); } else { payload = row; } GenericRowData before = (GenericRowData) payload.getField(0); GenericRowData after = (GenericRowData) payload.getField(1); String op = payload.getField(2).toString(); if (OP_CREATE.equals(op) || OP_READ.equals(op)) { after.setRowKind(RowKind.INSERT); out.collect(after); } else if (OP_UPDATE.equals(op)) { before.setRowKind(RowKind.UPDATE_BEFORE); after.setRowKind(RowKind.UPDATE_AFTER); out.collect(before); out.collect(after); } else if (OP_DELETE.equals(op)) { before.setRowKind(RowKind.DELETE); out.collect(before); } else { if (!ignoreParseErrors) { throw new IOException(format( "Unknown \"op\" value \"%s\". The Debezium JSON message is '%s'", op, new String(message))); } } } catch (Throwable t) { if (!ignoreParseErrors) { throw new IOException(format( "Corrupt Debezium JSON message '%s'.", new String(message)), t); } } }
Source:
<code>private int update(final Talk talk, final int max) throws IOException { final List<String> requests = talk.read().xpath(" final List<XML> logs = talk.read().nodes(ARCHIVE_LOG); int newmax = max; int index = this.max(talk); if (index < 1) { index = max; } if (requests.isEmpty() && !logs.isEmpty()) { talk.modify( new Directives().xpath(" .attr(INDEX, Integer.toString(index + 1)) .attr("id", this.createRequestId()) .add("type").set(INDEX) .up() .add("args") ); newmax += 1; } <START> return newmax; <END> }</code><technical_language>again, this method is is supposed do. set index of request max, if a request exists. if exists sets @index, return max+1. otherwise, return max. this is logic. implement different. supposed create /talk/request element in this class</technical_language>

Target:
private int update(final Talk talk, final int max) throws IOException { final List<XML> logs = talk.read().nodes(" int newmax = max; int index = this.max(talk); if (index < 1) { index = max; } final List<XML> nodes = talk.read() .nodes(" if (!nodes.isEmpty() && !logs.isEmpty()) { talk.modify(new Directives() .xpath("( .attr("index", Integer.toString(index + 1))); newmax += 1; } return newmax; }
Source:
<code>public ModelAndView question(@PathVariable long questionId, @RequestParam(value = "index", defaultValue = "1", required = false) int index) { QuestionDto question = questionService.getQuestion(LoginUserInfo.getLoginName(), questionId); if (question == null) { <START> ModelAndView modelAndView = new ModelAndView("error/404"); <END> modelAndView.addObject("errorPage","true"); return modelAndView; } ModelAndView modelAndView = new ModelAndView("/question", "questionId", questionId); modelAndView.addObject("isQuestionOwner", !StringUtils.isEmpty(question.getMobile()) && question.getMobile().equalsIgnoreCase(LoginUserInfo.getMobile())); modelAndView.addObject("question", question); modelAndView.addObject("bestAnswer", answerService.getBestAnswer(LoginUserInfo.getLoginName(), questionId)); modelAndView.addObject("answers", answerService.getNotBestAnswers(LoginUserInfo.getLoginName(), questionId, index, 10)); return modelAndView; }</code><technical_language>/error/404</technical_language>

Target:
public ModelAndView question(@PathVariable long questionId, @RequestParam(value = "index", defaultValue = "1", required = false) int index) { QuestionDto question = questionService.getQuestion(LoginUserInfo.getLoginName(), questionId); if (question == null) { ModelAndView modelAndView = new ModelAndView("/error/404"); modelAndView.addObject("errorPage","true"); return modelAndView; } ModelAndView modelAndView = new ModelAndView("/question", "questionId", questionId); modelAndView.addObject("isQuestionOwner", !StringUtils.isEmpty(question.getMobile()) && question.getMobile().equalsIgnoreCase(LoginUserInfo.getMobile())); modelAndView.addObject("question", question); modelAndView.addObject("bestAnswer", answerService.getBestAnswer(LoginUserInfo.getLoginName(), questionId)); modelAndView.addObject("answers", answerService.getNotBestAnswers(LoginUserInfo.getLoginName(), questionId, index, 10)); return modelAndView; }
Source:
<code>public void activate(final Subscription subscription, final StreamObserver<SubscriptionUpdate> responseObserver) { log().debug("Activating the subscription: {}", subscription); try { final BoundedContext boundedContext = selectBoundedContext(subscription); final Stand.StandUpdateCallback updateCallback = new Stand.StandUpdateCallback() { @Override public void onEntityStateUpdate(Any newEntityState) { Preconditions.checkNotNull(subscription); final SubscriptionUpdate update = SubscriptionUpdate.newBuilder() .setSubscription(subscription) .setResponse(Responses.ok()) .addUpdates(newEntityState) .build(); responseObserver.onNext(update); } }; <START> boundedContext.getStand().activate(subscription, updateCallback); <END> } catch (@SuppressWarnings("OverlyBroadCatchBlock") Exception e) { log().error("Error activating the subscription", e); responseObserver.onError(e); responseObserver.onCompleted(); } }</code><technical_language>wrap getStand() here</technical_language>

Target:
public void activate(final Subscription subscription, final StreamObserver<SubscriptionUpdate> responseObserver) { log().debug("Activating the subscription: {}", subscription); try { final BoundedContext boundedContext = selectBoundedContext(subscription); final Stand.EntityUpdateCallback updateCallback = new Stand.EntityUpdateCallback() { @Override public void onStateChanged(Any newEntityState) { checkNotNull(subscription); final SubscriptionUpdate update = SubscriptionUpdate.newBuilder() .setSubscription(subscription) .setResponse(Responses.ok()) .addUpdates(newEntityState) .build(); responseObserver.onNext(update); } }; final Stand targetStand = boundedContext.getStand(); targetStand.activate(subscription, updateCallback); } catch (@SuppressWarnings("OverlyBroadCatchBlock") Exception e) { log().error("Error activating the subscription", e); responseObserver.onError(e); } }
Source:
<code>public void run() { try { while (watchService != null) { <START> WatchKey key = watchService.take(); <END> Path watchedPath = (Path) key.watchable(); Map<String, List<Store>> pathRegistration = watchedPaths.get(watchedPath); if (pathRegistration != null) { for (WatchEvent<?> event : key.pollEvents()) { if (StandardWatchEventKinds.ENTRY_CREATE.equals(event.kind()) || StandardWatchEventKinds.ENTRY_MODIFY.equals(event.kind())) { Path context = (Path) event.context(); String name = context.getFileName().toString(); List<Store> stores = pathRegistration.get(name); if (stores != null) { for (Store current : stores) { executor.execute(new Notifier(current)); } } } else if (StandardWatchEventKinds.OVERFLOW.equals(event.kind())) { for (List<Store> stores : pathRegistration.values()) { for (Store current : stores) { executor.execute(new Notifier(current)); } } } } } key.reset(); } } catch (ClosedWatchServiceException | InterruptedException e) { } }</code><technical_language>NPE risk here. watchService field copied a local variable test in case is changed null in another thread "while" call .take()</technical_language>

Target:
public void run() { try { WatchService watchService = KeyStoreWatcher.this.watchService; while (watchService != null) { WatchKey key = watchService.take(); Path watchedPath = (Path) key.watchable(); System.out.println("Path " + watchedPath.toString()); Map<String, List<Store>> pathRegistration = watchedPaths.get(watchedPath); Set<Store> toNotify = new HashSet<Store>(); if (pathRegistration != null) { for (WatchEvent<?> event : key.pollEvents()) { System.out.println("Event Name " + event.kind().name()); if (StandardWatchEventKinds.ENTRY_CREATE.equals(event.kind()) || StandardWatchEventKinds.ENTRY_MODIFY.equals(event.kind())) { Path context = (Path) event.context(); String name = context.getFileName().toString(); System.out.println("File Name " + name); List<Store> stores = pathRegistration.get(name); if (stores != null) { for (Store current : stores) { toNotify.add(current); } } } else if (StandardWatchEventKinds.OVERFLOW.equals(event.kind())) { for (List<Store> stores : pathRegistration.values()) { for (Store current : stores) { toNotify.add(current); } } } } } key.reset(); for (Store current : toNotify) { current.modified(); } } } catch (ClosedWatchServiceException | InterruptedException e) { } }
Source:
<code>public void newFolderWithGivenPathThrowsIOExceptionIfFolderNamesConsistOfMultiplePathComponents() throws IOException { thrown.expect(IOException.class); thrown.expectMessage("name cannot consist of multiple path components"); <START> tempFolder.create(); <END> tempFolder.newFolder("temp1", "temp2", "temp3/temp4"); }</code><technical_language>This line thrown.expect... calls, exception thrown tempFolder.newFolder</technical_language>

Target:
public void newFolderWithGivenPathThrowsIOExceptionIfFolderNamesConsistOfMultiplePathComponents() throws IOException { tempFolder.create(); thrown.expect(IOException.class); thrown.expectMessage("name cannot consist of multiple path components"); tempFolder.newFolder("temp1", "temp2", "temp3/temp4"); }
Source:
<code><START> public static void setInForeground(boolean inForeground) { <END> OneSignal.inForeground = inForeground; logger.debug("Foreground set to: " + inForeground); }</code><technical_language>want this a public method, called internally SDK</technical_language>

Target:
static void setInForeground(boolean inForeground) { OneSignal.inForeground = inForeground; }
Source:
<code>public Compressor getCompressor(Algorithm compressionAlgorithm) throws IOException { Preconditions.checkNotNull(compressionAlgorithm, "Algorithm cannot be null"); try { return compressorPool.borrowObject(compressionAlgorithm); <START> } catch (Exception e) { <END> LOG.warn("Could not borrow compressor; creating instead", e); return compressionAlgorithm.getCodec().createCompressor(); } }</code><technical_language>Commons-Pool give a named exception differentiate Pool failing construct a new instance some pool operation failing? (your catch Exception clause)</technical_language>

Target:
public Compressor getCompressor(Algorithm compressionAlgorithm) throws IOException { Objects.requireNonNull(compressionAlgorithm, "Algorithm cannot be null"); try { return compressorPool.borrowObject(compressionAlgorithm); } catch (Exception e) { LOG.warn("Could not borrow compressor; creating instead", e); return compressionAlgorithm.getCodec().createCompressor(); } }
Source:
<code>public long size() throws IOException { <START> flushIfNeeded(0); END> return writeOutBytes; }</code><technical_language>I this is cleaner public long size() { return writeOutBytes; }</technical_language>

Target:
public long size() { return writeOutBytes; }
Source:
<code><START> public int getNumberOfEntries() { <END> int totalEntries = 0; for (String cn : cm.getCacheNames()) { if (cm.cacheExists(cn)) { Stats stats = cm.getCache(cn).getAdvancedCache().getStats(); totalEntries += stats.getTotalNumberOfEntries(); } } return totalEntries; }</code><technical_language><LINK_0> fixed, align this class size methods. in this case want "local-only" count</technical_language>

Target:
public int getNumberOfEntries() { int totalEntries = 0; for (String cn : cm.getCacheNames()) { if (cm.cacheExists(cn)) { Stats stats = cm.getCache(cn).getAdvancedCache().getStats(); int numberOfEntries = stats.getCurrentNumberOfEntries(); if (numberOfEntries > -1) { totalEntries += numberOfEntries; } } } return totalEntries; }
Source:
<code>public IStatus run(IProgressMonitor monitor) { HybridProject hybridProject = HybridProject.getHybridProject(project); if(hybridProject != null){ try{ <START> if(hybridProject.getEngineManager().getActiveEngines().length != 0) { <END> hybridProject.prepare(monitor); } }catch(CoreException e){ return e.getStatus(); } } return Status.OK_STATUS; }</code><technical_language>this check a utility EngineManager</technical_language>

Target:
public IStatus run(IProgressMonitor monitor) { HybridProject hybridProject = HybridProject.getHybridProject(project); if(hybridProject != null){ try{ if(hybridProject.getEngineManager().hasActiveEngine()) { hybridProject.prepare(monitor); } }catch(CoreException e){ return e.getStatus(); } } return Status.OK_STATUS; }
Source:
<code>static void parameterValue(JSONObject param, StringBuilder sb) { Object value = param.get("value"); Object type = param.get("type"); if ("submissionParameter".equals(type)) { JSONObject jo = (JSONObject) value; String splType = (String) jo.get("splType"); <START> String name = SPLGenerator.stringLiteral((String) jo.get("name")); <END> String defaultValue = (String) jo.get("defaultValue"); if (defaultValue == null) sb.append(String.format("(%s) getSubmissionTimeValue(%s)", splType, name)); else { defaultValue = SPLGenerator.stringLiteral(defaultValue); sb.append(String.format("(%s) getSubmissionTimeValue(%s, %s)", splType, name, defaultValue)); } return; } else if (value instanceof String && !PARAM_TYPES_TOSTRING.contains(type)) { SPLGenerator.stringLiteral(sb, value.toString()); return; } else if (value instanceof JSONArray) { JSONArray a = (JSONArray) value; for (int i = 0; i < a.size(); i++) { if (i != 0) sb.append(", "); String sv = (String) a.get(i); SPLGenerator.stringLiteral(sb, sv); } return; } else if (value instanceof Number) { SPLGenerator.numberLiteral(sb, (Number) value); return; } sb.append(value); }</code><technical_language>a parameter name need escaping a string literal</technical_language>

Target:
static void parameterValue(JSONObject param, StringBuilder sb) { Object value = param.get("value"); Object type = param.get("type"); if ("submissionParameter".equals(type)) { SubmissionTimeValue.generateRef((JSONObject) value, sb); return; } else if (value instanceof String && !PARAM_TYPES_TOSTRING.contains(type)) { if ("ustring".equals(type)) sb.append("(ustring)"); SPLGenerator.stringLiteral(sb, value.toString()); return; } else if (value instanceof JSONArray) { JSONArray a = (JSONArray) value; for (int i = 0; i < a.size(); i++) { if (i != 0) sb.append(", "); String sv = (String) a.get(i); SPLGenerator.stringLiteral(sb, sv); } return; } else if (value instanceof Number) { SPLGenerator.numberLiteral(sb, (Number) value, "unsigned".equals(type)); return; } sb.append(value); }
Source:
<code><START> private List<VirtualGuestBlockDevice> getBlockDevices(List<Integer> blockDeviceCapacities, String diskType) { <END> List<VirtualGuestBlockDevice> blockDevices = Lists.newArrayList(); int devicePosition = 0; for (int i = 0; i < blockDeviceCapacities.size(); i++) { if (i > 0) { devicePosition = i + 1; } blockDevices.add(VirtualGuestBlockDevice.builder() .device(devicePosition + "") .diskImage(VirtualDiskImage.builder() .capacity(blockDeviceCapacities.get(i)) .typeId(Type.valueOf(diskType).ordinal()) .build()) .build()); } return blockDevices; }</code><technical_language>[minor] below, of methods static</technical_language>

Target:
private static List<VirtualGuestBlockDevice> getBlockDevices(List<Integer> blockDeviceCapacities, String diskType) { ImmutableList.Builder<VirtualGuestBlockDevice> blockDevicesBuilder = ImmutableList.builder(); int devicePosition = 0; for (int i = 0; i < blockDeviceCapacities.size(); i++) { if (i > 0) { devicePosition = i + 1; } blockDevicesBuilder.add(VirtualGuestBlockDevice.builder() .device(devicePosition + "") .diskImage(VirtualDiskImage.builder() .capacity(blockDeviceCapacities.get(i)) .typeId(Type.valueOf(diskType).ordinal()) .build()) .build()); } return blockDevicesBuilder.build(); }
Source:
<code>public Settings(String serverURI, String username, String password) { <START> if (serverURI.endsWith("/")) { <END> this.serverURI = serverURI.substring(0, serverURI.length() - 1); } else { this.serverURI = serverURI; } this.username = username; this.password = password; }</code><technical_language>Including this logic construct level is idea. If I setter instead of constructor provide server URL this invoked manifest again</technical_language>

Target:
public Settings(String serverURI, String username, String password) { this.serverURI = serverURI; this.username = username; this.password = password; }
Source:
<code>public void setBlock(int x, int y, int z, BlockState block) { net.minecraft.world.World world = ((net.minecraft.world.World) (Object) this); if (block instanceof IBlockState) { world.setBlockState(new BlockPos(x, y, z), (IBlockState) block, 0); } else { <START> throw new UnsupportedOperationException(); <END> } }</code><technical_language>some kind of error message here</technical_language>

Target:
public void setBlock(int x, int y, int z, BlockState block) { SpongeHooks.setBlockState(((net.minecraft.world.World) (Object) this), x, y, z, block); }
Source:
<code>public void aggregate(ByteBuffer buf, int position) { if (buf.get(position) == BYTE_FLAG_IS_NOT_SET) { buf.putDouble(position + Byte.BYTES, valueSelector.getDouble()); <START> buf.put(position, BYTE_FLAG_IS_SET); <END> } }</code><technical_language>nit: suggest setting IS_SET byte double value, order in buffer</technical_language>

Target:
public void aggregate(ByteBuffer buf, int position) { if (buf.get(position) == BYTE_FLAG_IS_NOT_SET) { buf.put(position, BYTE_FLAG_IS_SET); buf.putDouble(position + Byte.BYTES, valueSelector.getDouble()); } }
Source:
<code>private LuceneBackendResources(LuceneBackendResources previous) { this.indexManager = previous.indexManager; this.indexName = previous.indexName; this.errorHandler = previous.errorHandler; this.workspace = previous.workspace; this.maxQueueLength = previous.maxQueueLength; <START> this.asyncIndexingExecutor = previous.asyncIndexingExecutor; <END> this.indexmodificationReadLock = previous.indexmodificationReadLock; this.indexmodificationWriteLock = previous.indexmodificationWriteLock; this.executorStateReadLock = previous.executorStateReadLock; this.executorStateWriteLock = previous.executorStateWriteLock; }</code><technical_language>this protected locking previous.executorStateReadLock? attribute is longer volatile, necessary... ? Also, I if executor + readLock + writeLock stuff encapsulated in a separate object... I find dangerous is copied executor, call shutdown a previous LuceneBackendResources, shut executor clean asyncIndexingExecutor attribute new LuceneBackendResources happened share executor. tasks submitted handled. a single, shared object hold references locks *and* executor solve issue. Then, starting shutting executor, change attribute of LuceneBackendResources, attribute of single, shared object referenced LuceneBackendResources, is slightly different. another mechanism guarantees call a method a previous version of resources created a new version</technical_language>

Target:
private LuceneBackendResources(LuceneBackendResources previous) { this.indexManager = previous.indexManager; this.indexName = previous.indexName; this.errorHandler = previous.errorHandler; this.workspace = previous.workspace; this.readLock = previous.readLock; this.writeLock = previous.writeLock; this.asynchExecutor = previous.asynchExecutor; }
Source:
<code>private static int getOffset() { if (testMode == TestMode.PLAYBACK) { <START> return -1; <END> } LocalDate today = LocalDate.now(ZoneId.systemDefault()); return (today.getDayOfWeek().getValue() + getPlatFormOffset()) % PLATFORM_COUNT; }</code><technical_language>If env variable is set rolling test is run in PLAYBACK mode, argument list empty offset -1 match of entries in matrix. Usually, HTTP_CLIENT_FROM_ENV SERVICE_VERSION_FROM_ENV set if AZURE_TEST_MODE is set generally a problem avoid making assumption here</technical_language>

Target:
private static int getOffset() { if (testMode == TestMode.PLAYBACK) { return 0; } LocalDate today = LocalDate.now(ZoneId.systemDefault()); return (today.getDayOfWeek().getValue() + getPlatFormOffset()) % PLATFORM_LIST.size(); }
Source:
<code>private boolean shouldShowPicturesInCurrentNetwork(boolean onlyShowViaWiFi) { if (!onlyShowViaWiFi) { return true; } <START> final ConnectivityManager connectivityManager = <END> (ConnectivityManager) getContext().getSystemService(Context.CONNECTIVITY_SERVICE); NetworkType networkType = NetworkType.fromConnectivityManagerType(connectivityManager.getActiveNetworkInfo().getType()); return networkType == NetworkType.WIFI; }</code><technical_language>this logic isolated in a method, live in a view</technical_language>

Target:
private boolean shouldShowPicturesInCurrentNetwork(boolean onlyShowViaWiFi) { return !onlyShowViaWiFi || !NetworkHelper.isActiveNetworkMeteredCompat(); }
Source:
<code>void verifyQueryBehavior(@Nullable TestItem actualItem) { verify(storIOSQLite).get(); verify(getResolver).performGet(storIOSQLite, query); <START> verify(getResolver, times(1)).mapFromCursor(cursor); <END> verify(cursor).getCount(); verify(cursor, times(1)).moveToNext(); verify(cursor, times(1)).close(); assertThat(actualItem).isEqualTo(item); if (withTypeMapping) { verify(storIOSQLite).internal(); verify(internal).typeMapping(TestItem.class); verify(typeMapping).getResolver(); } verifyNoMoreInteractions(storIOSQLite, internal, cursor); }</code><technical_language>times(1) is default behavior of verify, removed, again, if copied code :)</technical_language>

Target:
void verifyQueryBehavior(@Nullable TestItem actualItem) { verify(storIOSQLite).get(); verify(getResolver).performGet(storIOSQLite, query); verify(getResolver).mapFromCursor(cursor); verify(cursor).getCount(); verify(cursor).moveToNext(); verify(cursor).close(); assertThat(actualItem).isEqualTo(item); if (withTypeMapping) { verify(storIOSQLite).internal(); verify(internal).typeMapping(TestItem.class); verify(typeMapping).getResolver(); } verifyNoMoreInteractions(storIOSQLite, internal, cursor); }
Source:
<code>public final void send(final RawData msg) { if (msg == null) { throw new NullPointerException("Message must not be null"); } else if (!running.get()) { throw new IllegalStateException("connector must be started before sending messages is possible"); } else if (msg.getBytes().length > MAX_PLAINTEXT_FRAGMENT_LENGTH) { throw new IllegalArgumentException("Message data must not exceed " + MAX_PLAINTEXT_FRAGMENT_LENGTH + " bytes"); } else { <START> if (0 <= pendingOutboundMessages.decrementAndGet()) { <END> executor.execute(new StripedRunnable() { @Override public Object getStripe() { return msg.getEndpointContext().getPeerAddress(); } @Override public void run() { try { pendingOutboundMessages.incrementAndGet(); if (running.get()) { sendMessage(msg); } } catch (Exception e) { if (running.get()) { LOGGER.debug("Exception thrown by executor thread [{}]", Thread.currentThread().getName(), e); } } finally { pendingOutboundMessages.incrementAndGet(); } } }); } else { pendingOutboundMessages.incrementAndGet(); LOGGER.warn("Outbound message overflow! Dropping outbound message to peer [{}]", msg.getInetSocketAddress()); } } }</code><technical_language>MISRA ghost</technical_language>

Target:
public final void send(final RawData msg) { if (msg == null) { throw new NullPointerException("Message must not be null"); } else if (!running.get()) { throw new IllegalStateException("connector must be started before sending messages is possible"); } else if (msg.getBytes().length > MAX_PLAINTEXT_FRAGMENT_LENGTH) { throw new IllegalArgumentException("Message data must not exceed " + MAX_PLAINTEXT_FRAGMENT_LENGTH + " bytes"); } else { if (pendingOutboundMessages.decrementAndGet() >= 0) { executor.execute(new StripedRunnable() { @Override public Object getStripe() { return msg.getEndpointContext().getPeerAddress(); } @Override public void run() { try { pendingOutboundMessages.incrementAndGet(); if (running.get()) { sendMessage(msg); } } catch (Exception e) { if (running.get()) { LOGGER.debug("Exception thrown by executor thread [{}]", Thread.currentThread().getName(), e); } } finally { pendingOutboundMessages.incrementAndGet(); } } }); } else { pendingOutboundMessages.incrementAndGet(); LOGGER.warn("Outbound message overflow! Dropping outbound message to peer [{}]", msg.getInetSocketAddress()); } } }
Source:
<code>public Regions getRegions () { <START> return regions; <END> }</code><technical_language>consistent in referencing member variables. Is regions this.regions? I prefer more explicit/clear</technical_language>

Target:
public Regions getRegions () { return this.regions; }
Source:
<code>private long getCachedStartIndex(Path path) { Long startIndexForFile = startIndexMap.get(path); if (startIndexForFile == null) { try { FSDataInputStream fis = path.getFileSystem(conf).open(path); for (int j = 0; j < headerCount; j++) { fis.readLine(); <START> startIndexForFile = fis.getPos() - 1; <END> } } catch (IOException e) { startIndexForFile = 0L; } startIndexMap.put(path, startIndexForFile); } return startIndexForFile; }</code><technical_language>move this loop? Also, current logic, if data footer rows headerCount=0, startIndexForFile null. this statement loop handle it</technical_language>

Target:
private long getCachedStartIndex(Path path) throws IOException { if (headerCount == 0) { return 0; } Long startIndexForFile = startIndexMap.get(path); if (startIndexForFile == null) { FileSystem fileSystem; FSDataInputStream fis = null; fileSystem = path.getFileSystem(conf); try { fis = fileSystem.open(path); for (int j = 0; j < headerCount; j++) { if (fis.readLine() == null) { startIndexMap.put(path, Long.MAX_VALUE); return Long.MAX_VALUE; } } startIndexForFile = fis.getPos() - 1; } finally { if (fis != null) { fis.close(); } } startIndexMap.put(path, startIndexForFile); } return startIndexForFile; }
Source:
<code>private static void invokeWithTimeoutWithNoExecutor( ITestNGMethod tm, Object instance, Object[] parameterValues, ITestResult testResult, IHookable hookable) { InvokeMethodRunnable imr = new InvokeMethodRunnable(tm, instance, parameterValues, hookable, testResult); long startTime = System.currentTimeMillis(); long realTimeOut = MethodHelper.calculateTimeOut(tm); boolean notTimedout = true; try { Thread currentThread = Thread.currentThread(); new Thread(() -> { try { TimeUnit.MILLISECONDS.sleep(realTimeOut); } catch (InterruptedException e) { } currentThread.interrupt(); }).start(); imr.run(); notTimedout = System.currentTimeMillis() <= startTime + realTimeOut; if (notTimedout) { testResult.setStatus(ITestResult.SUCCESS); } else { ThreadTimeoutException exception = new ThreadTimeoutException( "Method " + tm.getQualifiedName() + "()" + " didn't finish within the time-out " + realTimeOut); testResult.setThrowable(exception); testResult.setStatus(ITestResult.FAILURE); } } catch (Exception ex) { <START> if (! notTimedout) { <END> ThreadTimeoutException exception = new ThreadTimeoutException( "Method " + tm.getQualifiedName() + "()" + " didn't finish within the time-out " + realTimeOut); testResult.setThrowable(exception); } else { testResult.setThrowable(ex.getCause()); } testResult.setStatus(ITestResult.FAILURE); } }</code><technical_language>Prefer a positive condition</technical_language>

Target:
private static void invokeWithTimeoutWithNoExecutor( ITestNGMethod tm, Object instance, Object[] parameterValues, ITestResult testResult, IHookable hookable) { InvokeMethodRunnable imr = new InvokeMethodRunnable(tm, instance, parameterValues, hookable, testResult); long startTime = System.currentTimeMillis(); long realTimeOut = MethodHelper.calculateTimeOut(tm); boolean notTimedout = true; try { Thread currentThread = Thread.currentThread(); new Thread(() -> { try { TimeUnit.MILLISECONDS.sleep(realTimeOut); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } currentThread.interrupt(); }).start(); imr.run(); notTimedout = System.currentTimeMillis() <= startTime + realTimeOut; if (notTimedout) { testResult.setStatus(ITestResult.SUCCESS); } else { ThreadTimeoutException exception = new ThreadTimeoutException( "Method " + tm.getQualifiedName() + "()" + " didn't finish within the time-out " + realTimeOut); testResult.setThrowable(exception); testResult.setStatus(ITestResult.FAILURE); } } catch (Exception ex) { if (notTimedout) { testResult.setThrowable(ex.getCause()); } else { ThreadTimeoutException exception = new ThreadTimeoutException( "Method " + tm.getQualifiedName() + "()" + " didn't finish within the time-out " + realTimeOut); testResult.setThrowable(exception); } testResult.setStatus(ITestResult.FAILURE); } }
Source:
<code>public Enum parseEnum(T object) { Error.push("parseEnum"); try { if (object != null) { String name = getStringProperty(object, STR_NAME); if (name == null) { throw Error.get(MetadataConstants.ERR_PARSE_MISSING_ELEMENT, STR_NAME); } Enum e = new Enum(name); List<String> values = getStringList(object, STR_VALUES); List<T> annotatedValues = getObjectList(object, STR_ANNOTATED_VALUES); Set<EnumValue> enumValues = new HashSet<EnumValue>(); <START> if((values != null) && (annotatedValues != null)){ <END> throw Error.get(MetadataConstants.ERR_INCOMPATIBLE_VALUE, STR_VALUES + " and " + STR_ANNOTATED_VALUES + " cannot both be defined."); } else if(values != null){ for(String string : values){ enumValues.add(new EnumValue(e.getName(), string, null)); } } else if(annotatedValues != null){ for(T value : annotatedValues){ EnumValue enumValue = new EnumValue(e.getName()); enumValue.setName(getRequiredStringProperty(value, STR_NAME)); enumValue.setDescription(getStringProperty(value, STR_DESCRIPTION)); enumValues.add(enumValue); } } if(enumValues.isEmpty()){ throw Error.get(MetadataConstants.ERR_PARSE_MISSING_ELEMENT, STR_VALUES); } e.setValues(enumValues); return e; } else { return null; } } catch (Error e) { throw e; } catch (Exception e) { LOGGER.error(e.getMessage(), e); throw Error.get(MetadataConstants.ERR_ILL_FORMED_METADATA, e.getMessage()); } finally { Error.pop(); } }</code><technical_language>Need this fail. ignore values. folks develop metadata in instance of lightblue openshift copy final metadata out for deployment managed environments. discussed means enums name, values, annotatedValues</technical_language>

Target:
public Enum parseEnum(T object) { Error.push("parseEnum"); try { if (object != null) { String name = getStringProperty(object, STR_NAME); if (name == null) { throw Error.get(MetadataConstants.ERR_PARSE_MISSING_ELEMENT, STR_NAME); } Enum e = new Enum(name); List<String> values = getStringList(object, STR_VALUES); List<T> annotatedValues = getObjectList(object, STR_ANNOTATED_VALUES); Set<EnumValue> enumValues = new HashSet<EnumValue>(); if(annotatedValues != null){ for(T value : annotatedValues){ EnumValue enumValue = new EnumValue(); enumValue.setName(getRequiredStringProperty(value, STR_NAME)); enumValue.setDescription(getRequiredStringProperty(value, STR_DESCRIPTION)); enumValues.add(enumValue); } } else if(values != null){ for(String string : values){ enumValues.add(new EnumValue(string, null)); } } if(enumValues.isEmpty()){ throw Error.get(MetadataConstants.ERR_PARSE_MISSING_ELEMENT, STR_VALUES); } e.setValues(enumValues); return e; } else { return null; } } catch (Error e) { throw e; } catch (Exception e) { LOGGER.error(e.getMessage(), e); throw Error.get(MetadataConstants.ERR_ILL_FORMED_METADATA, e.getMessage()); } finally { Error.pop(); } }
Source:
<code>private void factHandleSerialization(final boolean withOOPath) { final String str = "package org.kie.test\n" + "import java.util.concurrent.atomic.AtomicInteger\n" + "global java.util.List list\n" + "rule rule1\n" + "when\n" + (withOOPath ? " AtomicInteger($i: /intValue{this > 0})\n" : " $i: AtomicInteger(intValue > 0)\n") + "then\n" + " list.add( $i );\n" + "end\n" + "\n"; final KieBase kbase = new KieHelper().addContent(str, ResourceType.DRL).build(); KieSession ksession = KieServices.get().getStoreServices().newKieSession(kbase, null, env); List<?> list = new ArrayList<>(); ksession.setGlobal("list", list); final AtomicInteger value = new AtomicInteger(4); FactHandle atomicFH = ksession.insert(value); ksession.fireAllRules(); assertEquals(1, list.size()); value.addAndGet(1); ksession.update(atomicFH, value); ksession.fireAllRules(); assertEquals(2, list.size()); final String externalForm = atomicFH.toExternalForm(); ksession = KieServices.get().getStoreServices().loadKieSession(ksession.getIdentifier(), kbase, null, env); atomicFH = ksession.execute(CommandFactory.fromExternalFactHandleCommand(externalForm)); value.addAndGet(1); ksession.update(atomicFH, value); ksession.fireAllRules(); list = (List<?>) ksession.getGlobal("list"); <START> assertEquals(3, list.size()); <END> }</code><technical_language>AssertJ is friend. Assertions.assertThat(list).hasSize(3); test fail for vast difference in failure message if do that</technical_language>

Target:
private void factHandleSerialization(final boolean withOOPath) { final String str = "package org.kie.test\n" + "import java.util.concurrent.atomic.AtomicInteger\n" + "global java.util.List list\n" + "rule rule1\n" + "when\n" + (withOOPath ? " AtomicInteger($i: /intValue{this > 0})\n" : " $i: AtomicInteger(intValue > 0)\n") + "then\n" + " list.add( $i );\n" + "end\n" + "\n"; final KieBase kbase = new KieHelper().addContent(str, ResourceType.DRL).build(); KieSession ksession = KieServices.get().getStoreServices().newKieSession(kbase, null, env); List<AtomicInteger> list = new ArrayList<>(); ksession.setGlobal("list", list); final AtomicInteger value = new AtomicInteger(4); FactHandle atomicFH = ksession.insert(value); ksession.fireAllRules(); assertThat(list).hasSize(1); value.addAndGet(1); ksession.update(atomicFH, value); ksession.fireAllRules(); assertThat(list).hasSize(2); final String externalForm = atomicFH.toExternalForm(); ksession = KieServices.get().getStoreServices().loadKieSession(ksession.getIdentifier(), kbase, null, env); atomicFH = ksession.execute(CommandFactory.fromExternalFactHandleCommand(externalForm)); value.addAndGet(1); ksession.update(atomicFH, value); ksession.fireAllRules(); list = (List<AtomicInteger>) ksession.getGlobal("list"); assertThat(list).hasSize(3); }
Source:
<code><START> public QueueAsyncClient createQueue(String queueName) { <END> return createQueue(queueName, null); }</code><technical_language>Interesting - 'createQueue' previously</technical_language>

Target:
public Mono<Response<QueueAsyncClient>> createQueue(String queueName) { return createQueue(queueName, null); }