auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private PGPSecretKey findSecretKeyInLegacySecring(String signingkey, Path secringFile) throws IOException, PGPException { try (InputStream in = newInputStream(secringFile)) { PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection( PGPUtil.getDecoderStream(new BufferedInputStream(in)), new JcaKeyFingerprintCalculator()); Iterator<PGPSecretKeyRing> keyrings = pgpSec.getKeyRings(); while (keyrings.hasNext()) { PGPSecretKeyRing keyRing = keyrings.next(); Iterator<PGPSecretKey> keys = keyRing.getSecretKeys(); while (keys.hasNext()) { PGPSecretKey key = keys.next(); String fingerprint = Hex .toHexString(key.getPublicKey().getFingerprint()); if (fingerprint.endsWith(signingkey)) { return key; } Iterator<String> userIDs = key.getUserIDs(); while (userIDs.hasNext()) { String userId = userIDs.next(); <START> if (userId.toLowerCase() <END> .contains(signingKey.toLowerCase())) { return key; } } } } } throw new PGPException( "gpg failed to find secret-key which matches provided keyID: " + signingkey); }</code><technical_language>Locale.ROOT prevent surprises in Turkey <LINK_0></technical_language>

Target:
private PGPSecretKey findSecretKeyInLegacySecring(String signingkey, Path secringFile) throws IOException, PGPException { try (InputStream in = newInputStream(secringFile)) { PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection( PGPUtil.getDecoderStream(new BufferedInputStream(in)), new JcaKeyFingerprintCalculator()); Iterator<PGPSecretKeyRing> keyrings = pgpSec.getKeyRings(); while (keyrings.hasNext()) { PGPSecretKeyRing keyRing = keyrings.next(); Iterator<PGPSecretKey> keys = keyRing.getSecretKeys(); while (keys.hasNext()) { PGPSecretKey key = keys.next(); String fingerprint = Hex .toHexString(key.getPublicKey().getFingerprint()); if (fingerprint.endsWith(signingkey)) { return key; } Iterator<String> userIDs = key.getUserIDs(); while (userIDs.hasNext()) { String userId = userIDs.next(); if (containsSigningKey(userId)) { return key; } } } } } throw new PGPException(MessageFormat .format(JGitText.get().gpgNoSecretKeyFound, signingKey)); }
Source:
<code>public ServiceLoaderSupplier(final Class<E> service, final ClassLoader classLoader) { this.service = service; this.classLoader = classLoader; <START> this.acc = (System.getSecurityManager() != null) ? AccessController.getContext() : null; <END> }</code><technical_language>context captured here, security manager initialized *after* more configurations established</technical_language>

Target:
public ServiceLoaderSupplier(final Class<E> service, final ClassLoader classLoader) { this.service = service; this.classLoader = classLoader; this.acc = AccessController.getContext() ; }
Source:
<code>private void updateAccount(final String selector, final Account account) { final SqlSession session = sessions.openSession(); try { session.update(selector, toMap(account)); session.commit(); } finally { session.close(); } Iterator<AuthToken> iterator = account.getAuthToken().iterator(); while(iterator.hasNext()){ AuthToken token = iterator.next(); <START> System.out.println("Updating Account tokens token:"+token); <END> addAuthToken(new AuthToken(account.getSid(), token.getAuthToken(), token.getDescription())); } }</code><technical_language>Another system out</technical_language>

Target:
private void updateAccount(final String selector, final Account account) { final SqlSession session = sessions.openSession(); try { session.update(selector, toMap(account)); session.commit(); } finally { session.close(); } Iterator<AuthToken> iterator = account.getAuthToken().iterator(); while(iterator.hasNext()){ AuthToken token = iterator.next(); addAuthToken(new AuthToken(account.getSid(), token.getAuthToken(), token.getDescription())); } }
Source:
<code>public ValidationResult networkNameNotUsed() { for (Network otherNetwork : getNetworks()) { if (otherNetwork.getName().equals(network.getName()) && !otherNetwork.getId().equals(network.getId())) { return new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_NETWORK_NAME_IN_USE, <START> String.format("$NetworkName %s", network.getName())); <END> } } return ValidationResult.VALID; }</code><technical_language>this extracted a method appears in next method, i.e. getNetworkNameReplacement()</technical_language>

Target:
public ValidationResult networkNameNotUsed() { for (Network otherNetwork : getNetworks()) { if (otherNetwork.getName().equals(network.getName()) && !otherNetwork.getId().equals(network.getId())) { return new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_NETWORK_NAME_IN_USE, getNetworkNameReplacement()); } } return ValidationResult.VALID; }
Source:
<code>public List<SMREntry> current() { ILogData data = streamView.current(); if (data == null || data.getType() != DataType.DATA || !(data.getPayload(runtime) instanceof ISMRConsumable)) { <START> return new ArrayList<>(); <END> } return ((ISMRConsumable) data.getPayload(runtime)).getSMRUpdates(streamView.getId()); }</code><technical_language>Collections.emptyList() instead</technical_language>

Target:
public List<SMREntry> current() { ILogData data = streamView.current(); if (data == null || data.getType() != DataType.DATA || !(data.getPayload(runtime) instanceof ISMRConsumable)) { return Collections.emptyList(); } return ((ISMRConsumable) data.getPayload(runtime)).getSMRUpdates(streamView.getId()); }
Source:
<code>private static Map<String, String> readPairs(byte[] buff, int start, int end) throws TException { Map<String, String> headers = new HashMap<>(); int i = start; while (i < end) { try { int nameSize = ProtocolUtils.readInt(buff, i); i += 4; if (i > end || i + nameSize > end) { throw new FProtocolException(TProtocolException.INVALID_DATA, "invalid protocol header name"); } byte[] nameBuff = Arrays.copyOfRange(buff, i, nameSize + i); i += nameSize; String name = new String(nameBuff, "UTF-8"); int valueSize = ProtocolUtils.readInt(buff, i); i += 4; if (i > end || i + valueSize > end) { throw new FProtocolException(FProtocolException.INVALID_DATA, "invalid protocol header value"); } byte[] valueBuff = Arrays.copyOfRange(buff, i, valueSize + i); i += valueSize; String value = new String(valueBuff, "UTF-8"); headers.put(name, value); } catch (IOException e) { <START> throw new FProtocolException(FProtocolException.UNKNOWN, "could not read header bytes", e); <END> } } return headers; }</code><technical_language>I this is a transport exception (read error)</technical_language>

