auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void testMetaDataRemoval() { BugsnagAppender.addThreadMetaData("thread", "some key", "some thread value"); <START> BugsnagAppender.addThreadMetaData("report", "some key", "some report value"); <END> LOGGER.warn("Test exception", new RuntimeException("test")); BugsnagAppender.clearThreadMetaData(); LOGGER.warn("Test exception", new RuntimeException("test")); assertEquals(2, delivery.getNotifications().size()); Notification notification = delivery.getNotifications().get(0); Report report = notification.getEvents().get(0); assertTrue(report.getMetaData().containsKey("report")); assertTrue(report.getMetaData().containsKey("thread")); assertEquals("some report value", getMetaDataMap(notification, "report").get("some key")); assertEquals("some thread value", getMetaDataMap(notification, "thread").get("some key")); notification = delivery.getNotifications().get(1); report = notification.getEvents().get(0); assertFalse(report.getMetaData().containsKey("report")); assertFalse(report.getMetaData().containsKey("thread")); }</code><technical_language>this isnt required more</technical_language>

Target:
public void testMetaDataRemoval() { Bugsnag.addThreadMetaData("thread", "some key", "some thread value"); LOGGER.warn(new BugsnagMarker(new Callback() { @Override public void beforeNotify(Report report) { report.addToTab("report", "some key", "some report value"); } }), "Test exception", new RuntimeException("test")); LOGGER.warn("Test exception", new RuntimeException("test")); Bugsnag.clearThreadMetaData(); LOGGER.warn("Test exception", new RuntimeException("test")); assertEquals(3, delivery.getNotifications().size()); Notification notification = delivery.getNotifications().get(0); Report report = notification.getEvents().get(0); assertTrue(report.getMetaData().containsKey("report")); assertTrue(report.getMetaData().containsKey("thread")); assertEquals("some report value", getMetaDataMap(notification, "report").get("some key")); assertEquals("some thread value", getMetaDataMap(notification, "thread").get("some key")); notification = delivery.getNotifications().get(1); report = notification.getEvents().get(0); assertFalse(report.getMetaData().containsKey("report")); assertTrue(report.getMetaData().containsKey("thread")); assertEquals("some thread value", getMetaDataMap(notification, "thread").get("some key")); notification = delivery.getNotifications().get(2); report = notification.getEvents().get(0); assertFalse(report.getMetaData().containsKey("report")); assertFalse(report.getMetaData().containsKey("thread")); }
Source:
<code>public void init() { dataSourceSync(); if (refreshRate > 0) { refreshTimer.schedule(new TimerTask() { @Override public void run() { <START> dataSourceSync(); <END> } }, refreshRate, refreshRate); } }</code><technical_language>catch log run-time exceptions timer continues fire if is a temporary blip</technical_language>

Target:
public void init() { dataSourceSync(); if (refreshRate > 0) { refreshTimer.schedule(new TimerTask() { @Override public void run() { try { dataSourceSync(); } catch (Exception ex) { LOG.error("An error occurred while synchronizing the datasource: {}", ex.getMessage(), ex); } } }, refreshRate, refreshRate); } }
Source:
<code><START> public void delete(File file) throws IOException { <END> if (file != null && file.exists() && !file.delete()) { log.warn("Failed to delete file/directory at path: " + file.getAbsolutePath()); } }</code><technical_language>this method need public</technical_language>

Target:
private void delete(File file) throws IOException { if (file != null && file.exists() && !file.delete()) { log.warn("Failed to delete file/directory at path: " + file.getAbsolutePath()); } }
Source:
<code>private AbstractFile getOrMakeFolder(SleuthkitCase skCase, FsContent dataSource, String path) throws TskCoreException { String parentPath = getParentPath(path); String folderName = getFileName(path); List<AbstractFile> files = null; if(parentPath != null) { if(!parentPath.equals("/")) { parentPath = parentPath + "/"; } <START> files = skCase.findAllFilesWhere(String.format("fs_obj_id=%s AND parent_path='%s' AND name='%s'", dataSource.getFileSystemId(), parentPath, folderName != null ? folderName : "")); <END> } else { files = skCase.findAllFilesWhere(String.format("fs_obj_id=%s AND parent_path='/' AND name=''", dataSource.getFileSystemId())); } if(files == null || files.isEmpty()) { AbstractFile parent = getOrMakeFolder(skCase, dataSource, parentPath); return skCase.addVirtualDirectory(parent.getId(), folderName); } else { return files.get(0); } }</code><technical_language>need escape parent_path name in case ' in them</technical_language>

Target:
private AbstractFile getOrMakeFolder(SleuthkitCase skCase, FsContent dataSource, String path) throws TskCoreException { String parentPath = getParentPath(path); String folderName = getFileName(path); List<AbstractFile> files = null; if (parentPath != null) { if (!parentPath.equals("/")) { parentPath = parentPath + "/"; } files = skCase.findAllFilesWhere(String.format("fs_obj_id=%s AND parent_path='%s' AND name='%s'", dataSource.getFileSystemId(), SleuthkitCase.escapeSingleQuotes(parentPath), folderName != null ? SleuthkitCase.escapeSingleQuotes(folderName) : "")); } else { files = skCase.findAllFilesWhere(String.format("fs_obj_id=%s AND parent_path='/' AND name=''", dataSource.getFileSystemId())); } if (files == null || files.isEmpty()) { AbstractFile parent = getOrMakeFolder(skCase, dataSource, parentPath); return skCase.addVirtualDirectory(parent.getId(), folderName); } else { return files.get(0); } }
Source:
<code>public void testCreateFromXMLFunctionExtension5() throws InterruptedException { log.info("CreateFromXMLFunctionExtension TestCase 4"); SiddhiManager siddhiManager = new SiddhiManager(); siddhiManager.setExtension("str:concat", ConcatFunctionExtension.class); String inStreamDefinition = "\ndefine stream inputStream (longAttr long, doubleAttr double, booleanAttr bool, strAttr string);"; String query = ("@info(name = 'query1') from inputStream select " + "longAttr, doubleAttr, booleanAttr, strAttr as hashMap insert into outputStream;" + "from outputStream " + "select map:toXML(hashMap, 'sensor') as xmlString " + "insert into outputStream2"); ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(inStreamDefinition + query); InputHandler inputHandler = executionPlanRuntime.getInputHandler("inputStream"); executionPlanRuntime.start(); inputHandler.send(new Object[]{25, 100.1, true, "Event1"}); inputHandler.send(new Object[]{35, 100.11, false, "Event2"}); inputHandler.send(new Object[]{45, 100.13456, true, "Event3"}); <START> executionPlanRuntime.shutdown(); <END> }</code><technical_language>assert output</technical_language>

