auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void setBinaryData(Object binaryuri) { String binaryPath; try { binaryPath = getBinaryPathWithSizeCheck(binaryuri); } catch (IOException e) { e.printStackTrace(); showToast("form.attachment.copy.fail"); Logger.exception(LogTypes.TYPE_MAINTENANCE, e); return; } if (binaryPath == null) { if (!destMediaPath.isEmpty()) { new File(destMediaPath).delete(); } return; } File newMedia; if (!destMediaPath.isEmpty()) { newMedia = new File(destMediaPath); } else { recordedFileName = FileUtil.getFileName(binaryPath); String extension = FileUtil.getExtension(binaryPath); if (!FormUploadUtil.isSupportedMultimediaFile(binaryPath)) { Toast.makeText(getContext(), Localization.get("form.attachment.invalid"), Toast.LENGTH_LONG).show(); Log.e(TAG, String.format( "Could not save file with URI %s because of bad extension %s.", binaryPath, extension )); return; } destMediaPath = mInstanceFolder + System.currentTimeMillis() + customFileTag + "." + extension; File source = new File(binaryPath); newMedia = new File(destMediaPath); try { FileUtil.copyFile(source, newMedia); } catch (IOException e) { showToast("form.attachment.copy.fail"); Logger.exception(LogTypes.TYPE_MAINTENANCE, e); e.printStackTrace(); } } try { FileUtil.addMediaToGallery(getContext(), newMedia); showToast("form.attachment.success"); <START> } catch (Exception e) { <END> Log.e(TAG, "Inserting media file FAILED"); e.printStackTrace(); } mBinaryName = newMedia.getName(); }</code><technical_language>Agree save content Providers. @ctsims remove for Images in [here](<LINK_0>, guessing objections in removing for audio videos well</technical_language>

Target:
public void setBinaryData(Object binaryuri) { String binaryPath; try { binaryPath = getBinaryPathWithSizeCheck(binaryuri); } catch (IOException e) { e.printStackTrace(); showToast("form.attachment.copy.fail"); Logger.exception(LogTypes.TYPE_MAINTENANCE, e); return; } if (binaryPath == null) { if (!destMediaPath.isEmpty()) { new File(destMediaPath).delete(); } return; } File newMedia; if (!destMediaPath.isEmpty()) { newMedia = new File(destMediaPath); } else { recordedFileName = FileUtil.getFileName(binaryPath); String extension = FileUtil.getExtension(binaryPath); if (!FormUploadUtil.isSupportedMultimediaFile(binaryPath)) { Toast.makeText(getContext(), Localization.get("form.attachment.invalid"), Toast.LENGTH_LONG).show(); Log.e(TAG, String.format( "Could not save file with URI %s because of bad extension %s.", binaryPath, extension )); return; } destMediaPath = mInstanceFolder + System.currentTimeMillis() + customFileTag + "." + extension; File source = new File(binaryPath); newMedia = new File(destMediaPath); try { FileUtil.copyFile(source, newMedia); } catch (IOException e) { showToast("form.attachment.copy.fail"); Logger.exception(LogTypes.TYPE_MAINTENANCE, e); e.printStackTrace(); } } if (newMedia.exists()) { showToast("form.attachment.success"); } mBinaryName = newMedia.getName(); }
Source:
<code>public void addExtensions(OpenAPI openAPI) { <START> if (openAPI.getComponents().getSchemas() != null) { <END> schemas = openAPI.getComponents().getSchemas(); if (schemas == null) { schemas = new HashMap<>(); } } for (String name : schemas.keySet()) { Schema schema = schemas.get(name); if (schema.getExtensions() != null) { if (!schema.getExtensions().containsKey(Constants.X_SWAGGER_ROUTER_MODEL)) { schema.addExtension(Constants.X_SWAGGER_ROUTER_MODEL, name); } } else { schema.addExtension(Constants.X_SWAGGER_ROUTER_MODEL, name); } } if(openAPI.getPaths() != null) { for (String pathname : openAPI.getPaths().keySet()) { PathItem pathItem = openAPI.getPaths().get(pathname); resolvePath(pathItem); } } }</code><technical_language>is save assume "getComponents()" null</technical_language>

Target:
public void addExtensions(OpenAPI openAPI) { if (openAPI.getComponents() != null) { if (openAPI.getComponents().getSchemas() != null) { schemas = openAPI.getComponents().getSchemas(); if (schemas == null) { schemas = new HashMap<>(); } } for (String name : schemas.keySet()) { Schema schema = schemas.get(name); if (schema.getExtensions() != null) { if (!schema.getExtensions().containsKey(Constants.X_SWAGGER_ROUTER_MODEL)) { schema.addExtension(Constants.X_SWAGGER_ROUTER_MODEL, name); } } else { schema.addExtension(Constants.X_SWAGGER_ROUTER_MODEL, name); } } } if (openAPI.getPaths() != null) { for (String pathname : openAPI.getPaths().keySet()) { PathItem pathItem = openAPI.getPaths().get(pathname); resolvePath(pathItem); } } }
Source:
<code>public Subscription(TopicName topicName, String name, EndpointAddress endpoint, State state, String description, <START> Object subscriptionPolicy, <END> boolean trackingEnabled, String supportTeam, String contact, ContentType contentType, DeliveryType deliveryType) { this.topicName = topicName; this.name = name; this.endpoint = endpoint; this.state = state; this.description = description; this.trackingEnabled = trackingEnabled; this.supportTeam = supportTeam; this.contact = contact; this.contentType = contentType == null ? ContentType.JSON : contentType; this.deliveryType = deliveryType; this.batchSubscriptionPolicy = this.deliveryType == DeliveryType.BATCH ? (BatchSubscriptionPolicy) subscriptionPolicy : null; this.serialSubscriptionPolicy = this.deliveryType == DeliveryType.SERIAL ? (SubscriptionPolicy) subscriptionPolicy : null; }</code><technical_language>I if this constructor is accessed deliberately in test suite a good idea versions strong typing here</technical_language>

Target:
private Subscription(TopicName topicName, String name, EndpointAddress endpoint, State state, String description, Object subscriptionPolicy, boolean trackingEnabled, String supportTeam, String contact, ContentType contentType, DeliveryType deliveryType) { this.topicName = topicName; this.name = name; this.endpoint = endpoint; this.state = state; this.description = description; this.trackingEnabled = trackingEnabled; this.supportTeam = supportTeam; this.contact = contact; this.contentType = contentType == null ? ContentType.JSON : contentType; this.deliveryType = deliveryType; this.batchSubscriptionPolicy = this.deliveryType == DeliveryType.BATCH ? (BatchSubscriptionPolicy) subscriptionPolicy : null; this.serialSubscriptionPolicy = this.deliveryType == DeliveryType.SERIAL ? (SubscriptionPolicy) subscriptionPolicy : null; }
Source:
<code>protected AbstractMetadataResolver getMetadataResolverFromResponse(final HttpResponse response, final File backupFile) throws Exception { if (!HttpStatus.valueOf(response.getStatusLine().getStatusCode()).is2xxSuccessful()) { if (Files.exists(backupFile.toPath())) { <START> return new InMemoryResourceMetadataResolver(backupFile, this.configBean); <END> } else { throw new Exception("Unable to get entity from MDQ server and a backup file does not exist."); } } val entity = response.getEntity(); val result = IOUtils.toString(entity.getContent(), StandardCharsets.UTF_8); val path = backupFile.toPath(); LOGGER.trace("Writing metadata to file at [{}]", path); try (val output = Files.newBufferedWriter(path, StandardCharsets.UTF_8)) { IOUtils.write(result, output); output.flush(); output.close(); val etag = response.getFirstHeader("ETag").getValue(); Files.setAttribute(backupFile.toPath(), "user:ETag", ByteBuffer.wrap(etag.getBytes())); } EntityUtils.consume(entity); return new InMemoryResourceMetadataResolver(backupFile, configBean); }</code><technical_language>if backup file expired metadata</technical_language>

Target:
protected AbstractMetadataResolver getMetadataResolverFromResponse(final HttpResponse response, final File backupFile) throws Exception { if (!HttpStatus.valueOf(response.getStatusLine().getStatusCode()).is2xxSuccessful()) { if (Files.exists(backupFile.toPath())) { return new InMemoryResourceMetadataResolver(backupFile, this.configBean); } throw new Exception("Unable to get entity from MDQ server and a backup file does not exist."); } val entity = response.getEntity(); val result = IOUtils.toString(entity.getContent(), StandardCharsets.UTF_8); val path = backupFile.toPath(); LOGGER.trace("Writing metadata to file at [{}]", path); try (val output = Files.newBufferedWriter(path, StandardCharsets.UTF_8)) { IOUtils.write(result, output); output.flush(); val etag = response.getFirstHeader("ETag").getValue(); Files.setAttribute(backupFile.toPath(), "user:ETag", ByteBuffer.wrap(etag.getBytes())); } EntityUtils.consume(entity); return new InMemoryResourceMetadataResolver(backupFile, configBean); }
Source:
<code>public void update(final ViewerCell cell) { <START> if (cell.getElement() instanceof Document) { <END> final Document document = (Document) cell.getElement(); final StyledString styledString = new StyledString(); styledString.append(document.getName()); final String decoration = " -- " + getTypeLabel(document); styledString.append(decoration, StyledString.DECORATIONS_STYLER); styledString.append(" -- ", StyledString.DECORATIONS_STYLER); cell.setText(styledString.getString()); cell.setStyleRanges(styledString.getStyleRanges()); } }</code><technical_language>extract cell.getElement</technical_language>

Target:
public void update(final ViewerCell cell) { final Object element = cell.getElement(); if (element instanceof Document) { final Document document = (Document) element; final StyledString styledString = new StyledString(); styledString.append(document.getName()); final String decoration = " -- " + getTypeLabel(document); styledString.append(decoration, StyledString.DECORATIONS_STYLER); styledString.append(" -- ", StyledString.DECORATIONS_STYLER); cell.setText(styledString.getString()); cell.setStyleRanges(styledString.getStyleRanges()); cell.setImage(getImage(element)); } }
Source:
<code>private boolean loopSession() throws IOException { Screen s = getNextScreen(); while (s != null) { try { s.init(mPlatform, mSession, mSandbox); System.out.println("\n\n\n\n\n\n"); s.prompt(System.out); System.out.print("> "); String input = reader.readLine(); if(input.startsWith(":")) { if(input.equals(":exit") || input.equals(":quit")) { System.exit(-1); } if (input.startsWith(":update")) { mUpdatePending = true; if(input.contains("-f")) { mForceLatestUpdate = true; } return true; } if(input.equals(":home")) { <START> return true; <END> } } s.updateSession(mSession, input); s = getNextScreen(); } catch (CommCareSessionException ccse) { System.out.println("Error during session execution:"); ccse.printStackTrace(); System.out.println("Press return to restart the session"); reader.readLine(); return true; } } String formXmlns = mSession.getForm(); XFormPlayer player = new XFormPlayer(System.in, System.out, null); player.setSessionIIF(mSession.getIIF()); player.start(mEngine.loadFormByXmlns(formXmlns)); return true; }</code><technical_language>This method, loopSession, returns true. Is this expected? return void instead</technical_language>

Target:
private boolean loopSession() throws IOException { Screen s = getNextScreen(); while (s != null) { try { s.init(mPlatform, mSession, mSandbox); System.out.println("\n\n\n\n\n\n"); s.prompt(System.out); System.out.print("> "); String input = reader.readLine(); if(input.startsWith(":")) { if(input.equals(":exit") || input.equals(":quit")) { return false; } if (input.startsWith(":update")) { mUpdatePending = true; if(input.contains("-f")) { mForceLatestUpdate = true; } return true; } if(input.equals(":home")) { return true; } } s.updateSession(mSession, input); s = getNextScreen(); } catch (CommCareSessionException ccse) { System.out.println("Error during session execution:"); ccse.printStackTrace(); System.out.println("Press return to restart the session"); reader.readLine(); return true; } } String formXmlns = mSession.getForm(); XFormPlayer player = new XFormPlayer(System.in, System.out, null); player.setSessionIIF(mSession.getIIF()); player.start(mEngine.loadFormByXmlns(formXmlns)); return true; }
Source:
<code>private void assertExpireTime(long expectedExpire, Capture<TwoWayChannelMessage> initiateCapture) { final TwoWayChannelMessage response = initiateCapture.getValue(); final MessageType type = response.getType(); assertEquals("Wrong type " + type, MessageType.INITIATE, type); final long actualExpire = response.getInitiate().getExpireTimeSecs(); long delta = 1; <START> assertTrue("Expiretime to to small " + expectedExpire + " > " + actualExpire, expectedExpire <= actualExpire + delta); <END> assertTrue("Expiretime to to large " + expectedExpire + "<" + actualExpire, expectedExpire >= actualExpire - delta); }</code><technical_language>s/to to/too/</technical_language>

Target:
private void assertExpireTime(long expectedExpire, Capture<TwoWayChannelMessage> initiateCapture) { final TwoWayChannelMessage response = initiateCapture.getValue(); final MessageType type = response.getType(); assertEquals("Wrong type " + type, MessageType.INITIATE, type); final long actualExpire = response.getInitiate().getExpireTimeSecs(); assertTrue("Expire time too small " + expectedExpire + " > " + actualExpire, expectedExpire <= actualExpire); assertTrue("Expire time too large " + expectedExpire + "<" + actualExpire, expectedExpire >= actualExpire); }
Source:
<code>private static PersistenceDescriptor persistenceXml() { return Descriptors.create( PersistenceDescriptor.class ) .version( "2.0" ) .createPersistenceUnit() .name( "primary" ) .provider( "org.hibernate.ogm.jpa.HibernateOgmPersistence" ) .clazz( Member.class.getName() ) .getOrCreateProperties() .createProperty().name( "hibernate.ogm.datastore.provider" ).value( "couchdb" ).up() <START> .createProperty().name( "hibernate.ogm.couchdb.host" ).value( "localhost" ).up() <END> .createProperty().name( "hibernate.ogm.couchdb.port" ).value( "5984" ).up() .createProperty().name( "hibernate.ogm.couchdb.database" ).value( "ogm_test_database" ).up() .createProperty().name( "hibernate.org.couchdb.createdatabase" ).value( "true" ).up() .up().up(); }</code><technical_language>read set in COUCHDB_HOSTNAME if server is remote is work</technical_language>

Target:
private static PersistenceDescriptor persistenceXml() { return Descriptors.create( PersistenceDescriptor.class ) .version( "2.0" ) .createPersistenceUnit() .name( "primary" ) .provider( "org.hibernate.ogm.jpa.HibernateOgmPersistence" ) .clazz( Member.class.getName() ) .getOrCreateProperties() .createProperty().name( "hibernate.ogm.datastore.provider" ).value( "couchdb" ).up() .createProperty().name( "hibernate.ogm.couchdb.host" ).value( couchDBHostName ).up() .createProperty().name( "hibernate.ogm.couchdb.couchDBPortNumber" ).value( couchDBPortNumber ).up() .createProperty().name( "hibernate.ogm.couchdb.database" ).value( "ogm_test_database" ).up() .createProperty().name( "hibernate.org.couchdb.createdatabase" ).value( "true" ).up() .up().up(); }
Source:
<code>public void channelInactive(ChannelHandlerContext ctx) { try { if (requestHandler != null) { <START> requestHandler.onRequestComplete(request); <END> } if (responseHandler != null) { responseHandler.onRequestComplete(request); } } catch (Exception e) { logger.error("Unable to perform cleanup tasks. Swallowing exception..", e); nettyMetrics.channelInactiveTasksFailureCount.inc(); } }</code><technical_language>need move this logic rely channelInactive for alive. do now</technical_language>

Target:
public void channelInactive(ChannelHandlerContext ctx) { onRequestComplete(null, true); }
Source:
<code>public void stop() { authzHelper.checkPermission(AuthorizationPermission.LIFECYCLE); <START> startSemaphore.lock(); <END> if (stopSemaphore.tryLock()) { try { log.debugf("Stopping cache manager %s on %s", configurationManager.getGlobalConfiguration().transport().clusterName(), getAddress()); stopCaches(); globalComponentRegistry.getComponent(CacheManagerJmxRegistration.class).stop(); globalComponentRegistry.stop(); } finally { stopSemaphore.unlock(); } } else { log.trace("Ignore call to stop as the cache manager is stopping"); } startSemaphore.unlock(); }</code><technical_language>well, a lock for staring cache manager, a cache - sorry, unclear me, helps</technical_language>

Target:
public void stop() { authzHelper.checkPermission(AuthorizationPermission.LIFECYCLE); startLock.lock(); if (stopLock.tryLock()) { try { log.debugf("Stopping cache manager %s on %s", configurationManager.getGlobalConfiguration().transport().clusterName(), getAddress()); stopCaches(); globalComponentRegistry.getComponent(CacheManagerJmxRegistration.class).stop(); globalComponentRegistry.stop(); } finally { stopLock.unlock(); } } else { log.trace("Ignore call to stop as the cache manager is stopping"); } startLock.unlock(); }
Source:
<code>public ValidationIssueSearchRequestBuilder filterByDetails(Map<String, Object> details) { <START> final Options options = Options.builder().putAll(details).build(); <END> return addOption(OptionKey.DETAILS, options); }</code><technical_language>Add a static from(Map): Options method Options</technical_language>

Target:
public ValidationIssueSearchRequestBuilder filterByDetails(Map<String, Object> details) { final Options options = Options.from(details); return addOption(OptionKey.DETAILS, options); }
Source:
<code>public void requestMetadataSetCorrectly() { callRuntimeExceptionEndpoint(); Report report = verifyAndGetReport(); assertEquals("GET /throw-runtime-exception", report.getContext()); @SuppressWarnings(value = "unchecked") Map<String, Object> requestMetadata = (Map<String, Object>) report.getMetaData().get("request"); assertEquals("http://localhost:" + randomServerPort + "/throw-runtime-exception", requestMetadata.get("url")); assertEquals("GET", requestMetadata.get("method")); assertEquals("127.0.0.1", requestMetadata.get("clientIp")); @SuppressWarnings(value = "unchecked") Map<String, String[]> params = (Map<String, String[]>) requestMetadata.get("params"); assertEquals("paramVal1", params.get("param1")[0]); assertEquals("paramVal2", params.get("param2")[0]); <START> @SuppressWarnings(value = "unchecked") Map<String, String> headers = <END> (Map<String, String>) requestMetadata.get("headers"); assertEquals("headerVal1", headers.get("header1")); assertEquals("headerVal2", headers.get("header2")); }</code><technical_language>assuming headers a single value? If I recall correctly, HTTP standard allows multiple values set values for headers</technical_language>

Target:
public void requestMetadataSetCorrectly() { callRuntimeExceptionEndpoint(); Report report = verifyAndGetReport(); assertEquals("GET /throw-runtime-exception", report.getContext()); @SuppressWarnings(value = "unchecked") Map<String, Object> requestMetadata = (Map<String, Object>) report.getMetaData().get("request"); assertEquals("http://localhost:" + randomServerPort + "/throw-runtime-exception", requestMetadata.get("url")); assertEquals("GET", requestMetadata.get("method")); assertEquals("127.0.0.1", requestMetadata.get("clientIp")); @SuppressWarnings(value = "unchecked") Map<String, String[]> params = (Map<String, String[]>) requestMetadata.get("params"); assertEquals("paramVal1", params.get("param1")[0]); assertEquals("paramVal2", params.get("param2")[0]); @SuppressWarnings(value = "unchecked") Map<String, String> headers = (Map<String, String>) requestMetadata.get("headers"); assertEquals("header1Val1,header1Val2", headers.get("header1")); assertEquals("header2Val1", headers.get("header2")); }
Source:
<code>private void fillProjectProperties(final List<ProjectProperty> projectProperties, final SampleDetailsDTO samplesDetailsDto) { for (ProjectProperty projectProperty : projectProperties) { <START> if (projectProperty.getTypeId().equals(8383) && StringUtils.isNotBlank(projectProperty.getValue())) { <END> final String plantingDate = projectProperty.getValue(); samplesDetailsDto.setSeedingDate(plantingDate); } if (projectProperty.getTypeId().equals(8370) && StringUtils.isNotBlank(projectProperty.getValue())) { final String season = projectProperty.getValue(); samplesDetailsDto.setSeason(season); } } }</code><technical_language>Create a constant</technical_language>

Target:
private void fillProjectProperties(final List<ProjectProperty> projectProperties, final SampleDetailsDTO samplesDetailsDto) { for (final ProjectProperty projectProperty : projectProperties) { if (projectProperty.getTypeId().equals(TermId.SEEDING_DATE.getId()) && StringUtils.isNotBlank(projectProperty.getValue())) { final String plantingDate = projectProperty.getValue(); samplesDetailsDto.setSeedingDate(plantingDate); } if (projectProperty.getTypeId().equals(TermId.SEASON_VAR_TEXT.getId()) && StringUtils.isNotBlank(projectProperty.getValue())) { final String season = projectProperty.getValue(); samplesDetailsDto.setSeason(season); } } }
Source:
<code>protected synchronized void modified(Map<String, Object> config) { final String language = (String) config.get(LANGUAGE); final String script = (String) config.get(SCRIPT); final String region = (String) config.get(REGION); final String variant = (String) config.get(VARIANT); final String location = (String) config.get(LOCATION); if (location != null) { try { this.location = PointType.valueOf(location); } catch (IllegalArgumentException e) { logger.warn("Could not set new location, keeping old one: ", e.getMessage()); } } if (StringUtils.isEmpty(language)) { logger.debug("No language set, fallback to default system locale"); locale = null; return; } final Locale.Builder builder = new Locale.Builder(); try { builder.setLanguage(language); } catch (final RuntimeException ex) { logger.warn("Language ({}) is invalid. Cannot create locale, keep old one.", language, ex); return; } try { builder.setScript(script); } catch (final RuntimeException ex) { logger.warn("Script ({}) is invalid. Skip it.", script, ex); return; } try { builder.setRegion(region); } catch (final RuntimeException ex) { logger.warn("Region ({}) is invalid. Skip it.", region, ex); return; } try { builder.setVariant(variant); } catch (final RuntimeException ex) { logger.warn("Variant ({}) is invalid. Skip it.", variant, ex); return; } locale = builder.build(); <START> logger.info("Locale set to {}", locale); <END> }</code><technical_language>add location in log message (at is modified)</technical_language>

Target:
protected synchronized void modified(Map<String, Object> config) { final String language = (String) config.get(LANGUAGE); final String script = (String) config.get(SCRIPT); final String region = (String) config.get(REGION); final String variant = (String) config.get(VARIANT); final String location = (String) config.get(LOCATION); if (location != null) { try { this.location = PointType.valueOf(location); } catch (IllegalArgumentException e) { logger.warn("Could not set new location, keeping old one: ", e.getMessage()); } } if (StringUtils.isEmpty(language)) { logger.debug("No language set, fallback to default system locale"); locale = null; return; } final Locale.Builder builder = new Locale.Builder(); try { builder.setLanguage(language); } catch (final RuntimeException ex) { logger.warn("Language ({}) is invalid. Cannot create locale, keep old one.", language, ex); return; } try { builder.setScript(script); } catch (final RuntimeException ex) { logger.warn("Script ({}) is invalid. Skip it.", script, ex); return; } try { builder.setRegion(region); } catch (final RuntimeException ex) { logger.warn("Region ({}) is invalid. Skip it.", region, ex); return; } try { builder.setVariant(variant); } catch (final RuntimeException ex) { logger.warn("Variant ({}) is invalid. Skip it.", variant, ex); return; } locale = builder.build(); logger.info("Locale set to {}, Location set to {}", locale, this.location); }
Source:
<code>public static BytecodeExpression invokeFunction(Scope scope, CachedInstanceBinder cachedInstanceBinder, String name, ScalarFunctionImplementation function, List<BytecodeExpression> parameters) { requireNonNull(scope, "scope is null"); requireNonNull(function, "function is null"); <START> CallSiteBinder binder = cachedInstanceBinder.getCallSiteBinder(); <END> Binding binding = cachedInstanceBinder.getCallSiteBinder().bind(function.getMethodHandle()); Optional<BytecodeNode> instance = Optional.empty(); if (function.getInstanceFactory().isPresent()) { FieldDefinition field = cachedInstanceBinder.getCachedInstance(function.getInstanceFactory().get()); instance = Optional.of(scope.getThis().getField(field)); } return new InvokeFunctionBytecodeExpression(scope, binder, name, function, instance, parameters); }</code><technical_language>inline this variable</technical_language>

Target:
public static BytecodeExpression invokeFunction(Scope scope, CachedInstanceBinder cachedInstanceBinder, String name, ScalarFunctionImplementation function, List<BytecodeExpression> parameters) { requireNonNull(scope, "scope is null"); requireNonNull(function, "function is null"); Optional<BytecodeNode> instance = Optional.empty(); if (function.getInstanceFactory().isPresent()) { FieldDefinition field = cachedInstanceBinder.getCachedInstance(function.getInstanceFactory().get()); instance = Optional.of(scope.getThis().getField(field)); } return new InvokeFunctionBytecodeExpression(scope, cachedInstanceBinder.getCallSiteBinder(), name, function, instance, parameters); }
Source:
<code>public static @Nonnull JenkinsLocationConfiguration getOrDie(){ JenkinsLocationConfiguration config = JenkinsLocationConfiguration.get(); if (config == null) { <START> throw new IllegalStateException("JenkinsLocationConfiguration instance is missing. Probably the Jenkins instance is fully loaded at that time."); <END> } return config; }</code><technical_language>typo? "Probably Jenkins instance is fully loaded time" **not** fully loaded (also this time)</technical_language>

Target:
public static @Nonnull JenkinsLocationConfiguration getOrDie(){ JenkinsLocationConfiguration config = JenkinsLocationConfiguration.get(); if (config == null) { throw new IllegalStateException("JenkinsLocationConfiguration instance is missing. Probably the Jenkins instance is not fully loaded at this time."); } return config; }
Source:
<code>private void addSessionToken(ResourceId resourceId, String partitionKeyRangeId, ISessionToken parsedSessionToken) { ConcurrentHashMap<String, ISessionToken> existingTokensIfAny = this.collectionResourceIdToSessionTokens.get(resourceId.getUniqueDocumentCollectionId()); if (existingTokensIfAny != null) { ConcurrentHashMap<String, ISessionToken> existingTokens = existingTokensIfAny; <START> existingTokens.merge(partitionKeyRangeId, parsedSessionToken, (existingSessionTokens, newSessionToken) -> { <END> try { if (existingSessionTokens == null) { return newSessionToken; } return existingSessionTokens.merge(newSessionToken); } catch (CosmosClientException e) { throw new IllegalStateException(e); } }); return; } this.collectionResourceIdToSessionTokens.compute( resourceId.getUniqueDocumentCollectionId(), (k, existingTokens) -> { if (existingTokens == null) { logger.info("Registering a new collection resourceId in SessionTokens", resourceId); ConcurrentHashMap<String, ISessionToken> tokens = new ConcurrentHashMap(200, 0.75f, 2000); tokens.put(partitionKeyRangeId, parsedSessionToken); return tokens; } existingTokens.merge(partitionKeyRangeId, parsedSessionToken, (existingSessionTokens, newSessionToken) -> { try { if (existingSessionTokens == null) { return newSessionToken; } return existingSessionTokens.merge(newSessionToken); } catch (CosmosClientException e) { throw new IllegalStateException(e); } }); return existingTokens; }); }</code><technical_language>Line 227 - 237 code is duplicated in line 252 - 262. code in readability, extract this piece of code in helper method</technical_language>

Target:
private void addSessionToken(ResourceId resourceId, String partitionKeyRangeId, ISessionToken parsedSessionToken) { ConcurrentHashMap<String, ISessionToken> existingTokensIfAny = this.collectionResourceIdToSessionTokens.get(resourceId.getUniqueDocumentCollectionId()); if (existingTokensIfAny != null) { updateExistingTokensInternal(existingTokensIfAny, partitionKeyRangeId, parsedSessionToken); return; } this.collectionResourceIdToSessionTokens.compute( resourceId.getUniqueDocumentCollectionId(), (k, existingTokens) -> { if (existingTokens == null) { logger.info("Registering a new collection resourceId in SessionTokens", resourceId); ConcurrentHashMap<String, ISessionToken> tokens = new ConcurrentHashMap(200, 0.75f, 2000); tokens.put(partitionKeyRangeId, parsedSessionToken); return tokens; } updateExistingTokensInternal(existingTokens, partitionKeyRangeId, parsedSessionToken); return existingTokens; }); }
Source:
<code>private void startAutomaticRefresh(MeteoBlueConfiguration config) { if (refreshJob != null && !refreshJob.isCancelled()) { logger.trace("Refresh job already exists."); return; } <START> Runnable runnable = new Runnable() { <END> @Override public void run() { boolean updateSuccessful = false; try { updateSuccessful = updateWeatherData(); if (updateSuccessful) { for (int i = 0; i < 7; i++) { forecasts[i] = new Forecast(i, weatherData.getMetadata(), weatherData.getUnits(), weatherData.getDataDay()); } for (Channel channel : getThing().getChannels()) { updateChannel(channel.getUID().getId()); } } } catch (Exception e) { logger.debug("Exception occurred during weather update: {}", e.getMessage(), e); } } }; int period = config.refresh != null ? config.refresh : MeteoBlueConfiguration.DEFAULT_REFRESH; refreshJob = scheduler.scheduleWithFixedDelay(runnable, 0, period, TimeUnit.MINUTES); }</code><technical_language>a lambda here: Runnable runnable = () -> { .... };</technical_language>

Target:
private void startAutomaticRefresh(MeteoBlueConfiguration config) { if (refreshJob != null && !refreshJob.isCancelled()) { logger.trace("Refresh job already exists."); return; } Runnable runnable = () -> { boolean updateSuccessful = false; try { updateSuccessful = updateWeatherData(); if (updateSuccessful) { for (int i = 0; i < 7; i++) { forecasts[i] = new Forecast(i, weatherData.getMetadata(), weatherData.getUnits(), weatherData.getDataDay()); } for (Channel channel : getThing().getChannels()) { updateChannel(channel.getUID().getId()); } } } catch (Exception e) { logger.warn("Exception occurred during weather update: {}", e.getMessage(), e); } }; int period = config.refresh != null ? config.refresh : MeteoBlueConfiguration.DEFAULT_REFRESH; refreshJob = scheduler.scheduleWithFixedDelay(runnable, 0, period, TimeUnit.MINUTES); }
Source:
<code>public void fillContextMenu(IMenuManager aMenu) { IStructuredSelection selection = (IStructuredSelection) getContext().getSelection(); if (selection.size() != 1) { return; } Object object = selection.getFirstElement(); <START> if (! (object instanceof IFolder)) { <END> return; } IFolder folder = (IFolder) object; if (folder.getFile(IProjectDescription.DESCRIPTION_FILE_NAME).exists()) { for (IProject project : folder.getWorkspace().getRoot().getProjects()) { if (project.getLocation().equals(folder.getLocation())) { SelectProjectForFolderAction action = new SelectProjectForFolderAction(project, this.viewer); aMenu.insertAfter(ICommonMenuConstants.GROUP_OPEN, action); return; } } OpenFolderAsProjectAction action = new OpenFolderAsProjectAction(folder, this.viewer); aMenu.insertAfter(ICommonMenuConstants.GROUP_OPEN, action); } }</code><technical_language>adapt IFolder, org.eclipse.ui.internal.navigator.AdaptabilityUtility.getAdapter(Object, Class)</technical_language>

Target:
public void fillContextMenu(IMenuManager aMenu) { IStructuredSelection selection = (IStructuredSelection) getContext().getSelection(); if (selection.size() != 1) { return; } Object object = selection.getFirstElement(); IFolder folder = (IFolder)AdaptabilityUtility.getAdapter(object, IFolder.class); if (folder == null) { return; } if (folder.getFile(IProjectDescription.DESCRIPTION_FILE_NAME).exists()) { for (IProject project : folder.getWorkspace().getRoot().getProjects()) { if (project.getLocation().equals(folder.getLocation())) { SelectProjectForFolderAction action = new SelectProjectForFolderAction(project, this.viewer); aMenu.insertAfter(ICommonMenuConstants.GROUP_OPEN, action); return; } } OpenFolderAsProjectAction action = new OpenFolderAsProjectAction(folder, this.viewer); aMenu.insertAfter(ICommonMenuConstants.GROUP_BUILD, action); } }
Source:
<code>protected void copyVmDevices() { getVmDeviceUtils().copyVmDevices(vmDevicesSourceId, getVmId(), getSrcDeviceIdToTargetDeviceIdMapping(), isSoundDeviceEnabled(), getParameters().isConsoleEnabled(), isVirtioScsiEnabled(), isBalloonEnabled(), getParameters().getGraphicsDevices().keySet(), false, getEffectiveCompatibilityVersion()); <START> getVmDeviceUtils().updateUsbSlots(getVmTemplate(), getVm().getStaticData()); <END> if (getInstanceTypeId() != null) { copyDiskDevicesFromTemplate(); } }</code><technical_language>wrapping in if (getVmTemplate().getUsbPolicy() != getVm().getUsbPolicy()) { ... } change would: * Save db calls if possible. (I admit adding/editing VMs frequent flows.) * guest OS feel controllers travel bus address space. AFAIK devices reuses address is assigned run in VM</technical_language>

Target:
protected void copyVmDevices() { getVmDeviceUtils().copyVmDevices(vmDevicesSourceId, getVmId(), getSrcDeviceIdToTargetDeviceIdMapping(), isSoundDeviceEnabled(), getParameters().isConsoleEnabled(), isVirtioScsiEnabled(), isBalloonEnabled(), getParameters().getGraphicsDevices().keySet(), false, getEffectiveCompatibilityVersion()); if (getVmTemplate().getUsbPolicy() != getVm().getUsbPolicy()) { getVmDeviceUtils().updateUsbSlots(getVmTemplate(), getVm().getStaticData()); } if (getInstanceTypeId() != null) { copyDiskDevicesFromTemplate(); } }
Source:
<code>public ZapSupportPanel() { super(new GridBagLayout(), true); GridBagConstraints gbcSupportDetails = new GridBagConstraints(); JTextArea supportDetailsTextArea = new JTextArea(); supportDetailsTextArea.setEditable(false); <START> StringBuffer supportDetailsBuffer = new StringBuffer(300); <END> supportDetailsBuffer.append(PRODUCT).append(NEWLINE); supportDetailsBuffer.append(VERSION).append(NEWLINE); supportDetailsBuffer.append("---").append(NEWLINE); supportDetailsBuffer.append(WordUtils.wrap(INSTALLED_ADDONS, 60)).append(NEWLINE); supportDetailsBuffer.append("---").append(NEWLINE); supportDetailsBuffer.append(OS).append(NEWLINE); supportDetailsBuffer.append(JAVA_VERSION).append(NEWLINE); supportDetailsBuffer.append(ZAP_HOME).append(NEWLINE); supportDetailsTextArea.setText(supportDetailsBuffer.toString()); gbcSupportDetails.gridx = 3; gbcSupportDetails.gridy = 0; gbcSupportDetails.ipadx = 0; gbcSupportDetails.ipady = 0; gbcSupportDetails.anchor = GridBagConstraints.NORTHWEST; gbcSupportDetails.insets = new Insets(2, 2, 2, 2); this.add(supportDetailsTextArea, gbcSupportDetails); }</code><technical_language>Prefer StringBuilder, synchronisation provided StringBuffer is needed here</technical_language>

Target:
public ZapSupportPanel() { super(new GridBagLayout(), true); GridBagConstraints gbcSupportDetails = new GridBagConstraints(); JTextArea supportDetailsTextArea = new JTextArea(); supportDetailsTextArea.setEditable(false); supportDetailsTextArea.setText(ZapSupportUtils.getAll(true)); gbcSupportDetails.gridx = 3; gbcSupportDetails.gridy = 0; gbcSupportDetails.ipadx = 0; gbcSupportDetails.ipady = 0; gbcSupportDetails.weightx = 1.0D; gbcSupportDetails.weighty = 1.0D; gbcSupportDetails.fill = GridBagConstraints.BOTH; gbcSupportDetails.anchor = GridBagConstraints.NORTHWEST; gbcSupportDetails.insets = new Insets(2, 2, 2, 2); this.add(supportDetailsTextArea, gbcSupportDetails); }
Source:
<code><START> public float getX() { <END> return this.xCoordinate; }</code><technical_language>if float double for properties. lean double this is meant a generic class double store float vice-versa</technical_language>

Target:
public double getX() { return this.xCoordinate; }
Source:
<code>public ReaderOptions(ValidationStringency stringency, boolean includeUnmappedReads) { <START> super(); <END> this.stringency = stringency; this.includeUnmappedReads = includeUnmappedReads; }</code><technical_language>super is needed</technical_language>

Target:
public ReaderOptions(ValidationStringency stringency, boolean includeUnmappedReads) { this.stringency = stringency; this.includeUnmappedReads = includeUnmappedReads; }
Source:
<code>private String getDbVendor() { <START> return dbClient.getDatabase().getDialect().getId().toLowerCase(Locale.ENGLISH); <END> }</code><technical_language>I suggest case, database ids lowercase anyways</technical_language>

Target:
private String getDbVendor() { return dbClient.getDatabase().getDialect().getId(); }
Source:
<code><START> private ScriptExecutorFactory() { <END> }</code><technical_language>Sorry; missed</technical_language>

Target:
private ScriptExecutorFactory() { super(); }
Source:
<code>public JsonRpcResult getMatchedStylesForNode(JsonRpcPeer peer, JSONObject params) { final GetMatchedStylesForNodeRequest request = mObjectMapper.convertValue( params, GetMatchedStylesForNodeRequest.class); final ArrayListAccumulator<StyleInfo> styles = new ArrayListAccumulator<StyleInfo>() { @Override public void store(StyleInfo object) { <START> if (!object.isDefault()) { <END> super.store(object); } } }; mDocument.postAndWait(new Runnable() { @Override public void run() { mDocument.getElementStyle(request.nodeId, styles); } }); return new GetMatchedStylesForNodeResult(styles); }</code><technical_language>betting filtering out a lot of StyleInfo objects? default value? This leads a custom Accumulator, ala AttributeAccumulator, a idea here. allocate transmit. this work: interface StyleInfoAccumulator { void store(String name, String value, boolean isDefault); } right custom accumulator implementation do new StyleInfo for isDefault is false</technical_language>

Target:
public JsonRpcResult getMatchedStylesForNode(JsonRpcPeer peer, JSONObject params) { final GetMatchedStylesForNodeRequest request = mObjectMapper.convertValue( params, GetMatchedStylesForNodeRequest.class); final GetMatchedStylesForNodeResult result = new GetMatchedStylesForNodeResult(); final RuleMatch match = new RuleMatch(); result.matchedCSSRules = ListUtil.newImmutableList(match); match.matchingSelectors = ListUtil.newImmutableList(0); Selector selector = new Selector(); selector.value = "<this_element>"; CSSRule rule = new CSSRule(); rule.origin = Origin.REGULAR; rule.selectorList = new SelectorList(); rule.selectorList.selectors = ListUtil.newImmutableList(selector); rule.style = new CSSStyle(); rule.style.cssProperties = new ArrayList<>(); match.rule = rule; rule.style.shorthandEntries = Collections.emptyList(); mDocument.postAndWait(new Runnable() { @Override public void run() { Object elementForNodeId = mDocument.getElementForNodeId(request.nodeId); if (elementForNodeId == null) { LogUtil.w("Failed to get style of an element that does not exist, nodeid=" + request.nodeId); return; } mDocument.getElementStyles( elementForNodeId, new StyleAccumulator() { @Override public void store(String name, String value, boolean isDefault) { if (!isDefault) { CSSProperty property = new CSSProperty(); property.name = name; property.value = value; match.rule.style.cssProperties.add(property); } } }); } }); result.inherited = Collections.emptyList(); result.pseudoElements = Collections.emptyList(); return result; }
Source:
<code>public List<String> showAllLocks() { List<String> returnValue; <START> log.warn("All in memory locks will be shown"); <END> globalLock.lock(); try { returnValue = new ArrayList<String>(); for(Map.Entry<String, InternalLockView> entry : locks.entrySet()) { String lock = new StringBuilder("The object id is : ").append(entry.getKey()).append(' ').append(entry.getValue()).toString(); returnValue.add(lock); log.warn(lock); } } finally { globalLock.unlock(); } log.warn("All in memory locks were shown"); return returnValue; }</code><technical_language>is this a warn level message? user is action here. I log this all</technical_language>

Target:
public List<String> showAllLocks() { List<String> returnValue; log.warn("All in memory locks will be shown"); globalLock.lock(); try { returnValue = new ArrayList<String>(); for(Map.Entry<String, InternalLockView> entry : locks.entrySet()) { String lock = new StringBuilder("The object id is : ").append(entry.getKey()).append(' ').append(entry.getValue()).toString(); returnValue.add(lock); } } finally { globalLock.unlock(); } log.warn("All in memory locks were shown"); return returnValue; }
Source:
<code>public void setObject(int index, Object value, int sqlType) throws SQLException { <START> if (value == null) <END> statement.setNull(index, sqlType); else statement.setObject(index, value); }</code><technical_language>general convention is braces in if/else statements</technical_language>

Target:
public void setObject(int index, Object value, int sqlType) throws SQLException { if (value == null) { statement.setNull(index, sqlType); } else { statement.setObject(index, value); } }
Source:
<code>private void stopListening() { if (dependencies != null) { <START> for (int i = 0; i < dependencies.length; i++) { <END> IObservable observable = dependencies[i]; observable.removeChangeListener(privateInterface); } } }</code><technical_language>I forech loop</technical_language>

Target:
private void stopListening() { if (dependencies != null) { for (IObservable observable : dependencies) { observable.removeChangeListener(privateInterface); } } }
Source:
<code>public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_firestore_paging, menu); <START> return super.onCreateOptionsMenu(menu); <END> }</code><technical_language>return true ensure menu is displayed</technical_language>

