auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected static StereotypeModel getStereotype(StereotypeDefinition stereotypeDefinition, String namespace, Map<StereotypeDefinition, StereotypeModel> stereotypesCache) { <START> return FunctionalUtils.computeIfAbsent(stereotypesCache, stereotypeDefinition, definition -> { <END> if (!isValidStereotype(stereotypeDefinition, namespace)) { throw new IllegalModelDefinitionException(format( "Stereotype '%s' defines namespace '%s' which doesn't match extension stereotype '%s'. No extension can define " + "stereotypes on namespaces other than its own", stereotypeDefinition.getName(), stereotypeDefinition.getNamespace(), namespace)); } String resolvedNamespace = isBlank(stereotypeDefinition.getNamespace()) ? namespace : stereotypeDefinition.getNamespace(); final StereotypeModelBuilder builder = newStereotype(stereotypeDefinition.getName(), resolvedNamespace); stereotypeDefinition.getParent().ifPresent(parent -> { String parentNamespace = parent.getNamespace(); if (isBlank(parentNamespace)) { parentNamespace = namespace; } builder.withParent(getStereotype(parent, parentNamespace, stereotypesCache)); }); return builder.build(); }); }</code><technical_language>static import</technical_language>

Target:
protected static StereotypeModel getStereotype(StereotypeDefinition stereotypeDefinition, String namespace, Map<StereotypeDefinition, StereotypeModel> stereotypesCache) { return computeIfAbsent(stereotypesCache, stereotypeDefinition, definition -> { if (!isValidStereotype(stereotypeDefinition, namespace)) { throw new IllegalModelDefinitionException(format( "Stereotype '%s' defines namespace '%s' which doesn't match extension stereotype '%s'. No extension can define " + "stereotypes on namespaces other than its own", stereotypeDefinition.getName(), stereotypeDefinition.getNamespace(), namespace)); } String resolvedNamespace = isBlank(stereotypeDefinition.getNamespace()) ? namespace : stereotypeDefinition.getNamespace(); final StereotypeModelBuilder builder = newStereotype(stereotypeDefinition.getName(), resolvedNamespace); stereotypeDefinition.getParent().ifPresent(parent -> { String parentNamespace = parent.getNamespace(); if (isBlank(parentNamespace)) { parentNamespace = namespace; } builder.withParent(getStereotype(parent, parentNamespace, stereotypesCache)); }); return builder.build(); }); }
Source:
<code>private void checkHandle() { <START> if (!iterator.isOwningHandle()) { throw new IllegalStateException("RocksIterator handle is not valid"); } <END> }</code><technical_language>This message more descriptive. for handle invalid is if: 1) is some other thread access iterator. 2) iterator previously closed. message reflect conditions</technical_language>

Target:
private void checkHandle() { if (!iterator.isOwningHandle()) { throw new IllegalStateException("RocksIterator has been closed"); } }
Source:
<code>public void theUserClicksOnTabLink(String tab) throws Throwable { switch (tab) { case "Pozíciók": <START> driverProvider.getDriver().findElement(By.id("positions_link")).click(); <END> break; case "Csatornák": driverProvider.getDriver().findElement(By.id("channels_link")).click(); break; case "Jelszó-változtatás": driverProvider.getDriver().findElement(By.id("password_link")).click(); break; } }</code><technical_language>driverProvider.getDriver() getDriver() is in this file. Please replace current call getDriver()</technical_language>

Target:
public void theUserClicksOnTabLink(String tab) throws Throwable { switch (tab) { case "Pozíciók": getDriver().findElement(By.id("positions_link")).click(); break; case "Csatornák": getDriver().findElement(By.id("channels_link")).click(); break; case "Jelszó-változtatás": getDriver().findElement(By.id("password_link")).click(); break; } }
Source:
<code>public Optional<XMLObject> get(final String messageID) { final LinkedHashMap<String, String> messages = getMessages(); final String o = messages.get(messageID); if (o == null) { log.debug("Message not found in session {}", <START> messageID, context.getSessionStore().getOrCreateSessionId(context)); <END> return Optional.empty(); } log.debug("Message found in session {}, clearing", messageID, context.getSessionStore().getOrCreateSessionId(context)); messages.clear(); updateSession(messages); try { XMLObject message = XMLObjectSupport.unmarshallFromReader( Configuration.getParserPool(), new StringReader(o)); return Optional.of(message); } catch (Exception e) { log.error("Error unmarshalling message from input stream", e); return Optional.empty(); } }</code><technical_language>need log context.getSessionStore().getOrCreateSessionId(context), create a session id? @leleuj best</technical_language>

