auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private PieDataset createPerspectiveViewPieDataset() { double divisor = perspectiveDebug + perspectiveJava + perspectiveOther; <START> final DefaultPieDataset result = new DefaultPieDataset(); <END> result.setValue("Java" + printPercent(perspectiveJava, divisor), perspectiveJava); result.setValue("Debug" + printPercent(perspectiveDebug, divisor), perspectiveDebug); result.setValue("Other" + printPercent(perspectiveOther, divisor), perspectiveOther); return result; }</code><technical_language>final</technical_language>

Target:
private PieDataset createPerspectiveViewPieDataset() { double divisor = perspectiveDebug + perspectiveJava + perspectiveOther; DefaultPieDataset result = new DefaultPieDataset(); result.setValue("Java" + printPercent(perspectiveJava, divisor), perspectiveJava); result.setValue("Debug" + printPercent(perspectiveDebug, divisor), perspectiveDebug); result.setValue("Other" + printPercent(perspectiveOther, divisor), perspectiveOther); return result; }
Source:
<code>private void restartMeasurementLoader(String ministryId, String mcc, String period) { final LoaderManager manager = this.getSupportLoaderManager(); Bundle args = new Bundle(3); args.putString("ministryId", ministryId); args.putString("mcc", mcc); <START> args.putString("period", period); <END> manager.restartLoader(LOADER_MEASUREMENTS, args, measurementsLoaderCallbacks); }</code><technical_language>another spot shared constants useful</technical_language>

Target:
private void restartMeasurementLoader(String ministryId, String mcc, String period) { final LoaderManager manager = this.getSupportLoaderManager(); Bundle args = new Bundle(3); args.putString(Constants.ARG_MINISTRY_ID, ministryId); args.putString(Constants.ARG_MCC, mcc); args.putString(Constants.ARG_PERIOD, period); manager.restartLoader(LOADER_MEASUREMENTS, args, measurementsLoaderCallbacks); }
Source:
<code>private void validateAndSetDefaultsSubAccount(AccountingXmlDocumentAccountingLine xmlAccountingLine, AmazonKfsAccountDTO defaultAccountDto, boolean logErrorMessage) { if (StringUtils.isNotBlank(xmlAccountingLine.getSubAccountNumber()) && !validateSubAccountNumber(xmlAccountingLine.getChartCode(), xmlAccountingLine.getAccountNumber(), xmlAccountingLine.getSubAccountNumber(), logErrorMessage)) { <START> if (validateSubAccountNumber(xmlAccountingLine.getChartCode(), xmlAccountingLine.getAccountNumber(), defaultAccountDto.getKfsSubAccount(), logErrorMessage)) { <END> xmlAccountingLine.setSubAccountNumber(defaultAccountDto.getKfsSubAccount()); } } }</code><technical_language>if default Account is invalid</technical_language>

Target:
private void validateAndSetDefaultsSubAccount(AccountingXmlDocumentAccountingLine xmlAccountingLine, AmazonKfsAccountDTO defaultAccountDto, boolean logErrorMessage) { if (StringUtils.isNotBlank(xmlAccountingLine.getSubAccountNumber()) && !validateSubAccountNumber(xmlAccountingLine.getChartCode(), xmlAccountingLine.getAccountNumber(), xmlAccountingLine.getSubAccountNumber(), logErrorMessage)) { if (validateSubAccountNumber(xmlAccountingLine.getChartCode(), xmlAccountingLine.getAccountNumber(), defaultAccountDto.getKfsSubAccount(), logErrorMessage)) { xmlAccountingLine.setSubAccountNumber(defaultAccountDto.getKfsSubAccount()); } else { xmlAccountingLine.setSubAccountNumber(StringUtils.EMPTY); } } }
Source:
<code>private PartitionId getPartitionForPut() throws CoordinatorException { <START> List<? extends PartitionId> partitions = clusterMap.getWritablePartitionIds(); <END> if (partitions.isEmpty()) { throw new CoordinatorException("No writable partitions available.", CoordinatorError.AmbryUnavailable); } return partitions.get((int) getRandomLong(randomForPartitionSelection, partitions.size())); }</code><technical_language>List<PartitionId></technical_language>

Target:
private PartitionId getPartitionForPut() throws CoordinatorException { List<PartitionId> partitions = clusterMap.getWritablePartitionIds(); if (partitions.isEmpty()) { throw new CoordinatorException("No writable partitions available.", CoordinatorError.AmbryUnavailable); } return partitions.get((int) getRandomLong(randomForPartitionSelection, partitions.size())); }
Source:
<code>List<DataTypeTreeGridItem> makeTreeGridItems(final DataType dataType, final int level) { final DataTypeTreeGridItem gridItem = getGridItem(); final List<DataType> subDataTypes = dataType.getSubDataTypes(); final List<DataTypeTreeGridItem> gridItems = new ArrayList<>(); gridItem.setupDataType(dataType, level); gridItems.add(gridItem); if (!subDataTypes.isEmpty()) { for (final DataType subDataType : subDataTypes) { <START> gridItems.addAll(makeTreeGridItems(subDataType, level + 1)); <END> } } return gridItems; }</code><technical_language>If subDataTypes null block equal is lines shorter it. [1] java if (!subDataTypes.isEmpty()) { for (final DataType subDataType : subDataTypes) { gridItems.addAll(makeTreeGridItems(subDataType, level + 1)); } } [2] java for (final DataType subDataType : subDataTypes) { gridItems.addAll(makeTreeGridItems(subDataType, level + 1)); }</technical_language>

Target:
List<DataTypeTreeGridItem> makeTreeGridItems(final DataType dataType, final int level) { final DataTypeTreeGridItem gridItem = getGridItem(); final List<DataType> subDataTypes = dataType.getSubDataTypes(); final List<DataTypeTreeGridItem> gridItems = new ArrayList<>(); gridItem.setupDataType(dataType, level); gridItems.add(gridItem); for (final DataType subDataType : subDataTypes) { gridItems.addAll(makeTreeGridItems(subDataType, level + 1)); } return gridItems; }
Source:
<code>public void close(boolean fileOnly) throws IOException { super.close(fileOnly); if (!fileOnly) { seriesCount = 0; H5PositionList.clear(); H5PathsToImageData.clear(); cellObjectNames.clear(); <START> if (jhdf != null) { <END> jhdf.close(); } jhdf = null; lastChannel = 0; } }</code><technical_language>if super.close throws exception jhdf is closed</technical_language>

