auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public FormPage(final float height, final float textAngle, final DimensionUnit unit, final float width, final IterableStream<FormLine> lines, final IterableStream<FormTable> tables) { this.height = height; this.textAngle = textAngle; this.unit = unit; this.width = width; <START> this.lines = lines == null ? new IterableStream<FormLine>(Collections.emptyList()) : lines; this.tables = tables == null ? new IterableStream<FormTable>(Collections.emptyList()) : tables; <END> }</code><technical_language>factory instead of constructor is null safe. java this.lines = IterableStream.of(lines); this.tables = IterbaleStream.of(tables);</technical_language>

Target:
public FormPage(final float height, final float textAngle, final DimensionUnit unit, final float width, final IterableStream<FormLine> lines, final IterableStream<FormTable> tables) { this.height = height; this.textAngle = textAngle; this.unit = unit; this.width = width; this.lines = IterableStream.of(lines); this.tables = IterableStream.of(tables); }
Source:
<code>@Override public final boolean permitsMethod(Method method, Object receiver, Object[] args) { String key = Whitelist.canonicalMethodSig(method); Boolean b = permittedCache.get(key); if (b != null) { return b; } boolean output = false; for (MethodSignature s : methodSignatures()) { if (s.matches(method)) { output = true; break; } } permittedCache.put(key, output); <START> return output; <END> }</code><technical_language>This sense me. If precached signatures, iterating now? If is in cache, return false right away. delete matches methods too, permittedCache a Set<String>. I guess this handle wildcard signatures? I noted in #179, more easily (and efficiently) handled precaching wildcards (i.e., deleting isWildcard call in cacheSignatureList) permitsMethod do java return permittedCache.contains(Whitelist.canonicalMethodSig(method)) || permittedCache.contains(Whitelist.canonicalMethodSigStar(method)); canonicalMethodSigStar adds * method.getName(). Analogously for permitsField</technical_language>

Target:
@Override public final boolean permitsMethod(Method method, Object receiver, Object[] args) { String key = canonicalMethodSig(method); Boolean b = permittedCache.get(key); if (b != null) { return b; } boolean output = false; for (MethodSignature s : methodSignatures()) { if (s.matches(method)) { output = true; break; } } permittedCache.put(key, output); return output; }
Source:
<code>public void verifyPushToTopWikiThumbnail() { <START> waitForElementByElement(pushToTopWikiThumbnail); <END> }</code><technical_language>add log() method for easier debugging</technical_language>

Target:
public void verifyPushToTopWikiThumbnail() { waitForElementByElement(pushToTopWikiThumbnail); PageObjectLogging.log("verifyPushToTopWikiThumbnail", "Push to top wiki thumbnail verified", true, driver); }
Source:
<code>public boolean doSomething(@NotNull PsiFile file, @NotNull Project project, @Nullable final VirtualFile virtualFile, @NotNull String groupId) throws ExecutionException { if (virtualFile == null || !virtualFile.isInLocalFileSystem()) return true; Document document = PsiDocumentManager.getInstance(project).getDocument(file); assert document != null; String filePath = virtualFile.getCanonicalPath(); assert filePath != null; GeneralCommandLine commandLine = new GeneralCommandLine(); String sdkHome = GoSdkService.getInstance().getSdkHomePath(project); if (StringUtil.isEmpty(sdkHome)) { warning(project, groupId, "Project sdk is not valid"); return true; } File executable = GoEnvironmentUtil.getExecutableForSdk(sdkHome); commandLine.setExePath(executable.getAbsolutePath()); commandLine.addParameters("fmt", filePath); <START> commandLine.setPassParentEnvironment(true); <END> FileDocumentManager.getInstance().saveDocument(document); String commandLineString = commandLine.getCommandLineString(); OSProcessHandler handler = new OSProcessHandler(commandLine.createProcess(), commandLineString); handler.addProcessListener(new ProcessAdapter() { @Override public void processTerminated(ProcessEvent event) { ApplicationManager.getApplication().invokeLater(new Runnable() { @Override public void run() { ApplicationManager.getApplication().runWriteAction(new Runnable() { @Override public void run() { virtualFile.refresh(false, false); } }); } }); } }); handler.startNotify(); return false; }</code><technical_language>true default</technical_language>

Target:
public boolean doSomething(@NotNull PsiFile file, @NotNull Project project, @Nullable final VirtualFile virtualFile, @NotNull String groupId) throws ExecutionException { if (virtualFile == null || !virtualFile.isInLocalFileSystem()) return true; Document document = PsiDocumentManager.getInstance(project).getDocument(file); assert document != null; String filePath = virtualFile.getCanonicalPath(); assert filePath != null; File executable = GoEnvironmentUtil.getBinaryFilePathFromEnvironment("gofmt"); if (executable == null) { warning(project, groupId, "Looks like you haven't any gofmt executable in your PATH"); return true; } FileDocumentManager.getInstance().saveDocument(document); GoExecutor. in(project). addParameters("fmt", filePath). showOutputOnError(). execute(); return false; }
Source:
<code>protected ToggleDetailPaneAction getToggleDetailPaneAction(String orientation) { for (ToggleDetailPaneAction <START> fToggleDetailPaneAction : <END> fToggleDetailPaneActions) { if (fToggleDetailPaneAction.getOrientation().equals(orientation)) { return fToggleDetailPaneAction; } } return null; }</code><technical_language>rename action</technical_language>

Target:
protected ToggleDetailPaneAction getToggleDetailPaneAction(String orientation) { for (ToggleDetailPaneAction action : fToggleDetailPaneActions) { if (action.getOrientation().equals(orientation)) { return action; } } return null; }
Source:
<code>public PlanNode visitMarkDistinct(MarkDistinctNode node, RewriteContext<Expression> context) { <START> if (!SymbolsExtractor.extractUnique(context.get()).contains(node.getMarkerSymbol())) { <END> return context.defaultRewrite(node, context.get()); } if (context.get() == TRUE_LITERAL) { return node; } return new FilterNode(idAllocator.getNextId(), node, context.get()); }</code><technical_language>more clever here, e.g: split predicate conjuncts push marker symbol</technical_language>

