auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void assignActivityChristmasInterestCoupon(String message){ <START> InvestSuccessMessage investSuccessMessage = JsonConverter.readValue(message, InvestSuccessMessage.class); <END> Date nowDate = DateTime.now().toDate(); if(investSuccessMessage == null){ logger.error("[MQ] parse InvestSuccessMessage is error {}.", message); return; } if(investSuccessMessage.getInvestInfo() == null){ logger.error("[MQ] query invest by investId is not exists {}.", investSuccessMessage.getInvestInfo().getInvestId()); return; } logger.info("[MQ] ready to consume activity message: assigning coupon."); if ((activityChristmasStartTime.before(nowDate) && activityChristmasEndTime.after(nowDate)) && investSuccessMessage.getLoanDetailInfo().isActivity() && investSuccessMessage.getLoanDetailInfo().getActivityDesc().equals(LOAN_ACTIVITY_DESCRIPTION) && (!investSuccessMessage.getInvestInfo().getTransferStatus().equals("SUCCESS") && investSuccessMessage.getInvestInfo().getStatus().equals("SUCCESS")) && investSuccessMessage.getInvestInfo().getAmount() >= INVEST_LIMIT) { mqClient.sendMessage(MessageQueue.CouponAssigning, investSuccessMessage.getInvestInfo().getLoginName() + ":" + INTEREST_COUPON_OF_ZERO_5_PERCENT_COUPON_ID); } }</code><technical_language>exception</technical_language>

Target:
private void assignActivityChristmasInterestCoupon(String message) { InvestSuccessMessage investSuccessMessage = null; try { investSuccessMessage = JsonConverter.readValue(message, InvestSuccessMessage.class); } catch (IOException e) { throw new RuntimeException(e); } Date nowDate = DateTime.now().toDate(); logger.info("[MQ] ready to consume activity message: assigning coupon."); if ((activityChristmasStartTime.before(nowDate) && activityChristmasEndTime.after(nowDate)) && investSuccessMessage.getLoanDetailInfo().isActivity() && investSuccessMessage.getLoanDetailInfo().getActivityDesc().equals(LOAN_ACTIVITY_DESCRIPTION) && (!investSuccessMessage.getInvestInfo().getTransferStatus().equals("SUCCESS") && investSuccessMessage.getInvestInfo().getStatus().equals("SUCCESS")) && investSuccessMessage.getInvestInfo().getAmount() >= INVEST_LIMIT) { mqClient.sendMessage(MessageQueue.CouponAssigning, investSuccessMessage.getInvestInfo().getLoginName() + ":" + INTEREST_COUPON_OF_ZERO_5_PERCENT_COUPON_ID); } }
Source:
<code>ListPopup inflatePopupMenu(ArrayAdapter<ListPopup.Item> adapter, Context context) { ListPopup menu = new ListPopup(context); menu.setAdapter(adapter); String favApps = PreferenceManager.getDefaultSharedPreferences(context). getString("favorite-apps-list", ""); if (favApps.contains(this.pojo.id + ";")) { for (int i = 0; i < adapter.getCount(); i += 1) { ListPopup.Item item = adapter.getItem(i); assert item != null; if (item.stringId == R.string.menu_favorites_add) adapter.remove(item); } } else { for (int i = 0; i < adapter.getCount(); i += 1) { ListPopup.Item item = adapter.getItem(i); assert item != null; if (item.stringId == R.string.menu_favorites_remove) adapter.remove(item); } } if (BuildConfig.DEBUG) { <START> int relevance = pojo.relevance - 1; <END> adapter.add(new ListPopup.Item(context, "Relevance: " + relevance)); } return menu; }</code><technical_language>reason for - 1 ? before, granted, I need</technical_language>

Target:
ListPopup inflatePopupMenu(ArrayAdapter<ListPopup.Item> adapter, Context context) { ListPopup menu = new ListPopup(context); menu.setAdapter(adapter); String favApps = PreferenceManager.getDefaultSharedPreferences(context). getString("favorite-apps-list", ""); if (favApps.contains(this.pojo.id + ";")) { for (int i = 0; i < adapter.getCount(); i += 1) { ListPopup.Item item = adapter.getItem(i); assert item != null; if (item.stringId == R.string.menu_favorites_add) adapter.remove(item); } } else { for (int i = 0; i < adapter.getCount(); i += 1) { ListPopup.Item item = adapter.getItem(i); assert item != null; if (item.stringId == R.string.menu_favorites_remove) adapter.remove(item); } } if (BuildConfig.DEBUG) { adapter.add(new ListPopup.Item("Relevance: " + pojo.relevance)); } return menu; }
Source:
<code>public void null_if_unknown_symbol() throws Exception { ExpressionTree tree = firstExpression("void foo() { unknown(e -> e.method()); }"); <START> ExpressionTree expression = ((MethodInvocationTree) tree).arguments().get(0); <END> MethodInvocationTree methodInvocationTree = (MethodInvocationTree)((LambdaExpressionTree)expression).body(); ExpressionTree defaultValue = JavaPropertiesHelper.retrievedPropertyDefaultValue(methodInvocationTree); assertThat(defaultValue).isNull(); }</code><technical_language>nitpick: rename _expression_ _functionCallArgument_</technical_language>

Target:
public void null_if_unknown_symbol() throws Exception { ExpressionTree tree = firstExpression("void foo() { unknown(e -> e.method()); }"); ExpressionTree functionCallArgument = ((MethodInvocationTree) tree).arguments().get(0); MethodInvocationTree methodCallInsideLambda = (MethodInvocationTree)((LambdaExpressionTree)functionCallArgument).body(); ExpressionTree defaultValue = JavaPropertiesHelper.retrievedPropertyDefaultValue(methodCallInsideLambda); assertThat(defaultValue).isNull(); }
Source:
<code>private void encodeUtf8Component(CharSequence s) { for (int i = 0, len = s.length(); i < len; i++) { char c = s.charAt(i); if (!dontNeedEncoding(c)) { <START> if (i > 0) { <END> uriBuilder.append(s, 0, i); } encodeUtf8ComponentSlow(s, i); return; } } uriBuilder.append(s); }</code><technical_language>I pack this entire branch in a differet method</technical_language>

