auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static File writeToTempFile(Iterator<Tweet> iterator) throws IOException { File srcFile = File.createTempFile("tweets", "txt"); srcFile.deleteOnExit(); <START> FileWriter fw = new FileWriter(srcFile); <END> try { BufferedWriter bw = new BufferedWriter(fw); try { while (iterator.hasNext()) { bw.write(GSON.toJson(iterator.next())); bw.newLine(); } } finally { bw.close(); } } finally { fw.close(); } return srcFile; }</code><technical_language>simplified BufferedWriter writer = Files.newWriter(srcFile, Charsets.UTF_8);</technical_language>

Target:
public static File writeToTempFile(Iterator<Tweet> iterator) throws IOException { File srcFile = File.createTempFile("tweets", "txt"); srcFile.deleteOnExit(); BufferedWriter writer = Files.newWriter(srcFile, Charsets.UTF_8); try { while (iterator.hasNext()) { writer.write(GSON.toJson(iterator.next())); writer.newLine(); } } finally { writer.close(); } return srcFile; }
Source:
<code>public Long getUuid() { <START> return new Long(0); <END> }</code><technical_language>'L'</technical_language>

Target:
public Long getUuid() { return 0L; }
Source:
<code>@Override public void parseArguments(CommandArgIterator argIter) { String s = argIter.nextArg("New cluster state not found."); try { state = ClusterState.valueOf(s.toUpperCase()); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("Can't parse new cluster state. State: " + s, e); } if (argIter.hasNextArg()) { String arg = argIter.peekNextArg(); <START> if ("--force".equalsIgnoreCase(arg)) { <END> force = true; argIter.nextArg(""); } } }</code><technical_language>Missed break line</technical_language>

Target:
@Override public void parseArguments(CommandArgIterator argIter) { String s = argIter.nextArg("New cluster state not found."); try { state = ClusterState.valueOf(s.toUpperCase()); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("Can't parse new cluster state. State: " + s, e); } if (argIter.hasNextArg()) { String arg = argIter.peekNextArg(); if (FORCE_COMMAND.equalsIgnoreCase(arg)) { force = true; argIter.nextArg(""); } } }
Source:
<code>public static Archive<?> createTestArchive() { Archive<?> beanValidationJarWithMissingProvider = IntegrationTestUtil.createCustomBeanValidationProviderJar(); Node providerClass = beanValidationJarWithMissingProvider.delete( "org/hibernate/validator/integration/util/MyValidationProvider.class" ); if ( providerClass == null ) { fail( "MyValidationProvider was not as expected in the custom jar" ); } return ShrinkWrap.create( WebArchive.class, WAR_FILE_NAME ) .addClasses( MyValidatorCreator.class ) .addAsLibraries( IntegrationTestUtil.bundleHibernateValidatorWithDependencies( true ) ) .addAsLibrary( beanValidationJarWithMissingProvider ) .addAsResource( "log4j.properties" ) <START> .addAsWebInfResource( EmptyAsset.INSTANCE, ArchivePaths.create( "beans.xml" ) ) <END> .addAsWebInfResource( "jboss-deployment-structure.xml" ); }</code><technical_language>wondering ArchivePaths.create in other deployments addAsWebInfResource( EmptyAsset.INSTANCE, "beans.xml" )</technical_language>

Target:
public static Archive<?> createTestArchive() { Archive<?> beanValidationJarWithMissingProvider = IntegrationTestUtil.createCustomBeanValidationProviderJar(); Node providerClass = beanValidationJarWithMissingProvider.delete( "org/hibernate/validator/integration/util/MyValidationProvider.class" ); if ( providerClass == null ) { fail( "MyValidationProvider was not as expected in the custom jar" ); } return ShrinkWrap.create( WebArchive.class, WAR_FILE_NAME ) .addAsLibraries( IntegrationTestUtil.bundleHibernateValidatorWithDependencies( true ) ) .addAsLibrary( beanValidationJarWithMissingProvider ) .addAsResource( "log4j.properties" ) .addAsWebInfResource( "jboss-deployment-structure.xml" ); }
Source:
<code>public ConnectorSplitSource getSplits(ConnectorTransactionHandle transactionHandle, ConnectorSession session, ConnectorTableLayoutHandle layout, SplitSchedulingStrategy splitSchedulingStrategy) { ElasticsearchTableLayoutHandle layoutHandle = (ElasticsearchTableLayoutHandle) layout; ElasticsearchTableHandle tableHandle = layoutHandle.getTable(); ElasticsearchTableDescription table = client.getTable(tableHandle.getSchemaName(), tableHandle.getTableName()); checkState(table != null, "Table %s no longer exists", tableHandle.toString()); List<String> indices = client.getIndices(table); ImmutableList.Builder<ConnectorSplit> splits = ImmutableList.builder(); for (String index : indices) { ClusterSearchShardsResponse response = client.getSearchShards(index, table); DiscoveryNode[] nodes = response.getNodes(); for (ClusterSearchShardsGroup group : response.getGroups()) { int nodeIndex = group.getShardId().getId() % nodes.length; <START> ElasticsearchSplit split = new ElasticsearchSplit(table, index, group.getShardId().getId(), nodes[nodeIndex].getHostName(), nodes[nodeIndex].getAddress().getPort(), layoutHandle.getTupleDomain()); <END> splits.add(split); } } return new FixedSplitSource(splits.build()); }</code><technical_language>This line is long: ElasticsearchSplit split = new ElasticsearchSplit(table, index, group.getShardId().getId(), nodes[nodeIndex].getHostName(), nodes[nodeIndex].getAddress().getPort(), layoutHandle.getTupleDomain());</technical_language>