Target:
private static Map<String, String> readPairs(byte[] buff, int start, int end) throws TException { Map<String, String> headers = new HashMap<>(); int i = start; while (i < end) { try { int nameSize = ProtocolUtils.readInt(buff, i); i += 4; if (i > end || i + nameSize > end) { throw new FProtocolException(TProtocolException.INVALID_DATA, "invalid protocol header name"); } byte[] nameBuff = Arrays.copyOfRange(buff, i, nameSize + i); i += nameSize; String name = new String(nameBuff, "UTF-8"); int valueSize = ProtocolUtils.readInt(buff, i); i += 4; if (i > end || i + valueSize > end) { throw new FProtocolException(FProtocolException.INVALID_DATA, "invalid protocol header value"); } byte[] valueBuff = Arrays.copyOfRange(buff, i, valueSize + i); i += valueSize; String value = new String(valueBuff, "UTF-8"); headers.put(name, value); } catch (IOException e) { throw new TTransportException(FProtocolException.UNKNOWN, "could not read header bytes", e); } } return headers; }
Source:
<code>void drawDirection(final Canvas canvas, final MapProjectionImpl projection) { if (currentCoords == null) { return; } if (!Settings.isMapDirection()) { return; } if (linePaint == null) { linePaint = new Paint(); linePaint.setAntiAlias(true); linePaint.setStrokeWidth(width); linePaint.setStyle(Paint.Style.STROKE); linePaint.setColor(0xD0EB391E); } final Geopoint[] routingPoints = Routing.getTrack(currentCoords, destinationCoords); final ArrayList<Point> pixelPoints = new ArrayList<>(); <START> for (final Geopoint geopoint : routingPoints) { <END> pixelPoints.add(translateToPixels(projection, geopoint)); } CanvasUtils.drawPath(pixelPoints, canvas, linePaint); }</code><technical_language>routingPoints inlined there</technical_language>

Target:
void drawDirection(final Canvas canvas, final MapProjectionImpl projection) { if (currentCoords == null) { return; } if (!Settings.isMapDirection()) { return; } if (linePaint == null) { linePaint = new Paint(); linePaint.setAntiAlias(true); linePaint.setStrokeWidth(width); linePaint.setStyle(Paint.Style.STROKE); linePaint.setColor(0xD0EB391E); } final Geopoint[] routingPoints = Routing.getTrack(currentCoords, destinationCoords); final ArrayList<Point> pixelPoints = new ArrayList<>(routingPoints.length); for (final Geopoint geopoint : routingPoints) { pixelPoints.add(translateToPixels(projection, geopoint)); } CanvasUtils.drawPath(pixelPoints, canvas, linePaint); }
Source:
<code>public SequencerPartitionContainer saveSequencerPartitionContainer(SequencerPartitionContainer container) throws IOException { if (sequencerPartitionContainerStore != null) { if (container.getId() == SequencerPartitionContainerImpl.UNSAVED_ID) { container.setSecurityProfile(securityProfileStore.get(securityProfileStore.save(container.getSecurityProfile()))); container.setPlatform(platformStore.get(container.getPlatform().getId())); <START> container.setLastModifier(securityStore.getUserById(getCurrentUser().getUserId())); <END> Date now = new Date(); if (container.getCreationTime() == null) { container.setCreationTime(now); container.setLastModified(now); } else if (container.getLastModified() == null) { container.setLastModified(now); } return sequencerPartitionContainerStore.save(container); } else { SequencerPartitionContainer managed = getSequencerPartitionContainerById(container.getId()); updateContainer(container, managed); managed.setLastModifier(securityStore.getUserById(getCurrentUser().getUserId())); managed.setLastModified(new Date()); return sequencerPartitionContainerStore.save(managed); } } else { throw new IOException("No sequencerPartitionContainerStore available. Check that it has been declared in the Spring config."); } }</code><technical_language>set creator</technical_language>

Target:
public SequencerPartitionContainer saveSequencerPartitionContainer(SequencerPartitionContainer container) throws IOException { if (sequencerPartitionContainerStore != null) { if (container.getId() == SequencerPartitionContainerImpl.UNSAVED_ID) { container.setSecurityProfile(securityProfileStore.get(securityProfileStore.save(container.getSecurityProfile()))); container.setPlatform(platformStore.get(container.getPlatform().getId())); container.setLastModifier(securityStore.getUserById(getCurrentUser().getUserId())); Date now = new Date(); if (container.getCreationTime() == null) { container.setCreationTime(now); container.setCreator(securityStore.getUserById(getCurrentUser().getUserId())); container.setLastModified(now); } else if (container.getLastModified() == null) { container.setLastModified(now); } return sequencerPartitionContainerStore.save(container); } else { SequencerPartitionContainer managed = getSequencerPartitionContainerById(container.getId()); updateContainer(container, managed); managed.setLastModifier(securityStore.getUserById(getCurrentUser().getUserId())); managed.setLastModified(new Date()); return sequencerPartitionContainerStore.save(managed); } } else { throw new IOException("No sequencerPartitionContainerStore available. Check that it has been declared in the Spring config."); } }
Source:
<code>public Access authorize( AuthenticationResult authenticationResult, Resource resource, Action action ) { if (authenticationResult == null) { <START> return new Access(false); <END> } String identity = null; if (remapAuthNames) { String authorizationName = dbConnector.getAuthorizationNameFromAuthenticationName( authenticationResult.getIdentity() ); if (authorizationName == null) { return new Access(false); } else { identity = authorizationName; } } else { identity = authenticationResult.getIdentity(); } List<Map<String, Object>> permissions = dbConnector.getPermissionsForUser(identity); for (Map<String, Object> permission : permissions) { if (permissionCheck(resource, action, permission)) { return new Access(true); } } return new Access(false); }</code><technical_language>error message 'null authenticationResult'</technical_language>