Target:
public PlanNode visitMarkDistinct(MarkDistinctNode node, RewriteContext<Expression> context) { Set<Symbol> pushDownableSymbols = ImmutableSet.copyOf(node.getDistinctSymbols()); Map<Boolean, List<Expression>> conjuncts = extractConjuncts(context.get()).stream() .collect(Collectors.partitioningBy(conjunct -> SymbolsExtractor.extractUnique(conjunct).stream().allMatch(pushDownableSymbols::contains))); PlanNode rewrittenNode = context.defaultRewrite(node, combineConjuncts(conjuncts.get(true))); if (!conjuncts.get(false).isEmpty()) { rewrittenNode = new FilterNode(idAllocator.getNextId(), rewrittenNode, combineConjuncts(conjuncts.get(false))); } return rewrittenNode; }
Source:
<code>public void serve() throws TException { Dispatcher dispatcher = conn.createDispatcher(newRequestHandler()); for (String subject : subjects) { if (queue != null && !queue.isEmpty()) { dispatcher.subscribe(subject, queue); } else { dispatcher.subscribe(subject); } } LOGGER.info("Frugal server running..."); try { shutdownSignal.await(); } catch (InterruptedException ignored) { } LOGGER.info("Frugal server stopping..."); <START> for (String subject : subjects) { <END> try { dispatcher.unsubscribe(subject); } catch (IllegalArgumentException e) { LOGGER.warn("Frugal server failed to unsubscribe from " + subject + ": " + e.getMessage()); } } }</code><technical_language>close dispatcher well. <LINK_0> docs unsubscribe well, verify case if</technical_language>

Target:
public void serve() throws TException { Dispatcher dispatcher = conn.createDispatcher(newRequestHandler()); for (String subject : subjects) { if (queue != null && !queue.isEmpty()) { dispatcher.subscribe(subject, queue); } else { dispatcher.subscribe(subject); } } LOGGER.info("Frugal server running..."); try { shutdownSignal.await(); } catch (InterruptedException ignored) { } LOGGER.info("Frugal server stopping..."); for (String subject : subjects) { try { dispatcher.unsubscribe(subject); } catch (IllegalStateException e) { LOGGER.warn("Frugal server failed to unsubscribe from " + subject + ": " + e.getMessage()); } } conn.closeDispatcher(dispatcher); }
Source:
<code>public void test() throws Exception { deleteDb("functions"); testOverrideAlias(); deleteDb("functions"); if (!config.networked) { JdbcConnection conn = (JdbcConnection) getConnection("functions"); Session session = (Session) conn.getSession(); testToDate(session); testToDateException(session); conn.close(); } testVersion(); testFunctionTable(); testFunctionTableVarArgs(); testArrayParameters(); testDefaultConnection(); testFunctionInSchema(); testGreatest(); testSource(); testDynamicArgumentAndReturn(); testUUID(); <START> testBase64(); <END> testWhiteSpacesInParameters(); testSchemaSearchPath(); testDeterministic(); testTransactionId(); testPrecision(); testVarArgs(); testAggregate(); testAggregateType(); testFunctions(); testFileRead(); testValue(); testNvl2(); testConcatWs(); testToCharFromDateTime(); testToCharFromNumber(); testToCharFromText(); testFileWrite(); testThatCurrentTimestampIsSane(); testThatCurrentTimestampStaysTheSameWithinATransaction(); testThatCurrentTimestampUpdatesOutsideATransaction(); testAnnotationProcessorsOutput(); testSignal(); deleteDb("functions"); }</code><technical_language>prefer pure SQL test cases, TestScript h2/src/test/org/h2/test/scripts/functions/string</technical_language>

Target:
public void test() throws Exception { deleteDb("functions"); testOverrideAlias(); deleteDb("functions"); if (!config.networked) { JdbcConnection conn = (JdbcConnection) getConnection("functions"); Session session = (Session) conn.getSession(); testToDate(session); testToDateException(session); conn.close(); } testVersion(); testFunctionTable(); testFunctionTableVarArgs(); testArrayParameters(); testDefaultConnection(); testFunctionInSchema(); testGreatest(); testSource(); testDynamicArgumentAndReturn(); testUUID(); testWhiteSpacesInParameters(); testSchemaSearchPath(); testDeterministic(); testTransactionId(); testPrecision(); testVarArgs(); testAggregate(); testAggregateType(); testFunctions(); testFileRead(); testValue(); testNvl2(); testConcatWs(); testToCharFromDateTime(); testToCharFromNumber(); testToCharFromText(); testFileWrite(); testThatCurrentTimestampIsSane(); testThatCurrentTimestampStaysTheSameWithinATransaction(); testThatCurrentTimestampUpdatesOutsideATransaction(); testAnnotationProcessorsOutput(); testSignal(); deleteDb("functions"); }
Source:
<code>public double getSafely() throws InvalidSensorException { if (!enable) { return F * setpoint; } double input = 0.0; input = sensor.pidGet(); double error = setpoint - input; if (continuous) { double range = inputMax - inputMin; if (Math.abs(error) > range / 2) { if (error > 0) { error -= range; } else { error += range; } } } <START> double errorDerivative = (error - lastError); <END> totalError += error; double result = P * error + I * totalError + D * errorDerivative + F * setpoint; lastError = error; LogKitten.v(input + " " + setpoint + " " + result); if (capOutput) { result = Math.max(Math.min(result, outputMax), outputMin); } return result; }</code><technical_language>errorDerivative calculated encoders properly finding difference in time run</technical_language>