Target:
private void encodeUtf8Component(CharSequence s) { for (int i = 0, len = s.length(); i < len; i++) { char c = s.charAt(i); if (!dontNeedEncoding(c)) { encodeUtf8Component(s, i, len); return; } } uriBuilder.append(s); }
Source:
<code><START> public void testParseCorrectlyHandlesFileWithNoHeaders() throws IOException, InvalidFormatException, DataParserException { <END> InputStream file = getFile("/TestFile.xlsx"); Workbook workbook = WorkbookFactory.create(file); WorkbookParserSettings settings = WorkbookParserSettings.builder() .withHeader(ExcelHeader.NO_HEADER) .build(); WorkbookParser parser = new WorkbookParser(settings, getContext(), workbook, "Sheet1::0"); Record firstContentRow = parser.parse(); LinkedHashMap<String, Field> contentMap = new LinkedHashMap<>(); for (int i = 0; i <= 4; i++) { contentMap.put(String.valueOf(i), Field.create("column" + (i + 1))); } Field expected = Field.createListMap(contentMap); assertEquals(expected, firstContentRow.get()); }</code><technical_language>I if rat accept new binary files - need explicit exclude in main pom file</technical_language>

Target:
public void testParseCorrectlyHandlesFileWithNoHeaders() throws IOException, InvalidFormatException, DataParserException { Workbook workbook = createWorkbook("/excel/TestExcel.xlsx"); WorkbookParser parser = new WorkbookParser(settingsNoHeader, getContext(), workbook, "Sheet1::0"); Record firstContentRow = parser.parse(); LinkedHashMap<String, Field> contentMap = new LinkedHashMap<>(); for (int i = 0; i <= 4; i++) { contentMap.put(String.valueOf(i), Field.create("column" + (i + 1))); } Field expected = Field.createListMap(contentMap); assertEquals(expected, firstContentRow.get()); }
Source:
<code>public AsyncJobStatus queueJob(JobBuilder builder) { if (builder == null) { throw new IllegalArgumentException("job builder is null"); } AsyncJobStatus job = this.buildJobStatus(builder); job.setState(JobState.QUEUED); <START> job = this.jobCurator.create(job); <END> try { JobMessage message = new JobMessage(job.getId(), job.getJobKey()); this.dispatcher.sendJobMessage(message); } catch (Exception e) { log.warn("Error sending async job message.", e); this.jobCurator.delete(job); throw new RuntimeException("Error sending async job message.", e); } return job; }</code><technical_language>Hrmm... I understand this changed issue (ID generation is done persist), this correct -- implication is default state is "queued," creating default; of sits me. least, move this try block message sending</technical_language>

Target:
public AsyncJobStatus queueJob(JobBuilder builder) { if (builder == null) { throw new IllegalArgumentException("job builder is null"); } AsyncJobStatus job = this.buildJobStatus(builder); job.setState(JobState.CREATED); try { job = this.jobCurator.create(job); JobMessage message = new JobMessage(job.getId(), job.getJobKey()); this.dispatcher.sendJobMessage(message); job = job.setState(JobState.QUEUED); this.jobCurator.merge(job); } catch (Exception e) { log.warn("Error sending async job message.", e); if (job != null && job.getId() != null) { this.jobCurator.delete(job); } throw new RuntimeException("Error sending async job message.", e); } return job; }
Source:
<code>public String getSystem(String streamId) { return getOrDefault(String.format(SYSTEM_FOR_STREAM_ID, streamId), <START> new JobConfig(this).getDefaultSystem().orElse(null)); <END> }</code><technical_language>This is compute new JobConfig(this).getDefaultSystem().orElse(null), if used. a big deal, JobConfig constructor a new copy of config map, nicer lazily evaluate new JobConfig(this).getDefaultSystem().orElse(null)</technical_language>

Target:
public String getSystem(String streamId) { String system = get(String.format(SYSTEM_FOR_STREAM_ID, streamId)); return (system != null) ? system : new JobConfig(this).getDefaultSystem().orElse(null); }
Source:
<code>private boolean shutdownDevice() { List<String> simctlArgs; simctlArgs = Arrays.asList("xcrun", "simctl", "shutdown", deviceUUID); Command simctlCmd = new Command(simctlArgs, true); int exitCode = simctlCmd.executeAndWait(true); <START> if (exitCode == 146) { <END> log.info("This device shuts down already: " + deviceUUID); return true; } else if (exitCode == 0) { log.info("Successfully shut down the device: " + deviceUUID); return true; } log.warning("Failed to shut down the device: " + deviceUUID + ". Command was used: " + simctlCmd.commandString()); return false; }</code><technical_language>146 means? guessing refer _128 + signum_ imply signal 18 (SIGTSTP) sense me</technical_language>

Target:
private boolean shutdownDevice() { List<String> simctlArgs = Arrays.asList("xcrun", "simctl", "shutdown", deviceUUID); Command simctlCmd = new Command(simctlArgs, true); int exitCode = simctlCmd.executeAndWait(true); if (exitCode == 146) { log.info("This device shuts down already: " + deviceUUID); return true; } else if (exitCode == 0) { log.info("Successfully shut down the device: " + deviceUUID); return true; } log.warning("Failed to shut down the device: " + deviceUUID + ". Command was used: " + simctlCmd.commandString()); return false; }
Source:
<code>public void contextDestroyed(ServletContextEvent event) { if (config.getBoolean(ACTIVEMQ_ENABLED)) { activeMQContextListener.contextDestroyed(); <START> injector.getInstance(ActiveMQStatusMonitor.class).stop(); <END> ActiveMQClient.clearThreadPools(); } pinsetterListener.contextDestroyed(); loggerListener.contextDestroyed(); if (config.getBoolean(ConfigProperties.AMQP_INTEGRATION_ENABLED)) { Util.closeSafely(injector.getInstance(AMQPBusPublisher.class), "AMQPBusPublisher"); } injector.getInstance(PersistService.class).stop(); super.contextDestroyed(event); Enumeration<Driver> drivers = DriverManager.getDrivers(); while (drivers.hasMoreElements()) { Driver driver = drivers.nextElement(); try { DriverManager.deregisterDriver(driver); } catch (SQLException e) { log.info(String.format("Failed to de-registering driver %s", driver), e); } } InternalThreadLocalMap.destroy(); try { Thread.sleep(1000L); } catch (Exception e) { } }</code><technical_language>This logic is okay, leaving started shut down. In this case, I argue ActiveMQContextListener responsible for terminating it, arbitrarily grabbing in this class</technical_language>