Target:
public Access authorize( AuthenticationResult authenticationResult, Resource resource, Action action ) { if (authenticationResult == null) { throw new IAE("WTF? authenticationResult should never be null."); } List<Map<String, Object>> permissions = dbConnector.getPermissionsForUser(dbConfig.getDbPrefix(), authenticationResult.getIdentity()); for (Map<String, Object> permission : permissions) { if (permissionCheck(resource, action, permission)) { return new Access(true); } } return new Access(false); }
Source:
<code>private TableViewerColumn createTableViewerColumn(String title, int bound, final int colIndex, final PerfDiffTableSorter tableSorter, final Table table) { final TableViewerColumn viewerColumn = new TableViewerColumn( tableviewer, SWT.NONE); final TableColumn column = viewerColumn.getColumn(); column.setText(title); column.setWidth(bound); column.setResizable(true); column.setMoveable(true); column.addSelectionListener(new SelectionAdapter() { <START> public void widgetSelected(SelectionEvent e) { <END> tableSorter.setColumnIndex(colIndex); int dir = table.getSortDirection(); if (table.getSortColumn() == column) { dir = (dir == SWT.UP) ? SWT.DOWN : SWT.UP; } else { dir = SWT.DOWN; } table.setSortDirection(dir); table.setSortColumn(column); tableviewer.refresh(); } }); return viewerColumn; }</code><technical_language>Missing @Override</technical_language>

Target:
private TableViewerColumn createTableViewerColumn(String title, int bound, final int colIndex, final PerfDiffTableSorter tableSorter, final Table table) { final TableViewerColumn viewerColumn = new TableViewerColumn( tableviewer, SWT.NONE); final TableColumn column = viewerColumn.getColumn(); column.setText(title); column.setWidth(bound); column.setResizable(true); column.setMoveable(true); column.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { tableSorter.setColumnIndex(colIndex); int dir = table.getSortDirection(); if (table.getSortColumn() == column) { dir = (dir == SWT.UP) ? SWT.DOWN : SWT.UP; } else { dir = SWT.DOWN; } table.setSortDirection(dir); table.setSortColumn(column); tableviewer.refresh(); } }); return viewerColumn; }
Source:
<code>@Test public void decorateSimpleRabbitListenerContainerFactory_appends_as_first_when_absent() { SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory(); factory.setAdviceChain(new CacheInterceptor()); assertThat(rabbitTracing.decorateSimpleRabbitListenerContainerFactory(factory).getAdviceChain()) .hasSize(2) <START> .matches(adviceArray -> asList(adviceArray).get(0) instanceof TracingRabbitListenerAdvice); <END> }</code><technical_language>this work? (also removing import) suggestion .matches(adviceArray -> adviceArray[0] instanceof TracingRabbitListenerAdvice);</technical_language>

Target:
@Test public void decorateSimpleRabbitListenerContainerFactory_appends_as_first_when_absent() { SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory(); factory.setAdviceChain(new CacheInterceptor()); assertThat(rabbitTracing.decorateSimpleRabbitListenerContainerFactory(factory).getAdviceChain()) .hasSize(2) .matches(adviceArray -> adviceArray[0] instanceof TracingRabbitListenerAdvice); }
Source:
<code>public List subList(int fromIndex, int toIndex) { if (fromIndex < 0) { throw new IndexOutOfBoundsException("fromIndex = " + fromIndex); } if (fromIndex > toIndex) { throw new IllegalArgumentException("fromIndex(" + fromIndex + ") > toIndex(" + toIndex + ")"); } if (fromIndex == toIndex) { return new EmptyRange(from); } final Iterator it = iterator(); Object toValue = it.next(); int i = 0; <START> for (; i < fromIndex; i++) { <END> if (!it.hasNext()) { throw new IndexOutOfBoundsException("Index: " + i + " is too big for range: " + this); } toValue = it.next(); } final Object fromValue = toValue; for (; i < toIndex - 1; i++) { if (!it.hasNext()) { throw new IndexOutOfBoundsException("Index: " + i + " is too big for range: " + this); } toValue = it.next(); } return new ObjectRange((Comparable) fromValue, (Comparable) toValue, reverse); }</code><technical_language>before, iterator() is synchronized</technical_language>

Target:
public List<Comparable> subList(int fromIndex, int toIndex) { if (fromIndex < 0) { throw new IndexOutOfBoundsException("fromIndex = " + fromIndex); } if (fromIndex > toIndex) { throw new IllegalArgumentException("fromIndex(" + fromIndex + ") > toIndex(" + toIndex + ")"); } if (fromIndex == toIndex) { return new EmptyRange<Comparable>(from); } final Iterator<Comparable> iter = new LazySteppingIterator(this, 1); Comparable toValue = iter.next(); int i = 0; for (; i < fromIndex; i++) { if (!iter.hasNext()) { throw new IndexOutOfBoundsException("Index: " + i + " is too big for range: " + this); } toValue = iter.next(); } final Comparable fromValue = toValue; for (; i < toIndex - 1; i++) { if (!iter.hasNext()) { throw new IndexOutOfBoundsException("Index: " + i + " is too big for range: " + this); } toValue = iter.next(); } return new ObjectRange(fromValue, toValue, reverse); }
Source:
<code>public Set<String> getSupportedExtensions() { <START> return supportedExts; <END> }</code><technical_language>simply return 'null' supportedExts is set anywhere, null anyway... a result variable declared all</technical_language>

Target:
public Set<String> getSupportedExtensions() { return null; }
Source:
<code>public static <I, O> LazyMapList<I, O> of(List<I> list, Function<? super I, ? extends O> mapper) { <START> if (!(list instanceof RandomAccess)) { <END> throw new IllegalArgumentException( "The argument of the List type must support " + "fast (generally constant time) random access."); } return new LazyMapList<>(list, mapper); }</code><technical_language>Btw if this restriction is necessary. E.g. if implementation of get of LinkedList is "extra" slow-down caused LazyMapList</technical_language>

Target:
public static <I, O> LazyMapList<I, O> of(List<I> list, Function<? super I, ? extends O> mapper) { return new LazyMapList<>(list, mapper); }
Source:
<code>public CallEnv(Env caller, Continuation returnAddress, SourceLocation loc, int localsCount) { this.caller = caller; this.returnAddress = returnAddress; this.callSiteLoc = loc; this.invoker = caller==null ? Invoker.INSTANCE : caller.getInvoker(); assert returnAddress!=null; if (localsCount <= 0) { types = Collections.EMPTY_MAP; } else { types = Maps.newHashMapWithExpectedSize(localsCount); } depth = (caller instanceof DepthTrackingEnv) ? depth = ((DepthTrackingEnv) caller).getDepth() + 1 : 1; if (depth > DepthTrackingEnv.MAX_LEGAL_DEPTH) { <START> throw new StackOverflowError("Excessively nested blocks/function calls exceed limit of"+DepthTrackingEnv.MAX_LEGAL_DEPTH+":"+depth); <END> } }</code><technical_language>need a space "of". do is a in point user's code</technical_language>