Target:
public Optional<XMLObject> get(final String messageID) { final LinkedHashMap<String, String> messages = getMessages(); final String o = messages.get(messageID); if (o == null) { log.debug("Message not found in session {}", messageID, context.getSessionStore().getOrCreateSessionId(context)); return Optional.empty(); } log.debug("Message found in session {}, clearing", messageID, context.getSessionStore().getOrCreateSessionId(context)); messages.clear(); updateSession(messages); return Configuration.deserializeSamlObject(o); }
Source:
<code>private String buildPushFailedMessage(final PushRequest request, final RemoteRefUpdate remoteRefUpdate, final String currentBranch) { String message; <START> if (remoteRefUpdate.getStatus().equals(RemoteRefUpdate.Status.UP_TO_DATE)) { <END> message = INFO_PUSH_ATTEMPT_IGNORED_UP_TO_DATE; } else { String refspec = currentBranch + BRANCH_REFSPEC_SEPERATOR + request.getRefSpec().get(0).split(REFSPEC_COLON)[1]; if (remoteRefUpdate.getMessage() != null) { message = String.format(ERROR_PUSH_ATTEMPT_FAILED_WITHMSG, refspec, request.getRemote(), remoteRefUpdate.getStatus(), remoteRefUpdate.getMessage()); } else { message = String.format(ERROR_PUSH_ATTEMPT_FAILED_WITHOUTMSG, refspec, request.getRemote(), remoteRefUpdate.getStatus()); } } return message; }</code><technical_language>if (RemoteRefUpdate.Status.UP_TO_DATE.equals(remoteRefUpdate.getStatus()) replace equals ==</technical_language>

Target:
private String buildPushFailedMessage(final PushRequest request, final RemoteRefUpdate remoteRefUpdate, final String currentBranch) { String message; if (remoteRefUpdate.getStatus() == RemoteRefUpdate.Status.UP_TO_DATE) { message = INFO_PUSH_ATTEMPT_IGNORED_UP_TO_DATE; } else { String refspec = currentBranch + BRANCH_REFSPEC_SEPERATOR + request.getRefSpec().get(0).split(REFSPEC_COLON)[1]; if (remoteRefUpdate.getMessage() != null) { message = String.format(ERROR_PUSH_ATTEMPT_FAILED_WITHMSG, refspec, request.getRemote(), remoteRefUpdate.getStatus(), remoteRefUpdate.getMessage()); } else { message = String.format(ERROR_PUSH_ATTEMPT_FAILED_WITHOUTMSG, refspec, request.getRemote(), remoteRefUpdate.getStatus()); } } return message; }
Source:
<code><START> public EntityTypeRest findOne(Context context, Integer integer) { <END> try { return entityTypeConverter.fromModel(entityTypeService.find(context, integer)); } catch (SQLException e) { throw new RuntimeException(e.getMessage(), e); } }</code><technical_language>add security check</technical_language>

Target:
public EntityTypeRest findOne(Context context, Integer integer) { try { EntityType entityType = entityTypeService.find(context, integer); if (entityType == null) { throw new ResourceNotFoundException("The entityType for ID: " + integer + " could not be found"); } return entityTypeConverter.fromModel(entityType); } catch (SQLException e) { throw new RuntimeException(e.getMessage(), e); } }
Source:
<code>private File allocate(String filename, long size) throws IOException { File segmentFile = new File(dataDir, filename); if (!segmentFile.exists()) { if (diskSpaceAllocator != null) { diskSpaceAllocator.allocate(segmentFile, size); } else { <START> Utils.preAllocateFileIfNeeded(segmentFile, size); <END> } } return segmentFile; }</code><technical_language>discussed, do this allocator</technical_language>

Target:
private File allocate(String filename, long size) throws IOException { File segmentFile = new File(dataDir, filename); if (!segmentFile.exists()) { diskSpaceAllocator.allocate(segmentFile, size); } return segmentFile; }
Source:
<code>private static AttributeDefinition getListAttributeDefinition(String name, ModelType modelType) { return new StringListAttributeDefinition.Builder(name) .setRequired(false) .setAllowExpression(false) .setValidator(JavaIdListValidator.INSTANCE) .build(); <START> } <END></code><technical_language>concern '.' in char names applies this kind, users <map_attribute_name>.<key> target individual map entries</technical_language>

Target:
private static AttributeDefinition getListAttributeDefinition(String name, ModelType modelType) { return new StringListAttributeDefinition.Builder(name) .setRequired(false) .setAllowExpression(true) .setValidator(JavaIdListValidator.INSTANCE) .build(); }
Source:
<code>public void testInvoke() throws AxisFault { GlobalRequestCountHandler globalRequestCountHandler = new GlobalRequestCountHandler(); MessageContext messageContext; Counter counter = new Counter(); Parameter parameter = new Parameter(); parameter.setValue(counter); messageContext = Mockito.mock(MessageContext.class, Mockito.CALLS_REAL_METHODS); Mockito.doReturn(parameter).when(messageContext).getParameter(Mockito.anyString()); Handler.InvocationResponse response = globalRequestCountHandler.invoke(messageContext); Assert.assertEquals(response, Handler.InvocationResponse.CONTINUE); <START> Assert.assertEquals(counter.getCount(), 1); <END> }</code><technical_language>add assert messages</technical_language>

Target:
public void testInvoke() throws Exception { GlobalRequestCountHandler globalRequestCountHandler = new GlobalRequestCountHandler(); MessageContext messageContext; Counter counter = new Counter(); Parameter parameter = new Parameter(); parameter.setValue(counter); messageContext = Mockito.mock(MessageContext.class, Mockito.CALLS_REAL_METHODS); Mockito.doReturn(parameter).when(messageContext).getParameter(Mockito.anyString()); Handler.InvocationResponse response = globalRequestCountHandler.invoke(messageContext); Assert.assertEquals("Asserting the response of the method",response, Handler.InvocationResponse.CONTINUE); Assert.assertEquals("Counter should be incremented to 1", counter.getCount(), 1); }
Source:
<code>public void onHarvest(ActivateEvent event, EntityRef entity) { EntityRef target = event.getTarget(); EntityRef harvester = entity.equals(target) ? event.getInstigator() : entity; if (!event.isConsumed() && target.exists() && harvester.exists() <START> && target.hasComponent(BushDefinitionComponent.class)) { <END> BushDefinitionComponent bushComponent = target.getComponent(BushDefinitionComponent.class); if (bushComponent.currentStage == bushComponent.stages.length - 1) { EntityRef produce; try { produce = entityManager.create(bushComponent.produce); boolean giveSuccess = inventoryManager.giveItem(harvester, target, produce); if (!giveSuccess) { Vector3f position = event.getTargetLocation().add(0, 0.5f, 0); produce.send(new DropItemEvent(position)); produce.send(new ImpulseEvent(random.nextVector3f(15.0f))); } } catch (NullPointerException e) { logger.error("Unable to create produce: " + bushComponent.produce); } if (bushComponent.sustainable) { doBushGrowth(bushComponent, -1); } else { entity.send(new DoDestroyPlant()); worldProvider.setBlock(bushComponent.position, blockManager.getBlock(BlockManager.AIR_ID)); } event.consume(); } } }</code><technical_language>if(!event.isConsumed() && isValidPlantHarvest(target,harvester))</technical_language>

Target:
public void onHarvest(ActivateEvent event, EntityRef entity) { EntityRef target = event.getTarget(); EntityRef harvester = entity.equals(target) ? event.getInstigator() : entity; if (!event.isConsumed() && areValidHarvestEntities(target, harvester)) { BushDefinitionComponent bushComponent = target.getComponent(BushDefinitionComponent.class); if (isInLastStage(bushComponent)) { dropProduce(bushComponent.produce, event.getTargetLocation(), harvester, target); if (bushComponent.sustainable) { resetDelay(doBushGrowth(bushComponent, -1), bushComponent.stages[bushComponent.currentStage].minTime, bushComponent.stages[bushComponent.currentStage].maxTime); } else { entity.send(new DoDestroyPlant()); worldProvider.setBlock(bushComponent.position, blockManager.getBlock(BlockManager.AIR_ID)); } event.consume(); } } }
Source:
<code>public AbstractBuilder withPushObjectList(final List<CosemObjectDefinitionDto> pushObjectList) { if (pushObjectList == null) { this.pushObjectList = null; } else { <START> this.pushObjectList = new ArrayList<>(pushObjectList); <END> } return this; }</code><technical_language>Is this wanted functionality? Making a new list this refer object anymore, done in original situation</technical_language>

Target:
public AbstractBuilder withPushObjectList(final List<CosemObjectDefinitionDto> pushObjectList) { if (pushObjectList == null) { this.pushObjectList = null; } else { this.pushObjectList = pushObjectList; } return this; }
Source:
<code>public final void init(Config config, TaskContext context) throws Exception { <START> ApplicationRunner runner = ApplicationRunner.fromConfig(config); <END> StreamGraphImpl streams = new StreamGraphImpl(runner); this.graphBuilder.init(streams, config); this.contextManager = streams.getContextManager(); Map<SystemStream, MessageStreamImpl> inputBySystemStream = new HashMap<>(); context.getSystemStreamPartitions().forEach(ssp -> { if (!inputBySystemStream.containsKey(ssp.getSystemStream())) { inputBySystemStream.putIfAbsent(ssp.getSystemStream(), streams.getInputStream(ssp.getSystemStream())); } }); operatorGraph.init(inputBySystemStream, config, this.contextManager.initTaskContext(config, context)); }</code><technical_language>Issue: This passed in SamzaContainer constructor</technical_language>

Target:
public final void init(Config config, TaskContext context) throws Exception { StreamGraphImpl streamGraph = new StreamGraphImpl(this.runner, config); this.graphBuilder.init(streamGraph, config); this.contextManager = streamGraph.getContextManager(); Map<SystemStream, MessageStreamImpl> inputBySystemStream = new HashMap<>(); context.getSystemStreamPartitions().forEach(ssp -> { if (!inputBySystemStream.containsKey(ssp.getSystemStream())) { inputBySystemStream.putIfAbsent(ssp.getSystemStream(), streamGraph.getInputStream(ssp.getSystemStream())); } }); operatorGraph.init(inputBySystemStream, config, this.contextManager.initTaskContext(config, context)); }
Source:
<code>private Collection<String> getExistingIds(final BranchContext context, final Collection<String> ids, final Class<? extends SnomedComponentDocument> clazz) { return context.service(RevisionIndex.class).read(context.branch().path(), new RevisionIndexRead<Collection<String>>() { @Override public Collection<String> execute(final RevisionSearcher index) throws IOException { <START> final Hits<? extends SnomedComponentDocument> hits = index.searcher() <END> .search(Query.select(clazz) .where(RevisionDocument.Expressions.ids(ids)) .limit(ids.size()) .build()); return FluentIterable.from(hits).transform(ComponentUtils.getIdFunction()).toSet(); } }); }</code><technical_language>This return revisions for a single ID, RevisionSearcher.search(...) instead of raw searcher. opened RevisionSearcher instance context.service(RevisionSearcher.class)</technical_language>

Target:
private Collection<String> getExistingIds(final BranchContext context, final Collection<String> ids, final Class<? extends SnomedComponentDocument> clazz) { try { Hits<? extends SnomedComponentDocument> hits = context.service(RevisionSearcher.class).search(Query.select(clazz) .where(RevisionDocument.Expressions.ids(ids)) .limit(ids.size()) .build()); return FluentIterable.from(hits).transform(ComponentUtils.getIdFunction()).toSet(); } catch (IOException e) { throw new SnowowlRuntimeException(e); } }
Source:
<code>protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException { log.trace("doPost"); int idx = Integer.parseInt(request.getParameter("idx"), 10); log.debug("Removing index {}", idx); <START> InputStream is = request.getResource().getChild(RedirectMapModel.MAP_FILE_NODE).adaptTo(InputStream.class); <END> List<String> lines = IOUtils.readLines(is); log.debug("Loaded lines", lines.size()); lines.remove(idx); log.debug("Removed line..."); ModifiableValueMap mvm = request.getResource().getChild(RedirectMapModel.MAP_FILE_NODE) .getChild(JcrConstants.JCR_CONTENT).adaptTo(ModifiableValueMap.class); mvm.put(JcrConstants.JCR_DATA, StringUtils.join(lines, "\n")); request.getResourceResolver().commit(); request.getResourceResolver().refresh(); log.debug("Changes saved..."); super.doGet(request, response); }</code><technical_language>unclosed stream</technical_language>

Target:
protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException { log.trace("doPost"); int idx = Integer.parseInt(request.getParameter("idx"), 10); log.debug("Removing index {}", idx); List<String> lines = RedirectEntriesUtils.readEntries(request); lines.remove(idx); log.debug("Removed line..."); RedirectEntriesUtils.updateRedirectMap(request, lines); RedirectEntriesUtils.writeEntriesToResponse(request, response); }
Source:
<code>private void clientRequest(Tracing brave, String serviceName, ExchangeSendingEvent event) { ZipkinState state = event.getExchange().getProperty(ZipkinState.KEY, ZipkinState.class); if (state == null) { state = new ZipkinState(); event.getExchange().setProperty(ZipkinState.KEY, state); } Span last = state.peekServerSpan(); Span span; if (last != null) { span = brave.tracer().newChild(last.context()); } else { span = brave.tracer().nextSpan(); } span.kind(Span.Kind.CLIENT).start(); ZipkinClientRequestAdapter parser = new ZipkinClientRequestAdapter(this, event.getEndpoint()); INJECTOR.inject(span.context(), event.getExchange().getIn()); parser.onRequest(event.getExchange(), span.customizer()); state.pushClientSpan(span); if (LOG.isDebugEnabled()) { TraceContext context = span.context(); String traceId = "" + context.traceIdString(); String spanId = "" + context.spanId(); MDC.put("traceId", traceId); MDC.put("spanId", spanId); String parentId = context.parentId() != null ? "" + context.parentId() : null; if (parentId != null) { LOG.debug(String.format("clientRequest [service=%s, traceId=%20s, spanId=%20s, parentId=%20s]", serviceName, traceId, spanId, parentId)); MDC.put("parentId", parentId); } else { LOG.debug(String.format("clientRequest [service=%s, traceId=%20s, spanId=%20s]", serviceName, traceId, spanId)); } <START> } <END> }</code><technical_language>Beware some of code added MDC.put executed if DEBUG logging, need move this outside, fix in another way. This in a places in this source file</technical_language>

Target:
private void clientRequest(Tracing brave, String serviceName, ExchangeSendingEvent event) { ZipkinState state = event.getExchange().getProperty(ZipkinState.KEY, ZipkinState.class); if (state == null) { state = new ZipkinState(); event.getExchange().setProperty(ZipkinState.KEY, state); } Span last = state.peekServerSpan(); Span span; if (last != null) { span = brave.tracer().newChild(last.context()); } else { span = brave.tracer().nextSpan(); } span.kind(Span.Kind.CLIENT).start(); ZipkinClientRequestAdapter parser = new ZipkinClientRequestAdapter(this, event.getEndpoint()); INJECTOR.inject(span.context(), event.getExchange().getIn()); parser.onRequest(event.getExchange(), span.customizer()); state.pushClientSpan(span); TraceContext context = span.context(); String traceId = "" + context.traceIdString(); String spanId = "" + context.spanId(); String parentId = context.parentId() != null ? "" + context.parentId() : null; if (camelContext.isUseMDCLogging()) { MDC.put("traceId", traceId); MDC.put("spanId", spanId); MDC.put("parentId", parentId); } if (LOG.isDebugEnabled()) { if (parentId != null) { LOG.debug(String.format("clientRequest [service=%s, traceId=%20s, spanId=%20s, parentId=%20s]", serviceName, traceId, spanId, parentId)); } else { LOG.debug(String.format("clientRequest [service=%s, traceId=%20s, spanId=%20s]", serviceName, traceId, spanId)); } } }
Source:
<code>private void resetToFileBasedWriter() throws IOException { this.out.close(); BoundedByteArrayOutputStream bout = (BoundedByteArrayOutputStream) this.rawOut.getWrappedStream(); if (outputPath == null) { outputPath = taskOutput.getOutputFileForWrite(); } <START> LOG.info("Creating file " + outputPath); <END> FSDataOutputStream newRawOut = fs.create(outputPath); this.rawOut = newRawOut; this.checksumOut = new IFileOutputStream(this.rawOut); if (fileCodec != null) { this.compressor = CodecPool.getCompressor(fileCodec); if (this.compressor != null) { this.compressor.reset(); this.compressOutput = true; this.compressedOut = fileCodec.createOutputStream(checksumOut, compressor); this.out = new FSDataOutputStream(this.compressedOut, null); } else { LOG.warn("Could not obtain compressor from CodecPool"); this.out = new FSDataOutputStream(checksumOut, null); } } else { this.out = new FSDataOutputStream(checksumOut, null); } headerWritten = false; writeHeader(newRawOut); int sPos = HEADER.length; int len = (bout.size() - checksumSize - HEADER.length); this.out.write(bout.getBuffer(), sPos, len); bufferFull = true; bout.reset(); }</code><technical_language>Nit: Add "Switching mem stream disk stream" log message</technical_language>

Target:
private void resetToFileBasedWriter() throws IOException { this.out.close(); BoundedByteArrayOutputStream bout = (BoundedByteArrayOutputStream) this.rawOut.getWrappedStream(); if (outputPath == null) { outputPath = taskOutput.getOutputFileForWrite(); } LOG.info("Switching from mem stream to disk stream. File: " + outputPath); FSDataOutputStream newRawOut = fs.create(outputPath); this.rawOut = newRawOut; this.ownOutputStream = true; setupOutputStream(fileCodec); headerWritten = false; writeHeader(newRawOut); int sPos = HEADER.length; int len = (bout.size() - checksumSize - HEADER.length); this.out.write(bout.getBuffer(), sPos, len); bufferFull = true; bout.reset(); }
Source:
<code>public Snippet getSnippet(Integer snippetId) throws GitLabApiException { <START> if (snippetId == null) { <END> throw new RuntimeException("snippetId can't be null"); } Response response = get(Response.Status.OK, null, "snippets", snippetId); Snippet snippet = response.readEntity(Snippet.class); snippet.setContent(getSnippetContent(snippet.getId())); return snippet; }</code><technical_language>Do a flag download content not</technical_language>

Target:
public Snippet getSnippet(Integer snippetId) throws GitLabApiException { return getSnippet(snippetId, false); }
Source:
<code>public void addVariable() { TestSuiteModel testSuite = new TestSuiteModel(); String variable_indentifier = "variable_indentifier"; String variable_content = "variable_content"; String variable_description = "variable_description"; assertEquals(0, testSuite.getVariables().size()); testSuite.addVariable(variable_indentifier, variable_content, variable_description); <START> assertEquals(1, testSuite.getVariables().size()); <END> assertEquals(variable_indentifier, testSuite.getVariables().get(0).getName()); assertEquals(variable_content, testSuite.getVariables().get(0).getContent()); assertEquals(variable_description, testSuite.getVariables().get(0).getDescription()); String variable_indentifier_1 = variable_indentifier + "_1"; String variable_content_1 = "variable_content" + "_1"; String variable_description_1 = "variable_description" + "_1"; testSuite.addVariable(variable_indentifier_1, variable_content_1, variable_description_1); assertEquals(2, testSuite.getVariables().size()); assertEquals(variable_indentifier, testSuite.getVariables().get(0).getName()); assertEquals(variable_content, testSuite.getVariables().get(0).getContent()); assertEquals(variable_description, testSuite.getVariables().get(0).getDescription()); assertEquals(variable_indentifier_1, testSuite.getVariables().get(1).getName()); assertEquals(variable_content_1, testSuite.getVariables().get(1).getContent()); assertEquals(variable_description_1, testSuite.getVariables().get(1).getDescription()); }</code><technical_language>test is a copy of previous one, asserts unnecessary</technical_language>

Target:
public void addVariable() { TestSuiteModel testSuite = new TestSuiteModel(); for (int index = 0; index < elements; index++) { testSuite.setVariable(variableIndentifier[index], variableContent[index], variableDescription[index]); assertEquals(variableIndentifier[index], testSuite.getVariable(variableIndentifier[index]).getName()); assertEquals(variableContent[index], testSuite.getVariable(variableIndentifier[index]).getContent()); assertEquals(variableDescription[index], testSuite.getVariable(variableIndentifier[index]).getDescription()); } }
Source:
<code>public Field build() { <START> return new Field().setName(super.getName()).setType(super.getDataType()).setSearchable(true) .setKey(super.isKey()).setSortable(super.isSortable()).setFilterable(super.isFilterable()) .setHidden(super.isHidden()).setFacetable(super.isFacetable()).setAnalyzer(this.analyzer) .setSearchAnalyzer(this.searchAnalyzer).setIndexAnalyzer(this.indexAnalyzer) .setSynonymMaps(this.synonymMaps); <END> }</code><technical_language>more readable if setter line</technical_language>

Target:
public Field build() { return new Field() .setName(super.getName()) .setType(super.getDataType()) .setSearchable(true) .setKey(super.isKey()) .setSortable(super.isSortable()) .setFilterable(super.isFilterable()) .setHidden(super.isHidden()) .setFacetable(super.isFacetable()) .setAnalyzer(this.analyzer) .setSearchAnalyzer(this.searchAnalyzer) .setIndexAnalyzer(this.indexAnalyzer) .setSynonymMaps(this.synonymMapNames); }
Source:
<code>public static List<String> getResourceFiles(String path) throws IOException { List<String> fileNames = new ArrayList<>(); try ( InputStream in = getResourceAsStream(path); BufferedReader br = new BufferedReader(new InputStreamReader(in)) ) { String resource; while ((resource = br.readLine()) != null) { <START> if (resource.endsWith("code.ser") || resource.endsWith("conf.ser")) { <END> fileNames.add(path + "/" + resource); } } Collections.sort(fileNames); } return fileNames; }</code><technical_language>Nit: move file extensions constants head of file</technical_language>

Target:
public static List<String> getResourceFiles(String path) throws IOException { List<String> fileNames = new ArrayList<>(); try ( InputStream in = getResourceAsStream(path); BufferedReader br = new BufferedReader(new InputStreamReader(in)) ) { String resource; while ((resource = br.readLine()) != null) { if (resource.endsWith(COMPRESSED_SERIALIZED_TOPOLOGY_FILENAME_ENDING) || resource.endsWith(COMPRESSED_SERIALIZED_CONFIG_FILENAME_ENDING)) { fileNames.add(path + "/" + resource); } } Collections.sort(fileNames); } return fileNames; }
Source:
<code>public void onAttached(Run<?, ?> r) { ParametersDefinitionProperty p = r.getParent().getProperty(ParametersDefinitionProperty.class); if (p != null) { this.parameterDefinitionNames = p.getParameterDefinitionNames(); } else { this.parameterDefinitionNames = Collections.emptyList(); } if (wasInitializedWithNullParameters) { <START> LOGGER.log(Level.WARNING, "ParametersAction has been initialized with null parameter list for Run {0}. It is a bug in the plugin, which created this action (see JENKINS-39495).", r); <END> } this.run = r; }</code><technical_language>Do a a useful call stack here</technical_language>

Target:
public void onAttached(Run<?, ?> r) { ParametersDefinitionProperty p = r.getParent().getProperty(ParametersDefinitionProperty.class); if (p != null) { this.parameterDefinitionNames = p.getParameterDefinitionNames(); } else { this.parameterDefinitionNames = Collections.emptyList(); } if (wasInitializedWithNullParameters) { LOGGER.log(Level.FINE, "ParametersAction has been initialized with null parameter list for Run {0}. It is a bug in a plugin or script, which created this action (see JENKINS-39495).", r); } this.run = r; }
Source:
<code>private boolean isNetworkSelectionNeeded(List<ScanDetail> scanDetails, WifiInfo wifiInfo, boolean connected, boolean disconnected) { if (scanDetails.size() == 0) { localLog("Empty connectivity scan results. Skip network selection."); return false; } if (connected) { if (!mEnableAutoJoinWhenAssociated) { localLog("Switching networks in connected state is not allowed." + " Skip network selection."); return false; } if (mLastNetworkSelectionTimeStamp != INVALID_TIME_STAMP) { long gap = mClock.getElapsedSinceBootMillis() - mLastNetworkSelectionTimeStamp; if (gap < MINIMUM_NETWORK_SELECTION_INTERVAL_MS) { localLog("Too short since last network selection: " + gap + " ms." + " Skip network selection."); return false; } } <START> boolean is5GHzAvailable = is5GHzNetworkAvailable(scanDetails); <END> if (isCurrentNetworkSufficient(wifiInfo, is5GHzAvailable)) { localLog("Current connected network already sufficient. Skip network selection."); return false; } else { localLog("Current connected network is not sufficient."); return true; } } else if (disconnected) { return true; } else { localLog("WifiStateMachine is in neither CONNECTED nor DISCONNECTED state." + " Skip network selection."); return false; } }</code><technical_language>I reasoning want pass scanDetails a parameter, do this of isCurrentNetworkSufficient, but! If do this check wifiInfo.is24GHz, mitigate 'performance concerns'</technical_language>

Target:
private boolean isNetworkSelectionNeeded(List<ScanDetail> scanDetails, WifiInfo wifiInfo, boolean connected, boolean disconnected) { if (scanDetails.size() == 0) { localLog("Empty connectivity scan results. Skip network selection."); return false; } if (connected) { if (!mEnableAutoJoinWhenAssociated) { localLog("Switching networks in connected state is not allowed." + " Skip network selection."); return false; } if (mLastNetworkSelectionTimeStamp != INVALID_TIME_STAMP) { long gap = mClock.getElapsedSinceBootMillis() - mLastNetworkSelectionTimeStamp; if (gap < MINIMUM_NETWORK_SELECTION_INTERVAL_MS) { localLog("Too short since last network selection: " + gap + " ms." + " Skip network selection."); return false; } } if (isCurrentNetworkSufficient(wifiInfo, scanDetails)) { localLog("Current connected network already sufficient. Skip network selection."); return false; } else { localLog("Current connected network is not sufficient."); return true; } } else if (disconnected) { return true; } else { localLog("WifiStateMachine is in neither CONNECTED nor DISCONNECTED state." + " Skip network selection."); return false; } }
Source:
<code>public List<Event> getEvents(@QueryParam("client") String client, @QueryParam("user") String user, @QueryParam("dateFrom") String dateFrom, @QueryParam("dateTo") String dateTo, @QueryParam("ipAddress") String ipAddress, @QueryParam("first") Integer firstResult, @QueryParam("max") Integer maxResults) { auth.init(RealmAuth.Resource.EVENTS).requireView(); EventStoreProvider eventStore = session.getProvider(EventStoreProvider.class); EventQuery query = eventStore.createQuery().realm(realm.getId()); if (client != null) { query.client(client); } List<String> types = uriInfo.getQueryParameters().get("type"); if (types != null) { EventType[] t = new EventType[types.size()]; for (int i = 0; i < t.length; i++) { t[i] = EventType.valueOf(types.get(i)); } query.type(t); } if (user != null) { query.user(user); } if(dateFrom != null) { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); Date from = null; try { from = df.parse(dateFrom); } catch (ParseException e) { <START> e.printStackTrace(); <END> } query.fromDate(from); } if(dateTo != null) { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); Date to = null; try { to = df.parse(dateFrom); } catch (ParseException e) { e.printStackTrace(); } query.toDate(to); } if (ipAddress != null) { query.ipAddress(ipAddress); } if (firstResult != null) { query.firstResult(firstResult); } if (maxResults != null) { query.maxResults(maxResults); } return query.getResultList(); }</code><technical_language>This return error (or throw exception), "swallow" exception</technical_language>