Target:
public void contextDestroyed(ServletContextEvent event) { super.contextDestroyed(event); try { this.destroySubsystems(); } catch (Exception e) { throw new RuntimeException(e); } }
Source:
<code>protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ProfilingUtils.split("WPLaunchActivity.onCreate"); mMigrationProgressDialog = new ProgressDialog(this); mMigrationProgressDialog.setMessage(this.getResources().getString(R.string.migration_message)); mMigrationProgressDialog.setCancelable(false); <START> mMigrationProgressDialog.show(); <END> WordPress.registerMigrationListener(new WordPress.MigrationListener() { @Override public void onCompletion() { launchWPMainActivity(); } }); }</code><technical_language>show dialog if a migration process begin</technical_language>

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ProfilingUtils.split("WPLaunchActivity.onCreate"); if (WordPress.sIsMigrationInProgress) { final ProgressDialog migrationProgressDialog = new ProgressDialog(this); migrationProgressDialog.setMessage(this.getResources().getString(R.string.migration_message)); migrationProgressDialog.setCancelable(false); migrationProgressDialog.show(); WordPress.registerMigrationListener(new WordPress.MigrationListener() { @Override public void onCompletion() { migrationProgressDialog.dismiss(); launchWPMainActivity(); } }); } else { launchWPMainActivity(); } }
Source:
<code>public String toString() { StringBuilder result = new StringBuilder(); if (this.names.size() > 0) { for (int i=0; i<this.names.size(); i++){ PersonName personName = this.names.get(i); if (i==0){ result.append(personName.toString()); }else{ <START> result.append("|" + personName.toString()); <END> } } } return result.toString(); }</code><technical_language>Please append instead of "+" for performance gain</technical_language>

Target:
public String toString() { final StringBuilder result = new StringBuilder(); if (names.size() > 0) { for (int i = 0; i < names.size(); i++) { final PersonName personName = names.get(i); if (i == 0) { result.append(personName.toString()); } else { result.append("|"); result.append(personName.toString()); } } } return result.toString(); }
Source:
<code>public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { <START> db.execSQL("DROP TABLE IF EXISTS " + TABLE_SORT); <END> onCreate(db); }</code><technical_language>Remove</technical_language>

