auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public double scaledEvidenceProbabilityUsingGenotypeFrequencies(final double[] genotypeFrequencies) { final double[] likelihoods = getLikelihoods(); <START> assert (genotypeFrequencies.length == nGeno); <END> assert (likelihoods.length == nGeno); double result = 0; for (Genotype g: Genotype.values()){ result += likelihoods[g.v] * genotypeFrequencies[g.v]; } return result; }</code><technical_language>I assert is want here, effect code is run -ea flag. E.g. if a unit test trigger this assert, fail</technical_language>

Target:
public double scaledEvidenceProbabilityUsingGenotypeFrequencies(final double[] genotypeFrequencies) { final double[] likelihoods = getLikelihoods(); ValidationUtils.validateArg(genotypeFrequencies.length == NUM_GENOTYPES, "provided genotype frequencies must be length 3"); ValidationUtils.validateArg(likelihoods.length == NUM_GENOTYPES, "internal liklihoods must be length 3"); double result = 0; for (Genotype g : Genotype.values()) { result += likelihoods[g.v] * genotypeFrequencies[g.v]; } return result; }
Source:
<code>public Loader<Result> onCreateLoader(final int loaderId, final Bundle bundle) { BaseSimpleRequest request; switch (loaderId) { case ID_LOADER_REFRESH_ARTICLE: showLoadingState(true); request = new SimpleGetRequest( UrlFactory.buildNewsArticleURL(bundle.getString(ID)), BaseSimpleRequest.RequestType.FROM_NAVIGATION ); break; case ID_LOADER_HOOAH: request = new SimplePostRequest( UrlFactory.buildNewsArticleHooahURL(articleId), bundle ); break; case ID_LOADER_POST_COMMENT: request = new SimplePostRequest( UrlFactory.buildNewsArticlePostCommentURL(articleId), bundle ); break; case ID_LOADER_COMMENT_UPVOTE: request = new SimplePostRequest( UrlFactory.buildNewsArticleCommentUpvoteURL(bundle.getString(COMMENT_ID)), bundle ); break; case ID_LOADER_COMMENT_DOWNVOTE: request = new SimplePostRequest( UrlFactory.buildNewsArticleCommentDownvoteURL(bundle.getString(COMMENT_ID)), bundle ); break; default: <START> throw new IllegalArgumentException("No loader matching " + loaderId); <END> } return new IntelLoader(getActivity(), request); }</code><technical_language>I reason for exception. 5 loaders hard track</technical_language>

Target:
public Loader<Result> onCreateLoader(final int loaderId, final Bundle bundle) { BaseSimpleRequest request; switch (loaderId) { case ID_LOADER_REFRESH_ARTICLE: showLoadingState(bundle.getBoolean(FLAG_SHOW_LOADING, true)); request = new SimpleGetRequest( UrlFactory.buildNewsArticleURL(bundle.getString(ID)), BaseSimpleRequest.RequestType.FROM_NAVIGATION ); break; case ID_LOADER_HOOAH: request = new SimplePostRequest( UrlFactory.buildNewsArticleHooahURL(articleId), bundle ); break; case ID_LOADER_POST_COMMENT: request = new SimplePostRequest( UrlFactory.buildNewsArticlePostCommentURL(articleId), bundle ); break; case ID_LOADER_COMMENT_UPVOTE: request = new SimplePostRequest( UrlFactory.buildNewsArticleCommentUpvoteURL(bundle.getString(COMMENT_ID)), bundle ); break; case ID_LOADER_COMMENT_DOWNVOTE: request = new SimplePostRequest( UrlFactory.buildNewsArticleCommentDownvoteURL(bundle.getString(COMMENT_ID)), bundle ); break; default: throw new IllegalArgumentException("No loader matching " + loaderId); } return new IntelLoader(getActivity(), request); }
Source:
<code>public void flop(Throwable thr, String msg) { try { fail(msg); } catch (Throwable t) { asyncErrors.add(thr); <START> throw new RuntimeException(t); <END> } }</code><technical_language>rethrow original transparently</technical_language>

Target:
public void flop(Throwable thr, String msg) { try { fail(msg); } catch (Throwable t) { asyncErrors.add(thr); } }
Source:
<code>public boolean didMove() { <START> return moved || (copied && deletedOld); <END> }</code><technical_language>moved moveObject() needed anymore</technical_language>

Target:
public boolean didMove() { return copied && deletedOld; }
Source:
<code>public long readLong(final int numBits) { if (numBits < 0 || numBits > Long.SIZE) { throw new IllegalArgumentException("bits must be in range 0 ... 64!"); } long bits = 0; <START> if (currentBitIndex < 0 && (numBits & 0x7) == 0) { <END> for (int i = numBits; i > 0; i -= 8) { bits <<= 8; bits |= readByte(); } } else { for (int i = numBits - 1; i >= 0; i--) { if (currentBitIndex < 0) { readCurrentByte(); } boolean bit = (currentByte >> currentBitIndex & 1) != 0; if (bit) { bits |= (1L << i); } --currentBitIndex; } } return bits; }</code><technical_language>(numBits & 0x7) == 0, I idea is ensure numbits is a multiple of 8. For modulo is more intuitive. (but subjective)</technical_language>