Target:
public void testCreateFromXMLFunctionExtension5() throws InterruptedException { log.info("CreateFromXMLFunctionExtension TestCase with test Object[] data should be string format"); SiddhiManager siddhiManager = new SiddhiManager(); siddhiManager.setExtension("str:concat", ConcatFunctionExtension.class); String inStreamDefinition = "\ndefine stream inputStream (longAttr long, doubleAttr double, booleanAttr bool," + " strAttr string);"; String query = ("@info(name = 'query1') from inputStream select " + "longAttr, doubleAttr, booleanAttr, strAttr as hashMap insert into outputStream;" + "from outputStream " + "select map:toXML(hashMap, 'sensor') as xmlString " + "insert into outputStream2"); ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(inStreamDefinition + query); InputHandler inputHandler = executionPlanRuntime.getInputHandler("inputStream"); executionPlanRuntime.start(); inputHandler.send(new Object[]{25, 100.1}); executionPlanRuntime.shutdown(); }
Source:
<code>public List<PermissionSubject> getPermissionCheckSubjects() { if (permsList == null && disk != null) { permsList = new ArrayList<PermissionSubject>(); permsList.add(new PermissionSubject(disk.getimage_group_id(), VdcObjectType.Disk, ActionGroup.DELETE_DISK)); <START> if (disk.getvm_guid() != null) { <END> if (disk.getVmEntityType() == VmEntityType.VM) { permsList.add(new PermissionSubject(disk.getvm_guid(), VdcObjectType.VM, ActionGroup.CONFIGURE_VM_STORAGE)); } if (disk.getVmEntityType() == VmEntityType.TEMPLATE) { permsList.add(new PermissionSubject(disk.getvm_guid(), VdcObjectType.VmTemplate, ActionGroup.DELETE_TEMPLATE)); } } } return permsList; }</code><technical_language>need this anymore</technical_language>

Target:
public List<PermissionSubject> getPermissionCheckSubjects() { if (permsList == null && disk != null) { permsList = new ArrayList<PermissionSubject>(); permsList.add(new PermissionSubject(disk.getimage_group_id(), VdcObjectType.Disk, ActionGroup.DELETE_DISK)); } return permsList; }
Source:
<code>public Deserializer getDeserializer() { return (buffer, builder, columnConfig) -> { byte versionFromBuffer = buffer.get(); <START> if (VERSION_ONE == versionFromBuffer) { <END> int offset = buffer.getInt(); int initialPos = buffer.position(); final CompressedDoublesIndexedSupplier column = CompressedDoublesIndexedSupplier.fromByteBuffer( buffer, byteOrder, builder.getFileMapper() ); buffer.position(initialPos + offset); final ImmutableBitmap bitmap; if (buffer.hasRemaining()) { int bitmapSize = buffer.getInt(); bitmap = bitmapSerdeFactory.getObjectStrategy().fromByteBuffer(buffer, bitmapSize); builder.setNullValueBitmap(Suppliers.ofInstance(bitmap)); } else { bitmap = bitmapSerdeFactory.getBitmapFactory().makeEmptyImmutableBitmap(); } builder.setType(ValueType.DOUBLE) .setHasMultipleValues(false) .setGenericColumn(new DoubleGenericColumnSupplier(column, bitmap)); } else { throw new IAE("Unknown version[%d]", (int) versionFromBuffer); } }; }</code><technical_language>why/how a version missmatch? Serdeser is done jackson mapping factories type name</technical_language>

Target:
public Deserializer getDeserializer() { return (buffer, builder, columnConfig) -> { int offset = buffer.getInt(); int initialPos = buffer.position(); final Supplier<ColumnarDoubles> column = CompressedColumnarDoublesSuppliers.fromByteBuffer( buffer, byteOrder ); buffer.position(initialPos + offset); final ImmutableBitmap bitmap; if (buffer.hasRemaining()) { bitmap = bitmapSerdeFactory.getObjectStrategy().fromByteBufferWithSize(buffer); } else { bitmap = bitmapSerdeFactory.getBitmapFactory().makeEmptyImmutableBitmap(); } builder.setType(ValueType.DOUBLE) .setHasMultipleValues(false) .setGenericColumn(new DoubleGenericColumnSupplier(column, bitmap)); }; }
Source:
<code>public Set<String> getContentTypes() { <START> return new TreeSet<String>(contentTypeToBodyParserMap.keySet()); <END> }</code><technical_language>ImmutableSet.copyOf(contentTypeToTemplateEngineMap.keySet()); sense imho..</technical_language>

Target:
public Set<String> getContentTypes() { return ImmutableSet.copyOf(contentTypeToBodyParserMap.keySet()); }
Source:
<code>protected boolean isUserCanBeAuthenticated() { <START> boolean authenticated = authenticateWithLdap(); <END> if (authenticated) { if (!checkUserAndGroupsAuthorization(ldapUser.getUserId(), ldapUser.getGroupIds(), getActionType().getActionGroup(), MultiLevelAdministrationHandler.BOTTOM_OBJECT_ID, VdcObjectType.Bottom)) { addCanDoActionMessage(VdcBllMessages.USER_NOT_AUTHORIZED_TO_PERFORM_ACTION); return false; } VdcUser currentUser = new VdcUser(ldapUser); boolean isAdmin = MultiLevelAdministrationHandler.isAdminUser(currentUser); log.debugFormat("Checking if user {0} is an admin, result {1}", currentUser.getUserName(), isAdmin); currentUser.setAdmin(isAdmin); setCurrentUser(currentUser); } return authenticated; }</code><technical_language>necessarily LDAP. change "authenticateUser" similar</technical_language>

