auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void close() throws IOException { <START> System.out.println("* * * ** * * * * " + schema.toString()); <END> delegate.close(); }</code><technical_language>assuming this for debugging, remove</technical_language>

Target:
public void close() throws IOException { delegate.close(); }
Source:
<code>public void registerJobs() { List<AuthenticationMethod> authenticationMethods; try { authenticationMethods = this.securityService.getAuthenticationMethods(); } catch (Exception e) { logger.warn("Unable to retrieve ldap configuration details. This has most likely occurred as a result" + " of the dashboard database not yet being created."); return; } authenticationMethods.forEach(authenticationMethod -> { if (authenticationMethod.isScheduled()) { LdapDirectorySynchronisationJob job = new LdapDirectorySynchronisationJob(authenticationMethod, this.ldapService, this.securityService); JobDetail jobDetail = this.scheduledJobFactory.createJobDetail <START> (job, BusinessStreamNotificationJob.class, job.getJobName(), "scheduled-ldap"); <END> super.jobDetails.add(jobDetail); super.dashboardJobDetailsMap.put(job.getJobName(), jobDetail); this.dashboardJobsMap.put(jobDetail.getKey().toString(), job); } }); for (JobDetail jobDetail : this.jobDetails) { logger.info(String.format("Registering ldap synchronisation job[%s]", jobDetail.getKey().getName())); this.addJob(jobDetail.getKey().getName()); } }</code><technical_language>This line right this.scheduledJobFactory.createJobDetail (job, BusinessStreamNotificationJob.class, job.getJobName(), "scheduled-ldap"); is Ldap Sych need BusinessStreamNotificationJob class</technical_language>

Target:
public void registerJobs() { List<AuthenticationMethod> authenticationMethods; try { authenticationMethods = this.securityService.getAuthenticationMethods(); } catch (Exception e) { logger.warn("Unable to retrieve ldap configuration details. This has most likely occurred as a result" + " of the dashboard database not yet being created."); return; } authenticationMethods.forEach(authenticationMethod -> { if (authenticationMethod.isScheduled()) { LdapDirectorySynchronisationJob job = new LdapDirectorySynchronisationJob(authenticationMethod, this.ldapService, this.securityService); JobDetail jobDetail = this.scheduledJobFactory.createJobDetail (job, LdapDirectorySynchronisationJob.class, job.getJobName(), "scheduled-ldap"); super.dashboardJobDetailsMap.put(job.getJobName(), jobDetail); super.dashboardJobsMap.put(jobDetail.getKey().toString(), job); } }); for (JobDetail jobDetail : super.dashboardJobDetailsMap.values()) { logger.info(String.format("Registering ldap synchronisation job[%s]", jobDetail.getKey().getName())); this.addJob(jobDetail.getKey().getName()); } }
Source:
<code>private FieldDescriptor getFieldDescriptor(Descriptor messageDescriptor, String attributePath) { FieldDescriptor fd = null; String[] split = attributePath.split("[.]"); for (int i = 0; i < split.length; i++) { String name = split[i]; fd = messageDescriptor.findFieldByName(name); if (fd == null) { throw new IllegalArgumentException("Unknown field " + name + " in type " + messageDescriptor.getFullName()); } IndexingMetadata indexingMetadata = messageDescriptor.getProcessedAnnotation(IndexingMetadata.INDEXED_ANNOTATION); if (indexingMetadata != null && !indexingMetadata.isFieldIndexed(fd.getNumber())) { <START> throw new IllegalArgumentException("Field " + name + " from type " + messageDescriptor.getFullName() + " is not indexed"); <END> } if (i < split.length - 1) { messageDescriptor = fd.getMessageType(); } } return fd; }</code><technical_language>Please log interface for throwing kind of exceptions</technical_language>

Target:
private FieldDescriptor getFieldDescriptor(Descriptor messageDescriptor, String attributePath) { FieldDescriptor fd = null; String[] split = attributePath.split("[.]"); for (int i = 0; i < split.length; i++) { String name = split[i]; fd = messageDescriptor.findFieldByName(name); if (fd == null) { throw log.unknownField(name, messageDescriptor.getFullName()); } IndexingMetadata indexingMetadata = messageDescriptor.getProcessedAnnotation(IndexingMetadata.INDEXED_ANNOTATION); if (indexingMetadata != null && !indexingMetadata.isFieldIndexed(fd.getNumber())) { throw log.fieldIsNotIndexed(name, messageDescriptor.getFullName()); } if (i < split.length - 1) { messageDescriptor = fd.getMessageType(); } } return fd; }
Source:
<code>public void menuDetected(MenuDetectEvent e) { if (null == _timeProvider) { <START> return; <END> } Point p = toControl(e.x, e.y); int idx = getItemIndexAtY(p.y); if (idx >= 0 && idx < _data._expandedItems.length) { Item item = _data._expandedItems[idx]; ITimeGraphEntry entry = item._trace; if (entry.hasTimeEvents()) { ITimeEvent event = Utils.findEvent(entry, getTimeAtX(p.x), 2); if (event != null) { e.data = event; fireMenuEventOnTimeEvent(e); return; } } e.data = entry; fireMenuEventOnTimeGraphEntry(e); } }</code><technical_language>if (_dragState == DRAG_ZOOM && _dragX != _dragX0) { return; }</technical_language>

Target:
public void menuDetected(MenuDetectEvent e) { fPendingMenuDetectEvent = e; return; }
Source:
<code>protected void onPostExecute(Encounters encountersWithObservations) { if (encountersWithObservations == null) { <START> Toast.makeText(observationsByEncounterAdapter.getContext(),"This patient does not have any SHR data.", Toast.LENGTH_SHORT).show(); <END> return; } if (observationsByEncounterAdapter.getBackgroundListQueryTaskListener() != null) { observationsByEncounterAdapter.getBackgroundListQueryTaskListener().onQueryTaskFinish(); } }</code><technical_language>Toast messages, SHR another SHR if condition in doInBackground</technical_language>