Target:
public ConnectorSplitSource getSplits(ConnectorTransactionHandle transactionHandle, ConnectorSession session, ConnectorTableLayoutHandle layout, SplitSchedulingStrategy splitSchedulingStrategy) { ElasticsearchTableLayoutHandle layoutHandle = (ElasticsearchTableLayoutHandle) layout; ElasticsearchTableHandle tableHandle = layoutHandle.getTable(); ElasticsearchTableDescription table = client.getTable(tableHandle.getSchemaName(), tableHandle.getTableName()); verify(table != null, "Table no longer exists: %s", tableHandle.toString()); List<String> indices = client.getIndices(table); ImmutableList.Builder<ConnectorSplit> splits = ImmutableList.builder(); for (String index : indices) { ClusterSearchShardsResponse response = client.getSearchShards(index, table); DiscoveryNode[] nodes = response.getNodes(); for (ClusterSearchShardsGroup group : response.getGroups()) { int nodeIndex = group.getShardId().getId() % nodes.length; ElasticsearchSplit split = new ElasticsearchSplit(table, index, group.getShardId().getId(), nodes[nodeIndex].getHostName(), nodes[nodeIndex].getAddress().getPort(), layoutHandle.getTupleDomain()); splits.add(split); } } return new FixedSplitSource(splits.build()); }
Source:
<code>private String validateModel(String name, InputStream inputStream) throws IOException { Resource resource = resourceSet.createResource(URI.createURI("tmp_" + name)); try { resource.load(inputStream, Collections.EMPTY_MAP); StringBuilder criticalErrors = new StringBuilder(); StringBuilder warnings = new StringBuilder(); if (resource != null && !resource.getContents().isEmpty()) { for (Diagnostic diagnostic : resource.getErrors()) { criticalErrors.append(MessageFormat.format("[{0},{1}]: {2}\n", diagnostic.getLine(), diagnostic.getColumn(), diagnostic.getMessage())); } if (criticalErrors.length() > 0) { return criticalErrors.toString(); } org.eclipse.emf.common.util.Diagnostic diagnostic = Diagnostician.INSTANCE .validate(resource.getContents().get(0)); for (org.eclipse.emf.common.util.Diagnostic d : diagnostic.getChildren()) { warnings.append(d.getMessage()); warnings.append("\n"); } if (warnings.length() > 0) { <START> logger.warn("Validation error(s) in configuration model '{}':\n {}", name, warnings.toString()); <END> } } } finally { resourceSet.getResources().remove(resource); } return null; }</code><technical_language>toString() called automatically logger framework? some difference if call yourself. If call toString yourself, is executed time of log level (so, if current logger is set error)</technical_language>

Target:
private String validateModel(String name, InputStream inputStream) throws IOException { Resource resource = resourceSet.createResource(URI.createURI("tmp_" + name)); try { resource.load(inputStream, Collections.EMPTY_MAP); StringBuilder criticalErrors = new StringBuilder(); StringBuilder warnings = new StringBuilder(); if (resource != null && !resource.getContents().isEmpty()) { for (Diagnostic diagnostic : resource.getErrors()) { criticalErrors.append(MessageFormat.format("[{0},{1}]: {2}\n", diagnostic.getLine(), diagnostic.getColumn(), diagnostic.getMessage())); } if (criticalErrors.length() > 0) { return criticalErrors.toString(); } org.eclipse.emf.common.util.Diagnostic diagnostic = Diagnostician.INSTANCE .validate(resource.getContents().get(0)); for (org.eclipse.emf.common.util.Diagnostic d : diagnostic.getChildren()) { warnings.append(d.getMessage()); warnings.append("\n"); } if (warnings.length() > 0) { logger.warn("Validation error(s) in configuration model '{}':\n {}", name, warnings); } } } finally { resourceSet.getResources().remove(resource); } return null; }
Source:
<code>void insertVariables(final int id, final int actionId, Map<String, String> stateVariables, Map<String, String> originalStateVariables) { Map<String, String> changedStateVariables = changedStateVariables(stateVariables, originalStateVariables); if (changedStateVariables.isEmpty()) { return; } if (sqlVariants.useBatchUpdate()) { <START> final Iterator<Entry<String, String>> variables = changedStateVariables.entrySet().iterator(); <END> int[] updateStatus = jdbc.batchUpdate(insertWorkflowInstanceStateSql() + " values (?,?,?,?)", new AbstractInterruptibleBatchPreparedStatementSetter() { @Override protected boolean setValuesIfAvailable(PreparedStatement ps, int i) throws SQLException { if (!variables.hasNext()) { return false; } Entry<String, String> var = variables.next(); ps.setInt(1, id); ps.setInt(2, actionId); ps.setString(3, var.getKey()); ps.setString(4, var.getValue()); return true; } }); int updatedRows = 0; boolean unknownResults = false; for (int i = 0; i < updateStatus.length; ++i) { if (updateStatus[i] == Statement.SUCCESS_NO_INFO) { unknownResults = true; continue; } if (updateStatus[i] == Statement.EXECUTE_FAILED) { throw new IllegalStateException("Failed to insert/update state variables"); } updatedRows += updateStatus[i]; } if (!unknownResults && updatedRows != changedStateVariables.size()) { throw new IllegalStateException("Failed to insert/update state variables, expected update count " + changedStateVariables.size() + ", actual " + updatedRows); } } else { for (Entry<String, String> entry : changedStateVariables.entrySet()) { int updated = jdbc.update(insertWorkflowInstanceStateSql() + " values (?,?,?,?)", id, actionId, entry.getKey(), entry.getValue()); if (updated != 1) { throw new IllegalStateException("Failed to insert state variable " + entry.getKey()); } } } }</code><technical_language>Refactor code for batch-update non-batch-update separate methods</technical_language>

Target:
void insertVariables(final int id, final int actionId, Map<String, String> stateVariables, Map<String, String> originalStateVariables) { Map<String, String> changedStateVariables = changedStateVariables(stateVariables, originalStateVariables); if (changedStateVariables.isEmpty()) { return; } if (sqlVariants.useBatchUpdate()) { insertVariablesWithBatchUpdate(id, actionId, changedStateVariables); } else { insertVariablesWithMultipleUpdates(id, actionId, changedStateVariables); } }
Source:
<code>public static <T> T removeLast(List<T> self) { if (self.isEmpty()) { <START> throw new NoSuchElementException("Cannot pop() an empty List"); <END> } return self.remove(self.size() - 1); }</code><technical_language>pop() -> removeLast()</technical_language>

