auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void handleGetAdministrativeStatusResponse(final DeviceMessageMetadata deviceMessageMetadata, final ResponseMessageResultType responseMessageResultType, final OsgpException osgpException, final AdministrativeStatusTypeDto administrativeStatusTypeDto) { LOGGER.info("handleGetAdministrativeStatusResponse for MessageType: {}, with result: {}", deviceMessageMetadata.getMessageType(), responseMessageResultType.toString()); ResponseMessageResultType result = responseMessageResultType; if (osgpException != null) { LOGGER.error(DEVICE_RESPONSE_NOT_OK_LOG_MSG, osgpException); result = ResponseMessageResultType.NOT_OK; } final AdministrativeStatusType administrativeStatusType = this.configurationMapper .map(administrativeStatusTypeDto, AdministrativeStatusType.class); <START> this.webServiceResponseMessageSender.send( <END> ResponseMessage.newResponseMessageBuilder() .withCorrelationUid(deviceMessageMetadata.getCorrelationUid()) .withOrganisationIdentification(deviceMessageMetadata.getOrganisationIdentification()) .withDeviceIdentification(deviceMessageMetadata.getDeviceIdentification()).withResult(result) .withOsgpException(osgpException).withDataObject(administrativeStatusType) .withMessagePriority(deviceMessageMetadata.getMessagePriority()).build(), deviceMessageMetadata.getMessageType()); }</code><technical_language>Extract building of ResponseMessage variable (in eclipse, select text, right-click > refactor > extract local variable / select code + shift+alt+L). This code a bit more readable, especially passing in other besides ResponseMessage</technical_language>

Target:
public void handleGetAdministrativeStatusResponse(final DeviceMessageMetadata deviceMessageMetadata, final ResponseMessageResultType responseMessageResultType, final OsgpException osgpException, final AdministrativeStatusTypeDto administrativeStatusTypeDto) { LOGGER.info("handleGetAdministrativeStatusResponse for MessageType: {}, with result: {}", deviceMessageMetadata.getMessageType(), responseMessageResultType.toString()); ResponseMessageResultType result = responseMessageResultType; if (osgpException != null) { LOGGER.error(DEVICE_RESPONSE_NOT_OK_LOG_MSG, osgpException); result = ResponseMessageResultType.NOT_OK; } final AdministrativeStatusType administrativeStatusType = this.configurationMapper .map(administrativeStatusTypeDto, AdministrativeStatusType.class); ResponseMessage responseMessage = ResponseMessage.newResponseMessageBuilder() .withCorrelationUid(deviceMessageMetadata.getCorrelationUid()) .withOrganisationIdentification(deviceMessageMetadata.getOrganisationIdentification()) .withDeviceIdentification(deviceMessageMetadata.getDeviceIdentification()).withResult(result) .withOsgpException(osgpException).withDataObject(administrativeStatusType) .withMessagePriority(deviceMessageMetadata.getMessagePriority()).build(); this.webServiceResponseMessageSender.send( responseMessage, deviceMessageMetadata.getMessageType()); }
Source:
<code>public TestNGTestListener() { <START> EnvironmentCheck.checkJVMVersion(); <END> progressLogger = new TestSuiteProgress(); }</code><technical_language>For TestNG modules throw exception in TestNGSuiteChecksTest.beforeSuite() instead of calling System.exit()</technical_language>

Target:
public TestNGTestListener() { progressLogger = new TestSuiteProgress(); }
Source:
<code>public @Nullable Comparator<?> getComparator() { <START> return new Comparator<CalledFunction>() { <END> @Override public int compare(@Nullable CalledFunction o1, @Nullable CalledFunction o2) { if (o1 == null || o2 == null) { throw new IllegalArgumentException(); } return Long.compare(o1.getLength(), o2.getLength()); } }; }</code><technical_language>ClassCastException? this need ICalledFunction? ISegment instanceof checks</technical_language>

Target:
public @Nullable Comparator<?> getComparator() { return new Comparator<ISegment>() { @Override public int compare(@Nullable ISegment o1, @Nullable ISegment o2) { if (o1 == null || o2 == null) { throw new IllegalArgumentException(); } return Long.compare(o1.getLength(), o2.getLength()); } }; }
Source:
<code>public Image getImage() { Iterable<TemporalField<Image>> primaryImages = Iterables.filter( images, <START> new Predicate<TemporalField<Image>>() { <END> @Override public boolean apply(TemporalField<Image> input) { Image image = input.getValue(); return IS_PRIMARY_IMAGE.apply(image); } } ); return TemporalField.currentOrFutureValue(primaryImages); }</code><technical_language>I MorePredicates.transformingPredicate(TermporalField.toValueFunction(), IS_PRIMARY_IMAGE) here</technical_language>

Target:
public Image getImage() { Iterable<TemporalField<Image>> primaryImages = Iterables.filter( images, MorePredicates.transformingPredicate(TemporalField.<Image>toValueFunction(), IS_PRIMARY_IMAGE) ); return TemporalField.currentOrFutureValue(primaryImages); }
Source:
<code>public void updateMapping(final JID jid, final Map<String, String> resourceNameMapping) { final Map<String, String> lastResourceNameMapping = getMapping(jid); final Set<String> resourceNameDestinations = new HashSet<>(resourceNameMapping.values()); <START> for (final Iterator<Entry<String, String>> it = lastResourceNameMapping.entrySet().iterator(); <END> it.hasNext(); ) { final Entry<String, String> entry = it.next(); if (resourceNameDestinations.contains(entry.getValue())) it.remove(); } lastResourceNameMapping.putAll(resourceNameMapping); if (lastResourceNameMapping.isEmpty()) return; final StringBuilder builder = new StringBuilder(); for (final Entry<String, String> entry : lastResourceNameMapping.entrySet()) { builder.append(escape(entry.getKey())); builder.append(DELIMITER); builder.append(escape(entry.getValue())); builder.append(DELIMITER); } builder.setLength(builder.length() - 1); store.setValue(RESOURCE_MAPPING_STORE_PREFIX + jid.getBase(), builder.toString()); }</code><technical_language>I prefer a while loop defining iterator is easier read / unexpected. assumption is a for loop garbage collector (by binding variable loop scope). this is a bit confusing read</technical_language>