Target:
public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_firestore_paging, menu); return true; }
Source:
<code>public static String toString(int oid) { try { Field[] fields = Oid.class.getFields(); <START> for (int i = 0; i < fields.length; i++) { <END> Field field = fields[i]; if (field.getInt(null) == oid) { return field.getName(); } } } catch (IllegalAccessException e) { } return "<unknown:" + oid + ">"; }</code><technical_language>Please java foreach construct</technical_language>

Target:
public static String toString(int oid) { try { Field[] fields = Oid.class.getFields(); for (Field field : fields) { if (field.getInt(null) == oid) { return field.getName(); } } } catch (IllegalAccessException e) { } return "<unknown:" + oid + ">"; }
Source:
<code>public ReferenceSequence get(final int sequenceIndex) { if (referenceSequence != null && referenceSequence.getContigIndex() == sequenceIndex) { return referenceSequence; } <START> if (!referenceSequenceFile.isIndexed() && referenceSequence != null && referenceSequence.getContigIndex() > sequenceIndex) { <END> throw new SAMException("Requesting earlier reference sequence: " + sequenceIndex + " < " + referenceSequence.getContigIndex()); } referenceSequence = null; if(referenceSequenceFile.isIndexed()){ final SAMSequenceRecord samSequenceRecord = referenceSequenceFile.getSequenceDictionary().getSequence(sequenceIndex); if(samSequenceRecord != null){ referenceSequence = referenceSequenceFile.getSequence(samSequenceRecord.getSequenceName()) ; } } else { do { referenceSequence = referenceSequenceFile.nextSequence(); } while (referenceSequence != null && referenceSequence.getContigIndex() < sequenceIndex); } if (referenceSequence == null || referenceSequence.getContigIndex() != sequenceIndex) { throw new SAMException("Reference sequence (" + sequenceIndex + ") not found in " + referenceSequenceFile.toString()); } return referenceSequence; }</code><technical_language>isIndexed check for null</technical_language>