Target:
public void close(boolean fileOnly) throws IOException { try { super.close(fileOnly); } finally { if (!fileOnly) { seriesCount = 0; H5PositionList.clear(); H5PathsToImageData.clear(); cellObjectNames.clear(); if (jhdf != null) { jhdf.close(); } jhdf = null; lastChannel = 0; } } }
Source:
<code>public GraphFrame(Graph pGraph, TabPane pTabbedPane) { <START> super(); <END> aTabbedPane = pTabbedPane; ToolBar sideBar = new ToolBar(pGraph); aPanel = new GraphPanel(pGraph, sideBar, this); BorderPane layout = new BorderPane(); layout.setRight(sideBar); SwingNode panelNode = new SwingNode(); panelNode.setContent(new JScrollPane(aPanel)); layout.setCenter(panelNode); setTitle(false); setContent(layout); setOnCloseRequest(pEvent -> { pEvent.consume(); EditorFrame editorFrame = (EditorFrame) getTabPane().getParent(); editorFrame.close(this); }); }</code><technical_language>extraneous super consts call, removed</technical_language>

Target:
public GraphFrame(Graph pGraph, TabPane pTabbedPane) { aTabbedPane = pTabbedPane; ToolBar sideBar = new ToolBar(pGraph); aPanel = new GraphPanel(pGraph, sideBar, this); BorderPane layout = new BorderPane(); layout.setRight(sideBar); SwingNode panelNode = new SwingNode(); panelNode.setContent(new JScrollPane(aPanel)); layout.setCenter(panelNode); setTitle(false); setContent(layout); setOnCloseRequest(pEvent -> { pEvent.consume(); EditorFrame editorFrame = (EditorFrame) getTabPane().getParent(); editorFrame.close(this); }); }
Source:
<code>public Session<L> findSession(String id) { Map.Entry<MV, AV> value = this.factory.findValue(id); if (value == null) { <START> InfinispanWebLogger.ROOT_LOGGER.infof("Session %s not found", id); <END> return null; } ImmutableSession session = this.factory.createImmutableSession(id, value); if (session.getMetaData().isExpired()) { InfinispanWebLogger.ROOT_LOGGER.infof("Session %s was found, but has expired", id); this.expirationListener.sessionExpired(session); this.factory.remove(id); return null; } this.expirationScheduler.cancel(id); return new ValidSession<>(this.factory.createSession(id, value, this.context), this.expirationScheduler); }</code><technical_language>This INFO</technical_language>

Target:
public Session<L> findSession(String id) { Map.Entry<MV, AV> value = this.factory.findValue(id); if (value == null) { InfinispanWebLogger.ROOT_LOGGER.tracef("Session %s not found", id); return null; } ImmutableSession session = this.factory.createImmutableSession(id, value); if (session.getMetaData().isExpired()) { InfinispanWebLogger.ROOT_LOGGER.tracef("Session %s was found, but has expired", id); this.expirationListener.sessionExpired(session); this.factory.remove(id); return null; } this.expirationScheduler.cancel(id); return new ValidSession<>(this.factory.createSession(id, value, this.context), this.expirationScheduler); }
Source:
<code>public static boolean checkNetwork(Context context, @NonNull View view) { if (isInternetOn(context)) { return true; } else <START> Toast.makeText(context,R.string.internet_is_off,Toast.LENGTH_SHORT).show(); <END> return false; }</code><technical_language>this SnackBar changed a toast</technical_language>

Target:
public static boolean checkNetwork(Context context, @NonNull View view) { if (isInternetOn(context)) { return true; } else Snackbar.make(view,R.string.internet_is_off,Snackbar.LENGTH_SHORT).show(); return false; }
Source:
<code>private static void deleteAccount(UserInfo userInfo, String loginFilePath, String groupFilePath, Properties props, Multimap<String, String> groupsMap) throws ManageUsersException { <START> if (userInfo.getLogin().isEmpty()) { <END> warnWithMessage("Provided username is empty, skipping."); return; } if (!props.containsKey(userInfo.getLogin())) { warnWithMessage("USER " + userInfo.getLogin() + " does not exist in login file : " + loginFilePath); } if (!groupsMap.containsKey(userInfo.getLogin())) { warnWithMessage("USER " + userInfo.getLogin() + " does not exist in group file : " + groupFilePath); } props.remove(userInfo.getLogin()); groupsMap.removeAll(userInfo.getLogin()); System.out.println("Deleted user " + userInfo.getLogin()); }</code><technical_language>Is userInfo.getLogin _null_? in other parts of code</technical_language>

Target:
private static void deleteAccount(UserInfo userInfo, String loginFilePath, String groupFilePath, Properties props, Multimap<String, String> groupsMap) throws ManageUsersException { if (!userInfo.isLoginSet()) { warnWithMessage(PROVIDED_USERNAME + IS_EMPTY_SKIPPING); return; } if (!props.containsKey(userInfo.getLogin())) { warnWithMessage(USER_HEADER + userInfo.getLogin() + DOES_NOT_EXIST_IN_LOGIN_FILE + loginFilePath); } if (!groupsMap.containsKey(userInfo.getLogin())) { warnWithMessage(USER_HEADER + userInfo.getLogin() + DOES_NOT_EXIST_IN_GROUP_FILE + groupFilePath); } props.remove(userInfo.getLogin()); groupsMap.removeAll(userInfo.getLogin()); System.out.println("Deleted user " + userInfo.getLogin()); }
Source:
<code>public void validate(FailureCollector collector) { if (port != null && (port < 1 || port > 65535)) { <START> collector.addFailure("Invalid port.", "Port number must be an integer from 1 to 65535.") <END> .withConfigProperty(Cassandra.PORT); } }</code><technical_language>"Invalid port number." below</technical_language>

Target:
public void validate(FailureCollector collector) { if (port != null && (port < 1 || port > 65535)) { collector.addFailure("Invalid port number.", "Port number must be an integer from 1 to 65535.") .withConfigProperty(Cassandra.PORT); } }
Source:
<code>protected void decode( ChannelHandlerContext ctx, ByteBuf in, List<Object> out ) { if ( contentTypeProtocol.isExpecting( ContentType.ContentType ) ) { <START> byte b = in.readByte(); <END> ContentType contentType = getContentType( b ); contentTypeProtocol.expect( contentType ); } else { ctx.fireChannelRead( in.retain() ); } }</code><technical_language>same: messageCode</technical_language>