Target:
public void updateMapping(final JID jid, final Map<String, String> resourceNameMapping) { final Map<String, String> lastResourceNameMapping = getMapping(jid); final Set<String> resourceNameDestinations = new HashSet<>(resourceNameMapping.values()); final Iterator<Entry<String, String>> it = lastResourceNameMapping.entrySet().iterator(); while (it.hasNext()) { final Entry<String, String> entry = it.next(); if (resourceNameDestinations.contains(entry.getValue())) it.remove(); } lastResourceNameMapping.putAll(resourceNameMapping); if (lastResourceNameMapping.isEmpty()) return; final StringBuilder builder = new StringBuilder(); for (final Entry<String, String> entry : lastResourceNameMapping.entrySet()) { builder.append(escape(entry.getKey())); builder.append(DELIMITER); builder.append(escape(entry.getValue())); builder.append(DELIMITER); } builder.setLength(builder.length() - DELIMITER.length()); store.setValue(RESOURCE_MAPPING_STORE_PREFIX + jid.getBase(), builder.toString()); }
Source:
<code>public Iterator<String> iterator() { <START> LOG.debug("Not json, hoping it is a good string : %s", string); <END> return Splitter.on( new CharMatcher() { private boolean inQuotes = false; @Override public boolean matches(char c) { if ('"' == c) { inQuotes = !inQuotes; } if (inQuotes) { return false; } return CharMatcher.BREAKING_WHITESPACE.matches(c); } } ).omitEmptyStrings().split(string).iterator(); }</code><technical_language>this debug msg is valid anymore</technical_language>

Target:
public Iterator<String> iterator() { return Splitter.on( new CharMatcher() { private boolean inQuotes = false; @Override public boolean matches(char c) { if ('"' == c) { inQuotes = !inQuotes; } if (inQuotes) { return false; } return CharMatcher.BREAKING_WHITESPACE.matches(c); } } ).omitEmptyStrings().split(string).iterator(); }
Source:
<code>private void handleRequest(RpcMessageProto rpcRequestProto, ByteString rpcContent, RpcModule module) { Tracer.SpanBuilder spanBuilder = buildSpanFromRpcMessage(rpcRequestProto); Span minionSpan = spanBuilder.start(); RpcRequest request = module.unmarshalRequest(rpcContent.toStringUtf8()); setTagsOnMinion(rpcRequestProto, request, minionSpan); CompletableFuture<RpcResponse> future = module.execute(request); future.whenComplete((res, ex) -> { final RpcResponse response; if (ex != null) { LOG.warn("An error occured while executing a call in {}.", module.getId(), ex); response = module.createResponseWithException(ex); minionSpan.log(ex.getMessage()); minionSpan.setTag(TAG_RPC_FAILED, "true"); } else { response = res; } minionSpan.finish(); <START> bulkhead.onComplete(); <END> sendResponse(rpcRequestProto.getRpcId(), response, module); }); }</code><technical_language>This called if tryAcquirePermission returned true</technical_language>

Target:
private void handleRequest(RpcMessageProto rpcRequestProto, ByteString rpcContent, RpcModule module) { Tracer.SpanBuilder spanBuilder = buildSpanFromRpcMessage(rpcRequestProto); Span minionSpan = spanBuilder.start(); RpcRequest request = module.unmarshalRequest(rpcContent.toStringUtf8()); setTagsOnMinion(rpcRequestProto, request, minionSpan); CompletableFuture<RpcResponse> future = module.execute(request); final Meter requestSentMeter = getMetrics().meter(MetricRegistry.name(module.getId(), RPC_REQUESTS_RECEIVED)); requestSentMeter.mark(); future.whenComplete((res, ex) -> { final RpcResponse response; if (ex != null) { LOG.warn("An error occured while executing a call in {}.", module.getId(), ex); response = module.createResponseWithException(ex); minionSpan.log(ex.getMessage()); minionSpan.setTag(TAG_RPC_FAILED, "true"); Meter failedMeter = getMetrics().meter(MetricRegistry.name(module.getId(), RPC_FAILED)); failedMeter.mark(); } else { response = res; } minionSpan.finish(); uncheckBulkhead(); sendResponse(rpcRequestProto.getRpcId(), response, module); }); }
Source:
<code>public void onReceive(Context ctx, Intent intent) { String referrerStr = intent.getStringExtra(REFERRER_KEY); L.d("Received install referrer: " + referrerStr); if (!INSTALL_ACTION.equals(intent.getAction()) || TextUtils.isEmpty(referrerStr)) { return; } try { Uri uri = Uri.parse("/?" + referrerStr); <START> String refUrl = uri.getQueryParameter(InstallReferrerFunnel.PARAM_REFERRER_URL); <END> String refCampaignId = uri.getQueryParameter(InstallReferrerFunnel.PARAM_CAMPAIGN_ID); String refCampaignInstallId = uri.getQueryParameter(InstallReferrerFunnel.PARAM_CAMPAIGN_INSTALL_ID); if (!TextUtils.isEmpty(refUrl) || !TextUtils.isEmpty(refCampaignId) || !TextUtils.isEmpty(refCampaignInstallId)) { InstallReferrerFunnel funnel = new InstallReferrerFunnel(WikipediaApp.getInstance()); funnel.logInstall(refUrl, refCampaignId, refCampaignInstallId); } } catch (UnsupportedOperationException e) { } }</code><technical_language>tighten scope of this try block? code check emptiness of variables, additional code needed minimal</technical_language>

