auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void computeOverlaps() { SortedSet<RectangleNode> intersectingNodes = Sets.newTreeSet( RectangleStripOverlapRemover::compareRightRectangleBorders); <START> double scanlinePos = Double.MIN_VALUE; <END> for (RectangleNode currNode : rectangleNodes) { scanlinePos = currNode.rectangle.x; while (!intersectingNodes.isEmpty()) { RectangleNode intersectingRectangle = intersectingNodes.first(); if (intersectingRectangle.rectangle.x + intersectingRectangle.rectangle.width < scanlinePos) { intersectingNodes.remove(intersectingRectangle); } else { break; } } for (RectangleNode intersectingNode : intersectingNodes) { intersectingNode.overlappingNodes.add(currNode); currNode.overlappingNodes.add(intersectingNode); } intersectingNodes.add(currNode); } }</code><technical_language>want NEGATIVE_INFINITY</technical_language>

Target:
private void computeOverlaps() { SortedSet<RectangleNode> intersectingNodes = Sets.newTreeSet( RectangleStripOverlapRemover::compareRightRectangleBorders); double scanlinePos = Double.NEGATIVE_INFINITY; for (RectangleNode currNode : rectangleNodes) { scanlinePos = currNode.rectangle.x; while (!intersectingNodes.isEmpty()) { RectangleNode intersectingRectangle = intersectingNodes.first(); if (intersectingRectangle.rectangle.x + intersectingRectangle.rectangle.width < scanlinePos) { intersectingNodes.remove(intersectingRectangle); } else { break; } } for (RectangleNode intersectingNode : intersectingNodes) { intersectingNode.overlappingNodes.add(currNode); currNode.overlappingNodes.add(intersectingNode); } intersectingNodes.add(currNode); } }
Source:
<code>public ConfigurableColumnTableViewerSupport(TableViewer viewer, TableColumnDescriptor[] columnDescriptors, File stateFile) { super(viewer, stateFile); this.table = viewer.getTable(); this.columnDescriptors = columnDescriptors; this.viewer = viewer; <START> initializeViewerSupport(); <END> createConfigureColumnsAction(getHeaderMenu()); }</code><technical_language>this called superconstructor</technical_language>

Target:
public ConfigurableColumnTableViewerSupport(TableViewer viewer, TableColumnDescriptor[] columnDescriptors, File stateFile) { super(viewer, stateFile); this.columnDescriptors = columnDescriptors; this.viewer = viewer; createConfigureColumnsAction(getHeaderMenu()); }
Source:
<code>static SwapBlockListResult swapBlocks(FSDirectory fsd, FSPermissionChecker pc, String src, String dst, long genTimestamp) throws IOException { final INodesInPath srcIIP = fsd.resolvePath(pc, src, DirOp.WRITE); final INodesInPath dstIIP = fsd.resolvePath(pc, dst, DirOp.WRITE); if (fsd.isPermissionEnabled()) { fsd.checkAncestorAccess(pc, srcIIP, FsAction.WRITE); fsd.checkAncestorAccess(pc, dstIIP, FsAction.WRITE); } if (NameNode.stateChangeLog.isDebugEnabled()) { NameNode.stateChangeLog.debug("DIR* FSDirectory.swapBlockList: " + srcIIP.getPath() + " and " + dstIIP.getPath()); } <START> SwapBlockListResult result = null; <END> fsd.writeLock(); try { result = swapBlockList(fsd, srcIIP, dstIIP, genTimestamp); } finally { fsd.writeUnlock(); } return result; }</code><technical_language>nit. IDE complains null assignment is redundant. need assign null, is null</technical_language>

Target:
static SwapBlockListResult swapBlocks(FSDirectory fsd, FSPermissionChecker pc, String src, String dst, long genTimestamp) throws IOException { final INodesInPath srcIIP = fsd.resolvePath(pc, src, DirOp.WRITE); final INodesInPath dstIIP = fsd.resolvePath(pc, dst, DirOp.WRITE); if (fsd.isPermissionEnabled()) { fsd.checkAncestorAccess(pc, srcIIP, FsAction.WRITE); fsd.checkAncestorAccess(pc, dstIIP, FsAction.WRITE); } if (NameNode.stateChangeLog.isDebugEnabled()) { NameNode.stateChangeLog.debug("DIR* FSDirectory.swapBlockList: " + srcIIP.getPath() + " and " + dstIIP.getPath()); } SwapBlockListResult result; fsd.writeLock(); try { result = swapBlockList(fsd, srcIIP, dstIIP, genTimestamp); } finally { fsd.writeUnlock(); } return result; }
Source:
<code><START> private static Filter flatten(Filter root) { <END> if (root instanceof BooleanFilter) { List<Filter> children = ((BooleanFilter)root).getFilters(); for (int i = 0; i < children.size(); ++i) { Filter child = flatten(children.get(i)); if (child.getClass() == root.getClass() && !(child instanceof NotFilter)) { boolean first = true; List<Filter> grandKids = ((BooleanFilter)child).getFilters(); for (Filter grandkid : grandKids) { if (first) { first = false; children.set(i, grandkid); } else { children.add(++i, grandkid); } } } else { children.set(i, child); } } if (children.size() == 1 && (root instanceof AndFilter || root instanceof OrFilter)) { return children.get(0); } } return root; }</code><technical_language>Is this Hive</technical_language>

Target:
private static Filter flatten(Filter root) { if (root instanceof BooleanFilter) { List<Filter> children = new ArrayList<>(); children.addAll(((BooleanFilter) root).getFilters()); for (int i = 0; i < children.size(); ++i) { Filter child = flatten(children.get(i)); if (child.getClass() == root.getClass() && !(child instanceof NotFilter)) { boolean first = true; List<Filter> grandKids = ((BooleanFilter)child).getFilters(); for (Filter grandkid : grandKids) { if (first) { first = false; children.set(i, grandkid); } else { children.add(++i, grandkid); } } } else { children.set(i, child); } } if (children.size() == 1 && (root instanceof AndFilter || root instanceof OrFilter)) { return children.get(0); } if (root instanceof AndFilter) { return new AndFilter(children); } else if (root instanceof OrFilter) { return new OrFilter(children); } } return root; }
Source:
<code>default List<T> toList() { final List<T> list = new ArrayList<>(); while (hasNext()) list.add(next()); <START> return list; <END> }</code><technical_language>this close iterator returning list</technical_language>