Target:
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { onCreate(db); }
Source:
<code>public Paragraph<PS, SEG, S> trim(int length) { if(length >= length()) { return this; } else { Position pos = navigator.offsetToPosition(length, Backward); int segIdx = pos.getMajor(); List<SEG> segs = new ArrayList<>(segIdx + 1); segs.addAll(segments.subList(0, segIdx)); segmentOps.subSequence(segments.get(segIdx), 0, pos.getMinor()) <START> .ifPresent(seg -> segs.add(seg)); <END> return new Paragraph<>(paragraphStyle, segmentOps, segs); } }</code><technical_language>afraid this potential of breaking invariant [each Paragraph segment](<LINK_0></technical_language>

Target:
public Paragraph<PS, SEG, S> trim(int length) { if(length >= length()) { return this; } else { Position pos = navigator.offsetToPosition(length, Backward); int segIdx = pos.getMajor(); List<SEG> segs = new ArrayList<>(segIdx + 1); segs.addAll(segments.subList(0, segIdx)); segs.add(segmentOps.subSequence(segments.get(segIdx), 0, pos.getMinor())); if (segs.isEmpty()) { segs.add(segmentOps.createEmpty()); } return new Paragraph<>(paragraphStyle, segmentOps, segs); } }
Source:
<code>public void testDeleteMember() { <START> assertNotNull(nonSelfMember); <END> boolean successful = api().delete(nonSelfMember.id()); assertTrue(successful); }</code><technical_language>Fail test skip it</technical_language>

Target:
public void testDeleteMember() { boolean successful = api().delete(nonSelfMember.id()); assertTrue(successful); }
Source:
<code>public Mono<byte[]> getBodyAsByteArray() { <START> return cachedBody.next().map(byteBuffer -> byteBuffer.array()); <END> }</code><technical_language>suggestion return cachedBody.next().map(ByteBuffer::array);</technical_language>

Target:
public Mono<byte[]> getBodyAsByteArray() { return cachedBody.next().map(ByteBuffer::array); }
Source:
<code>public void playAttackSound() { String sound = getEntitySound() + "_attack"; if (!sound.equals("generic_attack") && AWNPCSounds.isValidSound(sound)) { <START> playSound(AWNPCSounds.getSoundEventFromString(sound), 1.0F, 1.2F / (rand.nextFloat() * 0.2F + 0.9F)); <END> } }</code><technical_language>sound event cached in a field a need query compile id query for time a sound needs played. approach is compile name in constructor cache private final SoundEvent attackSound;</technical_language>

Target:
private void playAttackSound() { if (attackSound != SoundEvents.ENTITY_GENERIC_HURT) { playSound(attackSound, 1.0F, 1.2F / (rand.nextFloat() * 0.2F + 0.9F)); } }
Source:
<code>void handleBody(InputStream payload) throws IOException, MessageFormatException { if (!successfullyDeserialized) { BlobData blobData = MessageFormatRecord.deserializeBlob(payload); chunkIndexToBuffer.put(chunkIndex, <START> ByteBuffer.wrap(Utils.readBytesFromStream(blobData.getStream(), (int) blobData.getSize()))); <END> numChunksRetrieved++; successfullyDeserialized = true; } else { } }</code><technical_language>1. payload get duplicated? In blobData payload is materialized in memory ByteBufferInputStream, Utils.readBytesFromStream create a byte array, double memory usage. this necessary? 2. If BlobData stream a ByteBuffer, this method blocking</technical_language>

Target:
void handleBody(InputStream payload) throws IOException, MessageFormatException { if (!successfullyDeserialized) { BlobData blobData = MessageFormatRecord.deserializeBlob(payload); chunkIndexToBuffer.put(chunkIndex, blobData.getStream().getByteBuffer()); numChunksRetrieved++; successfullyDeserialized = true; } else { } }
Source:
<code>void attemptScheduling(FSSchedulerNode node) { try { writeLock.lock(); if (rmContext.isWorkPreservingRecoveryEnabled() && !rmContext .isSchedulerReadyForAllocatingContainers()) { return; } final NodeId nodeID = node.getNodeID(); if (!nodeTracker.exists(nodeID)) { LOG.info( "Skipping scheduling as the node " + nodeID + " has been removed"); return; } <START> for (FSAppAttempt app : node.getPreemptionList()) { <END> if (!app.isStopped()) { app.assignContainer(node); } } boolean validReservation = false; FSAppAttempt reservedAppSchedulable = node.getReservedAppSchedulable(); if (reservedAppSchedulable != null) { validReservation = reservedAppSchedulable.assignReservedContainer(node); } if (!validReservation) { int assignedContainers = 0; Resource assignedResource = Resources.clone(Resources.none()); Resource maxResourcesToAssign = Resources.multiply( node.getUnallocatedResource(), 0.5f); while (node.getReservedContainer() == null) { boolean assignedContainer = false; Resource assignment = queueMgr.getRootQueue().assignContainer(node); if (!assignment.equals(Resources.none())) { assignedContainers++; assignedContainer = true; Resources.addTo(assignedResource, assignment); } if (!assignedContainer) { break; } if (!shouldContinueAssigning(assignedContainers, maxResourcesToAssign, assignedResource)) { break; } } } updateRootQueueMetrics(); } finally { writeLock.unlock(); } }</code><technical_language>handle case app is allocated multiple containers based preempted resources. store apps in a TreeMap in FSSchedulerNode a method returns next preempted app allocate to? If exist, return null? Also, if this work, revert behavior in earlier patch: add app/resources map container is preempted</technical_language>

Target:
void attemptScheduling(FSSchedulerNode node) { try { writeLock.lock(); if (rmContext.isWorkPreservingRecoveryEnabled() && !rmContext .isSchedulerReadyForAllocatingContainers()) { return; } final NodeId nodeID = node.getNodeID(); if (!nodeTracker.exists(nodeID)) { LOG.info( "Skipping scheduling as the node " + nodeID + " has been removed"); return; } assignPreemptedContainers(node); FSAppAttempt reservedAppSchedulable = node.getReservedAppSchedulable(); boolean validReservation = false; if (reservedAppSchedulable != null) { validReservation = reservedAppSchedulable.assignReservedContainer(node); } if (!validReservation) { int assignedContainers = 0; Resource assignedResource = Resources.clone(Resources.none()); Resource maxResourcesToAssign = Resources.multiply( node.getUnallocatedResource(), 0.5f); while (node.getReservedContainer() == null) { boolean assignedContainer = false; Resource assignment = queueMgr.getRootQueue().assignContainer(node); if (!assignment.equals(Resources.none())) { assignedContainers++; assignedContainer = true; Resources.addTo(assignedResource, assignment); } if (!assignedContainer) { break; } if (!shouldContinueAssigning(assignedContainers, maxResourcesToAssign, assignedResource)) { break; } } } updateRootQueueMetrics(); } finally { writeLock.unlock(); } }
Source:
<code>private void shutdown() { if (saveJob != null) { saveJob.cancel(); } if (idleListener == null) { return; } if (display != null && !display.isDisposed()) { try { display.asyncExec(new Runnable() { @Override public void run() { <START> display.timerExec(-1, runnable); <END> display.removeFilter(SWT.KeyUp, idleListener); display.removeFilter(SWT.MouseUp, idleListener); } }); } catch (SWTException ex) { } } }</code><technical_language>useless (If milliseconds is zero, runnable is executed.)</technical_language>

Target:
private void shutdown() { if (saveJob != null) { saveJob.cancel(); } if (idleListener == null) { return; } Display display = getWorkbenchDisplay(); if (display != null && !display.isDisposed()) { try { display.asyncExec(new Runnable() { @Override public void run() { display.removeFilter(SWT.KeyUp, idleListener); display.removeFilter(SWT.MouseUp, idleListener); } }); } catch (SWTException ex) { } } }
Source:
<code>public static Program findProgram(String extension) { Program program = Program.findProgram(extension); if (program == null && <START> isMediaFile(extension)) <END> { Program[] programs = Program.getPrograms(); for (Program prog : programs) { if (prog.getName().equals("PhotoViewer.FileAssoc.Tiff")) { program = prog; break; } } } return program; }</code><technical_language>Code consolidation: want perform toLowerCase() method instead of classes call this findProgram() method. This increases reusability ensures toLowerCase() is called</technical_language>

Target:
public static Program findProgram(String extension) { Program program = Program.findProgram(extension); if (program == null && isMediaFile(extension.toLowerCase())) { Program[] programs = Program.getPrograms(); for (Program prog : programs) { if (prog.getName().equals("PhotoViewer.FileAssoc.Tiff")) { program = prog; break; } } } return program; }
Source:
<code>public void setAngle(float angle) { <START> while (angle < 0) { angle += 360; } while (angle >= 360) { angle -= 360; } <END> this.angle = angle; }</code><technical_language>SolMath#norm Normalizes angle, puts in range (-180, 180]. worth investigating if change bounds that</technical_language>

Target:
public void setAngle(float angle) { this.angle = SolMath.norm(angle); }
Source:
<code>private ExpressionInterpreter(Expression expression, Metadata metadata, Session session, Map<NodeRef<Expression>, Type> expressionTypes, boolean optimize) { this.expression = requireNonNull(expression, "expression is null"); this.metadata = requireNonNull(metadata, "metadata is null"); <START> this.literalInterpreter = new LiteralInterpreter(metadata.getBlockEncodingSerde()); <END> this.session = requireNonNull(session, "session is null").toConnectorSession(); this.expressionTypes = ImmutableMap.copyOf(requireNonNull(expressionTypes, "expressionTypes is null")); verify((expressionTypes.containsKey(NodeRef.of(expression)))); this.optimize = optimize; this.functionInvoker = new FunctionInvoker(metadata.getFunctionRegistry()); this.visitor = new Visitor(); }</code><technical_language>This is kind of weird. "literalInterpreter" object, interpret literals. Especially functionality for LiteralInterpreter is named (com.facebook.presto.sql.planner.LiteralInterpreter#evaluate) remained static. functionality com.facebook.presto.sql.planner.LiteralInterpreter#toExpression moved a separate class</technical_language>

Target:
private ExpressionInterpreter(Expression expression, Metadata metadata, Session session, Map<NodeRef<Expression>, Type> expressionTypes, boolean optimize) { this.expression = requireNonNull(expression, "expression is null"); this.metadata = requireNonNull(metadata, "metadata is null"); this.literalEncoder = new LiteralEncoder(metadata.getBlockEncodingSerde()); this.session = requireNonNull(session, "session is null").toConnectorSession(); this.expressionTypes = ImmutableMap.copyOf(requireNonNull(expressionTypes, "expressionTypes is null")); verify((expressionTypes.containsKey(NodeRef.of(expression)))); this.optimize = optimize; this.functionInvoker = new FunctionInvoker(metadata.getFunctionRegistry()); this.legacyRowFieldOrdinalAccess = isLegacyRowFieldOrdinalAccessEnabled(session); this.visitor = new Visitor(); }
Source:
<code>public Set<Integer> getPorts() { <START> return Optional.of(ImmutableSet.of(ports.get(getNodeType()))) <END> .orElse(ImmutableSet.of()); }</code><technical_language>need optional, ImmutableSet.of(ports.get(getNodeType()) work</technical_language>

Target:
public Set<Integer> getPorts() { return ImmutableSet.of(PORTS.get(getNodeType())); }
Source:
<code>public void testNestedScatterGatherSequenceTest() { PollableChannel replyChannel = new QueueChannel(); this.scatterGatherInSubFlowChannel.send( MessageBuilder.withPayload("sequencetest") .setReplyChannel(replyChannel) .build()); Message<?> receive = replyChannel.receive(10000); assertThat(receive).isNotNull(); <START> assertThat(receive.getPayload()).isEqualTo("sequencetest"); <END> }</code><technical_language>Excuse me, this test sequence is popped properly. other test some difference this one, fails..</technical_language>

Target:
public void testNestedScatterGatherSequenceTest() { PollableChannel replyChannel = new QueueChannel(); this.scatterGatherInSubFlowChannel.send( MessageBuilder.withPayload("sequencetest") .setReplyChannel(replyChannel) .build()); Message<?> wiretapMessage1 = scatterGatherWireTapChannel.receive(10000); assertThat(wiretapMessage1).isNotNull(); MessageHeaders headers1 = wiretapMessage1.getHeaders(); Message<?> wiretapMessage2 = scatterGatherWireTapChannel.receive(10000); assertThat(wiretapMessage2).isNotNull() .extracting(Message::getHeaders) .isEqualToComparingOnlyGivenFields(headers1, IntegrationMessageHeaderAccessor.CORRELATION_ID, "gatherResultChannel", IntegrationMessageHeaderAccessor.SEQUENCE_NUMBER, IntegrationMessageHeaderAccessor.SEQUENCE_SIZE); Message<?> receive = replyChannel.receive(10000); assertThat(receive).isNotNull(); assertThat(receive.getPayload()).isEqualTo("sequencetest"); }
Source:
<code>public List<SshPairImpl> get(String owner, String service) throws ServerException { requireNonNull(owner); requireNonNull(service); try { EntityManager manager = managerProvider.get(); <START> List<SshPairImpl> resultList = manager.createQuery("SELECT pair " + <END> "FROM SshKeyPair pair " + "WHERE pair.owner = :owner " + " AND pair.service = :service", SshPairImpl.class) .setParameter("owner", owner) .setParameter("service", service) .getResultList(); return resultList; } catch (RuntimeException e) { throw new ServerException(e.getLocalizedMessage(), e); } }</code><technical_language>do need result list varialbe</technical_language>

Target:
public List<SshPairImpl> get(String owner, String service) throws ServerException { requireNonNull(owner); requireNonNull(service); try { return managerProvider.get() .createQuery("SELECT pair " + "FROM SshKeyPair pair " + "WHERE pair.owner = :owner " + " AND pair.service = :service", SshPairImpl.class) .setParameter("owner", owner) .setParameter("service", service) .getResultList(); } catch (RuntimeException e) { throw new ServerException(e.getLocalizedMessage(), e); } }
Source:
<code>private TaskFlowJob createJobWithSpelJobModelVariablesUnauthorizedType() throws UserException { TaskFlowJob job = new TaskFlowJob(); job.setVariables(ImmutableMap.of("var1", new JobVariable("var1", "value1", SPEL_LEFT + <START> "T(Runtime).exec('hostname').waitFor() instanceof T(Integer)" + <END> SPEL_RIGHT))); return job; }</code><technical_language>a mistake in this string, I T(java.lang.Runtime).getRuntime().exec( .</technical_language>

Target:
private TaskFlowJob createJobWithSpelJobModelVariablesUnauthorizedType() throws UserException { TaskFlowJob job = new TaskFlowJob(); job.setVariables(ImmutableMap.of("var1", new JobVariable("var1", "value1", SPEL_LEFT + "T(java.lang.Runtime).getRuntime().exec('hostname').waitFor() instanceof T(Integer)" + SPEL_RIGHT))); return job; }
Source:
<code>private String updateNginxHttpConfigScript(final String host) { final String hosts = String.format("%s.hosts.conf", host); return Joiner.on(";").join( String.format( <START> "if [[ $(grep '%1$s' %2$s) != *%1$s* ]]", hosts, this.config <END> ), String.format( "then sed -i.bak -r 's/http \\{/http \\{\\n include %s;/' %s", hosts, this.config ), String.format("rm %s.bak", this.config), "fi" ); }</code><technical_language>*%1$1* in comparison, asterisk other filesystem wildcard in bash</technical_language>

Target:
private String updateNginxHttpConfigScript(final String host) { final String hosts = String.format("%s.hosts.conf", host); return Joiner.on(";").join( String.format( "if ! grep -q '%s' %s", hosts, this.config ), String.format( "then sed -i.bak -r 's/http \\{/http \\{\\n include %s;/' %s", hosts, this.config ), String.format("rm %s.bak", this.config), "fi" ); }
Source:
<code>public void testDisappearedCacheWasNotFoundMessage() { SqlQuery<String, Person> qry = new SqlQuery<String, Person>(Person.class, JoinSqlTestHelper.JOIN_SQL).setArgs("Organization #0"); qry.setDistributedJoins(true); try { personCache.query(qry).getAll(); fail("No CacheException emitted."); } catch (CacheException e) { <START> boolean exp = e.getMessage().contains("Cache not found on local node"); <END> if (!exp) throw e; } }</code><technical_language>This work if exception is thrown</technical_language>

Target:
public void testDisappearedCacheWasNotFoundMessage() { SqlQuery<String, Person> qry = new SqlQuery<String, Person>(Person.class, JoinSqlTestHelper.JOIN_SQL).setArgs("Organization #0"); qry.setDistributedJoins(true); try { personCache.query(qry).getAll(); fail("No CacheException emitted."); } catch (CacheException e) { boolean exp = e.getMessage().contains("Cache not found on local node (was concurrently destroyed?)"); if (!exp) throw e; } }
Source:
<code>public Rotation getRotation() { switch (rot) { case 0: return Rotation.NONE; <START> case 1: <END> return Rotation.NONE; case 2: return Rotation.CLOCKWISE; case 3: return Rotation.CLOCKWISE; case 4: return Rotation.FLIPPED; case 5: return Rotation.FLIPPED; case 6: return Rotation.COUNTER_CLOCKWISE; case 7: return Rotation.COUNTER_CLOCKWISE; } return Rotation.NONE; }</code><technical_language>This switch reduced follows: java case 0: case 1: return Rotation.NONE; case 2: case 3: return Rotation.CLOCKWISE; // ..</technical_language>

Target:
public Rotation getRotation() { switch (rot) { case 0: case 1: return Rotation.NONE; case 2: case 3: return Rotation.CLOCKWISE; case 4: case 5: return Rotation.FLIPPED; case 6: case 7: return Rotation.COUNTER_CLOCKWISE; } return Rotation.NONE; }
Source:
<code>protected ColumnInfo copy(boolean immutable) { <START> return this; <END> }</code><technical_language>This a bit worrying</technical_language>

Target:
protected ColumnInfo copy(boolean immutable) { throw new UnsupportedOperationException("DynamicColumnIndices cannot be copied"); }
Source:
<code>public void patchMultipleOperationsWithSuccess() throws Exception { context.turnOffAuthorisationSystem(); EPerson ePerson = EPersonBuilder.createEPerson(context) .withNameInMetadata("John", "Doe") .withEmail("Johndoe@fake-email.com") .withNetId("testId") .build(); String token = getAuthToken(admin.getEmail(), password); List<Operation> ops = new ArrayList<Operation>(); <START> ReplaceOperation replaceOperation1 = new ReplaceOperation("/canLogin", "true"); <END> ops.add(replaceOperation1); ReplaceOperation replaceOperation2 = new ReplaceOperation("/netid", "multitestId"); ops.add(replaceOperation2); ReplaceOperation replaceOperation3 = new ReplaceOperation("/certificate", "true"); ops.add(replaceOperation3); String patchBody = getPatchContent(ops); getClient(token).perform(patch("/api/eperson/epersons/" + ePerson.getID()) .content(patchBody) .contentType(MediaType.APPLICATION_JSON_PATCH_JSON)) .andExpect(status().isOk()) .andExpect(jsonPath("$.canLogIn", Matchers.is(true))) .andExpect(jsonPath("$.netid", Matchers.is("multitestId"))) .andExpect(jsonPath("$.requireCertificate", Matchers.is(true))); }</code><technical_language>official true instead "true"</technical_language>

Target:
public void patchMultipleOperationsWithSuccess() throws Exception { context.turnOffAuthorisationSystem(); EPerson ePerson = EPersonBuilder.createEPerson(context) .withNameInMetadata("John", "Doe") .withEmail("Johndoe@fake-email.com") .withNetId("testId") .build(); String token = getAuthToken(admin.getEmail(), password); List<Operation> ops = new ArrayList<Operation>(); ReplaceOperation replaceOperation1 = new ReplaceOperation("/canLogin", true); ops.add(replaceOperation1); ReplaceOperation replaceOperation2 = new ReplaceOperation("/netid", "multitestId"); ops.add(replaceOperation2); ReplaceOperation replaceOperation3 = new ReplaceOperation("/certificate", true); ops.add(replaceOperation3); String patchBody = getPatchContent(ops); getClient(token).perform(patch("/api/eperson/epersons/" + ePerson.getID()) .content(patchBody) .contentType(MediaType.APPLICATION_JSON_PATCH_JSON)) .andExpect(status().isOk()) .andExpect(jsonPath("$.canLogIn", Matchers.is(true))) .andExpect(jsonPath("$.netid", Matchers.is("multitestId"))) .andExpect(jsonPath("$.requireCertificate", Matchers.is(true))); }
Source:
<code>public CassandraIsolatedClassLoader() { <START> super( new Versions.Version(FBUtilities.getReleaseVersionString(), Versions.getClassPath()).classpath); <END> }</code><technical_language>remove this dependency... I force in this JIRA though, if want tackle file another JIRA</technical_language>

Target:
public CassandraIsolatedClassLoader() { super(AbstractCluster.CURRENT_VERSION.classpath); }
Source:
<code><START> runTaskTest(Callable<Task<?>> callable) { <END> try { Task<?> task = callable.call(); task.waitForCompletion(); if (task.isFaulted()) { Exception error = task.getError(); if (error instanceof RuntimeException) { throw (RuntimeException) error; } throw new RuntimeException(error); } else if (task.isCancelled()) { throw new RuntimeException(new CancellationException()); } } catch (Exception e) { throw new RuntimeException(e); } }</code><technical_language>this change</technical_language>

Target:
private void runTaskTest(Callable<Task<?>> callable) { try { Task<?> task = callable.call(); task.waitForCompletion(); if (task.isFaulted()) { Exception error = task.getError(); if (error instanceof RuntimeException) { throw (RuntimeException) error; } throw new RuntimeException(error); } else if (task.isCancelled()) { throw new RuntimeException(new CancellationException()); } } catch (Exception e) { throw new RuntimeException(e); } }
Source:
<code>public void build() { final List<BaseColumn> expandedColumns = dtable.getExpandedColumns(); <START> for (; sourceColumnIndex < expandedColumns.size(); sourceColumnIndex++) { <END> final BaseColumn baseColumn = expandedColumns.get(sourceColumnIndex); if (baseColumn instanceof AttributeCol52) { makeAttribute((AttributeCol52) baseColumn); } else if (baseColumn instanceof MetadataCol52) { makeMetadata((MetadataCol52) baseColumn); } else if (baseColumn instanceof ConditionCol52) { makeCondition((ConditionCol52) baseColumn); } else if (baseColumn instanceof ActionCol52) { makeAction(baseColumn); } else if (baseColumn instanceof RowNumberCol52) { continue; } else if (baseColumn instanceof DescriptionCol52) { } else { throw new IllegalArgumentException("TODO REMOTE THIS"); } columnIndex++; } }</code><technical_language>I reading class I do need sourceColumnIndex class variable. I scope in for loop. I usage of sourceColumnIndex replaced columnIndex</technical_language>

Target:
public void build() { final List<BaseColumn> expandedColumns = dtable.getExpandedColumns(); for (int sourceColumnIndex = 0; sourceColumnIndex < expandedColumns.size(); sourceColumnIndex++) { final BaseColumn baseColumn = expandedColumns.get(sourceColumnIndex); if (baseColumn instanceof AttributeCol52) { makeAttribute((AttributeCol52) baseColumn); } else if (baseColumn instanceof MetadataCol52) { makeMetadata((MetadataCol52) baseColumn); } else if (baseColumn instanceof ConditionCol52) { makeCondition((ConditionCol52) baseColumn); } else if (baseColumn instanceof ActionCol52) { makeAction(sourceColumnIndex, baseColumn); } else if (baseColumn instanceof RowNumberCol52) { continue; } else if (baseColumn instanceof DescriptionCol52) { } else { throw new IllegalArgumentException("TODO REMOTE THIS"); } targetColumnIndex++; } }
Source:
<code><START> public ResponseEntity<ContentTypeDto> create( <END> @Valid @RequestBody ContentTypeDtoRequest contentType, BindingResult bindingResult) throws URISyntaxException { validator.validate(contentType, bindingResult); if(bindingResult.hasErrors()) { throw new ValidationGenericException(bindingResult); } ContentTypeDto result = service.create(contentType, bindingResult); return ResponseEntity.created( new URI("/plugins/contentTypes/" + result.getCode())) .body(result); }</code><technical_language>I API in format {payload:{}, metadata: {}, errors:[]}, in this case method return type ResponseEntity<SimpleRestResponse<ContentTypeDto>>, please check this @joewhite101</technical_language>

Target:
public ResponseEntity<SimpleRestResponse<ContentTypeDto>> create( @Valid @RequestBody ContentTypeDtoRequest contentType, BindingResult bindingResult) throws URISyntaxException { logger.debug("REST request - create content type: {}", contentType); validateCreate(contentType, bindingResult); ContentTypeDto result = service.create(contentType, bindingResult); return ResponseEntity.created( new URI("/plugins/contentTypes/" + result.getCode())) .body(new SimpleRestResponse<>(result)); }
Source:
<code><START> public BinarySourceBuilder fromAsFile(String asFile) { <END> this.asFile = asFile; return this; }</code><technical_language>return interfac IBinarySourceBuilder instead of concrete class here</technical_language>

Target:
public IBinarySourceBuilder fromAsFile(String asFile) { this.asFile = asFile; return this; }
Source:
<code>public Object create(SimpleObject propertiesToCreate, RequestContext context) throws ResponseException { DelegatingResourceHandler<? extends T> handler; if (hasTypesDefined()) { String type = (String) propertiesToCreate.remove(RestConstants.PROPERTY_FOR_TYPE); if (type == null) throw new IllegalArgumentException( "When creating a resource that supports subclasses, you must indicate the particular subclass with a " + RestConstants.PROPERTY_FOR_TYPE + " property"); handler = getResourceHandler(type); } else { handler = this; } T delegate = handler.newDelegate(); setConvertedProperties(delegate, propertiesToCreate, handler.getCreatableProperties(), true); try { <START> ValidateUtil.validate(delegate); <END> } catch (ValidationException ex) { context.getResponse().setStatus(HttpStatus.BAD_REQUEST.value()); return getValidationErrors(ex); } delegate = save(delegate); SimpleObject ret = (SimpleObject) ConversionUtil.convertToRepresentation(delegate, Representation.DEFAULT); if (hasTypesDefined()) { ret.add(RestConstants.PROPERTY_FOR_TYPE, getTypeName(delegate)); } return ret; }</code><technical_language>I save(delegate) invokes validator, need invoke twice</technical_language>

Target:
public Object create(SimpleObject propertiesToCreate, RequestContext context) throws ResponseException { DelegatingResourceHandler<? extends T> handler; if (hasTypesDefined()) { String type = (String) propertiesToCreate.remove(RestConstants.PROPERTY_FOR_TYPE); if (type == null) throw new IllegalArgumentException( "When creating a resource that supports subclasses, you must indicate the particular subclass with a " + RestConstants.PROPERTY_FOR_TYPE + " property"); handler = getResourceHandler(type); } else { handler = this; } T delegate = handler.newDelegate(propertiesToCreate); setConvertedProperties(delegate, propertiesToCreate, handler.getCreatableProperties(), true); ValidateUtil.validate(delegate); delegate = save(delegate); SimpleObject ret = (SimpleObject) ConversionUtil.convertToRepresentation(delegate, Representation.DEFAULT); if (hasTypesDefined()) { ret.add(RestConstants.PROPERTY_FOR_TYPE, getTypeName(delegate)); } return ret; }
Source:
<code>public void beforeDestroy(BeforeDestroyEvent event, EntityRef player, CharacterComponent characterComponent, AliveCharacterComponent aliveCharacterComponent) { if (player.hasComponent(PlayerCharacterComponent.class)) { event.consume(); String team = player.getComponent(LASTeamComponent.class).team; Prefab staffPrefab = assetManager.getAsset(LASUtils.MAGIC_STAFF_URI, Prefab.class).orElse(null); Vector3f startPosition = new Vector3f(player.getComponent(LocationComponent.class).getLocalPosition()); <START> Vector3f impulse = Vector3f.zero(); <END> int inventorySize = inventoryManager.getNumSlots(player); for (int slotNumber = 0; slotNumber <= inventorySize; slotNumber++) { EntityRef slot = inventoryManager.getItemInSlot(player, slotNumber); Prefab currentPrefab = slot.getParentPrefab(); if (currentPrefab != null && !currentPrefab.equals(staffPrefab)) { int count = inventoryManager.getStackSize(slot); player.send(new DropItemRequest(slot, player, impulse, startPosition, count)); } } player.send(new DoHealEvent(100000, player)); player.send(new CharacterTeleportEvent(LASUtils.getTeleportDestination(team))); } }</code><technical_language>out of curiosity, happen if impulse 0</technical_language>

Target:
public void beforeDestroy(BeforeDestroyEvent event, EntityRef player, CharacterComponent characterComponent, AliveCharacterComponent aliveCharacterComponent) { if (player.hasComponent(PlayerCharacterComponent.class)) { event.consume(); String team = player.getComponent(LASTeamComponent.class).team; dropItemsFromInventory(player); player.send(new DoHealEvent(100000, player)); player.send(new CharacterTeleportEvent(LASUtils.getTeleportDestination(team))); } }
Source:
<code>public void testUpdateTrackersAfterRedimineUpdate() throws RedmineException { List<Tracker> availableTrackers=mgr.getIssueManager().getTrackers(); assertTrue("a minumum of 3 trackers should be configured in redmine", availableTrackers.size()>=3); Project projectToCreate = generateRandomProject(); String createdProjectKey = null; try { projectToCreate.clearTrackers(); Project createdProject = projectManager.createProject(projectToCreate); createdProjectKey = createdProject.getIdentifier(); assertEquals(0, createdProject.getTrackers().size()); Collection<Tracker> trackers=new HashSet<Tracker>(Arrays.asList(availableTrackers.get(0))); createdProject.addTrackers(trackers); <START> projectManager.update(createdProject); <END> createdProject=projectManager.getProjectByKey(createdProjectKey); assertEquals(1, createdProject.getTrackers().size()); trackers=new HashSet<Tracker>(Arrays.asList(availableTrackers.get(1), availableTrackers.get(2))); createdProject.addTrackers(trackers); projectManager.update(createdProject); createdProject=projectManager.getProjectByKey(createdProjectKey); assertEquals(3, createdProject.getTrackers().size()); createdProject.clearTrackers(); projectManager.update(createdProject); createdProject=projectManager.getProjectByKey(createdProjectKey); assertEquals(0, createdProject.getTrackers().size()); } finally { if (createdProjectKey != null) { projectManager.deleteProject(createdProjectKey); } } }</code><technical_language>reuse vars defined. separate variables for readability instead</technical_language>

Target:
public void testUpdateTrackersAfterRedimineUpdate() throws RedmineException { List<Tracker> availableTrackers=mgr.getIssueManager().getTrackers(); assertTrue("a minumum of 3 trackers should be configured in redmine", availableTrackers.size()>=3); Project projectToCreate = generateRandomProject(); String createdProjectKey = null; try { Project createdProject = projectToCreate.clearTrackers().create(); createdProjectKey = createdProject.getIdentifier(); assertEquals(0, createdProject.getTrackers().size()); Collection<Tracker> trackersToSet=new HashSet<Tracker>(Arrays.asList(availableTrackers.get(0))); createdProject.addTrackers(trackersToSet).update(); createdProject=projectManager.getProjectByKey(createdProjectKey); assertEquals(1, createdProject.getTrackers().size()); Collection<Tracker> trackersToAdd=new HashSet<Tracker>(Arrays.asList(availableTrackers.get(1), availableTrackers.get(2))); createdProject.addTrackers(trackersToAdd).update(); createdProject=projectManager.getProjectByKey(createdProjectKey); assertEquals(3, createdProject.getTrackers().size()); createdProject.clearTrackers().update(); createdProject=projectManager.getProjectByKey(createdProjectKey); assertEquals(0, createdProject.getTrackers().size()); } finally { if (createdProjectKey != null) { projectManager.getProjectByKey(createdProjectKey).delete(); } } }
Source:
<code>public void setEvent(final String name, final String value) { if (!TextUtils.isEmpty(name)) { mEventList.add(Pair.create(name, value)); <START> } <END> }</code><technical_language>I throw exception if calls setEvent give empty event name. #Pending</technical_language>

Target:
public void setEvent(final String name, final String value) { if (TextUtils.isEmpty(name)) { throw new IllegalArgumentException("Telemetry setEvent on null name"); } if (value == null) { return; } mEventList.add(Pair.create(name, value)); }
Source:
<code>@NonNull public String dateTime() { if (dateTimeOriginal == null || dateTimeOriginal.value() == null) { <START> return ""; <END> } return dateTimeOriginal.value(); }</code><technical_language>reason change logic display empty string</technical_language>

Target:
@NonNull public String dateTime() { return StringUtils.defaultString(dateTimeOriginal == null ? null : dateTimeOriginal.value()); }
Source:
<code>public void getMarkupLanguagesNull() { MarkupLanguageProvider provider = new MarkupLanguageProvider() { @Override protected Set<MarkupLanguage> loadMarkupLanguages() { return null; } }; <START> thrown.expect(NullPointerException.class); <END> provider.getMarkupLanguages(); }</code><technical_language>Assert proper error message this hit implemenator default class generation</technical_language>

Target:
public void getMarkupLanguagesNull() { MarkupLanguageProvider provider = new MarkupLanguageProvider() { @Override protected Set<MarkupLanguage> loadMarkupLanguages() { return null; } }; thrown.expect(NullPointerException.class); thrown.expectMessage("loadMarkupLanguages() must not return null"); provider.getMarkupLanguages(); }