Target:
public void onReceive(Context ctx, Intent intent) { String referrerStr = intent.getStringExtra(REFERRER_KEY); L.d("Received install referrer: " + referrerStr); if (!INSTALL_ACTION.equals(intent.getAction()) || TextUtils.isEmpty(referrerStr)) { return; } String refUrl = null; String refCampaignId = null; String refCampaignInstallId = null; try { Uri uri = Uri.parse("/?" + referrerStr); refUrl = uri.getQueryParameter(InstallReferrerFunnel.PARAM_REFERRER_URL); refCampaignId = uri.getQueryParameter(InstallReferrerFunnel.PARAM_CAMPAIGN_ID); refCampaignInstallId = uri.getQueryParameter(InstallReferrerFunnel.PARAM_CAMPAIGN_INSTALL_ID); } catch (UnsupportedOperationException e) { } if (!TextUtils.isEmpty(refUrl) || !TextUtils.isEmpty(refCampaignId) || !TextUtils.isEmpty(refCampaignInstallId)) { InstallReferrerFunnel funnel = new InstallReferrerFunnel(WikipediaApp.getInstance()); funnel.logInstall(refUrl, refCampaignId, refCampaignInstallId); } }
Source:
<code>private StreamWriter getStreamWriterForPipe(PipeConfiguration pipeConf) throws IOException { StreamClient client = pipeConf.getSinkConfiguration().getStreamClient(); String streamName = pipeConf.getSinkConfiguration().getStreamName(); try { client.create(streamName); StreamWriter writer = null; <START> writer = client.createWriter(streamName); <END> return writer; } catch (IOException e) { throw new IOException("Can not create/get client stream by name:" + streamName + ": " + e.getMessage()); } }</code><technical_language>do StreamWriter writer = client.createWriter(streamName)</technical_language>

Target:
private StreamWriter getStreamWriterForPipe(PipeConfiguration pipeConf) throws IOException { StreamClient client = pipeConf.getSinkConfiguration().getStreamClient(); String streamName = pipeConf.getSinkConfiguration().getStreamName(); try { client.create(streamName); StreamWriter writer = client.createWriter(streamName); return writer; } catch (IOException e) { throw new IOException(String.format("Cannot create/get client stream by name: %s: %s", streamName, e)); } }
Source:
<code>public LoadFileUtils() { <START> throw new IllegalAccessError("This utility class as static methods, you should not instantiate this object."); <END> }</code><technical_language>Minor typo in error message (should "has" instead of "as")</technical_language>

Target:
public LoadFileUtils() { throw new IllegalAccessError("This utility class has static methods, you should not instantiate this object."); }
Source:
<code>private BytesValues(byte[][] values, boolean nullAllowed) { super(true, nullAllowed); requireNonNull(values, "values is null"); <START> checkArgument(values.length > 0, "values must contain at least 1 entries"); <END> this.values = values; lengthExists = new boolean[Arrays.stream(values).mapToInt(value -> value.length).max().getAsInt() + 1]; int hashTableSize = Integer.highestOneBit(values.length * 4); hashTableSizeMask = hashTableSize - 1; hashTable = new byte[hashTableSize][]; bloomSize = Math.max(1, hashTableSize / 8); bloom = new long[bloomSize]; for (byte[] value : values) { lengthExists[value.length] = true; long hashCode = hash(value, 0, value.length); bloom[bloomIndex(hashCode)] |= bloomMask(hashCode); int position = (int) (hashCode & hashTableSizeMask); for (int i = position; i <= position + hashTableSizeMask; i++) { int index = i & hashTableSizeMask; if (hashTable[index] == null) { hashTable[index] = value; break; } if (compareRanges(value, 0, value.length, hashTable[index], 0, hashTable[index].length) == 0) { break; } } } }</code><technical_language>message needs updating: checkArgument(values.length > 0, "values empty");</technical_language>

Target:
private BytesValues(byte[][] values, boolean nullAllowed) { super(true, nullAllowed); requireNonNull(values, "values is null"); checkArgument(values.length > 0, "values must not be empty"); this.values = values; lengthExists = new boolean[Arrays.stream(values).mapToInt(value -> value.length).max().getAsInt() + 1]; int hashTableSize = Integer.highestOneBit(values.length * 4); hashTableSizeMask = hashTableSize - 1; hashTable = new byte[hashTableSize][]; bloomSize = Math.max(1, hashTableSize / 8); bloom = new long[bloomSize]; for (byte[] value : values) { lengthExists[value.length] = true; long hashCode = hash(value, 0, value.length); bloom[bloomIndex(hashCode)] |= bloomMask(hashCode); int position = (int) (hashCode & hashTableSizeMask); for (int i = position; i <= position + hashTableSizeMask; i++) { int index = i & hashTableSizeMask; if (hashTable[index] == null) { hashTable[index] = value; break; } if (compareRanges(value, 0, value.length, hashTable[index], 0, hashTable[index].length) == 0) { break; } } } }
Source:
<code>private BlackboardArtifact createDownloadSourceArtifact(AbstractFile downloadFile, ZoneIdentifierInfo zoneInfo) { Collection<BlackboardAttribute> bbattributes = new ArrayList<>(); bbattributes.add(new BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_URL, <START> RecentActivityExtracterModuleFactory.getModuleName(), <END> (zoneInfo.getURL() != null) ? zoneInfo.getURL() : "")); bbattributes.add(new BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_DOMAIN, RecentActivityExtracterModuleFactory.getModuleName(), (zoneInfo.getURL() != null) ? NetworkUtils.extractDomain(zoneInfo.getURL()) : "")); bbattributes.add(new BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_LOCATION, RecentActivityExtracterModuleFactory.getModuleName(), (zoneInfo.getZoneIdAsString() != null) ? zoneInfo.getZoneIdAsString() : "")); return addArtifact(BlackboardArtifact.ARTIFACT_TYPE.TSK_DOWNLOAD_SOURCE, downloadFile, bbattributes); }</code><technical_language>I some static imports bbattributes.addAll(asLists(....)) remove alot of noise here</technical_language>