Target:
protected void decode( ChannelHandlerContext ctx, ByteBuf in, List<Object> out ) { if ( contentTypeProtocol.isExpecting( ContentType.ContentType ) ) { byte messageCode = in.readByte(); ContentType contentType = getContentType( messageCode ); contentTypeProtocol.expect( contentType ); } else { ctx.fireChannelRead( in.retain() ); } }
Source:
<code>public RqSimple(final Iterable<String> head, final InputStream body) { super( <START> new RqOf( <END> () -> head, () -> body ) ); }</code><technical_language>@fanifieiev above</technical_language>

Target:
public RqSimple(final Iterable<String> head, final InputStream body) { super(new RequestOf(head, body)); }
Source:
<code>private StringParameterValue checkValue(StringParameterValue value) { if (!choices.contains(value.value)) <START> throw new IllegalArgumentException("For " + getName() + ", illegal choice: " + value.value); <END> return value; }</code><technical_language>Weird sentence structure. Illegal choice for parameter foo: bar</technical_language>

Target:
private StringParameterValue checkValue(StringParameterValue value) { if (!choices.contains(value.value)) throw new IllegalArgumentException("Illegal choice for parameter " + getName() + ": " + value.value); return value; }
Source:
<code>public ContainerProxy getProxy(String hostname, int port) { String upstream = hostname + ":" + port; return proxies.computeIfAbsent(upstream, __ -> { try { final int toxiPort = nextPort.getAndIncrement(); if (toxiPort > LAST_PROXIED_PORT) { throw new IllegalStateException("Maximum number of proxies exceeded"); } <START> final Proxy proxy = client.createProxy(hostname, "0.0.0.0:" + toxiPort, upstream); <END> return new ContainerProxy(proxy, getContainerIpAddress(), getMappedPort(toxiPort)); } catch (IOException e) { throw new RuntimeException("Proxy could not be created", e); } }); }</code><technical_language>suggestion final Proxy proxy = client.createProxy(upstream, "0.0.0.0:" + toxiPort, upstream);</technical_language>

Target:
public ContainerProxy getProxy(String hostname, int port) { String upstream = hostname + ":" + port; return proxies.computeIfAbsent(upstream, __ -> { try { final int toxiPort = nextPort.getAndIncrement(); if (toxiPort > LAST_PROXIED_PORT) { throw new IllegalStateException("Maximum number of proxies exceeded"); } final Proxy proxy = client.createProxy(upstream, "0.0.0.0:" + toxiPort, upstream); return new ContainerProxy(proxy, getContainerIpAddress(), getMappedPort(toxiPort)); } catch (IOException e) { throw new RuntimeException("Proxy could not be created", e); } }); }
Source:
<code>public void savePreferences(ActionRequest request, ActionResponse response) throws IOException, PortletException { User sessionUser = UserCacheHolder.getUserFromRequest(request); UserService.Iface userClient = thriftClients.makeUserClient(); try { User user = userClient.getByEmail(sessionUser.getEmail()); <START> user.setWantsMailNotification(false); END> PortletUtils.setFieldValue(request, user, User._Fields.WANTS_MAIL_NOTIFICATION, User.metaDataMap.get(User._Fields.WANTS_MAIL_NOTIFICATION), ""); if (user.isWantsMailNotification()) { Map<String, Boolean> preferences = new HashMap<>(); SW360Constants.NOTIFICATION_EVENTS_KEYS.forEach(k -> { String value = request.getParameter(User._Fields.NOTIFICATION_PREFERENCES.toString() + k); if (value != null) { preferences.put(k, Boolean.TRUE); } }); user.setNotificationPreferences(preferences); } userClient.updateUser(user); request.setAttribute(PortalConstants.SW360_USER, user); } catch (TException e) { log.error("An error occurred while updating the user record", e); response.setProperty(ResourceResponse.HTTP_STATUS_CODE, Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)); } }</code><technical_language>sure? I if is given, field is set false. unchecked checkbox for parameter key is null code set field false line - no</technical_language>

Target:
public void savePreferences(ActionRequest request, ActionResponse response) throws IOException, PortletException { User sessionUser = UserCacheHolder.getUserFromRequest(request); UserService.Iface userClient = thriftClients.makeUserClient(); try { User user = userClient.getByEmail(sessionUser.getEmail()); PortletUtils.setFieldValue(request, user, User._Fields.WANTS_MAIL_NOTIFICATION, User.metaDataMap.get(User._Fields.WANTS_MAIL_NOTIFICATION), ""); if (user.isWantsMailNotification()) { Map<String, Boolean> preferences = new HashMap<>(); SW360Constants.NOTIFICATION_EVENTS_KEYS.forEach(k -> { String value = request.getParameter(User._Fields.NOTIFICATION_PREFERENCES.toString() + k); if (value != null) { preferences.put(k, Boolean.TRUE); } }); user.setNotificationPreferences(preferences); } userClient.updateUser(user); request.setAttribute(PortalConstants.SW360_USER, user); } catch (TException e) { log.error("An error occurred while updating the user record", e); response.setProperty(ResourceResponse.HTTP_STATUS_CODE, Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)); } }
Source:
<code>void tryToProvidePreviewSurface() { if (mResolution == null || mSurfaceTexture == null || mSurfaceCompleter == null) { return; } mSurfaceTexture.setDefaultBufferSize(mResolution.getWidth(), mResolution.getHeight()); final Surface surface = new Surface(mSurfaceTexture); mSurfaceReleaseFuture.addListener(() -> { surface.release(); <START> mSurfaceReleaseFuture = null; <END> }, ContextCompat.getMainExecutor(mTextureView.getContext())); mSurfaceCompleter.set(surface); mSurfaceCompleter = null; transformPreview(); }</code><technical_language>Again, careful here. mSurfaceReleaseFuture changed a future this listener added called. nulling out a more mSurfaceReleaseFuture belong surface (and completed). store release future in a local variable check is equal mSurfaceReleaseFuture nulling out</technical_language>