Target:
protected void onPostExecute(Encounters encountersWithObservations) { if (encountersWithObservations == null) { return; } if (observationsByEncounterAdapter.getBackgroundListQueryTaskListener() != null) { observationsByEncounterAdapter.getBackgroundListQueryTaskListener().onQueryTaskFinish(); } }
Source:
<code>protected void updatePreviewContent() { text.setText(formatText(getWizard().getTextForTextView())); if(browser == null) { return; } File f = getFile(); FileUtil.writeFile(f, getWizard().getTextForBrowser()); final Control c = Display.getCurrent().getFocusControl(); <START> if(browser.getUrl() == null || !browser.getUrl().endsWith(f.getName()) <END> ||"mozilla".equals(getBrowserType())) { browser.setUrl(url); } else { browser.refresh(); } if(c != null) { Display.getCurrent().asyncExec(new Runnable() { public void run() { c.forceFocus(); } }); } }</code><technical_language>okey - reason call setUrl() in cases</technical_language>

Target:
protected void updatePreviewContent() { text.setText(formatText(getWizard().getTextForTextView())); if(browser == null) { return; } File f = getFile(); FileUtil.writeFile(f, getWizard().getTextForBrowser()); final Control c = Display.getCurrent().getFocusControl(); if(browser.getUrl() == null || !browser.getUrl().endsWith(f.getName()) ||"mozilla".equals(getBrowserType())) { browser.setUrl(sourceURL); } else { browser.refresh(); } if(c != null) { Display.getCurrent().asyncExec(new Runnable() { public void run() { c.forceFocus(); } }); } }
Source:
<code>private void updateButtonsAfterStatusChange() { boolean anyDeselected = false; boolean anySelected = false; for (FormStatus f : formStatuses) { anyDeselected = anyDeselected || !f.isSelected(); anySelected = anySelected || f.isSelected(); } <START> btnTransfer.setEnabled(anySelected && (txtDestinationName == null || !TextUtils.isEmpty(txtDestinationName.getText()))); <END> if (!anyDeselected) { FormTransferTableModel.this.btnSelectOrClearAllForms.setText("Clear all"); } else { FormTransferTableModel.this.btnSelectOrClearAllForms.setText("Select all"); } }</code><technical_language>This btnTransfer.setEnabled(anySelected && sourceSelected)</technical_language>

Target:
private void updateButtonsAfterStatusChange() { boolean anyDeselected = false; boolean anySelected = false; for (FormStatus f : formStatuses) { anyDeselected = anyDeselected || !f.isSelected(); anySelected = anySelected || f.isSelected(); } btnTransfer.setEnabled(anySelected && sourceSelected); if (!anyDeselected) { FormTransferTableModel.this.btnSelectOrClearAllForms.setText("Clear all"); } else { FormTransferTableModel.this.btnSelectOrClearAllForms.setText("Select all"); } }
Source:
<code>public static void copy(File source, File destination, File root, boolean overwrite) throws IOException { File sourceFile = new File(source, root.getPath()); if (!sourceFile.exists()) throw new FileNotFoundException("Source: " + sourceFile + " does not exist"); File destinationFile = new File(destination, root.getPath()); if (destinationFile.exists()) if (overwrite) deleteAll(destinationFile); else throw new IOException("Destination: " + destinationFile + " already exists"); if (sourceFile.isDirectory()) { destinationFile.mkdirs(); File[] list = sourceFile.listFiles(); for (File <START> list1 : <END> list) { copy(source, destination, new File(root, list1.getName()), false); } } else { destinationFile.getParentFile().mkdirs(); try (InputStream in = new BufferedInputStream(new FileInputStream(sourceFile)); OutputStream out = new BufferedOutputStream(new FileOutputStream(destinationFile));) { copyStream(in, false, out, false); } } }</code><technical_language>file is name here</technical_language>

Target:
public static void copy(File source, File destination, File root, boolean overwrite) throws IOException { File sourceFile = new File(source, root.getPath()); if (!sourceFile.exists()) throw new FileNotFoundException("Source: " + sourceFile + " does not exist"); File destinationFile = new File(destination, root.getPath()); if (destinationFile.exists()) if (overwrite) deleteAll(destinationFile); else throw new IOException("Destination: " + destinationFile + " already exists"); if (sourceFile.isDirectory()) { destinationFile.mkdirs(); File[] list = sourceFile.listFiles(); for (File file : list) { copy(source, destination, new File(root, file.getName()), false); } } else { destinationFile.getParentFile().mkdirs(); try (InputStream in = new BufferedInputStream(new FileInputStream(sourceFile)); OutputStream out = new BufferedOutputStream(new FileOutputStream(destinationFile));) { copyStream(in, false, out, false); } } }
Source:
<code>public EventTemplate(String input, EventUtil eventUtil) { this.input = Objects.requireNonNull(input); this.eventUtil = Objects.requireNonNull(eventUtil); <START> this.parameterResolverRegistry = new ExpandableParameterResolverRegistry(); <END> parse(); }</code><technical_language>re-use ExpandableParameterResolverRegistry instead of re-creating for EventTemplate. pull EventUtil instance passed instead of passing another argument here</technical_language>

Target:
public EventTemplate(String input, EventUtil eventUtil) { this.input = Objects.requireNonNull(input); this.eventUtil = Objects.requireNonNull(eventUtil); parse(); this.requiresTransaction = tokens.stream().filter(t -> t.requiresTransaction()).findAny().isPresent(); }
Source:
<code>public ArrayList<Object> executePostRequest(HttpPost postRequest) throws OpenStackException { HttpResponse response; CloseableHttpClient httpClient = getHttpClient(); ArrayList<Object> message = new ArrayList(); Date localDate = null; String aux; try { response = httpClient.execute(postRequest); localDate = new Date(); <START> if ((response.getStatusLine().getStatusCode() != 201) && (response.getStatusLine().getStatusCode() != 200)) { <END> log.error("Failed : HTTP error code : " + response.getStatusLine().getStatusCode()); throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode()); } BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent()))); String temp = ""; while ((aux = br.readLine()) != null) { temp += aux; } message.add(temp); String aux1 = response.getHeaders("Date")[0].getValue(); log.info("Date recibido: " + aux1); message.add(response.getHeaders("Date")[0].getValue()); HttpEntity ent = response.getEntity(); if (ent != null) { EntityUtils.consume(ent); } } catch (ClientProtocolException ex) { log.error("Client protocol exception"); throw new OpenStackException("Client protocol exception " + ex.getMessage()); } catch (IOException ex) { log.error("I/O exception of some sort has occurred"); throw new OpenStackException("I/O exception of some sort has occurred " + ex.getMessage()); } return message; }</code><technical_language>gt 120</technical_language>

