auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void backoffTime() throws RetryableException { Instant startTime = Instant.now(); RecentChangesPoller poller = new RecentChangesPoller(repository, startTime, batchSize, new MetricRegistry()); Instant nextStartTime = startTime.plusSeconds(20); String error = null; Continue aContinue = null; List<RecentChange> recentChanges = new ArrayList<>(); recentChanges.add(new RecentChange(0L, "Q424242", nextStartTime, 42L, 42L, "edit")); Query query = new Query(recentChanges); RecentChangeResponse result = new RecentChangeResponse(error, aContinue, query); ArgumentCaptor<Instant> argument = ArgumentCaptor.forClass(Instant.class); when(repository.fetchRecentChangesByTime(argument.capture(), eq(batchSize))).thenReturn(result); when(repository.isEntityNamespace(0)).thenReturn(true); when(repository.isValidEntity(any(String.class))).thenReturn(true); Batch batch = poller.firstBatch(); assertThat(argument.getValue()).isBefore(startTime.minusSeconds(7)); assertThat(argument.getValue()).isAfter(startTime.minusSeconds(20)); batch = poller.nextBatch(batch); <START> assertThat(batch).isNull(); END> assertThat(argument.getValue()).isBefore(nextStartTime.minusSeconds(7)); assertThat(argument.getValue()).isAfter(nextStartTime.minusSeconds(20)); }</code><technical_language>original condition assertNotNull(batch) I this is error</technical_language>

Target:
public void backoffTime() throws RetryableException { Instant startTime = Instant.now(); RecentChangesPoller poller = new RecentChangesPoller(repository, startTime, batchSize, new MetricRegistry()); Instant nextStartTime = startTime.plusSeconds(20); String error = null; Continue aContinue = null; List<RecentChange> recentChanges = new ArrayList<>(); recentChanges.add(new RecentChange(0L, "Q424242", nextStartTime, 42L, 42L, "edit")); Query query = new Query(recentChanges); RecentChangeResponse result = new RecentChangeResponse(error, aContinue, query); ArgumentCaptor<Instant> argument = ArgumentCaptor.forClass(Instant.class); when(repository.fetchRecentChangesByTime(argument.capture(), eq(batchSize))).thenReturn(result); when(repository.isEntityNamespace(0)).thenReturn(true); when(repository.isValidEntity(any(String.class))).thenReturn(true); Batch batch = poller.firstBatch(); assertThat(argument.getValue()).isBefore(startTime.minusSeconds(7)); assertThat(argument.getValue()).isAfter(startTime.minusSeconds(20)); batch = poller.nextBatch(batch); assertThat(batch).isNotNull(); assertThat(argument.getValue()).isBefore(nextStartTime.minusSeconds(7)); assertThat(argument.getValue()).isAfter(nextStartTime.minusSeconds(20)); }
Source:
<code>private void showShareDialog() { EditText text = (EditText) findViewById(R.id.text); EditText title = (EditText) findViewById(R.id.title); EditText mimeType = (EditText) findViewById(R.id.mime_type); EditText dataUri = (EditText) findViewById(R.id.data_uri); Switch showMru = (Switch) findViewById(R.id.show_most_recently_used); new PrioritySharer.Builder() .setTargets(TARGET_APPS[targetApps.getSelectedItemPosition()]) .setText(text.getText().toString()) <START> .setTitle(title.getText().toString()) <END> .setMimeType(mimeType.getText().toString()) .showMru(showMru.isChecked()) .setDataUri(getDataUriOrNull(dataUri)) .setOnPrepareSharingIntentListener(listener) .show(this); }</code><technical_language>dammit interface accept CharSequence</technical_language>

Target:
private void showShareDialog() { EditText text = (EditText) findViewById(R.id.text); EditText title = (EditText) findViewById(R.id.title); EditText mimeType = (EditText) findViewById(R.id.mime_type); EditText dataUri = (EditText) findViewById(R.id.data_uri); Switch showMostRecentlyUsed = (Switch) findViewById(R.id.show_most_recently_used); new PrioritySharer.Builder() .setTargets(TARGET_APPS[targetApps.getSelectedItemPosition()]) .setText(text.getText().toString()) .setTitle(title.getText().toString()) .setMimeType(mimeType.getText().toString()) .showMru(showMostRecentlyUsed.isChecked()) .setDataUri(getDataUriOrNull(dataUri)) .setOnPrepareSharingIntentListener(listener) .show(this); }
Source:
<code>public Response clear() { try { final IPluginCacheManager iPluginCacheManager = PentahoSystem.get( IPluginCacheManager.class ); final IReportContentCache cache = iPluginCacheManager.getCache(); cache.cleanupCurrentSession(); final ICacheManager cacheManager = PentahoSystem.get( ICacheManager.class ); <START> cacheManager.clearRegionCache( "report-dataset-cache" ); <END> cacheManager.clearRegionCache( "report-output-handlers" ); return Response.ok().build(); } catch ( final Exception e ) { return Response.serverError().build(); } }</code><technical_language>This is a global purge sessions</technical_language>

Target:
public Response clear() { try { final IPluginCacheManager iPluginCacheManager = PentahoSystem.get( IPluginCacheManager.class ); final IReportContentCache cache = iPluginCacheManager.getCache(); cache.cleanupCurrentSession(); final ICacheManager cacheManager = PentahoSystem.get( ICacheManager.class ); cacheManager.clearRegionCache( "report-output-handlers" ); DataCacheFactory.getCache().getCacheManager().clearAll(); return Response.ok().build(); } catch ( final Exception e ) { return Response.serverError().build(); } }
Source:
<code><START> public long getCurrentTimestamp(AtlasReplInfo atlasReplInfo, String entityGuid) throws SemanticException { <END> AtlasServer atlasServer = atlasRestClient.getServer(atlasReplInfo.getSrcCluster()); long ret = (atlasServer == null || atlasServer.getAdditionalInfoRepl(entityGuid) == null) ? 0L : (long) atlasServer.getAdditionalInfoRepl(entityGuid); LOG.debug("HiveAtlasPlugin: fromTimestamp: {}", ret); return ret; }</code><technical_language>get atlasReplInfo work</technical_language>

