auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private static void readAndSeekTrace(CtfTestTrace testTrace, String testName, boolean inGlobalSummary) { assumeTrue(testTrace.exists()); Performance perf = Performance.getDefault(); PerformanceMeter pm = perf.createPerformanceMeter(TEST_ID + '#' + testName); perf.tagAsSummary(pm, TEST_SUITE_NAME + ':' + testName, Dimension.CPU_TIME); if (inGlobalSummary) { perf.tagAsGlobalSummary(pm, TEST_SUITE_NAME + ':' + testName, Dimension.CPU_TIME); } for (int loops = 0; loops < LOOP_COUNT; loops++) { try (CTFTrace trace = testTrace.getTrace(); CTFTraceReader traceReader = new CTFTraceReader(trace);) { EventDefinition firstEvent = traceReader.getCurrentEventDef(); final long startTime = firstEvent.getTimestamp(); long endTime = startTime; while (traceReader.hasMoreEvents()) { EventDefinition ev = traceReader.getCurrentEventDef(); endTime = ev.getTimestamp(); traceReader.advance(); } List<Long> seekTimestamps = new LinkedList<>(); final long range = endTime - 4277198419110L; for (int i = 0; i < NB_SEEKS; i++) { seekTimestamps.add(startTime + (RND.nextLong() % range)); } pm.start(); for (Long ts : seekTimestamps) { traceReader.seek(ts); traceReader.advance(); } pm.stop(); } catch (CTFReaderException e) { <START> fail(); <END> } } pm.commit(); }</code><technical_language>a more verbose fail message useful</technical_language>

Target:
private static void readAndSeekTrace(CtfTestTrace testTrace, String testName, boolean inGlobalSummary) { assumeTrue(testTrace.exists()); Performance perf = Performance.getDefault(); PerformanceMeter pm = perf.createPerformanceMeter(TEST_ID + '#' + testName); perf.tagAsSummary(pm, TEST_SUITE_NAME + ':' + testName, Dimension.CPU_TIME); if (inGlobalSummary) { perf.tagAsGlobalSummary(pm, TEST_SUITE_NAME + ':' + testName, Dimension.CPU_TIME); } for (int loop = 0; loop < LOOP_COUNT; loop++) { try (CTFTrace trace = testTrace.getTrace(); CTFTraceReader traceReader = new CTFTraceReader(trace);) { EventDefinition firstEvent = traceReader.getCurrentEventDef(); final long startTime = firstEvent.getTimestamp(); long endTime = startTime; while (traceReader.hasMoreEvents()) { EventDefinition ev = traceReader.getCurrentEventDef(); endTime = ev.getTimestamp(); traceReader.advance(); } List<Long> seekTimestamps = new LinkedList<>(); final long range = endTime - startTime; for (int i = 0; i < NB_SEEKS; i++) { seekTimestamps.add(startTime + (RND.nextLong() % range)); } pm.start(); for (Long ts : seekTimestamps) { traceReader.seek(ts); traceReader.advance(); } pm.stop(); } catch (CTFReaderException e) { fail("Test failed at iteration " + loop + ':' + e.getMessage()); } } pm.commit(); }
Source:
<code>private boolean hasAccess(PID pid, String datastream) { <START> if (datastream.equals("IMAGE_JP2000") || datastream == null) { <END> datastream = JP2_ACCESS_COPY.getId(); } Permission permission = DatastreamPermissionUtil.getPermissionForDatastream(datastream); AgentPrincipals agent = AgentPrincipals.createFromThread(); LOG.debug("Checking if user has access to belonging to object {}.", agent.getUsername(), datastream, pid); return accessControlService.hasAccess(pid, agent.getPrincipals(), permission); }</code><technical_language>hmm, IMAGE_JP2000 is boxc3 name for datastream. update JP2Viewer.js request datastreams jp2 (I current datastream name). kind of funny hasAccess this default datastream behavior actual controller methods require datastream name in path</technical_language>

Target:
private boolean hasAccess(PID pid, String datastream) { if (datastream == null) { datastream = JP2_ACCESS_COPY.getId(); } Permission permission = DatastreamPermissionUtil.getPermissionForDatastream(datastream); AgentPrincipals agent = AgentPrincipals.createFromThread(); LOG.debug("Checking if user has access to belonging to object {}.", agent.getUsername(), datastream, pid); return accessControlService.hasAccess(pid, agent.getPrincipals(), permission); }
Source:
<code>public List<ModuleDefinition> findDefinitions(ModuleType type) { List<ModuleDefinition> results = new ArrayList<ModuleDefinition>(); String path = Paths.build(Paths.MODULES, type.toString()); try { List<String> children = zooKeeperConnection.getClient().getChildren().forPath(path); for (String child : children) { byte[] data = zooKeeperConnection.getClient().getData().forPath( Paths.build(Paths.MODULES, type.toString(), child)); if (data != null && data.length > 0) { ModuleDefinition composed = this.findDefinition(child, type); <START> if (composed != null) { <END> results.add(composed); } } } } catch (Exception e) { ZooKeeperUtils.wrapAndThrowIgnoring(e, KeeperException.NoNodeException.class); } return results; }</code><technical_language>ignore if composed module is null here. In case, fail fast. throw NoSuchModuleException here</technical_language>

Target:
public List<ModuleDefinition> findDefinitions(ModuleType type) { List<ModuleDefinition> results = new ArrayList<>(); String path = Paths.build(Paths.MODULES, type.toString()); try { List<String> children = zooKeeperConnection.getClient().getChildren().forPath(path); for (String child : children) { byte[] data = zooKeeperConnection.getClient().getData().forPath( Paths.build(Paths.MODULES, type.toString(), child)); if (data != null && data.length > 0) { ModuleDefinition composed = this.findDefinition(child, type); if (composed != null) { results.add(composed); } else { throw new NoSuchModuleException(child, type); } } } } catch (Exception e) { ZooKeeperUtils.wrapAndThrowIgnoring(e, KeeperException.NoNodeException.class); } return results; }
Source:
<code>public void run() { while (!testContext.isStopped()) { int key = random.nextInt(keyCount); int increment = random.nextInt(maxIncrement); int delayMs=0; if(maxProcessorDelayMs > 0){ <START> delayMs = random.nextInt(maxProcessorDelayMs) + minProcessorDelayMs; <END> } cache.invoke(key, new IncrementEntryProcessor(increment, delayMs)); increments[key] += increment; } sleepMs(completeTaskDelayMs); targetInstance.getList(basename).add(increments); }</code><technical_language>this means delayMs greater maxProcessorDelayMs. counter-intuitive. do this way: delayMs = random.nextInt((maxProcessorDelayMs - minProcessorDelayMs) + 1) + minProcessorDelayMs; besides I recommend move method (getRandomSleepMs() ?) main flow (your test scenario) easier read</technical_language>