Target:
public double getSafely() throws InvalidSensorException { if (!enable) { return F * setpoint; } double input = 0.0; input = sensor.pidGet(); double error = setpoint - input; if (continuous) { double range = inputMax - inputMin; if (Math.abs(error) > range / 2) { if (error > 0) { error -= range; } else { error += range; } } } double errorDerivative; long latestTime = System.currentTimeMillis(); long timeDiff = latestTime - lastTime; if (sensor instanceof NativeDerivativeSensor && sensor.getPIDSourceType() == PIDSourceType.kDisplacement) { errorDerivative = ((NativeDerivativeSensor) sensor).getRateSafely(); } else { errorDerivative = (error - lastError) / timeDiff; } lastTime = latestTime; totalError += error * timeDiff; double result = P * error + I * totalError + D * errorDerivative + F * setpoint; lastError = error; LogKitten.v(input + " " + setpoint + " " + result); if (capOutput) { result = Math.max(Math.min(result, outputMax), outputMin); } if (Math.abs(result) < minimumNominalOutput) { result = Math.signum(result) * minimumNominalOutput; } return result; }
Source:
<code>public void shouldSaveARemoteIdentifierGenerator() throws Exception { long initialIdentifierSourceCount = getAllCount(); SimpleObject identifierSource = new SimpleObject(); identifierSource.add("name", "test remote identifier"); identifierSource.add("description", "test remote identifier"); identifierSource.add("url", "http://localhost"); identifierSource.add("username", "openmrsuser"); identifierSource.add("password", "openmrspassword"); identifierSource.add("identifierType", IDENTIFIER_TYPE_UUID); identifierSource.add("sourceType", "RemoteIdentifierSource"); String jsonIdentifierSource = new ObjectMapper().writeValueAsString(identifierSource); MockHttpServletRequest req = newPostRequest(getURI(), jsonIdentifierSource); handle(req); <START> assertEquals(service.getAllIdentifierSources(false).get(7).getName(), "test remote identifier"); <END> assertEquals(initialIdentifierSourceCount + 1, getAllCount()); }</code><technical_language>assert of properties posted saved</technical_language>

Target:
public void shouldSaveARemoteIdentifierGenerator() throws Exception { long initialIdentifierSourceCount = getAllCount(); SimpleObject identifierSource = new SimpleObject(); identifierSource.add("name", "test remote identifier"); identifierSource.add("description", "This is a test description for the remote identifier"); identifierSource.add("url", "http://localhost"); identifierSource.add("username", "openmrsuser"); identifierSource.add("password", "openmrspassword"); identifierSource.add("identifierType", IDENTIFIER_TYPE_UUID); identifierSource.add("sourceType", REMOTE_IDENTIFIER_SOURCE_TYPE); String jsonIdentifierSource = new ObjectMapper().writeValueAsString(identifierSource); MockHttpServletRequest req = newPostRequest(getURI(), jsonIdentifierSource); SimpleObject newIdentifierSource = deserialize(handle(req)); String newIdentifierSourceUuid = PropertyUtils.getProperty(newIdentifierSource, "uuid").toString(); RemoteIdentifierSource generatedIdentifierSource = (RemoteIdentifierSource) service.getIdentifierSourceByUuid(newIdentifierSourceUuid); assertEquals(newIdentifierSourceUuid, generatedIdentifierSource.getUuid()); assertEquals(generatedIdentifierSource.getName(), "test remote identifier"); assertEquals(generatedIdentifierSource.getDescription(), "This is a test description for the remote identifier"); assertEquals(generatedIdentifierSource.getUrl(), "http://localhost"); assertEquals(generatedIdentifierSource.getUser(), "openmrsuser"); assertEquals(generatedIdentifierSource.getPassword(), "openmrspassword"); assertEquals(generatedIdentifierSource.getIdentifierType().getUuid(), IDENTIFIER_TYPE_UUID); assertEquals(initialIdentifierSourceCount + 1, getAllCount()); }
Source:
<code>private Certificate generateCertificate() throws Exception { InputStream stream = new ByteArrayInputStream(publicCertificate); CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); Certificate certificate = certificateFactory.generateCertificate(stream); <START> stream.close(); <END> return certificate; }</code><technical_language>try-with-resources this: java try (InputStream stream = new ByteArrayInputStream(publicCertificate)) { CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); return certificateFactory.generateCertificate(stream); }</technical_language>

Target:
private Certificate generateCertificate() throws IOException, CertificateException { try (InputStream stream = new ByteArrayInputStream(publicCertificate)) { CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); return certificateFactory.generateCertificate(stream); } }
Source:
<code>public ScoredDocuments rerank(ScoredDocuments docs, RerankerContext context) { IndexReader reader = context.getIndexSearcher().getIndexReader(); String queryDocId = context.getQueryDocId(); final Map<String, Long> queryTermsMap = convertDocVectorToMap(reader, queryDocId); List<Map<String, Long>> docsVectorsMap = new ArrayList<>(); for (int i = 0; i < docs.documents.length; i++) { String docid = docs.documents[i].getField(FIELD_ID).stringValue(); docsVectorsMap.add(convertDocVectorToMap(reader, docid)); } <START> Set<Integer> forbiddenDocIdsIndex = new HashSet<>(); <END> for (int i = 0; i < docs.documents.length; i++) { if (forbiddenDocIdsIndex.contains(i)) continue; String docid = docs.documents[i].getField(FIELD_ID).stringValue(); if (computeCosineSimilarity(queryTermsMap, docsVectorsMap.get(i)) >= 0.9) { forbiddenDocIdsIndex.add(i); continue; } for (int j = i+1; j < docs.documents.length; j++) { if (computeCosineSimilarity(docsVectorsMap.get(i), docsVectorsMap.get(j)) >= 0.9) { forbiddenDocIdsIndex.add(j); } } } ScoredDocuments scoredDocs = new ScoredDocuments(); int resSize = docs.documents.length - forbiddenDocIdsIndex.size(); scoredDocs.documents = new Document[resSize]; scoredDocs.ids = new int[resSize]; scoredDocs.scores = new float[resSize]; int idx = 0; for (int i = 0; i < docs.documents.length; i++) { if (!forbiddenDocIdsIndex.contains(i)) { scoredDocs.documents[idx] = docs.documents[i]; scoredDocs.scores[idx] = docs.scores[i]; scoredDocs.ids[idx] = docs.ids[i]; idx++; } } return scoredDocs; }</code><technical_language>"forbidden" sounds scary... "duplicates"</technical_language>