Target:
private long getCurrentTimestamp(AtlasReplInfo atlasReplInfo, String entityGuid) throws SemanticException { AtlasServer atlasServer = atlasRestClient.getServer(atlasReplInfo.getSrcCluster()); long ret = (atlasServer == null || atlasServer.getAdditionalInfoRepl(entityGuid) == null) ? 0L : (long) atlasServer.getAdditionalInfoRepl(entityGuid); LOG.debug("Current timestamp is: {}", ret); return ret; }
Source:
<code>public FileUploader(String name, AsyncReader fileData, int offsetHi, int offsetLow, int lengthHi, int lengthLow, SymmetricKey baseKey, SymmetricKey metaKey, Location parentLocation, SymmetricKey parentparentKey, ProgressConsumer<Long> monitor, FileProperties fileProperties, int nOriginalFragments, int nAllowedFalures) { long length = lengthLow + ((lengthHi & 0xFFFFFFFFL) << 32); if (fileProperties == null) this.props = new FileProperties(name, length, LocalDateTime.now(), false, Optional.empty()); else this.props = fileProperties; if (baseKey == null) baseKey = SymmetricKey.random(); <START> fragmenter = Fragmenter.getInstance(); <END> long offset = offsetLow + ((offsetHi & 0xFFFFFFFFL) << 32); this.nchunks = length > 0 ? (length + Chunk.MAX_SIZE - 1) / Chunk.MAX_SIZE : 1; this.name = name; this.offset = offset; this.length = length; this.reader = fileData; this.baseKey = baseKey; this.metaKey = metaKey; this.parentLocation = parentLocation; this.parentparentKey = parentparentKey; this.monitor = monitor; this.nOriginalFragments = nOriginalFragments != -1 ? nOriginalFragments : EncryptedChunk.ERASURE_ORIGINAL; this.nAllowedFalures = nAllowedFalures != -1 ? nAllowedFalures : EncryptedChunk.ERASURE_ALLOWED_FAILURES; }</code><technical_language>I want this controllable consumer</technical_language>

Target:
public FileUploader(String name, AsyncReader fileData, int offsetHi, int offsetLow, int lengthHi, int lengthLow, SymmetricKey baseKey, SymmetricKey metaKey, Location parentLocation, SymmetricKey parentparentKey, ProgressConsumer<Long> monitor, FileProperties fileProperties, int nOriginalFragments, int nAllowedFalures) { long length = lengthLow + ((lengthHi & 0xFFFFFFFFL) << 32); if (fileProperties == null) this.props = new FileProperties(name, length, LocalDateTime.now(), false, Optional.empty()); else this.props = fileProperties; if (baseKey == null) baseKey = SymmetricKey.random(); fragmenter = nAllowedFalures == 0 ? new SplitFragmenter() : new peergos.shared.user.fs.ErasureFragmenter(nOriginalFragments, nAllowedFalures); long offset = offsetLow + ((offsetHi & 0xFFFFFFFFL) << 32); this.nchunks = length > 0 ? (length + Chunk.MAX_SIZE - 1) / Chunk.MAX_SIZE : 1; this.name = name; this.offset = offset; this.length = length; this.reader = fileData; this.baseKey = baseKey; this.metaKey = metaKey; this.parentLocation = parentLocation; this.parentparentKey = parentparentKey; this.monitor = monitor; this.nOriginalFragments = nOriginalFragments != -1 ? nOriginalFragments : EncryptedChunk.ERASURE_ORIGINAL; this.nAllowedFalures = nAllowedFalures != -1 ? nAllowedFalures : EncryptedChunk.ERASURE_ALLOWED_FAILURES; }
Source:
<code>private StorageDomainValidator getStorageDomainValidator(Map.Entry<Guid, StorageDomainValidator> entry) { if (entry.getValue() == null) { <START> entry.setValue(new StorageDomainValidator(getStorageDomainDAO().getForStoragePool(entry.getKey(), spId))); <END> } return entry.getValue(); }</code><technical_language>this code safe. If call db fails, class construction fail, hard troubleshoot it, proper logging, etc. get domain db, if returned OK, pass constructor</technical_language>

Target:
private StorageDomainValidator getStorageDomainValidator(Map.Entry<Guid, StorageDomainValidator> entry) { if (entry.getValue() == null) { entry.setValue(new StorageDomainValidator(getStorageDomainDAO().getForStoragePool(entry.getKey(), storagePoolId))); } return entry.getValue(); }
Source:
<code>public Response interceptWmtsRequest(HttpServletRequest request, String serviceId) throws UnsupportedEncodingException, InterceptorException, HttpException, URISyntaxException { Matcher matcher = WMTS_PATTERN.matcher(request.getRequestURI()); int id = Integer.parseInt(serviceId); if (!matcher.matches()) { throw new InterceptorException("No WMTS request path found!"); } String path = matcher.group(1); List<Layer> layers = layerService.findAll(); WmtsLayerDataSource dataSource = null; for (Layer layer : layers) { if (layer.getSource() instanceof WmtsLayerDataSource) { WmtsLayerDataSource source = (WmtsLayerDataSource) layer.getSource(); if (source.getId().equals(id)) { <START> dataSource = source; <END> } } } if (dataSource == null) { Response response = new Response(HttpStatus.FORBIDDEN, null, new byte[0]); return response; } String baseUrl = dataSource.getUrl(); Response response = HttpUtil.get(baseUrl + "/" + path); HttpHeaders forwardingHeaders = getResponseHeadersToForward(response.getHeaders()); response.setHeaders(forwardingHeaders); return response; }</code><technical_language>skip loop now</technical_language>