Target:
public void run() { while (!testContext.isStopped()) { int key = random.nextInt(keyCount); int increment = random.nextInt(maxIncrement); int delayMs=0; if(maxProcessorDelayMs > 0){ delayMs = random.nextInt(maxProcessorDelayMs - minProcessorDelayMs) + minProcessorDelayMs; } cache.invoke(key, new IncrementEntryProcessor(increment, delayMs)); increments[key] += increment; } sleepMs(completeTaskDelayMs); targetInstance.getList(basename).add(increments); }
Source:
<code>private static void configureController(HierarchicalConfiguration<ImmutableNode> src, MgcpControllerConfiguration dst) { dst.setAddress(src.getString("address", MgcpControllerConfiguration.ADDRESS)); dst.setPort(src.getInt("port", MgcpControllerConfiguration.PORT)); <START> dst.setMgcpBufferSize(src.getInt("mgcpBuffer[@size]", MgcpControllerConfiguration.MGCP_BUFFER_SIZE)); <END> List<HierarchicalConfiguration<ImmutableNode>> endpoints = src.childConfigurationsAt("endpoints"); for (HierarchicalConfiguration<ImmutableNode> endpoint : endpoints) { MgcpEndpointConfiguration endpointConfig = new MgcpEndpointConfiguration(); endpointConfig.setName(endpoint.getString("[@name]")); endpointConfig.setRelayType(endpoint.getString("[@relay]", "mixer")); dst.addEndpoint(endpointConfig); } }</code><technical_language>bufferSize instead of mgcpBuffer[@size]</technical_language>