Target:
public static <T> T removeLast(List<T> self) { if (self.isEmpty()) { throw new NoSuchElementException("Cannot removeLast() an empty List"); } return self.remove(self.size() - 1); }
Source:
<code>protected String[] getTopologyConf(PackingPlan packing) { config = Config.newBuilder() .putAll(config) .put(Key.TOPOLOGY_BINARY_FILE, FileUtils.getBaseName(Context.topologyBinaryFile(config))) .build(); ObjectMapper mapper = new ObjectMapper(); PackingPlan updatedPackingPlan = packing.cloneWithHomogeneousScheduledResource(); SchedulerUtils.persistUpdatedPackingPlan(Runtime.topologyName(runtime), updatedPackingPlan, Runtime.schedulerStateManagerAdaptor(runtime)); Resource containerResource = updatedPackingPlan.getContainers() <START> .iterator().next().getRequiredResource(); <END> String[] deploymentConfs = new String[Ints.checkedCast(Runtime.numContainers(runtime))]; for (int i = 0; i < Runtime.numContainers(runtime); i++) { ObjectNode instance = mapper.createObjectNode(); instance.put(KubernetesConstants.API_VERSION, KubernetesConstants.API_VERSION_1); instance.put(KubernetesConstants.API_KIND, KubernetesConstants.API_POD); instance.set(KubernetesConstants.API_METADATA, getMetadata(mapper, i)); instance.set(KubernetesConstants.API_SPEC, getContainerSpec(mapper, i, containerResource)); deploymentConfs[i] = instance.toString(); } return deploymentConfs; }</code><technical_language>getScheduledResource() request maximal container resource. Basically, Required Resource is resource generated packing plan, Scheduled Resource is maximal resource. For details, please check #1850</technical_language>

Target:
protected String[] getTopologyConf(PackingPlan packing) { config = Config.newBuilder() .putAll(config) .put(Key.TOPOLOGY_BINARY_FILE, FileUtils.getBaseName(Context.topologyBinaryFile(config))) .build(); ObjectMapper mapper = new ObjectMapper(); PackingPlan updatedPackingPlan = packing.cloneWithHomogeneousScheduledResource(); SchedulerUtils.persistUpdatedPackingPlan(Runtime.topologyName(runtime), updatedPackingPlan, Runtime.schedulerStateManagerAdaptor(runtime)); Resource containerResource = updatedPackingPlan.getContainers() .iterator().next().getScheduledResource().get(); String[] deploymentConfs = new String[Ints.checkedCast(Runtime.numContainers(runtime))]; for (int i = 0; i < Runtime.numContainers(runtime); i++) { ObjectNode instance = mapper.createObjectNode(); instance.put(KubernetesConstants.API_VERSION, KubernetesConstants.API_VERSION_1); instance.put(KubernetesConstants.API_KIND, KubernetesConstants.API_POD); instance.set(KubernetesConstants.API_METADATA, getMetadata(mapper, i)); instance.set(KubernetesConstants.API_SPEC, getContainerSpec(mapper, i, containerResource)); deploymentConfs[i] = instance.toString(); } return deploymentConfs; }
Source:
<code>public FileChooserDialog(Skin skin, String selectString, String cancelString, FileChooserListener fileChooserListener) { super(skin); this.fileChooserListener = fileChooserListener; root(files = new FilesListWidget(skin)); button(selectString).addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { FileChooserDialog.this.fileChooserListener.fileChosen(files .getSelectedFile().path(), FileChooserListener.Result.SUCCESS); } }); button(cancelString).addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { FileChooserDialog.this.fileChooserListener.fileChosen(null, <START> null); <END> } }); }</code><technical_language>This a Result.CANCELLED</technical_language>

Target:
public FileChooserDialog(Skin skin, String selectString, String cancelString, FileChooserListener fileChooserListener) { super(skin); this.fileChooserListener = fileChooserListener; root(files = new FilesListWidget(skin)); button(selectString).addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { FileChooserDialog.this.fileChooserListener.fileChosen(files .getSelectedFile().path(), FileChooserListener.Result.SUCCESS); } }); button(cancelString).addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { FileChooserDialog.this.fileChooserListener.fileChosen(null, FileChooserListener.Result.CANCELLED); } }); }
Source:
<code>public <T> void putList(final String dataType, final List<Long> ids, final List<T> values) { if (ids.size() != values.size()) { throw new RuntimeException("Different list sizes: ids " + ids.size() + ", values " + values.size()); } final Map<Long, T> idValueMap = new HashMap<>(); for (int index = 0; index < ids.size(); index++) { if (!router.isLocal(ids.get(index))) { <START> LOG.log(Level.INFO, "This id is not local: {0}", ids.get(index)); <END> } else { idValueMap.put(ids.get(index), values.get(index)); } } readWriteLock.writeLock().lock(); try { if (!dataMap.containsKey(dataType)) { dataMap.put(dataType, new TreeMap<Long, Object>()); } final Map<Long, Object> innerMap = dataMap.get(dataType); innerMap.putAll(idValueMap); } finally { readWriteLock.writeLock().unlock(); } }</code><technical_language>This a WARNING, if Exception, user needs put succeeded not</technical_language>

Target:
public <T> void putList(final String dataType, final List<Long> ids, final List<T> values) { if (ids.size() != values.size()) { throw new RuntimeException("Different list sizes: ids " + ids.size() + ", values " + values.size()); } final Map<Long, T> idValueMap = new HashMap<>(); for (int index = 0; index < ids.size(); index++) { if (!router.isLocal(ids.get(index))) { LOG.log(Level.WARNING, "This id is not local: {0}", ids.get(index)); } else { idValueMap.put(ids.get(index), values.get(index)); } } readWriteLock.writeLock().lock(); try { if (!dataMap.containsKey(dataType)) { dataMap.put(dataType, new TreeMap<Long, Object>()); } final Map<Long, Object> innerMap = dataMap.get(dataType); innerMap.putAll(idValueMap); } finally { readWriteLock.writeLock().unlock(); } }
Source:
<code><START> public <B> Eval<B> flatMap(final F<A, Eval<B>> f) { <END> return bind(f); }</code><technical_language>final</technical_language>