Target:
private BlackboardArtifact createDownloadSourceArtifact(AbstractFile downloadFile, ZoneIdentifierInfo zoneInfo) { Collection<BlackboardAttribute> bbattributes = new ArrayList<>(); bbattributes.addAll(Arrays.asList( new BlackboardAttribute(TSK_URL, RecentActivityExtracterModuleFactory.getModuleName(), StringUtils.defaultString(zoneInfo.getURL(), "")), new BlackboardAttribute(TSK_DOMAIN, RecentActivityExtracterModuleFactory.getModuleName(), (zoneInfo.getURL() != null) ? NetworkUtils.extractDomain(zoneInfo.getURL()) : ""), new BlackboardAttribute(TSK_LOCATION, RecentActivityExtracterModuleFactory.getModuleName(), StringUtils.defaultString(zoneInfo.getZoneIdAsString(), "")))); return addArtifact(TSK_DOWNLOAD_SOURCE, downloadFile, bbattributes); }
Source:
<code>protected void disableAndRemoveECrossReferenceAdapters() { ResourceSet resourceSet = getTransactionalEditingDomain().getResourceSet(); List<Adapter> adaptersToRemove = new ArrayList<Adapter>(); for (Adapter next : resourceSet.eAdapters()) { if (next instanceof SiriusCrossReferenceAdapter) { ((SiriusCrossReferenceAdapter) next).disableResolveProxy(); adaptersToRemove.add(next); } } resourceSet.eAdapters().removeAll(adaptersToRemove); for (Resource resource : resourceSet.getResources()) { disableCrossReferencerResolve(resource); resource.eAdapters().clear(); } Collection<Resource> semanticResources = getSemanticResources(); <START> EList<Resource> <END> controlledResources = getControlledResources(); Set<Resource> allSessionResources = getAllSessionResources(); ECrossReferenceAdapterWithUnproxyCapability semanticCrossReferencer = getSemanticCrossReferencer(); Iterable<Resource> resources = Iterables.concat(semanticResources, controlledResources, allSessionResources); for (Resource resource : resources) { if (!(resourceSet.getResources().contains(resource))) { disableCrossReferencerResolve(resource); resource.eAdapters().remove(semanticCrossReferencer); } } for (final DAnalysis analysis : Iterables.filter(allAnalyses(), Predicates.notNull())) { removeAdaptersOnAnalysis(analysis); } }</code><technical_language>Collection is enough</technical_language>

Target:
protected void disableAndRemoveECrossReferenceAdapters() { ResourceSet resourceSet = getTransactionalEditingDomain().getResourceSet(); List<Adapter> adaptersToRemove = new ArrayList<Adapter>(); for (Adapter next : resourceSet.eAdapters()) { if (next instanceof SiriusCrossReferenceAdapter) { ((SiriusCrossReferenceAdapter) next).disableResolveProxy(); adaptersToRemove.add(next); } } resourceSet.eAdapters().removeAll(adaptersToRemove); for (Resource resource : resourceSet.getResources()) { disableCrossReferencerResolve(resource); resource.eAdapters().clear(); } Collection<Resource> semanticResources = getSemanticResources(); Collection<Resource> controlledResources = getControlledResources(); Set<Resource> allSessionResources = getAllSessionResources(); Object semanticCrossReferencer = getSemanticCrossReferencer(); Iterable<Resource> resources = Iterables.concat(semanticResources, controlledResources, allSessionResources); for (Resource resource : resources) { if (!(resourceSet.getResources().contains(resource))) { disableCrossReferencerResolve(resource); resource.eAdapters().remove(semanticCrossReferencer); } } for (final DAnalysis analysis : Iterables.filter(allAnalyses(), Predicates.notNull())) { removeAdaptersOnAnalysis(analysis); } }
Source:
<code>public SpatialKnownIndex( IndexDirectoryStructure directoryStructure, CoordinateReferenceSystem crs, long indexId, PageCache pageCache, FileSystemAbstraction fs, SchemaIndexProvider.Monitor monitor, RecoveryCleanupWorkCollector recoveryCleanupWorkCollector ) { this.crs = crs; this.indexId = indexId; this.pageCache = pageCache; this.fs = fs; this.monitor = monitor; this.recoveryCleanupWorkCollector = recoveryCleanupWorkCollector; SchemaIndexProvider.Descriptor crsDescriptor = new SchemaIndexProvider.Descriptor( Integer.toString( crs.getTable().getTableId() ), Integer.toString( crs.getCode() ) ); <START> IndexDirectoryStructure indexDir = IndexDirectoryStructure.directoriesBySubProvider( directoryStructure ).forProvider( crsDescriptor ); <END> indexFile = new File( indexDir.directoryForIndex( indexId ), indexFileName( indexId ) ); curve = new HilbertSpaceFillingCurve2D( envelopeFromCRS( crs ), 8 ); }</code><technical_language>Long line</technical_language>

Target:
public SpatialKnownIndex( IndexDirectoryStructure directoryStructure, CoordinateReferenceSystem crs, long indexId, PageCache pageCache, FileSystemAbstraction fs, SchemaIndexProvider.Monitor monitor, RecoveryCleanupWorkCollector recoveryCleanupWorkCollector ) { this.crs = crs; this.indexId = indexId; this.pageCache = pageCache; this.fs = fs; this.monitor = monitor; this.recoveryCleanupWorkCollector = recoveryCleanupWorkCollector; SchemaIndexProvider.Descriptor crsDescriptor = new SchemaIndexProvider.Descriptor( Integer.toString( crs.getTable().getTableId() ), Integer.toString( crs.getCode() ) ); IndexDirectoryStructure indexDir = IndexDirectoryStructure.directoriesBySubProvider( directoryStructure ).forProvider( crsDescriptor ); indexFile = new File( indexDir.directoryForIndex( indexId ), "index-" + indexId ); curve = new HilbertSpaceFillingCurve2D( envelopeFromCRS( crs ), 8 ); state = State.NONE; }
Source:
<code>public static File createTempFile(String prefix, String suffix, File parentDir, boolean deleteOnExit) throws IOException { File result = null; File parent = (parentDir == null) ? getDefaultTempDir() : parentDir; if (suffix == null) { suffix = ".tmp"; } if (prefix == null) { prefix = "cxf"; } else if (prefix.length() < 3) { prefix = prefix + "cxf"; } result = Files.createTempFile(parent.toPath(), prefix, suffix).toFile(); if (deleteOnExit && parentDir != null) { result.deleteOnExit(); } return result; <START> } <END></code><technical_language>if wise removing public methods for a minor patch, wait move 3.4.0-SNAPSHOT</technical_language>

Target:
public static File createTempFile(String prefix, String suffix, File parentDir, boolean deleteOnExit) throws IOException { File parent = (parentDir == null) ? getDefaultTempDir() : parentDir; if (prefix == null) { prefix = "cxf"; } else if (prefix.length() < 3) { prefix = prefix + "cxf"; } File result = Files.createTempFile(parent.toPath(), prefix, suffix).toFile(); if (deleteOnExit && parentDir != null) { result.deleteOnExit(); } return result; }
Source:
<code>public String url(boolean isHttps) { String mergedIP = ipAddress().replaceAll("\\.", ""); char[] domainChars = mergedIP.toCharArray(); for (int i = 0; i < domainChars.length; i++) { char c = domainChars[i]; domainChars[i] = (char) (c + 97); } <START> String domain = String.valueOf(domainChars); <END> if (isHttps) return "https://" + domain + ".com"; else return "http://" + domain + ".com"; }</code><technical_language>Please add improve readability</technical_language>