Target:
public ArrayList<Object> executePostRequest(HttpPost postRequest) throws OpenStackException { HttpResponse response; CloseableHttpClient httpClient = getHttpClient(); ArrayList<Object> message = new ArrayList(); String aux; try { response = httpClient.execute(postRequest); int statusCode = response.getStatusLine().getStatusCode(); if ((statusCode != 201) && (statusCode != 200)) { String errorMessage = "Failed : HTTP error code : " + statusCode; log.error(errorMessage); throw new RuntimeException(errorMessage); } BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent()))); String temp = ""; while ((aux = br.readLine()) != null) { temp += aux; } message.add(temp); String aux1 = response.getHeaders("Date")[0].getValue(); log.info("Date recibido: " + aux1); message.add(response.getHeaders("Date")[0].getValue()); HttpEntity ent = response.getEntity(); if (ent != null) { EntityUtils.consume(ent); } } catch (ClientProtocolException ex) { log.error("Client protocol exception"); throw new OpenStackException("Client protocol exception " + ex.getMessage()); } catch (IOException ex) { log.error("I/O exception of some sort has occurred"); throw new OpenStackException("I/O exception of some sort has occurred " + ex.getMessage()); } return message; }
Source:
<code>private MyqBindingConfig parseBindingConfig(Item item, String bindingConfig) throws BindingConfigParseException { final MyqBindingConfig config = new MyqBindingConfig(); if (item instanceof SwitchItem) { config.type = ITEMTYPE.Switch; } else if (item instanceof RollershutterItem) { config.type = ITEMTYPE.Rollershutter; } else if (item instanceof ContactItem) { config.type = ITEMTYPE.ContactStatus; } else if (item instanceof StringItem) { config.type = ITEMTYPE.StringStatus; <START> } <END> config.deviceIndex = Integer.parseInt(bindingConfig); return config; }</code><technical_language>mentioned before, instead of ITEMTYPE, consider config.acceptedDataTypes = new ArrayList<Class<? extends State>>(item.getAcceptedDataTypes()); stay unaware of item classes altogether. post update looping array finding a type support</technical_language>

Target:
private MyqBindingConfig parseBindingConfig(Item item, String bindingConfig) throws BindingConfigParseException { final MyqBindingConfig config = new MyqBindingConfig(); config.acceptedDataTypes = new ArrayList<Class<? extends State>>( item.getAcceptedDataTypes()); config.deviceIndex = Integer.parseInt(bindingConfig); return config; }
Source:
<code>private void createServerStore(ClientDescriptor clientDescriptor, CreateServerStore createServerStore) throws ClusterException { validateClusteredTierManagerConfigured(clientDescriptor); if(createServerStore.getStoreConfiguration().getPoolAllocation() instanceof PoolAllocation.Unknown) { throw new LifecycleException("Clustered tier can't be created with an Unknown resource pool"); } boolean isDuplicate = isLifeCycleMessageDuplicate(createServerStore); final String name = createServerStore.getName(); ServerStoreImpl serverStore; if (!isDuplicate) { LOGGER.info("Client creating new clustered tier '{}'", clientDescriptor, name); ServerStoreConfiguration storeConfiguration = createServerStore.getStoreConfiguration(); serverStore = ehcacheStateService.createStore(name, storeConfiguration); management.serverStoreCreated(name); } else { serverStore = ehcacheStateService.getStore(name); } serverStore.setEvictionListener(key -> invalidateHashAfterEviction(name, key)); attachStore(clientDescriptor, name); try { entityMessenger.messageSelfAndDeferRetirement(createServerStore, new ClientIDTrackerMessage.ServerStoreLifeCycleReplicationMessage(createServerStore)); } catch (MessageCodecException e) { <START> LOGGER.error("Codec Exception", e); <END> } }</code><technical_language>throw AssertionError this a programming error, else. for similar block below</technical_language>

Target:
private void createServerStore(ClientDescriptor clientDescriptor, CreateServerStore createServerStore) throws ClusterException { validateClusteredTierManagerConfigured(clientDescriptor); if(createServerStore.getStoreConfiguration().getPoolAllocation() instanceof PoolAllocation.Unknown) { throw new LifecycleException("Clustered tier can't be created with an Unknown resource pool"); } boolean isDuplicate = isLifeCycleMessageDuplicate(createServerStore); final String name = createServerStore.getName(); ServerStoreImpl serverStore; if (!isDuplicate) { LOGGER.info("Client creating new clustered tier '{}'", clientDescriptor, name); ServerStoreConfiguration storeConfiguration = createServerStore.getStoreConfiguration(); serverStore = ehcacheStateService.createStore(name, storeConfiguration); management.serverStoreCreated(name); } else { serverStore = ehcacheStateService.getStore(name); } serverStore.setEvictionListener(key -> invalidateHashAfterEviction(name, key)); attachStore(clientDescriptor, name); try { entityMessenger.messageSelfAndDeferRetirement(createServerStore, new ClientIDTrackerMessage.ServerStoreLifeCycleReplicationMessage(createServerStore)); } catch (MessageCodecException e) { throw new AssertionError("Codec error", e); } }
Source:
<code>private SortedMap<Path, IOException> deleteAllFilesAndDirectories() throws IOException { if (Files.notExists(dir)) { return Collections.emptySortedMap(); } SortedMap<Path, IOException> failures = new TreeMap<>(); Files.walkFileTree(dir, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) { return deleteAndContinue(file); } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) { return deleteAndContinue(dir); } private FileVisitResult deleteAndContinue(Path path) { try { Files.delete(path); return CONTINUE; } catch (IOException ex) { return deleteUndeletableAndContinue(path, ex); } } private FileVisitResult deleteUndeletableAndContinue(Path path, IOException ex) { boolean isWritable; try { isWritable = path.toFile().setWritable(true); } catch (Exception e) { ex.addSuppressed(e); failures.put(path, ex); return CONTINUE; } if (!isWritable) { <START> ex.addSuppressed( <END> new Exception("Cannot make file " + path + " writable with .toFile().setWritable(true)") { @Override public synchronized Throwable fillInStackTrace() { return this; } }); return CONTINUE; } try { Files.delete(path); } catch (IOException ex2) { ex.addSuppressed(ex2); failures.put(path, ex); } return CONTINUE; } }); return failures; }</code><technical_language>failures.put is missing in this case. I this error-prone. extracting a method returns exception suppress handle cases in place</technical_language>