Target:
public long readLong(final int numBits) { if (numBits < 0 || numBits > Long.SIZE) { throw new IllegalArgumentException("bits must be in range 0 ... 64!"); } long bits = 0; if (currentBitIndex < 0 && (numBits & 0x7) == 0) { for (int i = 0; i < numBits; i += 8) { bits <<= 8; bits |= readByte(); } } else { for (int i = numBits - 1; i >= 0; i--) { if (currentBitIndex < 0) { readCurrentByte(); } boolean bit = (currentByte >> currentBitIndex & 1) != 0; if (bit) { bits |= (1L << i); } --currentBitIndex; } } return bits; }
Source:
<code>public void testElementWithGenericNodeAttributes() { FaxResponse.Builder builder = new FaxResponse.Builder(); GenericNode.Builder genericBuilder = new GenericNode.Builder("genericTag"); genericBuilder.option("key", "value").addText("someText"); <START> GenericNode node = genericBuilder.build(); <END> Receive.Builder receiveBuilder = new Receive.Builder().addChild(node); Receive message = receiveBuilder.build(); FaxResponse elem = builder.receive(message).build(); Assert.assertEquals( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<Response>" + "<Receive>"+ "<genericTag key=\"value\">"+ "someText"+ "</genericTag>"+ "</Receive>"+ "</Response>", elem.toXml() ); }</code><technical_language>find more readable if combine some of lines put in sections constructing object, bottom up: GenericNode.Builder genericBuilder = new GenericNode.Builder("genericTag"); GenericNode node = genericBuilder.option("key", "value").addText("someText").build(); Receive.Builder receiveBuilder = new Receive.Builder(); Receive message = receiveBuilder.addChild(node).build(); FaxResponse.Builder builder = new FaxResponse.Builder(); FaxResponse elem = builder.receive(message).build();</technical_language>

Target:
public void testElementWithGenericNodeAttributes() { GenericNode.Builder genericBuilder = new GenericNode.Builder("genericTag"); GenericNode node = genericBuilder.option("key", "value").addText("someText").build(); FaxResponse.Builder builder = new FaxResponse.Builder(); FaxResponse elem = builder.addChild(node).build(); Assert.assertEquals( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<Response>" + "<genericTag key=\"value\">" + "someText" + "</genericTag>" + "</Response>", elem.toXml() ); }
Source:
<code>private static boolean isBlacklistedTransformer(TransformerDescriptors descriptors, String id) { for (String transformer : descriptors.getBlackListedMetacardTransformers()) { <START> if (id.endsWith(transformer)) { <END> return true; } } return false; }</code><technical_language>ends instead of .equals()</technical_language>

Target:
private static boolean isBlacklistedTransformer(TransformerDescriptors descriptors, String id) { return descriptors .getBlackListedMetacardTransformerIds() .stream() .anyMatch(s -> id.endsWith(s)); }
Source:
<code>protected void isNuageVspManagerLoaded() throws Exception { if (!_isNuageVspClientLoaded || _nuageVspManagerClient == null) { <START> throw new Exception(NUAGE_VSP_PLUGIN_ERROR_MESSAGE); <END> } }</code><technical_language>Generally, Exception thrown. Thrown specific type of exception this condition (e.g. IllegalStateException)</technical_language>

Target:
protected void isNuageVspManagerLoaded() throws ConfigurationException { if (!_isNuageVspClientLoaded || _nuageVspManagerClient == null) { throw new ConfigurationException(NUAGE_VSP_PLUGIN_ERROR_MESSAGE); } }
Source:
<code>private void saveMediaToDevice() { String[] permissionList = { Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE }; if (!PermissionUtils.checkAndRequestPermissions(this, WPPermissionUtils.MEDIA_PREVIEW_PERMISSION_REQUEST_CODE, permissionList)) { return; } if (!NetworkUtils.checkConnection(this)) { return; } DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE); DownloadManager.Request request = new DownloadManager.Request(Uri.parse(mMedia.getUrl())); try { request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, mMedia.getFileName()); } catch (IllegalStateException error) { AppLog.e(AppLog.T.MEDIA, error); ToastUtils.showToast(MediaSettingsActivity.this, R.string.error_media_save); return; } request.allowScanningByMediaScanner(); request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE); <START> request.addRequestHeader("User-Agent", WordPress.getDefaultUserAgent()); <END> mDownloadId = dm.enqueue(request); invalidateOptionsMenu(); ToastUtils.showToast(this, R.string.media_downloading); }</code><technical_language>I WordPress.getUserAgent() instead. This adds application information [explained here](<LINK_0> Checked backend effectively common detect of apps there</technical_language>

Target:
private void saveMediaToDevice() { String[] permissionList = { Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE }; if (!PermissionUtils.checkAndRequestPermissions(this, WPPermissionUtils.MEDIA_PREVIEW_PERMISSION_REQUEST_CODE, permissionList)) { return; } if (!NetworkUtils.checkConnection(this)) { return; } DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE); DownloadManager.Request request = new DownloadManager.Request(Uri.parse(mMedia.getUrl())); try { request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, mMedia.getFileName()); } catch (IllegalStateException error) { AppLog.e(AppLog.T.MEDIA, error); ToastUtils.showToast(MediaSettingsActivity.this, R.string.error_media_save); return; } request.allowScanningByMediaScanner(); request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE); request.addRequestHeader("User-Agent", WordPress.getUserAgent()); mDownloadId = dm.enqueue(request); invalidateOptionsMenu(); ToastUtils.showToast(this, R.string.media_downloading); }
Source:
<code>public Type toStorageType(Type type) { Type storageType; if (type.equals(BOOLEAN) || type.equals(BIGINT) || type.equals(INTEGER) || type.equals(SMALLINT) || type.equals(TINYINT) || type.equals(DOUBLE) || type.equals(REAL) || type.equals(DATE) || isCharType(type) || isVarcharType(type) || isLongDecimal(type) || isShortDecimal(type) || type.equals(VARBINARY)) { storageType = type; } else if (type.equals(TIME) || type.equals(TIMESTAMP)) { storageType = BIGINT; } else if (type instanceof ArrayType) { storageType = new ArrayType(toStorageType(((ArrayType) type).getElementType())); } else if (type instanceof MapType) { storageType = mapType(toStorageType(((MapType) type).getKeyType()), toStorageType(((MapType) type).getValueType())); } else { throw new PrestoException(NOT_SUPPORTED, "Type not supported: " + type); } try { checkState(storageType.getJavaType().equals(type.getJavaType())); } catch (Exception e) { <START> System.out.println("ooh"); <END> } return storageType; }</code><technical_language>ooh</technical_language>