Target:
void tryToProvidePreviewSurface() { if (mResolution == null || mSurfaceTexture == null || mSurfaceCompleter == null) { return; } mSurfaceTexture.setDefaultBufferSize(mResolution.getWidth(), mResolution.getHeight()); final Surface surface = new Surface(mSurfaceTexture); final ListenableFuture<Void> surfaceReleaseFuture = mSurfaceReleaseFuture; mSurfaceReleaseFuture.addListener(() -> { surface.release(); if (mSurfaceReleaseFuture == surfaceReleaseFuture) { mSurfaceReleaseFuture = null; } }, ContextCompat.getMainExecutor(mTextureView.getContext())); mSurfaceCompleter.set(surface); mSurfaceCompleter = null; transformPreview(); }
Source:
<code>public DataInputStream getChunkDataInputStream(int x, int z) throws IOException { checkBounds(x, z); int offset = getOffset(x, z); if (offset == 0) { return null; } int sectorNumber = offset >> 8; int numSectors = offset & 0xFF; if (sectorNumber + numSectors > totalSectors) { throw new IOException("Invalid sector: " + sectorNumber + "+" + numSectors + " > " + totalSectors); } file.seek(sectorNumber * SECTOR_BYTES); int length = file.readInt(); if (length > SECTOR_BYTES * numSectors) { throw new IOException("Invalid length: " + length + " > " + SECTOR_BYTES * numSectors); } byte version = file.readByte(); if (version == VERSION_GZIP) { byte[] data = new byte[length - 1]; file.read(data); return new DataInputStream(new BufferedInputStream(new GZIPInputStream(new ByteArrayInputStream(data)))); } else if (version == VERSION_DEFLATE) { byte[] data = new byte[length - 1]; file.read(data); <START> return new DataInputStream(new BufferedInputStream(new InflaterInputStream(new ByteArrayInputStream(data)))); <END> } throw new IOException("Unknown version: " + version); }</code><technical_language><LINK_0></technical_language>

Target:
public DataInputStream getChunkDataInputStream(int x, int z) throws IOException { checkBounds(x, z); int offset = getOffset(x, z); if (offset == 0) { return null; } int sectorNumber = offset >> 8; int numSectors = offset & 0xFF; if (sectorNumber + numSectors > totalSectors) { throw new IOException("Invalid sector: " + sectorNumber + "+" + numSectors + " > " + totalSectors); } file.seek(sectorNumber * SECTOR_BYTES); int length = file.readInt(); if (length > SECTOR_BYTES * numSectors) { throw new IOException("Invalid length: " + length + " > " + SECTOR_BYTES * numSectors); } byte version = file.readByte(); if (version == VERSION_GZIP) { byte[] data = new byte[length - 1]; file.read(data); return new DataInputStream(new BufferedInputStream(new GZIPInputStream(new ByteArrayInputStream(data), 2048))); } else if (version == VERSION_DEFLATE) { byte[] data = new byte[length - 1]; file.read(data); return new DataInputStream(new BufferedInputStream(new InflaterInputStream(new ByteArrayInputStream(data), new Inflater(), 2048))); } throw new IOException("Unknown version: " + version); }
Source:
<code>public void testKeyRangeCompareUpperRange() throws Exception { List<KeyRange> rowKeyRanges1 = CreateKeyRangeListWithFixedLowerRange( Arrays.asList(Integer.MAX_VALUE, Integer.MAX_VALUE, 10000, 1001, 1000, 1000, 1000, 1000), Arrays.asList(false, false, true, true, true, true, false, true)); <START> List<KeyRange> rowKeyRanges2 = CreateKeyRangeListWithFixedLowerRange( <END> Arrays.asList(Integer.MAX_VALUE, 10000, Integer.MAX_VALUE, 1000, 1001, 1000, 1000, 1000), Arrays.asList(false, false, false, true, true, true, false, false)); List<Integer> expectedResults = Arrays.asList(0, 1, -1, 1, -1, 0, 0, 1); assertEquals(rowKeyRanges1.size(), rowKeyRanges2.size()); assertEquals(rowKeyRanges1.size(), expectedResults.size()); for (int i = 0; i < expectedResults.size(); i++) { int compareResult = KeyRange.compareUpperRange(rowKeyRanges1.get(i), rowKeyRanges2.get(i)); assertEquals(expectedResults.get(i).intValue(), compareResult); } }</code><technical_language>Add some keys strings in key ranges</technical_language>

Target:
public void testKeyRangeCompareUpperRange() throws Exception { List<KeyRange> rowKeyRanges1 = createKeyRangeListWithFixedLowerRange( Arrays.asList(Integer.MAX_VALUE, Integer.MAX_VALUE, 10000, 1001, 1000, 1000, 1000, 1000, 1000), Arrays.asList(false, false, true, true, true, true, false, true, false)); List<KeyRange> rowKeyRanges2 = createKeyRangeListWithFixedLowerRange( Arrays.asList(Integer.MAX_VALUE, 10000, Integer.MAX_VALUE, 1000, 1001, 1000, 1000, 1000, 1000), Arrays.asList(false, false, false, true, true, true, false, false, true)); List<Integer> expectedResults = Arrays.asList(0, 1, -1, 1, -1, 0, 0, 1, -1); assertEquals(rowKeyRanges1.size(), rowKeyRanges2.size()); assertEquals(rowKeyRanges1.size(), expectedResults.size()); for (int i = 0; i < expectedResults.size(); i++) { int compareResult = KeyRange.compareUpperRange(rowKeyRanges1.get(i), rowKeyRanges2.get(i)); assertEquals(expectedResults.get(i).intValue(), compareResult); } }
Source:
<code>private Locale deJavaLocale(String value) { if (value.length() == 0) { return new Locale(""); } int extStart = value.indexOf("_#"); if (extStart != -1) value = value.substring(0, extStart); int pos1 = value.indexOf('_'); if (pos1 == -1) { <START> return null; <END> } String lang = value.substring(0, pos1++), country, var; int pos2 = value.indexOf('_', pos1); if (pos2 == -1) { country = value.substring(pos1); var = ""; } else { country = value.substring(pos1, pos2); var = value.substring(pos2 + 1); } return new Locale(lang, country, var); }</code><technical_language>This is wrong. arbitrarily return null for unrecognized: return in exception</technical_language>