Target:
default List<T> toList() { final List<T> list = new ArrayList<>(); while (hasNext()) list.add(next()); close(); return list; }
Source:
<code>public TicketTransferToken setupForTransfer(Long ticketId, String goalUserName){ User u = userService.getUserByUsername(goalUserName).orElseThrow(() -> new UsernameNotFoundException("User " + goalUserName + " not found.")); Ticket t = ticketRepository.findOne(ticketId); <START> if (tttRepository.findByTicketId(ticketId).isPresent()) { <END> throw new IllegalStateException("Ticket " + ticketId + " is already set up for transfer!"); } else { TicketTransferToken ttt = new TicketTransferToken(u, t); tttRepository.save(ttt); try { String acceptUrl = acceptTransferUrl + "/?token=" + ttt.getToken(); mailService.sendTicketTransferMail(ttt.getTicket().getOwner(), ttt.getUser(), acceptUrl); } catch (MessagingException e) { e.printStackTrace(); } return ttt; } }</code><technical_language>Damn, I currently tttRepository query for token. multiple. This fixed. this currently checks presence of a token, if valid</technical_language>

Target:
public TicketTransferToken setupForTransfer(Long ticketId, String goalUserName){ User u = userService.getUserByUsername(goalUserName).orElseThrow(() -> new UsernameNotFoundException("User " + goalUserName + " not found.")); Ticket t = ticketRepository.findOne(ticketId); List<TicketTransferToken> ticketTransferTokens = tttRepository.findAllByTicketId(ticketId).stream() .filter(Token::isValid) .collect(Collectors.toList()); if (!ticketTransferTokens.isEmpty()) { throw new DuplicateTicketTransferTokenException(ticketId); } else { TicketTransferToken ttt = new TicketTransferToken(u, t); tttRepository.save(ttt); try { String acceptUrl = acceptTransferUrl + "/?token=" + ttt.getToken(); mailService.sendTicketTransferMail(ttt.getTicket().getOwner(), ttt.getUser(), acceptUrl); } catch (MessagingException e) { e.printStackTrace(); } return ttt; } }
Source:
<code>public void testDuplicateKeys() throws FileNotFoundException { String baseDir = System.getProperty("basedir"); assumeNotNull(baseDir); String fileName = "AppErrors.properties"; final File dir = new File(baseDir, "src/main/resources/bundles"); <START> File file = new File(dir, fileName); <END> DuplicateKeysCheck.assertNoDuplicateKeys(file.getAbsolutePath()); }</code><technical_language>IMO is self-explained: Path path = Paths.get(baseDir, "/src/main/resources/bundles/", "AppErrors.properties"); DuplicateKeysCheck.assertNoDuplicateKeys(path.toString()); join path file name: Path path = Paths.get(baseDir, "/src/main/resources/bundles/AppErrors.properties");</technical_language>

Target:
public void testDuplicateKeys() throws FileNotFoundException { String baseDir = System.getProperty("basedir"); assumeNotNull(baseDir); final File file = new File(baseDir, "src/main/resources/bundles/AppErrors.properties"); DuplicateKeysCheck.assertNoDuplicateKeys(file.getAbsolutePath()); }
Source:
<code>public Dialog onCreateDialog(Bundle savedInstanceState) { if (underlyingDialog == null) { <START> return super.onCreateDialog(savedInstanceState); <END> } return underlyingDialog.getDialog(); }</code><technical_language>this right do here</technical_language>

Target:
public Dialog onCreateDialog(Bundle savedInstanceState) { if (underlyingDialog == null) { dismiss(); return super.onCreateDialog(savedInstanceState); } return underlyingDialog.getDialog(); }
Source:
<code>protected final void fireErrors(String fileName) { final SortedSet<LocalizedMessage> errors = messageCollector .getMessages(); messageCollector.reset(); <START> getMessageDispatcher().fireErrors(fileName, new FileProcessingResult(null, errors)); <END> }</code><technical_language>need pass null constructor parameter means this is a problem in design. Please, create more constructor receives parameter sets fileText null. constructor reused in FileProcessingResult itself</technical_language>

Target:
protected final void fireErrors(String fileName) { final SortedSet<LocalizedMessage> errors = new TreeSet<>(messageCollector); messageCollector.clear(); getMessageDispatcher().fireErrors(new FileProcessingResult(fileName, null, errors)); }
Source:
<code>public void recordTimings(long totalUnaccountedCpuNanos, long totalUnaccountedUserNanos, long totalUnaccountedCpuWallNanos) { if (cpuUnaccountedWallNanos > 0) { <START> operationTiming.recordEstimatedCpuTime(cpuMeasuredNanos + totalUnaccountedCpuNanos * (totalUnaccountedCpuWallNanos / cpuUnaccountedWallNanos)); <END> operationTiming.recordEstimatedUserTime(userMeasuredNanos + totalUnaccountedUserNanos * (totalUnaccountedCpuWallNanos / cpuUnaccountedWallNanos)); } else { operationTiming.recordEstimatedCpuTime(cpuMeasuredNanos); operationTiming.recordEstimatedUserTime(userMeasuredNanos); } }</code><technical_language>formula next totalUnaccountedCpuNanos * currentOperatorUnaccountedFraction, currentOperatorUnaccountedFraction = cpuUnaccountedWallNanos / (double) totalUnaccountedCpuWallNanos</technical_language>

Target:
public void recordTimings(long totalUnaccountedCpuNanos, long totalUnaccountedUserNanos, long totalUnaccountedCpuWallNanos) { if (cpuUnaccountedWallNanos > 0) { double unaccountedCpuFraction = cpuUnaccountedWallNanos / (double) totalUnaccountedCpuWallNanos; operationTiming.recordEstimatedCpuTime((long) (cpuMeasuredNanos + totalUnaccountedCpuNanos * unaccountedCpuFraction)); operationTiming.recordEstimatedUserTime((long) (userMeasuredNanos + totalUnaccountedUserNanos * unaccountedCpuFraction)); } else { operationTiming.recordEstimatedCpuTime(cpuMeasuredNanos); operationTiming.recordEstimatedUserTime(userMeasuredNanos); } }
Source:
<code>public void testFetchSize() throws SQLException { assumeCallableStatementsSupported(); CallableStatement call = con.prepareCall("{ ? = call testspg__getRefcursor () }"); call.registerOutParameter(1, cursorType); call.setFetchSize(2); call.execute(); ResultSet rs = (ResultSet) call.getObject(1); assertTrue(rs.next()); assertTrue(rs.getInt(1) == 1); <START> <END> assertTrue(rs.next()); assertTrue(rs.getInt(1) == 2); assertTrue(rs.next()); assertTrue(rs.getInt(1) == 3); assertTrue(rs.next()); assertTrue(rs.getInt(1) == 4); assertTrue(rs.next()); assertTrue(rs.getInt(1) == 6); assertTrue(rs.next()); assertTrue(rs.getInt(1) == 9); assertTrue(!rs.next()); rs.close(); call.close(); }</code><technical_language>Please assertEquals(a, b) assertEquals(String, a, b)</technical_language>