Target:
public CallEnv(Env caller, Continuation returnAddress, SourceLocation loc, int localsCount) { this.caller = caller; this.returnAddress = returnAddress; this.callSiteLoc = loc; this.invoker = caller==null ? Invoker.INSTANCE : caller.getInvoker(); assert returnAddress!=null; if (localsCount <= 0) { types = Collections.EMPTY_MAP; } else { types = Maps.newHashMapWithExpectedSize(localsCount); } depth = (caller instanceof DepthTrackingEnv) ? ((DepthTrackingEnv) caller).getDepth() + 1 : 1; }
Source:
<code>public void handlePersistForm(MotechEvent event) { Map<String, Object> params = event.getParameters(); String title = (String) params.get(EventParameters.FORM_TITLE); String configName = (String) params.get(EventParameters.CONFIGURATION_NAME); String instanceId = (String) params.get(EventParameters.INSTANCE_ID); <START> if (title != null && configName != null && instanceId != null) { <END> if (formInstanceService.getByInstanceId(instanceId) != null) { LOGGER.error("Form Instance with ID: " + instanceId + " already exists. Discarding form instance data"); } else { LOGGER.debug("Saving form instance.Title: " + title + " ConfigName: " + configName + " Instance ID: " + instanceId); FormDefinition formDefinition = formDefinitionService.findByConfigurationNameAndTitle(configName, title); if (formDefinition != null) { FormInstanceBuilder builder = new FormInstanceBuilder(formDefinition, params, instanceId); FormInstance instance = builder.build(); formInstanceService.create(instance); } } } }</code><technical_language>log if conditions met</technical_language>

Target:
public void handlePersistForm(MotechEvent event) { Map<String, Object> params = event.getParameters(); String title = (String) params.get(EventParameters.FORM_TITLE); String configName = (String) params.get(EventParameters.CONFIGURATION_NAME); String instanceId = (String) params.get(EventParameters.INSTANCE_ID); if (title != null && configName != null && instanceId != null) { if (formInstanceService.getByInstanceId(instanceId) != null) { LOGGER.error("Form Instance with ID: " + instanceId + " already exists. Discarding form instance data"); } else { FormDefinition formDefinition = formDefinitionService.findByConfigurationNameAndTitle(configName, title); if (formDefinition != null) { persistFormInstance(formDefinition, params, instanceId); } else { LOGGER.error("Unable to save form. Form definition does not exist. Configuration name: " + configName + " Title: " + title); } } } else { LOGGER.error("Unable to save form. Event is missing required parameters", event); } }
Source:
<code>public void init() { try { <START> log.info("Search using solr on: "+ getSolrUrl()); <END> } catch (IllegalStateException e) { log.error(e.getMessage()); } }</code><technical_language>a clear separation call getSolrUrl() creation of a log</technical_language>

Target:
public void init() { try { String url = getSolrUrl(); log.info("Search using solr on: "+ url); } catch (IllegalStateException e) { log.error(e.getMessage()); } }
Source:
<code>protected void tearDown() throws Exception { super.tearDown(); <START> for (File file : toDelete) delete(file); <END> toDelete.clear(); FailingMetadataRepositoryFactory.FAIL = false; }</code><technical_language>add block</technical_language>

Target:
protected void tearDown() throws Exception { super.tearDown(); for (File file : toDelete) { delete(file); } toDelete.clear(); FailingMetadataRepositoryFactory.FAIL = false; }
Source:
<code>public void testCSVBundle() throws Exception { ServiceReference refs[] = m_bundle.getRegisteredServices(); ServiceReference<AbstractFormatterFactory> reference = refs[0]; AbstractFormatterFactory o = m_bundle.getBundleContext().getService(reference); Properties prop = new Properties(); prop.setProperty("format", "csv"); AbstractFormatter formatter = o.create(prop); Object[] results = formatter.transform("12,10.05,test"); <START> assertEquals(results.length, 3); <END> }</code><technical_language>verify actual values in results array</technical_language>

Target:
public void testCSVBundle() throws Exception { ServiceReference refs[] = m_bundle.getRegisteredServices(); ServiceReference<AbstractFormatterFactory> reference = refs[0]; AbstractFormatterFactory o = m_bundle.getBundleContext().getService(reference); Properties prop = new Properties(); Formatter formatter = o.create("csv", prop); Object[] results = formatter.transform("12,10.05,test"); assertEquals(results.length, 3); assertEquals(results[0], "12"); assertEquals(results[1], "10.05"); assertEquals(results[2], "test"); }
Source:
<code>public void configureMiniCluster(MiniAccumuloConfigImpl cfg, Configuration hadoopCoreSite) { String keyPath = System.getProperty("user.dir") + "/target/mini-tests/WriteAheadLogEncryptedIT-testkeyfile"; cfg.setProperty(Property.TABLE_CRYPTO_SERVICE, "org.apache.accumulo.core.security.crypto.impl.AESCryptoService"); cfg.setProperty(TABLE_CRYPTO_PREFIX.getKey() + "kekId", keyPath); <START> cfg.setProperty(TABLE_CRYPTO_PREFIX.getKey() + "keyManager", "uri"); <END> cfg.setProperty(Property.TSERV_WALOG_MAX_SIZE, "2M"); cfg.setProperty(Property.GC_CYCLE_DELAY, "1"); cfg.setProperty(Property.GC_CYCLE_START, "1"); cfg.setProperty(Property.MASTER_RECOVERY_DELAY, "1s"); cfg.setProperty(Property.TSERV_MAJC_DELAY, "1"); cfg.setProperty(Property.INSTANCE_ZK_TIMEOUT, "15s"); hadoopCoreSite.set("fs.file.impl", RawLocalFileSystem.class.getName()); try { Path keyFile = new Path(keyPath); FileSystem fs = FileSystem.getLocal(CachedConfiguration.getInstance()); fs.delete(keyFile, true); if (fs.createNewFile(keyFile)) log.info("Created keyfile at {}", keyPath); else log.error("Failed to create key file at {}", keyPath); try (FSDataOutputStream out = fs.create(keyFile)) { out.writeUTF("sixteenbytekey"); } } catch (Exception e) { log.error("Exception during configure", e); } }</code><technical_language>keyManager property is set uri. need set</technical_language>