Target:
public ScoredDocuments rerank(ScoredDocuments docs, RerankerContext context) { IndexReader reader = context.getIndexSearcher().getIndexReader(); String queryDocId = context.getQueryDocId(); final Map<String, Long> queryTermsMap = convertDocVectorToMap(reader, queryDocId); List<Map<String, Long>> docsVectorsMap = new ArrayList<>(); for (int i = 0; i < docs.documents.length; i++) { String docid = docs.documents[i].getField(FIELD_ID).stringValue(); docsVectorsMap.add(convertDocVectorToMap(reader, docid)); } Set<Integer> duplicates = new HashSet<>(); for (int i = 0; i < docs.documents.length; i++) { if (duplicates.contains(i)) continue; String docid = docs.documents[i].getField(FIELD_ID).stringValue(); if (computeCosineSimilarity(queryTermsMap, docsVectorsMap.get(i)) >= 0.9) { duplicates.add(i); continue; } for (int j = i+1; j < docs.documents.length; j++) { if (computeCosineSimilarity(docsVectorsMap.get(i), docsVectorsMap.get(j)) >= 0.9) { duplicates.add(j); } } } ScoredDocuments scoredDocs = new ScoredDocuments(); int resSize = docs.documents.length - duplicates.size(); scoredDocs.documents = new Document[resSize]; scoredDocs.ids = new int[resSize]; scoredDocs.scores = new float[resSize]; int idx = 0; for (int i = 0; i < docs.documents.length; i++) { if (!duplicates.contains(i)) { scoredDocs.documents[idx] = docs.documents[i]; scoredDocs.scores[idx] = docs.scores[i]; scoredDocs.ids[idx] = docs.ids[i]; idx++; } } return scoredDocs; }
Source:
<code>DeviceToNodeMetadata(PlanToHardware planToHardware, OperatingSystemToImage operatingSystemToImage, FacilityToLocation facilityToLocation, Function<Device.State, NodeMetadata.Status> toPortableStatus, GroupNamingConvention.Factory groupNamingConvention) { <START> this.planToHardware = checkNotNull(planToHardware, "planToHardware cannot be null"); <END> this.operatingSystemToImage = checkNotNull(operatingSystemToImage, "operatingSystemToImage cannot be null"); this.facilityToLocation = checkNotNull(facilityToLocation, "facilityToLocation cannot be null"); this.toPortableStatus = checkNotNull(toPortableStatus, "toPortableStatus cannot be null"); this.groupNamingConvention = checkNotNull(groupNamingConvention, "groupNamingConvention cannot be null") .createWithoutPrefix(); }</code><technical_language>need for null checks in injection constructors</technical_language>

Target:
DeviceToNodeMetadata(PlanToHardware planToHardware, OperatingSystemToImage operatingSystemToImage, FacilityToLocation facilityToLocation, Function<Device.State, NodeMetadata.Status> toPortableStatus, GroupNamingConvention.Factory groupNamingConvention) { this.planToHardware = planToHardware; this.operatingSystemToImage = operatingSystemToImage; this.facilityToLocation = facilityToLocation; this.toPortableStatus = toPortableStatus; this.groupNamingConvention = groupNamingConvention.createWithoutPrefix(); }
Source:
<code>private void onEvent(CoreEvent event, ExecutorCallback executorCallback) { try { SdkInternalContext sdkInternalContext = <START> ((SdkInternalContext) ((InternalEvent) event).<SdkInternalContext>getSdkInternalContext()); <END> final Optional<ConfigurationInstance> configuration = sdkInternalContext.getConfiguration(); final Map<String, Object> resolutionResult = sdkInternalContext.getResolutionResult(); OperationExecutionFunction operationExecutionFunction = (parameters, operationEvent, callback) -> { sdkInternalContext.setOperationExecutionParams(configuration, parameters, operationEvent, callback); fluxSupplier.get().next(operationEvent); }; if (getLocation() != null) { ((DefaultFlowCallStack) event.getFlowCallStack()) .setCurrentProcessorPath(resolvedProcessorRepresentation); sdkInternalContext.getPolicyToApply().process(event, operationExecutionFunction, () -> resolutionResult, getLocation(), executorCallback); } else { operationExecutionFunction.execute(resolutionResult, event, executorCallback); } } catch (Throwable t) { executorCallback.error(unwrap(t)); } }</code><technical_language>extract static method in org.mule.runtime.module.extension.api.util.MuleExtensionUtils</technical_language>

Target:
private void onEvent(CoreEvent event, ExecutorCallback executorCallback) { try { SdkInternalContext sdkInternalContext = from(event); final Optional<ConfigurationInstance> configuration = sdkInternalContext.getConfiguration(); final Map<String, Object> resolutionResult = sdkInternalContext.getResolutionResult(); OperationExecutionFunction operationExecutionFunction = (parameters, operationEvent, callback) -> { sdkInternalContext.setOperationExecutionParams(configuration, parameters, operationEvent, callback); fluxSupplier.get().next(operationEvent); }; if (getLocation() != null) { ((DefaultFlowCallStack) event.getFlowCallStack()) .setCurrentProcessorPath(resolvedProcessorRepresentation); sdkInternalContext.getPolicyToApply().process(event, operationExecutionFunction, () -> resolutionResult, getLocation(), executorCallback); } else { operationExecutionFunction.execute(resolutionResult, event, executorCallback); } } catch (Throwable t) { executorCallback.error(unwrap(t)); } }
Source:
<code>public List<Channel> getChannelsOfGroup(String channelGroupId) { List<Channel> channels = new ArrayList<>(); for (Channel channel : this.channels) { ChannelUID channelUID = channel.getUID(); if (channelUID.isInGroup() && channelUID.getGroupId().equals(channelGroupId)) { channels.add(channel); } } <START> return Collections.unmodifiableList(channels); <END> }</code><technical_language>reason unmodifiable list list is a newly created one</technical_language>