Target:
public Response interceptWmtsRequest(HttpServletRequest request, String serviceId) throws UnsupportedEncodingException, InterceptorException, HttpException, URISyntaxException { Matcher matcher = WMTS_PATTERN.matcher(request.getRequestURI()); int id = Integer.parseInt(serviceId); if (!matcher.matches()) { throw new InterceptorException("No WMTS request path found!"); } String path = matcher.group(1); List<Layer> layers = layerService.findAll(); WmtsLayerDataSource dataSource = null; for (Layer layer : layers) { if (layer.getSource() instanceof WmtsLayerDataSource) { WmtsLayerDataSource source = (WmtsLayerDataSource) layer.getSource(); if (source.getId().equals(id)) { dataSource = source; break; } } } if (dataSource == null) { return new Response(HttpStatus.FORBIDDEN, null, new byte[0]); } String baseUrl = dataSource.getUrl(); Response response = HttpUtil.get(baseUrl + "/" + path); HttpHeaders forwardingHeaders = getResponseHeadersToForward(response.getHeaders()); response.setHeaders(forwardingHeaders); return response; }
Source:
<code>public Environment findOne(String application, String profile, String label, boolean includeOrigin) { Environment env = new Environment(application, new String[] { profile }, label, null, null); if (this.environmentRepositories.size() == 1) { Environment envRepo = this.environmentRepositories.get(0).findOne(application, profile, label, includeOrigin); env.addAll(envRepo.getPropertySources()); env.setVersion(envRepo.getVersion()); env.setState(envRepo.getState()); } else { for (EnvironmentRepository repo : environmentRepositories) { try { env.addAll(repo.findOne(application, profile, label, includeOrigin).getPropertySources()); } catch (Exception e) { <START> log.info("Error adding environment for " + repo); <END> } } } return env; }</code><technical_language>some discussion, team this opt-in configuration. new behavior surprise users a single property config server, clients. if log errors = true log error else rethrow</technical_language>

Target:
public Environment findOne(String application, String profile, String label, boolean includeOrigin) { Environment env = new Environment(application, new String[] { profile }, label, null, null); if (this.environmentRepositories.size() == 1) { Environment envRepo = this.environmentRepositories.get(0).findOne(application, profile, label, includeOrigin); env.addAll(envRepo.getPropertySources()); env.setVersion(envRepo.getVersion()); env.setState(envRepo.getState()); } else { for (EnvironmentRepository repo : environmentRepositories) { try { env.addAll(repo.findOne(application, profile, label, includeOrigin).getPropertySources()); } catch (Exception e) { if (failOnError) { throw e; } else { log.info("Error adding environment for " + repo); } } } } return env; }
Source:
<code>public void replaceMilestoneAliasesTestNoOpenMilestone() { TurboMilestone msClose1 = new TurboMilestone(REPO, 1, "future1"); msClose1.setOpen(false); msClose1.setDueDate(Optional.of(LocalDate.now().plusMonths(2))); TurboMilestone msClose2 = new TurboMilestone(REPO, 2, "future2"); msClose2.setOpen(false); msClose2.setDueDate(Optional.of(LocalDate.now().plusMonths(3))); TurboMilestone msClose3 = new TurboMilestone(REPO, 3, "future3"); msClose3.setOpen(false); msClose3.setDueDate(Optional.of(LocalDate.now().plusMonths(4))); model = TestUtils.singletonModel(new Model(REPO, new ArrayList<>(), new ArrayList<>(), new ArrayList<>(Arrays.asList(msClose1, msClose2, msClose3)), new ArrayList<>())); FilterExpression noMilestoneAlias; List<Qualifier> milestoneQualifiers; noMilestoneAlias = Qualifier.replaceMilestoneAliases(model, Parser.parse("milestone:current")); assertEquals(noMilestoneAlias.getQualifierNames().size(), 1); assertEquals(noMilestoneAlias.getQualifierNames().get(0), "false"); milestoneQualifiers = noMilestoneAlias.find(Qualifier::isMilestoneQualifier); assertEquals(milestoneQualifiers.size(), 0); noMilestoneAlias = Qualifier.replaceMilestoneAliases(model, Parser.parse("milestone:current-1")); assertEquals(noMilestoneAlias.getQualifierNames().size(), 1); assertEquals(noMilestoneAlias.getQualifierNames().get(0), "false"); milestoneQualifiers = noMilestoneAlias.find(Qualifier::isMilestoneQualifier); assertEquals(milestoneQualifiers.size(), 0); noMilestoneAlias = Qualifier.replaceMilestoneAliases(model, Parser.parse("milestone:current+1")); assertEquals(noMilestoneAlias.getQualifierNames().size(), 1); assertEquals(noMilestoneAlias.getQualifierNames().get(0), "false"); milestoneQualifiers = noMilestoneAlias.find(Qualifier::isMilestoneQualifier); <START> assertEquals(milestoneQualifiers.size(), 0); <END> }</code><technical_language>blocks similar</technical_language>

Target:
public void replaceMilestoneAliasesTestNoOpenMilestone() { TurboMilestone msClose1 = new TurboMilestone(REPO, 1, "future1"); msClose1.setOpen(false); msClose1.setDueDate(Optional.of(LocalDate.now().plusMonths(2))); TurboMilestone msClose2 = new TurboMilestone(REPO, 2, "future2"); msClose2.setOpen(false); msClose2.setDueDate(Optional.of(LocalDate.now().plusMonths(3))); TurboMilestone msClose3 = new TurboMilestone(REPO, 3, "future3"); msClose3.setOpen(false); msClose3.setDueDate(Optional.of(LocalDate.now().plusMonths(4))); model = TestUtils.singletonModel(new Model(REPO, new ArrayList<>(), new ArrayList<>(), new ArrayList<>(Arrays.asList(msClose1, msClose2, msClose3)), new ArrayList<>())); assertMilestoneAliasFalseQualifierSize1("milestone:current"); assertMilestoneAliasFalseQualifierSize1("milestone:current+1"); FilterExpression noMilestoneAlias; List<Qualifier> milestoneQualifiers; noMilestoneAlias = Qualifier.replaceMilestoneAliases(model, Parser.parse("milestone:current-1")); milestoneQualifiers = noMilestoneAlias.find(Qualifier::isMilestoneQualifier); milestoneQualifiers.stream().forEach(msQ -> { assertEquals(true, msQ.getContent().get().equalsIgnoreCase("future3")); }); }
Source:
<code>@Test public void triggersNewBuild() throws Exception { TaskListener listener = new StreamTaskListener(System.out, Charset.defaultCharset()); Launcher launcher = j.jenkins.createLauncher(listener); FreeStyleProject project = j.createFreeStyleProject(); MercurialSCM scm = new MercurialSCM(null, tmp.getRoot().getPath(), null, null, null, null, false, null); project.setScm(scm); File repo = tmp.getRoot(); m.hg(repo, "init"); m.touchAndCommit(repo, "x"); PollingResult pr = scm.compare( launcher, listener, new MercurialTagAction("tip","",null,null), listener.getLogger(), <START> Jenkins.getInstance().toComputer().getNode(), <END> new FilePath(tmp.getRoot()), project); assertEquals(PollingResult.Change.SIGNIFICANT, pr.change); }</code><technical_language><code>j.jenkins</code></technical_language>