Target:
private SortedMap<Path, IOException> deleteAllFilesAndDirectories() throws IOException { if (Files.notExists(dir)) { return Collections.emptySortedMap(); } SortedMap<Path, IOException> failures = new TreeMap<>(); Files.walkFileTree(dir, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) { return deleteAndContinue(file); } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) { return deleteAndContinue(dir); } private FileVisitResult deleteAndContinue(Path path) { try { Files.delete(path); } catch (NoSuchFileException ignore) { } catch (DirectoryNotEmptyException exception) { failures.put(path, exception); } catch (IOException exception) { makeWritableAndTryToDeleteAgain(path, exception); } return CONTINUE; } private void makeWritableAndTryToDeleteAgain(Path path, IOException exception) { try { makeWritable(path); Files.delete(path); } catch (Exception suppressed) { exception.addSuppressed(suppressed); failures.put(path, exception); } } private void makeWritable(Path path) { boolean writable = path.toFile().setWritable(true); if (!writable) { throw new UndeletableFileException("Attempt to make file '" + path + "' writable failed"); } } }); return failures; }
Source:
<code>public void testBucketProbingV1() throws Exception { <START> Configuration configuration = this.getConfiguration(); <END> configuration.setInt(S3A_BUCKET_PROBE, 1); intercept(FileNotFoundException.class, () -> FileSystem.get(uri, configuration)); }</code><technical_language>need for this</technical_language>

Target:
public void testBucketProbingV1() throws Exception { describe("Test the V1 bucket probe"); Configuration configuration = createConfigurationWithProbe(1); expectUnknownStore( () -> FileSystem.get(uri, configuration)); }
Source:
<code>public int handleCommand(final Namespace ns, final Manager m) { if (!m.isRegistered()) { System.err.println("User is not registered."); return 1; } for (String contact_number : ns.<String>getList("contact")) { m.setContactBlocked(contact_number, true); } <START> if(ns.<String>getList("group") != null) { <END> for (String groupIdString : ns.<String>getList("group")) { try { byte[] groupId = Util.decodeGroupId(groupIdString); m.setGroupBlocked(groupId, true); } catch (GroupIdFormatException | GroupNotFoundException e) { System.err.println(e.getMessage()); } } } return 0; }</code><technical_language>missing space if</technical_language>

Target:
public int handleCommand(final Namespace ns, final Manager m) { if (!m.isRegistered()) { System.err.println("User is not registered."); return 1; } for (String contact_number : ns.<String>getList("contact")) { try { m.setContactBlocked(contact_number, true); } catch (InvalidNumberException e) { System.err.println(e.getMessage()); } } if (ns.<String>getList("group") != null) { for (String groupIdString : ns.<String>getList("group")) { try { byte[] groupId = Util.decodeGroupId(groupIdString); m.setGroupBlocked(groupId, true); } catch (GroupIdFormatException | GroupNotFoundException e) { System.err.println(e.getMessage()); } } } return 0; }
Source:
<code>public void init(final OrganizationalUnit organizationalUnit) { view.init(this); organizationalUnitPopUpPresenter.setup(); view.setup("fa-folder", "fa-folder-open", organizationalUnit, () -> open(organizationalUnit), <START> () -> edit(organizationalUnit), <END> () -> remove(organizationalUnit)); }</code><technical_language>top values "fa-folder" "fa-folder-open"? If in view</technical_language>

Target:
public void init(final OrganizationalUnit organizationalUnit) { view.init(this); view.setup("fa-folder", "fa-folder-open", organizationalUnit, () -> open(organizationalUnit), () -> edit(organizationalUnit), () -> remove(organizationalUnit)); if (!canUpdateOrganizationalUnit(organizationalUnit)) { view.hideEditAction(); } if (!canRemoveOrganizationalUnit(organizationalUnit)) { view.hideRemoveAction(); } }
Source:
<code>public Response get(String url, Map<String, String> headers) throws IOException { try (CloseableHttpClient client = createHttpClient()) { final HttpGet request = new HttpGet(url); addHeaders(headers, request); <START> log.info("Sending request: " + request + " with headers: " + Arrays.asList(request.getAllHeaders())); <END> final HttpResponse response = client.execute(request); return Response.from(response); } }</code><technical_language>Do need info level</technical_language>

Target:
public Response get(String url, Map<String, String> headers) throws IOException { try (CloseableHttpClient client = createHttpClient()) { final HttpGet request = new HttpGet(url); addHeaders(headers, request); String message = "Sending request: " + request + " with headers: " + Arrays.asList(request.getAllHeaders()); log.log(PropertySecurityAction.isArquillianDebug() ? Level.INFO : Level.FINE, message); final HttpResponse response = client.execute(request); return Response.from(response); } }
Source:
<code>public static Slice stUnion(@SqlType(GEOMETRY_TYPE_NAME) Slice left, @SqlType(GEOMETRY_TYPE_NAME) Slice right) { OGCGeometry leftGeometry = deserialize(left); OGCGeometry rightGeometry = deserialize(right); <START> OGCGeometry ogcGeometry = leftGeometry.union(rightGeometry); <END> return ogcGeometry == null ? null : serialize(ogcGeometry); }</code><technical_language>@yaoxin226 supports multi-geometries, geometry-collection</technical_language>