Target:
public List<Channel> getChannelsOfGroup(String channelGroupId) { List<Channel> channels = new ArrayList<>(); for (Channel channel : this.channels) { if (channelGroupId.equals(channel.getUID().getGroupId())) { channels.add(channel); } } return Collections.unmodifiableList(channels); }
Source:
<code>public void delete(final OperatorChain query) { <START> synchronized (sharedLock) { <END> activeQueryWaitingQueue.remove(query); activeQueryWorkingQueue.remove(query); } }</code><technical_language>synchronized</technical_language>

Target:
public void delete(final OperatorChain query) { activeQueryQueue.remove(query); }
Source:
<code>public void updateCatalog(Table table, long genId) { m_es.execute(new Runnable() { public void run() { <START> if (genId != m_previousGenId) { <END> assert (genId > m_previousGenId); StreamTableSchemaSerializer ds = new StreamTableSchemaSerializer(table, table.getTypeName(), genId); try { m_committedBuffers.updateSchema(ds); } catch (IOException e) { VoltDB.crashLocalVoltDB("Unable to write PBD export header.", true, e); } m_previousGenId = genId; } } }); }</code><technical_language>I check equality add a runable if needed avoid unneeded runs</technical_language>

Target:
public void updateCatalog(Table table, long genId) { if (m_previousGenId >= genId) { return; } m_es.execute(new Runnable() { public void run() { if (m_previousGenId < genId) { StreamTableSchemaSerializer ds = new StreamTableSchemaSerializer(table, table.getTypeName(), genId); try { m_committedBuffers.updateSchema(ds); } catch (IOException e) { VoltDB.crashLocalVoltDB("Unable to write PBD export header.", true, e); } m_previousGenId = genId; } } }); }
Source:
<code>public static String getPathInDocument(Document document, String path) <START> throws InterceptorException { <END> if (document == null) { throw new InterceptorException("document may not be null"); } if (StringUtils.isEmpty(path)) { throw new InterceptorException("Missing parameter path"); } String result; try { XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xpath = xPathfactory.newXPath(); XPathExpression expr = xpath.compile(path); result = expr.evaluate(document, XPathConstants.STRING).toString(); } catch (XPathExpressionException e) { throw new InterceptorException("Could not : " + e.getMessage()); } return result; }</code><technical_language>This utility class (even is in interceptor context) throw InterceptorException some other exception</technical_language>

Target:
public static String getPathInDocument(Document document, String path) throws InterceptorException { if (document == null) { throw new InterceptorException("Document may not be null"); } if (StringUtils.isEmpty(path)) { throw new InterceptorException("Missing parameter path"); } String result; try { XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xpath = xPathfactory.newXPath(); XPathExpression expr = xpath.compile(path); result = expr.evaluate(document, XPathConstants.STRING).toString(); } catch (XPathExpressionException e) { throw new InterceptorException("Error while selecting document " + "element with XPath: " + e.getMessage()); } return result; }
Source:
<code>public static void createTables(KeyValueService keyValueService) { keyValueService.createTables(ImmutableMap.of( TransactionConstants.TRANSACTION_TABLE, TransactionConstants.TRANSACTION_TABLE_METADATA.persistToBytes(), TransactionConstants.TRANSACTIONS2_TABLE, <START> TransactionConstants.TRANSACTIONS2_METADATA.persistToBytes())); <END> }</code><technical_language>discuss offline. I this is fine, creating tx1 tx2 feels a bit strange me</technical_language>

Target:
public static void createTables(KeyValueService keyValueService) { keyValueService.createTables(ImmutableMap.of( TransactionConstants.TRANSACTION_TABLE, TransactionConstants.TRANSACTION_TABLE_METADATA.persistToBytes(), TransactionConstants.TRANSACTIONS2_TABLE, TransactionConstants.TRANSACTIONS2_TABLE_METADATA.persistToBytes())); }
Source:
<code>public void testSettingVariableWithSetWithMemory() throws Throwable { MIStoppedEvent stoppedEvent = SyncUtil.runToLocation("testMemoryChanges"); final IFrameDMContext frameDmc = SyncUtil.getStackFrame(stoppedEvent.getDMContext(), 0); final IExpressionDMContext exprDmc = SyncUtil.createExpression(frameDmc, "i"); Query<IExpressionDMAddress> query = new Query<IExpressionDMAddress>() { @Override protected void execute(final DataRequestMonitor<IExpressionDMAddress> rm) { fExprService.getExpressionAddressData(exprDmc, rm); } }; fSession.getExecutor().execute(query); IExpressionDMAddress data = query.get(); IMemoryDMContext memoryDmc = DMContexts.getAncestorOfType(frameDmc, IMemoryDMContext.class); readMemory(memoryDmc, data.getAddress(), 1); fEventsReceived.clear(); <START> final String NEW_VALUE = "100"; <END> queueConsoleCommand("set variable i=" + NEW_VALUE); IMemoryChangedEvent memoryEvent = waitForEvent(IMemoryChangedEvent.class); assertEquals(1, memoryEvent.getAddresses().length); assertEquals(data.getAddress(), memoryEvent.getAddresses()[0]); MemoryByte[] memory = readMemory(memoryDmc, data.getAddress(), 1); assertEquals(NEW_VALUE, Byte.toString(memory[0].getValue())); String exprValue = SyncUtil.getExpressionValue(exprDmc, IFormattedValues.DECIMAL_FORMAT); assertEquals(NEW_VALUE, exprValue); }</code><technical_language>uppercase letters for static variables. "NEW_VALUE" is a local variable. I suggest consistent de facto coding standard</technical_language>