Target:
public final <B> Eval<B> flatMap(final F<A, Eval<B>> f) { return bind(f); }
Source:
<code><START> public void executeTransactionAsync_cancelTransactionInside() throws Throwable { <END> final TestHelper.TestLogger testLogger = new TestHelper.TestLogger(LogLevel.DEBUG); RealmLog.add(testLogger); final Realm realm = looperThread.realm; assertEquals(0, realm.where(Owner.class).count()); realm.executeTransactionAsync(new Realm.Transaction() { @Override public void execute(Realm realm) { Owner owner = realm.createObject(Owner.class); owner.setName("Owner"); realm.cancelTransaction(); } }, new Realm.Transaction.OnSuccess() { @Override public void onSuccess() { fail("Should not reach success if runtime exception is thrown in callback."); } }, new Realm.Transaction.OnError() { @Override public void onError(Throwable error) { assertTrue(testLogger.message.contains( "Exception has been throw: Can't commit a non-existing write transaction")); assertTrue(error instanceof IllegalStateException); RealmLog.remove(testLogger); looperThread.testComplete(); } }); }</code><technical_language>This change right. hiding user specific exception. This test case created a user issue if I remember correctly</technical_language>

Target:
public void executeTransactionAsync_cancelTransactionInside() throws Throwable { final TestHelper.TestLogger testLogger = new TestHelper.TestLogger(LogLevel.DEBUG); RealmLog.add(testLogger); final Realm realm = looperThread.realm; assertEquals(0, realm.where(Owner.class).count()); realm.executeTransactionAsync(new Realm.Transaction() { @Override public void execute(Realm realm) { Owner owner = realm.createObject(Owner.class); owner.setName("Owner"); realm.cancelTransaction(); } }, new Realm.Transaction.OnSuccess() { @Override public void onSuccess() { fail("Should not reach success if runtime exception is thrown in callback."); } }, new Realm.Transaction.OnError() { @Override public void onError(Throwable error) { assertTrue(testLogger.message.contains( "Exception has been thrown: Can't commit a non-existing write transaction")); assertTrue(error instanceof IllegalStateException); RealmLog.remove(testLogger); looperThread.testComplete(); } }); }
Source:
<code>public void validate(Object object, Errors errors) { if(object == null){ throw new IllegalArgumentException("The object parameter should not be null"); } if(!(object instanceof Condition)){ throw new IllegalArgumentException("The object parameter should be of type " + Condition.class); } Condition condition = (Condition) object; if(condition.getCondition() == null){ <START> throw new APIException("The condition parameter is required"); <END> } if(condition.getClinicalStatus() == null){ throw new APIException("The clinical status is required"); } }</code><technical_language>reject field throw exception for proper handling of external code</technical_language>

Target:
public void validate(Object object, Errors errors) { if(object == null){ throw new IllegalArgumentException("The object parameter should not be null"); } if(!(object instanceof Condition)){ throw new IllegalArgumentException("The object parameter should be of type " + Condition.class); } Condition condition = (Condition) object; if(condition.getCondition() == null){ errors.rejectValue("condition", "Condition.conditionShouldNotBeNull", "The condition is required"); } if(condition.getClinicalStatus() == null){ errors.rejectValue("clinicalStatus", "Condition.clinicalStatusShouldNotBeNull", "The clinical status is required"); } }
Source:
<code>private void dropStrict() throws IOException { if ( index != null ) { index.close(); index = null; } <START> fileSystem.deleteFile( storeFile ); <END> }</code><technical_language>fileSystem.deleteFileOrThrow underneath</technical_language>

Target:
private void dropStrict() throws IOException { if ( index != null ) { index.close(); index = null; } fileSystem.deleteFileOrThrow( storeFile ); }
Source:
<code>public String toString() { <START> return "[" + a.toString() + ", " + b.toString() + "]"; <END> }</code><technical_language>this explode if is a null still... This is a weird case, return "[" + a+ ", " + b + "]"; fine. I thought before, special syntactic sugar checks nulls in string concatenations</technical_language>

Target:
public String toString() { return "[" + a + ", " + b + "]"; }
Source:
<code><START> private void skip(long timestamp) { <END> try { long offset = frameSize * (timestamp / period / 1000000L); byte[] skip = new byte[(int) offset]; int bytesRead = 0; buff.position(0); buff.limit(skip.length); while (bytesRead < skip.length && buff.remaining() > 0) { int len = rbChannel.read(buff.get(skip)); if (len == -1) return; totalRead += len; bytesRead += len; } } catch (IOException e) { logger.error(e); } }</code><technical_language>reuse this <LINK_0></technical_language>

Target:
private void skip(long timestamp) { try { long offset = frameSize * (timestamp / period / 1000000L); byte[] skip = new byte[(int) offset]; int buffSize = header.length + skip.length; if (buff.capacity()< skip.length){ ByteBuffer newBuff = ByteBuffer.allocate(buffSize); newBuff.put((ByteBuffer) buff.flip()); buff = newBuff; } buff.position(header.length); int bytesRead = rbChannel.read(buff); while (bytesRead < skip.length && buff.remaining() > 0) { int len = rbChannel.read(ByteBuffer.wrap(skip, bytesRead , skip.length - bytesRead)); if (len == -1) { return; } totalRead += len; bytesRead += len; } } catch (IOException e) { logger.error(e); } }
Source:
<code>public static Cipher getInstance( Properties props, CipherTransformation transformation) throws IOException { try { List<Class<? extends Cipher>> klasses = getCipherClasses(props); Cipher cipher = null; if (klasses != null) { for (Class<? extends Cipher> klass : klasses) { try { cipher = ReflectionUtils.newInstance(klass, props, transformation); if(cipher != null) { LOG.debug("Using cipher for transformation {}.", klass.getName(), transformation.getName()); break; } } catch (Exception e) { <START> LOG.debug("Cipher is not available or transformation is not supported.", <END> klass.getName(), transformation.getName()); } } } return (cipher == null) ? new JceCipher(props, transformation) : cipher; } catch (GeneralSecurityException e) { throw new IOException(e); } }</code><technical_language>LOG.error</technical_language>