Target:
public static Slice stUnion(@SqlType(GEOMETRY_TYPE_NAME) Slice left, @SqlType(GEOMETRY_TYPE_NAME) Slice right) { OGCGeometry leftGeometry = deserialize(left); validateType("ST_Union", leftGeometry, EnumSet.of(POINT, MULTI_POINT, LINE_STRING, MULTI_LINE_STRING, POLYGON, MULTI_POLYGON)); if (leftGeometry.isEmpty()) { return right; } OGCGeometry rightGeometry = deserialize(right); validateType("ST_Union", rightGeometry, EnumSet.of(POINT, MULTI_POINT, LINE_STRING, MULTI_LINE_STRING, POLYGON, MULTI_POLYGON)); if (rightGeometry.isEmpty()) { return left; } return serialize(leftGeometry.union(rightGeometry)); }
Source:
<code>protected final void registerAddRevisionDelta(CDOObject object, EStructuralFeature feature, int index, Object value) { <START> final CDOAddFeatureDeltaImpl featureDelta = new CDOAddFeatureDeltaImpl(feature, 0, value); <END> getRevisionDelta(object).addFeatureDelta(featureDelta); }</code><technical_language>index is passed in argument, 0 is in add feature delta</technical_language>

Target:
protected final void registerAddRevisionDelta(CDOObject object, EStructuralFeature feature, int index, Object value) { final CDOAddFeatureDeltaImpl featureDelta = new CDOAddFeatureDeltaImpl(feature, index, value); getRevisionDelta(object).addFeatureDelta(featureDelta); }
Source:
<code>public InternetDataConnection.BothStreams andOutput() throws IOException { <START> if (connected) <END> throw new RuntimeException("Cannot enable output after having already connected"); return new InternetDataConnection.BothStreams(this, new InternetDataConnection.OutputStreamProvider()); }</code><technical_language>Missing branckets explanation</technical_language>

Target:
public InternetDataConnection.BothStreams andOutput() throws IOException { if (connected) { throw new RuntimeException("Cannot enable output after having already connected"); } return new InternetDataConnection.BothStreams(this, new InternetDataConnection.OutputStreamProvider()); }
Source:
<code>public void shouldRetrievePermissionWithoutFailure() { assertNotNull(uiPermissionService); String[] permissions = uiPermissionService.getUIPermissions("unExistingType"); assertNotNull(permissions); <START> assertTrue(permissions.length == 0); <END> }</code><technical_language>assertEquals(0, permissions.length)</technical_language>

Target:
public void shouldRetrievePermissionWithoutFailure() { assertNotNull(uiPermissionService); String[] permissions = uiPermissionService.getUIPermissions("unExistingType"); assertNotNull(permissions); assertEquals(0, permissions.length); }
Source:
<code>public void testWithCollectionCallbackFindOne() throws Exception { Message<String> message = MessageBuilder.withPayload("").build(); MongoDbOutboundGateway gateway = createGateway(); gateway.setEntityClass(Person.class); <START> gateway.setExpectSingleResult(true); <END> gateway.setCollectionNameExpression(new LiteralExpression("data")); gateway.setRequiresReply(false); gateway.setCollectionCallback(collection -> { collection.insertOne(new Document("name", "Mike")); return null; }); gateway.afterPropertiesSet(); gateway.handleRequestMessage(message); List<Person> persons = this.mongoTemplate.find(new Query(), Person.class, COLLECTION_NAME); assertEquals(5, persons.size()); assertTrue(persons.stream().anyMatch(p -> p.getName().equals("Mike"))); }</code><technical_language>some this setter option sense if query is specified. OTOH add assert MongoDbOutboundGateway . doInit() collectionCallback query mutually exclusive</technical_language>

Target:
public void testWithCollectionCallbackFindOne() throws Exception { Message<String> message = MessageBuilder.withPayload("").build(); MongoDbOutboundGateway gateway = createGateway(); gateway.setEntityClass(Person.class); gateway.setCollectionNameExpression(new LiteralExpression("data")); gateway.setRequiresReply(false); gateway.setCollectionCallback(collection -> { collection.insertOne(new Document("name", "Mike")); return null; }); gateway.afterPropertiesSet(); gateway.handleRequestMessage(message); List<Person> persons = this.mongoTemplate.find(new Query(), Person.class, COLLECTION_NAME); assertEquals(5, persons.size()); assertTrue(persons.stream().anyMatch(p -> p.getName().equals("Mike"))); }
Source:
<code>private static void assertEmptyCanDoActionMessage() { <START> assertTrue(EXPECTED_EMPTY_CAN_DO_MESSAGE, canDoActionMessages.size() == 0); <END> }</code><technical_language>Optional: consider assertTrue(EXPECTED_EMPTY_CAN_DO_MESSAGE, canDoActionMessages.isEmpty())</technical_language>

Target:
private void assertEmptyCanDoActionMessage() { assertTrue(EXPECTED_EMPTY_CAN_DO_MESSAGE, canDoActionMessages.isEmpty()); }
Source:
<code>public static boolean isDyeable(Item item) { if (item.equals(Items.dye)) { return true; } <START> Block bl = Block.getBlockFromItem(item); <END> return bl != null && (bl.equals(Blocks.wool) || bl.equals(Blocks.stained_glass) || bl.equals(Blocks.stained_glass_pane) || bl.equals(Blocks.stained_hardened_clay)); }</code><technical_language>Name block? more characters hurt. :older_woman:</technical_language>

Target:
public static boolean isDyeable(Item item) { if (item.equals(Items.dye)) { return true; } Block block = Block.getBlockFromItem(item); return block != null && (block.equals(Blocks.wool) || block.equals(Blocks.stained_glass) || block.equals(Blocks.stained_glass_pane) || block.equals(Blocks.stained_hardened_clay)); }
Source:
<code><START> void setThreshold(int threshold) { <END> this.threshold = threshold; }</code><technical_language>is visible for testing : is visible set instantiators of Check class (ie platform) public annotation</technical_language>

Target:
public void setThreshold(int threshold) { this.threshold = threshold; }
Source:
<code>private static void uploadJar(File jarFile, final Path path,final FileSystem fs) throws IOException { log.info("Uploading jar to path[%s]", path); ByteStreams.copy( Files.newInputStreamSupplier(jarFile), new OutputSupplier<OutputStream>() { @Override public OutputStream getOutput() throws IOException { <START> return fs.create(path); <END> } } ); }</code><technical_language>this retry transient errors? want a copy able retry (and overwrite if prior a partial success) feasible</technical_language>

