auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private boolean isStaleMessage(Message message, String currentState) { <START> if (_isTaskFrameworkPipeline || currentState == null || message.getFromState() == null <END> || message.getToState() == null) { return false; } return !message.getFromState().equalsIgnoreCase(currentState) || message.getToState() .equalsIgnoreCase(currentState); }</code><technical_language>Introducing _isTaskFrameworkPipeline isStaleMessage is confusing. I prefer do this, "if (!_isTaskFrameworkPipeline && isStaleMessage(...)) {set stale message}"</technical_language>

Target:
private boolean isStaleMessage(Message message, String currentState) { if (currentState == null || message.getFromState() == null || message.getToState() == null) { return false; } return !message.getFromState().equalsIgnoreCase(currentState) || message.getToState() .equalsIgnoreCase(currentState); }
Source:
<code>public CompletableFuture<Boolean> replaceIssueMilestone(TurboIssue issue, Optional<Integer> newMilestone) { logger.info("Changing milestone for " + issue + " in models"); CompletableFuture<Optional<TurboIssue>> localMilestoneReplaceFuture = repoOpControl.replaceIssueMilestoneLocally(issue, newMilestone); localMilestoneReplaceFuture.thenRun(this::refreshUI); return updateIssueMilestonesOnServer(issue, newMilestone) .thenCombine(localMilestoneReplaceFuture, (isUpdateSuccessful, originalIssue) -> <START> handleIssueMilestoneUpdateOnServerResult(isUpdateSuccessful, originalIssue)); <END> }</code><technical_language>This bit replaced this::handleIssueMilestoneUpdateOnServerResult</technical_language>

Target:
public CompletableFuture<Boolean> replaceIssueMilestone(TurboIssue issue, Optional<Integer> newMilestone) { logger.info("Changing milestone for " + issue + " in models"); CompletableFuture<Optional<TurboIssue>> localMilestoneReplaceFuture = repoOpControl.replaceIssueMilestoneLocally(issue, newMilestone); localMilestoneReplaceFuture.thenRun(this::refreshUI); return updateIssueMilestonesOnServer(issue, newMilestone) .thenCombine(localMilestoneReplaceFuture, this::handleIssueMilestoneUpdateOnServerResult); }
Source:
<code>private Collection<CommandAssociatedEntity> buildCommandAssociatedEntities(Guid cmdId, Map<Guid, VdcObjectType> entityMap) { if (entityMap == null) { <START> entityMap = Collections.emptyMap(); <END> } List<CommandAssociatedEntity> results = new ArrayList<>(entityMap.size()); for (Map.Entry<Guid, VdcObjectType> entry : entityMap.entrySet()) { results.add(new CommandAssociatedEntity(cmdId, entry.getValue(), entry.getKey())); } return results; }</code><technical_language>return empty list instead continue executing method result is</technical_language>

Target:
private Collection<CommandAssociatedEntity> buildCommandAssociatedEntities(Guid cmdId, Map<Guid, VdcObjectType> entityMap) { if (entityMap == null) { return Collections.emptyList(); } List<CommandAssociatedEntity> results = new ArrayList<>(entityMap.size()); for (Map.Entry<Guid, VdcObjectType> entry : entityMap.entrySet()) { results.add(new CommandAssociatedEntity(cmdId, entry.getValue(), entry.getKey())); } return results; }
Source:
<code>private DbUser getDbUserForPrincipalName(String principalName, String authzName) { ExtMap principalRecord = AuthzUtils.fetchPrincipalRecord( EngineExtensionsManager.getInstance().getExtensionByName(authzName), principalName, false, false); if (principalRecord == null) { <START> throw new RuntimeException(String.format("Unable to find principal %s in domain '%s'", principalName, authzName)); <END> } return new DbUser(DirectoryUtils.mapPrincipalRecordToDirectoryUser(authzName, principalRecord)); }</code><technical_language>pls format (>120 chars)</technical_language>

Target:
private DbUser getDbUserForPrincipalName(String principalName, String authzName) { ExtMap principalRecord = AuthzUtils.fetchPrincipalRecord( EngineExtensionsManager.getInstance().getExtensionByName(authzName), principalName, false, false); if (principalRecord == null) { throw new RuntimeException(String.format("Unable to find principal %s in domain '%s'", principalName, authzName)); } DbUser user = new DbUser(DirectoryUtils.mapPrincipalRecordToDirectoryUser(authzName, principalRecord)); user.setId(Guid.newGuid()); return user; }
Source:
<code>public Filter merge(Filter filter) { boolean skipBrackets = !filter.hasMultiple() || operatorItem == filter.operatorItem || filter.isInverted() || (operatorItem == FilterItem.OR && filter.operatorItem == <START> FilterItem.AND); <END> insertOperator(); if (!skipBrackets) { filterItems.addLast(FilterItem.OPEN); } filter.filterItems.stream().forEach(filterItems::addLast); if (!skipBrackets) { filterItems.addLast(FilterItem.CLOSE); } return this; }</code><technical_language>this want brackets, if merge OR? if yes, why? this is a class in api.base, for backends, precedence of defined clear e.g. precedence of multiplication addition. I prefer additional brackets if hurt if rely precedence else</technical_language>

Target:
public Filter merge(Filter filter) { boolean addBrackets = !filter.isInverted() || filter.hasMultiple() && !(operatorItem == filter.operatorItem); insertOperator(); if (addBrackets) { filterItems.addLast(FilterItem.OPEN); } filter.filterItems.stream().forEach(filterItems::addLast); if (addBrackets) { filterItems.addLast(FilterItem.CLOSE); } return this; }
Source:
<code>public String getFirstAllowedEditorRole() { <START> return edit == null || edit.isEmpty() ? "" : edit; <END> }</code><technical_language>if StringUtils.defaultString(edit)</technical_language>

Target:
public String getFirstAllowedEditorRole() { return StringUtils.defaultString(edit); }
Source:
<code>public GdbMemoryBlockRetrievalManager(String modelId, ILaunchConfiguration config, DsfSession session) <START> throws DebugException { <END> fModelId = modelId; fSession = session; fLaunchConfig = config; }</code><technical_language>throw exception</technical_language>