Target:
public List<Event> getEvents(@QueryParam("client") String client, @QueryParam("user") String user, @QueryParam("dateFrom") String dateFrom, @QueryParam("dateTo") String dateTo, @QueryParam("ipAddress") String ipAddress, @QueryParam("first") Integer firstResult, @QueryParam("max") Integer maxResults) { auth.init(RealmAuth.Resource.EVENTS).requireView(); EventStoreProvider eventStore = session.getProvider(EventStoreProvider.class); EventQuery query = eventStore.createQuery().realm(realm.getId()); if (client != null) { query.client(client); } List<String> types = uriInfo.getQueryParameters().get("type"); if (types != null) { EventType[] t = new EventType[types.size()]; for (int i = 0; i < t.length; i++) { t[i] = EventType.valueOf(types.get(i)); } query.type(t); } if (user != null) { query.user(user); } if(dateFrom != null) { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); Date from = null; try { from = df.parse(dateFrom); } catch (ParseException e) { throw new BadRequestException("Invalid value for 'Date(From)', excepted format is yyyy-MM-dd"); } query.fromDate(from); } if(dateTo != null) { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); Date to = null; try { to = df.parse(dateTo); } catch (ParseException e) { throw new BadRequestException("Invalid value for 'Date(To)', excepted format is yyyy-MM-dd"); } query.toDate(to); } if (ipAddress != null) { query.ipAddress(ipAddress); } if (firstResult != null) { query.firstResult(firstResult); } if (maxResults != null) { query.maxResults(maxResults); } return query.getResultList(); }
Source:
<code>public static String nullLiteral() { <START> return NullHandlingHelper.useDefaultValuesForNull() ? "''" : null; <END> }</code><technical_language>This right. nullLiteral() return expression is equivalent a SQL NULL literal. expression is expression, a java null. this: return "null"; expression system do right of those. treat empty string not, depending current null-handling-behavior setting</technical_language>