Target:
private static void configureController(HierarchicalConfiguration<ImmutableNode> src, MgcpControllerConfiguration dst) { dst.setAddress(src.getString("address", MgcpControllerConfiguration.ADDRESS)); dst.setPort(src.getInt("port", MgcpControllerConfiguration.PORT)); dst.setChannelBuffer(src.getInt("channelBuffer", MgcpControllerConfiguration.CHANNEL_BUFFER)); List<HierarchicalConfiguration<ImmutableNode>> endpoints = src.childConfigurationsAt("endpoints"); for (HierarchicalConfiguration<ImmutableNode> endpoint : endpoints) { MgcpEndpointConfiguration endpointConfig = new MgcpEndpointConfiguration(); endpointConfig.setName(endpoint.getString("[@name]")); endpointConfig.setRelayType(endpoint.getString("[@relay]", "mixer")); dst.addEndpoint(endpointConfig); } }
Source:
<code>public TestkitResponse process( TestkitState testkitState ) { return Optional.ofNullable( testkitState.getSessionStates().getOrDefault( data.sessionId, null ) ) .map( sessionState -> { Session session = sessionState.getSession(); session.readTransaction( tx -> <START> { <END> System.out.println( "Start" ); sessionState.setRetryableState( 0 ); String txId = testkitState.newId(); testkitState.getTransactions().put( txId, tx ); testkitState.getResponseWriter().accept( retryableTry( txId ) ); while ( true ) { testkitState.getProcessor().get(); switch ( sessionState.retryableState ) { case 0: break; case 1: return 0; case -1: if ( !"".equals( sessionState.retryableErrorId ) ) { throw testkitState.getErrors().get( sessionState.retryableErrorId ); } else { throw new RuntimeException( "Error from client in retryable tx" ); } } } } ); return retryableDone(); } ).orElseThrow( () -> new RuntimeException( "Could not find session" ) ); }</code><technical_language>handlers refactored out a method return fitting SAM type i.e public TransactionWork<TestkitResponse> handler() { return tx -> new TestkitResponse(); // } // session.readTransaction(handler()); I call lambdas lambda pyramid of death ;)</technical_language>

Target:
public TestkitResponse process( TestkitState testkitState ) { return Optional.ofNullable( testkitState.getSessionStates().getOrDefault( data.sessionId, null ) ) .map( sessionState -> { Session session = sessionState.getSession(); session.readTransaction( handle( testkitState, sessionState ) ); return retryableDone(); } ).orElseThrow( () -> new RuntimeException( "Could not find session" ) ); }
Source:
<code>public Observable<Boolean> copyMediaFile(String originFilePath, String destinationFilePath) { File originalFile = new File(originFilePath); try { boolean copied = fileHelper.copyFile(originalFile, new File(destinationFilePath)) == null; <START> if (copied) { <END> return Observable.error(new Exception("Error copying video file")); } else { originalFile.delete(); } return Observable.just(true); } catch (IOException e) { return Observable.error(e); } }</code><technical_language>variable feels weird. copied impression worked I throw error if copied == true. else e.g. failedToCopy? alternatively return string check null</technical_language>

Target:
public Observable<Boolean> copyMediaFile(String originFilePath, String destinationFilePath) { File originalFile = new File(originFilePath); try { String copiedFilePath = fileHelper .copyFile(originalFile, new File(destinationFilePath)); if (copiedFilePath != null) { originalFile.delete(); } else { return Observable.error(new Exception("Error copying video file")); } return Observable.just(true); } catch (IOException e) { return Observable.error(e); } }
Source:
<code>public AWSCredentials getCredentials() { getCredentialsCalled = true; return credentialsFetcher.getCredentials(); <START> } <END></code><technical_language>Is sufficient getCredentials() called? Suggestion - a stronger statement 'getCredentials() called succeeded' java public AWSCredentials getCredentials() { AWSCredentials creds = credentialsFetcher.getCredentials(); getCredentialsCalled = true; return creds; }</technical_language>

Target:
public AWSCredentials getCredentials() { AWSCredentials creds = credentialsFetcher.getCredentials(); getCredentialsCalled = true; return creds; }
Source:
<code>public void flush() throws IOException { if (started.get()) { Future future = exec.schedule(new ConsumerRunnable(), 0, TimeUnit.MILLISECONDS); try { future.get(FLUSH_TIMEOUT, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { log.error(e, e.getMessage()); <START> } <END> catch (ExecutionException e) { log.error(e, e.getMessage()); } catch (TimeoutException e) { log.error(e, e.getMessage()); } } }</code><technical_language>this fail receiving interrupt</technical_language>

Target:
public void flush() throws IOException { if (started.get()) { Future future = exec.schedule(new ConsumerRunnable(), 0, TimeUnit.MILLISECONDS); try { future.get(FLUSH_TIMEOUT, TimeUnit.MILLISECONDS); } catch (InterruptedException | ExecutionException | TimeoutException e) { if (e instanceof InterruptedException) { throw new RuntimeException("interrupted flushing elements from queue", e); } log.error(e, e.getMessage()); } } }
Source:
<code>protected int readNoFilter(int[] positions, int positionCount) throws IOException { int streamPosition = 0; for (int i = 0; i < positionCount; i++) { int position = positions[i]; if (position > streamPosition) { skip(position - streamPosition); streamPosition = position; } if (presentStream != null && !presentStream.nextBit()) { <START> if ((nonDeterministicFilter && filter.testNull()) || nullsAllowed) { <END> if (outputRequired) { nulls[outputPositionCount] = true; } outputPositionCount++; } } else { int scale = (int) scaleStream.next(); long rescale = Decimals.rescale(dataStream.nextLong(), scale, decimalType.getScale()); if (outputRequired) { values[outputPositionCount] = rescale; } if (nullsAllowed && presentStream != null) { nulls[outputPositionCount] = false; } outputPositionCount++; } outputPositions = positions; streamPosition++; } return streamPosition; }</code><technical_language>filter is null nullsAllowed is true</technical_language>

Target:
protected int readNoFilter(int[] positions, int positionCount) throws IOException { int streamPosition = 0; for (int i = 0; i < positionCount; i++) { int position = positions[i]; if (position > streamPosition) { skip(position - streamPosition); streamPosition = position; } if (presentStream != null && !presentStream.nextBit()) { nulls[i] = true; } else { values[i] = Decimals.rescale(dataStream.nextLong(), (int) scaleStream.next(), this.scale); if (presentStream != null) { nulls[i] = false; } } streamPosition++; } outputPositionCount = positionCount; return streamPosition; }
Source:
<code>public DoubleColumnSelector makeDoubleColumnSelector( IncrementalIndexStorageAdapter.EntryHolder currEntry, IncrementalIndex.DimensionDesc desc ) { final int dimIndex = desc.getIndex(); class IndexerDoubleColumnSelector implements DoubleColumnSelector { @Override public double get() { final Object[] dims = currEntry.getKey().getDims(); if (dimIndex >= dims.length) { <START> return 0L; <END> } float floatVal = (Float) dims[dimIndex]; return (double) floatVal; } @Override public void inspectRuntimeShape(RuntimeShapeInspector inspector) { } } return new IndexerDoubleColumnSelector(); }</code><technical_language>0.0</technical_language>

Target:
public DoubleColumnSelector makeDoubleColumnSelector( IncrementalIndexStorageAdapter.EntryHolder currEntry, IncrementalIndex.DimensionDesc desc ) { final int dimIndex = desc.getIndex(); class IndexerDoubleColumnSelector implements DoubleColumnSelector { @Override public double get() { final Object[] dims = currEntry.getKey().getDims(); if (dimIndex >= dims.length) { return 0.0; } float floatVal = (Float) dims[dimIndex]; return (double) floatVal; } @Override public void inspectRuntimeShape(RuntimeShapeInspector inspector) { } } return new IndexerDoubleColumnSelector(); }
Source:
<code>public void setUp() throws Exception { Admin admin = TEST_UTIL.getAdmin(); <START> if (admin.tableExists(TABLE_NAME)) { <END> TEST_UTIL.deleteTable(TABLE_NAME); } TableDescriptor tableDesc = TableDescriptorBuilder.newBuilder(TABLE_NAME) .setColumnFamily(ColumnFamilyDescriptorBuilder.of("fam1")).build(); int startKey = 0; int endKey = 80000; admin.createTable(tableDesc, Bytes.toBytes(startKey), Bytes.toBytes(endKey), 9); }</code><technical_language>this is race-y work properly if tests run in parallel. a junit rule get name of test method for table name</technical_language>

Target:
public void setUp() throws Exception { final TableName tableName = TableName.valueOf(name.getMethodName()); TableDescriptor tableDesc = TableDescriptorBuilder.newBuilder(tableName) .setColumnFamily(ColumnFamilyDescriptorBuilder.of("fam1")).build(); int startKey = 0; int endKey = 80000; TEST_UTIL.getAdmin().createTable(tableDesc, Bytes.toBytes(startKey), Bytes.toBytes(endKey), 9); }
Source:
<code>protected GoVisitor buildGoVisitor(@NotNull final ProblemsHolder holder, @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @Override public void visitCallExpr(@NotNull GoCallExpr o) { <START> String name = o.getExpression().getText().toLowerCase(); <END> if (name.lastIndexOf('.') != -1) { if (name.lastIndexOf('.') == name.length() - 1) { return; } name = name.substring(name.lastIndexOf('.') + 1); } if (!formattingFunctions.containsKey(name)) { return; } Integer position = formattingFunctions.get(name); List<GoExpression> arguments = o.getArgumentList().getExpressionList(); if (arguments.size() <= position) { return; } Integer placeholdersCount = getPlaceholders(arguments.get(position)); Integer parameterCount = arguments.size() - position - 1; if (!placeholdersCount.equals(parameterCount)) { PsiElement element = o.getExpression(); String message = String.format("Got %d placeholder(s) for %d arguments(s)", placeholdersCount, parameterCount); if (placeholdersCount < parameterCount) { element = arguments.get(position); } holder.registerProblem(element, message, ProblemHighlightType.GENERIC_ERROR_OR_WARNING); } } }; }</code><technical_language>Please extract method isFormattingFunction + I check real function declarations instead of call expressions. do that, resolve expression check a function name package. E.g.: java func = callExpression.getExpression().getReference().resolve() check func.getName check func.getContainingFile.getPackage func.getCointaningFile.getImportPath</technical_language>

Target:
protected GoVisitor buildGoVisitor(@NotNull final ProblemsHolder holder, @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @Override public void visitCallExpr(@NotNull GoCallExpr o) { PsiReference psiReference = o.getExpression().getReference(); if (psiReference == null) return; PsiElement resolved = psiReference.resolve(); if (!(resolved instanceof GoFunctionOrMethodDeclaration)) return; if (!isInCorrectPackage((GoFunctionOrMethodDeclaration)resolved)) return; String name = getName((GoFunctionOrMethodDeclaration)resolved); Integer placeholderPosition = FORMATTING_FUNCTIONS.get(name); List<GoExpression> arguments = o.getArgumentList().getExpressionList(); if (arguments.size() <= placeholderPosition) return; GoExpression placeholder = arguments.get(placeholderPosition); if (!isStringPlaceholder(placeholder)) { String message = "Value used for formatting text does not appear to be a string"; holder.registerProblem(placeholder, message, ProblemHighlightType.GENERIC_ERROR_OR_WARNING); return; } int parameterCount = arguments.size() - placeholderPosition - 1; int placeholdersCount = getPlaceholders(placeholder); if (placeholdersCount == -1 || placeholdersCount == parameterCount) return; String message = String.format("Got %d placeholder(s) for %d arguments(s)", placeholdersCount, parameterCount); holder.registerProblem(placeholder, message, ProblemHighlightType.GENERIC_ERROR_OR_WARNING); } }; }
Source:
<code>public SecretVaultValueReader(File activitiConfigFile) throws BPSFault { try (FileInputStream fileInputStream = new FileInputStream(activitiConfigFile)) { StAXOMBuilder builder = new StAXOMBuilder(fileInputStream); <START> activitiConfigElement = builder.getDocumentElement(); <END> secretResolver = SecretResolverFactory.create(activitiConfigElement, true); } catch (XMLStreamException | IOException e) { log.error("Unable to read activiti.xml file", e); throw new BPSFault("Failed to find activiti.xml", e); } }</code><technical_language>this error catch in I need log error print it. WDYT</technical_language>

Target:
public SecretVaultValueReader(File activitiConfigFile) throws BPSFault { try (FileInputStream fileInputStream = new FileInputStream(activitiConfigFile)) { StAXOMBuilder builder = new StAXOMBuilder(fileInputStream); activitiConfigElement = builder.getDocumentElement(); secretResolver = SecretResolverFactory.create(activitiConfigElement, true); } catch (XMLStreamException | IOException e) { throw new BPSFault("Failed to find activiti.xml", e); } }
Source:
<code>public Client setup() throws Exception { final Settings settings = Settings.builder() .put("node.name", InetAddress.getLocalHost().getHostName()) .put("discovery.zen.ping.multicast.enabled", false) .putArray("discovery.zen.ping.unicast.hosts", seeds) <START> .put("path.home", "/tmp/" + UUID.randomUUID()) <END> .build(); final Node node = NodeBuilder .nodeBuilder() .settings(settings) .client(true) .clusterName(clusterName) .node(); return node.client(); }</code><technical_language>of [Files.createTempDirectory()](<LINK_0>,%20java.nio.file.attribute.FileAttribute...%29) right already</technical_language>

Target:
public Client setup() throws Exception { final Settings settings = Settings .builder() .put("node.name", InetAddress.getLocalHost().getHostName()) .put("discovery.zen.ping.multicast.enabled", false) .putArray("discovery.zen.ping.unicast.hosts", seeds) .put("path.home", Files.createTempDirectory("tmp")) .build(); final Node node = NodeBuilder .nodeBuilder() .settings(settings) .client(true) .clusterName(clusterName) .node(); return node.client(); }
Source:
<code>public void intercept(HttpServletRequest req, HttpServletResponse resp) { ContentSecurityPolicy csp = BEANS.get(ContentSecurityPolicy.class).appendScriptSrc("'unsafe-inline'"); BrowserInfo browserInfo = BrowserInfo.createFrom(req); if (browserInfo.isWebkit()) { String resolvedSelfUri = m_browserUri.toString(); csp .appendImgSrc(resolvedSelfUri) .appendStyleSrc(resolvedSelfUri); } String cspToken = csp.toToken(); <START> resp.setHeader(HttpServletControl.HTTP_HEADER_CSP, cspToken); <END> if (browserInfo.isMshtml()) { resp.setHeader(HttpServletControl.HTTP_HEADER_CSP_LEGACY, cspToken); } }</code><technical_language>Send this header in "else" block of if? handle this header</technical_language>

Target:
public void intercept(HttpServletRequest req, HttpServletResponse resp) { ContentSecurityPolicy csp = BEANS.get(ContentSecurityPolicy.class).appendScriptSrc("'unsafe-inline'"); BrowserInfo browserInfo = BrowserInfo.createFrom(req); if (browserInfo.isWebkit()) { String resolvedSelfUri = m_browserUri.toString(); csp .appendImgSrc(resolvedSelfUri) .appendStyleSrc(resolvedSelfUri); } String cspToken = csp.toToken(); if (browserInfo.isMshtml()) { resp.setHeader(HttpServletControl.HTTP_HEADER_CSP_LEGACY, cspToken); } else { resp.setHeader(HttpServletControl.HTTP_HEADER_CSP, cspToken); } }
Source:
<code>private Mono<Boolean> ensureValidKeyAvailable() { <START> boolean keyAvailable = !(this.key == null && keyCollection != null); <END> if (!keyAvailable) { if (keyCollection.equals(SECRETS_COLLECTION)) { return getSecretKey().flatMap(jwk -> { this.key = new AtomicReference<>(jwk); initializeCryptoClients(); return Mono.just(this.key.get().isValid()); }); } else { return getKey().flatMap(kvKey -> { this.key = new AtomicReference<>(kvKey.getKey()); initializeCryptoClients(); return Mono.just(key.get().isValid()); }); } } else { return Mono.defer(() -> Mono.just(true)); } }</code><technical_language>Nit: line spends time negating, slows a readability more difficult. simplified</technical_language>

Target:
private Mono<Boolean> ensureValidKeyAvailable() { boolean keyNotAvailable = (this.key == null && keyCollection != null); if (keyNotAvailable) { if (keyCollection.equals(SECRETS_COLLECTION)) { return getSecretKey().map(jwk -> { this.key = (jwk); initializeCryptoClients(); return this.key.isValid(); }); } else { return getKey().map(kvKey -> { this.key = (kvKey.getKey()); initializeCryptoClients(); return key.isValid(); }); } } else { return Mono.defer(() -> Mono.just(true)); } }
Source:
<code>public String dateFormatChange(String time) { String k; DateTimeFormatter input_format = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz yyyy"); DateTimeFormatter output_format = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); LocalDateTime parsed_time = LocalDateTime.parse(time, input_format); ZonedDateTime final_time = <START> ZonedDateTime.of(parsed_time, ZoneId.of("Asia/Kolkata")) <END> .withZoneSameInstant(ZoneId.of("UTC+00:00")); k = String.valueOf(output_format.format(final_time)); return k; }</code><technical_language>please explain this? this hold everywhere</technical_language>

Target:
public String dateFormatChange(String time) { String k; DateTimeFormatter input_format = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz yyyy"); DateTimeFormatter output_format = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); LocalDateTime parsed_time = LocalDateTime.parse(time, input_format); ZonedDateTime ldtZoned = parsed_time.atZone(ZoneId.systemDefault()); ZonedDateTime final_time = ldtZoned.withZoneSameInstant(ZoneId.of("UTC")); k = String.valueOf(output_format.format(final_time)); return k; }
Source:
<code>private void deleteEntry(final int index) { final LocalItem infoItem = itemListAdapter.getItemsList() .get(index); if(infoItem instanceof StreamStatisticsEntry) { final StreamStatisticsEntry entry = (StreamStatisticsEntry) infoItem; final Disposable onDelte = recordManager.deleteStreamHistory(entry.streamId) .observeOn(AndroidSchedulers.mainThread()) .subscribe( <START> howManyDelted -> Snackbar.make(getView(), R.string.one_item_deleted, <END> Snackbar.LENGTH_SHORT).show(), throwable -> showSnackBarError(throwable, UserAction.DELETE_FROM_HISTORY, "none", "Deleting item failed", R.string.general_error)); disposables.add(onDelte); } }</code><technical_language>getView is called async call, user removed fragment call running a potential NPE coming main thread. Also, "onDelte" -> "onDelete"</technical_language>

Target:
private void deleteEntry(final int index) { final LocalItem infoItem = itemListAdapter.getItemsList() .get(index); if(infoItem instanceof StreamStatisticsEntry) { final StreamStatisticsEntry entry = (StreamStatisticsEntry) infoItem; final Disposable onDelete = recordManager.deleteStreamHistory(entry.streamId) .observeOn(AndroidSchedulers.mainThread()) .subscribe( howManyDelted -> { if(getView() != null) { Snackbar.make(getView(), R.string.one_item_deleted, Snackbar.LENGTH_SHORT).show(); } else { Toast.makeText(getContext(), R.string.one_item_deleted, Toast.LENGTH_SHORT).show(); } }, throwable -> showSnackBarError(throwable, UserAction.DELETE_FROM_HISTORY, "none", "Deleting item failed", R.string.general_error)); disposables.add(onDelete); } }
Source:
<code>public void shouldAuthoriseChargeForValidCardDetails() throws Exception { String uniqueChargeId = "983794837598475"; setupCharge(uniqueChargeId); given().port(app.getLocalPort()) .contentType(JSON) .body(validCardDetails) .post(cardUrlForChargeId(uniqueChargeId)) .then() <START> .statusCode(204); <END> assertChargeStatusIs(uniqueChargeId, "AUTHORIZATION SUCCESS"); }</code><technical_language>~~Response charge card details (masked) - please add assertions here.~~ implemented later</technical_language>

Target:
public void shouldAuthoriseChargeForValidCardDetails() throws Exception { String chargeId = createNewCharge(); givenSetup() .body(validCardDetails) .post(cardUrlFor(chargeId)) .then() .statusCode(204); assertChargeStatusIs(chargeId, "AUTHORIZATION SUCCESS"); }
Source:
<code>public void run(String workflowNameArg, String matchPattern) throws Exception { Properties systemProps = loadSystemProperties(); <START> systemProps.setProperty("environment", DigdagClient.objectMapper().writeValueAsString(env)); <END> try (DigdagEmbed digdag = new DigdagEmbed.Bootstrap() .setEnvironment(env) .setSystemPlugins(loadSystemPlugins(systemProps)) .addModules(binder -> { binder.bind(ResumeStateManager.class).in(Scopes.SINGLETON); binder.bind(YamlMapper.class).in(Scopes.SINGLETON); binder.bind(Run.class).toInstance(this); }) .overrideModulesWith((binder) -> { binder.bind(OperatorManager.class).to(OperatorManagerWithSkip.class).in(Scopes.SINGLETON); }) .initializeWithoutShutdownHook()) { run(systemProps, digdag.getInjector(), workflowNameArg, matchPattern); } }</code><technical_language>Is this needed? For future use</technical_language>

Target:
public void run(String workflowNameArg, String matchPattern) throws Exception { Properties systemProps = loadSystemProperties(); try (DigdagEmbed digdag = new DigdagEmbed.Bootstrap() .setEnvironment(env) .setSystemConfig(PropertyUtils.toConfigElement(systemProps)) .setSystemPlugins(loadSystemPlugins(systemProps)) .addModules(binder -> { binder.bind(SecretAccessPolicy.class).to(LocalSecretAccessPolicy.class).in(Scopes.SINGLETON); binder.bind(SecretStoreManager.class).to(LocalSecretStoreManager.class).in(Scopes.SINGLETON); binder.bind(ResumeStateManager.class).in(Scopes.SINGLETON); binder.bind(YamlMapper.class).in(Scopes.SINGLETON); binder.bind(Run.class).toInstance(this); }) .overrideModulesWith((binder) -> { binder.bind(OperatorManager.class).to(OperatorManagerWithSkip.class).in(Scopes.SINGLETON); }) .initializeWithoutShutdownHook()) { run(systemProps, digdag.getInjector(), workflowNameArg, matchPattern); } }
Source:
<code>private void setProperty(String envProperty, String initParam, Properties properties) { Environment env = context.getBean(Environment.class); String value = env <START> .getProperty(SharedUtil.camelCaseToDashSeparated(envProperty)); <END> if (value == null) { value = env.getProperty(envProperty); } if (value != null) { properties.put(initParam, value); } }</code><technical_language>dashseparated put case? string vaadin.productionMODE vaadin.production-mODE environment stores in case</technical_language>

Target:
private void setProperty(String envProperty, String initParam, Properties properties) { Environment env = context.getBean(Environment.class); String value = env.getProperty(upperCaseToDashSeparated(envProperty)); if (value == null) { value = env.getProperty(envProperty); } if (value != null) { properties.put(initParam, value); } }
Source:
<code>protected Void doInBackground(ServiceRequest... params) { synchronized (this) { while (mServiceRequestController == null) { try { this.wait(); } catch (InterruptedException e) { <START> e.printStackTrace(); <END> } } } mServiceRequestController.handleServiceRequest(params[0]); return null; }</code><technical_language>Adding a log instead of printing stack trace give a idea of wrong</technical_language>

Target:
protected Void doInBackground(ServiceRequest... params) { synchronized (this) { while (mServiceRequestController == null) { try { this.wait(); } catch (InterruptedException e) { Log.d("Y:" + this.getClass().getName(),e.getMessage()); } } } if (params.length > 0 && params[0] != null) { mServiceRequestController.handleServiceRequest(params[0]); } else { throw new IllegalArgumentException(); } return null; }
Source:
<code>public boolean isBinaryEquivalent(IDeclaration obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof StructDeclaration)) { return false; } StructDeclaration other = (StructDeclaration) obj; if (fFields.length != other.fFields.length) { return false; } <START> List<IDeclaration> localDecs = new ArrayList<>(); localDecs.addAll(Arrays.asList(fFields)); <END> List<IDeclaration> otherDecs = new ArrayList<>(); otherDecs.addAll(Arrays.asList(other.fFields)); for (int i = 0; i < fFields.length; i++) { if (!otherDecs.get(i).isBinaryEquivalent(localDecs.get(i))) { return false; } } if (fMaxAlign != other.fMaxAlign) { return false; } return true; }</code><technical_language>List<IDeclaration> localDecs = Arrays.asList(fFields);</technical_language>

Target:
public boolean isBinaryEquivalent(IDeclaration obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof StructDeclaration)) { return false; } StructDeclaration other = (StructDeclaration) obj; if (fFields.length != other.fFields.length) { return false; } List<IDeclaration> localDecs = Arrays.asList(fFields); List<IDeclaration> otherDecs = Arrays.asList(other.fFields); for (int i = 0; i < fFields.length; i++) { if (!otherDecs.get(i).isBinaryEquivalent(localDecs.get(i))) { return false; } } if (fMaxAlign != other.fMaxAlign) { return false; } return true; }
Source:
<code>public void onNext(final AllocatedEvaluator allocatedEvaluator) { if (dataLoader.isDataLoaderRequest()) { idMap.put(allocatedEvaluator.getId(), DataLoader.class.getName()); dataLoader.handleDataLoadingEvalAlloc(allocatedEvaluator); } else if (emResourceRequestManager.bindCallback(allocatedEvaluator)) { idMap.put(allocatedEvaluator.getId(), ElasticMemory.class.getName()); allocatedEvaluator.submitContextAndService(getContextConfiguration(), getServiceConfiguration()); } else { <START> LOG.warning("Unknown evaluator allocated. Ignore " + allocatedEvaluator.toString()); <END> } }</code><technical_language>close allocatedEvaluator if it</technical_language>