Target:
public GdbMemoryBlockRetrievalManager(String modelId, ILaunchConfiguration config, DsfSession session) { fModelId = modelId; fSession = session; fLaunchConfig = config; }
Source:
<code>private void handlePotentialTimeout(Invocation invocation) { Object identifier = invocation.getIdentifier(); Invocation currentInvocation = activeAsyncInvocations.get(identifier); <START> if (currentInvocation != null && currentInvocation == invocation) { <END> TrackingCallable currentWrapper = activeIdentifiers.get(identifier); if (currentWrapper != null) { invocation.handleTimeout(currentWrapper); } } }</code><technical_language>invocation is null dereferenced above. So, if test currentInvocation == invocation, test currentInvocation != null redundant</technical_language>

Target:
private void handlePotentialTimeout(Invocation invocation) { Object identifier = invocation.getIdentifier(); Invocation currentInvocation = activeAsyncInvocations.get(identifier); if (currentInvocation == invocation) { TrackingCallable currentWrapper = activeIdentifiers.get(identifier); if (currentWrapper != null) { invocation.handleTimeout(currentWrapper); } } }
Source:
<code>public boolean test(R record) { <START> return record.headers().allWithName(name).hasNext(); <END> }</code><technical_language>want break this avoid NPE [Headers::allWithName](<LINK_0> is technically allowed return null in some situations: suggestion Iterator<Header> headersWithName = record.headers().allWithName(name); return headersWithName != null ? headersWithName.hasNext() : false;</technical_language>

Target:
public boolean test(R record) { Iterator<Header> headerIterator = record.headers().allWithName(name); return headerIterator != null && headerIterator.hasNext(); }
Source:
<code>public void run() throws Exception { while (true) { if (IFuture.CURRENT.get().isCancelled() || m_sessionProvider.isClosing()) { LOG.debug("JMS MessageConsumer for was closed", m_destination); break; } Message message; try { message = JmsSessionProviderMigration.receive(m_sessionProvider, m_subscribeInput, m_receiveTimeoutMillis); if (message == null) { continue; } } catch (Exception e) { if (IFuture.CURRENT.get().isCancelled() || m_sessionProvider.isClosing()) { LOG.debug("JMS MessageConsumer for was closed", m_destination); break; } <START> BEANS.get(MomExceptionHandler.class).handle(e); <END> continue; } try { LOG.debug("Receiving JMS message [message={}]", message); m_mom.getMessageHandler().handleIncoming(m_destination, message, m_marshaller); onJmsMessage(message); } catch (Exception e) { if (isRollbackNecessary(e)) { Session transactedSession = null; try { transactedSession = m_sessionProvider.getSession(); transactedSession.rollback(); } catch (final JMSException ex) { LOG.error("Failed to rollback transacted session [session={}]", transactedSession, ex); } } BEANS.get(MomExceptionHandler.class).handle(e); } } LOG.debug("JMS MessageConsumer for was closed", m_destination); }</code><technical_language>In case of a connection error, this "false-positive" error log statements 2x15 retries. e.g. 2019-04-16 09:17:54,512 ERROR [scout-thread-6 JMS subscriber] org.eclipse.scout.rt.platform.exception.ExceptionHandler.handleThrowable(ExceptionHandler.java:135) - XxxxException ...</technical_language>

Target:
public void run() throws Exception { while (true) { if (IFuture.CURRENT.get().isCancelled() || m_sessionProvider.isClosing()) { LOG.debug("JMS MessageConsumer for was closed", m_destination); break; } final Session transactedSession; final Message message; try { transactedSession = m_sessionProvider.getSession(); message = JmsSessionProviderMigration.receive(m_sessionProvider, m_subscribeInput, m_receiveTimeoutMillis); if (message == null) { continue; } } catch (Exception e) { if (IFuture.CURRENT.get().isCancelled() || m_sessionProvider.isClosing()) { LOG.debug("JMS MessageConsumer for was closed", m_destination); break; } LOG.warn("JMS MessageConsumer for is still idle after several retry attempts", m_destination, e); continue; } try { m_mom.getMessageHandler().handleIncoming(m_destination, message, m_marshaller); onJmsMessage(message); } catch (Exception e) { if (isRollbackNecessary(e)) { try { transactedSession.rollback(); } catch (final JMSException ex) { LOG.error("Failed to rollback transacted session [session={}]", transactedSession, ex); } } BEANS.get(MomExceptionHandler.class).handle(e); } } LOG.debug("JMS MessageConsumer for was closed", m_destination); }
Source:
<code>create(String name, InputKind kind, Map<String, Object> args) { args = Args.create(args).add("name", name); <START> String path = this.path + "/" + kind.getRelpath(); <END> service.post(path, args); invalidate(); return (T)get(name); }</code><technical_language>Please expand getRelativePath</technical_language>

Target:
create(String name, InputKind kind, Map<String, Object> args) { args = Args.create(args).add("name", name); String path = this.path + "/" + kind.getRelativePath(); service.post(path, args); invalidate(); return (T)get(name); }
Source:
<code>public DecodingFormat<DeserializationSchema<RowData>> createDecodingFormat( <START> DynamicTableFactory.Context context, <END> ReadableConfig formatOptions) { FactoryUtil.validateFactoryOptions(this, formatOptions); String schemaRegistryURL = formatOptions.get(SCHEMA_REGISTRY_URL); return new DecodingFormat<DeserializationSchema<RowData>>() { @Override public DeserializationSchema<RowData> createRuntimeDecoder( DynamicTableSource.Context context, DataType producedDataType) { final RowType rowType = (RowType) producedDataType.getLogicalType(); final TypeInformation<RowData> rowDataTypeInfo = (TypeInformation<RowData>) context.createTypeInformation(producedDataType); return new DebeziumAvroDeserializationSchema( rowType, rowDataTypeInfo, schemaRegistryURL); } @Override public ChangelogMode getChangelogMode() { return ChangelogMode.newBuilder() .addContainedKind(RowKind.INSERT) .addContainedKind(RowKind.UPDATE_BEFORE) .addContainedKind(RowKind.UPDATE_AFTER) .addContainedKind(RowKind.DELETE) .build(); } }; }</code><technical_language>Add more indent for method arguments. Please check other methods</technical_language>

Target:
public DecodingFormat<DeserializationSchema<RowData>> createDecodingFormat( DynamicTableFactory.Context context, ReadableConfig formatOptions) { FactoryUtil.validateFactoryOptions(this, formatOptions); String schemaRegistryURL = formatOptions.get(SCHEMA_REGISTRY_URL); return new DecodingFormat<DeserializationSchema<RowData>>() { @Override public DeserializationSchema<RowData> createRuntimeDecoder( DynamicTableSource.Context context, DataType producedDataType) { final RowType rowType = (RowType) producedDataType.getLogicalType(); final TypeInformation<RowData> producedTypeInfo = context.createTypeInformation(producedDataType); return new DebeziumAvroDeserializationSchema( rowType, producedTypeInfo, schemaRegistryURL); } @Override public ChangelogMode getChangelogMode() { return ChangelogMode.newBuilder() .addContainedKind(RowKind.INSERT) .addContainedKind(RowKind.UPDATE_BEFORE) .addContainedKind(RowKind.UPDATE_AFTER) .addContainedKind(RowKind.DELETE) .build(); } }; }
Source:
<code>public List<Repository> getSelectedRepositories() { <START> if (repos.isEmpty()) { <END> return null; } return repos; }</code><technical_language>style nit: braces single line blocks</technical_language>

Target:
public List<Repository> getSelectedRepositories() { if (repos.isEmpty()) return null; return repos; }
Source:
<code>protected Map<String, String> params() { return Map.of( "card[cvc]", cvc, "card[exp_month]", expiryMonth, "card[exp_year]", expiryYear, "card[number]", cardNo, <START> "type", "card"); <END> }</code><technical_language>send cardholder_name & billing address do</technical_language>

Target:
protected Map<String, String> params() { Map<String, String> localParams = new HashMap<>(); localParams.put("card[exp_month]", authCardDetails.expiryMonth()); localParams.put("card[exp_year]", authCardDetails.expiryYear()); localParams.put("card[number]", authCardDetails.getCardNo()); localParams.put("card[cvc]", authCardDetails.getCvc()); localParams.put("card[name]", authCardDetails.getCardHolder()); localParams.put("type", "card"); authCardDetails.getAddress().ifPresent(address -> { localParams.put("card[address_line1]", address.getLine1()); if (StringUtils.isNotBlank(address.getLine2())) { localParams.put("card[address_line2]", address.getLine2()); } localParams.put("card[address_city]", address.getCity()); localParams.put("card[address_country]", address.getCountry()); localParams.put("card[address_zip]", address.getPostcode()); }); return Map.copyOf(localParams); }
Source:
<code>public NfcStatus disableExclusiveNfc() { NfcAdapter adapter = NfcAdapter.getDefaultAdapter(activity); if (adapter != null) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { disableReaderMode(adapter); } else { disableForegroundDispatch(adapter); } return NfcStatus.AVAILABLE; } <START> if (handleUnavailableNfc) toast("NFC is not available on this device"); <END> return NfcStatus.NOT_AVAILABLE; }</code><technical_language>@Franzaine I this is a bit overkill</technical_language>