Target:
public String url(boolean isHttps) { String mergedIP = ipAddress().replaceAll("\\.", ""); char[] domainChars = mergedIP.toCharArray(); for (int i = 0; i < domainChars.length; i++) { char c = domainChars[i]; domainChars[i] = (char) (c + 97); } String domain = String.valueOf(domainChars); if (isHttps) { return "https://" + domain + ".com"; } else { return "http://" + domain + ".com"; } }
Source:
<code>public void run(BatchActionContext batchActionContext) throws Exception { int retries = 0; Exception exception = null; do { HttpURLConnection conn = null; Map<String, List<String>> headers = conf.parseRequestProperties(); try { URL url = new URL(conf.url); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod(conf.method); conn.setConnectTimeout(conf.connectTimeoutMillis); for (Map.Entry<String, List<String>> propertyEntry : headers.entrySet()) { String propertyKey = propertyEntry.getKey(); for (String propertyValue : propertyEntry.getValue()) { <START> conn.setRequestProperty(propertyKey, propertyValue); <END> } } if (conf.body != null) { conn.setDoOutput(true); try (OutputStream outputStream = conn.getOutputStream()) { outputStream.write(conf.body.getBytes(Charsets.UTF_8)); } } LOG.info("Request to resulted in response code {}.", conf.url, conn.getResponseCode()); break; } catch (MalformedURLException | ProtocolException e) { throw new IllegalStateException("Error opening url connection. Reason: " + e.getMessage(), e); } catch (Exception e) { LOG.warn("Error making request to url with headers {}.", conf.method, conf.url, headers); exception = e; } finally { if (conn != null) { conn.disconnect(); } } retries++; } while (retries < conf.numRetries); if (exception != null) { throw exception; } }</code><technical_language>do want call addRequestProperty</technical_language>

Target:
public void run(BatchActionContext batchActionContext) throws Exception { int retries = 0; Exception exception = null; do { HttpURLConnection conn = null; Map<String, List<String>> headers = conf.parseRequestProperties(); try { URL url = new URL(conf.url); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod(conf.method); conn.setConnectTimeout(conf.connectTimeoutMillis); for (Map.Entry<String, List<String>> propertyEntry : headers.entrySet()) { String propertyKey = propertyEntry.getKey(); for (String propertyValue : propertyEntry.getValue()) { conn.addRequestProperty(propertyKey, propertyValue); } } if (conf.body != null) { conn.setDoOutput(true); try (OutputStream outputStream = conn.getOutputStream()) { outputStream.write(conf.body.getBytes(Charsets.UTF_8)); } } LOG.info("Request to resulted in response code {}.", conf.url, conn.getResponseCode()); break; } catch (MalformedURLException | ProtocolException e) { throw new IllegalStateException("Error opening url connection. Reason: " + e.getMessage(), e); } catch (Exception e) { LOG.warn("Error making request to url with headers {}.", conf.method, conf.url, headers); exception = e; } finally { if (conn != null) { conn.disconnect(); } } retries++; } while (retries < conf.numRetries); if (exception != null) { throw exception; } }
Source:
<code>public boolean delete(long contestPK) { <START> final boolean[] result = new boolean[1]; <END> dslContext.transaction(configuration -> { DSLContext ctx = DSL.using(configuration); deleteContestData(ctx, contestPK); deleteContestPhases(ctx, contestPK); deleteOrphanProposals(ctx); result[0] = deleteContest(ctx, contestPK); }); return result[0]; }</code><technical_language>AtomicBoolean usable lambda nicer read instead of single-element array</technical_language>

Target:
public boolean delete(long contestPK) { AtomicBoolean result = new AtomicBoolean(); dslContext.transaction(configuration -> { DSLContext ctx = DSL.using(configuration); deleteContestData(ctx, contestPK); deleteContestPhases(ctx, contestPK); deleteOrphanProposals(ctx); result.set(deleteContest(ctx, contestPK)); }); return result.get(); }
Source:
<code>public String createHiddenSpace(String spaceId, int expirationInDays) { String bucketName = getHiddenBucketName(spaceId); try { Bucket bucket = s3Client.createBucket(bucketName); BucketLifecycleConfiguration.Rule expiresRule = new BucketLifecycleConfiguration.Rule() <START> .withId("ExpireInSeconds") <END> .withExpirationInDays(expirationInDays) .withStatus(BucketLifecycleConfiguration.ENABLED); BucketLifecycleConfiguration configuration = new BucketLifecycleConfiguration() .withRules(expiresRule); s3Client.setBucketLifecycleConfiguration(bucketName, configuration); return spaceId; } catch (AmazonClientException e) { String err = "Could not create S3 bucket with name " + bucketName + " due to error: " + e.getMessage(); throw new StorageException(err, e, RETRY); } }</code><technical_language>This Id confusing expiration is set a multiple of days</technical_language>

Target:
public String createHiddenSpace(String spaceId, int expirationInDays) { String bucketName = getHiddenBucketName(spaceId); try { Bucket bucket = s3Client.createBucket(bucketName); BucketLifecycleConfiguration.Rule expiresRule = new BucketLifecycleConfiguration.Rule() .withId("ExpirationRule") .withExpirationInDays(expirationInDays) .withStatus(BucketLifecycleConfiguration.ENABLED); BucketLifecycleConfiguration configuration = new BucketLifecycleConfiguration() .withRules(expiresRule); s3Client.setBucketLifecycleConfiguration(bucketName, configuration); return spaceId; } catch (AmazonClientException e) { String err = "Could not create S3 bucket with name " + bucketName + " due to error: " + e.getMessage(); throw new StorageException(err, e, RETRY); } }
Source:
<code>protected void execute() { for (ExpireBindingProvider provider : providers) { for (String itemName : provider.getItemNames()) { Long nextExpireTs = nextExpireTsMap.get(itemName); if (nextExpireTs == null || nextExpireTs <= System.currentTimeMillis()) { <START> logger.info("Item was not updated for - setting state to undefined", itemName, "5s"); <END> eventPublisher.postUpdate(itemName, UnDefType.UNDEF); nextExpireTsMap.put(itemName, Long.MAX_VALUE); } } } }</code><technical_language>Hello, nice idea, i some neat cases for this. hat this line require a more dynamic instead of 5s</technical_language>