Target:
private Locale deJavaLocale(String value) { if (value.isEmpty()) { return new Locale(""); } int extStart = value.indexOf("_#"); if (extStart != -1) value = value.substring(0, extStart); String language = value, country = "", variant = ""; int pos1 = value.indexOf('_'); if (pos1 != -1) { language = value.substring(0, pos1++); int pos2 = value.indexOf('_', pos1); if (pos2 == -1) { country = value.substring(pos1); } else { country = value.substring(pos1, pos2); variant = value.substring(pos2 + 1); } } return new Locale(language, country, variant); }
Source:
<code>protected static void checkHostStatusOnMaster(String host) throws Exception { final URI mgmtURI = getMasterMgmtUri(); final String operation = getHostStateRunningOperationJson(host); final long time = System.currentTimeMillis() + TIMEOUT; do { <START> Thread.sleep(1000); <END> if (isHostStateRunning(mgmtURI, operation)) { return; } } while (System.currentTimeMillis() < time); Assert.fail("Cannot validate host '" + host + "' is running"); }</code><technical_language>Please move sleep "if (isHostStateRunning(mgmtURI, operation)) {" block decrease sleep time 100ms most. testsuite run fast</technical_language>

Target:
protected static void checkHostStatusOnMaster(String host) throws Exception { final URI mgmtURI = getMasterMgmtUri(); final String operation = createHostStateRunningOperationJson(host); final long time = System.currentTimeMillis() + TIMEOUT; do { if (isHostStateRunning(mgmtURI, operation)) { return; } Thread.sleep(100); } while (System.currentTimeMillis() < time); Assert.fail("Cannot validate host '" + host + "' is running"); }
Source:
<code>private void notifyUserThatAcctCreatedAndReturnToProfile() { new AlertDialog.Builder(this) .setIcon(android.R.drawable.ic_dialog_alert) .setTitle(R.string.done_registering) .setMessage(R.string.done_registering_msg) .setPositiveButton( R.string.OK, (dialog1, which) -> { <START> startActivity(new Intent(App.getAppInstance(), InstanceSwitcherActivity.class)); <END> }) .show(); }</code><technical_language>instead TabLayout activity iff a selected instance (i.e. get InstanceSwitcherActivity)</technical_language>

Target:
private void notifyUserThatAcctCreatedAndReturnToProfile() { new AlertDialog.Builder(this) .setIcon(android.R.drawable.ic_dialog_alert) .setTitle(R.string.done_registering) .setMessage(R.string.done_registering_msg) .setPositiveButton( R.string.OK, (dialog1, which) -> { startActivity(new Intent(App.getAppInstance(), App.hasInstanceCode() ? TabLayout.class : InstanceSwitcherActivity.class)); }) .show(); }
Source:
<code><START> public String getTypeName() { return SchemaOrgConstants.TYPE_TIMESPAN; } <END></code><technical_language>mapping, SchemaOrg type for Timespans is timespan. please update remove JsonIgnore annotation</technical_language>

Target:
public String getTypeName() { return SchemaOrgConstants.TYPE_THING;}
Source:
<code>public KeychainModule(ReactApplicationContext reactContext) { super(reactContext); prefsStorage = new PrefsStorage(reactContext); mReactContext = reactContext; addCipherStorageToMap(new CipherStorageFacebookConceal(reactContext)); addCipherStorageToMap(new CipherStorageKeystoreAESCBC()); <START> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { <END> addCipherStorageToMap(new CipherStorageKeystoreRSAECB(reactContext)); } }</code><technical_language>Introducing another of limiting ciphers Android version confusion in future. I code cleaner if cipher Android version checks performed way. suggest limit while creating cipherStorageMap remove redundant checks getMinSupportedApiLevel, alternatively add ciphers map rely getMinSupportedApiLevel for checks. I is completely fine</technical_language>

Target:
public KeychainModule(ReactApplicationContext reactContext) { super(reactContext); prefsStorage = new PrefsStorage(reactContext); addCipherStorageToMap(new CipherStorageFacebookConceal(reactContext)); addCipherStorageToMap(new CipherStorageKeystoreAESCBC()); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { addCipherStorageToMap(new CipherStorageKeystoreRSAECB()); } }
Source:
<code>private void givenSequentialRecords(long deltaSeconds, int deltaNanos) { final Duration delta = Duration.newBuilder().setSeconds(deltaSeconds).setNanos(deltaNanos).build(); time1 = getCurrentTime().toBuilder().setNanos(POSITIVE_DELTA * 10).build(); <START> record1 = Given.EventStorage.projectCreated(time1); <END> time2 = add(time1, delta); record2 = Given.EventStorage.taskAdded(time2); time3 = add(time2, delta); record3 = Given.EventStorage.projectStarted(time3); writeAll(record1, record2, record3); }</code><technical_language>retrieving EventStorage EventStorageRecord, rename this class (the for other classes creating records, etc)</technical_language>

Target:
private void givenSequentialRecords(long deltaSeconds, int deltaNanos) { final Duration delta = Duration.newBuilder().setSeconds(deltaSeconds).setNanos(deltaNanos).build(); time1 = getCurrentTime().toBuilder().setNanos(POSITIVE_DELTA * 10).build(); record1 = Given.EventStorageRecord.projectCreated(time1); time2 = add(time1, delta); record2 = Given.EventStorageRecord.taskAdded(time2); time3 = add(time2, delta); record3 = Given.EventStorageRecord.projectStarted(time3); writeAll(record1, record2, record3); }
Source:
<code>public boolean isRunning() { WinRmToolResponse runningCheck = executeCommand(VanillaWindowsProcess.CHECK_RUNNING_COMMAND, VanillaWindowsProcess.CHECK_RUNNING_POWERSHELL_COMMAND, false); if(runningCheck.getStatusCode() != 0) { <START> LOG.info(this + " isRunning check failed: exit code " + runningCheck.getStatusCode() + "; " + runningCheck.getStdErr()); <END> } return runningCheck.getStatusCode() == 0; }</code><technical_language>Instead of logging this, log getEntity() (the toString driver good)</technical_language>