Target:
public static String nullLiteral() { return "null"; }
Source:
<code>private Cookie getSessionCookie(TestEnvironmentEntity testEnv) { Cookie cookie = new Cookie(TestEnvUtils.SESSION_COOKIE, testEnv.getSessionId()); cookie.setMaxAge(environmentsTtlMinutes * 60); <START> <END> return cookie; }</code><technical_language>Expires time updated cookie.setPath("/"); Check it, please, fix if right</technical_language>

Target:
private Cookie getSessionCookie(TestEnvironmentEntity testEnv) { Cookie cookie = new Cookie(TestEnvUtils.SESSION_COOKIE, testEnv.getSessionId()); cookie.setMaxAge(environmentsTtlMinutes * 60); cookie.setPath("/"); return cookie; }
Source:
<code>private Version createVersion(ProjectHistory projectHistory, Project projectState, LogMessage logMessage, ACUser user, Version previousVersion) throws ESException { final Version newVersion = VersioningFactory.eINSTANCE.createVersion(); long computedChecksum = ModelUtil.NO_CHECKSUM; try { if (ServerConfiguration.isComputeChecksumOnCommitActive()) { computedChecksum = ModelUtil.computeChecksum(projectState); ModelUtil.logProjectDetails( <START> MessageFormat.format("Checksum computaion during version create: {0}", computedChecksum), END> user.getName(), projectHistory.getProjectName(), projectHistory.getProjectId().getId(), null, -1); } } catch (final SerializationException exception) { throw new ESException(MessageFormat.format( Messages.VersionSubInterfaceImpl_ChecksumComputationFailed, projectHistory.getProjectName()), exception); } logMessage.setDate(new Date()); logMessage.setAuthor(user.getName()); newVersion.setLogMessage(logMessage); newVersion.setPrimarySpec(Versions.createPRIMARY(previousVersion.getPrimarySpec(), projectHistory.getVersions() .size())); newVersion.getPrimarySpec().setProjectStateChecksum(computedChecksum); newVersion.setNextVersion(null); projectHistory.getVersions().add(newVersion); return newVersion; }</code><technical_language>typo => computation</technical_language>