Target:
static void uploadJar(File jarFile, final Path path, final FileSystem fs) throws IOException { log.info("Uploading jar to path[%s]", path); ByteStreams.copy( Files.newInputStreamSupplier(jarFile), new OutputSupplier<OutputStream>() { @Override public OutputStream getOutput() throws IOException { return fs.create(path); } } ); }
Source:
<code>public Void invoke(File f, VirtualChannel channel) throws IOException { <START> Util.deleteRecursive(deleting(f)); <END> return null; }</code><technical_language>previous implementation of deleteRecursive call deleting(...) file in directory. new Util.deleteRecursive do this? If not, I this a problem for agent-master security</technical_language>

Target:
public Void invoke(File f, VirtualChannel channel) throws IOException { Util.deleteRecursive(fileToPath(f), path -> deleting(path.toFile())); return null; }
Source:
<code>private void loadTrace(final ITmfTrace trace) { if (fZoomThread != null) { fZoomThread.cancel(); fZoomThread = null; } if (fTrace != null) { fFiltersMap.put(fTrace, fTimeGraphViewer.getFilters()); <START> fViewContext.put(fTrace, new ViewContext(fCurrentSortColumn, fSortDirection, fTimeGraphViewer.getSelection(), fTimeGraphViewer.getExpandedElements())); <END> } fTrace = trace; TraceCompassLogUtils.traceInstant(LOGGER, Level.FINE, "TimeGraphView:LoadingTrace", "trace", trace.getName(), "viewId", getViewId()); restoreViewContext(); fEditorFile = TmfTraceManager.getInstance().getTraceEditorFile(trace); synchronized (fEntryListMap) { fEntryList = fEntryListMap.get(fTrace); if (fEntryList == null) { rebuild(); } else { setTimeBoundsAndRefresh(); } } }</code><technical_language>method getExpandedElements() is good enough for need... allow expanded state for items currently shown of parents is collapsed, currently filtered-out. (unless OK lose expanded states of entries) recursively get expanded state of entry children (collecting expanded collapsed list), restoring state determined for entry based is included in list not</technical_language>

Target:
private void loadTrace(final ITmfTrace trace) { if (fZoomThread != null) { fZoomThread.cancel(); fZoomThread = null; } if (fTrace != null) { fFiltersMap.put(fTrace, fTimeGraphViewer.getFilters()); fViewContext.put(fTrace, new ViewContext(fCurrentSortColumn, fSortDirection, fTimeGraphViewer.getSelection(), fTimeGraphViewer.getAllExpandedElements())); } fTrace = trace; TraceCompassLogUtils.traceInstant(LOGGER, Level.FINE, "TimeGraphView:LoadingTrace", "trace", trace.getName(), "viewId", getViewId()); restoreViewContext(); fEditorFile = TmfTraceManager.getInstance().getTraceEditorFile(trace); synchronized (fEntryListMap) { fEntryList = fEntryListMap.get(fTrace); if (fEntryList == null) { rebuild(); } else { setTimeBoundsAndRefresh(); } } }
Source:
<code>protected DMNExpressionEvaluator compileDecisionTable(DMNCompilerContext ctx, DMNModelImpl model, DMNBaseNode node, String dtName, DecisionTable dt) { String decisionName = ExecModelDMNEvaluatorCompiler.getDecisionTableName(dtName, dt); DTableModel dTableModel = new DTableModel(ctx.getFeelHelper(), model, dtName, decisionName, dt); String evaluatorClassName = dTableModel.getGeneratedClassName(ExecModelDMNEvaluatorCompiler.GeneratorsEnum.EVALUATOR); Optional<String> generatedClass = dmnRuleClassFile.getCompiledClass(evaluatorClassName); return generatedClass.map(gc -> { try { Class<?> evaluatorClass = getRootClassLoader().loadClass(gc); AbstractModelEvaluator evaluatorInstance = (AbstractModelEvaluator) evaluatorClass.newInstance(); String feelExpressionClassName = dTableModel.getGeneratedClassName(ExecModelDMNEvaluatorCompiler.GeneratorsEnum.FEEL_EXPRESSION); Class<?> feelExpressionClass = getRootClassLoader().loadClass(feelExpressionClassName); DTableModel execModelDTableModel = new ExecModelDTableModel(ctx.getFeelHelper(), model, dtName, decisionName, dt, feelExpressionClass); evaluatorInstance.initParameters(ctx, execModelDTableModel, node); logger.debug("Read compiled evaluator from class loader: " + evaluatorClassName); return evaluatorInstance; } catch (IllegalAccessException | InstantiationException | ClassNotFoundException e) { throw new RuntimeException("Cannot instantiate class" + e); } <START> }).orElseThrow(() -> new RuntimeException("No evaluator class find in file: " + dmnRuleClassFile)); <END> }</code><technical_language>*found</technical_language>