Target:
public ReferenceSequence get(final int sequenceIndex) { if (referenceSequence != null && referenceSequence.getContigIndex() == sequenceIndex) { return referenceSequence; } if (referenceSequence != null && referenceSequence.getContigIndex() > sequenceIndex) { throw new SAMException("Requesting earlier reference sequence: " + sequenceIndex + " < " + referenceSequence.getContigIndex()); } referenceSequence = null; if(referenceSequenceFile.isIndexed()) { final SAMSequenceRecord samSequenceRecord = referenceSequenceFile.getSequenceDictionary().getSequence(sequenceIndex); if(samSequenceRecord != null) { referenceSequence = referenceSequenceFile.getSequence(samSequenceRecord.getSequenceName()) ; } } else { do { referenceSequence = referenceSequenceFile.nextSequence(); } while (referenceSequence != null && referenceSequence.getContigIndex() < sequenceIndex); } if (referenceSequence == null || referenceSequence.getContigIndex() != sequenceIndex) { throw new SAMException("Reference sequence (" + sequenceIndex + ") not found in " + referenceSequenceFile.toString()); } return referenceSequence; }
Source:
<code>public void writeIndexToFile(long fileEndPointer) throws IOException, StoreException { if (prevNumOfEntriesWritten != index.size()) { File temp = new File(getFile().getAbsolutePath() + ".tmp"); FileOutputStream fileStream = new FileOutputStream(temp); CrcOutputStream crc = new CrcOutputStream(fileStream); DataOutputStream writer = new DataOutputStream(crc); try { rwLock.readLock().lock(); writer.writeShort(PersistentIndex.version); writer.writeInt(this.keySize); writer.writeInt(this.valueSize); writer.writeLong(fileEndPointer); int numOfEntries = 0; for (Map.Entry<StoreKey, IndexValue> entry : index.entrySet()) { <START> long offsetEnd = entry.getValue().getOffset() + entry.getValue().getSize(); <END> if (entry.getValue().getOffset() + entry.getValue().getSize() <= fileEndPointer) { writer.write(entry.getKey().toBytes()); writer.write(entry.getValue().getBytes().array()); logger.trace("IndexSegment : writing key - value - offset size fileEndOffset {}", getFile().getAbsolutePath(), entry.getKey(), entry.getValue().getOffset(), entry.getValue().getSize(), fileEndPointer); numOfEntries++; } } prevNumOfEntriesWritten = numOfEntries; long crcValue = crc.getValue(); writer.writeLong(crcValue); fileStream.getChannel().force(true); temp.renameTo(getFile()); } catch (IOException e) { throw new StoreException("IndexSegment : " + indexFile.getAbsolutePath() + " IO error while persisting index to disk", e, StoreErrorCodes.IOError); } finally { writer.close(); rwLock.readLock().unlock(); } logger.trace("IndexSegment : completed writing index to file", indexFile.getAbsolutePath()); } }</code><technical_language>offsetEnd is used</technical_language>