Target:
public Type toStorageType(Type type) { Type storageType; if (type.equals(BOOLEAN) || type.equals(BIGINT) || type.equals(INTEGER) || type.equals(SMALLINT) || type.equals(TINYINT) || type.equals(DOUBLE) || type.equals(REAL) || type.equals(DATE) || isCharType(type) || isVarcharType(type) || isLongDecimal(type) || isShortDecimal(type) || type.equals(VARBINARY)) { storageType = type; } else if (type.equals(TIME) || type.equals(TIMESTAMP)) { storageType = BIGINT; } else if (type instanceof ArrayType) { storageType = new ArrayType(toStorageType(((ArrayType) type).getElementType())); } else if (type instanceof MapType) { storageType = mapType(toStorageType(((MapType) type).getKeyType()), toStorageType(((MapType) type).getValueType())); } else { throw new PrestoException(NOT_SUPPORTED, "Type not supported: " + type); } checkState(storageType.getJavaType().equals(type.getJavaType())); return storageType; }
Source:
<code>public DirectConnectionConfig() { this.connectionTimeout = null; <START> this.idleConnectionTimeout = Duration.ZERO; <END> this.idleEndpointTimeout = DEFAULT_IDLE_ENDPOINT_TIMEOUT; this.maxConnectionsPerEndpoint = DEFAULT_MAX_CONNECTIONS_PER_ENDPOINT; this.maxRequestsPerConnection = DEFAULT_MAX_REQUESTS_PER_ENDPOINT; }</code><technical_language>0 idle connection timeout mean</technical_language>

Target:
public DirectConnectionConfig() { this.idleConnectionTimeout = Duration.ZERO; this.connectionTimeout = DEFAULT_CONNECTION_TIMEOUT; this.idleEndpointTimeout = DEFAULT_IDLE_ENDPOINT_TIMEOUT; this.maxConnectionsPerEndpoint = DEFAULT_MAX_CONNECTIONS_PER_ENDPOINT; this.maxRequestsPerConnection = DEFAULT_MAX_REQUESTS_PER_CONNECTION; }
Source:
<code>AnnotationMirror convertStringValToMatchesRegex( AnnotationMirror stringValAnno) { List<String> values = getStringValues(stringValAnno); List<@Regex String> valuesAsRegexes = new ArrayList<>(); for (String value : values) { <START> valuesAsRegexes.add("^" + Pattern.quote(value) + "$"); <END> } return createMatchesRegexAnnotation(valuesAsRegexes); }</code><technical_language>implementation matches Matcher.find, do need anchors. tests pass them</technical_language>

Target:
AnnotationMirror convertStringValToMatchesRegex( AnnotationMirror stringValAnno) { List<String> values = getStringValues(stringValAnno); List<@Regex String> valuesAsRegexes = new ArrayList<>(); for (String value : values) { valuesAsRegexes.add(Pattern.quote(value)); } return createMatchesRegexAnnotation(valuesAsRegexes); }
Source:
<code>public long applyPoliteness(WebURL url) { long politenessDelay = NO_POLITENESS_APPLIED; String host = getHost(url); if (host != null) { if (seenHosts.containsKey(host)) { Date lastFetchTime = seenHosts.get(host); if (lastFetchTime != null) { long now = (new Date()).getTime(); long diff = (now - lastFetchTime.getTime()); if (diff < config.getPolitenessDelay()) { politenessDelay = config.getPolitenessDelay() - diff; logger.debug("Applying politeness delay of ms for host {}", politenessDelay, host); } else { } } } <START> seenHosts.put(host, new Date()); <END> return politenessDelay; } else { logger.warn("Could not determine host for: " + url.getURL()); return politenessDelay; } }</code><technical_language>Guava jar is 2MB provides other useful features in other places. Feel free add that</technical_language>

Target:
public long applyPoliteness(WebURL url) { synchronized (mutex) { long politenessDelay = NO_POLITENESS_APPLIED; String host = getHost(url); if (host != null) { Date lastFetchTime = seenHosts.getIfPresent(host); if (lastFetchTime != null) { long now = (new Date()).getTime(); long diff = (now - lastFetchTime.getTime()); if (diff < config.getPolitenessDelay()) { politenessDelay = config.getPolitenessDelay() - diff; logger.debug("Applying politeness delay of ms for host {}", politenessDelay, host); } else { } } seenHosts.put(host, new Date()); } return politenessDelay; } }
Source:
<code>protected void doHealthCheck(Health.Builder builder) throws Exception { builder.up(); List<Map<String, Object>> details = new ArrayList<>(); for (String name : this.repositories.keySet()) { Repository repository = this.repositories.get(name); String application = (repository.getName() == null)? name : repository.getName(); String profiles = repository.getProfiles(); try { Environment environment = this.environmentRepository.findOne(application, profiles, repository.getLabel()); HashMap<String, Object> detail = new HashMap<>(); detail.put("name", environment.getName()); detail.put("label", environment.getLabel()); if (environment.getCached()) { <START> builder.outOfService(); <END> } if (environment.getProfiles() != null && environment.getProfiles().length > 0) { detail.put("profiles", Arrays.asList(environment.getProfiles())); } if (!CollectionUtils.isEmpty(environment.getPropertySources())) { List<String> sources = new ArrayList<>(); for (PropertySource source : environment.getPropertySources()) { sources.add(source.getName()); } detail.put("sources", sources); } details.add(detail); } catch (Exception e) { HashMap<String, String> map = new HashMap<>(); map.put("application", application); map.put("profiles", profiles); builder.withDetail("repository", map); builder.down(e); return; } } builder.withDetail("repositories", details); }</code><technical_language>consider config server out of service repo couldnt reached? I technically serve configuration data right</technical_language>