Target:
public void configureMiniCluster(MiniAccumuloConfigImpl cfg, Configuration hadoopCoreSite) { String keyPath = System.getProperty("user.dir") + "/target/mini-tests/WriteAheadLogEncryptedIT-testkeyfile"; cfg.setProperty(Property.INSTANCE_CRYPTO_SERVICE, "org.apache.accumulo.core.security.crypto.impl.AESCryptoService"); cfg.setProperty(INSTANCE_CRYPTO_PREFIX.getKey() + "kekId", keyPath); cfg.setProperty(INSTANCE_CRYPTO_PREFIX.getKey() + "keyManager", "uri"); cfg.setProperty(Property.TSERV_WALOG_MAX_SIZE, "2M"); cfg.setProperty(Property.GC_CYCLE_DELAY, "1"); cfg.setProperty(Property.GC_CYCLE_START, "1"); cfg.setProperty(Property.MASTER_RECOVERY_DELAY, "1s"); cfg.setProperty(Property.TSERV_MAJC_DELAY, "1"); cfg.setProperty(Property.INSTANCE_ZK_TIMEOUT, "15s"); hadoopCoreSite.set("fs.file.impl", RawLocalFileSystem.class.getName()); try { Path keyFile = new Path(keyPath); FileSystem fs = FileSystem.getLocal(CachedConfiguration.getInstance()); fs.delete(keyFile, true); if (fs.createNewFile(keyFile)) log.info("Created keyfile at {}", keyPath); else log.error("Failed to create key file at {}", keyPath); try (FSDataOutputStream out = fs.create(keyFile)) { out.writeUTF("sixteenbytekey"); } } catch (Exception e) { log.error("Exception during configure", e); } }
Source:
<code><START> public static Set<FieldDeclaration> mergeFDs( DirectCompilerResult... sets ) { <END> Set<FieldDeclaration> result = new HashSet<>(); for ( DirectCompilerResult fs : sets ) { result.addAll(fs.getFieldDeclarations()); } return result; }</code><technical_language>Formatting of ( DirectCompilerResult... sets ), (DirectCompilerResult... sets)</technical_language>

Target:
public static Set<FieldDeclaration> mergeFDs( DirectCompilerResult... sets ) { return mergeFDs(Arrays.asList(sets)); }
Source:
<code>private void removeAllAnnotations() { final Set<IAnnotationModel> annotationModels = new HashSet<>(); for (final History history : sourceToHistory.values()) <START> while (!history.entries.isEmpty()) <END> annotationModels.add(history.entries.peek().annotation.getModel()); for (final IAnnotationModel annotationModel : annotationModels) annotationModelHelper.removeAnnotationsFromModel( annotationModel, (a) -> a instanceof ContributionAnnotation); }</code><technical_language>Is this eternal loop? def. of peek Retrieves, remove, head (first element) of this list.. simply for (HistoryEntry entry : history.entries)</technical_language>

Target:
private void removeAllAnnotations() { removeFromHistoryAndAnnotationModel(sourceToHistory.values()); }
Source:
<code>public List<Cookie> getAll() { try { lock.lock(); final boolean[] removeExpired = {false}; List<Cookie> result = cookieJar .entrySet() <START> .parallelStream() <END> .filter(pair -> { boolean hasCookieExpired = hasCookieExpired(pair.getValue().cookie, pair.getValue().createdAt); if (hasCookieExpired && !removeExpired[0]) removeExpired[0] = true; return !hasCookieExpired; }) .map(pair -> pair.getValue().cookie) .collect(Collectors.toList()); if (removeExpired[0]) removeExpired(); return result; } finally { lock.unlock(); } }</code><technical_language>do need a parallelStream here? overkill, more users a cookies time</technical_language>

Target:
public List<Cookie> getAll() { final boolean[] removeExpired = {false}; List<Cookie> result = cookieJar .entrySet() .stream() .filter(pair -> { boolean hasCookieExpired = hasCookieExpired(pair.getValue().cookie, pair.getValue().createdAt); if (hasCookieExpired && !removeExpired[0]) removeExpired[0] = true; return !hasCookieExpired; }) .map(pair -> pair.getValue().cookie) .collect(Collectors.toList()); if (removeExpired[0]) removeExpired(); return result; }
Source:
<code>public Object getObjectProperty(String key) { <START> if (key.startsWith(AMQPMessageSupport.JMS_AMQP_MESSAGE_ANNOTATION_PREFIX)) { <END> return getMessageAnnotation(key.substring(AMQPMessageSupport.JMS_AMQP_MESSAGE_ANNOTATION_PREFIX.length() - 1)); } else if (key.equals(MessageUtil.TYPE_HEADER_NAME.toString())) { if (properties != null) { return properties.getSubject(); } } else if (key.equals(MessageUtil.CONNECTION_ID_PROPERTY_NAME.toString())) { return getConnectionID(); } else if (key.equals(MessageUtil.JMSXGROUPID)) { return getGroupID(); } else if (key.equals(MessageUtil.JMSXGROUPSEQ)) { return getGroupSequence(); } else if (key.equals(MessageUtil.JMSXUSERID)) { return getAMQPUserID(); } else if (key.equals(MessageUtil.CORRELATIONID_HEADER_NAME.toString())) { if (properties != null && properties.getCorrelationId() != null) { return AMQPMessageIdHelper.INSTANCE.toCorrelationIdString(properties.getCorrelationId()); } } else { Object value = getApplicationPropertiesMap(false).get(key); if (value instanceof UnsignedInteger || value instanceof UnsignedByte || value instanceof UnsignedLong || value instanceof UnsignedShort) { return ((Number)value).longValue(); } else { return value; } } return null; }</code><technical_language>This right all, specification reserves Annotations Symbol UnsignedLong keys for broker populating annotations violate that. client other intermediary rights (technically required) close connection receiving a message broker specific message annotations spec: <- 3.2.10 Annotations - annotations type is a map keys restricted of type symbol of type ulong. ulong keys, symbolic keys beginning "x-" reserved. Keys beginning "x-opt-" if understood. receiving annotation key is understood, "x-opt", receiving AMQP container detach link a not-implemented error</technical_language>