Target:
public void disableExclusiveNfc() { NfcAdapter adapter = NfcAdapter.getDefaultAdapter(activity); if (adapter != null) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { disableReaderMode(adapter); } else { disableForegroundDispatch(adapter); } } }
Source:
<code>@Override public void load(Request request, int networkPolicy, Callback callback) { try { Source source = Okio.source(getInputStream(request)); callback.onSuccess(new Result(source, DISK)); } catch (Exception e) { <START> callback.onError(e); <END> } }</code><technical_language>here. double callback call</technical_language>

Target:
@Override public void load(Request request, int networkPolicy, Callback callback) { boolean signaledCallback = false; try { Source source = Okio.source(getInputStream(request)); signaledCallback = true; callback.onSuccess(new Result(source, DISK)); } catch (Exception e) { if (!signaledCallback) { callback.onError(e); } } }
Source:
<code>public Location getLastLocation() { if (!googleApiClient.isConnected()) { <START> new Thread(googleApiClient::blockingConnect).start(); <END> } return fusedLocationProviderApi.getLastLocation(googleApiClient); }</code><technical_language>a concerned this. If client connected, spin a new thread connect problems for call getLastLocation (as happen client is connected)? Also, testing of this in GoogleFusedLocationClientTest (using a timeout) flakey call blockingConnect is async (and behaviour of method indeterminate). pull this fix out of PR a part of a PR</technical_language>

Target:
public Location getLastLocation() { if (!googleApiClient.isConnected()) { googleApiClient.blockingConnect(); } return fusedLocationProviderApi.getLastLocation(googleApiClient); }
Source:
<code>protected ResultHeaderItem(final String name) { <START> this.name = name; <END> }</code><technical_language>put notEmpty</technical_language>

Target:
protected ResultHeaderItem(final String name) { this.name = notEmpty(name, "name"); }
Source:
<code>public void request_with_unknown_binding_only_forward_traffic() throws Exception { when(bindingRepo.findOne(BINDING_ID)).thenReturn(null); mockMvc.perform(get(Path.PROXY_CONTEXT+"/"+BINDING_ID) <START> .header(ProxyController.HEADER_FORWARD_URL,"www.google.fr") <END> .accept(MediaType.ALL)) .andExpect(status().is(HttpStatus.MOVED_TEMPORARILY.value())); }</code><technical_language>Choose another url please :smile:</technical_language>