Target:
protected boolean isUserCanBeAuthenticated() { boolean authenticated = performUserAuthentication(); if (authenticated) { if (!checkUserAndGroupsAuthorization(ldapUser.getUserId(), ldapUser.getGroupIds(), getActionType().getActionGroup(), MultiLevelAdministrationHandler.BOTTOM_OBJECT_ID, VdcObjectType.Bottom)) { addCanDoActionMessage(VdcBllMessages.USER_NOT_AUTHORIZED_TO_PERFORM_ACTION); return false; } VdcUser currentUser = new VdcUser(ldapUser); retrieveUserAdminStatus(currentUser); setCurrentUser(currentUser); } return authenticated; }
Source:
<code>public VertexRef getTarget() { <START> return Optional.ofNullable(getPropertyValue(PROPERTY_TARGET)).map(VertexRef::new).orElse(null); <END> }</code><technical_language>if (...) more easy read</technical_language>

Target:
public VertexRefEntity getTarget() { return target; }
Source:
<code>void onAnnounce(Message announcementMessage) { LOG.debug(String.format("Handling announcement message %s...", announcementMessage)); boolean successfullyAggregated = aggregateInfo(masterAggregatorStats, announcementMessage); <START> if(successfullyAggregated) { <END> LOG.debug(String.format("Calling registered handler for for aggregated statistics %s...", masterAggregatorStats)); handler.call(masterAggregatorStats); LOG.debug(String.format("Announcement message processed")); } else { LOG.error("Message will be skipped in statistics computation.", announcementMessage); } }</code><technical_language>missing space</technical_language>

Target:
void onAnnounce(Message announcementMessage) { LOG.debug(String.format("Handling announcement message %s...", announcementMessage)); boolean successfullyAggregated = aggregateInfo(masterAggregatorStats, announcementMessage); if (successfullyAggregated) { LOG.debug(String.format("Calling registered handler for announcement statistics %s...", masterAggregatorStats)); handler.call(masterAggregatorStats); LOG.debug(String.format("Announcement message processed")); } }
Source:
<code>public Map<String, ByteBuffer> unTar() throws IOException { Map<String, ByteBuffer> fileContent = new HashMap<>(); TarArchiveEntry tarEntry = null; tarEntry = tarInputStream.getNextTarEntry(); while (tarEntry != null) { byte[] content = new byte[(int) tarEntry.getSize()]; try (InputStream is = new FileInputStream(tarEntry.getFile());) { if (is.read(content) == -1) { <START> log.errorFormat("File {0} could not be read ", tarEntry.getFile()); <END> } } fileContent.put(tarEntry.getName(), ByteBuffer.wrap(content)); tarEntry = tarInputStream.getNextTarEntry(); } return fileContent; }</code><technical_language>need add continue (no need put in map) imo throw exception in case</technical_language>

Target:
public Map<String, ByteBuffer> unTar() throws IOException { Map<String, ByteBuffer> fileContent = new HashMap<>(); TarArchiveEntry tarEntry = null; tarEntry = tarInputStream.getNextTarEntry(); while (tarEntry != null) { byte[] content = new byte[(int) tarEntry.getSize()]; try (InputStream is = new FileInputStream(tarEntry.getFile());) { if (is.read(content) == -1) { log.errorFormat("File {0} could not be read ", tarEntry.getFile()); continue; } } fileContent.put(tarEntry.getName(), ByteBuffer.wrap(content)); tarEntry = tarInputStream.getNextTarEntry(); } return fileContent; }
Source:
<code>private String modifybasename(String name) { if(name.equalsIgnoreCase("children")) return "child"; if(name.length()>2 && name.endsWith("s")) <START> return name.substring(0,name.length()-1); <END> return FOR_LOOP_ELEMENT_IDENTIFIER; }</code><technical_language>this handle suffix 'es'</technical_language>

Target:
private String modifybasename(String name) { if(name.equalsIgnoreCase("children")) return "child"; if(name.endsWith("Entries")) { String firstpart=name.substring(0,name.length()-7); return firstpart+"Entry"; } if(name.length()>2 && name.endsWith("s")) return name.substring(0,name.length()-1); return FOR_LOOP_ELEMENT_IDENTIFIER; }
Source:
<code><START> public AmqpTransaction(ByteBuffer transactionId) { <END> this.transactionId = transactionId; }</code><technical_language>transactionId null. Add a null check here</technical_language>

Target:
public AmqpTransaction(ByteBuffer transactionId) { this.transactionId = Objects.requireNonNull(transactionId, "'transactionId' cannot be null."); }
Source:
<code>public static void main(String[] args) throws InterruptedException { MesosCluster cluster = new MesosCluster( MesosClusterConfig.builder() .mesosImageTag(MESOS_IMAGE_TAG) <START> .slaveResources(new String[]{"ports(*):[4000-4000,5000-5000]", "ports(*):[4001-4001,5001-5001]", "ports(*):[4002-4002,5002-5002]"}) <END> .build() ); final AtomicReference<ElasticsearchSchedulerContainer> schedulerReference = new AtomicReference<>(null); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { if (schedulerReference.get() != null) { schedulerReference.get().remove(); } cluster.stop(); new DockerUtil(cluster.getConfig().dockerClient).killAllExecutors(); } }); cluster.start(); LOGGER.info("Starting scheduler"); ElasticsearchSchedulerContainer scheduler = new ElasticsearchSchedulerContainer(cluster.getConfig().dockerClient, cluster.getZkContainer().getIpAddress(), cluster); schedulerReference.set(scheduler); scheduler.start(); seedData(cluster, scheduler); LOGGER.info("Scheduler started at http://" + scheduler.getIpAddress() + ":" + TEST_CONFIG.getSchedulerGuiPort()); LOGGER.info("Type CTRL-C to quit"); while (true) { Thread.sleep(1000); } }</code><technical_language>out of curiosity: new ports</technical_language>