Target:
@Test public void triggersNewBuild() throws Exception { TaskListener listener = new StreamTaskListener(System.out, Charset.defaultCharset()); Launcher launcher = j.jenkins.createLauncher(listener); FreeStyleProject project = j.createFreeStyleProject(); MercurialSCM scm = new MercurialSCM(null, tmp.getRoot().getPath(), null, null, null, null, false, null); project.setScm(scm); File repo = tmp.getRoot(); m.hg(repo, "init"); m.touchAndCommit(repo, "x"); PollingResult pr = scm.compare( launcher, listener, new MercurialTagAction("tip","",null,null), listener.getLogger(), j.jenkins, new FilePath(tmp.getRoot()), project); assertEquals(PollingResult.Change.SIGNIFICANT, pr.change); }
Source:
<code>private void processVariables() { final Arguments args1 = (Arguments) this.getUserDefinedVariablesAsProperty().getObjectValue(); Arguments args = (Arguments) args1.clone(); final JMeterVariables vars = JMeterContextService.getContext().getVariables(); Iterator<Map.Entry<String, String>> it = args.getArgumentsAsMap().entrySet().iterator(); Map.Entry<String, String> var; while (it.hasNext()) { var = it.next(); <START> log.debug("Setting " + var.getKey() + "=" + var.getValue()); <END> vars.put(var.getKey(), var.getValue()); } }</code><technical_language>slf4j this log , surrounded isDebugEnable() calls methods</technical_language>

Target:
private void processVariables() { final Arguments args1 = (Arguments) this.getUserDefinedVariablesAsProperty().getObjectValue(); Arguments args = (Arguments) args1.clone(); final JMeterVariables vars = JMeterContextService.getContext().getVariables(); Iterator<Map.Entry<String, String>> it = args.getArgumentsAsMap().entrySet().iterator(); Map.Entry<String, String> var; while (it.hasNext()) { var = it.next(); if (log.isDebugEnabled()) { log.debug("Setting " + var.getKey() + "=" + var.getValue()); } vars.put(var.getKey(), var.getValue()); } }
Source:
<code>public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; HostStateEntity that = (HostStateEntity) o; <START> if (hostId != null ? !hostId.equals(that.hostId) : that.hostId != null) return false; <END> if (availableMem != null ? !availableMem.equals(that.availableMem) : that.availableMem != null) return false; if (timeInState != null ? !timeInState.equals(that.timeInState) : that.timeInState!= null) return false; if (agentVersion != null ? !agentVersion.equals(that.agentVersion) : that.agentVersion != null) return false; if (currentState != null ? !currentState.equals(that.currentState) : that.currentState != null) return false; return true; }</code><technical_language>prefer Objects.equals()</technical_language>

Target:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; HostStateEntity that = (HostStateEntity) o; return Objects.equals(hostId, that.hostId) && Objects.equals(availableMem, that.availableMem) && Objects.equals(timeInState, that.timeInState) && Objects.equals(agentVersion, that.agentVersion) && currentState == that.currentState; }
Source:
<code>private void prepareTestFiles() throws IOException { final AzureBlobFileSystem fs = getFileSystem(); for (String levelOneFolder : SORTED_ENTRY_NAMES) { Path levelOnePath = new Path("/" + levelOneFolder); Assert.assertTrue(fs.mkdirs(levelOnePath)); for (String fileName : SORTED_ENTRY_NAMES) { Path filePath = new Path(levelOnePath, fileName); <START> fs.create(filePath); <END> Assert.assertTrue(fs.exists(filePath)); } } }</code><technical_language>this close stream. fs.create(path).close()</technical_language>

Target:
private void prepareTestFiles() throws IOException { final AzureBlobFileSystem fs = getFileSystem(); for (String levelOneFolder : SORTED_ENTRY_NAMES) { Path levelOnePath = new Path("/" + levelOneFolder); Assert.assertTrue(fs.mkdirs(levelOnePath)); for (String fileName : SORTED_ENTRY_NAMES) { Path filePath = new Path(levelOnePath, fileName); ContractTestUtils.touch(fs, filePath); ContractTestUtils.assertIsFile(fs, filePath); } } }
Source:
<code>private void read(SelectionKey key, Transmissions transmissions) throws InterruptedException, IOException { long startTimeToReadInMs = time.milliseconds(); try { if (!transmissions.hasReceive()) { transmissions.receive = new NetworkReceive(transmissions.getConnectionId(), new BoundedByteBufferReceive(), time); } SocketChannel socketChannel = channel(key); long bytesRead = transmissions.receive.getReceivedBytes().readFrom(socketChannel); if (bytesRead == -1) { close(key); return; } metrics.selectorBytesReceived.update(bytesRead); metrics.selectorBytesReceivedCount.inc(bytesRead); if (transmissions.receive.getReceivedBytes().isReadComplete()) { this.completedReceives.add(transmissions.receive); metrics.updateNodeReceiveMetric(transmissions.remoteHostName, transmissions.remotePort, transmissions.receive.getReceivedBytes().getPayload().limit(), time.milliseconds() - transmissions.receive.getReceiveStartTimeInMs()); transmissions.clearReceive(); } } finally { if (logger.isTraceEnabled()) { long readTime = time.milliseconds() - startTimeToReadInMs; <START> logger.trace("SocketServer time spent on read per key = {}", transmissions.connectionId, readTime); <END> } } }</code><technical_language>useful record this a metric</technical_language>