Target:
private Version createVersion(ProjectHistory projectHistory, Project projectState, LogMessage logMessage, ACUser user, Version previousVersion) throws ESException { final Version newVersion = VersioningFactory.eINSTANCE.createVersion(); long computedChecksum = ModelUtil.NO_CHECKSUM; try { if (ServerConfiguration.isComputeChecksumOnCommitActive()) { computedChecksum = ModelUtil.computeChecksum(projectState); ModelUtil.logProjectDetails( MessageFormat.format("Checksum computation during version create: {0}", computedChecksum), user.getName(), projectHistory.getProjectName(), projectHistory.getProjectId().getId(), null, -1); } } catch (final SerializationException exception) { throw new ESException(MessageFormat.format( Messages.VersionSubInterfaceImpl_ChecksumComputationFailed, projectHistory.getProjectName()), exception); } logMessage.setDate(new Date()); logMessage.setAuthor(user.getName()); newVersion.setLogMessage(logMessage); newVersion.setPrimarySpec(Versions.createPRIMARY(previousVersion.getPrimarySpec(), projectHistory.getVersions() .size())); newVersion.getPrimarySpec().setProjectStateChecksum(computedChecksum); newVersion.setNextVersion(null); projectHistory.getVersions().add(newVersion); return newVersion; }
Source:
<code>public void testIsEmpty() { assertTrue( Version.isEmpty( null ) ); assertTrue( Version.isEmpty( "" ) ); <START> assertTrue( Version.isEmpty( String.format( " %n" ) ) ); <END> assertFalse( Version.isEmpty( "a" ) ); assertFalse( Version.isEmpty( String.format ( "a %n" ) ) ); }</code><technical_language>" " + System.lineSeparator()</technical_language>