Target:
public static void main(String[] args) throws InterruptedException { MesosCluster cluster = new MesosCluster( MesosClusterConfig.builder() .mesosImageTag(MESOS_IMAGE_TAG) .slaveResources(TEST_CONFIG.getPortRanges()) .build() ); final AtomicReference<ElasticsearchSchedulerContainer> schedulerReference = new AtomicReference<>(null); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { if (schedulerReference.get() != null) { schedulerReference.get().remove(); } cluster.stop(); new DockerUtil(cluster.getConfig().dockerClient).killAllExecutors(); } }); cluster.start(); LOGGER.info("Starting scheduler"); ElasticsearchSchedulerContainer scheduler = new ElasticsearchSchedulerContainer(cluster.getConfig().dockerClient, cluster.getZkContainer().getIpAddress(), cluster); schedulerReference.set(scheduler); scheduler.start(); seedData(cluster, scheduler); LOGGER.info("Scheduler started at http://" + scheduler.getIpAddress() + ":" + TEST_CONFIG.getSchedulerGuiPort()); LOGGER.info("Type CTRL-C to quit"); while (true) { Thread.sleep(1000); } }
Source:
<code>public static Step addStep(ExecutionContext context, StepEnum stepName, String description, boolean isExternal) { if (context == null) { return null; } Step step = null; if (context.isMonitored()) { if (description == null) { description = ExecutionMessageDirector.getInstance().getStepMessage(stepName); } try { Job job = context.getJob(); if (context.getExecutionMethod() == ExecutionMethod.AsJob && job != null) { <START> JobRepositoryFactory.getJobRepository().loadJobSteps(job); <END> step = job.addStep(stepName, description); try { step.setExternal(isExternal); JobRepositoryFactory.getJobRepository().saveStep(step); } catch (Exception e) { log.errorFormat("Failed to save new step {0} for job {1}, {2}.", stepName.name(), job.getId(), job.getActionType().name(), e); job.getSteps().remove(step); step = null; } } else { Step contextStep = context.getStep(); if (context.getExecutionMethod() == ExecutionMethod.AsStep && contextStep != null) { JobRepositoryFactory.getJobRepository().loadParentStepSteps(contextStep); step = addSubStep(contextStep, stepName, description); step.setExternal(isExternal); } } } catch (Exception e) { log.error(e); } } return step; }</code><technical_language>suggest fetching steps of job a parent step if job steps. of time adding a step is in context creating job, previously created steps part of job. else, face excessive db access. In addition, if check if (job.getSteps().isEmpty()) { JobRepositoryFactory.getJobRepository().loadJobSteps(job); } called for step created for Job, monitored command invocation demand extra db access for db. If is considered a big issue - some "initialized" indicator Job, rely for new-job steps loading. (for simplicity, start it)</technical_language>

Target:
public static Step addStep(ExecutionContext context, StepEnum stepName, String description, boolean isExternal) { if (context == null) { return null; } Step step = null; if (context.isMonitored()) { if (description == null) { description = ExecutionMessageDirector.getInstance().getStepMessage(stepName); } try { Job job = context.getJob(); if (context.getExecutionMethod() == ExecutionMethod.AsJob && job != null) { step = job.addStep(stepName, description); try { step.setExternal(isExternal); JobRepositoryFactory.getJobRepository().saveStep(step); } catch (Exception e) { log.errorFormat("Failed to save new step {0} for job {1}, {2}.", stepName.name(), job.getId(), job.getActionType().name(), e); job.getSteps().remove(step); step = null; } } else { Step contextStep = context.getStep(); if (context.getExecutionMethod() == ExecutionMethod.AsStep && contextStep != null) { step = addSubStep(contextStep, stepName, description); step.setExternal(isExternal); } } } catch (Exception e) { log.error(e); } } return step; }
Source:
<code>public static synchronized Properties getProperties() { <START> if (properties == null) { <END> File propFile = getPropertiesFile(getBasedir().getAbsoluteFile(), BUILD_PROPS_SEARCH_PARENT_DIR_LIMIT); Validate.isTrue(propFile.exists(), "Couldn't find build.properties at '%s'!", propFile.getAbsolutePath()); properties = new Properties(); FileInputStream fis = null; try { fis = new FileInputStream(propFile); properties.load(fis); } catch (FileNotFoundException e) { throw new IllegalStateException("Properties file not found. At this point, this is impossible.", e); } catch (IOException e) { throw new IllegalStateException("Properties file cannot be read!", e); } finally { if (fis != null) { try { fis.close(); } catch (IOException ex) { LOGGER.warn("Failed to close input stream", ex); } } } } return (Properties) properties.clone(); }</code><technical_language>Point of style: if statement is 95 % of method, method refactored return needs indented. Alternatively, block turned a new method (Properties createProperties()), is cleaner</technical_language>

Target:
public static synchronized Properties getProperties() { return (properties==null) ? createProperties() : (Properties) properties.clone(); }
Source:
<code>protected String getRFC822EmailAddress(final Collection<List<?>> subjectAltNames) { try { if (subjectAltNames == null) { return null; } Optional<List<?>> email = subjectAltNames.stream().filter(s -> ((Integer) s.get(0)) == RFC822_SAN_TYPE).findFirst(); if (email.isPresent()) { return (String) email.get().get(1); } <START> } catch (final ArrayIndexOutOfBoundsException e) { <END> LOGGER.error("Subject Alternative Name List does not contain at least two required elements. Returning null principal id..."); } return null; }</code><technical_language>This is odd; sort of catch. this prevented</technical_language>

Target:
protected String getRFC822EmailAddress(final Collection<List<?>> subjectAltNames) { if (subjectAltNames == null) { return null; } Optional<List<?>> email = subjectAltNames .stream() .filter(s -> s.size() == 2 && ((Integer) s.get(0)) == SAN_RFC822_EMAIL_TYPE) .findFirst(); if (email.isPresent()) { return (String) email.get().get(1); } return null; }
Source:
<code>public SimplifyExpressions(Metadata metadata, SqlParser sqlParser) <START> { <END> super((expression, context) -> rewrite(expression, context, metadata, sqlParser)); }</code><technical_language>I thought more rewrites</technical_language>

Target:
public SimplifyExpressions(Metadata metadata, SqlParser sqlParser) { this.metadata = metadata; this.sqlParser = sqlParser; }
Source:
<code>private void validateDeploymentProperties(D definition, Map<String, String> properties) { List<ModuleDescriptor> modules = parser.parse(definition.getName(), definition.getDefinition(), definitionKind); Set<String> moduleLabels = new HashSet<String>(modules.size()); for (ModuleDescriptor md : modules) { moduleLabels.add(md.getModuleLabel()); } <START> DeploymentPropertiesUtility.validateDeploymentProperties(properties, moduleLabels); <END> }</code><technical_language>a fan of static utility methods if avoided. AbstractDeployer is class this utility method, included in AbstractDeployer</technical_language>