Target:
private void read(SelectionKey key, Transmissions transmissions) throws IOException { long startTimeToReadInMs = time.milliseconds(); try { if (!transmissions.hasReceive()) { transmissions.receive = new NetworkReceive(transmissions.getConnectionId(), new BoundedByteBufferReceive(), time); } SocketChannel socketChannel = channel(key); long bytesRead = transmissions.receive.getReceivedBytes().readFrom(socketChannel); if (bytesRead == -1) { close(key); return; } metrics.selectorBytesReceived.update(bytesRead); metrics.selectorBytesReceivedCount.inc(bytesRead); if (transmissions.receive.getReceivedBytes().isReadComplete()) { this.completedReceives.add(transmissions.receive); metrics.updateNodeReceiveMetric(transmissions.remoteHostName, transmissions.remotePort, transmissions.receive.getReceivedBytes().getPayload().limit(), time.milliseconds() - transmissions.receive.getReceiveStartTimeInMs()); transmissions.clearReceive(); } } finally { long readTime = time.milliseconds() - startTimeToReadInMs; logger.trace("SocketServer time spent on read per key = {}", transmissions.connectionId, readTime); } }
Source:
<code>private void contactsRemoved(Collection<String> addresses) { if (roster == null) return; for (String address : addresses) { XMPPContact removedContact = contacts.remove(address); if (removedContact == null) { <START> log.info("Strange behaviour: Contact for " + address + " not found!"); <END> continue; } removedContact.removeResources(); removedContact.setBaseStatus(ContactStatus.TYPE_REMOVED); notifyListeners(removedContact, UpdateType.REMOVED); } }</code><technical_language>debug / warn</technical_language>

Target:
private void contactsRemoved(Collection<String> addresses) { if (roster == null) return; for (String address : addresses) { XMPPContact removedContact = contacts.remove(address); if (removedContact == null) { log.warn("Strange behaviour: Contact for " + address + " not found!"); continue; } discoveryService.removeResources(removedContact.getResources()); removedContact.removeResources(); removedContact.setBaseStatus(ContactStatus.TYPE_REMOVED); notifyListeners(removedContact, UpdateType.REMOVED); } }
Source:
<code>private URL getUrl() { String urlString = null; URL url = null; try { urlString = oProxyHelper .getAdapterEndPointFromConnectionManager(DIRECT_CONFIG_SERVICE_NAME); } catch (ConnectionManagerException ex) { <START> LOG.error("Error reading directConfig Url cannot be found: {}", ex.getLocalizedMessage(), ex); <END> } try { url = new URL(urlString); } catch (MalformedURLException ex) { LOG.error("Error while converting urlString into Url format {}", ex.getMessage(), ex); } return url; }</code><technical_language>I OK ex.getErrorMessage() getLocalizedMessage(), I do agree try stick method in code for loggers</technical_language>

Target:
private URL getUrl() { String urlString = null; URL url = null; try { urlString = oProxyHelper .getAdapterEndPointFromConnectionManager(DIRECT_CONFIG_SERVICE_NAME); } catch (ConnectionManagerException ex) { LOG.error("Error reading directConfig Url cannot be found: {}", ex.getLocalizedMessage(), ex); } try { url = new URL(urlString); } catch (MalformedURLException ex) { LOG.error("Error while converting urlString into Url format {}", ex.getLocalizedMessage(), ex); } return url; }
Source:
<code>public int executeBackendUpdateQuery(BackendQuery<String> query, QueryParameters queryParameters, TupleContext tupleContext) { Map<String, Object> parameters = getParameters( queryParameters ); String nativeQuery = buildNativeQuery( query, queryParameters ); Statement statement = new Statement( nativeQuery, parameters ); statement.setResultDataContents( Arrays.asList( Statement.AS_ROW ) ); Statements statements = new Statements(); statements.addStatement( statement ); Long txId = transactionId( tupleContext.getTransactionContext() ); StatementsResponse response = client.executeQueriesInOpenTransaction( txId, statements ); <START> return 0; <END> }</code><technical_language>I if -1 better. states is unknown value. WDYT</technical_language>

Target:
public int executeBackendUpdateQuery(BackendQuery<String> query, QueryParameters queryParameters, TupleContext tupleContext) { Map<String, Object> parameters = getParameters( queryParameters ); String nativeQuery = buildNativeQuery( query, queryParameters ); Statement statement = new Statement( nativeQuery, parameters ); statement.setResultDataContents( Arrays.asList( Statement.AS_ROW ) ); Statements statements = new Statements(); statements.addStatement( statement ); Long txId = transactionId( tupleContext.getTransactionContext() ); StatementsResponse response = client.executeQueriesInOpenTransaction( txId, statements ); validate( response, nativeQuery ); return UNKNOWN_UPDATES; }
Source:
<code>public String getLog() throws IOException { File logFile = getLogFile(); if (null == logFile) { <START> return ""; <END> } return Util.loadFile(logFile); }</code><technical_language>throw IOException</technical_language>

Target:
public String getLog() throws IOException { return Util.loadFile(getLogFileForJob(job)); }
Source:
<code>public StreamManager(@Nonnull CorfuRuntime runtime, int maxSubscribers) { this.runtime = runtime; this.maxSubscribers = maxSubscribers; this.subscriptions = new HashMap<>(); this.scheduledExecutorService = Executors.newScheduledThreadPool(maxSubscribers); <START> } <END></code><technical_language>I a limit maxSubscribers, especially a poller subscription increases IO. Besides tasks scheduled run in infinite loop (if new data fetched), means if more maxSubscribers subscriptions, new subscriptions scheduled, right</technical_language>

Target:
public StreamManager(@Nonnull CorfuRuntime runtime, int maxSubscribers) { this.runtime = runtime; this.subscriptions = new HashMap<>(); this.scheduledExecutorService = Executors.newScheduledThreadPool(maxSubscribers); }
Source:
<code>public void verifyNoAsyncErrors() { for (Throwable e : asyncErrors) { if (e instanceof AssertionError) { throw (AssertionError) e; } else { <START> fail("Async error during test execution: " + e, e); <END> } } }</code><technical_language>explicit e.getMessage here? (and enclose in double-quotes)</technical_language>

Target:
public void verifyNoAsyncErrors() { for (Throwable e : asyncErrors) { if (e instanceof AssertionError) { throw (AssertionError) e; } else { fail("Async error during test execution: " + e.getMessage(), e); } } }
Source:
<code>public Value evaluate(DataSourceFactory dsf, Value... args) throws FunctionException { final CoordinateReferenceSystem crs = args[0].getCRS(); if (crs == null) { <START> return ValueFactory.createNullValue(); <END> } else { String identifiers = crs.getName(); return ValueFactory.createValue(identifiers); } }</code><technical_language>a warning message a logger telling user CRS found</technical_language>