Target:
public static Cipher getInstance( Properties props, CipherTransformation transformation) throws IOException { try { List<Class<? extends Cipher>> klasses = getCipherClasses(props); Cipher cipher = null; if (klasses != null) { for (Class<? extends Cipher> klass : klasses) { try { cipher = ReflectionUtils.newInstance(klass, props, transformation); if(cipher != null) { LOG.debug("Using cipher for transformation {}.", klass.getName(), transformation.getName()); break; } } catch (Exception e) { LOG.error("Cipher is not available or transformation is not supported.", klass.getName(), transformation.getName()); } } } return (cipher == null) ? new JceCipher(props, transformation) : cipher; } catch (GeneralSecurityException e) { throw new IOException(e); } }
Source:
<code>public static boolean validQuestionGroups(final Survey survey){ <START> return survey.getQuestionGroupMap().values().stream().filter(i -> i.getRepeatable().booleanValue()).collect(Collectors.toList()).size() == 0; <END> }</code><technical_language>do need explicit boolean primitive? .... i.getRepeatable() trick</technical_language>

Target:
public static boolean validQuestionGroups(final Survey survey) { return survey.getQuestionGroupMap().values().stream().filter(i -> i.getRepeatable()).collect(Collectors.toList()).size() == 0; }
Source:
<code>public void execute() throws Exception { VirtualFile root = VFS.getChild(this.env.getJbossHome()); List<VirtualFile> matches = root.getChildrenRecursively(Filters.and(this.filter, this.blacklistFilter)); if(sorter != null){ Collections.sort(matches, sorter); } Limiter limiter = new Limiter(limit); Iterator<VirtualFile> iter = matches.iterator(); while(iter.hasNext() && !limiter.isDone()) { VirtualFile f = iter.next(); try (InputStream stream = limiter.limit(f)) { InputStream modifiedStream = stream; for (Sanitizer sanitizer : this.sanitizers) { if (sanitizer.accepts(f)) { <START> modifiedStream = sanitizer.sanitize(stream); <END> } } this.env.getZip().add(f, modifiedStream); } } }</code><technical_language>this chain, i.e. modifiedStream = sanitizer.sanitize(modifiedStream);</technical_language>

Target:
public void execute() throws Exception { VirtualFile root = VFS.getChild(this.env.getJbossHome()); List<VirtualFile> matches = root.getChildrenRecursively(Filters.and(this.filter, this.blacklistFilter)); if(sorter != null){ Collections.sort(matches, sorter); } Limiter limiter = new Limiter(limit); Iterator<VirtualFile> iter = matches.iterator(); while(iter.hasNext() && !limiter.isDone()) { VirtualFile f = iter.next(); try (InputStream stream = limiter.limit(f)) { InputStream modifiedStream = stream; for (Sanitizer sanitizer : this.sanitizers) { if (sanitizer.accepts(f)) { modifiedStream = sanitizer.sanitize(modifiedStream); } } this.env.getZip().add(f, modifiedStream); } } }
Source:
<code>public Result upload(Long folderId) { MultipartFormData body = request().body().asMultipartFormData(); Http.MultipartFormData.FilePart upload = body.getFile("file"); Folder folder = folderManager.findById(folderId); if (!Secured.viewFolder(folder)) { return forbidden("Dazu hast du keine Berechtigung"); } if (upload != null) { if (mediaManager.byteAsMB(upload.getFile().length()) > MAX_FILESIZE) { return status(REQUEST_ENTITY_TOO_LARGE, "Es sind maximal "+ MAX_FILESIZE + " MByte pro Datei möglich."); } if (mediaManager.existsInFolder(upload.getFilename(), folder)) { return status(CONFLICT, "Eine Datei mit diesem Namen existiert bereits."); } Media med = new Media(); med.title = upload.getFilename(); med.mimetype = upload.getContentType(); med.fileName = upload.getFilename(); med.file = upload.getFile(); med.owner = Component.currentAccount(); med.folder = folder; med.temporarySender = Component.currentAccount(); try { mediaManager.create(med); NotificationService.getInstance().createNotification(med, Media.MEDIA_NEW_MEDIA); } catch (Exception e) { return internalServerError("Während des Uploads ist etwas schiefgegangen!"); } Folder rootFolder = FolderManager.findRoot(folder); List<Media> mediaSet = folder.files; List<Folder> folderList = folder.folders; <START> return created(list.render(mediaSet, folderList, rootFolder.id)); <END> } else { return internalServerError("Es konnte keine Datei gefunden werden!"); } }</code><technical_language>ah, this breaks file upload for posts i guess depricated mediaList call</technical_language>

Target:
public Result upload(Long folderId) { MultipartFormData body = request().body().asMultipartFormData(); Http.MultipartFormData.FilePart upload = body.getFile("file"); Folder folder = folderManager.findById(folderId); if (!Secured.viewFolder(folder)) { return forbidden("Dazu hast du keine Berechtigung"); } if (upload != null) { if (mediaManager.byteAsMB(upload.getFile().length()) > MAX_FILESIZE) { return status(REQUEST_ENTITY_TOO_LARGE, "Es sind maximal "+ MAX_FILESIZE + " MByte pro Datei möglich."); } if (mediaManager.existsInFolder(upload.getFilename(), folder)) { return status(CONFLICT, "Eine Datei mit diesem Namen existiert bereits."); } Media med = new Media(); med.title = upload.getFilename(); med.mimetype = upload.getContentType(); med.fileName = upload.getFilename(); med.file = upload.getFile(); med.owner = Component.currentAccount(); med.folder = folder; med.temporarySender = Component.currentAccount(); try { mediaManager.create(med); NotificationService.getInstance().createNotification(med, Media.MEDIA_NEW_MEDIA); } catch (Exception e) { return internalServerError("Während des Uploads ist etwas schiefgegangen!"); } return created("/media/" + med.id); } else { return internalServerError("Es konnte keine Datei gefunden werden!"); } }
Source:
<code>private int sendMergingUpdateBatch(String entityPrefix, String statementPrefix, Set<String> entityIds, List<Statement> insertStatements, Set<String> valueSet, Set<String> refSet, boolean verifyResult ) { log.debug("Processing IDs and statements", entityIds.size(), insertStatements.size()); long start = System.currentTimeMillis(); Integer modified = rdfClient.mergingUpdate( entityPrefix, statementPrefix, insertStatements, valueSet, refSet); log.debug("Update query took millis and modified statements", System.currentTimeMillis() - start, modified); if (verifyResult) { try { <START> verifyStatements(entityIds, insertStatements); <END> } catch (QueryEvaluationException e) { throw new FatalException("Can't load verify results: " + e, e); } } return modified; }</code><technical_language>verify currently handle bnodes properly. try fix it</technical_language>