Target:
protected void doHealthCheck(Health.Builder builder) throws Exception { builder.up(); List<Map<String, Object>> details = new ArrayList<>(); for (String name : this.repositories.keySet()) { Repository repository = this.repositories.get(name); String application = (repository.getName() == null)? name : repository.getName(); String profiles = repository.getProfiles(); try { Environment environment = this.environmentRepository.findOne(application, profiles, repository.getLabel()); HashMap<String, Object> detail = new HashMap<>(); detail.put("name", environment.getName()); detail.put("label", environment.getLabel()); if (environment.getCached()) { builder.unknown(); } if (environment.getProfiles() != null && environment.getProfiles().length > 0) { detail.put("profiles", Arrays.asList(environment.getProfiles())); } if (!CollectionUtils.isEmpty(environment.getPropertySources())) { List<String> sources = new ArrayList<>(); for (PropertySource source : environment.getPropertySources()) { sources.add(source.getName()); } detail.put("sources", sources); } details.add(detail); } catch (Exception e) { HashMap<String, String> map = new HashMap<>(); map.put("application", application); map.put("profiles", profiles); builder.withDetail("repository", map); builder.down(e); return; } } builder.withDetail("repositories", details); }
Source:
<code>@Override protected Void run() throws Exception { String fromImage = null; FilePath dockerfile = workspace.child(step.dockerfile); InputStream is = dockerfile.read(); BufferedReader r = null; try { <START> r = new BufferedReader(new InputStreamReader(is, "ASCII")); END> String line; while ((line = r.readLine()) != null) { line = line.trim(); if (line.startsWith("#")) { continue; } if (line.startsWith("FROM ")) { fromImage = line.substring(5); break; } } } finally { IOUtils.closeQuietly(r); } if (fromImage == null) { throw new AbortException("could not find FROM instruction in " + dockerfile); } DockerClient client = new DockerClient(launcher, node, step.toolName); String descendantImageId = client.inspectRequiredField(env, step.image, ".Id"); if (fromImage.equals("scratch")) { DockerFingerprints.addFromFacet(null, descendantImageId, run); } else { DockerFingerprints.addFromFacet(client.inspectRequiredField(env, fromImage, ".Id"), descendantImageId, run); ImageAction.add(fromImage, run); } return null; }</code><technical_language>if default UTF-8 - in reality if need a charset host uses. a FilePath host able get this information</technical_language>

Target:
@Override protected Void run() throws Exception { String fromImage = null; FilePath dockerfile = workspace.child(step.dockerfile); InputStream is = dockerfile.read(); try { BufferedReader r = new BufferedReader(new InputStreamReader(is, "ISO-8859-1")); try { String line; while ((line = r.readLine()) != null) { line = line.trim(); if (line.startsWith("#")) { continue; } if (line.startsWith("FROM ")) { fromImage = line.substring(5); break; } } } finally { r.close(); } } finally { is.close(); } if (fromImage == null) { throw new AbortException("could not find FROM instruction in " + dockerfile); } DockerClient client = new DockerClient(launcher, node, step.toolName); String descendantImageId = client.inspectRequiredField(env, step.image, ".Id"); if (fromImage.equals("scratch")) { DockerFingerprints.addFromFacet(null, descendantImageId, run); } else { DockerFingerprints.addFromFacet(client.inspectRequiredField(env, fromImage, ".Id"), descendantImageId, run); ImageAction.add(fromImage, run); } return null; }
Source:
<code>private Map<String, LockFile> lockLooseRefs(List<ReceiveCommand> commands) throws IOException { ReceiveCommand failed = null; Map<String, LockFile> locks = new HashMap<>(); try { RETRY: for (int ms : refdb.getRetrySleepMs()) { failed = null; unlockAll(locks); locks.clear(); RefDirectory.sleep(ms); for (ReceiveCommand c : commands) { String name = c.getRefName(); LockFile lock = new LockFile(refdb.fileFor(name)); if (locks.put(name, lock) != null) { throw new IOException( MessageFormat.format(JGitText.get().duplicateRef, name)); } if (!lock.lock()) { failed = c; continue RETRY; } } return locks; } } catch (IOException e) { <START> unlockAll(locks); <END> throw e; } unlockAll(locks); lockFailure(failed != null ? failed : commands.get(0), commands); return null; }</code><technical_language>this in a finally block</technical_language>

Target:
private Map<String, LockFile> lockLooseRefs(List<ReceiveCommand> commands) throws IOException { ReceiveCommand failed = null; Map<String, LockFile> locks = new HashMap<>(); try { RETRY: for (int ms : refdb.getRetrySleepMs()) { failed = null; unlockAll(locks); locks.clear(); RefDirectory.sleep(ms); for (ReceiveCommand c : commands) { String name = c.getRefName(); LockFile lock = new LockFile(refdb.fileFor(name)); if (locks.put(name, lock) != null) { throw new IOException( MessageFormat.format(JGitText.get().duplicateRef, name)); } if (!lock.lock()) { failed = c; continue RETRY; } } Map<String, LockFile> result = locks; locks = null; return result; } } finally { unlockAll(locks); } lockFailure(failed != null ? failed : commands.get(0), commands); return null; }
Source:
<code>public void handleValidationErrors(GlusterVolumeSnapshotModel object) { StringBuilder generalTabErrorBuilder = new StringBuilder(); <START> if (!snapshotNameEditor.isValid()){ <END> appendErrors(Collections.singletonList(constants.volumeSnapshotNamePrefixLabel()), generalTabErrorBuilder); appendErrors(object.getSnapshotName().getInvalidityReasons(), generalTabErrorBuilder); } generalTabErrorMsgLabel.setText(generalTabErrorBuilder.toString()); generalTabErrorMsgLabel.setVisible(generalTabErrorBuilder.toString() != null || !generalTabErrorBuilder.toString().isEmpty()); if (!clusterNameEditor.isValid() || !volumeNameEditor.isValid() || !snapshotNameEditor.isValid() || !snapshotDescriptionEditor.isValid()) { tabContainer.switchTab(generalTab); } else if (!recurrenceEditor.isValid() || !intervalEditor.isValid() || !timeZoneEditor.isValid() || !startAtEditor.isValid() || !executionTimeEditor.isValid() || !daysOfWeekEditor.isValid() || !daysOfMonthEditor.isValid() || !endByOptionsEditor.isValid() || !endDate.isValid()) { tabContainer.switchTab(scheduleTab); } }</code><technical_language>do handle this special one</technical_language>

Target:
public void handleValidationErrors(GlusterVolumeSnapshotModel object) { String generalTabErrors = collectGeneralTabErrors(object); setMessage(generalTabErrors, generalTabErrorMsgLabel); String scheduleTabErrors = collectScheduleTabErrors(object); setMessage(scheduleTabErrors, errorMsgLabel); }
Source:
<code>private void unBindGpioPin(MCP23017BindingProvider provider, String itemName) { GpioPin pin = gpioPins.remove(itemName); gpio.unprovisionPin(pin); <START> logger.debug("unbound " + itemName); <END> }</code><technical_language>parameterized logging instead of string concatenation</technical_language>