Target:
public Value evaluate(DataSourceFactory dsf, Value... args) throws FunctionException { final CoordinateReferenceSystem crs = args[0].getCRS(); if (crs == null) { return ValueFactory.createNullValue(); } else { String authorityName = crs.getAuthorityName(); String authorityKey= crs.getAuthorityKey(); return ValueFactory.createValue(authorityName+":"+authorityKey); } }
Source:
<code>public void <START> onCreateOptionsMenu(Menu <END> menu, MenuInflater inflater) { inflater.inflate(R.menu.menu_main, menu); viewPager.post(new Runnable() { @Override public void run() { setUpOverflowButton(); } }); }</code><technical_language>Missed this earlier. call super in onOptionsItemSelected</technical_language>

Target:
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.menu_main, menu); viewPager.post(new Runnable() { @Override public void run() { setUpOverflowButton(); } }); }
Source:
<code>public AuthenticationConfiguration(Predicate<HttpServerExchange> isAuthenticationRequiredPredicate, List<AuthenticationMechanism> authMechanisms, IdentityManager identityManager) { <START> Preconditions.checkNotNull(isAuthenticationRequiredPredicate, "Authentication constraint predicate has to be provided"); <END> Preconditions.checkArgument(!authMechanisms.isEmpty(), "At least one AuthenticationMechanism has to be provided."); Preconditions.checkNotNull(identityManager, "IdentityManager has to be provided"); this.isAuthenticationRequiredPredicate = isAuthenticationRequiredPredicate; this.authMechanisms = authMechanisms; this.identityManager = identityManager; }</code><technical_language>Please change null check message well. :)</technical_language>

Target:
public AuthenticationConfiguration(Predicate<HttpServerExchange> isAuthenticationRequiredPredicate, List<AuthenticationMechanism> authMechanisms, IdentityManager identityManager) { Preconditions.checkNotNull(isAuthenticationRequiredPredicate, "IsAuthenticationRequired predicate has to be provided"); Preconditions.checkArgument(!authMechanisms.isEmpty(), "At least one AuthenticationMechanism has to be provided."); Preconditions.checkNotNull(identityManager, "IdentityManager has to be provided"); this.isAuthenticationRequiredPredicate = isAuthenticationRequiredPredicate; this.authMechanisms = authMechanisms; this.identityManager = identityManager; }
Source:
<code>public static String getGoExecutablePath(@Nullable String sdkHomePath) { if (sdkHomePath != null) { if (isAppEngineSdkPath(sdkHomePath)) { String executable = GoEnvironmentUtil.getBinaryFileNameForPath(GoConstants.GAE_EXECUTABLE_NAME); sdkHomePath = StringUtil.trimEnd(sdkHomePath, GoConstants.APP_ENGINE_GO_ROOT_DIRECTORY_PATH); return sdkHomePath.endsWith(GoConstants.GCLOUD_APP_ENGINE_DIRECTORY_PATH) ? FileUtil.join(StringUtil.trimEnd(sdkHomePath, GoConstants.GCLOUD_APP_ENGINE_DIRECTORY_PATH), "bin", executable) <START> : FileUtil.join(sdkHomePath, SystemInfo.isWindows ? StringUtil.replace(executable, ".exe", ".bat") : executable); <END> } else { return FileUtil.join(sdkHomePath, "bin", GoEnvironmentUtil.getBinaryFileNameForPath(GoConstants.GO_EXECUTABLE_NAME)); } } return null; }</code><technical_language>OK, this is amazing, GAE for Windows goapp.batbut gcloud for Windows goapp.cmd. Haha :) funny. > I create a new pull request includes gae gcloud for Windows correction? push correction in fork-master, PR updated automatically (hope so). note. is a line String executable = GoEnvironmentUtil.getBinaryFileNameForPath(GoConstants.GAE_EXECUTABLE_NAME); strange append executable "exe" (getBinaryNameForPath it) replace "exe" else. Please inline executable FileUtil.join invocation. sense create util methods getBinaryOrCmdFileName getBinaryOrBatFileName</technical_language>

Target:
public static String getGoExecutablePath(@Nullable String sdkHomePath) { if (sdkHomePath != null) { if (isAppEngineSdkPath(sdkHomePath)) { sdkHomePath = StringUtil.trimEnd(PathUtil.toSystemIndependentName(sdkHomePath), GoConstants.APP_ENGINE_GO_ROOT_DIRECTORY_PATH); return sdkHomePath.endsWith(GoConstants.GCLOUD_APP_ENGINE_DIRECTORY_PATH) ? FileUtil.join(StringUtil.trimEnd(sdkHomePath, GoConstants.GCLOUD_APP_ENGINE_DIRECTORY_PATH), "bin", SystemInfo.isWindows ? GoConstants.GAE_CMD_EXECUTABLE_NAME : GoConstants.GAE_EXECUTABLE_NAME) : FileUtil.join(sdkHomePath, SystemInfo.isWindows ? GoConstants.GAE_BAT_EXECUTABLE_NAME : GoConstants.GAE_EXECUTABLE_NAME); } else { return FileUtil.join(sdkHomePath, "bin", GoEnvironmentUtil.getBinaryFileNameForPath(GoConstants.GO_EXECUTABLE_NAME)); } } return null; }
Source:
<code>private static void verify(String methodName, boolean expectPass, int guessing, char... laResults) throws Exception { final AssertGenTextBlockLexer instance = new AssertGenTextBlockLexer(); instance.laPosition = 0; instance.laResults = laResults.clone(); instance.inputState.guessing = guessing; final Method method = GeneratedTextBlockLexer.class.getDeclaredMethod(methodName, boolean.class); boolean exception; try { method.invoke(instance, true); exception = false; } catch (InvocationTargetException ex) { if (expectPass) { throw ex; } final Class<?> clss = ex.getTargetException().getClass(); if (clss != NoViableAltForCharException.class && clss != SemanticException.class) { throw ex; } exception = true; } if (expectPass) { <START> assertFalse(exception, "Call to GeneratedJava14TextBlockLexer." + methodName <END> + " resulted in an exception"); } else { assertTrue(exception, "Call to GeneratedJava14TextBlockLexer." + methodName + " did not result in an exception"); } }</code><technical_language>Class name is GeneratedTextBlockLexer</technical_language>