Target:
private int sendMergingUpdateBatch(String entityPrefix, String statementPrefix, Set<String> entityIds, List<Statement> insertStatements, Set<String> valueSet, Set<String> refSet, boolean verifyResult ) { log.debug("Processing IDs and statements", entityIds.size(), insertStatements.size()); long start = System.currentTimeMillis(); Integer modified = rdfClient.mergingUpdate( entityPrefix, statementPrefix, insertStatements, valueSet, refSet); log.debug("Update query took millis and modified statements", System.currentTimeMillis() - start, modified); if (verifyResult) { try { verifyStatements(entityIds, insertStatements); } catch (QueryEvaluationException e) { throw new FatalException("Can't verify update results: " + e, e); } } return modified; }
Source:
<code>void convertToType() { XWikiContext context = mock(XWikiContext.class); when(this.xcontextProvider.get()).thenReturn(context); when(context.getWikiReference()).thenReturn(new WikiReference("s1")); this.converter.convertToType(mock(Type.class), "XWiki.U1"); <START> verify(this.userReferenceResolver).resolve("XWiki.U1", new WikiReference("s1")); <END> }</code><technical_language>I dont understand verify() instead of assert result. test is fragile a consequence completely implementation-dependent</technical_language>

Target:
void convertToType() { UserReference userReference = () -> false; when(this.userReferenceResolver.resolve("XWiki.U1")).thenReturn(userReference); UserReference actual = this.converter.convertToType(mock(Type.class), "XWiki.U1"); assertEquals(userReference, actual); }
Source:
<code>private static Map<String, Set<Method>> extractMethods(Class<?> childClass, Class<?> clazz, Map<String, Set<Method>> collected) { Map<String, Set<Method>> methods = Maps.newHashMap(); Method[] declaredMethods = clazz.getDeclaredMethods(); Package childPackage = childClass.getPackage(); Package classPackage = clazz.getPackage(); boolean isSamePackage = false; if ((null == childPackage) && (null == classPackage)) { isSamePackage = true; } if ((null != childPackage) && (null != classPackage)) { isSamePackage = childPackage.getName().equals(classPackage.getName()); } for (final Method method : declaredMethods) { int methodModifiers = method.getModifiers(); if ((Modifier.isPublic(methodModifiers) || Modifier.isProtected(methodModifiers)) || (isSamePackage && !Modifier.isPrivate(methodModifiers))) { if (!isOverridden(method, collected) && !Modifier.isAbstract(methodModifiers)) { if (methods.containsKey(method.getName())) { methods.get(method.getName()).add(method); continue; } <START> methods.put(method.getName(), new HashSet<Method>() {{add(method);}}); <END> } } } return methods; }</code><technical_language>Avoid {{}} is creating anonymous sub-HashSet instances</technical_language>

Target:
private static Map<String, Set<Method>> extractMethods(Class<?> childClass, Class<?> clazz, Map<String, Set<Method>> collected) { Map<String, Set<Method>> methods = Maps.newHashMap(); Method[] declaredMethods = clazz.getDeclaredMethods(); Package childPackage = childClass.getPackage(); Package classPackage = clazz.getPackage(); boolean isSamePackage = false; if ((null == childPackage) && (null == classPackage)) { isSamePackage = true; } if ((null != childPackage) && (null != classPackage)) { isSamePackage = childPackage.getName().equals(classPackage.getName()); } for (final Method method : declaredMethods) { int methodModifiers = method.getModifiers(); if ((Modifier.isPublic(methodModifiers) || Modifier.isProtected(methodModifiers)) || (isSamePackage && !Modifier.isPrivate(methodModifiers))) { if (!isOverridden(method, collected) && !Modifier.isAbstract(methodModifiers)) { Set<Method> eligibleMethods = methods.get(method.getName()); if (eligibleMethods == null) { eligibleMethods = Sets.newHashSet(); methods.put(method.getName(), eligibleMethods); } eligibleMethods.add(method); } } } return methods; }
Source:
<code><START> public boolean hasDlmsMessageListener() { <END> return this.dlmsMessageListener != null; }</code><technical_language>I consider making a constructor DlmsMessageListener parameter, create instance of DlmsMessageListener interface implements interface methods leaves empty. listener is null, insert empty listener elsewhere. This lose lines of code "if (conn.hasDlmsMessageListener()) ", in opinion code a lot cleaner</technical_language>

Target:
public boolean hasDlmsMessageListener() { return DO_NOTHING_LISTENER != this.dlmsMessageListener; }
Source:
<code>private Menu getNatTableMenu() { Event event = createMouseEvent(x, y, 3, SWT.NONE, 1); MouseEvent mouseevent = new MouseEvent(event); IMouseAction action = ((NatTable)control).getUiBindingRegistry().getMouseDownAction(mouseevent); if (action instanceof PopupMenuAction) { PopupMenuAction popupMenuAction = (PopupMenuAction) action; Field privateMenu = null; try { privateMenu = PopupMenuAction.class.getDeclaredField("menu"); <START> } catch (NoSuchFieldException | SecurityException e) { <END> return null; } privateMenu.setAccessible(true); try { return (Menu) privateMenu.get(popupMenuAction); } catch (IllegalArgumentException | IllegalAccessException e) { return null; } } return null; }</code><technical_language>need split multi-catch blocks classpath is set Java 1.6</technical_language>