Target:
private void validateDeploymentProperties(D definition, Map<String, String> properties) { List<ModuleDescriptor> modules = parser.parse(definition.getName(), definition.getDefinition(), definitionKind); Set<String> moduleLabels = new HashSet<String>(modules.size()); for (ModuleDescriptor md : modules) { moduleLabels.add(md.getModuleLabel()); } for (Map.Entry<String, String> pair : properties.entrySet()) { Matcher matcher = DEPLOYMENT_PROPERTY_PATTERN.matcher(pair.getKey()); Assert.isTrue(matcher.matches(), String.format("'%s' does not match '%s'", pair.getKey(), DEPLOYMENT_PROPERTY_PATTERN)); String moduleName = matcher.group(1); Assert.isTrue(moduleLabels.contains(moduleName), String.format("'%s' refers to a module that is not in the list: %s", pair.getKey(), moduleLabels)); } }
Source:
<code>public String toString() { return Objects.toStringHelper(this) <START> .add("World:", this.worldObj) <END> .add("Position: ", this.xPosition + this.zPosition) .toString(); }</code><technical_language>world, ToStringHelper automatically formats uppercase keys odd</technical_language>

Target:
public String toString() { return Objects.toStringHelper(this) .add("World", this.worldObj) .add("Position", this.xPosition + this.zPosition) .toString(); }
Source:
<code>private SharedRealm getSharedRealm() { RealmConfiguration config; <START> config = configFactory.createConfiguration(); <END> return getSharedRealm(config); }</code><technical_language>RealmConfiguration config = configFactory.createConfiguration();</technical_language>

Target:
private SharedRealm getSharedRealm() { RealmConfiguration config = configFactory.createConfiguration(); return getSharedRealm(config); }
Source:
<code>public final HttpResponse invoke(Q query, String endpoint) throws InvocationException { Preconditions.checkNotNull(query); Preconditions.checkNotNull(endpoint); httpClient.setParams(getHttpClientParams(query)); HttpRequestBase method; HttpEntity response = null; try { method = getHttpMethod(query, endpoint); org.apache.http.HttpResponse httpResponse = httpClient.execute(method); response = httpResponse.getEntity(); return HttpResponse.create(httpResponse.getStatusLine().getStatusCode(), EntityUtils.toString(response)); } catch (URISyntaxException e) { <START> log.debug("Error during invocation", e); <END> throw new InvocationException("InvocationException : ", e); } catch (ClientProtocolException e) { log.debug("Error during invocation", e); throw new InvocationException("InvocationException : ", e); } catch (IOException e) { log.debug("Error during invocation", e); throw new InvocationException("InvocationException : ", e); } finally { try { if (response != null) EntityUtils.consume(response); } catch (Throwable e) { log.error("Cannot release connection", e); } } }</code><technical_language>Please provide URL in message</technical_language>

Target:
public final HttpResponse invoke(Q query, String endpoint) throws InvocationException { Preconditions.checkNotNull(query); Preconditions.checkNotNull(endpoint); httpClient.setParams(getHttpClientParams(query)); HttpRequestBase method = null; HttpEntity response = null; try { method = getHttpMethod(query, endpoint); org.apache.http.HttpResponse httpResponse = httpClient.execute(method); response = httpResponse.getEntity(); return HttpResponse.create(httpResponse.getStatusLine().getStatusCode(), EntityUtils.toString(response)); } catch (Exception e) { if (method != null) { log.debug("Error during invocation with URL: " + method.getURI() + ", endpoint: " + endpoint + ", query: " + query, e); } else { log.debug("Error during invocation with: endpoint: " + endpoint + ", query: " + query, e); } throw new InvocationException("InvocationException : ", e); } finally { EntityUtils.consumeQuietly(response); } }
Source:
<code>public <T> T doPost(final String uri, final Object body, final Multimap<String, String> options, final Class<T> clazz) throws KillBillClientException { <START> return doPost(uri, body, options, this.httpTimeOut, clazz); <END> }</code><technical_language>executeAndWait method changed expect a in milliseconds (httpTimeOut is in milliseconds, seconds)</technical_language>

Target:
public <T> T doPost(final String uri, final Object body, final Multimap<String, String> options, final Class<T> clazz) throws KillBillClientException { return doPost(uri, body, options, requestTimeoutSec, clazz); }
Source:
<code><START> private static AuditListener createListener(String format, <END> String outputLocation) throws IOException { final OutputStream out; final AutomaticBean.OutputStreamOptions closeOutputStream; if (outputLocation == null) { out = System.out; closeOutputStream = AutomaticBean.OutputStreamOptions.NONE; } else { out = Files.newOutputStream(Paths.get(outputLocation)); closeOutputStream = AutomaticBean.OutputStreamOptions.CLOSE; } final AuditListener listener; if (XML_FORMAT_NAME.equals(format)) { listener = new XMLLogger(out, closeOutputStream); } else if (PLAIN_FORMAT_NAME.equals(format)) { listener = new DefaultLogger(out, closeOutputStream, out, AutomaticBean.OutputStreamOptions.NONE); } else { if (closeOutputStream == AutomaticBean.OutputStreamOptions.CLOSE) { CommonUtils.close(out); } final LocalizedMessage outputFormatExceptionMessage = new LocalizedMessage(0, Definitions.CHECKSTYLE_BUNDLE, CREATE_LISTENER_EXCEPTION, new String[] {format, PLAIN_FORMAT_NAME, XML_FORMAT_NAME}, null, Main.class, null); throw new IllegalStateException(outputFormatExceptionMessage.getMessage()); } return listener; }</code><technical_language>ok, call new feature request, enhancement, type of ticket Eclipse better. If IDEA false positives, Eclipse ? If Eclipse is configurable/smart ... activate ? sense activate IDEA ? Do get some benefit Eclipse only(not detected IDEA)</technical_language>