Target:
private static void verify(String methodName, boolean expectPass, int guessing, char... laResults) throws Exception { final AssertGenTextBlockLexer instance = new AssertGenTextBlockLexer(); instance.laPosition = 0; instance.laResults = laResults.clone(); instance.inputState.guessing = guessing; final Method method = GeneratedTextBlockLexer.class.getDeclaredMethod(methodName, boolean.class); boolean exception; try { method.invoke(instance, true); exception = false; } catch (InvocationTargetException ex) { if (expectPass) { throw ex; } final Class<?> clss = ex.getTargetException().getClass(); if (clss != NoViableAltForCharException.class && clss != SemanticException.class) { throw ex; } exception = true; } if (expectPass) { assertFalse(exception, "Call to GeneratedTextBlockLexer." + methodName + " resulted in an exception"); } else { assertTrue(exception, "Call to GeneratedTextBlockLexer." + methodName + " did not result in an exception"); } }
Source:
<code>void refreshConstraintComponent() { if (isBooleanType() || isStructureType() || isContextType() || isList() <START> || isIndirectTypeOf(CAN_NOT_HAVE_CONSTRAINT)) { <END> dataTypeConstraintComponent.disable(); } else { dataTypeConstraintComponent.enable(); } }</code><technical_language>this if complex, I small exercise refactor <LINK_0>, please do changes I propose</technical_language>

Target:
void refreshConstraintComponent() { if (canNotHaveConstraint()) { dataTypeConstraintComponent.disable(); } else { dataTypeConstraintComponent.enable(); } }
Source:
<code>private void runProducer() { for (int i = 0; i < numThreads; i++) { <START> CorfuRuntime rt = rts[i % rts.length]; <END> CorfuTableOperations corfuTableOperations = new CorfuTableOperations(operationName, rt, numRequests, ratio,false, false); runProducer(corfuTableOperations); } }</code><technical_language>rts, array if arraylist sed</technical_language>

Target:
private void runProducer() { for (int i = 0; i < numThreads; i++) { CorfuRuntime runtime = runtimes.getRuntime(i); UUID uuid = streams.getStreamID(i); CorfuTable<String, String> table = corfuTables.getTable(uuid); CorfuTableOperations corfuTableOperations = new CorfuTableOperations(operationName, runtime, table, numRequests, ratio); runProducer(corfuTableOperations); } }
Source:
<code>public void idle() { if (lastSendInterval++ >= sendIntervals) { lastSendInterval = 0; Iterator<DispatchAttempt> iterator = sendQueue.iterator(); while (iterator.hasNext()) { DispatchAttempt attempt = iterator.next(); try { EventMessageContent message = new EventMessageContent(); message.prepareMessage(hostName, attempt.event, isBodyHtml); <START> log.info("Sending mail subject='{}' to='{}'", <END> message.getMessageSubject(), attempt.address); log.debug("Send mail body='{}'", message.getMessageBody()); sendMail(attempt.address, message.getMessageSubject(), message.getMessageBody()); log.info( "E-mail subject='{}' to='{}' sent successfully", message.getMessageSubject(), attempt.address ); notifyObservers(DispatchResult.success(attempt.event, attempt.address, EventNotificationMethod.SMTP)); iterator.remove(); } catch (Exception ex) { attempt.retries++; if (attempt.retries >= retries) { notifyObservers(DispatchResult.failure(attempt.event, attempt.address, EventNotificationMethod.SMTP, ex.getMessage())); iterator.remove(); } } } } }</code><technical_language>OK, correct :-) 1. In this patch add "sent successfully" log message 2. Create additional patch bug-url do remaining fixes 'mail -> email' 'Send mail -> Sending e-mail' Thanks</technical_language>

Target:
public void idle() { if (lastSendInterval++ >= sendIntervals) { lastSendInterval = 0; Iterator<DispatchAttempt> iterator = sendQueue.iterator(); while (iterator.hasNext()) { DispatchAttempt attempt = iterator.next(); try { EventMessageContent message = new EventMessageContent(); message.prepareMessage(hostName, attempt.event, isBodyHtml); log.info("Send mail subject='{}' to='{}'", message.getMessageSubject(), attempt.address); log.debug("Send mail body='{}'", message.getMessageBody()); sendMail(attempt.address, message.getMessageSubject(), message.getMessageBody()); log.info( "Mail subject='{}' to='{}' sent successfully", message.getMessageSubject(), attempt.address ); notifyObservers(DispatchResult.success(attempt.event, attempt.address, EventNotificationMethod.SMTP)); iterator.remove(); } catch (Exception ex) { attempt.retries++; if (attempt.retries >= retries) { notifyObservers(DispatchResult.failure(attempt.event, attempt.address, EventNotificationMethod.SMTP, ex.getMessage())); iterator.remove(); } } } } }
Source:
<code>private static Stream<Profile> parseProfileName( File profile ) { File profileFolder = profile.getParentFile(); File dir = profileFolder.getParentFile(); String name = profile.getName(); if ( !name.endsWith( SUFFIX_CACHEPROF ) ) { return Stream.empty(); } int lastDot = name.lastIndexOf( '.' ); int secondLastDot = name.lastIndexOf( '.', lastDot - 1 ); String countStr = name.substring( secondLastDot + 1, lastDot ); try { <START> long sequenceId = Long.parseLong( countStr, 16 ); <END> String mappedFileName = name.substring( 0, secondLastDot ); return Stream.of( new Profile( profile, new File( dir, mappedFileName ), sequenceId ) ); } catch ( NumberFormatException e ) { return Stream.empty(); } }</code><technical_language>hex?! save 3 chars... 9223372036854775807 19 chars 7FFFFFFFFFFFFFFF 16 chars Human readability is more important 3</technical_language>