Target:
public void testFetchSize() throws SQLException { checkAndRunResult(3); }
Source:
<code>private void setTarget(int x, int y, int z) { this.targetX = x; this.targetY = y; this.targetZ = z; Block b = worldObj.getBlock(x, y - 1, z); this.nextDigRequiredEnergy = DIG_BASE_REQUIRED_ENERGY + <START> (b.getBlockHardness(null, 0, 0, 0) * DIG_HARDNESS_ENERGY_MULTIPLIER); <END> }</code><technical_language>Terrible idea. Pass in proper parameters, them</technical_language>

Target:
private void setTarget(int x, int y, int z) { this.targetX = x; this.targetY = y; this.targetZ = z; Block b = worldObj.getBlock(x, y - 1, z); this.nextDigRequiredEnergy = DIG_BASE_REQUIRED_ENERGY + (b.getBlockHardness(worldObj, x, y - 1, z) * DIG_HARDNESS_ENERGY_MULTIPLIER); }
Source:
<code>public YarnContainerHeartbeatServlet(YarnAppState yarnAppState, ReadableMetricsRegistry registry) { this.yarnAppState = yarnAppState; this.jsonResponse = new JSONObject(); <START> this.heartbeatInvalidCount = registry.newCounter(GROUP, "heartbeats-invalid"); <END> }</code><technical_language>**nit**: s/heartbeatInvalidCount/heartbeatsInvalidCount/</technical_language>

Target:
public YarnContainerHeartbeatServlet(YarnAppState yarnAppState, ReadableMetricsRegistry registry) { this.yarnAppState = yarnAppState; this.mapper = new ObjectMapper(); this.heartbeatsExpiredCount = registry.newCounter(GROUP, "heartbeats-expired"); }
Source:
<code>protected <T> T wrapRead(Read<T> op) throws MessagingException { <START> ReentrantReadWriteLock.ReadLock lock = this.lock.readLock(); <END> lock.lock(); try { Preconditions.checkState(referenceCount > 0, "Attempt to read a disposed message"); return op.read(wrapped); } finally { lock.unlock(); } }</code><technical_language>idem readLock</technical_language>

Target:
private <T> T wrapRead(Read<T> op) throws MessagingException { ReentrantReadWriteLock.ReadLock readLock = lock.readLock(); readLock.lock(); try { Preconditions.checkState(referenceCount > 0, "Attempt to read a disposed message"); return op.read(wrapped); } finally { readLock.unlock(); } }
Source:
<code>public String getvm_host() { if (!StringHelper.isNullOrEmpty(this.getvm_ip())) { this.mVmDynamic.setvm_host(getvm_ip()); } else if (!StringHelper.isNullOrEmpty(getvm_domain())) { if (StringHelper.isNullOrEmpty(this.mVmDynamic.getvm_host()) <START> || !this.mVmDynamic.getvm_host().contains(getvm_domain())) { <END> this.mVmDynamic.setvm_host(getvm_name() + "." + getvm_domain()); } } if (StringHelper.isNullOrEmpty(this.mVmDynamic.getvm_host())) { this.mVmDynamic.setvm_host(getvm_name()); } return this.mVmDynamic.getvm_host(); }</code><technical_language>1. need differentiate: - this.mVmDynamic.getvm_host() is empty, vm_host set vm_name + "." + vm_domain - this.mVmDynamic.getvm_host() is empty, vm_host set vm_host + "." + vm_domain. In this patch (in this part), setting vm_host vm_name + "." + vm_domain 2. I replace ".contains" ".endsWith" (if is that)</technical_language>

Target:
public String getvm_host() { if (!StringHelper.isNullOrEmpty(this.getvm_ip())) { this.mVmDynamic.setvm_host(getvm_ip()); } else if (!StringHelper.isNullOrEmpty(getvm_domain())) { if (StringHelper.isNullOrEmpty(this.mVmDynamic.getvm_host()) || !this.mVmDynamic.getvm_host().endsWith(getvm_domain())) { this.mVmDynamic.setvm_host(getvm_host() + "." + getvm_domain()); } } if (StringHelper.isNullOrEmpty(this.mVmDynamic.getvm_host())) { this.mVmDynamic.setvm_host(getvm_name()); } return this.mVmDynamic.getvm_host(); }
Source:
<code>private void addHosts(final MultipleHostsModel hostsModel) { hostsModel.startProgress(null); ArrayList<VdcActionParametersBase> parametersList = new ArrayList<VdcActionParametersBase>(); for (Object object : hostsModel.getHosts().getItems()) { HostDetailModel hostDetailModel = (HostDetailModel) ((EntityModel) object).getEntity(); VDS host = new VDS(); host.setVdsName(hostDetailModel.getName()); host.setHostName(hostDetailModel.getAddress()); host.setSshKeyFingerprint(hostDetailModel.getFingerprint()); host.setPort(54321); <START> host.setVdsGroupId(hostsModel.getClusterModel().getClusterId()); <END> host.setpm_enabled(false); AddVdsActionParameters parameters = new AddVdsActionParameters(); parameters.setVdsId(host.getId()); parameters.setvds(host); parameters.setRootPassword(hostDetailModel.getPassword()); parameters.setOverrideFirewall(false); parameters.setRebootAfterInstallation(hostsModel.getClusterModel().getEnableOvirtService().getIsSelected()); parametersList.add(parameters); } Frontend.RunMultipleAction(VdcActionType.AddVds, parametersList, true, new IFrontendMultipleActionAsyncCallback() { @Override public void executed(FrontendMultipleActionAsyncResult result) { hostsModel.stopProgress(); boolean isAllCanDoPassed = true; for (VdcReturnValueBase returnValueBase : result.getReturnValue()) { isAllCanDoPassed = isAllCanDoPassed && returnValueBase.getCanDoAction(); if (!isAllCanDoPassed) { break; } } if (isAllCanDoPassed) { cancel(); } } }, null); }</code><technical_language>this change is part of this patch</technical_language>