Target:
public void onNext(final AllocatedEvaluator allocatedEvaluator) { if (dataLoader.isDataLoaderRequest()) { evalToRequestorMap.put(allocatedEvaluator.getId(), DataLoader.class.getName()); dataLoader.handleDataLoadingEvalAlloc(allocatedEvaluator); } else if (emResourceRequestManager.bindCallback(allocatedEvaluator)) { evalToRequestorMap.put(allocatedEvaluator.getId(), ElasticMemory.class.getName()); allocatedEvaluator.submitContextAndService(getContextConfiguration(), getServiceConfiguration()); } else { LOG.warning("Unknown evaluator allocated. Ignore " + allocatedEvaluator); allocatedEvaluator.close(); } }
Source:
<code>public void execute(JPakeClient jClient) { Logger.debug(LOG_TAG, "Verifying their key."); ExtendedJSONObject verificationObj = jClient.jIncoming; if (!verificationObj.get(Constants.JSON_KEY_TYPE).equals( <START> jClient.theirSignerId + "3")) { <END> Logger.error(LOG_TAG, "Invalid round 3 message: " + verificationObj.toJSONString()); jClient.abort(Constants.JPAKE_ERROR_WRONGMESSAGE); return; } ExtendedJSONObject payload; try { payload = verificationObj .getObject(Constants.JSON_KEY_PAYLOAD); } catch (NonObjectJSONException e) { Logger.error(LOG_TAG, "JSON exception.", e); jClient.abort(Constants.JPAKE_ERROR_INVALID); return; } String theirCiphertext = (String) payload .get(Constants.JSON_KEY_CIPHERTEXT); String iv = (String) payload.get(Constants.JSON_KEY_IV); boolean correctPairing; try { correctPairing = verifyCiphertext(theirCiphertext, iv, jClient.myKeyBundle); } catch (UnsupportedEncodingException e) { Logger.error(LOG_TAG, "Unsupported encoding.", e); jClient.abort(Constants.JPAKE_ERROR_INTERNAL); return; } catch (CryptoException e) { Logger.error(LOG_TAG, "Crypto exception.", e); jClient.abort(Constants.JPAKE_ERROR_INTERNAL); return; } if (correctPairing) { Logger.debug(LOG_TAG, "Keys verified successfully."); jClient.paired = true; jClient.onPaired(); } else { Logger.error(LOG_TAG, "Keys don't match."); jClient.abort(Constants.JPAKE_ERROR_KEYMISMATCH); } }</code><technical_language>Split this some local variables readable</technical_language>