Target:
public boolean isRunning() { WinRmToolResponse runningCheck = executeCommand(VanillaWindowsProcess.CHECK_RUNNING_COMMAND, VanillaWindowsProcess.CHECK_RUNNING_POWERSHELL_COMMAND, false); if(runningCheck.getStatusCode() != 0) { LOG.info(getEntity() + " isRunning check failed: exit code " + runningCheck.getStatusCode() + "; " + runningCheck.getStdErr()); } return runningCheck.getStatusCode() == 0; }
Source:
<code>public int write(Iterable<StructuredRecord> structuredRecords, DataWriter dataWriter) throws Exception { int numRecordsWritten = 0; String solrFieldName; List<SolrInputDocument> documentList = new ArrayList<SolrInputDocument>(); SolrInputDocument document; for (StructuredRecord structuredRecord : structuredRecords) { config.validateKeyField(structuredRecord.getSchema()); config.validateInputFieldsDataType(structuredRecord.getSchema()); <START> if (structuredRecord.get(uniqueKey) == null) { <END> continue; } document = new SolrInputDocument(); for (Schema.Field field : structuredRecord.getSchema().getFields()) { solrFieldName = field.getName(); if (outputFieldMap.containsKey(solrFieldName)) { document.addField(outputFieldMap.get(solrFieldName), structuredRecord.get(solrFieldName)); } else { document.addField(solrFieldName, structuredRecord.get(solrFieldName)); } } documentList.add(document); numRecordsWritten++; } solrClient.add(documentList); solrClient.commit(); return numRecordsWritten; }</code><technical_language>skip records keyField ? update description for keyField more specific. this skip for SolrBatch, miss adding</technical_language>

Target:
public int write(Iterable<StructuredRecord> structuredRecords, DataWriter dataWriter) throws Exception { int numRecordsWritten = 0; List<SolrInputDocument> documentList = new ArrayList<SolrInputDocument>(); for (StructuredRecord structuredRecord : structuredRecords) { config.validateKeyField(structuredRecord.getSchema()); config.validateInputFieldsDataType(structuredRecord.getSchema()); if (structuredRecord.get(keyField) == null) { metrics.count("invalid", 1); continue; } SolrInputDocument document = new SolrInputDocument(); for (Schema.Field field : structuredRecord.getSchema().getFields()) { String solrFieldName = field.getName(); if (outputFieldMap.containsKey(solrFieldName)) { document.addField(outputFieldMap.get(solrFieldName), structuredRecord.get(solrFieldName)); } else { document.addField(solrFieldName, structuredRecord.get(solrFieldName)); } } documentList.add(document); numRecordsWritten++; } solrClient.add(documentList); solrClient.commit(); return numRecordsWritten; }
Source:
<code>public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); discussionCommentsAdapter = new DiscussionCommentsAdapter(getActivity(), this, discussionComment); discussionCommentsListView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false)); final int overlap = getResources().getDimensionPixelSize(R.dimen.edx_hairline); discussionCommentsListView.addItemDecoration(new RecyclerView.ItemDecoration() { @Override public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { outRect.set(0, -overlap, 0, 0); } }); discussionCommentsListView.setAdapter(discussionCommentsAdapter); if (isTopicClosed) { <START> createNewCommentTextView.setText(context.getString(R.string.discussion_add_comment_disabled_title)); <END> TextViewCompat.setCompoundDrawablesRelative(createNewCommentTextView, new IconDrawable(getActivity(), Iconify.IconValue.fa_lock) .sizeRes(R.dimen.icon_view_standard_width_height) .colorRes(R.color.edx_grayscale_neutral_white_t), null, null, null ); createNewCommentLayout.setEnabled(false); } else { createNewCommentTextView.setText(context.getString(R.string.discussion_post_create_new_comment)); TextViewCompat.setCompoundDrawablesRelative(createNewCommentTextView, new IconDrawable(getActivity(), Iconify.IconValue.fa_plus_circle) .sizeRes(R.dimen.icon_view_standard_width_height) .colorRes(R.color.edx_grayscale_neutral_white_t), null, null, null ); createNewCommentLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { router.showCourseDiscussionAddComment(context, discussionComment); } }); } }</code><technical_language>need context.getString() here; pass string ID getText()</technical_language>

Target:
public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); discussionCommentsAdapter = new DiscussionCommentsAdapter(getActivity(), this, discussionComment); discussionCommentsListView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false)); final int overlap = getResources().getDimensionPixelSize(R.dimen.edx_hairline); discussionCommentsListView.addItemDecoration(new RecyclerView.ItemDecoration() { @Override public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { outRect.set(0, -overlap, 0, 0); } }); discussionCommentsListView.setAdapter(discussionCommentsAdapter); DiscussionUtils.setStateOnTopicClosed(isTopicClosed, createNewCommentTextView, R.string.discussion_post_create_new_comment, R.string.discussion_add_comment_disabled_title, createNewCommentLayout, new View.OnClickListener() { @Override public void onClick(View v) { router.showCourseDiscussionAddComment(context, discussionComment); } }); }
Source:
<code>protected PagerAdapter createAdapter() { return new WelcomePagerAdapter(R.layout.welcome_pager_item, new int[]{R.drawable.waving_android, R.drawable.welcome_app_icon, R.drawable.thumb_up}, <START> new String[]{"So a while a go the GitHub app was discontinued and some of us wanted something new...", <END> "We move the app under a new name and are now PocketHub", "Click done and we'll get you logged in!"}, new String[]{"Welcome", "Long story short", "Let's get started"}); }</code><technical_language>move strings resource instead</technical_language>