Target:
public void testIsEmpty() { assertTrue( Version.isEmpty(null) ); assertTrue( Version.isEmpty("") ); assertTrue( Version.isEmpty(" " + System.lineSeparator() ) ); assertFalse( Version.isEmpty( "a") ); assertFalse( Version.isEmpty( " a " + System.lineSeparator() ) ); }
Source:
<code>public void addOrUpdateAlert(final Alert alert) { assertIsOpen(); LOGGER.debug() .setMessage("Upserting alert") .addData("alert", alert) .log(); final Transaction transaction = Ebean.beginTransaction(); try { models.ebean.Alert ebeanAlert = Ebean.find(models.ebean.Alert.class) .where() .eq("uuid", alert.getId()) .findUnique(); boolean created = false; if (ebeanAlert == null) { ebeanAlert = new models.ebean.Alert(); created = true; } ebeanAlert.setCluster(alert.getCluster()); ebeanAlert.setUuid(alert.getId()); ebeanAlert.setMetric(alert.getMetric()); ebeanAlert.setContext(alert.getContext()); ebeanAlert.setNagiosExtension(getNagiosExtensionFromMap(alert.getExtensions())); ebeanAlert.setName(alert.getName()); ebeanAlert.setOperator(alert.getOperator()); ebeanAlert.setPeriod(alert.getPeriod().toStandardSeconds().getSeconds()); ebeanAlert.setQuantityValue(alert.getValue().getValue()); ebeanAlert.setQuantityUnit(alert.getValue().getUnit().isPresent() ? alert.getValue().getUnit().get() : null); ebeanAlert.setStatistic(alert.getStatistic()); ebeanAlert.setService(alert.getService()); <START> _alertQueryGenerator.saveAlert(ebeanAlert); <END> transaction.commit(); LOGGER.info() .setMessage("Upserted alert") .addData("alert", alert) .addData("isCreated", created) .log(); } finally { transaction.end(); } }</code><technical_language>if this fails? is a race condition here</technical_language>