Target:
private void unBindGpioPin(MCP23017BindingProvider provider, String itemName) { GpioPin pin = gpioPins.remove(itemName); gpio.unprovisionPin(pin); logger.debug("Unbound item {}", itemName); }
Source:
<code>private String getMimeType(URI resourceURI, String productName) throws MimeTypeResolutionException, IOException { String mimeType = null; if (mimeTypeMapper == null) { LOGGER.debug("mimeTypeMapper is NULL"); } else { String fileExtension = FilenameUtils.getExtension(productName); mimeType = mimeTypeMapper.getMimeTypeForFileExtension(fileExtension); } if ((mimeType == null || mimeType.isEmpty() || mimeType.equals(DEFAULT_MIME_TYPE)) && URL_FILE_SCHEME.equalsIgnoreCase(resourceURI.getScheme())) { final Tika tika = new Tika(); try { mimeType = AccessController.doPrivileged( (PrivilegedExceptionAction<String>) () -> tika.detect(resourceURI.toURL())); } catch (PrivilegedActionException e) { <START> throw new IOException("Error performing privileged action", e); <END> } LOGGER.debug("Tika determined mimeType for url = {}", mimeType); } else { LOGGER.debug("mimeType = set by MimeTypeMapper", mimeType); } if (mimeType == null || mimeType.equals("content/unknown")) { mimeType = "application/unknown"; } LOGGER.debug("mimeType set to: {}", mimeType); return mimeType; }</code><technical_language>e.getException() piggy exception generated wrapper</technical_language>

Target:
private String getMimeType(URI resourceURI, String productName) throws MimeTypeResolutionException, IOException { String mimeType = null; if (mimeTypeMapper == null) { LOGGER.debug("mimeTypeMapper is NULL"); } else { String fileExtension = FilenameUtils.getExtension(productName); mimeType = mimeTypeMapper.getMimeTypeForFileExtension(fileExtension); } if ((mimeType == null || mimeType.isEmpty() || mimeType.equals(DEFAULT_MIME_TYPE)) && URL_FILE_SCHEME.equalsIgnoreCase(resourceURI.getScheme())) { final Tika tika = new Tika(); try { mimeType = AccessController.doPrivileged( (PrivilegedExceptionAction<String>) () -> tika.detect(resourceURI.toURL())); } catch (PrivilegedActionException e) { throw new IOException("Error performing privileged action", e.getException()); } LOGGER.debug("Tika determined mimeType for url = {}", mimeType); } else { LOGGER.debug("mimeType = set by MimeTypeMapper", mimeType); } if (mimeType == null || mimeType.equals("content/unknown")) { mimeType = "application/unknown"; } LOGGER.debug("mimeType set to: {}", mimeType); return mimeType; }
Source:
<code>private void deleteTableData(Path tablePath, boolean ifPurge, Database db) throws MetaException { if (tablePath != null) { <START> wh.deleteDir(tablePath, true, ifPurge, db); <END> } }</code><technical_language>for ..just log error ..ignore exception while deleting</technical_language>

Target:
private void deleteTableData(Path tablePath, boolean ifPurge, Database db) { if (tablePath != null) { try { wh.deleteDir(tablePath, true, ifPurge, db); } catch (Exception e) { LOG.error("Failed to delete table directory: " + tablePath + " " + e.getMessage()); } } }
Source:
<code>public Collection<UberfireDock> provideDocks(final String perspectiveIdentifier) { List<UberfireDock> result = new ArrayList<>(); settingsDock = new UberfireDock(UberfireDockPosition.EAST, "SLIDERS", new DefaultPlaceRequest(SettingsPresenter.IDENTIFIER), perspectiveIdentifier); result.add(settingsDock.withSize(450).withLabel(ScenarioSimulationEditorConstants.INSTANCE.settings())); toolsDock = new UberfireDock(UberfireDockPosition.EAST, "INFO_CIRCLE", new DefaultPlaceRequest(TestToolsPresenter.IDENTIFIER), perspectiveIdentifier); result.add(toolsDock.withSize(450).withLabel(ScenarioSimulationEditorConstants.INSTANCE.testTools())); cheatSheetDock = new UberfireDock(UberfireDockPosition.EAST, "FILE_TEXT", new DefaultPlaceRequest(CheatSheetPresenter.IDENTIFIER), perspectiveIdentifier); result.add(cheatSheetDock.withSize(450).withLabel(ScenarioSimulationEditorConstants.INSTANCE.scenarioCheatSheet())); reportDock = new UberfireDock(UberfireDockPosition.EAST, "PLAY_CIRCLE", new DockPlaceHolderPlace(TEST_RUNNER_REPORTING_PANEL), perspectiveIdentifier); <START> result.add(reportDock.withSize(450).withLabel("TEST REPORT" )); <END> coverageDock = new UberfireDock(UberfireDockPosition.EAST, "BAR_CHART", new DefaultPlaceRequest(CoverageReportPresenter.IDENTIFIER), perspectiveIdentifier); result.add(coverageDock.withSize(450).withLabel(ScenarioSimulationEditorConstants.INSTANCE.coverageReport())); return result; }</code><technical_language>Is this change required? hard coded string</technical_language>