Target:
protected DMNExpressionEvaluator compileDecisionTable(DMNCompilerContext ctx, DMNModelImpl model, DMNBaseNode node, String dtName, DecisionTable dt) { String decisionName = ExecModelDMNEvaluatorCompiler.getDecisionTableName(dtName, dt); DTableModel dTableModel = new DTableModel(ctx.getFeelHelper(), model, dtName, decisionName, dt); String evaluatorClassName = dTableModel.getGeneratedClassName(ExecModelDMNEvaluatorCompiler.GeneratorsEnum.EVALUATOR); Optional<String> generatedClass = dmnRuleClassFile.getCompiledClass(evaluatorClassName); return generatedClass.map(gc -> { try { Class<?> evaluatorClass = getRootClassLoader().loadClass(gc); AbstractModelEvaluator evaluatorInstance = (AbstractModelEvaluator) evaluatorClass.newInstance(); String feelExpressionClassName = dTableModel.getGeneratedClassName(ExecModelDMNEvaluatorCompiler.GeneratorsEnum.FEEL_EXPRESSION); Class<?> feelExpressionClass = getRootClassLoader().loadClass(feelExpressionClassName); DTableModel execModelDTableModel = new ExecModelDTableModel(ctx.getFeelHelper(), model, dtName, decisionName, dt, feelExpressionClass); evaluatorInstance.initParameters(ctx, execModelDTableModel, node); logger.debug("Read compiled evaluator from class loader: " + evaluatorClassName); return evaluatorInstance; } catch (IllegalAccessException | InstantiationException | ClassNotFoundException e) { throw new RuntimeException("Cannot instantiate class" + e); } }).orElseThrow(() -> new RuntimeException("No evaluator class found in file: " + dmnRuleClassFile)); }
Source:
<code>public Class<?> resolveSuperClassFor(Class<?> eventClass, Class<?> superClass) { if (superClass == null) { ImplementedBy implementedBy = null; final Queue<Class<?>> queue = new ArrayDeque<Class<?>>(); queue.add(eventClass); Class<?> scannedType; while ((scannedType = queue.poll()) != null) { if ((implementedBy = scannedType.getAnnotation(ImplementedBy.class)) != null) { break; } for (Class<?> implInterfaces : scannedType.getInterfaces()) { queue.offer(implInterfaces); } } if (implementedBy != null) { return implementedBy.value(); } <START> throw new RuntimeException("Congratulations. You've attempted to create an event which doesn't have" <END> + "an @ImplementedBy annotation, on itself of any of its superinterfaces." + "If your event extends Event, then, well, something's mess up pretty badly." + "If not: *WHY* aren't you extending Event????"); } return superClass; }</code><technical_language>Need spaces strings concatenate gonna end stuff havean @ImplementedBy in output</technical_language>

Target:
public Class<?> resolveSuperClassFor(Class<?> eventClass, Class<?> superClass) { if (superClass != null) { return superClass; } ImplementedBy implementedBy = null; final Queue<Class<?>> queue = new ArrayDeque<Class<?>>(); queue.add(eventClass); Class<?> scannedType; while ((scannedType = queue.poll()) != null) { if ((implementedBy = scannedType.getAnnotation(ImplementedBy.class)) != null) { break; } for (Class<?> implInterfaces : scannedType.getInterfaces()) { queue.offer(implInterfaces); } } if (implementedBy != null) { return implementedBy.value(); } throw new RuntimeException("Congratulations. You've attempted to create an event which doesn't have " + "an @ImplementedBy annotation, on itself of any of its superinterfaces. " + "If your event extends Event, then, well, something's mess up pretty badly. " + "If not: *WHY* aren't you extending Event????"); }
Source:
<code>protected void updateDataProvider(List<Job> items) { <START> List<Job> firstRowData = items.isEmpty() ? Arrays.asList(emptyJob) : Arrays.asList(items.get(0)); <END> super.updateDataProvider(firstRowData); }</code><technical_language>array static well</technical_language>

Target:
protected void updateDataProvider(List<Job> items) { List<Job> firstRowData = items.isEmpty() ? emptyJobList : Arrays.asList(items.get(0)); super.updateDataProvider(firstRowData); }
Source:
<code>public boolean execute() throws Exception { String archivePathArg = requiredArgument(0, Messages.i18n.format("InvalidArgMsg.EntryPath")); String subCommandArg = requiredArgument(1, Messages.i18n.format("UpdateEntry.InvalidArgMsg.SubCommand")); QName varName = new QName("archive", "active-archive"); SrampArchive archive = (SrampArchive) getContext().getVariable(varName); if (archive == null) { print(Messages.i18n.format("NO_ARCHIVE_OPEN")); return false; <START> } else if (archivePathArg.endsWith(File.separator)) { <END> print(Messages.i18n.format("Archive.Path.Arg.should.not.contain.slash.end")); return false; } else { if (!archive.containsEntry(archivePathArg)) { throw new InvalidCommandArgumentException(0, Messages.i18n.format("UpdateEntry.EntryNotFound", archivePathArg)); } if ("setContent".equals(subCommandArg)) { executeSetContent(archive, archivePathArg, getContext()); } if ("setProperty".equals(subCommandArg)) { executeSetProperty(archive, archivePathArg, getContext()); } if ("setRelationship".equals(subCommandArg)) { executeSetRelationship(archive, archivePathArg, getContext()); } } return true; }</code><technical_language>shared 'validateArchivePath' method well</technical_language>

Target:
public boolean execute() throws Exception { super.initialize(); String archivePathArg = requiredArgument(0, Messages.i18n.format("InvalidArgMsg.EntryPath")); String subCommandArg = requiredArgument(1, Messages.i18n.format("UpdateEntry.InvalidArgMsg.SubCommand")); if (!validate(archivePathArg)) { return false; } else { if ("setContent".equals(subCommandArg)) { executeSetContent(archive, archivePathArg, getContext()); } if ("setProperty".equals(subCommandArg)) { executeSetProperty(archive, archivePathArg, getContext()); } if ("setRelationship".equals(subCommandArg)) { executeSetRelationship(archive, archivePathArg, getContext()); } } return true; }
Source:
<code>public void addFormatters(FormatterRegistry registry) { registry.addConverter(sortConverter()); <START> registry.addConverter(query()); <END> }</code><technical_language>Consistency: queryConverter() instead of query()</technical_language>

Target:
public void addFormatters(FormatterRegistry registry) { registry.addConverter(sortConverter()); registry.addConverter(queryConverter()); }
Source:
<code>public KijiTable retain() { <START> Preconditions.checkState(mRetainCount.incrementAndGet() >= 0, <END> "Cannot retain a closed KijiTable."); return this; }</code><technical_language>This be: > 1</technical_language>