Target:
public void addOrUpdateAlert(final Alert alert) { assertIsOpen(); LOGGER.debug() .setMessage("Upserting alert") .addData("alert", alert) .log(); try (Transaction transaction = Ebean.beginTransaction()) { models.ebean.Alert ebeanAlert = Ebean.find(models.ebean.Alert.class) .where() .eq("uuid", alert.getId()) .findUnique(); boolean created = false; if (ebeanAlert == null) { ebeanAlert = new models.ebean.Alert(); created = true; } ebeanAlert.setCluster(alert.getCluster()); ebeanAlert.setUuid(alert.getId()); ebeanAlert.setMetric(alert.getMetric()); ebeanAlert.setContext(alert.getContext()); ebeanAlert.setNagiosExtension(convertToEbeanNagiosExtension(alert.getNagiosExtension())); ebeanAlert.setName(alert.getName()); ebeanAlert.setOperator(alert.getOperator()); ebeanAlert.setPeriod(alert.getPeriod().toStandardSeconds().getSeconds()); ebeanAlert.setQuantityValue(alert.getValue().getValue()); ebeanAlert.setQuantityUnit(alert.getValue().getUnit().orNull()); ebeanAlert.setStatistic(alert.getStatistic()); ebeanAlert.setService(alert.getService()); _alertQueryGenerator.saveAlert(ebeanAlert); transaction.commit(); LOGGER.info() .setMessage("Upserted alert") .addData("alert", alert) .addData("isCreated", created) .log(); } catch (final IOException | RuntimeException e) { LOGGER.error() .setMessage("Failed to upsert alert") .addData("alert", alert) .setThrowable(e) .log(); throw new PersistenceException(e); } }
Source:
<code>public BitstreamResource uploadBitstream(HttpServletRequest request, @PathVariable UUID uuid, @RequestParam("file") MultipartFile uploadfile, @RequestParam(value = "properties", required = false) String properties) { Context context = ContextUtil.obtainContext(request); Item item = null; Bitstream bitstream = null; try { item = itemService.find(context, uuid); } catch (SQLException e) { log.error("Something went wrong trying to find the Item with uuid: " + uuid, e); } if (item == null) { throw new ResourceNotFoundException("The given uuid did not resolve to an Item on the server: " + uuid); } InputStream fileInputStream = null; try { fileInputStream = uploadfile.getInputStream(); } catch (IOException e) { log.error("Something went wrong when trying to read the inputstream from the given file in the request"); <START> throw new UnprocessableEntityException("The InputStream from the file couldn't be read"); <END> } try { bitstream = processBitstreamCreation(context, item, fileInputStream, properties, uploadfile.getOriginalFilename()); itemService.update(context, item); context.commit(); } catch (AuthorizeException | IOException | SQLException e) { log.error( "Something went wrong with trying to create the single bitstream for file with filename: " + uploadfile .getOriginalFilename() + " for item with uuid: " + uuid + " and possible properties: " + properties); } return new BitstreamResource(bitstreamConverter.fromModel(bitstream), utils); }</code><technical_language>IOException "swallowed" in logged returned user. need ensure is minimally logged in log.error statement here</technical_language>