Target:
protected PagerAdapter createAdapter() { return new WelcomePagerAdapter(R.layout.welcome_pager_item, new int[]{R.drawable.waving_android, R.drawable.welcome_app_icon, R.drawable.thumb_up}, getResources().getStringArray(R.array.welcome_texts), getResources().getStringArray(R.array.welcome_titles)); }
Source:
<code>DigitalTwinsAsyncClient(HttpPipeline pipeline, DigitalTwinsServiceVersion serviceVersion, String host) { final SimpleModule stringModule = new SimpleModule("String Serializer"); <START> stringModule.addSerializer(new StdSerializer<String>(String.class, false){ <END> @Override public void serialize(String value, JsonGenerator gen, SerializerProvider provider) throws IOException { if (isJSONValid(value)) { gen.writeRawValue(value); } else { gen.writeString(value); } } }); JacksonAdapter jacksonAdapter = new JacksonAdapter(); jacksonAdapter.serializer().registerModule(stringModule); this.protocolLayer = new AzureDigitalTwinsAPIBuilder() .host(host) .pipeline(pipeline) .serializerAdapter(jacksonAdapter) .buildClient(); this.serviceVersion = serviceVersion; }</code><technical_language>space ){</technical_language>

Target:
DigitalTwinsAsyncClient(HttpPipeline pipeline, DigitalTwinsServiceVersion serviceVersion, String host) { final SimpleModule stringModule = new SimpleModule("String Serializer"); stringModule.addSerializer(new DigitalTwinsStringSerializer(String.class, false, mapper)); JacksonAdapter jacksonAdapter = new JacksonAdapter(); jacksonAdapter.serializer().registerModule(stringModule); this.protocolLayer = new AzureDigitalTwinsAPIImplBuilder() .host(host) .pipeline(pipeline) .serializerAdapter(jacksonAdapter) .buildClient(); this.serviceVersion = serviceVersion; }
Source:
<code>public Optional<BufferOrEvent> pollNext() throws IOException, InterruptedException { Optional<BufferOrEvent> next = inputGate.pollNext(); if (!next.isPresent()) { return handleEmptyBuffer(); } BufferOrEvent bufferOrEvent = next.get(); checkState(!barrierHandler.isBlocked(bufferOrEvent.getChannelInfo())); if (bufferOrEvent.isEvent()) { handleEvent(bufferOrEvent); } else { <START> barrierHandler.processBuffer(bufferOrEvent.getBuffer(), bufferOrEvent.getChannelInfo()); <END> } return next; }</code><technical_language>for in this commit, this is a NO-OP call</technical_language>

Target:
public Optional<BufferOrEvent> pollNext() throws IOException, InterruptedException { Optional<BufferOrEvent> next = inputGate.pollNext(); if (!next.isPresent()) { return handleEmptyBuffer(); } BufferOrEvent bufferOrEvent = next.get(); checkState(!barrierHandler.isBlocked(bufferOrEvent.getChannelInfo())); if (bufferOrEvent.isEvent()) { handleEvent(bufferOrEvent); } return next; }
Source:
<code>public void initialize(InputSplit inputSplit, TaskAttemptContext context) throws IOException, InterruptedException { Preconditions.checkNotNull(inputSplit, "InputSplit is null"); Preconditions.checkNotNull(context, "TaskAttemptContext is null"); Configuration conf = context.getConfiguration(); this.fileSplit = (FileSplit) inputSplit; Path path = this.fileSplit.getPath(); <START> this.reader = new SequenceFile.Reader(FileSystem.get(conf), path, conf); <END> this.vbytes = this.reader.createValueBytes(); this.more = true; }</code><technical_language>splits handled? this split start end account</technical_language>

Target:
public void initialize(InputSplit inputSplit, TaskAttemptContext context) throws IOException, InterruptedException { Preconditions.checkNotNull(inputSplit, "InputSplit is null"); Preconditions.checkNotNull(context, "TaskAttemptContext is null"); Configuration conf = context.getConfiguration(); FileSplit fileSplit = (FileSplit) inputSplit; Path path = fileSplit.getPath(); reader = new SequenceFile.Reader(FileSystem.get(conf), path, conf); vbytes = this.reader.createValueBytes(); start = fileSplit.getStart(); if (start > reader.getPosition()) { reader.sync(start); } start = reader.getPosition(); end = fileSplit.getStart() + fileSplit.getLength(); more = start < end; }
Source:
<code>public double getClassNumber(int elem) { <START> return (double) (2.5f * Math.pow(elem, 0.25)); <END> }</code><technical_language>Useless cast well, Math.pow returns double</technical_language>

Target:
public double getClassNumber(int elem) { return 2.5f * Math.pow(elem, 0.25); }
Source:
<code><START> public Integer getMaxPagePartitioningBufferCount() <END> { return maxPagePartitioningBufferCount; }</code><technical_language>remove @NotNull - Integer -> int</technical_language>

Target:
public int getMaxPagePartitioningBufferCount() { return maxPagePartitioningBufferCount; }
Source:
<code>private void replicate(String binaryPath, String originalFileChecksum, String[] replicationLocations, String binaryMimeType, String binaryUri) throws InterruptedException { String remoteFile = null; String localBinary = null; try { for (String location : replicationLocations) { String fullPath = createRemoteSubDirectory(location, originalFileChecksum); if (Files.exists(Paths.get(binaryPath))) { localBinary = binaryPath; } else { <START> localBinary = dbFilePath(binaryUri, originalFileChecksum); <END> } remoteFile = fullPath + "/" + originalFileChecksum; String[] cmd = new String[]{"rsync", "--update", "--whole-file", "--times", "--verbose", localBinary, remoteFile}; Process runCmd = Runtime.getRuntime().exec(cmd); int exitCode = runCmd.waitFor(); if (exitCode != 0) { BufferedReader errInput = new BufferedReader(new InputStreamReader( runCmd.getErrorStream())); String message = errInput.readLine(); throw new ReplicationException(String.format("Error replicating %s to %s with error code %d and message %s", binaryPath, remoteFile, exitCode, message)); } verifyChecksums(originalFileChecksum, remoteFile); } } catch (IOException e) { throw new ReplicationException(String.format("Unable to replicate %s", binaryPath), e); } }</code><technical_language>temp file this is need cleaned is finished replicated, absolutely want do for other case</technical_language>

Target:
private void replicate(String binaryPath, String originalFileChecksum, String[] replicationLocations, String binaryMimeType, String binaryUri) throws InterruptedException { String destinationFullPath = null; String localBinary = null; File fcrepoBinary = null; if (Files.exists(Paths.get(binaryPath))) { localBinary = binaryPath; } else { try { fcrepoBinary = fcrepoBinaryDownload(binaryUri, originalFileChecksum); } catch (IOException e) { throw new ReplicationException(String.format("Unable to replicate %s", binaryPath), e); } localBinary = fcrepoBinary.getAbsolutePath(); } try { for (String location : replicationLocations) { String destinationDirectory = createRemoteSubDirectory(location, originalFileChecksum); destinationFullPath = destinationDirectory + "/" + originalFileChecksum; String[] cmd = new String[]{"rsync", "--update", "--whole-file", "--times", "--verbose", localBinary, destinationFullPath}; Process runCmd = Runtime.getRuntime().exec(cmd); int exitCode = runCmd.waitFor(); if (exitCode != 0) { BufferedReader errInput = new BufferedReader(new InputStreamReader( runCmd.getErrorStream())); String message = errInput.readLine(); String errorMsg = String.format("Error replicating %s to %s with error code %d and message %s", binaryPath, destinationFullPath, exitCode, message); throw new ReplicationException(errorMsg); } verifyChecksums(originalFileChecksum, destinationFullPath); if (fcrepoBinary != null) { fcrepoBinary.delete(); } } } catch (IOException e) { throw new ReplicationException(String.format("Unable to replicate %s", binaryPath), e); } }
Source:
<code><START> protected BufferBuilder getBufferBuilder() throws IOException, InterruptedException { BufferBuilder builder; if (!targetPartition.isApproximatelyAvailable()) { long start = System.currentTimeMillis(); builder = targetPartition.getBufferBuilder(); idleTimeMsPerSecond.markEvent(System.currentTimeMillis() - start); } else { builder = targetPartition.getBufferBuilder(); } return builder; <END> }</code><technical_language>I this is of times correct, a race condition NetworkBufferPool#redistributeBuffers isApproximatelyAvailable() check. Check return available, while method block. proper of add blocking version of method getBufferBuilder() (or rename existing getBufferBuilderBlocking() implement new getBufferBuilder() blocking) ResultPartition (and BufferPool + LocalBufferPool). easy, blocking methods for requesting memory segments</technical_language>

Target:
public BufferBuilder getBufferBuilder() throws IOException, InterruptedException { BufferBuilder builder = targetPartition.tryGetBufferBuilder(); if (builder == null) { long start = System.currentTimeMillis(); builder = targetPartition.getBufferBuilder(); idleTimeMsPerSecond.markEvent(System.currentTimeMillis() - start); } return builder; }
Source:
<code>public Optional<ElderData> createFrom(DataHolder dataHolder) { <START> if (dataHolder.supports(Keys.ELDER_GUARDIAN)) { <END> return Optional.<ElderData>of(new SpongeElderData(dataHolder.get(Keys.ELDER_GUARDIAN).get())); } return Optional.absent(); }</code><technical_language>delegate data builder processor here. This data processor's createFrom(DataHolder) method</technical_language>

Target:
public Optional<ElderData> createFrom(DataHolder dataHolder) { if (dataHolder instanceof EntityGuardian) { return Optional.of(new SpongeElderData(((EntityGuardian) dataHolder).isElder())); } return Optional.empty(); }
Source:
<code><START> private Boolean processOutput(CallContext callContext){ <END> logger.trace("output endpoint={} count={} state={}", getEndpointPath(), getCallCount(), callContext.getEndpointState()); InputStream[] output = getOutputStream(); processOutputBatch(output, getOutputListener()); switch(getPhase()) { case INTERRUPTING: setPhase(WorkPhase.INTERRUPTED); logger.info("output interrupted endpoint={} count={} work={}", getEndpointPath(), getCallCount(), getWorkUnit()); return false; case RUNNING: if (output == null || output.length == 0) { setPhase(WorkPhase.COMPLETED); logger.info("output completed endpoint={} count={} work={}", getEndpointPath(), getCallCount(), callContext.getWorkUnit()); return false; } return true; case INTERRUPTED: case COMPLETED: throw new IllegalStateException( "cannot process more output as current phase is " + getPhase().name()); default: throw new MarkLogicInternalException( "unexpected state for "+getEndpointPath()+" during loop: "+getPhase().name() ); } }</code><technical_language>return lower-case primitive boolean instead of Boolean object? Is a reason autobox</technical_language>

Target:
private boolean processOutput(CallContext callContext){ logger.trace("output endpoint={} count={} state={}", getEndpointPath(), getCallCount(), callContext.getEndpointState()); InputStream[] output = getOutputStream(); processOutputBatch(output, getOutputListener()); switch(getPhase()) { case INTERRUPTING: setPhase(WorkPhase.INTERRUPTED); logger.info("output interrupted endpoint={} count={} work={}", getEndpointPath(), getCallCount(), getWorkUnit()); return false; case RUNNING: if (output == null || output.length == 0) { setPhase(WorkPhase.COMPLETED); logger.info("output completed endpoint={} count={} work={}", getEndpointPath(), getCallCount(), callContext.getWorkUnit()); return false; } return true; case INTERRUPTED: case COMPLETED: throw new IllegalStateException( "cannot process more output as current phase is " + getPhase().name()); default: throw new MarkLogicInternalException( "unexpected state for "+getEndpointPath()+" during loop: "+getPhase().name() ); } }
Source:
<code>public static List<CharSequence> truncateCommonSubdir(@NonNull final List<CharSequence> directories) { if (directories.size() < 2) { return directories; } final String firstDir = directories.get(0).toString(); String commonEnding = null; int offset = 0; LOOP: while (true) { final String newEnding = firstDir.substring(firstDir.lastIndexOf('/', firstDir.length() - offset)); for (int i = 1; i < directories.size(); i++) { if (!directories.get(i).toString().endsWith(newEnding)) { break LOOP; } } commonEnding = newEnding; offset = commonEnding.length() + 1; } final List<CharSequence> truncatedDirs = new ArrayList<>(directories.size()); for (final CharSequence title : directories) { CharSequence truncated = title; <START> if (commonEnding != null) { <END> truncated = title.subSequence(0, title.length() - commonEnding.length() + 1) + "\u2026"; } truncatedDirs.add(truncated); } return truncatedDirs; }</code><technical_language>condition is loop invariant, test loop simply return directories if commonEnding is null</technical_language>

Target:
public static List<CharSequence> truncateCommonSubdir(@NonNull final List<CharSequence> directories) { if (directories.size() < 2) { return directories; } String commonEnding = directories.get(0).toString(); for (int i = 1; i < directories.size(); i++) { final String directory = directories.get(i).toString(); while (!directory.endsWith(commonEnding)) { final int offset = commonEnding.indexOf('/', 1); if (offset == -1) { return directories; } commonEnding = commonEnding.substring(offset); } } final List<CharSequence> truncatedDirs = new ArrayList<>(directories.size()); for (final CharSequence title : directories) { truncatedDirs.add(title.subSequence(0, title.length() - commonEnding.length() + 1) + "\u2026"); } return truncatedDirs; }