Target:
private Menu getNatTableMenu() { Event event = createMouseEvent(x, y, 3, SWT.NONE, 1); MouseEvent mouseevent = new MouseEvent(event); IMouseAction action = ((NatTable)control).getUiBindingRegistry().getMouseDownAction(mouseevent); if (action instanceof PopupMenuAction) { PopupMenuAction popupMenuAction = (PopupMenuAction) action; Field privateMenu = null; try { privateMenu = PopupMenuAction.class.getDeclaredField("menu"); } catch (NoSuchFieldException e) { return null; } catch (SecurityException e) { return null; } privateMenu.setAccessible(true); try { return (Menu) privateMenu.get(popupMenuAction); } catch (IllegalArgumentException e) { return null; } catch (IllegalAccessException e) { return null; } } return null; }
Source:
<code>private String getStorageDomainNameById(String storageDomainId) { <START> for (StorageDomain storageDomainItem : storageDomainDao.getAll()) { <END> if (storageDomainItem != null && storageDomainItem.getStorageStaticData() != null) { if (storageDomainItem.getStorageStaticData().getStorage().equals(storageDomainId)) { return storageDomainItem.getStorageStaticData().getName(); } } } return ""; }</code><technical_language>storage domain ID, storageDomainDao.get(storageDomainId) if exists</technical_language>

Target:
private String getStorageDomainNameById(String storageDomainId) { if ( storageDomainId == null || storageDomainId.equals("")) return ""; for (StorageDomain storageDomainItem : storageDomainDao.getAll()) { if (storageDomainItem != null && storageDomainItem.getStorageStaticData() != null) { if (storageDomainItem.getStorageStaticData().getStorage().equals(storageDomainId)) { return storageDomainItem.getStorageStaticData().getName(); } } } return ""; }
Source:
<code>protected Set<String> executeQueryTree(QueryNode node, SQLDatabase db) { if (node instanceof AndQueryNode) { Set<String> accumulator = null; AndQueryNode andNode = (AndQueryNode) node; for (QueryNode qNode: andNode.children) { Set<String> childIds = executeQueryTree(qNode, db); if (accumulator == null) { accumulator = new HashSet<String>(childIds); } else { if (childIds != null) { accumulator = Sets.intersection(accumulator, childIds); <START> } <END> } } return accumulator; } if (node instanceof OrQueryNode) { Set<String> accumulator = null; OrQueryNode orNode = (OrQueryNode) node; for (QueryNode qNode: orNode.children) { Set<String> childIds = executeQueryTree(qNode, db); if (accumulator == null) { accumulator = new HashSet<String>(childIds); } else { if (childIds != null) { accumulator = Sets.union(accumulator, childIds); } } } return accumulator; } else if (node instanceof SqlQueryNode) { SqlQueryNode sqlNode = (SqlQueryNode) node; SqlParts sqlParts = sqlNode.sql; List<String> docIds = new ArrayList<String>(); Cursor cursor = null; try { cursor = db.rawQuery(sqlParts.sqlWithPlaceHolders, sqlParts.placeHolderValues); while (cursor.moveToNext()) { String docId = cursor.getString(0); docIds.add(docId); } } catch (SQLException e) { logger.log(Level.SEVERE, "Failed to get a list of doc ids.", e); } finally { DatabaseUtils.closeCursorQuietly(cursor); } return new HashSet<String>(docIds); } else { return null; } }</code><technical_language>Feels more logical if (childIds == null) { continue; } assignment childIds, this avoids creating accumulator if children. Also, HashSet constructor nil</technical_language>

Target:
protected Set<String> executeQueryTree(QueryNode node, SQLDatabase db) { if (node instanceof AndQueryNode) { Set<String> accumulator = null; AndQueryNode andNode = (AndQueryNode) node; for (QueryNode qNode: andNode.children) { Set<String> childIds = executeQueryTree(qNode, db); if (childIds == null) { continue; } if (accumulator == null) { accumulator = new HashSet<String>(childIds); } else { if (childIds != null) { accumulator = Sets.intersection(accumulator, childIds); } } } return accumulator; } if (node instanceof OrQueryNode) { Set<String> accumulator = null; OrQueryNode orNode = (OrQueryNode) node; for (QueryNode qNode: orNode.children) { Set<String> childIds = executeQueryTree(qNode, db); if (childIds == null) { continue; } if (accumulator == null) { accumulator = new HashSet<String>(childIds); } else { if (childIds != null) { accumulator = Sets.union(accumulator, childIds); } } } return accumulator; } else if (node instanceof SqlQueryNode) { SqlQueryNode sqlNode = (SqlQueryNode) node; SqlParts sqlParts = sqlNode.sql; List<String> docIds = new ArrayList<String>(); Cursor cursor = null; try { cursor = db.rawQuery(sqlParts.sqlWithPlaceHolders, sqlParts.placeHolderValues); while (cursor.moveToNext()) { String docId = cursor.getString(0); docIds.add(docId); } } catch (SQLException e) { logger.log(Level.SEVERE, "Failed to get a list of doc ids.", e); } finally { DatabaseUtils.closeCursorQuietly(cursor); } return new HashSet<String>(docIds); } else { return null; } }
Source:
<code>private boolean eventExists(String eventName) { <START> for (AuditLogType alt : AuditLogType.values()) { <END> if (alt.name().equals(eventName)) { return true; } } return false; }</code><technical_language>this solution traverse values do string comparisons? private boolean eventExists(String eventName) { boolean exists = false; try { AuditLogType.valueOf(eventName); exists = true; } catch (Exception ex) { } return exists; }</technical_language>