Target:
public void request_with_unknown_binding_only_forward_traffic() throws Exception { when(bindingRepo.findOne(BINDING_ID)).thenReturn(null); mockMvc.perform(get(Path.PROXY_CONTEXT+"/"+BINDING_ID) .header(ProxyController.HEADER_FORWARD_URL,"www.cloudfoundry.org") .accept(MediaType.ALL)) .andExpect(status().is(HttpStatus.MOVED_TEMPORARILY.value())); }
Source:
<code>public void immediateFade(String channelString, String fadeString, Boolean resumeAfter) { List<DmxChannel> channels = new ArrayList<>(); try { List<BaseDmxChannel> configChannels = BaseDmxChannel.fromString(channelString, getUniverseId()); logger.trace("found channels in {}", configChannels.size(), this.thing.getUID()); for (BaseDmxChannel channel : configChannels) { channels.add(getDmxChannel(channel, this.thing)); } } catch (IllegalArgumentException e) { logger.debug("invalid channel configuration: {}", channelString); return; } ValueSet value = ValueSet.fromString(fadeString); if (value.isEmpty()) { <START> logger.info("invalid fade configuration: {}", fadeString); <END> return; } Integer channelCounter = 0; for (DmxChannel channel : channels) { if (resumeAfter) { channel.suspendAction(); } else { channel.clearAction(); } channel.addChannelAction( new FadeAction(value.getFadeTime(), value.getValue(channelCounter), value.getHoldTime())); if (resumeAfter) { channel.addChannelAction(new ResumeAction()); } channelCounter++; } }</code><technical_language>do a WARN</technical_language>

Target:
public void immediateFade(String channelString, String fadeString, Boolean resumeAfter) { List<DmxChannel> channels = new ArrayList<>(); try { List<BaseDmxChannel> configChannels = BaseDmxChannel.fromString(channelString, getUniverseId()); logger.trace("found channels in {}", configChannels.size(), this.thing.getUID()); for (BaseDmxChannel channel : configChannels) { channels.add(getDmxChannel(channel, this.thing)); } } catch (IllegalArgumentException e) { logger.warn("invalid channel configuration: {}", channelString); return; } ValueSet value = ValueSet.fromString(fadeString); if (value.isEmpty()) { logger.warn("invalid fade configuration: {}", fadeString); return; } Integer channelCounter = 0; for (DmxChannel channel : channels) { if (resumeAfter) { channel.suspendAction(); } else { channel.clearAction(); } channel.addChannelAction( new FadeAction(value.getFadeTime(), value.getValue(channelCounter), value.getHoldTime())); if (resumeAfter) { channel.addChannelAction(new ResumeAction()); } channelCounter++; } }
Source:
<code>public void setUp(Context context, Run<?, ?> build, FilePath workspace, Launcher launcher, TaskListener listener, EnvVars initialEnvironment) throws IOException, InterruptedException { context.setDisposer(new MesosSingleUseSlaveDisposer()); Computer computer = workspace.toComputer(); if (computer != null) { if (MesosComputer.class.isInstance(computer)) { String msg = "Marking " + computer.getName() + " as single-use."; <START> LOGGER.warning(msg); <END> listener.getLogger().println(msg); MesosSlave mesosSlave = (MesosSlave) computer.getNode(); if (mesosSlave != null) { mesosSlave.setSingleUse(true); } } else { listener.getLogger().println("Not able to set single-use slave, this is a " + computer.getClass()); } } }</code><technical_language>this is a LOGGER.warning. this Logger.info this is intentional</technical_language>

Target:
public void setUp(Context context, Run<?, ?> build, FilePath workspace, Launcher launcher, TaskListener listener, EnvVars initialEnvironment) throws IOException, InterruptedException { context.setDisposer(new MesosSingleUseSlaveDisposer()); Computer computer = workspace.toComputer(); if (computer != null) { if (MesosComputer.class.isInstance(computer)) { String msg = "Marking " + computer.getName() + " as single-use."; LOGGER.info(msg); listener.getLogger().println(msg); MesosSlave mesosSlave = (MesosSlave) computer.getNode(); if (mesosSlave != null) { mesosSlave.setSingleUse(true); } } else { listener.getLogger().println("Not able to set single-use slave, this is a " + computer.getClass()); } } }
Source:
<code>private void findNextValidResultCursor() { while (queryIterator.hasNext()){ final DBObject currentQuery = queryIterator.next(); currentBindingSetCollection = rangeMap.get(currentQuery); final List<Document> pipeline = new ArrayList<>(); pipeline.add(new Document("$match", currentQuery)); pipeline.addAll(AggregationUtil.createRedactPipeline(auths)); log.debug(pipeline); <START> final AggregationOptions opts = AggregationOptions.builder() <END> .batchSize(1000) .build(); final AggregateIterable<Document> aggIter = coll.aggregate(pipeline); resultsIterator = aggIter.iterator(); if (resultsIterator.hasNext()) { break; } } }</code><technical_language>this used? Do need apply this iterator</technical_language>

Target:
private void findNextValidResultCursor() { while (queryIterator.hasNext()){ final DBObject currentQuery = queryIterator.next(); currentBindingSetCollection = rangeMap.get(currentQuery); final List<Document> pipeline = new ArrayList<>(); pipeline.add(new Document("$match", currentQuery)); pipeline.addAll(AggregationUtil.createRedactPipeline(auths)); log.debug(pipeline); final AggregateIterable<Document> aggIter = coll.aggregate(pipeline); aggIter.batchSize(1000); resultsIterator = aggIter.iterator(); if (resultsIterator.hasNext()) { break; } } }
Source:
<code><START> public void delete(Question question) { <END> session.createSQLQuery("SET foreign_key_checks = 0").executeUpdate(); QuestionQuery query = new QuestionQuery(question); query.execute("delete f,qf from Question q" + " join Question_Flags qf on qf.Question_id=q.id" + " join Flag f on f.id=qf.flags_id" + " where q.id=:id"); query.execute("delete w,qw from Question q" + " join Question_Watchers qw on qw.Question_id=q.id" + " join Watcher w on w.id=qw.watchers_id" + " where q.id=:id"); query.execute("delete from ReputationEvent where context_id=:id and context_type='QUESTION'"); deleteAttachments(question); deleteRelationshipTables(question); session.createSQLQuery("delete from QuestionInformation_Tag where QuestionInformation_id=:id") .setParameter("id", question.getInformation().getId()) .executeUpdate(); query.execute("delete from QuestionInformation where question_id=:id"); query.execute("delete from Question where id=:id"); session.createSQLQuery("SET foreign_key_checks = 1").executeUpdate(); }</code><technical_language>I delete logically(deleted=true), this recover a question want</technical_language>