Target:
private void addHosts(final MultipleHostsModel hostsModel) { hostsModel.startProgress(null); ArrayList<VdcActionParametersBase> parametersList = new ArrayList<VdcActionParametersBase>(); for (Object object : hostsModel.getHosts().getItems()) { HostDetailModel hostDetailModel = (HostDetailModel) ((EntityModel) object).getEntity(); VDS host = new VDS(); host.setVdsName(hostDetailModel.getName()); host.setHostName(hostDetailModel.getAddress()); host.setSSHKeyFingerprint(hostDetailModel.getFingerprint()); host.setPort(54321); host.setVdsGroupId((Guid) hostsModel.getClusterModel().getClusterId()); host.setpm_enabled(false); AddVdsActionParameters parameters = new AddVdsActionParameters(); parameters.setVdsId(host.getId()); parameters.setvds(host); parameters.setRootPassword(hostDetailModel.getPassword()); parameters.setOverrideFirewall(false); parameters.setRebootAfterInstallation(hostsModel.getClusterModel().getEnableOvirtService().getIsSelected()); parametersList.add(parameters); } Frontend.RunMultipleAction(VdcActionType.AddVds, parametersList, true, new IFrontendMultipleActionAsyncCallback() { @Override public void executed(FrontendMultipleActionAsyncResult result) { hostsModel.stopProgress(); boolean isAllCanDoPassed = true; for (VdcReturnValueBase returnValueBase : result.getReturnValue()) { isAllCanDoPassed = isAllCanDoPassed && returnValueBase.getCanDoAction(); if (!isAllCanDoPassed) { break; } } if (isAllCanDoPassed) { cancel(); } } }, null); }
Source:
<code>private void updateSubscribedTopics(final Set<String> topics, final String logPrefix) { final Collection<String> existingTopics = subscriptionUpdates(); if (!existingTopics.equals(topics)) { <START> subscriptionUpdates.clear(); <END> subscriptionUpdates.addAll(topics); log.debug("{}found topics possibly matching subscription", logPrefix, topics.size()); setRegexMatchedTopicsToSourceNodes(); setRegexMatchedTopicToStateStore(); } }</code><technical_language>This function is called callers: xxxFromMetadata xxxFromAssignment. For do maintain topics replace passed in value, for maintain topics -- this care if leader assign tasks / partitions due assignment error. logic here</technical_language>

Target:
private void updateSubscribedTopics(final Set<String> topics, final String logPrefix) { subscriptionUpdates.clear(); subscriptionUpdates.addAll(topics); log.debug("{}found topics possibly matching subscription", logPrefix, topics.size()); setRegexMatchedTopicsToSourceNodes(); setRegexMatchedTopicToStateStore(); }
Source:
<code>public void canDeclareSpecificComponentsAsSafe() { TableDefinition definition = new TableDefinition() {{ javaTableName(TABLE_REF.getTablename()); rowName(); <START> rowComponent(ROW_NAME, ValueType.STRING, TableMetadataPersistence.ValueByteOrder.ASCENDING, true); <END> columns(); column(COLUMN_NAME, COLUMN_SHORTNAME, ValueType.VAR_LONG); }}; assertRowComponentSafety(definition, true); assertNamedColumnSafety(definition, false); }</code><technical_language>Do want enum explicit true means here</technical_language>

Target:
public void canDeclareSpecificComponentsAsSafe() { TableDefinition definition = new TableDefinition() {{ javaTableName(TABLE_REF.getTablename()); rowName(); rowComponent( ROW_NAME, ValueType.STRING, TableMetadataPersistence.ValueByteOrder.ASCENDING, LogSafety.SAFE); columns(); column(COLUMN_NAME, COLUMN_SHORTNAME, ValueType.VAR_LONG); }}; assertRowComponentSafety(definition, LogSafety.SAFE); assertNamedColumnSafety(definition, LogSafety.UNSAFE); }
Source:
<code><START> public Map<String, EList<String>> getSortedPermitted() { <END> TreeMap<String, EList<String>> sortedPermitted = new TreeMap<>(); Iterator<Entry<String, EList<String>>> iterator = super.getPermitted_labels().iterator(); while (iterator.hasNext()) { Entry<String, EList<String>> permittedlabel = iterator.next(); sortedPermitted.put(permittedlabel.getKey(), permittedlabel.getValue()); } return sortedPermitted; }</code><technical_language>Rename getSortedPermittedLabels()</technical_language>