Target:
private static Stream<Profile> parseProfileName( File profile ) { File profileFolder = profile.getParentFile(); File dir = profileFolder.getParentFile(); String name = profile.getName(); if ( !name.endsWith( SUFFIX_CACHEPROF ) ) { return Stream.empty(); } int lastDot = name.lastIndexOf( '.' ); int secondLastDot = name.lastIndexOf( '.', lastDot - 1 ); String countStr = name.substring( secondLastDot + 1, lastDot ); try { long sequenceId = Long.parseLong( countStr, 10 ); String mappedFileName = name.substring( 0, secondLastDot ); return Stream.of( new Profile( profile, new File( dir, mappedFileName ), sequenceId ) ); } catch ( NumberFormatException e ) { return Stream.empty(); } }
Source:
<code>public void testGetErrorResponse() { <START> int throttleTimeMs = 10; <END> WriteTxnMarkersRequest.Builder builder = new WriteTxnMarkersRequest.Builder(markers); for (short version = 0; version <= ApiKeys.WRITE_TXN_MARKERS.latestVersion(); version++) { WriteTxnMarkersRequest request = builder.build(version); WriteTxnMarkersResponse errorResponse = request.getErrorResponse(throttleTimeMs, Errors.UNKNOWN_PRODUCER_ID.exception()); assertEquals(Collections.singletonMap( topicPartition, Errors.UNKNOWN_PRODUCER_ID), errorResponse.errors(producerId)); assertEquals(Collections.singletonMap(Errors.UNKNOWN_PRODUCER_ID, 1), errorResponse.errorCounts()); assertEquals(0, errorResponse.throttleTimeMs()); } }</code><technical_language>Do need this variable inline it</technical_language>

Target:
public void testGetErrorResponse() { WriteTxnMarkersRequest.Builder builder = new WriteTxnMarkersRequest.Builder(markers); for (short version = 0; version <= ApiKeys.WRITE_TXN_MARKERS.latestVersion(); version++) { WriteTxnMarkersRequest request = builder.build(version); WriteTxnMarkersResponse errorResponse = request.getErrorResponse(throttleTimeMs, Errors.UNKNOWN_PRODUCER_ID.exception()); assertEquals(Collections.singletonMap( topicPartition, Errors.UNKNOWN_PRODUCER_ID), errorResponse.errors(producerId)); assertEquals(Collections.singletonMap(Errors.UNKNOWN_PRODUCER_ID, 1), errorResponse.errorCounts()); assertEquals(0, errorResponse.throttleTimeMs()); } }
Source:
<code>public static void startup(Properties p) { applyLogLevels(); <START> setupLogAppenders(); <END> }</code><technical_language>remove code here? is needed. remove code a variable a constant. If a variable a constant get a compile error means able a constant. task of this ticket is simply constants reassigned</technical_language>

Target:
public static void startup(Properties p) { String val = p.getProperty("obscure_patients", null); if (val != null && "true".equalsIgnoreCase(val)) { OpenmrsConstants.OBSCURE_PATIENTS = true; } val = p.getProperty("obscure_patients.family_name", null); if (val != null) { OpenmrsConstants.OBSCURE_PATIENTS_FAMILY_NAME = val; } val = p.getProperty("obscure_patients.given_name", null); if (val != null) { OpenmrsConstants.OBSCURE_PATIENTS_GIVEN_NAME = val; } val = p.getProperty("obscure_patients.middle_name", null); if (val != null) { OpenmrsConstants.OBSCURE_PATIENTS_MIDDLE_NAME = val; } val = p.getProperty("connection.database_name", null); if (val == null) { val = p.getProperty("connection.url", null); if (val != null) { try { int endIndex = val.lastIndexOf("?"); if (endIndex == -1) { endIndex = val.length(); } int startIndex = val.lastIndexOf("/", endIndex); val = val.substring(startIndex + 1, endIndex); OpenmrsConstants.DATABASE_NAME = val; } catch (Exception e) { log.error(MarkerFactory.getMarker("FATAL"), "Database name cannot be configured from 'connection.url' ." + "Either supply 'connection.database_name' or correct the url", e); } } } val = p.getProperty("connection.database_business_name", null); if (val == null) { val = OpenmrsConstants.DATABASE_NAME; } OpenmrsConstants.DATABASE_BUSINESS_NAME = val; applyLogLevels(); setupLogAppenders(); }
Source:
<code>private CreationStatus getJobIdStatus(VdcReturnValueBase result) { NGuid jobId = result.getJobId(); if (jobId ==null || jobId.getValue().equals(NGuid.Empty)) { return CreationStatus.COMPLETE; } else { GetJobByJobIdQueryParameters params = new GetJobByJobIdQueryParameters(); params.setJobId(jobId.getValue()); VdcQueryReturnValue queryResult = backend.RunQuery(VdcQueryType.GetJobByJobId, <START> sessionize(params)); <END> if (queryResult != null && queryResult.getSucceeded() && queryResult.getReturnValue() != null) { Job job = (Job)queryResult.getReturnValue(); return job.getStatus()==JobExecutionStatus.STARTED ? CreationStatus.IN_PROGRESS : CreationStatus.COMPLETE; } else { return CreationStatus.COMPLETE; } } }</code><technical_language>implementing new infrustructure method BackendResource.doQuery() reuse in BackendResource.doGetEntity() here</technical_language>

Target:
private CreationStatus getJobIdStatus(VdcReturnValueBase result) { NGuid jobId = result.getJobId(); if (jobId ==null || jobId.getValue().equals(NGuid.Empty)) { return CreationStatus.COMPLETE; } else { GetJobByJobIdQueryParameters params = new GetJobByJobIdQueryParameters(); params.setJobId(jobId.getValue()); VdcQueryReturnValue queryResult = runQuery(VdcQueryType.GetJobByJobId, params); if (queryResult != null && queryResult.getSucceeded() && queryResult.getReturnValue() != null) { Job job = (Job)queryResult.getReturnValue(); return job.getStatus()==JobExecutionStatus.STARTED ? CreationStatus.IN_PROGRESS : CreationStatus.COMPLETE; } else { return CreationStatus.COMPLETE; } } }
Source:
<code><START> public void imageLink(Attributes linkAttributes, Attributes imageAttributes, String href, String imageUrl) { <END> link(linkAttributes, href, "{{" + Strings.nullToEmpty(imageUrl) + "}}"); }</code><technical_language><LINK_0> is example: [[<LINK_1>|{{image:<LINK_2>}} click for large version]] image link link text. reproduce this example</technical_language>

Target:
public void imageLink(Attributes linkAttributes, Attributes imageAttributes, String href, String imageUrl) { String altText = ""; if (imageAttributes instanceof ImageAttributes && !Strings.isNullOrEmpty(((ImageAttributes) imageAttributes).getAlt())) { altText = ((ImageAttributes) imageAttributes).getAlt(); } link(linkAttributes, href, "{{" + Strings.nullToEmpty(imageUrl) + "}}" + altText); }