Target:
public BitstreamResource uploadBitstream(HttpServletRequest request, @PathVariable UUID uuid, @RequestParam("file") MultipartFile uploadfile, @RequestParam(value = "properties", required = false) String properties) { Context context = ContextUtil.obtainContext(request); Item item = null; Bitstream bitstream = null; try { item = itemService.find(context, uuid); } catch (SQLException e) { log.error("Something went wrong trying to find the Item with uuid: " + uuid, e); } if (item == null) { throw new ResourceNotFoundException("The given uuid did not resolve to an Item on the server: " + uuid); } InputStream fileInputStream = null; try { fileInputStream = uploadfile.getInputStream(); } catch (IOException e) { log.error("Something went wrong when trying to read the inputstream from the given file in the request", e); throw new UnprocessableEntityException("The InputStream from the file couldn't be read", e); } try { bitstream = processBitstreamCreation(context, item, fileInputStream, properties, uploadfile.getOriginalFilename()); itemService.update(context, item); context.commit(); } catch (AuthorizeException | IOException | SQLException e) { String message = "Something went wrong with trying to create the single bitstream for file with filename: " + uploadfile.getOriginalFilename() + " for item with uuid: " + uuid + " and possible properties: " + properties; log.error(message, e); throw new RuntimeException(message, e); } return new BitstreamResource(bitstreamConverter.fromModel(bitstream), utils); }
Source:
<code>public String toString() { try { <START> return new ObjectMapper().writeValueAsString(this); <END> } catch (Exception e) { return ""; } }</code><technical_language>ObjectMapper is a thread safe object. create a static instance reuse it</technical_language>

Target:
public String toString() { try { return OBJECT_MAPPER.writeValueAsString(this); } catch (Exception e) { return ""; } }
Source:
<code>public void suspend() { switch (state()) { case CREATED: case SUSPENDED: log.info("Skip suspending since state is {}", state()); break; case RESTORING: case RUNNING: try { <START> closeTopology(); <END> } finally { transitionTo(State.SUSPENDED); log.info("Suspended"); } break; case CLOSED: throw new IllegalStateException("Illegal state " + state() + " while suspending active task " + id); default: throw new IllegalStateException("Unknown state " + state() + " while suspending active task " + id); } }</code><technical_language>Is this addressed</technical_language>

Target:
public void suspend() { switch (state()) { case CREATED: case SUSPENDED: log.info("Skip suspending since state is {}", state()); break; case RESTORING: transitionTo(State.SUSPENDED); log.info("Suspended restoring"); break; case RUNNING: try { ENDED even if user code throws in `Processor#close()` closeTopology(); } finally { transitionTo(State.SUSPENDED); log.info("Suspended running"); } break; case CLOSED: throw new IllegalStateException("Illegal state " + state() + " while suspending active task " + id); default: throw new IllegalStateException("Unknown state " + state() + " while suspending active task " + id); } }
Source:
<code>protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (StringUtils.isEmpty(SSOUtils.getParameter(request, SSOUtils.POST_ACTION_URL))) { throw new RuntimeException("No post action url found in request."); <START> } <END> HttpSession session = request.getSession(true); if (SSOUtils.isUserAuthenticated(session)) { request.getRequestDispatcher(SSOUtils.LOGIN_PHASE3_URI).forward(request, response); } else { authenticateUser(session, request, response); } }</code><technical_language>I unsure need this, checked this in phase1 already, no</technical_language>

Target:
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(true); try { if (SSOUtils.isUserAuthenticated(session)) { request.getRequestDispatcher(SSOUtils.LOGIN_PHASE3_URI).forward(request, response); } else { authenticateUser(session, request, response); } } catch (AuthenticationException ex) { request.getRequestDispatcher("/WEB-INF/login.jsp?msg=" + ex.getMessage()).forward(request, response); } finally { request.getSession().removeAttribute(SSOUtils.USER_CREDENTIALS); } }
Source:
<code>public Iterable<String> names() throws IOException { assert this.dir != null; assert this.user != null; <START> assert this.label != null; <END> return Arrays.asList(this.friends.list()); }</code><technical_language>@pinaf explain purpose of asserts</technical_language>

Target:
public Iterable<String> names() { return Arrays.asList(this.friends.list()); }
Source:
<code>public <U> Vector<U> map(Function<? super T, ? extends U> mapper) { Objects.requireNonNull(mapper, "mapper is null"); final MutableWrapper<Object[]> newLeading = new MutableWrapper<>(Arrays.empty()); final Object[] newMiddle = new Object[middle.leafCount()]; final MutableWrapper<Object[]> newTrailing = new MutableWrapper<>(Arrays.empty()); leafVisitor((ordinal, leaf, start, end) -> { final Object[] copy = copyMap(mapper, leaf, start, end); if (ordinal == 0) { newLeading.val = copy; } else if (ordinal <= newMiddle.length) { <START> newMiddle[ordinal - 1] = copy); <END> } else { newTrailing.val = copy; } }); final BitMappedTrie<U> middle = BitMappedTrie.ofAll(newMiddle, this.middle.length(), BRANCHING_BASE); return ofAll(newLeading.val, leadingOffset, middle, newTrailing.val, trailingLength); }</code><technical_language>Huh, this ')' from? compile!</technical_language>

Target:
public <U> Vector<U> map(Function<? super T, ? extends U> mapper) { return ofAll(trie.map(mapper)); }