Target:
public Collection<UberfireDock> provideDocks(final String perspectiveIdentifier) { List<UberfireDock> result = new ArrayList<>(); settingsDock = new UberfireDock(UberfireDockPosition.EAST, "SLIDERS", new DefaultPlaceRequest(SettingsPresenter.IDENTIFIER), perspectiveIdentifier); result.add(settingsDock.withSize(450).withLabel(ScenarioSimulationEditorConstants.INSTANCE.settings())); toolsDock = new UberfireDock(UberfireDockPosition.EAST, "INFO_CIRCLE", new DefaultPlaceRequest(TestToolsPresenter.IDENTIFIER), perspectiveIdentifier); result.add(toolsDock.withSize(450).withLabel(ScenarioSimulationEditorConstants.INSTANCE.testTools())); cheatSheetDock = new UberfireDock(UberfireDockPosition.EAST, "FILE_TEXT", new DefaultPlaceRequest(CheatSheetPresenter.IDENTIFIER), perspectiveIdentifier); result.add(cheatSheetDock.withSize(450).withLabel(ScenarioSimulationEditorConstants.INSTANCE.scenarioCheatSheet())); reportDock = new UberfireDock(UberfireDockPosition.EAST, "PLAY_CIRCLE", new DockPlaceHolderPlace(TEST_RUNNER_REPORTING_PANEL), perspectiveIdentifier); result.add(reportDock.withSize(450).withLabel(ScenarioSimulationEditorConstants.INSTANCE.testReport())); coverageDock = new UberfireDock(UberfireDockPosition.EAST, "BAR_CHART", new DefaultPlaceRequest(CoverageReportPresenter.IDENTIFIER), perspectiveIdentifier); result.add(coverageDock.withSize(450).withLabel(ScenarioSimulationEditorConstants.INSTANCE.coverageReport())); return result; }
Source:
<code>public List<String> unapply(final String value) { if (value == null) { return Collections.EMPTY_LIST; } final List<String> retList; try { <START> retList = reverseLoadingCache.get(value, new Callable<List<String>>() <END> { @Override public List<String> call() throws Exception { return dataFetcher.reverseFetchKeys(value); } }); return retList; } catch (ExecutionException e) { LOGGER.debug("list of keys not found for value [%s]", value); return Collections.EMPTY_LIST; } }</code><technical_language>suggest making this Callable a class field</technical_language>

Target:
public List<String> unapply(final String value) { if (value == null) { return Collections.EMPTY_LIST; } final List<String> retList; try { retList = reverseLoadingCache.get(value, new unapplyCallable(value)); return retList; } catch (ExecutionException e) { LOGGER.debug("list of keys not found for value [%s]", value); return Collections.EMPTY_LIST; } }
Source:
<code>public void startPlugins() { for (PluginWrapper pluginWrapper : resolvedPlugins) { PluginState pluginState = pluginWrapper.getPluginState(); if ((PluginState.DISABLED != pluginState) && (PluginState.STARTED != pluginState)) { <START> tryStartPlugin(pluginWrapper, pluginWrapper.getDescriptor(), pluginState); <END> } } }</code><technical_language>this is a mechanic extraction. enough pass pluginWrapper</technical_language>

Target:
public void startPlugins() { for (PluginWrapper pluginWrapper : resolvedPlugins) { PluginState pluginState = pluginWrapper.getPluginState(); if ((PluginState.DISABLED != pluginState) && (PluginState.STARTED != pluginState)) { tryStartPlugin(pluginWrapper); } } }
Source:
<code>public void consume(Iterator<KeyMessage<String, String>> updateIterator) throws IOException { while (updateIterator.hasNext()) { KeyMessage<String, String> km = updateIterator.next(); String key = km.getKey(); String message = km.getMessage(); switch (key) { case "UP": <START> List<?> update = MAPPER.readValue(message, List.class); <END> int id = Integer.parseInt(update.get(0).toString()); double[] vector = MAPPER.convertValue(update.get(1), double[].class); model.update(id, vector); break; case "MODEL": PMML pmml; try { pmml = PMMLUtils.fromString(message); } catch (JAXBException e) { throw new IOException(e); } KMeansPMMLUtils.validatePMMLVsSchema(pmml, inputSchema); model = new KMeansSpeedModel(KMeansPMMLUtils.read(pmml)); log.info("Model with clusters", model.getClusters().size()); break; default: throw new IllegalStateException("Unexpected key " + key); } } }</code><technical_language>This layer get updated batch layer. ignore them. In fact hearing updates</technical_language>

Target:
public void consume(Iterator<KeyMessage<String, String>> updateIterator) throws IOException { while (updateIterator.hasNext()) { KeyMessage<String, String> km = updateIterator.next(); String key = km.getKey(); String message = km.getMessage(); switch (key) { case "UP": break; case "MODEL": PMML pmml; try { pmml = PMMLUtils.fromString(message); } catch (JAXBException e) { throw new IOException(e); } KMeansPMMLUtils.validatePMMLVsSchema(pmml, inputSchema); model = new KMeansSpeedModel(KMeansPMMLUtils.read(pmml)); log.info("Model with clusters", model.getClusters().size()); break; default: throw new IllegalStateException("Unexpected key " + key); } } }
Source:
<code>void bindResource(OsgiVaadinStaticResource resource) throws NamespaceException { <START> Bundle bundle = FrameworkUtil.getBundle(resource.getClass()); <END> Delegate registration = new Delegate(resource.getAlias(), resource.getPath(), bundle); resourceToDelegate.put(resource, registration); registration.init(httpService); httpService.registerResources(registration.alias, registration.path, registration); }</code><technical_language>This method is called in this PR</technical_language>

Target:
void bindResource(OsgiVaadinStaticResource resource) throws NamespaceException { Bundle bundle = FrameworkUtil.getBundle(resource.getClass()); Delegate registration = new Delegate(resource.getAlias(), resource.getPath(), bundle, httpService.createDefaultHttpContext()); httpService.registerResources(registration.alias, registration.path, registration); }
Source:
<code>public void setNotifierFrequency(org.wso2.iot.agent.beans.Operation operation) throws AndroidAgentException { try { JSONObject inputData = new JSONObject(operation.getPayLoad().toString()); int notifierFrequencyValue = inputData.getInt(getContextResources() .getString(R.string.notifire_frequency_value_key)); Preference.putInt(context, context.getString(R.string.shared_pref_frequency), notifierFrequencyValue); operation.setStatus(getContextResources().getString(R.string.operation_value_completed)); operation.setOperationResponse("Notification frequency updated successfully."); getResultBuilder().build(operation); <START> } catch (JSONException | NullPointerException e) { <END> operation.setStatus(getContextResources().getString(R.string.operation_value_error)); operation.setOperationResponse("Error in parsing NOTIFICATION payload."); getResultBuilder().build(operation); throw new AndroidAgentException("Invalid JSON format.", e); } }</code><technical_language>Null pointers check allowing throw exception. Please check objects for null necessary return error response accordingly</technical_language>