Target:
public Map<String, EList<String>> getSortedPermitted() { TreeMap<String, EList<String>> sortedPermitted = new TreeMap<>(); Iterator<Entry<String, EList<String>>> iterator = getPermitted_labels().iterator(); while (iterator.hasNext()) { Entry<String, EList<String>> permittedlabel = iterator.next(); sortedPermitted.put(permittedlabel.getKey(), permittedlabel.getValue()); } return sortedPermitted; }
Source:
<code>public SecurityInfo add(SecurityInfo info) throws NonUniqueSecurityInfoException { byte[] data = serialize(info); try (Jedis j = pool.getResource()) { if (info.getIdentity() != null) { String oldEndpoint; <START> if ((oldEndpoint = j.hget(PSKID_SEC, info.getIdentity())) != null <END> && !oldEndpoint.equals(info.getEndpoint())) { throw new NonUniqueSecurityInfoException("PSK Identity " + info.getIdentity() + " is already used"); } j.hset(PSKID_SEC.getBytes(), info.getIdentity().getBytes(), info.getEndpoint().getBytes()); } j.set((SEC_EP + info.getEndpoint()).getBytes(), data); return null; } }</code><technical_language>In Leshan code base, generally initialize variable in if condition. please, move initialization out of if ? java String oldEndpoint = j.hget(PSKID_SEC, info.getIdentity(); if (oldEndpoint != null ..</technical_language>

Target:
public SecurityInfo add(SecurityInfo info) throws NonUniqueSecurityInfoException { byte[] data = serialize(info); try (Jedis j = pool.getResource()) { if (info.getIdentity() != null) { String oldEndpoint = j.hget(PSKID_SEC, info.getIdentity()); if (oldEndpoint != null && !oldEndpoint.equals(info.getEndpoint())) { throw new NonUniqueSecurityInfoException("PSK Identity " + info.getIdentity() + " is already used"); } j.hset(PSKID_SEC.getBytes(), info.getIdentity().getBytes(), info.getEndpoint().getBytes()); } byte[] previousData = j.getSet((SEC_EP + info.getEndpoint()).getBytes(), data); SecurityInfo previous = previousData == null ? null : deserialize(previousData); String previousIdentity = previous == null ? null : previous.getIdentity(); if (previousIdentity != null && !previousIdentity.equals(info.getIdentity())) { j.hdel(PSKID_SEC, previousIdentity); } return previous; } }
Source:
<code>protected void helpAction() { <START> BrowserUtil.browse("<LINK_2>"); <END> }</code><technical_language>Cool! This fixes <LINK_0></technical_language>

Target:
protected void helpAction() { BrowserUtil.browse("<LINK_1>"); }
Source:
<code><START> Optional<CatchUpStorage> getStorage() { <END> return Optional.ofNullable(storage); }</code><technical_language>This method used. If is used, please rename avoiding get prefix. Assuming is a method ensures is a storage (i.e. storage()), hasStorage() if need query presence</technical_language>

Target:
CatchUpStorage getStorage() { return checkNotNull(storage); }
Source:
<code>public void connect() throws Exception { synchronized (connectionLock) { if (connectionStatus == STATUS.CONNECTED) { <START> log.info("Already connected to Qpid Broker, ignoring this connect request"); <END> } log.debug("creating connection"); try { connection = connectionFactory.createConnection(); } catch (JMSException ex) { log.error("Error connecting to Qpid, it is probably down"); throw ex; } connection.start(); log.debug("creating topic session"); session = createTopicSession(); log.info("AMQP session created successfully..."); Map<Target, Map<Type, TopicPublisher>> pm = Util.newMap(); buildAllTopicPublishers(pm); producerMap = pm; connectionStatus = STATUS.CONNECTED; } }</code><technical_language>Is request ignored? method for log message</technical_language>

Target:
public void connect() throws Exception { synchronized (connectionLock) { connection = newConnection(); log.debug("creating topic session"); session = createTopicSession(); log.info("AMQP session created successfully..."); Map<Target, Map<Type, TopicPublisher>> pm = Util.newMap(); buildAllTopicPublishers(pm); producerMap = pm; connectionStatus = STATUS.CONNECTED; } }
Source:
<code>public void testRefreshIsDebugEnabledFalse() throws Exception { configurator.setContext(context); ((LoggerContext) context).reset(); configurator.doConfigure(logbackUnitTestFilePath); Map<String, String> mapExpectedFirstFetch = new HashMap<String, String>(); mapExpectedFirstFetch.put("001", "firstRetrieve001"); mapExpectedFirstFetch.put("002", "firstRetrieve002"); mapExpectedFirstFetch.put("003", "firstRetrieve003"); Map<String, String> mapExpectedSecondFetch = new HashMap<String, String>(); mapExpectedSecondFetch.put("001", "secondRetrieve001"); mapExpectedSecondFetch.put("002", "secondRetrieve002"); mapExpectedSecondFetch.put("003", "secondRetrieve003"); AbstractReloadableCodeList reloadableCodeList = new ExtendedReloadableCodelist(); Map<String, String> mapResult1 = reloadableCodeList.asMap(); assertThat(mapResult1.size(), is(mapExpectedFirstFetch.size())); for (String key : mapResult1.keySet()) { assertThat(mapResult1.get(key), is(mapExpectedFirstFetch.get(key))); } <START> assertFalse(logger.isDebugEnabled()); <END> reloadableCodeList.afterPropertiesSet(); Map<String, String> mapResult2 = reloadableCodeList.asMap(); assertThat(mapResult2.size(), is(mapExpectedSecondFetch.size())); for (String key : mapResult2.keySet()) { assertThat(mapResult2.get(key), is(mapExpectedSecondFetch.get(key))); } ((LoggerContext) context).reset(); configurator.doConfigure(logbackDefaultFilePath); }</code><technical_language>[x] assertFalse(target) -> assertThat(target, is(false)) --- modified. b3c7a59bc6a81bb862a9bcdc8b697fac263f617d</technical_language>

Target:
public void testRefreshIsDebugEnabledFalse() throws Exception { LogLevelChangeUtil.setLogLevel(LogLevelChangeUtil.LogLevel.INFO); Map<String, String> mapExpectedFirstFetch = new HashMap<String, String>(); mapExpectedFirstFetch.put("001", "firstRetrieve001"); mapExpectedFirstFetch.put("002", "firstRetrieve002"); mapExpectedFirstFetch.put("003", "firstRetrieve003"); Map<String, String> mapExpectedSecondFetch = new HashMap<String, String>(); mapExpectedSecondFetch.put("001", "secondRetrieve001"); mapExpectedSecondFetch.put("002", "secondRetrieve002"); mapExpectedSecondFetch.put("003", "secondRetrieve003"); AbstractReloadableCodeList reloadableCodeList = new ExtendedReloadableCodelist(); Map<String, String> mapResult1 = reloadableCodeList.asMap(); assertThat(mapResult1.size(), is(mapExpectedFirstFetch.size())); for (String key : mapResult1.keySet()) { assertThat(mapResult1.get(key), is(mapExpectedFirstFetch.get(key))); } assertThat(logger.isDebugEnabled(), is(false)); reloadableCodeList.afterPropertiesSet(); Map<String, String> mapResult2 = reloadableCodeList.asMap(); assertThat(mapResult2.size(), is(mapExpectedSecondFetch.size())); for (String key : mapResult2.keySet()) { assertThat(mapResult2.get(key), is(mapExpectedSecondFetch.get(key))); } LogLevelChangeUtil.resetLogLevel(); }
Source:
<code>public void sendResponse(Send payloadToSend, NetworkRequest originalRequest, ServerNetworkResponseMetrics metrics) throws InterruptedException { if (!(originalRequest instanceof NettyServerRequest)) { throw new IllegalArgumentException("NetworkRequest should be NettyRequest"); } ChannelHandlerContext ctx = ((NettyServerRequest) originalRequest).getCtx(); http2ServerMetrics.requestTotalProcessingTime.update( System.currentTimeMillis() - originalRequest.getStartTimeInMs()); <START> ctx.pipeline().writeAndFlush(payloadToSend); <END> }</code><technical_language>ctx.writeAndFlush do work. way, do ctx.isOpen check write, it, connection closed server a chance write</technical_language>

Target:
public void sendResponse(Send payloadToSend, NetworkRequest originalRequest, ServerNetworkResponseMetrics metrics) throws InterruptedException { if (!(originalRequest instanceof NettyServerRequest)) { throw new IllegalArgumentException("NetworkRequest should be NettyRequest"); } ChannelHandlerContext ctx = ((NettyServerRequest) originalRequest).getCtx(); http2ServerMetrics.requestTotalProcessingTime.update( System.currentTimeMillis() - originalRequest.getStartTimeInMs()); ctx.channel().writeAndFlush(payloadToSend); }
Source:
<code>public synchronized void stop() { RuntimeException toThrow = null; try { if (process != null) { process.stop(); process.waitFor(); process = null; } } catch (Exception e) { toThrow = new RuntimeException("Could not stop container", e); } finally { <START> if (closeConnectionBeforeStop) <END> closeConnection(); final ExecutorService exec = executor; if (exec != null) { exec.shutdownNow(); executor = null; } if (closeClientConfig) { try { clientConfiguration.close(); } catch (Exception e) { if (toThrow == null) { toThrow = new RuntimeException("Could not stop client configuration", e); } } } } if (toThrow != null) { throw toThrow; } }</code><technical_language>start() creates a new connection, closeConnection() cleanup domainClient, solve issue well</technical_language>

Target:
public synchronized void stop() { RuntimeException toThrow = null; try { if (process != null) { process.stop(); process.waitFor(); process = null; } } catch (Exception e) { toThrow = new RuntimeException("Could not stop container", e); } finally { closeConnection(); final ExecutorService exec = executor; if (exec != null) { exec.shutdownNow(); executor = null; } if (closeClientConfig) { try { clientConfiguration.close(); } catch (Exception e) { if (toThrow == null) { toThrow = new RuntimeException("Could not stop client configuration", e); } } } } if (toThrow != null) { throw toThrow; } }
Source:
<code>public void updateQueryTag(String queryId, String queryTag) { Operation operation = queryIdOperation.get(queryId); if (operation != null) { if (queryTagToIdMap.get(queryTag) != null) { throw new RuntimeException("tag " + queryTag + " is already applied for query " + queryId); } queryTagToIdMap.put(queryTag, queryId); LOG.debug("Query " + queryId + " is updated with tag " + queryTag); return; } LOG.info("Query id is missing during query tag updation"); <START> } <END></code><technical_language>Is normal scenario update tag queryId? If not, throw exception</technical_language>

Target:
public void updateQueryTag(String queryId, String queryTag) { Operation operation = queryIdOperation.get(queryId); if (operation != null) { String queryIdTemp = queryTagToIdMap.get(queryTag); if (queryIdTemp != null) { throw new RuntimeException("tag " + queryTag + " is already applied for query " + queryIdTemp); } queryTagToIdMap.put(queryTag, queryId); LOG.info("Query " + queryId + " is updated with tag " + queryTag); return; } LOG.info("Query id is missing during query tag updation"); }
Source:
<code>public void test01_01_requestControllerHandling() { driver.findElement(By.id("requestControllerHandling_01_01")).click(); dbLogProvider.waitForAssertion(); <START> assertTrue(driver.getTitle().contains("terasoluna-gfw-functionaltest")); <END> assertThat(dbLogProvider.countContainsMessageAndLevelsAndLogger( "\\[w.xx.0002\\] ResultMessages \\[type=error, list=\\[ResultMessage \\[code=null, args=\\[\\], text=Error\\]\\]\\]", "WARN", "org.terasoluna.gfw.common.exception.ExceptionLogger"), is(1L)); assertThat(dbLogProvider.countContainsMessageAndLevelsAndLogger( "\\[w.xx.0002\\] ResultMessages \\[type=error, list=\\[ResultMessage \\[code=null, args=\\[\\], text=Error\\]\\]\\]", "WARN", "org.terasoluna.gfw.common.exception.ExceptionLogger.Monitoring"), is(1L)); assertThat(driver.findElement(By.xpath(" }</code><technical_language>[ ] asertThat</technical_language>

Target:
public void test01_01_requestControllerHandling() { driver.findElement(By.id("requestControllerHandling_01_01")).click(); assertThat(driver.getTitle(), is("terasoluna-gfw-functionaltest")); assertThat(dbLogProvider.countContainsMessageAndLevelsAndLogger( "\\[w.xx.0002\\] ResultMessages \\[type=error, list=\\[ResultMessage \\[code=null, args=\\[\\], text=Error\\]\\]\\]", "WARN", "org.terasoluna.gfw.common.exception.ExceptionLogger"), is(1L)); assertThat(dbLogProvider.countContainsMessageAndLevelsAndLogger( "\\[w.xx.0002\\] ResultMessages \\[type=error, list=\\[ResultMessage \\[code=null, args=\\[\\], text=Error\\]\\]\\]", "WARN", "org.terasoluna.gfw.common.exception.ExceptionLogger.Monitoring"), is(1L)); assertThat(driver.findElement(By.xpath(" }
Source:
<code>private Optional<IjFolder> tryCreateNewParentFolderFromChildrenResourceFolders( Path currentPath, ImmutableCollection<IjFolder> children, FolderTypeWithPackageInfo typeForMerging) { IjResourceFolderType ijResourceFolderType = typeForMerging.getIjResourceFolderType(); ImmutableList<IjFolder> childrenToMerge = children .stream() .filter(ijResourceFolderType::isIjFolderInstance) .collect(MoreCollectors.toImmutableList()); if (childrenToMerge.isEmpty()) { return Optional.empty(); } final Path resourcesRoot = ijResourceFolderType.getResourcesRootFromFolder(childrenToMerge.get(0)); <START> if (!currentPath.startsWith(resourcesRoot)) { <END> return Optional.empty(); } boolean childrenHaveSameResourcesRoot = childrenToMerge .stream() .allMatch( folder -> Objects.equals( resourcesRoot, ijResourceFolderType.getResourcesRootFromFolder(folder))); if (!childrenHaveSameResourcesRoot) { return Optional.empty(); } IjFolder mergedFolder = ijResourceFolderType .getFactory() .create( currentPath, resourcesRoot, childrenToMerge .stream() .flatMap(folder -> folder.getInputs().stream()) .collect(MoreCollectors.toImmutableSortedSet())); removeFolders(childrenToMerge); mergePathsMap.put(currentPath, mergedFolder); return Optional.of(mergedFolder); }</code><technical_language>resourcesRoot null, this throw a NullPointerException, please address</technical_language>

Target:
private Optional<IjFolder> tryCreateNewParentFolderFromChildrenResourceFolders( Path currentPath, ImmutableCollection<IjFolder> children, FolderTypeWithPackageInfo typeForMerging) { IjResourceFolderType ijResourceFolderType = typeForMerging.getIjResourceFolderType(); ImmutableList<IjFolder> childrenToMerge = children .stream() .filter(ijResourceFolderType::isIjFolderInstance) .collect(MoreCollectors.toImmutableList()); if (childrenToMerge.isEmpty()) { return Optional.empty(); } final Path resourcesRoot = ijResourceFolderType.getResourcesRootFromFolder(childrenToMerge.get(0)); if (resourcesRoot != null && !resourcesRoot.equals(Paths.get("")) && !currentPath.startsWith(resourcesRoot)) { return Optional.empty(); } boolean childrenHaveSameResourcesRoot = childrenToMerge .stream() .allMatch( folder -> Objects.equals( resourcesRoot, ijResourceFolderType.getResourcesRootFromFolder(folder))); if (!childrenHaveSameResourcesRoot) { return Optional.empty(); } IjFolder mergedFolder = ijResourceFolderType .getFactory() .create( currentPath, resourcesRoot, childrenToMerge .stream() .flatMap(folder -> folder.getInputs().stream()) .collect(MoreCollectors.toImmutableSortedSet())); removeFolders(childrenToMerge); mergePathsMap.put(currentPath, mergedFolder); return Optional.of(mergedFolder); }
Source:
<code>public boolean authenticate(String username, String password) throws DirectoryException { Document user = getCollection().find(MongoDBSerializationHelper.fieldMapToBson(getIdField(), username)).first(); if (user == null) { return false; } if (isMultiTenant()) { String tenantId = getCurrentTenantId(); if (StringUtils.isNotBlank(tenantId)) { String entryTenantId = user.getString(TENANT_ID_FIELD); if (StringUtils.isNotBlank(entryTenantId) && !entryTenantId.equals(tenantId)) { <START> return false; <END> } } } String storedPassword = user.getString(getPasswordField()); return PasswordHelper.verifyPassword(password, storedPassword); }</code><technical_language>this pattern times, do a method for</technical_language>

Target:
public boolean authenticate(String username, String password) throws DirectoryException { Document user = getCollection().find(MongoDBSerializationHelper.fieldMapToBson(getIdField(), username)).first(); if (user == null) { return false; } String storedPassword = user.getString(getPasswordField()); if (isMultiTenant()) { if(!checkEntryTenantId(user.getString(TENANT_ID_FIELD))) { storedPassword = null; } } return PasswordHelper.verifyPassword(password, storedPassword); }
Source:
<code>private boolean validatePackagePath() { File file = new File(PACKAGE_PATH_NAME); try { return ((file.exists() && file.isDirectory()) || (file.exists() && file.getPath().endsWith(".zip"))); <START> } catch (Exception e) { <END> return false; } }</code><technical_language>exceptions for control flow</technical_language>

Target:
private void validatePackagePath() { File file = new File(PACKAGE_PATH_NAME); if (file.exists()) { if (!(file.isDirectory() || file.getPath().endsWith(".zip"))) { logger.warn(PACKAGE_PATH_NAME + " must be a directory or a zip file."); throw new CLIException(REASON_INVALID_ARGUMENTS, String.format("'%s' must be a directory or a zip file.", PACKAGE_PATH_NAME)); } } else { logger.warn(PACKAGE_PATH_NAME + " is not a valid package."); throw new CLIException(REASON_INVALID_ARGUMENTS, String.format("'%s' is not a valid package.", PACKAGE_PATH_NAME)); } }
Source:
<code>private synchronized void handleTestRunningState(String testID) { try { TestRunningState testRunningState = testModelDAO.getTestRunningState(testID); logger .info("handleTestRunningState for " + testID + " with state " + testRunningState.name()); if (!timeoutTasks.containsKey(testID)) { Time maxRunTime = testModelDAO.getMaxRunningTime(testID); TimeoutTask timeoutTask = new TimeoutTask(testID, this); ScheduledFuture<?> timeoutFuture = timeoutScheduledThreadPoolExecutor.schedule(timeoutTask, maxRunTime.toSecondsPart(), TimeUnit.SECONDS); timeoutTasks.put(testID, timeoutFuture); } switch (testRunningState) { case DETERMINE_EXPLORATION_STRATEGY: runningStatesHandler.determineExplorationStrategy(testID); break; case ADD_STORED_KNOWLEDGE: runningStatesHandler.addStoredKnowledge(testID); break; case DETERMINE_EXECUTE_VALIDATION_SET: runningStatesHandler.determineExecuteInitialValidationSet(testID); break; case DETERMINE_EXECUTE_EXPERIMENTS: runningStatesHandler.determineAndExecuteExperiments(testID); break; case HANDLE_EXPERIMENT_RESULT: runningStatesHandler.handleExperimentResult(testID); break; case VALIDATE_TERMINATION_CRITERIA: runningStatesHandler.validateTerminationCriteria(testID); break; case DERIVE_PREDICTION_FUNCTION: <START> testModelDAO.setTestRunningState(testID, VALIDATE_PREDICTION_FUNCTION); <END> runningStatesHandler.derivePredictionFunction(testID); break; case VALIDATE_PREDICTION_FUNCTION: runningStatesHandler.validatePredictionFunction(testID); break; case REMOVE_NON_REACHABLE_EXPERIMENTS: runningStatesHandler.removeNonReachableExperiments(testID); break; default: break; } } catch (BenchFlowTestIDDoesNotExistException e) { e.printStackTrace(); } }</code><technical_language>do this in function called in next line</technical_language>

Target:
protected synchronized BenchFlowTestState handleTestRunningState(String testID) throws BenchFlowTestIDDoesNotExistException { try { TestRunningState testRunningState = testModelDAO.getTestRunningState(testID); logger .info("handleTestRunningState for " + testID + " with state " + testRunningState.name()); switch (testRunningState) { case DETERMINE_EXPLORATION_STRATEGY: runningStatesHandler.determineExplorationStrategy(testID); break; case ADD_STORED_KNOWLEDGE: runningStatesHandler.addStoredKnowledge(testID); break; case DETERMINE_EXECUTE_VALIDATION_SET: runningStatesHandler.determineExecuteInitialValidationSet(testID); break; case DETERMINE_EXECUTE_EXPERIMENTS: runningStatesHandler.determineAndExecuteExperiments(testID); break; case HANDLE_EXPERIMENT_RESULT: runningStatesHandler.handleExperimentResult(testID); break; case VALIDATE_TERMINATION_CRITERIA: runningStatesHandler.validateTerminationCriteria(testID); break; case DERIVE_PREDICTION_FUNCTION: runningStatesHandler.derivePredictionFunction(testID); break; case VALIDATE_PREDICTION_FUNCTION: runningStatesHandler.validatePredictionFunction(testID); break; case REMOVE_NON_REACHABLE_EXPERIMENTS: runningStatesHandler.removeNonReachableExperiments(testID); break; default: break; } } catch (BenchFlowTestIDDoesNotExistException e) { e.printStackTrace(); } return testModelDAO.getTestState(testID); }
Source:
<code>public void applyChangeSetToIndex(final IdAndVersion tableId, final SparseChangeSet rowset, final long changeSetVersionNumber) { final long currentVersion = tableIndexDao .getMaxCurrentCompleteVersionForTable(tableId); if (changeSetVersionNumber > currentVersion) { tableIndexDao .executeInWriteTransaction(new TransactionCallback<Void>() { @Override public Void doInTransaction(TransactionStatus status) { for(Grouping grouping: rowset.groupByValidValues()){ tableIndexDao.createOrUpdateOrDeleteRows(tableId, grouping); } Set<Long> fileHandleIds = rowset.getFileHandleIdsInSparseChangeSet(); if (!fileHandleIds.isEmpty()) { tableIndexDao.applyFileHandleIdsToTable( tableId, fileHandleIds); } tableIndexDao.setMaxCurrentCompleteVersionForTable( tableId, changeSetVersionNumber); <START> <END> for(ListColumnChanges listColumnChange : rowset.groupListColumnChanges()){ tableIndexDao.deleteFromListColumnIndexTable(tableId, listColumnChange.getColumnModel(), listColumnChange.getRowIds()); tableIndexDao.populateListColumnIndexTable(tableId, listColumnChange.getColumnModel(), listColumnChange.getRowIds()); } return null; } }); } }</code><technical_language>move</technical_language>

Target:
public void applyChangeSetToIndex(final IdAndVersion tableId, final SparseChangeSet rowset, final long changeSetVersionNumber) { final long currentVersion = tableIndexDao .getMaxCurrentCompleteVersionForTable(tableId); if (changeSetVersionNumber > currentVersion) { tableIndexDao .executeInWriteTransaction(new TransactionCallback<Void>() { @Override public Void doInTransaction(TransactionStatus status) { for(Grouping grouping: rowset.groupByValidValues()){ tableIndexDao.createOrUpdateOrDeleteRows(tableId, grouping); } Set<Long> fileHandleIds = rowset.getFileHandleIdsInSparseChangeSet(); if (!fileHandleIds.isEmpty()) { tableIndexDao.applyFileHandleIdsToTable( tableId, fileHandleIds); } for(ListColumnChanges listColumnChange : rowset.groupListColumnChanges()){ tableIndexDao.deleteFromListColumnIndexTable(tableId, listColumnChange.getColumnModel(), listColumnChange.getRowIds()); tableIndexDao.populateListColumnIndexTable(tableId, listColumnChange.getColumnModel(), listColumnChange.getRowIds()); } tableIndexDao.setMaxCurrentCompleteVersionForTable( tableId, changeSetVersionNumber); return null; } }); } }
Source:
<code>public void testNewFileNoWait() throws Exception { for (int i = 0; i < 5; i++) { long start = System.currentTimeMillis(); File f1 = createFile("newfile"); FileSnapshot save = FileSnapshot.save(f1); long res = FS.getFsTimerResolution(f1.toPath()).toMillis(); long end = System.currentTimeMillis(); if (end - start > 2 * res) { continue; } assertTrue(save.isModified(f1)); return; } <START> fail("too much load for this test"); <END> }</code><technical_language>this test fails always, idle system, if file time resolution is smaller time needed create a file a FileSnapshot this Mac Java 11 APFS SSD disk: * file timestamp resolution is 7mus (measured [1]) * min racy threshold is 0 (measured [1]) * time create a file is 90 mus (measured [2]) * time create a FileSnapshot is 6 mus (measured [2]) I skip this test if file time resolution is some threshold e.g. 10ms [1] cherry-picked this fix patch series <LINK_0> stable-5.1 [2] <LINK_1></technical_language>

Target:
public void testNewFileNoWait() throws Exception { Assume.assumeTrue(fsAttrCache.getFsTimestampResolution() .compareTo(Duration.ofMillis(10)) > 0); for (int i = 0; i < 50; i++) { Instant start = Instant.now(); Path f1 = createFile("newfile"); FileSnapshot save = FileSnapshot.save(f1.toFile()); Duration res = FS.getFileStoreAttributes(f1) .getFsTimestampResolution(); Instant end = Instant.now(); if (Duration.between(start, end) .compareTo(res.multipliedBy(2)) > 0) { continue; } assertTrue(save.isModified(f1.toFile())); return; } fail("too much load for this test"); }
Source:
<code>public static String unshorten(String text) { while (true) { try { Matcher m = emoji_pattern.matcher(text); if (m.find()) { String emoji = m.group(1); text = m.replaceFirst(emoji); continue; } } catch (Throwable e) { e.printStackTrace(); break; } try { Matcher m = hashtag_pattern.matcher(text); if (m.find()) { text = m.replaceFirst(" #" + m.group(1) + " "); continue; } } catch (Throwable e) { e.printStackTrace(); break; } try { Matcher m = timeline_link_pattern.matcher(text); if (m.find()) { String expanded = RedirectUnshortener.unShorten(m.group(1)); text = m.replaceFirst(" " + expanded); continue; } } catch (Throwable e) { e.printStackTrace(); break; } try { Matcher m = timeline_embed_pattern.matcher(text); if (m.find()) { String shorturl = RedirectUnshortener.unShorten(m.group(1)); <START> text = m.replaceFirst(" <LINK_0>" + shorturl + " "); <END> continue; } } catch (Throwable e) { e.printStackTrace(); break; } break; } text = cleanup_pattern.matcher(text).replaceAll(""); text = MessageEntry.html2utf8(text); text = doublespace_pattern.matcher(text).replaceAll(" "); text = text.trim(); return text; }</code><technical_language>Is needed replaceFirst() initial characters ? trim replacement Matching required pattern matcher</technical_language>

Target:
public static String unshorten(String text) { while (true) { try { Matcher m = emoji_pattern.matcher(text); if (m.find()) { String emoji = m.group(1); text = m.replaceFirst(emoji); continue; } } catch (Throwable e) { e.printStackTrace(); break; } try { Matcher m = hashtag_pattern.matcher(text); if (m.find()) { text = m.replaceFirst(" #" + m.group(1) + " "); continue; } } catch (Throwable e) { e.printStackTrace(); break; } try { Matcher m = timeline_link_pattern.matcher(text); if (m.find()) { String expanded = RedirectUnshortener.unShorten(m.group(2)); text = m.replaceFirst(" " + expanded); continue; } } catch (Throwable e) { e.printStackTrace(); break; } try { Matcher m = timeline_embed_pattern.matcher(text); if (m.find()) { String shorturl = RedirectUnshortener.unShorten(m.group(2)); text = m.replaceFirst(" <LINK_0>" + shorturl + " "); continue; } } catch (Throwable e) { e.printStackTrace(); break; } break; } text = cleanup_pattern.matcher(text).replaceAll(""); text = MessageEntry.html2utf8(text); text = doublespace_pattern.matcher(text).replaceAll(" "); text = text.trim(); return text; }
Source:
<code>private void checkAndMaybeComplete() { if (operationTracker.isDone() || operationCompleted) { if (operationTracker.hasSucceeded()) { operationException.set(null); } else if (operationTracker.hasFailedOnNotFound()) { <START> operationException.set(new RouterException("", RouterErrorCode.BlobDoesNotExist)); <END> } operationCompleted = true; } }</code><technical_language>add some info RouterException instead of empty string</technical_language>

Target:
private void checkAndMaybeComplete() { if (operationTracker.isDone() || operationCompleted) { if (operationTracker.hasSucceeded()) { operationException.set(null); } else if (operationTracker.hasFailedOnNotFound()) { operationException.set(new RouterException("DeleteOperation failed because of BlobNotFound", RouterErrorCode.BlobDoesNotExist)); } operationCompleted = true; } }