Target:
public void execute(JPakeClient jClient) { Logger.debug(LOG_TAG, "Verifying their key."); ExtendedJSONObject verificationObj = jClient.jIncoming; String signerId = (String) verificationObj.get(Constants.JSON_KEY_TYPE); if (!signerId.equals(jClient.theirSignerId + "3")) { Logger.error(LOG_TAG, "Invalid round 3 message: " + verificationObj.toJSONString()); jClient.abort(Constants.JPAKE_ERROR_WRONGMESSAGE); return; } ExtendedJSONObject payload; try { payload = verificationObj.getObject(Constants.JSON_KEY_PAYLOAD); } catch (NonObjectJSONException e) { Logger.error(LOG_TAG, "JSON exception.", e); jClient.abort(Constants.JPAKE_ERROR_INVALID); return; } String theirCiphertext = (String) payload.get(Constants.JSON_KEY_CIPHERTEXT); String iv = (String) payload.get(Constants.JSON_KEY_IV); boolean correctPairing; try { correctPairing = verifyCiphertext(theirCiphertext, iv, jClient.myKeyBundle); } catch (UnsupportedEncodingException e) { Logger.error(LOG_TAG, "Unsupported encoding.", e); jClient.abort(Constants.JPAKE_ERROR_INTERNAL); return; } catch (CryptoException e) { Logger.error(LOG_TAG, "Crypto exception.", e); jClient.abort(Constants.JPAKE_ERROR_INTERNAL); return; } if (correctPairing) { Logger.debug(LOG_TAG, "Keys verified successfully."); jClient.paired = true; jClient.onPaired(); } else { Logger.error(LOG_TAG, "Keys don't match."); jClient.abort(Constants.JPAKE_ERROR_KEYMISMATCH); } }
Source:
<code>private String queryServer() throws GAWrapperException, UnirestException, InvalidProtocolBufferException { final String url = makeUrl(urlRoot, path); if (wireTracker != null) { wireTracker.theUrl = url; } try { HttpResponse<JsonNode> response = queryServer(url); if (wireTracker != null) { wireTracker.bodyReceived = response.getBody().toString(); wireTracker.setResponseStatus(fromInt(response.getStatus())); } int httpStatus = response.getStatus(); if (httpStatus == HttpStatus.SC_OK) { return response.getBody().toString(); } else { String json = response.getBody().toString(); Common.GAException.Builder exceptionBuilder = Common.GAException.newBuilder(); try { JsonFormat.parser().merge(json, exceptionBuilder); } catch (InvalidProtocolBufferException e) { log.warn("Failure when processing GAException: BODY <" + json + ">: ", e.toString()); throw e; } <START> log.info("Throwing GAException for " + json + ", status " + httpStatus); <END> throw new GAWrapperException(exceptionBuilder.build(), httpStatus); } } catch (UnirestException e) { log.warn("problem communicating with " + url, e.getMessage()); log.debug(e.toString()); throw e; } }</code><technical_language>this want error, a more descriptive message</technical_language>