Target:
private static AuditListener createListener(String format, String outputLocation) throws IOException { final AuditListener listener; if (XML_FORMAT_NAME.equals(format)) { final OutputStream out = getOutputStream(outputLocation); final AutomaticBean.OutputStreamOptions closeOutputStreamOption = getOutputStreamOptions(outputLocation); listener = new XMLLogger(out, closeOutputStreamOption); } else if (PLAIN_FORMAT_NAME.equals(format)) { final OutputStream out = getOutputStream(outputLocation); final AutomaticBean.OutputStreamOptions closeOutputStreamOption = getOutputStreamOptions(outputLocation); listener = new DefaultLogger(out, closeOutputStreamOption); } else { final LocalizedMessage outputFormatExceptionMessage = new LocalizedMessage(0, Definitions.CHECKSTYLE_BUNDLE, CREATE_LISTENER_EXCEPTION, new String[] {format, PLAIN_FORMAT_NAME, XML_FORMAT_NAME}, null, Main.class, null); throw new IllegalStateException(outputFormatExceptionMessage.getMessage()); } return listener; }
Source:
<code><START> private byte[] findBasesByMD5(final String md5) throws IOException { <END> final String url = String.format(Defaults.EBI_REFERENCE_SERVICE_URL_MASK, md5); for (int i = 0; i < downloadTriesBeforeFailing; i++) { try (final InputStream is = new URL(url).openStream()) { if (is == null) return null; log.debug("Downloading reference sequence: " + url); final byte[] data = InputStreamUtils.readFully(is); log.debug("Downloaded " + data.length + " bytes for md5 " + md5); is.close(); final String downloadedMD5 = SequenceUtil.calculateMD5String(data); if (md5.equals(downloadedMD5)) { return data; } else { final String message = String .format("Downloaded sequence is corrupt: requested md5=%s, received md5=%s", md5, downloadedMD5); log.error(message); } } catch (final NoSuchAlgorithmException e) { throw new RuntimeException(e); } } throw new RuntimeException("Giving up on downloading sequence for md5 " + md5); }</code><technical_language>want remove this throws IOException well</technical_language>

Target:
private byte[] findBasesByMD5(final String md5) { final String url = String.format(Defaults.EBI_REFERENCE_SERVICE_URL_MASK, md5); for (int i = 0; i < downloadTriesBeforeFailing; i++) { try (final InputStream is = new URL(url).openStream()) { if (is == null) return null; log.info("Downloading reference sequence: " + url); final byte[] data = InputStreamUtils.readFully(is); log.info("Downloaded " + data.length + " bytes for md5 " + md5); final String downloadedMD5 = SequenceUtil.calculateMD5String(data); if (md5.equals(downloadedMD5)) { return data; } else { final String message = String .format("Downloaded sequence is corrupt: requested md5=%s, received md5=%s", md5, downloadedMD5); log.error(message); } } catch (final NoSuchAlgorithmException | IOException e) { throw new RuntimeException(e); } } throw new GaveUpException("Giving up on downloading sequence for md5 " + md5); }
Source:
<code>protected void doExecute() { if (representationDescriptor != null) { representationDescriptor.setName(newName); <START> representationDescriptor.setName(newName); <END> } }</code><technical_language>remove. line :)</technical_language>

Target:
protected void doExecute() { if (representationDescriptor != null) { representationDescriptor.setName(newName); } }
Source:
<code>public static String insertId(String message, ObjectId changeId) { if (message.indexOf("\nChange-Id:") > 0) return message; <START> message = message.replaceAll("(.*\n)\n*([a-zA-Z0-9-]+:.*)$", <END> "$1\nChange-Id: I" + ObjectId.toString(changeId) + "\n$2"); if (message.indexOf("\nChange-Id:") > 0) return message; return message + "\nChange-Id: I" + ObjectId.toString(changeId) + "\n"; }</code><technical_language>I prefer running this parser RevCommit parsing footer lines. code is part of RevCommit. need pull out a utility class, find a construct a RevCommit buffered message reuse parser. if do that, search end of string find paragraph break denotes "footer" insert there. point, replicating parsing code. In of rules do in shell hook is, try insert Change-Id line Bug line, if is present, other lines. hard do a simple regex replaceAll insert item string</technical_language>

Target:
public static String insertId(String message, ObjectId changeId) { if (message.indexOf("\nChange-Id:") > 0) return message; String[] lines = message.split("\n"); int lastPattern = -1; int firstPattern = -1; for (int i = lines.length - 1; i > 0; --i) { if (issuePattern.matcher(lines[i]).matches()) { firstPattern = i; lastPattern = i; continue; } if (footerPattern.matcher(lines[i]).matches()) { lastPattern = i; continue; } if (lines[i].trim().length() == 0) { lines[i] = ""; break; } lastPattern = lines.length; break; } if (lastPattern == -1) lastPattern = lines.length; if (firstPattern == -1) firstPattern = lastPattern - 1; if (firstPattern > lastPattern) firstPattern = lastPattern - 1; StringBuilder ret = new StringBuilder(); int i = 0; for (; i <= firstPattern; ++i) { if (lines[i].length() != 0 || i > 0 && lines[i-1].length() != 0) { ret.append(lines[i]); ret.append("\n"); } } if (i == lines.length && lastPattern == lines.length) ret.append("\n"); ret.append("Change-Id: I"); ret.append(ObjectId.toString(changeId)); ret.append("\n"); for (; i < lines.length; ++i) { ret.append(lines[i]); ret.append("\n"); } return ret.toString(); }
Source:
<code>private boolean isPolicyValid(RespondingGatewayProvideAndRegisterDocumentSetSecuredResponseRequestType request, AssertionType assertion) { boolean isValid = false; if (hasNhinTargetHomeCommunityId(request)) { String senderHCID = getSubjectHelper().determineSendingHomeCommunityId(assertion.getHomeCommunity(), assertion); String receiverHCID = getNhinTargetHomeCommunityId(request); String direction = NhincConstants.POLICYENGINE_OUTBOUND_DIRECTION; <START> <END> isValid = getXDRPolicyChecker().checkXDRResponsePolicy(request.getRegistryResponse(), assertion, senderHCID, receiverHCID, direction); } else { LOG.warn("Check on policy requires a non null target home community ID specified in the request"); } LOG.debug("Check on policy returns: " + isValid); return isValid; }</code><technical_language>need for declaring receiverHCID direction.We inline method calls here</technical_language>