Target:
public final Object getObjectProperty(String key) { if (key.equals(MessageUtil.TYPE_HEADER_NAME.toString())) { if (properties != null) { return properties.getSubject(); } } else if (key.equals(MessageUtil.CONNECTION_ID_PROPERTY_NAME.toString())) { return getConnectionID(); } else if (key.equals(MessageUtil.JMSXGROUPID)) { return getGroupID(); } else if (key.equals(MessageUtil.JMSXGROUPSEQ)) { return getGroupSequence(); } else if (key.equals(MessageUtil.JMSXUSERID)) { return getAMQPUserID(); } else if (key.equals(MessageUtil.CORRELATIONID_HEADER_NAME.toString())) { if (properties != null && properties.getCorrelationId() != null) { return AMQPMessageIdHelper.INSTANCE.toCorrelationIdString(properties.getCorrelationId()); } } else { Object value = getApplicationPropertiesMap(false).get(key); if (value instanceof UnsignedInteger || value instanceof UnsignedByte || value instanceof UnsignedLong || value instanceof UnsignedShort) { return ((Number)value).longValue(); } else { return value; } } return null; }
Source:
<code>public Href path(final String suffix) { final String slash = "/"; <START> final StringBuilder sbr = new StringBuilder(this.uri.toString()); <END> if ( !this.uri.toString().endsWith(slash) && !suffix.startsWith(slash) ) { sbr.append(slash); } sbr.append(Href.encode(suffix)); return new Href( URI.create(sbr.toString()), this.params ); }</code><technical_language>I more elegant do this: java return new Href( URI.create( new StringBuilder(this.uri.toString().replaceAll("/$", "")) .append('/') .append(Href.encode(suffix)).toString() ), URI.create(sbr.toString()), this.params ); think</technical_language>

Target:
public Href path(final String suffix) { return new Href( URI.create( new StringBuilder(this.uri.toString().replaceAll("/$", "")) .append('/') .append(Href.encode(suffix)).toString() ), this.params ); }
Source:
<code>private void receiveCommandsToOutputPort() { readerThread = new Thread(new Runnable() { @Override public void run() { try { tcpSocketRead = initTcpSocket(tcpSocketRead); while (!readerThread.isInterrupted()) { String result = readFromSocket(tcpSocketRead, 0); opOutput.sendData(ConversionUtils.stringToBytes(result)); logger.log(Level.INFO, "IRTrans received: " + result); } } catch (Exception e) { logger.log(Level.INFO, "reading from socket to receive command stopped"); <START> } <END> } }); readerThread.start(); }</code><technical_language>closing tcpSocketRead done in a finally block here, ensure is closed in case of exception normal interruption. finally { if(tcpSocketRead !=null) tcpSocketRead.close(); }</technical_language>

Target:
private void receiveCommandsToOutputPort() { readerThread = new Thread(new Runnable() { @Override public void run() { try { tcpSocketRead = initTcpSocket(tcpSocketRead); while (!readerThread.isInterrupted()) { String result = readFromSocket(tcpSocketRead, 0); opOutput.sendData(ConversionUtils.stringToBytes(result)); logger.log(Level.INFO, "IRTrans received: " + result); } } catch (Exception e) { logger.log(Level.INFO, "reading from socket to receive command stopped"); } finally { closeTcpSocket(tcpSocketRead); } } }); readerThread.start(); }
Source:
<code><START> public void validateDetailCountGood() { <END> try { concurStandardAccountingExtractService.validateDetailCount(file); assertTrue("We successfully validated counts.", true); } catch (ValidationException ve) { assertTrue("The counts should be been the same.", false); } }</code><technical_language>I tests cleaner more clear if validation methods returned true/false instead of throwing exception. If is a good reason ValidationException I more sense a boolean local variable here, success, is initialized true set false catch. a single assertTrue statement end: assertTrue("The counts same.", success); for tests in this class</technical_language>

Target:
public void validateDetailCountGood() { assertTrue("The counts should be been the same.", concurStandardAccountingValidationService.validateDetailCount(file)); }
Source:
<code>public void processRecord(ComputationContext context, String inputStream, Record record) { BulkStatus status = codec.decode(record.getData()); if (IndexAction.ACTION_NAME.equals(status.getAction()) && BulkStatus.State.COMPLETED.equals(status.getState())) { logIndexing(status); BulkService bulkService = Framework.getService(BulkService.class); BulkCommand command = bulkService.getCommand(status.getId()); if (command != null) { refreshIndexIfNeeded(command); updateAliasIfNeeded(command); } else { <START> log.error(String.format("Command not found for id = %s", status.getId())); <END> } } context.askForCheckpoint(); }</code><technical_language>log4j2</technical_language>

Target:
public void processRecord(ComputationContext context, String inputStream, Record record) { BulkStatus status = codec.decode(record.getData()); if (IndexAction.ACTION_NAME.equals(status.getAction()) && BulkStatus.State.COMPLETED.equals(status.getState())) { logIndexing(status); BulkService bulkService = Framework.getService(BulkService.class); BulkCommand command = bulkService.getCommand(status.getId()); if (command != null) { refreshIndexIfNeeded(command); updateAliasIfNeeded(command); } else { log.error("Command not found for id: {}", status::getId); } } context.askForCheckpoint(); }
Source:
<code><START> public Object getEventName() { return eventData.get("event"); } <END></code><technical_language>suggestion public Object getName() { return eventData.get("event"); } this one. feels redundant prefixing this Event object is a PusherEvent. more consistent swift SDK: <LINK_0> downside is property in JSON object is called event, a confusing if called "name" this object. Do thoughts @jameshfisher</technical_language>

Target:
public String getEventName() { return (String)eventData.get("event"); }
Source:
<code>public IStatus validate(IProject project, String path) { if( fileExists(path)){ return Status.OK_STATUS; } <START> return new Status(IStatus.ERROR, "TmfTraceStub", "File does not exist: " + path) ; <END> }</code><technical_language>PLUGIN_ID</technical_language>