Target:
private boolean eventExists(String eventName) { boolean exists = false; try { AuditLogType.valueOf(eventName); exists = true; } catch (Exception ex) { } return exists; }
Source:
<code>private String getExpectedInstructorString(InstructorAttributes[] instructors) { <START> StringJoiner expected = new StringJoiner("\n"); <END> for (InstructorAttributes instructor : instructors) { expected.add(instructor.getRole() + ": " + instructor.getName() + " (" + instructor.getEmail() + ")"); } return expected.toString(); }</code><technical_language>Consider System.lineSeparator() this work OS</technical_language>

Target:
private String getExpectedInstructorString(InstructorAttributes[] instructors) { StringJoiner expected = new StringJoiner(System.lineSeparator()); for (InstructorAttributes instructor : instructors) { expected.add(instructor.getRole() + ": " + instructor.getName() + " (" + instructor.getEmail() + ")"); } return expected.toString(); }
Source:
<code>public SignatureWidget( final PopupResources popupResources, @Assisted final OrionEditorWidget textEditor, @Assisted final OrionKeyModeOverlay assistMode) { this.popupResources = popupResources; this.textEditor = textEditor; this.assistMode = assistMode; popupElement = Elements.createDivElement(popupResources.popupStyle().popup()); Element headerElement = Elements.createDivElement(popupResources.popupStyle().header()); headerElement.setInnerText("Signatures:"); popupElement.appendChild(headerElement); popupBodyElement = Elements.createDivElement(popupResources.popupStyle().body()); <START> popupBodyElement.setClassName("signaturesContent"); <END> popupElement.appendChild(popupBodyElement); listElement = Elements.createUListElement(); popupBodyElement.appendChild(listElement); docPopup = new FlowPanel(); docPopup.setStyleName(popupResources.popupStyle().popup()); docPopup.setSize("370px", "180px"); popupListener = evt -> { if (!(evt instanceof MouseEvent)) { return; } final MouseEvent mouseEvent = (MouseEvent) evt; final EventTarget target = mouseEvent.getTarget(); if (target instanceof Element) { final Element elementTarget = (Element) target; if (docPopup.isVisible() && (elementTarget.equals(docPopup.getElement()) || elementTarget.getParentElement().equals(docPopup.getElement()))) { return; } if (!SignatureWidget.this.popupElement.contains(elementTarget)) { hide(); evt.preventDefault(); } } }; }</code><technical_language>gwt-debug-id here</technical_language>

Target:
public SignatureWidget( final PopupResources popupResources, @Assisted final OrionEditorWidget textEditor, @Assisted final OrionKeyModeOverlay assistMode) { this.popupResources = popupResources; this.textEditor = textEditor; this.assistMode = assistMode; popupElement = Elements.createDivElement(popupResources.popupStyle().popup()); Element headerElement = Elements.createDivElement(popupResources.popupStyle().header()); headerElement.setInnerText("Signatures:"); popupElement.appendChild(headerElement); popupBodyElement = Elements.createDivElement(popupResources.popupStyle().body()); popupBodyElement.setId(SIGNATURES_CONTENT_ID); popupElement.appendChild(popupBodyElement); listElement = Elements.createUListElement(); popupBodyElement.appendChild(listElement); docPopup = new FlowPanel(); docPopup.setStyleName(popupResources.popupStyle().popup()); docPopup.setSize("370px", "180px"); popupListener = evt -> { if (!(evt instanceof MouseEvent)) { return; } final MouseEvent mouseEvent = (MouseEvent) evt; final EventTarget target = mouseEvent.getTarget(); if (target instanceof Element) { final Element elementTarget = (Element) target; if (docPopup.isVisible() && (elementTarget.equals(docPopup.getElement()) || elementTarget.getParentElement().equals(docPopup.getElement()))) { return; } if (!SignatureWidget.this.popupElement.contains(elementTarget)) { hide(); evt.preventDefault(); } } }; }
Source:
<code>public void run() { doIt(); logger.trace("Task #" + this.taskID + " is rescheduling a new task now..."); this.executor.execute(new ReSchedulingTask(this.executor)); <START> logger.trace("... task #" + this.taskID + " has completed recheduling a new task."); <END> }</code><technical_language>recheduling, minor typo error</technical_language>

Target:
public void run() { doIt(); logger.trace("Task #" + this.taskID + " is rescheduling a new task now..."); if (tasksCounter <= MAX_TASKS) { this.executor.execute(new ReSchedulingTask(this.executor)); } logger.trace("... task #" + this.taskID + " has completed rescheduling a new task."); }
Source:
<code>public int getSizeInventory() { if (cached == null) { initCache(); } <START> if(cached.size() == 0) <END> return 1; return cached.size(); }</code><technical_language>spacing, code style</technical_language>

Target:
public int getSizeInventory() { if (cached == null) { initCache(); } if(cached.size() == 0) { return 1; } return cached.size(); }
Source:
<code>private static StructuredProperty buildContextualisedTitle(String softwareTitle, String repositoryName, String publicationTitle) { return buildTitle( MessageFormat.format(SOFTWARE_TITLE_ALTERNATIVE_TEMPLATE, <START> new Object[] { softwareTitle, repositoryName, publicationTitle }), <END> InfoSpaceConstants.SEMANTIC_CLASS_ALTERNATIVE_TITLE); }</code><technical_language>I array creation is redundant replaced giving varargs explicitly</technical_language>

Target:
private static StructuredProperty buildContextualisedTitle(String softwareTitle, String repositoryName, String publicationTitle) { return buildTitle(MessageFormat.format(SOFTWARE_TITLE_ALTERNATIVE_TEMPLATE, softwareTitle, repositoryName, publicationTitle), InfoSpaceConstants.SEMANTIC_CLASS_ALTERNATIVE_TITLE); }
Source:
<code>public static <V> ExecutorCompletionService<V> createCompletionService() { <START> ExecutorCompletionService<V> ecs = new ExecutorCompletionService<V>(es); <END> return ecs; }</code><technical_language>forgot inline liner method moti suggested patch #1 .. :-) other - good me</technical_language>

Target:
public static <V> ExecutorCompletionService<V> createCompletionService() { return new ExecutorCompletionService<V>(es); }