Target:
private boolean isPolicyValid(RespondingGatewayProvideAndRegisterDocumentSetSecuredResponseRequestType request, AssertionType assertion) { boolean isValid = false; if (hasNhinTargetHomeCommunityId(request)) { isValid = getXDRPolicyChecker().checkXDRResponsePolicy(request.getRegistryResponse(), assertion, getSubjectHelper().determineSendingHomeCommunityId(assertion.getHomeCommunity(), assertion), getNhinTargetHomeCommunityId(request), NhincConstants.POLICYENGINE_OUTBOUND_DIRECTION); } else { LOG.warn("Check on policy requires a non null target home community ID specified in the request"); } LOG.debug("Check on policy returns: " + isValid); return isValid; }
Source:
<code>public void cleanupStaleBuffers() { m_es.execute(new Runnable() { public void run() { long generationIdCreated = m_committedBuffers.getGenerationIdCreated(); try { <START> if (m_committedBuffers.deleteStalePBDSegments(generationIdCreated)) { <END> m_gapTracker = new ExportSequenceNumberTracker(); } } catch (IOException e) { VoltDB.crashLocalVoltDB("Error while trying to delete stale PBD segments older than generation " + generationIdCreated, true, e); } } }); }</code><technical_language>Verify delete stale segments in scenario of bug #16009</technical_language>

Target:
public void cleanupStaleBuffers() { m_es.execute(new Runnable() { public void run() { long generationIdCreated = m_committedBuffers.getGenerationIdCreated(); try { if (m_committedBuffers.deleteStaleBlocks(generationIdCreated)) { m_gapTracker = m_committedBuffers.scanForGap(); } } catch (IOException e) { VoltDB.crashLocalVoltDB("Error while trying to delete stale PBD segments older than generation " + generationIdCreated, true, e); } } }); }
Source:
<code>private static Map<Class<? extends Message>, Method> scan(Class<?> declaringClass, Predicate<Method> filter) { final Map<Class<? extends Message>, Method> tempMap = Maps.newHashMap(); for (Method method : declaringClass.getDeclaredMethods()) { if (filter.apply(method)) { final Class<? extends Message> messageClass = HandlerMethod.getFirstParamType(method); if (tempMap.containsKey(messageClass)) { final Method alreadyPresent = tempMap.get(messageClass); throw new DuplicateHandlerMethodException( declaringClass, messageClass, alreadyPresent.getName(), method.getName()); } tempMap.put(messageClass, method); } } <START> final ImmutableMap.Builder<Class<? extends Message>, Method> builder = ImmutableMap.builder(); <END> builder.putAll(tempMap); return builder.build(); }</code><technical_language>refactor temp map add builder beginning</technical_language>

Target:
private static Map<Class<? extends Message>, Method> scan(Class<?> declaringClass, Predicate<Method> filter) { final Map<Class<? extends Message>, Method> tempMap = Maps.newHashMap(); for (Method method : declaringClass.getDeclaredMethods()) { if (filter.apply(method)) { final Class<? extends Message> messageClass = HandlerMethod.getFirstParamType(method); if (tempMap.containsKey(messageClass)) { final Method alreadyPresent = tempMap.get(messageClass); throw new DuplicateHandlerMethodException( declaringClass, messageClass, alreadyPresent.getName(), method.getName()); } tempMap.put(messageClass, method); } } final ImmutableMap<Class<? extends Message>, Method> result = ImmutableMap.copyOf(tempMap); return result; }
Source:
<code>public List<DeterministicKey> getKeys(KeyPurpose purpose,int numberOfKeys) { checkArgument(numberOfKeys > 0); lock.lock(); try { DeterministicKey parentKey; int index; switch (purpose) { case RECEIVE_FUNDS: case REFUND: issuedExternalKeys += numberOfKeys; index = issuedExternalKeys; parentKey = externalKey; break; case CHANGE: issuedInternalKeys += numberOfKeys; index = issuedInternalKeys; parentKey = internalKey; break; default: throw new UnsupportedOperationException(); } List<DeterministicKey> lookahead = maybeLookAhead(parentKey, index); basicKeyChain.importKeys(lookahead); List keys = new ArrayList<DeterministicKey>(numberOfKeys); <START> for (int i=1; i<=numberOfKeys; i++) { <END> keys.add(hierarchy.get(HDUtils.append(parentKey.getPath(), new ChildNumber((index-numberOfKeys+i) - 1, false)), false, false)); } return keys; } finally { lock.unlock(); } }</code><technical_language>Please watch code style guidelines: for (int i = 1; i <= numberOfKeys; i++) { } (spaces operators). in expression below</technical_language>

Target:
public List<DeterministicKey> getKeys(KeyPurpose purpose,int numberOfKeys) { checkArgument(numberOfKeys > 0); lock.lock(); try { DeterministicKey parentKey; int index; switch (purpose) { case RECEIVE_FUNDS: case REFUND: issuedExternalKeys += numberOfKeys; index = issuedExternalKeys; parentKey = externalKey; break; case CHANGE: issuedInternalKeys += numberOfKeys; index = issuedInternalKeys; parentKey = internalKey; break; default: throw new UnsupportedOperationException(); } List<DeterministicKey> lookahead = maybeLookAhead(parentKey, index); basicKeyChain.importKeys(lookahead); List<DeterministicKey> keys = new ArrayList<DeterministicKey>(numberOfKeys); for (int i = 1; i <= numberOfKeys; i++) { keys.add(hierarchy.get(HDUtils.append(parentKey.getPath(), new ChildNumber((index-numberOfKeys+i) - 1, false)), false, false)); } return keys; } finally { lock.unlock(); } }
Source:
<code>public void testBlockCompressSequenceFileWriterSync() throws IOException, EventDeliveryException, InterruptedException { String hdfsPath = testPath + "/sequenceFileWriterSync"; String body = "test event-" + System.nanoTime(); Configuration conf = new Configuration(); FileSystem fs = FileSystem.get(conf); fs.setVerifyChecksum(false); fs.setWriteChecksum(false); Path dirPath = new Path(hdfsPath); fs.delete(dirPath, true); fs.mkdirs(dirPath); Context context = new Context(); context.put("hdfs.path", hdfsPath); context.put("hdfs.rollCount", "10"); context.put("hdfs.rollSize", "0"); context.put("hdfs.rollInterval", "0"); <START> context.put("hdfs.batchSize", "1"); <END> context.put("hdfs.fileType", "SequenceFile"); context.put("hdfs.codeC", "BZip2Codec"); context.put("hdfs.writeFormat", "Writable"); Configurables.configure(sink, context); Channel channel = new MemoryChannel(); Configurables.configure(channel, context); sink.setChannel(channel); sink.start(); Transaction txn = channel.getTransaction(); txn.begin(); Event event = new SimpleEvent(); event.setBody(body.getBytes()); channel.put(event); txn.commit(); txn.close(); sink.process(); FileStatus[] dirStat = fs.listStatus(dirPath); Path[] paths = FileUtil.stat2Paths(dirStat); Assert.assertEquals(1, paths.length); SequenceFile.Reader reader = new SequenceFile.Reader(conf, SequenceFile.Reader.stream(fs.open(paths[0]))); LongWritable key = new LongWritable(); BytesWritable value = new BytesWritable(); Assert.assertTrue(reader.next(key, value)); Assert.assertArrayEquals(body.getBytes(), value.copyBytes()); fs.close(); }</code><technical_language>Please increase batch size 2 events</technical_language>