Target:
public IStatus validate(IProject project, String path) { if (fileExists(path)) { return Status.OK_STATUS; } return new Status(IStatus.ERROR, Activator.PLUGIN_ID, Messages.TmfTraceStub_FileNotFound + ": " + path); }
Source:
<code>private void record(final ReadableMap options, final Promise promise) { if (mRecordingPromise == null) { mCamera = RCTCamera.getInstance().acquireCameraInstance(options.getInt("type")); if (null == mCamera) { promise.reject("No camera found."); return; } if (!prepareMediaRecorder(options)) { <START> promise.reject("Fail in prepareMediaRecorder()!"); <END> return; } try { mMediaRecorder.start(); MRStartTime = System.currentTimeMillis(); mRecordingOptions = options; mRecordingPromise = promise; } catch (final Exception ex) { promise.reject("Exception in thread"); return; } } }</code><technical_language>promise rejections include Throwable object argument</technical_language>

Target:
private void record(final ReadableMap options, final Promise promise) { if (mRecordingPromise != null) { return; } mCamera = RCTCamera.getInstance().acquireCameraInstance(options.getInt("type")); if (mCamera == null) { promise.reject(new RuntimeException("No camera found.")); return; } Throwable prepareError = prepareMediaRecorder(options); if (prepareError != null) { promise.reject(prepareError); return; } try { mMediaRecorder.start(); MRStartTime = System.currentTimeMillis(); mRecordingOptions = options; mRecordingPromise = promise; } catch (Exception ex) { Log.e(TAG, "Media recorder start error.", ex); promise.reject(ex); } }
Source:
<code>public void process(JSONRequestContext jsonRequestContext) { CurriculumDAO curriculumDAO = DAOFactory.getInstance().getCurriculumDAO(); Long rowCountLong = jsonRequestContext.getLong("curriculumsTable.rowCount"); if (rowCountLong == null) throw new SmvcRuntimeException(StatusCode.UNDEFINED, "Row count was not defined."); int rowCount = rowCountLong.intValue(); for (int i = 0; i < rowCount; i++) { String colPrefix = "curriculumsTable." + i; Long curriculumId = jsonRequestContext.getLong(colPrefix + ".curriculumId"); String name = jsonRequestContext.getString(colPrefix + ".name"); boolean modified = new Integer(1).equals(jsonRequestContext.getInteger(colPrefix + ".modified")); if (curriculumId == -1) { curriculumDAO.create(name); } else if (modified) { <START> Curriculum curriculum = curriculumDAO.findById(curriculumId); <END> curriculumDAO.updateName(curriculum, name); } } jsonRequestContext.setRedirectURL(jsonRequestContext.getReferer(true)); }</code><technical_language>Check curriculum for null</technical_language>

Target:
public void process(JSONRequestContext jsonRequestContext) { CurriculumDAO curriculumDAO = DAOFactory.getInstance().getCurriculumDAO(); Long rowCountLong = jsonRequestContext.getLong("curriculumsTable.rowCount"); if (rowCountLong == null) throw new SmvcRuntimeException(StatusCode.UNDEFINED, "Row count was not defined."); int rowCount = rowCountLong.intValue(); for (int i = 0; i < rowCount; i++) { String colPrefix = "curriculumsTable." + i; Long curriculumId = jsonRequestContext.getLong(colPrefix + ".curriculumId"); String name = jsonRequestContext.getString(colPrefix + ".name"); boolean modified = new Integer(1).equals(jsonRequestContext.getInteger(colPrefix + ".modified")); if (curriculumId == -1) { curriculumDAO.create(name); } else if (modified) { Curriculum curriculum = curriculumDAO.findById(curriculumId); if (curriculum != null) curriculumDAO.updateName(curriculum, name); else throw new SmvcRuntimeException(StatusCode.UNDEFINED, "Modified curriculum was not found."); } } jsonRequestContext.setRedirectURL(jsonRequestContext.getReferer(true)); }
Source:
<code>public void onStart() { Log.d(TAG, "onStart()"); <START> handler.postDelayed(moveAround, 60000); <END> handler.postDelayed(fadeClock, 30000); }</code><technical_language>is this modification necessary</technical_language>

Target:
public void onStart() { Log.d(TAG, "onStart()"); handler.postDelayed(moveAround, 30000); handler.postDelayed(fadeClock, 30000); }
Source:
<code><START> public Type getClassType(String fullyQualifiedName) { <END> return bytecodeCompleter.loadClass(fullyQualifiedName).type; }</code><technical_language>I spot unit test of one. Especially check this reacts edgecases. (null empty string, existing class, etc.)</technical_language>

Target:
public Type getClassType(String fullyQualifiedName) { return bytecodeCompleter.loadClass(fullyQualifiedName).type(); }
Source:
<code>public void testSessionStartup() throws ObjectFactoryException { int oldLogLevel = Logger.getLogLevel(); Logger.setLogLevel( ILogger.TRACE ); final ISolutionEngine engine = mock( ISolutionEngine.class ); pentahoObjectFactory = mock( IPentahoObjectFactory.class ); when( pentahoObjectFactory.objectDefined( anyString() ) ).thenReturn( true ); when( pentahoObjectFactory.get( this.anyClass(), anyString(), any( IPentahoSession.class ) ) ).thenAnswer( new Answer<Object>() { @Override public ISolutionEngine answer( InvocationOnMock invocation ) throws Throwable { return engine; } } ); PentahoSystem.registerObjectFactory( pentahoObjectFactory ); ISessionStartupAction action = mock( ISessionStartupAction.class ); when( action.getActionOutputScope() ).thenReturn( PentahoSystem.SCOPE_SESSION ); when( action.getSessionType() ).thenReturn( session.getClass().getName() ); when( session.isAuthenticated() ).thenReturn( true ); PentahoSystem.setSessionStartupActions( Arrays.asList( action ) ); PentahoSystem.sessionStartup( session, null ); System.out.flush(); <START> System.out.println( baos.toString() ); <END> assertNotNull( baos ); assertTrue( baos.toString().contains( "Process session startup actions" ) ); Logger.setLogLevel( oldLogLevel ); }</code><technical_language>System.out.println in test</technical_language>