Target:
public void testSettingVariableWithSetWithMemory() throws Throwable { MIStoppedEvent stoppedEvent = SyncUtil.runToLocation("testMemoryChanges"); final IFrameDMContext frameDmc = SyncUtil.getStackFrame(stoppedEvent.getDMContext(), 0); final IExpressionDMContext exprDmc = SyncUtil.createExpression(frameDmc, "i"); Query<IExpressionDMAddress> query = new Query<IExpressionDMAddress>() { @Override protected void execute(final DataRequestMonitor<IExpressionDMAddress> rm) { fExprService.getExpressionAddressData(exprDmc, rm); } }; fSession.getExecutor().execute(query); IExpressionDMAddress data = query.get(); IMemoryDMContext memoryDmc = DMContexts.getAncestorOfType(frameDmc, IMemoryDMContext.class); readMemory(memoryDmc, data.getAddress(), 1); fEventsReceived.clear(); final String newValue = "100"; queueConsoleCommand("set variable i=" + newValue); IMemoryChangedEvent memoryEvent = waitForEvent(IMemoryChangedEvent.class); assertEquals(1, memoryEvent.getAddresses().length); assertEquals(data.getAddress(), memoryEvent.getAddresses()[0]); MemoryByte[] memory = readMemory(memoryDmc, data.getAddress(), 1); assertEquals(newValue, Byte.toString(memory[0].getValue())); String exprValue = SyncUtil.getExpressionValue(exprDmc, IFormattedValues.DECIMAL_FORMAT); assertEquals(newValue, exprValue); }
Source:
<code>public synchronized void resumeAction() { if (isSuspended) { clearAction(); if (!suspendedActions.isEmpty()) { actions.addAll(suspendedActions); suspendedActions.clear(); } else { value = suspendedValue; } isSuspended = false; logger.trace("resuming suspended actions for channel {}", this); } else { <START> logger.warn("trying to resume actions in non-suspended channel {}", this); <END> } }</code><technical_language>Bug situation? -> exception</technical_language>

Target:
public synchronized void resumeAction() throws IllegalStateException { if (isSuspended) { clearAction(); if (!suspendedActions.isEmpty()) { actions.addAll(suspendedActions); suspendedActions.clear(); } else { value = suspendedValue; } isSuspended = false; logger.trace("resuming suspended actions for channel {}", this); } else { throw new IllegalStateException("trying to resume actions in non-suspended channel " + this.toString()); } }
Source:
<code>public void rangeWrite(CorfuPayloadMsg<RangeWriteMsg> msg, ChannelHandlerContext ctx, IServerRouter r) { List<LogData> range = msg.getPayload().getEntries(); log.debug("rangeWrite: Writing entries [{}-{}]", range.size(), range.get(0).getGlobalAddress(), range.get(range.size() - 1).getGlobalAddress()); batchWriter.addTask(RANGE_WRITE, msg) .thenAccept(Void -> r.sendResponse(ctx, msg, CorfuMsgType.WRITE_OK.msg())) .exceptionally(ex -> { handleException(ex, ctx, msg, r); return null; <START> }); <END> }</code><technical_language>I return null. please replace exceptionally() handle(...) whenCompleted(...)</technical_language>

Target:
public void rangeWrite(CorfuPayloadMsg<RangeWriteMsg> msg, ChannelHandlerContext ctx, IServerRouter r) { List<LogData> range = msg.getPayload().getEntries(); log.debug("rangeWrite: Writing entries [{}-{}]", range.size(), range.get(0).getGlobalAddress(), range.get(range.size() - 1).getGlobalAddress()); batchWriter.addTask(RANGE_WRITE, msg) .thenRun(() -> r.sendResponse(ctx, msg, CorfuMsgType.WRITE_OK.msg())) .exceptionally(ex -> { handleException(ex, ctx, msg, r); return null; }); }
Source:
<code>public Object finalizeComputation(@Nullable Object object) { <START> return object == null ? object : ((SerializablePair<Long, Float>) object).rhs; <END> }</code><technical_language>Double* variant of this class object == null ? null is</technical_language>

Target:
public Object finalizeComputation(@Nullable Object object) { return object == null ? null : ((SerializablePair<Long, Float>) object).rhs; }
Source:
<code>public void testCollector() { final CollectorAsserterMonitor mon = new CollectorAsserterMonitor(); final int[] numLoops = new int[] { 10000 }; IProgressMonitorWithBlocking wrapper = ProgressMonitorUtil.createAccumulatingProgressMonitor(mon, Display.getDefault()); wrapper.beginTask("Some Task", 100); for (int i = 0; i < numLoops[0]; i++) { wrapper.setTaskName("Task Name " + i); } wrapper.done(); ArrayList<String> tasks = mon.getTaskNames(); int size = tasks.size(); assertEquals(0, size); runEventLoopUntilEmpty(); tasks = mon.getTaskNames(); size = tasks.size(); <START> assertEquals(1, size); <END> }</code><technical_language>Suggest adding assert task name in list corresponds invocation of setTaskName(...)</technical_language>

Target:
public void testCollector() { final CollectorAsserterMonitor mon = new CollectorAsserterMonitor(); final int[] numLoops = new int[] { 10000 }; IProgressMonitorWithBlocking wrapper = ProgressMonitorUtil.createAccumulatingProgressMonitor(mon, Display.getDefault()); wrapper.beginTask("Some Task", 100); for (int i = 0; i < numLoops[0]; i++) { wrapper.setTaskName("Task Name " + i); } wrapper.done(); ArrayList<String> tasks = mon.getTaskNames(); int size = tasks.size(); assertEquals(0, size); runEventLoopUntilEmpty(); tasks = mon.getTaskNames(); size = tasks.size(); assertEquals(1, size); String expected = "Task Name " + (numLoops[0] - 1); assertEquals(expected, tasks.get(0)); }
Source:
<code>public void getMrrtReportTemplateByIdentifier_shouldFindObjectGivenValidIdentifier() throws Exception { MrrtReportTemplate template = mrrtReportTemplateService.getMrrtReportTemplateByIdentifier("identifier1"); assertNotNull(template); assertThat(template.getDcTermsIdentifier(), is("identifier1")); <START> assertThat(template.getDcTermsTitle(), is("title1")); <END> }</code><technical_language>@ivange94 remove assertion for title, do identifier</technical_language>