Target:
public void setNotifierFrequency(org.wso2.iot.agent.beans.Operation operation) throws AndroidAgentException { try { if (operation.getPayLoad() != null) { JSONObject inputData = new JSONObject(operation.getPayLoad().toString()); int notifierFrequencyValue = inputData.getInt(Constants.NOTIFIRE_FREQUENCY_VALUE_KEY); Preference.putInt(context, context.getString(R.string.shared_pref_frequency), notifierFrequencyValue); operation.setStatus(getContextResources().getString(R.string.operation_value_completed)); operation.setOperationResponse("Notification frequency updated successfully."); getResultBuilder().build(operation); } else { operation.setStatus(getContextResources().getString(R.string.operation_value_error)); operation.setOperationResponse("invalid NOTIFICATION payload."); getResultBuilder().build(operation); } } catch (JSONException e) { operation.setStatus(getContextResources().getString(R.string.operation_value_error)); operation.setOperationResponse("Error in parsing NOTIFICATION payload."); getResultBuilder().build(operation); throw new AndroidAgentException("Invalid JSON format.", e); } }
Source:
<code>public PluginInfo.Release preferReleaseVersion( @Nonnull String id, @Nonnull String releaseVersion, boolean preferred) { PluginInfo pluginInfo = repository.findById(id); Optional<PluginInfo.Release> release = pluginInfo.getReleaseByVersion(releaseVersion); <START> if (release.isPresent()) { release.get().setPreferred(preferred); pluginInfo.setReleaseByVersion(releaseVersion, release.get()); if (preferred) { pluginInfo.getReleases().stream() .filter(it -> !it.getVersion().equals(release.get().getVersion())) .forEach(it -> it.setPreferred(false)); } repository.update(pluginInfo.getId(), pluginInfo); } return release.orElse(null); <END> }</code><technical_language>nit: release.map(r -> { /* do stuff */).orElse(null) -- avoid isPresent() explicit get() call</technical_language>

Target:
public PluginInfo.Release preferReleaseVersion( @Nonnull String id, @Nonnull String releaseVersion, boolean preferred) { PluginInfo pluginInfo = repository.findById(id); Optional<PluginInfo.Release> release = pluginInfo.getReleaseByVersion(releaseVersion); return release .map( r -> { r.setPreferred(preferred); pluginInfo.setReleaseByVersion(releaseVersion, r); if (preferred) { pluginInfo.getReleases().stream() .filter(it -> !it.getVersion().equals(r.getVersion())) .forEach(it -> it.setPreferred(false)); } repository.update(pluginInfo.getId(), pluginInfo); return r; }) .orElse(null); }
Source:
<code>public static void registerLog4jMBeans() throws JMException { if (isLog4jJmxEnabled()) { LOG.debug("registerLog4jMBeans()"); MBeanServer mbs = MBeanRegistry.getInstance().getPlatformMBeanServer(); try { Object hdm = Class.forName("org.apache.log4j.jmx.HierarchyDynamicMBean").getDeclaredConstructor().newInstance(); <START> ObjectName mbo = new ObjectName("log4j:hierarchy=default"); <END> mbs.registerMBean(hdm, mbo); Object rootLogger = Class.forName("org.apache.log4j.Logger") .getMethod("getRootLogger", (Class<?>[]) null) .invoke(null, (Object[]) null); Object rootLoggerName = rootLogger.getClass() .getMethod("getName", (Class<?>[]) null) .invoke(rootLogger, (Object[]) null); hdm.getClass().getMethod("addLoggerMBean", String.class) .invoke(hdm, rootLoggerName); Object r = Class.forName("org.apache.log4j.LogManager") .getMethod("getLoggerRepository", (Class<?>[]) null) .invoke(null, (Object[]) null); Enumeration enumer = (Enumeration) r.getClass() .getMethod("getCurrentLoggers", (Class<?>[]) null) .invoke(r, (Object[]) null); while (enumer.hasMoreElements()) { Object logger = enumer.nextElement(); Object loggerName = logger.getClass() .getMethod("getName", (Class<?>[]) null) .invoke(logger, (Object[]) null); hdm.getClass().getMethod("addLoggerMBean", String.class) .invoke(hdm, loggerName); } } catch (Exception e) { LOG.error("Problems while registering log4j jmx beans!", e); throw new JMException(e.toString()); } } }</code><technical_language>Is change impact integrated systems. this name configurable people able revert name. This change in master (3.6.0) is a public configuration/API change</technical_language>

Target:
public static void registerLog4jMBeans() throws JMException { if (isLog4jJmxEnabled()) { LOG.debug("registerLog4jMBeans()"); MBeanServer mbs = MBeanRegistry.getInstance().getPlatformMBeanServer(); try { Object hdm = Class.forName("org.apache.log4j.jmx.HierarchyDynamicMBean").getConstructor().newInstance(); String mbean = System.getProperty("zookeeper.jmx.log4j.mbean", "log4j:hierarchy=default"); ObjectName mbo = new ObjectName(mbean); mbs.registerMBean(hdm, mbo); Object rootLogger = Class.forName("org.apache.log4j.Logger") .getMethod("getRootLogger", (Class<?>[]) null) .invoke(null, (Object[]) null); Object rootLoggerName = rootLogger.getClass() .getMethod("getName", (Class<?>[]) null) .invoke(rootLogger, (Object[]) null); hdm.getClass().getMethod("addLoggerMBean", String.class) .invoke(hdm, rootLoggerName); Object r = Class.forName("org.apache.log4j.LogManager") .getMethod("getLoggerRepository", (Class<?>[]) null) .invoke(null, (Object[]) null); Enumeration enumer = (Enumeration) r.getClass() .getMethod("getCurrentLoggers", (Class<?>[]) null) .invoke(r, (Object[]) null); while (enumer.hasMoreElements()) { Object logger = enumer.nextElement(); Object loggerName = logger.getClass() .getMethod("getName", (Class<?>[]) null) .invoke(logger, (Object[]) null); hdm.getClass().getMethod("addLoggerMBean", String.class) .invoke(hdm, loggerName); } } catch (Exception e) { LOG.error("Problems while registering log4j jmx beans!", e); throw new JMException(e.toString()); } } }
Source:
<code>public void showChargesList(Page<Charges> chargesPage) { if (mApiRestCounter == 1) { chargesList = chargesPage.getPageItems(); mChargesNameListAdapter = new ChargeNameListAdapter(getActivity(), chargesList, clientId); rv_charges.setAdapter(mChargesNameListAdapter); ll_error.setVisibility(View.GONE); } else { chargesList.addAll(chargesPage.getPageItems()); mChargesNameListAdapter.notifyDataSetChanged(); if (chargesPage.getPageItems().size() == 0 && (chargesPage.getTotalFilteredRecords() == chargesList.size())) <START> Toaster.show(rootView, getString(R.string.no_more_changes_available)); <END> } }</code><technical_language>String name no_more_charges_available no_more_changes_available</technical_language>

Target:
public void showChargesList(Page<Charges> chargesPage) { if (mApiRestCounter == 1) { chargesList = chargesPage.getPageItems(); mChargesNameListAdapter = new ChargeNameListAdapter(getActivity(), chargesList, clientId); rv_charges.setAdapter(mChargesNameListAdapter); ll_error.setVisibility(View.GONE); } else { chargesList.addAll(chargesPage.getPageItems()); mChargesNameListAdapter.notifyDataSetChanged(); if (chargesPage.getPageItems().size() == 0 && (chargesPage.getTotalFilteredRecords() == chargesList.size())) Toaster.show(rootView, getString(R.string.no_more_charges_available)); } }
Source:
<code>public <V> V getAttachment(Logger.AttachmentKey<V> key) { if (key == null) { <START> throw new NullPointerException("key is null"); <END> } synchronized (this) { if (key == attachmentKey1) return (V) attachmentValue1; if (key == attachmentKey2) return (V) attachmentValue2; } return null; }</code><technical_language>wildfly-common for null checks a required dependency. matter though</technical_language>

Target:
public <V> V getAttachment(Logger.AttachmentKey<V> key) { Assert.checkNotNullParam("key", key); synchronized (this) { if (key == attachmentKey1) return (V) attachmentValue1; if (key == attachmentKey2) return (V) attachmentValue2; } return null; }
Source:
<code>private static int msToSeconds(long millis) { <START> return (int) (millis / 1000); <END> }</code><technical_language>TimeUnit.MILLISECONDS.toSeconds() safely in-lined</technical_language>

Target:
private static long msToSeconds(long millis) { return TimeUnit.MILLISECONDS.toSeconds(millis); }
Source:
<code>public boolean visit(final Method method) { int modifiers = method.getModifiers(); if (method.isAnnotationPresent(PostConstruct.class)) { String methodName = method.getName(); if (Modifier.isStatic(modifiers)) { <START> LOG.info("invalid static @PostConstruct method {}.{}()", new Object[] { method.getDeclaringClass().getName(), methodName }); <END> } else if (method.getParameterCount() > 0) { LOG.info("invalid @PostConstruct method {}.{}() with parameters", new Object[] { method.getDeclaringClass().getName(), methodName, method.getParameterCount() }); } else if (Void.TYPE != method.getReturnType()) { LOG.info("invalid @PostConstruct method {}.{}() with return type {}", new Object[] { method.getDeclaringClass().getName(), methodName, method.getReturnType().getName() }); } else { if (!visitContext.contains(methodName)) { if (!method.isAccessible()) { method.setAccessible(true); } PostConstructAction postConstructAction = new PostConstructAction(method); LOG.debug("adding lifecycle action for {}", postConstructAction.description); this.typeActions.addFirst(postConstructAction); visitContext.add(methodName); } } } return true; }</code><technical_language>newObject[]</technical_language>

Target:
public boolean visit(final Method method) { int modifiers = method.getModifiers(); if (method.isAnnotationPresent(PostConstruct.class)) { String methodName = method.getName(); if (Modifier.isStatic(modifiers)) { LOG.info("invalid static @PostConstruct method {}.{}()", new Object[] { method.getDeclaringClass().getName(), methodName }); } else if (method.getParameterCount() > 0) { LOG.info("invalid @PostConstruct method {}.{}() with parameters", new Object[] { method.getDeclaringClass().getName(), methodName, method.getParameterCount() }); } else if (Void.TYPE != method.getReturnType()) { LOG.info("invalid @PostConstruct method {}.{}() with return type {}", new Object[] { method.getDeclaringClass().getName(), methodName, method.getReturnType().getName() }); } else { boolean hasCheckedException=false; if (method.getExceptionTypes().length > 0) { for (Class<?> e : method.getExceptionTypes()) { if (!RuntimeException.class.isAssignableFrom(e)) { LOG.info("invalid @PostConstruct method {}.{}() with checked exception type {}", new Object[] { method.getDeclaringClass().getName(), methodName, e.getName() }); hasCheckedException = true; } } } if (!hasCheckedException && !visitContext.contains(methodName)) { if (!method.isAccessible()) { method.setAccessible(true); } PostConstructAction postConstructAction = new PostConstructAction(method); LOG.debug("adding lifecycle action for {}", postConstructAction.description); this.typeActions.addFirst(postConstructAction); visitContext.add(methodName); } } } return true; }
Source:
<code>public Repository open(HttpServletRequest req, String name) throws RepositoryNotFoundException, ServiceNotEnabledException { if (!name.equals(repoName)) throw new RepositoryNotFoundException(name); <START> final Repository <END> db = repo.getRepository(); db.incrementOpen(); return db; }</code><technical_language>unnecessary</technical_language>

Target:
public Repository open(HttpServletRequest req, String name) throws RepositoryNotFoundException, ServiceNotEnabledException { if (!name.equals(repoName)) throw new RepositoryNotFoundException(name); Repository db = repo.getRepository(); db.incrementOpen(); return db; }