Target:
public KijiTable retain() { Preconditions.checkState(mRetainCount.getAndIncrement() >= 0, String.format( "Cannot retain a closed resource: retain counter is %s.", mRetainCount.get())); return this; }
Source:
<code>public static <R> R parsePemContent(CodePointIterator pemContent, BiFunction<String, ByteIterator, R> contentFunction) throws IllegalArgumentException { Assert.checkNotNullParam("pemContent", pemContent); Assert.checkNotNullParam("contentFunction", contentFunction); <START> pemContent = pemContent.skip(Character::isWhitespace).skipCrLf(); <END> if (! pemContent.limitedTo(10).contentEquals("-----BEGIN")) { throw log.malformedPemContent(pemContent.offset()); } String type = pemContent.delimitedBy('-').drainToString().trim(); final Matcher matcher = VALID_LABEL.matcher(type); if (matcher.find()) { throw log.malformedPemContent(matcher.start() + 10); } if (! pemContent.limitedTo(5).contentEquals("-----")) { throw log.malformedPemContent(pemContent.offset()); } final ByteIterator byteIterator = pemContent.delimitedBy('-').base64Decode(); final R result = contentFunction.apply(type, byteIterator); if (! pemContent.limitedTo(8).contentEquals("-----END")) { throw log.malformedPemContent(pemContent.offset()); } if (! pemContent.limitedTo(type.length()).contentEquals(type)) { throw log.malformedPemContent(pemContent.offset()); } if (! pemContent.limitedTo(5).contentEquals("-----")) { throw log.malformedPemContent(pemContent.offset()); } return result; }</code><technical_language>This in allows invalid input accepted</technical_language>

Target:
public static <R> R parsePemContent(CodePointIterator pemContent, BiFunction<String, ByteIterator, R> contentFunction) throws IllegalArgumentException { Assert.checkNotNullParam("pemContent", pemContent); Assert.checkNotNullParam("contentFunction", contentFunction); while(true) { if (! pemContent.hasNext()) return null; int cp = pemContent.next(); if (cp == '-') break; if (! Character.isWhitespace(cp)) { throw log.malformedPemContent(pemContent.offset()); } } if (! pemContent.limitedTo(10).contentEquals("----BEGIN ")) { throw log.malformedPemContent(pemContent.offset()); } String type = pemContent.delimitedBy('-').drainToString(); final Matcher matcher = VALID_LABEL.matcher(type); if (matcher.find()) { throw log.malformedPemContent(matcher.start() + 11); } if (! pemContent.limitedTo(5).contentEquals("-----")) { throw log.malformedPemContent(pemContent.offset()); } CodePointIterator delimitedIterator = pemContent.delimitedBy('-').skip(Character::isWhitespace).skipCrLf(); final ByteIterator byteIterator = delimitedIterator.base64Decode(); final R result = contentFunction.apply(type, byteIterator); delimitedIterator.skipAll(); if (! pemContent.limitedTo(9).contentEquals("-----END ")) { throw log.malformedPemContent(pemContent.offset()); } if (! pemContent.limitedTo(type.length()).contentEquals(type)) { throw log.malformedPemContent(pemContent.offset()); } if (! pemContent.limitedTo(5).contentEquals("-----")) { throw log.malformedPemContent(pemContent.offset()); } return result; }
Source:
<code>public void encode(Object object, Type bodyType, RequestTemplate template) { try { JavaType javaType = mapper.getTypeFactory().constructType(bodyType); <START> template.body(mapper.writerFor(javaType).writeValueAsBytes(object), StandardCharsets.UTF_8); <END> } catch (JsonProcessingException e) { throw new EncodeException(e.getMessage(), e); } }</code><technical_language>change I is Util.UTF_8 constant for consistency</technical_language>

Target:
public void encode(Object object, Type bodyType, RequestTemplate template) { try { JavaType javaType = mapper.getTypeFactory().constructType(bodyType); template.body(mapper.writerFor(javaType).writeValueAsBytes(object), Util.UTF_8); } catch (JsonProcessingException e) { throw new EncodeException(e.getMessage(), e); } }
Source:
<code>public Linkifier(GitilesUrls urls, Config config) { this.urls = checkNotNull(urls, "urls"); List<CommentLinkInfo> list = new ArrayList<>(); list.add(new CommentLinkInfo(HTTP_URL_PATTERN, "$0")); Set<String> subsections = config.getSubsections(COMMENTLINK); List<String> patterns = new ArrayList<>(); patterns.add(HTTP_URL_PATTERN.pattern()); patterns.add(CHANGE_ID_PATTERN.pattern()); for (String subsection : subsections) { String match = config.getString("commentlink", subsection, "match"); String link = config.getString("commentlink", subsection, "link"); String html = config.getString("commentlink", subsection, "html"); <START> if (html != null) System.out.println( "Beware: html in commentlinks is unsupported in gitiles; " + "Did you copy it from a gerrit config?"); <END> checkArgument(!Strings.isNullOrEmpty(match), "invalid commentlink.%s.match", subsection); Pattern compiledPattern = Pattern.compile(match); list.add(new CommentLinkInfo(compiledPattern, link)); patterns.add(match); } this.commentLinks = Collections.unmodifiableList(list); allPattern = Pattern.compile(Joiner.on('|').join(patterns)); }</code><technical_language>Gitiles slf4j for logging. import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ... { private static final Logger log = LoggerFactory.getLogger(Linkifier.class); ... log.warn(...)</technical_language>

Target:
public Linkifier(GitilesUrls urls, Config config) { this.urls = checkNotNull(urls, "urls"); List<CommentLinkInfo> list = new ArrayList<>(); list.add(new CommentLinkInfo(HTTP_URL_PATTERN, "$0")); Set<String> subsections = config.getSubsections(COMMENTLINK); List<String> patterns = new ArrayList<>(); patterns.add(HTTP_URL_PATTERN.pattern()); patterns.add(CHANGE_ID_PATTERN.pattern()); for (String subsection : subsections) { String match = config.getString("commentlink", subsection, "match"); String link = config.getString("commentlink", subsection, "link"); String html = config.getString("commentlink", subsection, "html"); if (html != null) log.warn( "Beware: html in commentlinks is unsupported in gitiles; " + "Did you copy it from a gerrit config?"); checkArgument(!Strings.isNullOrEmpty(match), "invalid commentlink.%s.match", subsection); Pattern compiledPattern = Pattern.compile(match); list.add(new CommentLinkInfo(compiledPattern, link)); patterns.add(match); } this.commentLinks = Collections.unmodifiableList(list); allPattern = Pattern.compile(Joiner.on('|').join(patterns)); }