Target:
private String queryServer() throws GAWrapperException, UnirestException, InvalidProtocolBufferException { final String url = makeUrl(urlRoot, path); if (wireTracker != null) { wireTracker.theUrl = url; } try { HttpResponse<JsonNode> response = queryServer(url); if (wireTracker != null) { wireTracker.bodyReceived = response.getBody().toString(); wireTracker.setResponseStatus(fromInt(response.getStatus())); } int httpStatus = response.getStatus(); if (httpStatus == HttpStatus.SC_OK) { return response.getBody().toString(); } else { String json = response.getBody().toString(); Common.GAException.Builder exceptionBuilder = Common.GAException.newBuilder(); try { JsonFormat.parser().merge(json, exceptionBuilder); } catch (InvalidProtocolBufferException e) { log.warn("Failure when processing GAException: BODY <" + json + ">: ", e.toString()); throw e; } log.warn("Throwing GAException for " + json + ", status " + httpStatus); throw new GAWrapperException(exceptionBuilder.build(), httpStatus); } } catch (UnirestException e) { log.warn("problem communicating with " + url, e.getMessage()); throw e; } }
Source:
<code>public void benchmark() <START> throws ExecutionException, InterruptedException <END> { Semaphore semaphore = new Semaphore(futureCount); ArrayList<SettableFuture<?>> futures = new ArrayList<>(); for (int i = 0; i < futureCount; i++) { SettableFuture<?> future = SettableFuture.create(); future.addListener(() -> semaphore.release(1), directExecutor()); futures.add(future); } ListenableFuture<?> anyComplete = whenAnyCompleteCancelOthers(futures); futures.get(futureCount / 2).set(null); semaphore.acquireUninterruptibly(futureCount); anyComplete.get(); }</code><technical_language>throw Exception</technical_language>