Target:
protected void execute() { for (ExpireBindingProvider provider : providers) { for (String itemName : provider.getItemNames()) { Long nextExpireTs = nextExpireTsMap.get(itemName); if (nextExpireTs == null) { long expireAfterMs = provider.getExpiresAfterMs(itemName); nextExpireTsMap.put(itemName, System.currentTimeMillis() + expireAfterMs); } else if (nextExpireTs <= System.currentTimeMillis()) { State newState = provider.getExpiredState(itemName); logger.debug("Item was not updated for - setting state to {}", itemName, provider.getExpiresAfterAsText(itemName), newState); eventPublisher.postUpdate(itemName, newState); nextExpireTsMap.put(itemName, Long.MAX_VALUE); } } } }
Source:
<code>public void shutdown() throws StoreException { long startTimeInMs = time.milliseconds(); synchronized (storeWriteLock) { checkStarted(); try { logger.info("Store : " + dataDir + " shutting down"); blobStoreStats.close(); <START> metrics.deregisterMetrics(storeId); <END> compactor.close(30); index.close(); log.close(); started = false; } catch (Exception e) { logger.error("Store : " + dataDir + " shutdown of store failed for directory ", e); } finally { try { fileLock.destroy(); } catch (IOException e) { logger.error("Store : " + dataDir + " IO Exception while trying to close the file lock", e); } metrics.storeShutdownTimeInMs.update(time.milliseconds() - startTimeInMs); } } }</code><technical_language>deregister log is closed</technical_language>

Target:
public void shutdown() throws StoreException { long startTimeInMs = time.milliseconds(); synchronized (storeWriteLock) { checkStarted(); try { logger.info("Store : " + dataDir + " shutting down"); blobStoreStats.close(); compactor.close(30); index.close(); log.close(); metrics.deregisterMetrics(storeId); started = false; } catch (Exception e) { logger.error("Store : " + dataDir + " shutdown of store failed for directory ", e); } finally { try { fileLock.destroy(); } catch (IOException e) { logger.error("Store : " + dataDir + " IO Exception while trying to close the file lock", e); } metrics.storeShutdownTimeInMs.update(time.milliseconds() - startTimeInMs); } } }
Source:
<code>public void createFullTextResource() throws IOException, JsonParseException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { String requestBody = getJsonStringInput(DESCRIBING_WEB_RESOURCE); <START> Annotation storedAnno = createDescribing(requestBody); <END> assertTrue(storedAnno.getMotivation().equals(MotivationTypes.DESCRIBING.name().toLowerCase())); assertTrue(storedAnno.getTarget().getSource() != null); assertEquals(storedAnno.getBody().getInternalType(), BodyInternalTypes.TEXT.name()); }</code><technical_language>replace createAnnotation</technical_language>

Target:
public void createFullTextResource() throws IOException, JsonParseException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { String requestBody = getJsonStringInput(DESCRIBING_WEB_RESOURCE); ResponseEntity<String> response = getApiClient().createAnnotation( getApiKey(), WebAnnotationFields.PROVIDER_WEBANNO, null, true, requestBody, TEST_USER_TOKEN, null ); assertNotNull(response.getBody()); assertEquals(response.getStatusCode(), HttpStatus.CREATED); Annotation storedAnno = getApiClient().parseResponseBody(response); assertTrue(storedAnno.getMotivation().equals(MotivationTypes.DESCRIBING.name().toLowerCase())); assertTrue(storedAnno.getTarget().getSource() != null); assertEquals(storedAnno.getBody().getInternalType(), BodyInternalTypes.TEXT.name()); }
Source:
<code>public static void setup() { <START> CliClientFactory.getClient(); <END> dsOps = new DataSourcesOperations(client); dsNameValid = dsOps.createDataSource(VALID_URL); dsNameInvalid = dsOps.createDataSource(INVALID_URL); xaDsNameInvalid = dsOps.createXADataSource(INVALID_URL); xaDsNameValid = dsOps.createXADataSource(VALID_URL); client.reload(); }</code><technical_language>is variable assignment missing</technical_language>

Target:
public static void setup() { client = CliClientFactory.getClient(); dsOps = new DataSourcesOperations(client); dsNameValid = dsOps.createDataSource(VALID_URL); dsNameInvalid = dsOps.createDataSource(INVALID_URL); xaDsNameInvalid = dsOps.createXADataSource(INVALID_URL); xaDsNameValid = dsOps.createXADataSource(VALID_URL); client.reload(); }
Source:
<code>public long getTime(String hostname) { try { NTPUDPClient timeClient = new NTPUDPClient(); timeClient.setDefaultTimeout(NTP_TIMEOUT); InetAddress inetAddress = InetAddress.getByName(hostname); TimeInfo timeInfo = timeClient.getTime(inetAddress); logger.debug("{} Got time update from: : {}", getThing().getUID().toString(), hostname, SDF.format(new Date(timeInfo.getReturnTime()))); updateStatus(ThingStatus.ONLINE, ThingStatusDetail.NONE); return timeInfo.getReturnTime(); } catch (UnknownHostException uhe) { String msg = getThing().getUID().toString() + " the given hostname '" + hostname + "' of the timeserver is unknown -> returning current sytem time instead."; <START> logger.info(msg); <END> updateStatus(ThingStatus.ONLINE, ThingStatusDetail.COMMUNICATION_ERROR, msg); } catch (IOException ioe) { String msg = getThing().getUID().toString() + " couldn't establish network connection [host '" + hostname + "'] -> returning current sytem time instead."; logger.info(msg); updateStatus(ThingStatus.ONLINE, ThingStatusDetail.COMMUNICATION_ERROR, msg); } return System.currentTimeMillis(); }</code><technical_language>I for debug level message is logged a status update</technical_language>