Target:
public void delete(Question question) { session.delete(question); }
Source:
<code>public OperationFuture<LoadBalancerPool> delete(LoadBalancerPool loadBalancerPool) { LoadBalancer loadBalancer = loadBalancerPool.getLoadBalancer(); loadBalancerPoolClient.delete( <START> fetchDataCenterId(loadBalancer.getDataCenter()), <END> fetchLoadBalancerId(loadBalancer), findByRef(loadBalancerPool).getId() ); return new OperationFuture<>( loadBalancerPool, new NoWaitingJobFuture() ); }</code><technical_language>load load balancer get information data center</technical_language>

Target:
public OperationFuture<LoadBalancerPool> delete(LoadBalancerPool loadBalancerPool) { LoadBalancerPoolMetadata loadBalancerPoolMetadata = findByRef(loadBalancerPool); loadBalancerPoolClient.delete( loadBalancerPoolMetadata.getDataCenterId(), loadBalancerPoolMetadata.getLoadBalancerId(), loadBalancerPoolMetadata.getId() ); return new OperationFuture<>( loadBalancerPool, new NoWaitingJobFuture() ); }
Source:
<code>public void test() throws Exception { deleteDb("concurrent"); final String url = getURL("concurrent", true); try (Connection conn = getConnection(url)) { Statement stat = conn.createStatement(); stat.execute("create table test(id int primary key, name varchar)"); Task[] tasks = new Task[THREADS]; for (int i = 0; i < THREADS; i++) { final int threadId = i; Task t = new Task() { @Override public void call() throws Exception { Random r = new Random(threadId); try (Connection conn = getConnection(url)) { PreparedStatement insert = conn.prepareStatement( <START> "merge into test values(?, ?)"); <END> PreparedStatement update = conn.prepareStatement( "update test set name = ? where id = ?"); PreparedStatement delete = conn.prepareStatement( "delete from test where id = ?"); PreparedStatement select = conn.prepareStatement( "select * from test where id = ?"); while (!stop) { int x = r.nextInt(ROW_COUNT); String data = "x" + r.nextInt(ROW_COUNT); switch (r.nextInt(3)) { case 0: insert.setInt(1, x); insert.setString(2, data); insert.execute(); break; case 1: update.setString(1, data); update.setInt(2, x); update.execute(); break; case 2: delete.setInt(1, x); delete.execute(); break; case 4: select.setInt(1, x); ResultSet rs = select.executeQuery(); while (rs.next()) { rs.getString(2); } break; } } } } }; tasks[i] = t; t.execute(); } for (int i = 0; i < 200; i++) { Thread.sleep(10); for (Task t : tasks) { if (t.isFinished()) { i = 1000; break; } } } for (Task t : tasks) { t.get(); } } }</code><technical_language>INSERT replaced MERGE</technical_language>

Target:
public void test() throws Exception { deleteDb("concurrent"); final String url = getURL("concurrent", true); try (Connection conn = getConnection(url)) { Statement stat = conn.createStatement(); stat.execute("create table test(id int primary key, name varchar)"); Task[] tasks = new Task[THREADS]; for (int i = 0; i < THREADS; i++) { final int threadId = i; Task t = new Task() { @Override public void call() throws Exception { Random r = new Random(threadId); try (Connection conn = getConnection(url)) { PreparedStatement insert = conn.prepareStatement( "merge into test values(?, ?)"); PreparedStatement update = conn.prepareStatement( "update test set name = ? where id = ?"); PreparedStatement delete = conn.prepareStatement( "delete from test where id = ?"); PreparedStatement select = conn.prepareStatement( "select * from test where id = ?"); while (!stop) { int x = r.nextInt(ROW_COUNT); String data = "x" + r.nextInt(ROW_COUNT); switch (r.nextInt(4)) { case 0: insert.setInt(1, x); insert.setString(2, data); insert.execute(); break; case 1: update.setString(1, data); update.setInt(2, x); update.execute(); break; case 2: delete.setInt(1, x); delete.execute(); break; case 3: select.setInt(1, x); ResultSet rs = select.executeQuery(); while (rs.next()) { rs.getString(2); } break; } } } } }; tasks[i] = t; t.execute(); } for (int i = 0; i < 200; i++) { Thread.sleep(10); for (Task t : tasks) { if (t.isFinished()) { i = 1000; break; } } } for (Task t : tasks) { t.get(); } } }
Source:
<code>public SubmissionResult toSubmissionResult() { SubmissionResult submissionResult = new SubmissionResult(); if (error == null && status == SubmissionResult.Status.ERROR) { error = "errored"; } submissionResult.setError(error); submissionResult.setStatus(status); ArrayList<String> submissionPoints = new ArrayList<>(); if (status == SubmissionResult.Status.OK) { <START> submissionPoints.add(String.valueOf("1")); <END> } else { submissionPoints.add(String.valueOf("0")); } submissionResult.setPoints(submissionPoints); submissionResult.setTestCases(testResults); return submissionResult; }</code><technical_language>this (and similar line in else block) end String.valueOf(((Object)"1").toString())? Is some specific reason want cast a String Object a String adding String</technical_language>

Target:
public SubmissionResult toSubmissionResult() { SubmissionResult submissionResult = new SubmissionResult(); if (error == null && status == SubmissionResult.Status.ERROR) { error = "errored"; } submissionResult.setError(error); submissionResult.setStatus(status); ArrayList<String> submissionPoints = new ArrayList<>(); if (status == SubmissionResult.Status.OK) { submissionPoints.add("1"); } else { submissionPoints.add("0"); } submissionResult.setPoints(submissionPoints); submissionResult.setTestCases(testResults); return submissionResult; }
Source:
<code>public static <T> Notification<T> createOnNext(T value) { <START> Objects.requireNonNull(value, "value is null"); <END> return new NextNotification<T>(value); }</code><technical_language>This unfortunate. RS spec forbid null values</technical_language>