Target:
public void testSessionStartup() throws ObjectFactoryException { int oldLogLevel = Logger.getLogLevel(); Logger.setLogLevel( ILogger.TRACE ); final ISolutionEngine engine = mock( ISolutionEngine.class ); pentahoObjectFactory = mock( IPentahoObjectFactory.class ); when( pentahoObjectFactory.objectDefined( anyString() ) ).thenReturn( true ); when( pentahoObjectFactory.get( this.anyClass(), anyString(), any( IPentahoSession.class ) ) ).thenAnswer( new Answer<Object>() { @Override public ISolutionEngine answer( InvocationOnMock invocation ) throws Throwable { return engine; } } ); PentahoSystem.registerObjectFactory( pentahoObjectFactory ); ISessionStartupAction action = mock( ISessionStartupAction.class ); when( action.getActionOutputScope() ).thenReturn( PentahoSystem.SCOPE_SESSION ); when( action.getSessionType() ).thenReturn( session.getClass().getName() ); when( session.isAuthenticated() ).thenReturn( true ); PentahoSystem.setSessionStartupActions( Arrays.asList( action ) ); PentahoSystem.sessionStartup( session, null ); System.out.flush(); assertNotNull( baos ); assertTrue( baos.toString().contains( "Process session startup actions" ) ); Logger.setLogLevel( oldLogLevel ); }
Source:
<code>protected void handleReceiveSlowConsumerKillMessage(DisconnectConsumerWithKillMessage message) { if (message.getNodeID() != null) { <START> setKilled(true); <END> } }</code><technical_language>called true, sense a kill() method instead</technical_language>

Target:
protected void handleReceiveSlowConsumerKillMessage(DisconnectConsumerWithKillMessage message) { if (message.getNodeID() != null) { kill(); } }
Source:
<code>public void testTransactionHistoryInfo() throws Exception { Ignite ignite = startGridsMultiThreaded(2); ignite.cluster().active(true); Ignite client = startGrid("client"); client.getOrCreateCache(new CacheConfiguration<>(DEFAULT_CACHE_NAME) .setAtomicityMode(TRANSACTIONAL).setBackups(2).setWriteSynchronizationMode(FULL_SYNC)); for (Ignite ig : G.allGrids()) assertNotNull(ig.cache(DEFAULT_CACHE_NAME)); CountDownLatch lockLatch = new CountDownLatch(1); CountDownLatch unlockLatch = new CountDownLatch(1); IgniteInternalFuture<?> fut = startTransactions(lockLatch, unlockLatch, false); U.awaitQuiet(lockLatch); doSleep(3000); Set<GridCacheVersion> nearXids = new HashSet<>(); for (int i = 0; i < 2; i++) { IgniteEx grid = grid(i); IgniteTxManager tm = grid.context().cache().context().tm(); for (IgniteInternalTx tx : tm.activeTransactions()) nearXids.add(tx.nearXidVersion()); } unlockLatch.countDown(); fut.get(); doSleep(3000); injectTestSystemOut(); for (GridCacheVersion nearXid : nearXids) assertEquals(EXIT_CODE_OK, execute("--tx", "--info", nearXid.toString())); String out = testOut.toString(); assertTrue(out.contains("Transaction was found in completed versions history of the following nodes:")); assertTrue(out.contains("COMMITTED")); <START> assertTrue(out.contains("ROLLED_BACK")); <END> }</code><technical_language>unclear startTransactions produce transaction (ROLLED_BACK COMMITED in this case)</technical_language>

Target:
public void testTransactionHistoryInfo() throws Exception { Ignite ignite = startGridsMultiThreaded(2); ignite.cluster().active(true); Ignite client = startGrid("client"); client.getOrCreateCache(new CacheConfiguration<>(DEFAULT_CACHE_NAME) .setAtomicityMode(TRANSACTIONAL).setBackups(2).setWriteSynchronizationMode(FULL_SYNC)); for (Ignite ig : G.allGrids()) assertNotNull(ig.cache(DEFAULT_CACHE_NAME)); CountDownLatch lockLatch = new CountDownLatch(1); CountDownLatch unlockLatch = new CountDownLatch(1); IgniteInternalFuture<?> fut = startTransactions(lockLatch, unlockLatch, false); U.awaitQuiet(lockLatch); doSleep(3000); Set<GridCacheVersion> nearXids = new HashSet<>(); for (int i = 0; i < 2; i++) { IgniteEx grid = grid(i); IgniteTxManager tm = grid.context().cache().context().tm(); for (IgniteInternalTx tx : tm.activeTransactions()) nearXids.add(tx.nearXidVersion()); } unlockLatch.countDown(); fut.get(); doSleep(3000); injectTestSystemOut(); boolean commitMatched = false; boolean rollbackMatched = false; for (GridCacheVersion nearXid : nearXids) { assertEquals(EXIT_CODE_OK, execute("--tx", "--info", nearXid.toString())); String out = testOut.toString(); testOut.reset(); assertTrue(out.contains("Transaction was found in completed versions history of the following nodes:")); if (out.contains(TransactionState.COMMITTED.name())) { commitMatched = true; assertFalse(out.contains(TransactionState.ROLLED_BACK.name())); } if (out.contains(TransactionState.ROLLED_BACK.name())) { rollbackMatched = true; assertFalse(out.contains(TransactionState.COMMITTED.name())); } } assertTrue(commitMatched); assertTrue(rollbackMatched); }
Source:
<code>public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { this.watermark = in.readLong(); this.flags = decodeFlags(in.readShort()); this.key = (String) in.readObject(); int dataLength = in.readInt(); if (dataLength == 0) { this.data = null; } else { this.data = new byte[dataLength]; int pos = 0; while (pos < dataLength) { <START> pos += in.read(this.data, pos, dataLength - pos); <END> } } }</code><technical_language>In case of corrupted stream read return -1 dataLength bytes read, this account here</technical_language>

Target:
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { this.watermark = in.readLong(); this.flags = decodeFlags(in.readShort()); this.key = (String) in.readObject(); int dataLength = in.readInt(); if (dataLength == 0) { this.data = null; } else { this.data = new byte[dataLength]; int pos = 0; while (pos < dataLength) { int byteRead = in.read(this.data, pos, dataLength - pos); if (byteRead == -1) { throw new IllegalStateException("Corrupted stream, can not read " + dataLength + " bytes"); } pos += byteRead; } } }
Source:
<code>public int calculateLeadImageWidth() { Resources res = app.getResources(); <START> return (int) (res.getDimension(R.dimen.leadImageWidth) <END> / res.getDisplayMetrics().density); }</code><technical_language>calling getDimensionPixelSize() instead? remove cast density division</technical_language>

Target:
private int calculateLeadImageWidth() { Resources res = app.getResources(); return (int) (res.getDimension(R.dimen.leadImageWidth) / res.getDisplayMetrics().density); }