Target:
public long getTime(String hostname) { try { NTPUDPClient timeClient = new NTPUDPClient(); timeClient.setDefaultTimeout(NTP_TIMEOUT); InetAddress inetAddress = InetAddress.getByName(hostname); TimeInfo timeInfo = timeClient.getTime(inetAddress); logger.debug("{} Got time update from: : {}", getThing().getUID().toString(), hostname, SDF.format(new Date(timeInfo.getReturnTime()))); updateStatus(ThingStatus.ONLINE, ThingStatusDetail.NONE); return timeInfo.getReturnTime(); } catch (UnknownHostException uhe) { String msg = getThing().getUID().toString() + " the given hostname '" + hostname + "' of the timeserver is unknown -> returning current sytem time instead."; logger.debug(msg); updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, msg); } catch (IOException ioe) { String msg = getThing().getUID().toString() + " couldn't establish network connection [host '" + hostname + "'] -> returning current sytem time instead."; logger.debug(msg); updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, msg); } return System.currentTimeMillis(); }
Source:
<code><START> protected String gtk_rgba_to_css_string (GdkRGBA rgba) { <END> String color = "rgba(" + (int)(rgba.red * 255) + "," + (int)(rgba.green * 255) + "," + (int)(rgba.blue * 255) + "," + (int)(rgba.alpha * 255) + ")"; return color; }</code><technical_language>This protected package</technical_language>

Target:
String gtk_rgba_to_css_string (GdkRGBA rgba) { String color = "rgba(" + (int)(rgba.red * 255) + "," + (int)(rgba.green * 255) + "," + (int)(rgba.blue * 255) + "," + (int)(rgba.alpha * 255) + ")"; return color; }
Source:
<code>public void provision(KubernetesEnvironment kubernetesEnvironment) throws InfrastructureException { for (ChePluginEndpoint endpoint : endpoints) {; <START> if (Boolean.parseBoolean(endpoint.getAttributes().getOrDefault("discoverable", "true"))) { <END> String serviceName = endpoint.getName(); Service service = createService(serviceName, podName, endpoint.getTargetPort()); Map<String, Service> services = kubernetesEnvironment.getServices(); if (!services.containsKey(serviceName)) { services.put(serviceName, service); } else { throw new InfrastructureException( format( "Applying of sidecar tooling failed. Kubernetes service with name '%s' already exists in the workspace environment.", serviceName)); } } } }</code><technical_language>Increase of nesting harder read, next approach better: if (!Boolean.parseBoolean(endpoint.getAttributes().getOrDefault("discoverable", "true"))) { continue; } that, reading operations needed check server discoverable code clean harder read. single-use private methods I recommend code cleaner</technical_language>

Target:
public void provision(KubernetesEnvironment kubernetesEnvironment) throws InfrastructureException { for (ChePluginEndpoint endpoint : endpoints) { if (!isDiscoverable(endpoint)) { continue; } String serviceName = endpoint.getName(); Service service = createService(serviceName, podName, endpoint.getTargetPort()); Map<String, Service> services = kubernetesEnvironment.getServices(); if (!services.containsKey(serviceName)) { services.put(serviceName, service); } else { throw new InfrastructureException( format( "Applying of sidecar tooling failed. Kubernetes service with name '%s' already exists in the workspace environment.", serviceName)); } } }
Source:
<code>private Optional<String> getEncoding(InputStream in) throws IOException { <START> InputStream inputStream = Objects.requireNonNull(in); <END> if (!inputStream.markSupported()) { inputStream = new BufferedInputStream(inputStream); } CharsetDetector detector = new CharsetDetector(); detector.setText(inputStream); CharsetMatch charsetMatch = detector.detect(); return charsetMatch == null ? Optional.empty() : Optional.of(charsetMatch.getName()); }</code><technical_language>this is needed. If null, throw NPE in next line..</technical_language>

Target:
private Optional<String> getEncoding(InputStream in) throws IOException { InputStream inputStream = in; if (!inputStream.markSupported()) { inputStream = new BufferedInputStream(inputStream); } CharsetDetector detector = new CharsetDetector(); detector.setText(inputStream); CharsetMatch charsetMatch = detector.detect(); return Optional.ofNullable(charsetMatch).map(CharsetMatch::getName); }
Source:
<code>public void serialize(SliceOutput out) { super.serialize(out); for (int i = 0; i < super.getBucketCount(); ++i) { out.appendLong(breakdowns.get(i).size()); <START> breakdowns.get(i).entrySet() <END> .forEach(e -> { out.appendDouble(e.getKey()); out.appendLong(e.getValue()); }); } }</code><technical_language>suggestion breakdowns.get(i).forEach((key, value) -> { out.appendDouble(key); out.appendLong(value); });</technical_language>

Target:
public void serialize(SliceOutput out) { super.serialize(out); for (int i = 0; i < super.getBucketCount(); ++i) { out.appendLong(breakdowns[i].getSize()); System.out.println("ser " + i + ": " + breakdowns[i].getSize()); Streams.stream(breakdowns[i].iterator()) .forEach(e -> { System.out.println("ser " + e.weight + "; " + e.count); out.appendDouble(e.weight); out.appendLong(e.count); }); } }
Source:
<code>private String loadMapping(final Settings settings, final String key, final String keyDefault) { String mapping = settings.get(key); if(mapping != null && new File(mapping).exists()) { logger.info("Trying to load Kibana mapping for from plugin: {}", key, mapping); try { InputStream stream = new FileInputStream(mapping.toString()); return IOUtils.toString(stream); }catch(Exception e) { <START> logger.error("Unable to load the Kibana mapping specified by {}: {}", key, mapping); <END> } } logger.info("Loading default Kibana mapping for from plugin: {}", key, keyDefault); try { final ClassLoader classLoader = getClass().getClassLoader(); return IOUtils.toString(classLoader.getResourceAsStream(keyDefault)); }catch(Exception e) { logger.error("Unable to load the Kibana mapping specified by {}: {}", key, keyDefault); } return null; }</code><technical_language>this log information Exception</technical_language>