Target:
public static <T> Notification<T> createOnNext(T value) { Objects.requireNonNull(value, "value is null"); return new Notification<T>(value); }
Source:
<code>protected void doStartMachine(KubernetesServerResolver serverResolver) throws InfrastructureException { <START> machineStartupTraces = new ConcurrentHashMap<>(getContext().getEnvironment().getPods().size()); <END> final KubernetesEnvironment environment = getContext().getEnvironment(); final Map<String, InternalMachineConfig> machineConfigs = environment.getMachines(); final String workspaceId = getContext().getIdentity().getWorkspaceId(); LOG.debug("Begin pods creation for workspace '{}'", workspaceId); for (Pod toCreate : environment.getPods().values()) { final Pod createdPod = namespace.deployments().deploy(toCreate); LOG.debug( "Creating pod '{}' in workspace '{}'", toCreate.getMetadata().getName(), workspaceId); final ObjectMeta podMetadata = createdPod.getMetadata(); for (Container container : createdPod.getSpec().getContainers()) { String machineName = Names.machineName(toCreate, container); machineStartupTraces.put( machineName, tracer .buildSpan("container-create") .asChildOf(tracer.activeSpan()) .withTag("machineName", machineName) .start()); LOG.debug("Creating machine '{}' in workspace '{}'", machineName, workspaceId); machines.put( getContext().getIdentity(), new KubernetesMachineImpl( workspaceId, machineName, podMetadata.getName(), container.getName(), MachineStatus.STARTING, machineConfigs.get(machineName).getAttributes(), serverResolver.resolve(machineName))); eventPublisher.sendStartingEvent(machineName, getContext().getIdentity()); } } LOG.debug("Pods creation finished in workspace '{}'", workspaceId); }</code><technical_language># of machines != # of pods. I misunderstanding this predicted size for a map for a # of machines</technical_language>

Target:
protected void doStartMachine(KubernetesServerResolver serverResolver) throws InfrastructureException { machineStartupTraces = new ConcurrentHashMap<>(getContext().getEnvironment().getMachines().size()); final KubernetesEnvironment environment = getContext().getEnvironment(); final Map<String, InternalMachineConfig> machineConfigs = environment.getMachines(); final String workspaceId = getContext().getIdentity().getWorkspaceId(); LOG.debug("Begin pods creation for workspace '{}'", workspaceId); for (Pod toCreate : environment.getPods().values()) { startTracingContainersStartup(toCreate); final Pod createdPod = namespace.deployments().deploy(toCreate); LOG.debug( "Creating pod '{}' in workspace '{}'", toCreate.getMetadata().getName(), workspaceId); final ObjectMeta podMetadata = createdPod.getMetadata(); for (Container container : createdPod.getSpec().getContainers()) { String machineName = Names.machineName(toCreate, container); LOG.debug("Creating machine '{}' in workspace '{}'", machineName, workspaceId); machines.put( getContext().getIdentity(), new KubernetesMachineImpl( workspaceId, machineName, podMetadata.getName(), container.getName(), MachineStatus.STARTING, machineConfigs.get(machineName).getAttributes(), serverResolver.resolve(machineName))); eventPublisher.sendStartingEvent(machineName, getContext().getIdentity()); } } LOG.debug("Pods creation finished in workspace '{}'", workspaceId); }
Source:
<code>public boolean isBandwidthRestricted() { <START> if (bandwidthLimit == Long.MAX_VALUE) { <END> return false; } return true; }</code><technical_language>return bandwidthLimit != Long.MAX_VALUE</technical_language>

Target:
public boolean isBandwidthRestricted() { return bandwidthLimit != Long.MAX_VALUE; }
Source:
<code>private void setGameModes() { for (Field f: GameModes.class.getDeclaredFields()) { try { <START> f.set(null, gameModeMappings.get(f.getName())); <END> } catch (Exception e) { e.printStackTrace(); } } }</code><technical_language>[RegistryHelper](<LINK_0></technical_language>

Target:
private void setGameModes() { RegistryHelper.mapFields(GameModes.class, gameModeMappings); }
Source:
<code>protected boolean canDoAction() { if (!super.canDoAction()) { return false; } <START> if (getParameters().getClusterId() == null) { <END> addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_CLUSTER_IS_NOT_VALID); return false; } if (getParameters().getConfigParams() == null) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_VOLUME_SNAPSHOT_CONFIG_PARAMS_IS_EMPTY); return false; } for (GlusterVolumeSnapshotConfig param : getParameters().getConfigParams()) { if (StringUtils.isEmpty(param.getParamValue())) { addCustomValue("snapshotConfigParam", param.getParamName()); addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_VOLUME_SNAPSHOT_CONFIG_PARAM_VALUE_IS_EMPTY); return false; } } return true; }</code><technical_language>Check is cluster supports gluster snapshot</technical_language>

Target:
protected boolean canDoAction() { if (!super.canDoAction()) { return false; } if (getParameters().getClusterId() == null) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_CLUSTER_IS_NOT_VALID); return false; } if (!GlusterFeatureSupported.glusterSnapshot(getVdsGroup().getCompatibilityVersion())) { failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_VOLUME_SNAPSHOT_NOT_SUPPORTED); } if (getParameters().getConfigParams() == null) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_VOLUME_SNAPSHOT_CONFIG_PARAMS_IS_EMPTY); return false; } for (GlusterVolumeSnapshotConfig param : getParameters().getConfigParams()) { if (StringUtils.isEmpty(param.getParamValue())) { addCustomValue("snapshotConfigParam", param.getParamName()); addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_VOLUME_SNAPSHOT_CONFIG_PARAM_VALUE_IS_EMPTY); return false; } } return true; }
Source:
<code>public void addRequestable( IAEItemStack option ) { if( this.isStackNull( option ) ) { return; } final IAEItemStack st = this.getItemRecord( option.getItem() ).get( option ); if( st != null ) { ( (IAEItemStack) st ).setCountRequestable( st.getCountRequestable() + option.getCountRequestable() ); return; } <START> final IAEItemStack opt = (IAEItemStack) option.copy(); <END> opt.setStackSize( 0 ); opt.setCraftable( false ); opt.setCountRequestable( opt.getCountRequestable() ); this.putItemRecord( opt ); }</code><technical_language>s.o</technical_language>