Target:
public void benchmark() throws Exception { Semaphore semaphore = new Semaphore(futureCount); ArrayList<SettableFuture<?>> futures = new ArrayList<>(); for (int i = 0; i < futureCount; i++) { SettableFuture<?> future = SettableFuture.create(); future.addListener(() -> semaphore.release(1), directExecutor()); futures.add(future); } ListenableFuture<?> anyComplete = whenAnyCompleteCancelOthers(futures); futures.get(futureCount / 2).set(null); semaphore.acquireUninterruptibly(futureCount); anyComplete.get(); }
Source:
<code>public void addLiteralToForm(EditConfigurationVTwo editConfig, FieldVTwo field, String var, String[] valuesArray) { List<String> valueList = (valuesArray != null) ? Arrays.asList(valuesArray) : null; if( valueList != null && valueList.size() > 0 ) { List<Literal> literalsArray = new ArrayList<Literal>(); for(String value:valueList) { value = N3EditUtils.stripInvalidXMLChars(value); if (!StringUtils.isEmpty(value)) { String rangeLang = field.getRangeLang(); try { if (_vreq != null ) { <START> if (editConfig.getLiteralsInScope().get("label").get(0).getLanguage() != "") <END> { rangeLang = editConfig.getLiteralsInScope().get("label").get(0).getLanguage(); } else { rangeLang = _vreq.getLocale().getLanguage(); if (!_vreq.getLocale().getCountry().isEmpty()) { rangeLang += "-" + _vreq.getLocale().getCountry(); } } } } catch (Exception e) { } literalsArray.add(createLiteral( value, field.getRangeDatatypeUri(), rangeLang)); } } literalsFromForm.put(var, literalsArray); }else{ log.debug("could not find value for parameter " + var ); } }</code><technical_language>Instead of !=, !...equals(). ..or .isEmpty(). Is a chance language null? If so, StringUtils.isBlank()</technical_language>