Target:
public void getMrrtReportTemplateByIdentifier_shouldFindObjectGivenValidIdentifier() throws Exception { MrrtReportTemplate template = mrrtReportTemplateService.getMrrtReportTemplateByIdentifier("identifier1"); assertNotNull(template); assertThat(template.getDcTermsIdentifier(), is("identifier1")); }
Source:
<code>private String getText(IAtsWorkPackage workPackage) { String result = ""; <START> if (workPackage != null) { <END> if (workPackage.getActivityId() != null && workPackage.getActivityName() != null) { result = String.format("%s - %s", workPackage.getActivityId(), workPackage.getActivityName()); } } return result; }</code><technical_language>Want show values if exist. Consider: String activityId = Strings.isValid(workPackage.getActivityId()) ? workPackage.getActivityId() : ""; String activityName = Strings.isValid(workPackage.getActivityName()) ? workPackage.getActivityName() : ""; result = String.format("%s - %s", activityId, activityName);</technical_language>

Target:
private String getText(IAtsWorkPackage workPackage) { String result = ""; if (workPackage != null) { String activityId = Strings.isValid(workPackage.getActivityId()) ? workPackage.getActivityId() : ""; String activityName = Strings.isValid(workPackage.getActivityName()) ? workPackage.getActivityName() : ""; result = String.format("%s - %s", activityId, activityName); } return result; }
Source:
<code>public List<StructuredViewer> getViewers() { List<StructuredViewer> viewers = new ArrayList<StructuredViewer>(); IViewPart view = super.getPartForAction(); try { <START> Class<?> clazz = Class.forName("org.eclipse.search2.internal.ui.SearchView"); END> Method method = clazz.getMethod("getActivePage"); Page page = (Page) method.invoke(view); if (page.getControl() != null) { IWorkbenchSite site = page.getSite(); if (site != null) { ISelectionProvider provider = site.getSelectionProvider(); if (provider instanceof TreeViewer) { viewers.add((TreeViewer) provider); } } } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } return viewers; }</code><technical_language>do need reflection? cast view SearchView</technical_language>

Target:
public List<StructuredViewer> getViewers() { List<StructuredViewer> viewers = new ArrayList<StructuredViewer>(); updateCurrentPage(); if (page instanceof AbstractTextSearchViewPage) { try { Method getViewer = AbstractTextSearchViewPage.class.getDeclaredMethod("getViewer"); getViewer.setAccessible(true); StructuredViewer viewer = (StructuredViewer) getViewer.invoke(page); viewers.add(viewer); } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { e.printStackTrace(); } } return viewers; }
Source:
<code>public boolean isAlwaysTrue() { <START> return equiConditions.isEmpty() && allTrueLiteralNonEquiConditions; <END> }</code><technical_language>allTrueLiteralNonEquiConditions is here; caching isAlwaysTrue directly</technical_language>

Target:
public boolean isAlwaysTrue() { return isAlwaysTrue; }
Source:
<code>public void testFactoryFailureResultsInErrorEmission() { TestSubscriber<Object> ts = TestSubscriber.create(); final RuntimeException e = new RuntimeException(); Flowable.just(1).collect(new Callable<List<Integer>>() { @Override public List<Integer> call() throws Exception { throw e; } }, new BiConsumer<List<Integer>, Integer>() { @Override public void accept(List<Integer> list, Integer t) { list.add(t); } }).subscribe(ts); <START> ts.assertNoValues(); <END> ts.assertError(e); ts.assertNotComplete(); }</code><technical_language>instead throw TestException("Forced failure") simply java Flowable.just(1).collect(...) .test() .assertFailureAndMessage(TestException.class, "Forced failure");</technical_language>

Target:
public void testFactoryFailureResultsInErrorEmission() { final RuntimeException e = new RuntimeException(); Flowable.just(1).collect(new Callable<List<Integer>>() { @Override public List<Integer> call() throws Exception { throw e; } }, new BiConsumer<List<Integer>, Integer>() { @Override public void accept(List<Integer> list, Integer t) { list.add(t); } }) .test() .assertNoValues() .assertError(e) .assertNotComplete(); }
Source:
<code>private void parsePath(String path) { if (path == null || path.length() == 0 || path.charAt(0) != '/') { throw new IllegalArgumentException("URL path \"" + path + "\" on method " + method.getName() + " must start with '/'. (" + method.getName() + ")"); } String url = path; String query = null; int question = path.indexOf('?'); if (question != -1 && question < path.length() - 1) { url = path.substring(0, question); query = path.substring(question + 1); hasQueryParams = true; <START> Matcher queryMatcher = PATH_PARAMETERS.matcher(query); <END> if (queryMatcher.find()) { List<String> matches = new ArrayList<String>(); do { matches.add("{" + queryMatcher.group(1) + "}"); } while (queryMatcher.find()); throw new IllegalStateException("URL query string \"" + query + "\" on method " + method.getName() + " may not have replace block. Found: " + matches); } } Set<String> urlParams = parsePathParameters(path); requestUrl = url; requestUrlParamNames = urlParams; requestQuery = query; }</code><technical_language>queryMatcher --> pathParamMatcher</technical_language>

Target:
private void parsePath(String path) { if (path == null || path.length() == 0 || path.charAt(0) != '/') { throw new IllegalArgumentException("URL path \"" + path + "\" on method " + method.getName() + " must start with '/'. (" + method.getName() + ")"); } String url = path; String query = null; int question = path.indexOf('?'); if (question != -1 && question < path.length() - 1) { url = path.substring(0, question); query = path.substring(question + 1); hasQueryParams = true; Matcher queryParamMatcher = URL_PARAMETERS.matcher(query); if (queryParamMatcher.find()) { throw new IllegalStateException("URL query string \"" + query + "\" on method " + method.getName() + " may not have replace block."); } } Set<String> urlParams = parsePathParameters(path); requestUrl = url; requestUrlParamNames = urlParams; requestQuery = query; }
Source:
<code>static Map<String, List<String>> findQueryParamsGroupedByName(HttpServletRequest request) { <START> Map<String, List<String>> result = new HashMap<>(); <END> String query = request.getQueryString(); if (StringUtils.isEmpty(query)) { return result; } for (String value : StringUtils.tokenizeToStringArray(query, "&")) { if (value.contains("=")) { String key = value.substring(0, value.indexOf("=")); value = value.substring(value.indexOf("=") + 1, value.length()); if (!result.containsKey(key)) { ArrayList<String> listOfQueryValues = new ArrayList<>(); listOfQueryValues.add(value); result.put(key, listOfQueryValues); } else { result.get(key).add(value); } } } return result; }</code><technical_language>this simplify this code a bit UriComponentsBuilder.fromUriString(request.getRequestURI()).build().getQueryParams();</technical_language>