Target:
public void addRequestable( IAEItemStack option ) { if( option == null ) { return; } final IAEItemStack st = this.getItemRecord( option.getItem() ).get( option ); if( st != null ) { st.setCountRequestable( st.getCountRequestable() + option.getCountRequestable() ); return; } final IAEItemStack opt = option.copy(); opt.setStackSize( 0 ); opt.setCraftable( false ); opt.setCountRequestable( option.getCountRequestable() ); this.putItemRecord( opt ); }
Source:
<code>private KieSession marshallAndUnmarshall(final KieServices ks, final KieBase kbase, KieSession ksession, final KieSessionConfiguration sessionConfig) { Marshaller marshaller = ks.getMarshallers().newMarshaller(kbase); try (final ByteArrayOutputStream baos = new ByteArrayOutputStream()) { marshaller.marshall(baos, ksession); try (final ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray())) { marshaller = MarshallerFactory.newMarshaller(kbase); ksession = marshaller.unmarshall(bais, sessionConfig, null); } } catch (Exception e) { e.printStackTrace(); <START> Assertions.fail("unexpected exception :" + e.getMessage()); <END> } return ksession; }</code><technical_language>System.out. Assertions.fail(msg, ex) exists for this exact purpose</technical_language>

Target:
private KieSession marshallAndUnmarshall(final KieServices ks, final KieBase kbase, KieSession ksession, final KieSessionConfiguration sessionConfig) { Marshaller marshaller = ks.getMarshallers().newMarshaller(kbase); try (final ByteArrayOutputStream baos = new ByteArrayOutputStream()) { marshaller.marshall(baos, ksession); try (final ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray())) { marshaller = MarshallerFactory.newMarshaller(kbase); ksession = marshaller.unmarshall(bais, sessionConfig, null); } } catch (Exception e) { Assertions.fail("Unexpected exception: ", e); } return ksession; }
Source:
<code>static ChangedFileSet getTextSymbols(@NonNull IProject project) { String path = getRelativeAndroidOut(project); ChangedFileSet set = new ChangedFileSet( "textSymbols", <START> path + "/R.txt"); <END> return set; }</code><technical_language>in a CL, R.txt a constant</technical_language>

Target:
static ChangedFileSet getTextSymbols(@NonNull IProject project) { String path = getRelativeAndroidOut(project); ChangedFileSet set = new ChangedFileSet( "textSymbols", path + '/' + SdkConstants.FN_RESOURCE_TEXT); return set; }
Source:
<code>private SupportedTypesResourceDefinition(SimpleAttributeDefinition... attributes) { <START> super(ModelElement.SUPPORTED_TYPES, new IDMConfigAddStepHandler(attributes), null, attributes); <END> }</code><technical_language>remove handler</technical_language>

Target:
private SupportedTypesResourceDefinition(SimpleAttributeDefinition... attributes) { super(ModelElement.SUPPORTED_TYPES, new IDMConfigAddStepHandler(attributes), attributes); }
Source:
<code>private void saveParsingIssue(SensorContext context, RecognitionException e, InputFile inputFile) { if (parsingErrorRuleKey != null) { NewIssue issue = context.newIssue(); NewIssueLocation location = issue.newLocation() .message(e.getMessage()) .on(inputFile); <START> if (e.getLine() > 0) { <END> location.at(inputFile.selectLine(e.getLine())); } issue .forRule(parsingErrorRuleKey) .at(location) .save(); } }</code><technical_language>@ivandalbosco Is invalid line? a consequence a parsing issue file level</technical_language>

Target:
private void saveParsingIssue(SensorContext context, RecognitionException e, InputFile inputFile) { if (parsingErrorRuleKey != null) { NewIssue issue = context.newIssue(); NewIssueLocation location = issue.newLocation() .message(e.getMessage()) .on(inputFile) .at(inputFile.selectLine(e.getLine())); issue .forRule(parsingErrorRuleKey) .at(location) .save(); } }
Source:
<code>public String getSizeOfDataset() { GetDatasetStorageSizeCommand cmd = new GetDatasetStorageSizeCommand(dvRequestService.getDataverseRequest(), dataset, false, GetDatasetStorageSizeCommand.Mode.DOWNLOAD, workingVersion); try { long bytes = commandEngine.submit(cmd); <START> return FileSizeChecker.bytesToHumanReadable(bytes); <END> } catch (CommandException ex) { return ""; } }</code><technical_language>Bug in download size displayed. locally tested datasets download "300 B", resulting ZIP is 11 KB, 11,000 B</technical_language>

Target:
public String getSizeOfDataset() { boolean original = false; return DatasetUtil.getDownloadSize(workingVersion, original); }
Source:
<code>private int averageSizeAroundAllNodes() { int totalSize = 0; for (Ignite ignite : IgnitionEx.allGrids()) { <START> for (String cacheName : CACHE_NAMES) { <END> totalSize += ignite.cache(cacheName).size(); } } return totalSize / IgnitionEx.allGrids().size(); }</code><technical_language>Brackets removed</technical_language>

Target:
private int averageSizeAroundAllNodes() { int totalSize = 0; for (Ignite ignite : IgnitionEx.allGrids()) { for (String cacheName : CACHE_NAMES) totalSize += ignite.cache(cacheName).size(); } return totalSize / IgnitionEx.allGrids().size(); }
Source:
<code>protected void ensureHashTableLoaded() { if (this.hashTables != null) { return; } synchronized (this) { if (this.hashTables != null) { return; } <START> int[] offsets = getOffsets(); <END> int elementCount = getRawKeyBlock().getPositionCount(); int mapCount = offsets.length - 1; boolean[] mapIsNull = getMapIsNull(); int[] hashTables = new int[elementCount * HASH_MULTIPLIER]; Arrays.fill(hashTables, -1); for (int i = 0; i < mapCount; i++) { int keyOffset = offsets[i]; int keyCount = offsets[i + 1] - keyOffset; if (keyCount < 0) { throw new IllegalArgumentException(format("Offset is not monotonically ascending. offsets[%s]=%s, offsets[%s]=%s", i, offsets[i], i + 1, offsets[i + 1])); } if (mapIsNull != null && mapIsNull[i] && keyCount != 0) { throw new IllegalArgumentException("A null map must have zero entries"); } buildHashTable( getRawKeyBlock(), keyOffset, keyCount, keyBlockHashCode, hashTables, keyOffset * HASH_MULTIPLIER, keyCount * HASH_MULTIPLIER); } this.hashTables = hashTables; } }</code><technical_language>do offsets variable instead of accessing this.offsets directly</technical_language>