Target:
public void writeIndexToFile(long fileEndPointer) throws IOException, StoreException { if (prevNumOfEntriesWritten != index.size()) { File temp = new File(getFile().getAbsolutePath() + ".tmp"); FileOutputStream fileStream = new FileOutputStream(temp); CrcOutputStream crc = new CrcOutputStream(fileStream); DataOutputStream writer = new DataOutputStream(crc); try { rwLock.readLock().lock(); writer.writeShort(PersistentIndex.version); writer.writeInt(this.keySize); writer.writeInt(this.valueSize); writer.writeLong(fileEndPointer); int numOfEntries = 0; for (Map.Entry<StoreKey, IndexValue> entry : index.entrySet()) { if (entry.getValue().getOffset() + entry.getValue().getSize() <= fileEndPointer) { writer.write(entry.getKey().toBytes()); writer.write(entry.getValue().getBytes().array()); logger.trace("IndexSegment : writing key - value - offset size fileEndOffset {}", getFile().getAbsolutePath(), entry.getKey(), entry.getValue().getOffset(), entry.getValue().getSize(), fileEndPointer); numOfEntries++; } } prevNumOfEntriesWritten = numOfEntries; long crcValue = crc.getValue(); writer.writeLong(crcValue); fileStream.getChannel().force(true); temp.renameTo(getFile()); } catch (IOException e) { throw new StoreException("IndexSegment : " + indexFile.getAbsolutePath() + " IO error while persisting index to disk", e, StoreErrorCodes.IOError); } finally { writer.close(); rwLock.readLock().unlock(); } logger.trace("IndexSegment : completed writing index to file", indexFile.getAbsolutePath()); } }