Target:
static Map<String, List<String>> findQueryParamsGroupedByName( HttpServletRequest request) { String query = request.getQueryString(); if (isEmpty(query)) { return emptyMap(); } return UriComponentsBuilder.fromUriString("?" + query).build().getQueryParams(); }
Source:
<code>public void testIsQuestionAnswered() { FeedbackQuestionAttributes question; ______TS("test question is answered by user"); question = getQuestionFromDatastore("qn1InSession1InCourse1"); try { assertTrue(fqLogic.isQuestionAnsweredByUser(question, "student1InCourse1@gmail.com")); } catch (EntityDoesNotExistException e) { signalDetectionOfWrongException(e.getMessage()); } try { assertFalse(fqLogic.isQuestionAnsweredByUser(question, "studentWithNoResponses@gmail.com")); } catch (EntityDoesNotExistException e) { signalDetectionOfWrongException(e.getMessage()); } List<FeedbackResponseAttributes> responses = new ArrayList<FeedbackResponseAttributes>(); assertFalse(fqLogic.isQuestionAnsweredByUser(question, "student1InCourse1@gmail.com", responses)); responses = frLogic.getFeedbackResponsesForQuestion(question.getId()); assertTrue(fqLogic.isQuestionAnsweredByUser(question, "student2InCourse1@gmail.com", responses)); ______TS("test question is fully answered by user"); try { assertTrue(fqLogic.isQuestionFullyAnsweredByUser(question, "student1InCourse1@gmail.com")); <START> } catch (EntityDoesNotExistException e) { <END> signalDetectionOfWrongException(e.getMessage()); } try { assertFalse(fqLogic.isQuestionFullyAnsweredByUser(question, "studentWithNoResponses@gmail.com")); } catch (EntityDoesNotExistException e) { signalDetectionOfWrongException(e.getMessage()); } ______TS("test question is fully answered by team"); try { assertFalse(fqLogic.isQuestionFullyAnsweredByTeam(question, "Team 1.1")); } catch (EntityDoesNotExistException e) { signalDetectionOfWrongException(e.getMessage()); } }</code><technical_language>if try try-catch simply test method throws Exception? result, right</technical_language>

Target:
public void testIsQuestionAnswered() throws Exception { FeedbackQuestionAttributes question; ______TS("test question is answered by user"); question = getQuestionFromDatastore("qn1InSession1InCourse1"); assertTrue(fqLogic.isQuestionAnsweredByUser(question, "student1InCourse1@gmail.com")); assertFalse(fqLogic.isQuestionAnsweredByUser(question, "studentWithNoResponses@gmail.com")); List<FeedbackResponseAttributes> responses = new ArrayList<FeedbackResponseAttributes>(); assertFalse(fqLogic.isQuestionAnsweredByUser(question, "student1InCourse1@gmail.com", responses)); responses = frLogic.getFeedbackResponsesForQuestion(question.getId()); assertTrue(fqLogic.isQuestionAnsweredByUser(question, "student2InCourse1@gmail.com", responses)); ______TS("test question is fully answered by user"); assertTrue(fqLogic.isQuestionFullyAnsweredByUser(question, "student1InCourse1@gmail.com")); assertFalse(fqLogic.isQuestionFullyAnsweredByUser(question, "studentWithNoResponses@gmail.com")); ______TS("test question is fully answered by team"); assertFalse(fqLogic.isQuestionFullyAnsweredByTeam(question, "Team 1.1")); }
Source:
<code>public boolean evalToNullIfParamIsNull(StatementContext context, int index) throws SQLException { <START> return false; <END> }</code><technical_language>strictly necessary, I this read return index == 0, this other parameters ok null</technical_language>

Target:
public boolean evalToNullIfParamIsNull(StatementContext context, int index) throws SQLException { return index == 0; }
Source:
<code>public static UserLayer createUserLayer(SimpleFeatureCollection fc, String uuid, String name, String desc, String source) <START> throws FactoryException, TransformException { <END> final SimpleFeatureType ft = fc.getSchema(); final UserLayer userLayer = new UserLayer(); userLayer.setUuid(uuid); userLayer.setLayer_name(ConversionHelper.getString(name, ft.getTypeName())); userLayer.setLayer_desc(ConversionHelper.getString(desc, "")); userLayer.setLayer_source(ConversionHelper.getString(source, "")); userLayer.setFields(parseFields(ft)); userLayer.setWkt(getWGS84ExtentAsWKT(fc)); return userLayer; }</code><technical_language>I wrap exceptions a ServiceException (in opinion) details interesting a list of exceptions is required. A bunch of exceptions a method throw lead a catch(Exception e) error handling. if problems calculating coverage/bounds for data treated a failure leave WKT empty. if transform fails a problem data treated a failure store invalid data. thoughts these</technical_language>

Target:
public static UserLayer createUserLayer(SimpleFeatureCollection fc, String uuid, String name, String desc, String source) { final SimpleFeatureType ft = fc.getSchema(); final UserLayer userLayer = new UserLayer(); userLayer.setUuid(uuid); userLayer.setLayer_name(ConversionHelper.getString(name, ft.getTypeName())); userLayer.setLayer_desc(ConversionHelper.getString(desc, "")); userLayer.setLayer_source(ConversionHelper.getString(source, "")); userLayer.setFields(parseFields(ft)); userLayer.setWkt(getWGS84ExtentAsWKT(fc)); return userLayer; }