Target:
public void testBlockCompressSequenceFileWriterSync() throws IOException, EventDeliveryException { String hdfsPath = testPath + "/sequenceFileWriterSync"; FileSystem fs = FileSystem.get(new Configuration()); fs.setVerifyChecksum(false); fs.setWriteChecksum(false); String codecs = {"BZip2Codec", "DeflateCodec"}; for (String codec : codecs) { sequenceFileWriteAndVerifyEvents(fs, hdfsPath, codec, Collections.singletonList( "single-event" )); sequenceFileWriteAndVerifyEvents(fs, hdfsPath, codec, Arrays.asList( "multiple-events-1", "multiple-events-2", "multiple-events-3", "multiple-events-4", "multiple-events-5" )); } fs.close(); }
Source:
<code>public void putShouldChangeCachedValueImmediately(Boolean initialCacheValue, boolean newCacheValue) { initializeCache(initialCacheValue); remoteRepositoryAlivenessCacheManager.put(remoteRepository, newCacheValue); boolean actualCacheValue = remoteRepositoryAlivenessCacheManager.isAlive(remoteRepository); <START> <END> assertEquals(newCacheValue, actualCacheValue); }</code><technical_language>consider com.hazelcast.config.MapConfig#setTimeToLiveSeconds</technical_language>

Target:
public void putShouldChangeCachedValueImmediately(Boolean initialCacheValue, boolean newCacheValue) { initializeCache(initialCacheValue); remoteRepositoryAlivenessCacheManager.put(remoteRepository, newCacheValue); boolean alive = remoteRepositoryAlivenessCacheManager.isAlive(remoteRepository); assertThat(alive).isEqualTo(newCacheValue); }
Source:
<code>public Token getRequestToken() { createSession(); PostMethod requestPostMethod = new PostMethod(this.config.getRequestTokenURL()); signRequest(OAuthConstants.EMPTY_TOKEN, requestPostMethod, false); int requestTokenResponse = -1; try { requestTokenResponse = this.httpClient.executeMethod(requestPostMethod); } catch (HttpException e1) { MessageDialog.openError(PlatformUI.getWorkbench().getDisplay().getActiveShell(), "Error", "Failed to obtain valid authentication response"); } catch (IOException e1) { MessageDialog.openError(PlatformUI.getWorkbench().getDisplay().getActiveShell(), "Error", "Failed to obtain valid authentication response"); } Token requestToken = null; try { System.out.println(requestTokenResponse); System.out.println("Request Token" + <START> requestPostMethod.getResponseBodyAsString()); <END> InputStream responseBodyAsStream = requestPostMethod.getResponseBodyAsStream(); TokenExtractorImpl tokenextractor = new TokenExtractorImpl(); requestToken = tokenextractor.extract(StreamUtils.getStreamContents(responseBodyAsStream)); } catch (IOException e1) { MessageDialog.openError(PlatformUI.getWorkbench().getDisplay().getActiveShell(), "Error", "Failed to obtain valid authentication response"); } return requestToken; }</code><technical_language>logged in system instead of pritnln'd</technical_language>

Target:
public Token getRequestToken() { createSession(); PostMethod requestPostMethod = new PostMethod(this.config.getRequestTokenURL()); signRequest(OAuthConstants.EMPTY_TOKEN, requestPostMethod, false); int requestTokenResponse = -1; try { requestTokenResponse = this.httpClient.executeMethod(requestPostMethod); } catch (HttpException e1) { MessageDialog.openError(PlatformUI.getWorkbench().getDisplay().getActiveShell(), "Error", "Failed to obtain valid authentication response"); } catch (IOException e1) { MessageDialog.openError(PlatformUI.getWorkbench().getDisplay().getActiveShell(), "Error", "Failed to obtain valid authentication response"); } Token requestToken = null; try { OseeLog.log(DWAOAuthService.class, Level.INFO, "requestTokenResponse: " + requestTokenResponse); OseeLog.log(DWAOAuthService.class, Level.INFO, "Request Token" + requestPostMethod.getResponseBodyAsString()); InputStream responseBodyAsStream = requestPostMethod.getResponseBodyAsStream(); TokenExtractorImpl tokenextractor = new TokenExtractorImpl(); requestToken = tokenextractor.extract(StreamUtils.getStreamContents(responseBodyAsStream)); } catch (IOException e1) { MessageDialog.openError(PlatformUI.getWorkbench().getDisplay().getActiveShell(), "Error", "Failed to obtain valid authentication response"); } return requestToken; }
Source:
<code>public List<String> getPushOptions() { <START> if (allowPushOptions) { <END> if (enabledCapabilities == null) { throw new RequestNotYetReadException(); } return pushOptions == null ? null : Collections.unmodifiableList(pushOptions); } else { throw new IllegalStateException(); } }</code><technical_language>simplify dealing exceptional case first: if (!allowPushOptions) { // Reading push options a prior setAllowPushOptions(true) // call sense. throw new IllegalStateException(); } if (enabledCapabilities == null) { // Push options receive() called. throw new RequestNotYetReadException(); } if (pushOptions == null) { // client support push options. Return null distinguish // this case client declared support for push // options empty list of them. return null; } return Collections.unmodifiableList(pushOptions);</technical_language>

Target:
public List<String> getPushOptions() { if (!allowPushOptions) { throw new IllegalStateException(); } if (enabledCapabilities == null) { throw new RequestNotYetReadException(); } if (pushOptions == null) { return null; } return Collections.unmodifiableList(pushOptions); }