Target:
public void addLiteralToForm(EditConfigurationVTwo editConfig, FieldVTwo field, String var, String[] valuesArray) { List<String> valueList = (valuesArray != null) ? Arrays.asList(valuesArray) : null; if( valueList != null && valueList.size() > 0 ) { List<Literal> literalsArray = new ArrayList<Literal>(); for(String value:valueList) { value = N3EditUtils.stripInvalidXMLChars(value); if (!StringUtils.isEmpty(value)) { String rangeLang = field.getRangeLang(); try { if (_vreq != null ) { Boolean getLabelLanguage = false; if (!StringUtils.isBlank(editConfig.formUrl) && editConfig.formUrl.contains("RDFSLabelGenerator")) { getLabelLanguage = true; } if (!StringUtils.isBlank(editConfig.getLiteralsInScope().get("label").get(0).getLanguage()) && getLabelLanguage) { rangeLang = editConfig.getLiteralsInScope().get("label").get(0).getLanguage(); } else { rangeLang = _vreq.getLocale().getLanguage(); if (!_vreq.getLocale().getCountry().isEmpty()) { rangeLang += "-" + _vreq.getLocale().getCountry(); } } } } catch (Exception e) { } literalsArray.add(createLiteral( value, field.getRangeDatatypeUri(), rangeLang)); } } literalsFromForm.put(var, literalsArray); }else{ log.debug("could not find value for parameter " + var ); } }
Source:
<code>public void shouldRemoveNonExistingElement() { final Seq<Integer> t = of(1, 2, 3); assertThat(t.remove(4)).isEqualTo(t); <START> assertNotSame(t, t.remove(4)); <END> }</code><technical_language>current test is in form assertThat(actual).testMethod(expected); more - assertThat(actual) is support chaining: assertThat(t.remove(4)).isEqualTo(t).isNotSameAs(t);</technical_language>

Target:
public void shouldRemoveNonExistingElement() { final Seq<Integer> t = of(1, 2, 3); assertThat(t.remove(4)).isEqualTo(t).isNotSameAs(t); }
Source:
<code>public void ValidationStereotypesListClass2Test() { EList<Stereotype> appliedStereotypes = class2.getAppliedStereotypes(); List<Stereotype> expectedStereotypes = new ArrayList<Stereotype>(); expectedStereotypes.add(stereotype2); expectedStereotypes.add(stereotype1); <START> assertEquals(appliedStereotypes, expectedStereotypes); <END> }</code><technical_language>Please add error message</technical_language>

Target:
public void ValidationStereotypesListClass2Test() { EList<Stereotype> appliedStereotypes = class2.getAppliedStereotypes(); List<Stereotype> expectedStereotypes = new ArrayList<Stereotype>(); expectedStereotypes.add(stereotype2); expectedStereotypes.add(stereotype1); assertEquals("The stereotypes applied on the class must be the same as the expected stereotypes.", appliedStereotypes, expectedStereotypes); }
Source:
<code>public List<String> getSelection() throws RemoteException { String name = getSelectorName(); Object selection = browser.syncRun(String.format( "return view.getFieldValue('%s')", name)); if (selection != null) { String raw = selection.toString(); <START> String[] items = raw.replaceAll("\\[", "").replaceAll("\\]", "") <END> .replaceAll("\\s", "").split(","); return Arrays.asList(items); } return null; }</code><technical_language>Instead of calling "replaceAll" times call time a regex (\\[|\\]|\\s)</technical_language>

Target:
public List<String> getSelection() throws RemoteException { String name = getSelectorName(); Object selection = browser.syncRun(String.format( "return view.getFieldValue('%s')", name)); if (selection != null) { String raw = selection.toString(); String[] items = raw.replaceAll("(\\[|\\]|\\s)", "").split(","); return Arrays.asList(items); } return null; }
Source:
<code>public void writeTaskContainerMapping(String taskName, String containerId) { String existingContainerId = taskNameToContainerId.get(taskName); if (existingContainerId != null && !existingContainerId.equals(containerId)) { LOG.info("Task \"{}\" moved from container to container {}", new Object[]{taskName, existingContainerId, containerId}); } else { LOG.debug("Task \"{}\" assigned to container {}", taskName, containerId); } if (containerId == null) { <START> metadataStore.remove(keySerde.toBytes(taskName)); <END> taskNameToContainerId.remove(taskName); } else { metadataStore.put(keySerde.toBytes(taskName), valueSerde.toBytes(containerId)); taskNameToContainerId.put(taskName, containerId); } }</code><technical_language>if remove() fails (throws exception)</technical_language>

Target:
public void writeTaskContainerMapping(String taskName, String containerId) { String existingContainerId = taskNameToContainerId.get(taskName); if (existingContainerId != null && !existingContainerId.equals(containerId)) { LOG.info("Task \"{}\" moved from container to container {}", new Object[]{taskName, existingContainerId, containerId}); } else { LOG.debug("Task \"{}\" assigned to container {}", taskName, containerId); } if (containerId == null) { metadataStore.delete(keySerde.toBytes(taskName)); taskNameToContainerId.remove(taskName); } else { metadataStore.put(keySerde.toBytes(taskName), valueSerde.toBytes(containerId)); taskNameToContainerId.put(taskName, containerId); } }
Source:
<code>TayamLuminousEnigmaEffect() { super(Outcome.Benefit); this.filter = new FilterPermanentCard("permanent card in your graveyard with converted mana cost 3 or less"); <START> this.filter.add(new ConvertedManaCostPredicate(ComparisonType.FEWER_THAN, 4)); <END> }</code><technical_language>This filter private static final</technical_language>

Target:
TayamLuminousEnigmaEffect() { super(Outcome.Benefit); staticText = ", then return a permanent card with converted mana cost 3 or less from your graveyard to the battlefield"; }
Source:
<code>public void setServer(AbstractServer server) { router.reset(); <START> router.setIgnoreMessageValidation(true); <END> router.addServer(server); }</code><technical_language>ignore epoch/cluster id check</technical_language>

Target:
public void setServer(AbstractServer server) { router.reset(); router.addServer(server); }