Target:
protected void ensureHashTableLoaded() { if (this.hashTables != null) { return; } synchronized (this) { if (this.hashTables != null) { return; } int[] hashTables = new int[getRawKeyBlock().getPositionCount() * HASH_MULTIPLIER]; Arrays.fill(hashTables, -1); for (int i = 0; i < offsets.length - 1; i++) { int keyOffset = offsets[i]; int keyCount = offsets[i + 1] - keyOffset; if (keyCount < 0) { throw new IllegalArgumentException(format("Offset is not monotonically ascending. offsets[%s]=%s, offsets[%s]=%s", i, offsets[i], i + 1, offsets[i + 1])); } if (mapIsNull != null && mapIsNull[i] && keyCount != 0) { throw new IllegalArgumentException("A null map must have zero entries"); } buildHashTable( getRawKeyBlock(), keyOffset, keyCount, keyBlockHashCode, hashTables, keyOffset * HASH_MULTIPLIER, keyCount * HASH_MULTIPLIER); } this.hashTables = hashTables; } }
Source:
<code>public void applyPartitions(List<Map<String, String>> remainingPartitions) { if (catalogTable.getPartitionKeys() != null && catalogTable.getPartitionKeys().size() != 0) { this.remainingPartitions = remainingPartitions; <START> } <END> }</code><technical_language>report error for else branch</technical_language>

Target:
public void applyPartitions(List<Map<String, String>> remainingPartitions) { if (catalogTable.getPartitionKeys() != null && catalogTable.getPartitionKeys().size() != 0) { this.remainingPartitions = remainingPartitions; } else { throw new UnsupportedOperationException( "Should not apply partitions to a non-partitioned table."); } }
Source:
<code>public <T> T withLock(Function<Boolean, T> function) { try { return function.apply(lock.tryLock()); } finally { <START> lock.unlock(); <END> } }</code><technical_language>I imagine happen technically this throw a IllegalMonitorStateException. catch ignore out of abundance of caution</technical_language>

Target:
public <T> T withLock(Function<Boolean, T> function) { try { return function.apply(lock.tryLock()); } finally { try { lock.unlock(); } catch (IllegalMonitorStateException ignored) { } } }
Source:
<code>private boolean isTraceActionDecoratedByRxWorker(Runnable action) { try { <START> if (action instanceof Disposable) { <END> Field modifiersField = action.getClass() .getDeclaredField("decoratedRun"); modifiersField.setAccessible(true); return modifiersField.get(action) instanceof TraceAction; } return false; } catch (Exception e) { return false; } }</code><technical_language>this is expensive check. check w/ some rx maintainers if a way</technical_language>

Target:
private boolean isTraceActionDecoratedByRxWorker(Runnable action) { if (action instanceof TraceAction) { return true; } else if (action instanceof SchedulerRunnableIntrospection) { SchedulerRunnableIntrospection runnableIntrospection = (SchedulerRunnableIntrospection) action; return runnableIntrospection.getWrappedRunnable() instanceof TraceAction; } return false; }
Source:
<code>public String createProject(Project project, User user) { <START> return this.projectDao.create(project, user); <END> }</code><technical_language>Consider capturing DAO layer exceptions creating service layer exceptions, abstract persistence layer servlets</technical_language>

Target:
public String createProject(Project project, User user) { validateInput(project); return this.projectDao.create(project, user); }
Source:
<code>public void addChildElement(PropertyWriter p) { this.childElements.put(p.getElement().getId(), p); <START> if (p instanceof BoundaryEventPropertyWriter) { <END> process.getFlowElements().add(p.getFlowElement()); } else { process.getFlowElements().add(0, p.getFlowElement()); } p.setParent(this); ElementParameters simulationParameters = p.getSimulationParameters(); if (simulationParameters != null) { this.simulationParameters.add(simulationParameters); } this.itemDefinitions.addAll(p.itemDefinitions); this.rootElements.addAll(p.rootElements); }</code><technical_language>code duplication</technical_language>

Target:
public void addChildElement(PropertyWriter p) { p.setParent(this); Processes.addChildElement( p, childElements, process, simulationParameters, itemDefinitions, rootElements); }
Source:
<code>public void testReportsServiceDownWhenKilled() throws Exception { LOG.info("test=testReportsServiceDownWithKilled; entity="+entity+"; app="+entity.getApplication()); Entities.start(entity.getApplication(), ImmutableList.of(loc)); <START> EntityTestUtils.assertAttributeEqualsEventually(MutableMap.of("timeout", 120 * 1000), entity, Startable.SERVICE_UP, true); <END> killEntityBehindBack(entity); LOG.info("Killed behind mgmt's back, waiting for service up false in mgmt context", entity); EntityTestUtils.assertAttributeEqualsEventually(entity, Startable.SERVICE_UP, false); LOG.info("success getting service up false in primary mgmt universe"); }</code><technical_language>Duration.minutes(2)</technical_language>

Target:
public void testReportsServiceDownWhenKilled() throws Exception { LOG.info("test=testReportsServiceDownWithKilled; entity="+entity+"; app="+entity.getApplication()); Entities.start(entity.getApplication(), ImmutableList.of(loc)); EntityTestUtils.assertAttributeEqualsEventually(MutableMap.of("timeout", Duration.minutes(2)), entity, Startable.SERVICE_UP, true); killEntityBehindBack(entity); LOG.info("Killed behind mgmt's back, waiting for service up false in mgmt context", entity); EntityTestUtils.assertAttributeEqualsEventually(entity, Startable.SERVICE_UP, false); LOG.info("success getting service up false in primary mgmt universe"); }