Target:
private String loadMapping(final Settings settings, final String key, final String keyDefault) { String mapping = settings.get(key); if(mapping != null && new File(mapping).exists()) { logger.info("Trying to load Kibana mapping for from plugin: {}", key, mapping); try { InputStream stream = new FileInputStream(mapping.toString()); return IOUtils.toString(stream); }catch(Exception e) { logger.error("Unable to load the Kibana mapping specified by {}: {}", key, e, mapping); } } logger.info("Loading default Kibana mapping for from plugin: {}", key, keyDefault); try { final ClassLoader classLoader = getClass().getClassLoader(); return IOUtils.toString(classLoader.getResourceAsStream(keyDefault)); }catch(Exception e) { logger.error("Unable to load the Kibana mapping specified by {}: {}", key, e, keyDefault); } return null; }
Source:
<code>private void addRowDefinedValueTable(Table definedValueTable, final Node child) { TableItem item = new TableItem(definedValueTable, SWT.NONE); item.setData(Messages.NodeKey, child); final String initialName = child.getAttributes().getNamedItem(TmfXmlStrings.NAME).getNodeValue(); item.setText(0, initialName); item.setText(1, child.getAttributes().getNamedItem(TmfXmlStrings.VALUE).getNodeValue()); final Node colorNode = child.getAttributes().getNamedItem(TmfXmlStrings.COLOR); if (colorNode != null) { String stringColor = colorNode.getNodeValue(); final RGB oldRGB = new RGB(XmlManagerUtils.hexaToRed(stringColor), XmlManagerUtils.hexaToGreen(stringColor), XmlManagerUtils.hexaToBlue(stringColor)); <START> item.setBackground(2, new Color(fproperties.getDisplay(), oldRGB)); <END> } definedValueTable.layout(true, true); }</code><technical_language>A Color is a system resource needs disposed longer used. a LocalResourceManager create colors, dispose manager dialog closed. dispose color immediately replaced a new color editor</technical_language>

Target:
private void addRowDefinedValueTable(Table definedValueTable, final Node child) { TableItem item = new TableItem(definedValueTable, SWT.NONE); item.setData(Messages.NodeKey, child); final String initialName = child.getAttributes().getNamedItem(TmfXmlStrings.NAME).getNodeValue(); item.setText(0, initialName); item.setText(1, child.getAttributes().getNamedItem(TmfXmlStrings.VALUE).getNodeValue()); final Node colorNode = child.getAttributes().getNamedItem(TmfXmlStrings.COLOR); if (colorNode != null) { String stringColor = colorNode.getNodeValue(); int[] colorComponents = XmlAnalysisManagerUtils.hexaColorToInt(stringColor); if(colorComponents != null) { final RGB oldRGB = new RGB(colorComponents[0], colorComponents[1], colorComponents[2]); item.setBackground(2, colorManager.createColor(oldRGB)); } } definedValueTable.layout(true, true); }
Source:
<code>private long unique(File... dirs) throws Exception { <START> ArrayList<String> args = new ArrayList<>(Arrays.asList("-D", "mapred.job.tracker=local", "-D", "fs.default.name=file:/ END> for (File dir : dirs) { args.add(dir.toURI().toString()); } int ret = ToolRunner.run(new Unique(), args.toArray(new String[args.size()])); Assert.assertEquals(0, ret); return Unique.getNumUnique(); }</code><technical_language>Same: fs.defaultFS</technical_language>

Target:
private int unique(File... dirs) throws Exception { ArrayList<String> args = new ArrayList<>(Arrays.asList("-D", "mapred.job.tracker=local", "-D", "fs.defaultFS=file:/ for (File dir : dirs) { args.add(dir.toURI().toString()); } int ret = ToolRunner.run(new Unique(), args.toArray(new String[args.size()])); Assert.assertEquals(0, ret); return Unique.getNumUnique(); }
Source:
<code>public ArrayOfDoublesSketchTTestPostAggregator( @JsonProperty("name") final String name, @JsonProperty("fields") List<PostAggregator> fields ) { super(name, fields); if (fields.size() != 2) { <START> throw new IAE("Illegal number of fields[%s], must be 2", fields.size()); <END> } }</code><technical_language>%d</technical_language>

Target:
public ArrayOfDoublesSketchTTestPostAggregator( @JsonProperty("name") final String name, @JsonProperty("fields") List<PostAggregator> fields ) { super(name, fields); if (fields.size() != 2) { throw new IAE("Illegal number of fields[%d], must be 2", fields.size()); } }
Source:
<code>public String getActualCpuTopology() { if (StringHelper.isNullOrEmpty(actualCpuTopology) || actualCpuTopology.equals("-1")) { <START> return "N/A"; END> } else { return actualCpuTopology; } }</code><technical_language>please notAvailableLabel constant</technical_language>

Target:
public String getActualCpuTopology() { if (StringHelper.isNullOrEmpty(actualCpuTopology) || actualCpuTopology.equals("-1")) { return ConstantsManager.getInstance().getConstants().notAvailableLabel(); } else { return actualCpuTopology; } }
Source:
<code>private void checkZipContainsExactlyOneMainFile(Set<String> extensions) throws ActionParamsException { long mainFileExtensions = extensions.stream() .filter(FeatureCollectionParsers::hasByFileExt) .limit(2) .count(); if (mainFileExtensions == 0) { throw new ActionParamsException("Couldn't find valid file for import in zip file", UserLayerHandlerHelper.createErrorJSON("no_main_file")); } else if (mainFileExtensions == 2) { Set <String> mainExtensions = extensions.stream() .filter(FeatureCollectionParsers::hasByFileExt) <START> .collect(Collectors.toCollection(HashSet::new)); <END> throw new ActionParamsException("Found too many valid files for import in zip file", UserLayerHandlerHelper.createErrorJSON("multiple_main", "extensions", mainExtensions)); } }</code><technical_language>Collectors.toSet() care implementation</technical_language>

Target:
private void checkZipContainsExactlyOneMainFile(Set<String> extensions) throws UserLayerException { long mainFileExtensions = extensions.stream() .filter(FeatureCollectionParsers::hasByFileExt) .limit(2) .count(); if (mainFileExtensions == 0) { throw new UserLayerException("Couldn't find valid file for import in zip file", UserLayerException.ErrorType.NO_FILE); } else if (mainFileExtensions == 2) { throw new UserLayerException("Found too many valid files for import in zip file", UserLayerException.ErrorType.MULTI_MAIN); } }