auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public ExternalServerExposerStrategyProvider( @Named("che.infra.kubernetes.server_strategy") String strategy, Map<String, ExternalServerExposerStrategy> strategies) { final ExternalServerExposerStrategy externalServerExposerStrategy = strategies.get(strategy); if (externalServerExposerStrategy != null) { this.externalServerExposerStrategy = externalServerExposerStrategy; } else { <START> throw new IllegalArgumentException( <END> format("Unsupported Ingress strategy '%s' configured", strategy)); } }</code><technical_language>throw org.eclipse.che.inject.ConfigurationException</technical_language>

Target:
public ExternalServerExposerStrategyProvider( @Named("che.infra.kubernetes.server_strategy") String strategy, Map<String, ExternalServerExposerStrategy> strategies) { final ExternalServerExposerStrategy externalServerExposerStrategy = strategies.get(strategy); if (externalServerExposerStrategy != null) { this.externalServerExposerStrategy = externalServerExposerStrategy; } else { throw new ConfigurationException( format("Unsupported Ingress strategy '%s' configured", strategy)); } }
Source:
<code>public synchronized long read(ByteBuffer[] dsts, int offset, int length) throws IOException { if (length == 0) return 0; long returnValue = 0; long readBytes; long totalLength = 0; int remains; boolean bufferAvailable = false; int limit = offset + length; for (int i = offset; i < limit; i++) { remains = dsts[i].remaining(); if (remains > 0) { bufferAvailable = true; totalLength += remains; } else if (!bufferAvailable) { <START> offset += 1; <END> } if (totalLength > maxRemoteSize && totalLength > size()) break; } if (offset == length) return 0; totalLength = getMaxRead(remoteOffset, totalLength); readBytes = startRead(remoteOffset, totalLength, dsts[offset++], true); if (readBytes == -1) return -1; returnValue += readBytes; for (int i = offset; i < length; i++) { while (dsts[i].hasRemaining()) { readBytes = readMore(dsts[i]); if (readBytes == -1) break; returnValue += readBytes; } } remoteOffset += returnValue; return returnValue; }</code><technical_language>If a buffer partway array room, this skip earlier buffer. A, B, C zero offset B is full. Ater this, offset 1 B C skipped A room</technical_language>

Target:
public synchronized long read(ByteBuffer[] dsts, int offset, int length) throws IOException { if (length == 0) return 0; long returnValue = 0; long readBytes; long totalLength = 0; int remains; boolean bufferAvailable = false; int limit = offset + length; for (int i = offset; i < limit; i++) { remains = dsts[i].remaining(); if (remains > 0) { bufferAvailable = true; totalLength += remains; } else if (!bufferAvailable) { offset += 1; } if (totalLength > maxRemoteSize && totalLength > size()) break; } if (!bufferAvailable) return 0; totalLength = getMaxRead(remoteOffset, totalLength); readBytes = startRead(remoteOffset, totalLength, dsts[offset++], true); if (readBytes == -1) return -1; returnValue += readBytes; for (int i = offset; i < length; i++) { while (dsts[i].hasRemaining()) { readBytes = readMore(dsts[i]); if (readBytes == -1) break; returnValue += readBytes; } } remoteOffset += returnValue; return returnValue; }
Source:
<code><START> public void visitMethodDeclaration(MethodDeclarationTree tree) { <END> if (tree.body().is(Kind.BLOCK) && !(hasValuableBody((BlockTree) tree.body()) || isClassAbstract(tree))) { context().newIssue(this, tree, MESSAGE); } super.visitMethodDeclaration(tree); }</code><technical_language>In addition methods, cover functions anonymous functions. do for [JavaScript](<LINK_0></technical_language>

Target:
public void visitMethodDeclaration(MethodDeclarationTree tree) { if (tree.body().is(Kind.BLOCK) && !(hasValuableBody((BlockTree) tree.body()) || isClassAbstract(tree) || hasCommentAbove(tree.modifiers().get(0)))) { commitIssue(tree, "method"); } super.visitMethodDeclaration(tree); }
Source:
<code>public Response add(Step step) { validateParameters(step, "type", "status.state" , "description"); String id; <START> if (step.isSetParentStep() && step.getParentStep().getId() != null) { <END> id = step.getParentStep().getId(); } else { id = jobId.toString(); } return performCreate(VdcActionType.AddExternalStep, new AddExternalStepParameters(asGuid(id), step.getDescription(),StepMapper.map(StepEnum.fromValue(step.getType())), JobMapper.map(step.getStatus(), null)), new QueryIdResolver<Guid>(VdcQueryType.GetStepByStepId, IdQueryParameters.class)); }</code><technical_language>this in 'else' while intention (if <paranet_step/> specified) 1. please remove new condition 2. add validateParameters(step, "type", "step.parentStep.id"); in this if()</technical_language>

Target:
public Response add(Step step) { validateParameters(step, "type", "status.state" , "description"); String id; if (step.isSetParentStep()) { validateParameters(step, "step.parentStep.id"); id = step.getParentStep().getId(); } else { id = jobId.toString(); } return performCreate(VdcActionType.AddExternalStep, new AddExternalStepParameters(asGuid(id), step.getDescription(),StepMapper.map(StepEnum.fromValue(step.getType())), JobMapper.map(step.getStatus(), null)), new QueryIdResolver<Guid>(VdcQueryType.GetStepByStepId, IdQueryParameters.class)); }
Source:
<code>public void setResponsesObject(Responses responsesObject) { this.responsesObject = responsesObject; <START> if (responses == null && responsesObject != null) { <END> responses = new LinkedHashMap<String, Response>(); for (String key : this.responsesObject.keySet()) { responses.put(key, responsesObject.get(key)); } } }</code><technical_language>remove added logic, logic is handled in getter</technical_language>

Target:
public void setResponsesObject(Responses responsesObject) { this.responsesObject = responsesObject; }
Source:
<code>public Pattern parseFromInput(String input, ParserContext context) throws InputParseException { if (!input.startsWith("#clipboard") && !input.startsWith("#copy")) { return null; } LocalSession session = context.requireSession(); int offsetPart; BlockVector3 offset = BlockVector3.ZERO; <START> if ((offsetPart = input.indexOf('@')) >= 0) { <END> if (input.length() <= offsetPart + 1) { throw new InputParseException("Clipboard offset coordinates not specified!"); } String offsetString = input.substring(offsetPart + 1); String[] offsetCoords = offsetString.split(","); if (offsetCoords.length != 3) { throw new InputParseException("Clipboard offset needs x,y,z coordinates."); } offset = BlockVector3.at( Integer.valueOf(offsetCoords[0]), Integer.valueOf(offsetCoords[1]), Integer.valueOf(offsetCoords[2]) ); } if (session != null) { try { ClipboardHolder holder = session.getClipboard(); Clipboard clipboard = holder.getClipboard(); return new ClipboardPattern(clipboard, offset); } catch (EmptyClipboardException e) { throw new InputParseException("To use #clipboard, please first copy something to your clipboard"); } } else { throw new InputParseException("No session is available, so no clipboard is available"); } }</code><technical_language>split instead of indexOf+substring. for more readable code</technical_language>

Target:
public Pattern parseFromInput(String input, ParserContext context) throws InputParseException { String[] offsetParts = input.split("@", 2); if (!offsetParts[0].equalsIgnoreCase("#clipboard") && !offsetParts[0].equalsIgnoreCase("#copy")) { return null; } LocalSession session = context.requireSession(); BlockVector3 offset = BlockVector3.ZERO; if (offsetParts.length == 2) { String[] offsetSplit = offsetParts[1].split(","); if (offsetSplit.length != 3) { throw new InputParseException("Clipboard offset needs x,y,z coordinates."); } offset = BlockVector3.at( Integer.valueOf(offsetSplit[0]), Integer.valueOf(offsetSplit[1]), Integer.valueOf(offsetSplit[2]) ); } if (session != null) { try { ClipboardHolder holder = session.getClipboard(); Clipboard clipboard = holder.getClipboard(); return new ClipboardPattern(clipboard, offset); } catch (EmptyClipboardException e) { throw new InputParseException("To use #clipboard, please first copy something to your clipboard"); } } else { throw new InputParseException("No session is available, so no clipboard is available"); } }
Source:
<code><START> public Ticket requestTicketOfType(TicketType type, User owner, boolean pickupService, boolean chMember) { <END> if (ticketRepository.countByType(type) >= type.getLimit()) { throw new TicketUnavailableException(type); } else { Ticket ticket = new Ticket(owner, type, pickupService, chMember); return ticketRepository.save(ticket); } }</code><technical_language>this a copy of function removed? missing synchronized here, if other changes</technical_language>

Target:
public synchronized Ticket requestTicketOfType(TicketType type, User owner, boolean pickupService, boolean chMember) { if (ticketRepository.countByType(type) >= type.getLimit()) { throw new TicketUnavailableException(type); } else { Ticket ticket = new Ticket(owner, type, pickupService, chMember); return ticketRepository.save(ticket); } }
Source:
<code>private ProjectState newProjectState(ProjectConfig local) { <START> PrologEnvironment.Factory envFactory = null; GitRepositoryManager gitMgr = null; ProjectControl.AssistedFactory projectControlFactory = null; RulesCache rulesCache = null; SitePaths sitePaths = null; List<CommentLinkInfo> commentLinks = null; all.put(local.getProject().getNameKey(), new ProjectState(sitePaths, projectCache, allProjectsName, projectControlFactory, envFactory, gitMgr, rulesCache, commentLinks, local)); <END> return all.get(local.getProject().getNameKey()); }</code><technical_language>add(ProjectConfig) method instead of repeating code</technical_language>

Target:
private ProjectState newProjectState(ProjectConfig local) { add(local); return all.get(local.getProject().getNameKey()); }
Source:
<code>private boolean bindToLifecycleSafely(UseCase useCase, int buttonViewId) { CameraSelector cameraSelector = <START> new CameraSelector.Builder().requireLensFacing(mCurrentCameraLensFacing).build(); <END> try { LifecycleCameraProvider.bindToLifecycle(this, cameraSelector, useCase); } catch (IllegalArgumentException e) { Log.e(TAG, e.getMessage()); Toast.makeText(getApplicationContext(), "Bind too many use cases.", Toast.LENGTH_SHORT) .show(); Button button = this.findViewById(buttonViewId); button.setBackgroundColor(Color.RED); return false; } return true; }</code><technical_language>nit: Create CameraSelector changing lens facing directional toggle, instead of binding lifecycle</technical_language>

Target:
private boolean bindToLifecycleSafely(UseCase useCase, int buttonViewId) { try { LifecycleCameraProvider.bindToLifecycle(this, mCurrentCameraSelector, useCase); } catch (IllegalArgumentException e) { Log.e(TAG, e.getMessage()); Toast.makeText(getApplicationContext(), "Bind too many use cases.", Toast.LENGTH_SHORT) .show(); Button button = this.findViewById(buttonViewId); button.setBackgroundColor(Color.RED); return false; } return true; }
Source:
<code>public void shouldFindStringAnnotatedGeoMarkersInRangeForGivenCriteriaQuery() { loadAnnotationBaseEntities(); CriteriaQuery geoLocationCriteriaQuery = new CriteriaQuery( new Criteria("locationAsString").within(new GeoPoint(51.000000, 0.100000), "1km")); <START> List<SearchHit<LocationMarkerEntity>> geoAuthorsForGeoCriteria = operations.queryForList(geoLocationCriteriaQuery, <END> LocationMarkerEntity.class, locationMarkerIndex); assertThat(geoAuthorsForGeoCriteria).hasSize(1); }</code><technical_language>SearchHits, migration easier users switch List<T> SearchHits<T></technical_language>

Target:
public void shouldFindStringAnnotatedGeoMarkersInRangeForGivenCriteriaQuery() { loadAnnotationBaseEntities(); CriteriaQuery geoLocationCriteriaQuery = new CriteriaQuery( new Criteria("locationAsString").within(new GeoPoint(51.000000, 0.100000), "1km")); SearchHits<LocationMarkerEntity> geoAuthorsForGeoCriteria = operations.search(geoLocationCriteriaQuery, LocationMarkerEntity.class, locationMarkerIndex); assertThat(geoAuthorsForGeoCriteria).hasSize(1); }
Source:
<code>public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { <START> ViewGroup rootView = createMainView(inflater, container, savedInstanceState); return rootView; <END> }</code><technical_language>Nitpick: is complaining unnecessary rootView variable</technical_language>

Target:
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return createMainView(inflater, container, savedInstanceState); }
Source:
<code>private Set<String> getRefNamesAllUsers(String prefix) throws OrmException { <START> Repository repo = null; try { repo = repoManager.openRepository(allUsers); RefDatabase refDb = repo.getRefDatabase(); return refDb.getRefs(prefix).keySet(); } catch (IOException e) { throw new OrmException(e); } finally { if (repo != null) { repo.close(); } } <END> }</code><technical_language>Overly complex. say: Repository repo = repoManager.openRepository(...); try { ... } finally { repo.close(); }</technical_language>

Target:
private Set<String> getRefNamesAllUsers(String prefix) throws OrmException { Repository repo; try { repo = repoManager.openRepository(allUsers); } catch (IOException e) { throw new OrmException(e); } try { RefDatabase refDb = repo.getRefDatabase(); return refDb.getRefs(prefix).keySet(); } catch (IOException e) { throw new OrmException(e); } finally { repo.close(); } }
Source:
<code><START> public Long getLatestSequenceNumber(StreamPartition<Integer> partition) <END> { seekToLatest(Collections.singleton(partition)); return consumer.position(new TopicPartition(partition.getStream(), partition.getPartitionId())); }</code><technical_language>This call side-effect of changing position of pointer in stream unexpected callers. save current position, get latest sequence number, restore current position after</technical_language>

Target:
public Long getLatestSequenceNumber(StreamPartition<Integer> partition) { Long currPos = consumer.position(new TopicPartition(partition.getStream(), partition.getPartitionId())); seekToLatest(Collections.singleton(partition)); Long nextPos = consumer.position(new TopicPartition(partition.getStream(), partition.getPartitionId())); seek(partition, currPos); return nextPos; }
Source:
<code>private void updateUndefinedSize() { assert !definedSize : "This method should never be called when using defined size"; if (resendEntireRange || sizeReset) { int size = initialSizeEstimate; if (sizeEstimateCallback != null) { size = getNewSizeEstimateFromCallback(true); } if (size == -1) { size = getDefaultInitialSize(); } getLogger(DataCommunicator.class) <START> .info("Requested: " + requestedRange + " old size: " + assumedSize + " new size: " + size); <END> assumedSize = size; } else { if (requestedRange.getEnd() + pageSize > assumedSize) { int previousAssumedSize = assumedSize; if (sizeEstimateCallback != null) { assumedSize = getNewSizeEstimateFromCallback(false); } else { assumedSize += getEstimatedSizeIncrease(); } getLogger(DataCommunicator.class).info("Requested: " + requestedRange + " old size: " + previousAssumedSize + " new size: " + assumedSize); } } }</code><technical_language>suggestion .info("Requested range: size: new size: {}", requestedRange, assumedSize, size);</technical_language>

Target:
private void updateUndefinedSize() { assert !definedSize : "This method should never be called when using defined size"; if (resendEntireRange || sizeReset) { int size = initialSizeEstimate; if (sizeEstimateCallback != null) { size = getNewSizeEstimateFromCallback(true); } if (size == -1) { size = getDefaultInitialSize(); } getLogger(DataCommunicator.class).info( "Requested range: old size: new size: {}", requestedRange, assumedSize, size); assumedSize = size; } else { if (requestedRange.getEnd() + pageSize > assumedSize) { int previousAssumedSize = assumedSize; if (sizeEstimateCallback != null) { assumedSize = getNewSizeEstimateFromCallback(false); } else { assumedSize += getEstimatedSizeIncrease(); } getLogger(DataCommunicator.class).info( "Requested range: old size: new size: {}", requestedRange, previousAssumedSize, assumedSize); } } }
Source:
<code>public void testSTCrosses() throws Exception { assertQuery("select ST_Crosses(ST_GeometryFromText('LineString(0 0, 1 1)'), ST_GeometryFromText('LineString(1 0, 0 1)'))", "select true"); assertQuery("select ST_Crosses(ST_GeometryFromText('Polygon ((1 1, 1 4, 4 4, 4 1))'), ST_GeometryFromText('Polygon ((2 2, 2 5, 5 5, 5 2))'))", "select false"); assertQuery("select ST_Crosses(ST_GeometryFromText('Polygon ((1 1, 1 4, 4 4, 4 1))'), ST_GeometryFromText('LineString(2 0, 2 3)'))", "select true"); <START> assertQuery("select ST_Crosses(ST_GeometryFromText('LineString(0 0, 1 1)'), ST_GeometryFromText('LineString(1 0, 0 1)'))", "select true"); <END> }</code><technical_language>this line a copy of line 263</technical_language>

Target:
public void testSTCrosses() throws Exception { assertFunction("ST_Crosses(ST_GeometryFromText('POINT (20 20)'), ST_GeometryFromText('POINT (25 25)'))", BOOLEAN, false); assertFunction("ST_Crosses(ST_GeometryFromText('LINESTRING (20 20, 30 30)'), ST_GeometryFromText('POINT (25 25)'))", BOOLEAN, false); assertFunction("ST_Crosses(ST_GeometryFromText('LINESTRING (20 20, 30 30)'), ST_GeometryFromText('MULTIPOINT (25 25, 31 31)'))", BOOLEAN, true); assertFunction("ST_Crosses(ST_GeometryFromText('LINESTRING(0 0, 1 1)'), ST_GeometryFromText('LINESTRING (1 0, 0 1)'))", BOOLEAN, true); assertFunction("ST_Crosses(ST_GeometryFromText('POLYGON ((1 1, 1 4, 4 4, 4 1))'), ST_GeometryFromText('POLYGON ((2 2, 2 5, 5 5, 5 2))'))", BOOLEAN, false); assertFunction("ST_Crosses(ST_GeometryFromText('MULTIPOLYGON (((0 0 , 0 2, 2 2, 2 0)), ((2 2, 2 4, 4 4, 4 2)))'), ST_GeometryFromText('POLYGON ((2 2, 2 3, 3 3, 3 2))'))", BOOLEAN, false); assertFunction("ST_Crosses(ST_GeometryFromText('LINESTRING (-2 -2, 6 6)'), ST_GeometryFromText('POLYGON ((0 0, 0 4, 4 4, 4 0))'))", BOOLEAN, true); }
Source:
<code>public FileDownloadPanel(String id) { super(id); WorkInProgressPopup loadingPopup = new WorkInProgressPopup("exportZipLoadingPopup", new ResourceModel("common.action.export.zip.loading")); add( loadingPopup, new FileDownloadAjaxLink("exportZip", loadingPopup, <START> new AbstractFileGenerationModel( <END> ExportFileUtils.getFileNameMediaTypeModel( Model.of("export-showcase-"), Model.of(MediaType.APPLICATION_ZIP) ) ) { private static final long serialVersionUID = 1L; @Override protected File generateFile() { return generateTFile(); } } ) ); }</code><technical_language>I told a bit verbose for taste. add a constructor AbstractFileGenerationModel accept parameter of ExportFileUtils.getFileNameMediaTypeModel call ExportFileUtils.getFileNameMediaTypeModel build model? another a String a MediaType parameters (not models)? Another solution, cleaner: add a SimpleFileDownloadAjaxLink a generateFile method constructors above. Yes, a step before, we'de FileDownloadAjaxLink for more complex needs</technical_language>

Target:
public FileDownloadPanel(String id) { super(id); WorkInProgressPopup loadingPopup = new WorkInProgressPopup("exportZipLoadingPopup", new ResourceModel("common.action.export.zip.loading")); add( loadingPopup, new SimpleFileDownloadAjaxLink("exportZip", loadingPopup, "export-showcase-", MediaType.APPLICATION_ZIP) { private static final long serialVersionUID = 1L; @Override protected File generateFile() { return generateTFile(); } } ); }
Source:
<code>public void visitNode(Tree tree) { <START> if (tree.is(Kind.CLASS)) { <END> TypeSymbol classSymbol = ((ClassTree) tree).symbol(); initFieldsMetaData(classSymbol); classSymbol.memberSymbols().stream() .filter(PrivateFieldUsedLocallyCheck::isPrivateField) .filter(memberSymbol -> !memberSymbol.usages().isEmpty()) .filter(memberSymbol -> !isUsedOutsideMethods(memberSymbol, classSymbol)) .forEach(this::checkPrivateField); } }</code><technical_language>useless test : this result in a uncovered branch</technical_language>

Target:
public void visitNode(Tree tree) { TypeSymbol classSymbol = ((ClassTree) tree).symbol(); initFieldsMetaData(classSymbol); classSymbol.memberSymbols().stream() .filter(PrivateFieldUsedLocallyCheck::isPrivateField) .filter(memberSymbol -> !memberSymbol.usages().isEmpty()) .filter(memberSymbol -> !isUsedOutsideMethods(memberSymbol, classSymbol)) .forEach(this::checkPrivateField); fieldsReadOnAnotherInstance.clear(); fieldsLiveInMethodEntry.clear(); }
Source:
<code>public static ExtensionsManager getInstance() { if (instance == null) { synchronized (EngineExtensionsManager.class) { if (instance == null) { instance = new ExtensionsManager(); instance.getGlobalContext().put(Base.GlobalContextKeys.APPLICATION_NAME, Base.ApplicationNames.OVIRT_ENGINE); createInternalAAAConfigurations(); createKerberosLdapAAAConfigurations(); for (File directory : EngineLocalConfig.getInstance().getExtensionsDirectories()) { if (!directory.exists()) { log.warn(String.format("The directory '%1$s' cotaning configuration files does not exist.", directory.getAbsolutePath())); } else { File[] files = directory.listFiles(); if (files != null) { sort(files); for (File file : files) { if (file.getName().endsWith(".properties")) { instance.load(file); } } } } } for (ExtensionProxy extension : instance.getExtensions()) { if (EngineLocalConfig.getInstance().getBoolean(ENGINE_EXTENSION_ENABLED + extension.getContext().<String> get(Base.ContextKeys.INSTANCE_NAME), true)) { try { <START> instance.activate(extension.getContext().<String> get(Base.ContextKeys.INSTANCE_NAME)); <END> } catch (Exception ex) { log.error(ex.getMessage()); log.debug(ex); } } } } } } instance.dump(); return instance; }</code><technical_language>ok... I do follow, done this... if extension is enabled = false properties enabled explicit configuration engine config. in other words if is a in engine config override extension properties... if is no, properties account</technical_language>

Target:
public static ExtensionsManager getInstance() { if (instance == null) { synchronized (EngineExtensionsManager.class) { if (instance == null) { instance = new ExtensionsManager(); instance.getGlobalContext().put(Base.GlobalContextKeys.APPLICATION_NAME, Base.ApplicationNames.OVIRT_ENGINE); createInternalAAAConfigurations(); createKerberosLdapAAAConfigurations(); for (File directory : EngineLocalConfig.getInstance().getExtensionsDirectories()) { if (!directory.exists()) { log.warn(String.format("The directory '%1$s' cotaning configuration files does not exist.", directory.getAbsolutePath())); } else { File[] files = directory.listFiles(); if (files != null) { sort(files); for (File file : files) { if (file.getName().endsWith(".properties")) { instance.load(file); } } } } } for (ExtensionProxy extension : instance.getExtensions()) { if (EngineLocalConfig.getInstance().getBoolean(ENGINE_EXTENSION_ENABLED + extension.getContext().<String> get(Base.ContextKeys.INSTANCE_NAME), true)) { try { instance.activate( extension.getContext().<String> get(Base.ContextKeys.INSTANCE_NAME), EngineLocalConfig.getInstance().getBoolean( ENGINE_EXTENSION_ENABLED + extension.getContext().<String> get(Base.ContextKeys.INSTANCE_NAME) ) ); } catch (Exception ex) { log.error(ex.getMessage()); log.debug(ex); } } } } } } instance.dump(); return instance; }
Source:
<code>public void visit(OAuthAuthenticationResult result) { <START> throw new UnsupportedOperationException("visit(OauthAuthenticationResult) is not expected."); <END> }</code><technical_language>Need update exception message OAuth instead of Oauth</technical_language>

Target:
public void visit(OAuthAuthenticationResult result) { throw new UnsupportedOperationException("visit(OAuthAuthenticationResult) is not expected."); }
Source:
<code>public void executeQueryFromFile() throws IOException { HiveShell shell = createHiveShell(); shell.start(); String statement = "select current_database(), NULL, 100"; when(container.executeStatement(statement)).thenReturn(Arrays.<Object[]> asList( new Object[] {"default", null, 100})); String hql = statement + ";"; <START> File file = new File(tempFolder.getRoot(), "script.hql"); <END> Files.write(hql, file, UTF_8); List<String> results = shell.executeQuery(UTF_8, Paths.get(file.toURI()), "xxx", "yyy"); assertThat(results.size(), is(1)); assertThat(results.get(0), is("defaultxxxyyyxxx100")); }</code><technical_language>"tempFolder.newFile("script.hql")"</technical_language>

Target:
public void executeQueryFromFile() throws IOException { HiveShell shell = createHiveShell(); shell.start(); String statement = "select current_database(), NULL, 100"; when(container.executeStatement(statement)).thenReturn(Arrays.<Object[]> asList( new Object[] {"default", null, 100})); String hql = statement + ";"; File file = tempFolder.newFile("script.hql"); Files.write(hql, file, UTF_8); List<String> results = shell.executeQuery(UTF_8, Paths.get(file.toURI()), "xxx", "yyy"); assertThat(results.size(), is(1)); assertThat(results.get(0), is("defaultxxxyyyxxx100")); }
Source:
<code>public static Simple copyOrUpdate(Realm realm, Simple object, boolean update, Map<RealmObject,RealmObjectProxy> cache) { if (((RealmObject) object).realm != null && ((RealmObject) object).realm.threadId != realm.threadId) { throw new IllegalArgumentException( <START> "Objects belonging to Realm instances in other threads cannot be copied into this Realm instance."); <END> } if (((RealmObject) object).realm != null && ((RealmObject) object).realm.getPath().equals(realm.getPath())) { return object; } return copy(realm, object, update, cache); }</code><technical_language>"belonging" -> "which belong"</technical_language>

Target:
public static Simple copyOrUpdate(Realm realm, Simple object, boolean update, Map<RealmObject,RealmObjectProxy> cache) { if (((RealmObject) object).realm != null && ((RealmObject) object).realm.threadId != realm.threadId) { throw new IllegalArgumentException( "Objects which belong to Realm instances in other threads cannot be copied into this Realm instance."); } if (((RealmObject) object).realm != null && ((RealmObject) object).realm.getPath().equals(realm.getPath())) { return object; } return copy(realm, object, update, cache); }
Source:
<code>public Properties getProperties(final String filePath) { final Properties result = new Properties(); <START> final String fullFileName = filePath.substring(filePath.lastIndexOf("/") + 1); <END> final String fileNamePart = fullFileName.substring(0, fullFileName.indexOf("-")); final String fileVersion = fullFileName.substring(fullFileName.indexOf("-") + 1).replace(".jar", ""); final String value = notMavenizedArtifacts.getProperty(fileNamePart); if (value != null) { final String[] GAV = value.split(":"); result.put(GROUP_ID, GAV[0]); result.put(ARTIFACT_ID, GAV[1]); result.put(VERSION, fileVersion); } return result; }</code><technical_language>(last)IndexOf(String) character String, replace overloaded version (last)IndexOf(Char), is faster. 3 occurrences in this PR</technical_language>

Target:
public Properties getProperties(final String filePath) { final Properties result = new Properties(); final String fullFileName = filePath.substring(filePath.lastIndexOf('/') + 1); for (Map.Entry<String, String[]> entry : notMavenizedArtifacts.entrySet()) { if (fullFileName.startsWith(entry.getKey())) { final String fileVersion = fullFileName.substring(entry.getKey().length()).replace(".jar", ""); result.put(GROUP_ID, entry.getValue()[0]); result.put(ARTIFACT_ID, entry.getValue()[1]); result.put(VERSION, fileVersion); break; } } return result; }
Source:
<code>public StoreIndexDescriptor withIds( long id, long owningConstraintId ) { <START> assert owningConstraintId >= 0; <END> return new StoreIndexDescriptor( this, id, owningConstraintId ); }</code><technical_language>discussed Kernel, real exceptions instead of assert. Also, do need this check for owning constraint for id</technical_language>

Target:
public StoreIndexDescriptor withIds( long id, long owningConstraintId ) { assertValidId( id, "id" ); assertValidId( owningConstraintId, "owning constraint id" ); return new StoreIndexDescriptor( this, id, owningConstraintId ); }
Source:
<code>public void run(@Nonnull JSession session) throws Exception { Collection<Rule> rules = new ArrayList<Rule>(); if (ThreadConfig.get(PreProcessor.ENABLE).booleanValue()) { InputStreamFile input = ThreadConfig.get(PreProcessor.FILE); InputStream inputStream = input.getInputStream(); try { rules.addAll(parseRules(session, inputStream)); } finally { try { inputStream.close(); } catch (IOException e) { } } } for (Meta meta : session.getMetas()) { InputVFile file = meta.getVFile(); if (file.getName().endsWith(".jpp")) { InputStream inputStream = null; try { inputStream = file.openRead(); <START> rules.addAll(parseRules(session, inputStream)); <END> } finally { try { if (inputStream != null) { inputStream.close(); } } catch (IOException e) { } } } } applyRules(rules, session); }</code><technical_language>Note that. For me, remove</technical_language>

Target:
public void run(@Nonnull JSession session) throws Exception { Collection<Rule> rules = new ArrayList<Rule>(); if (ThreadConfig.get(PreProcessor.ENABLE).booleanValue()) { InputStreamFile input = ThreadConfig.get(PreProcessor.FILE); InputStream inputStream = input.getInputStream(); try { rules.addAll(parseRules(session, inputStream)); } finally { try { inputStream.close(); } catch (IOException e) { } } } for (Iterator<InputRootVDir> iter = session.getPathSources(); iter.hasNext();) { InputRootVDir dir = iter.next(); for (InputVElement sub : dir.list()) { if (sub.getName().equals("JACK-INF") && sub.isVDir()) { for (InputVElement inf : ((InputVDir) sub).list()) { if (inf.getName().endsWith(".jpp") && !inf.isVDir()) { InputStream inputStream = ((InputVFile) inf).openRead(); try { rules.addAll(parseRules(session, inputStream)); } finally { try { inputStream.close(); } catch (IOException e) { } } } } break; } } } applyRules(rules, session); }
Source:
<code>public Response getAll(@Context HttpServletRequest request, @PathParam("params") String params) { webResource.init(params, true, request, true, PortletID.CONFIGURATION.toString()); try { JSONArray array=new JSONArray(); for ( Map<String, Object> lic : LicenseUtil.getLicenseRepoList() ) { JSONObject obj = new JSONObject(); for ( Map.Entry<String, Object> entry : lic.entrySet() ) { String key = entry.getKey(); String value = (entry.getValue()==null) ? "" : String.valueOf(entry.getValue()); obj.put(key, value ); <START> if ( "serverid".equals(key) ) { <END> obj.put("serverid", LicenseUtil.getDisplayServerId(value) ); obj.put( "fullserverid", value ); } else if ( "id".equals(key) ) { obj.put( "idDisplay", LicenseUtil.getDisplaySerial(value) ); } } array.put( obj ); } return Response.ok(array.toString(), MediaType.APPLICATION_JSON_TYPE).build(); } catch(Exception ex) { Logger.error(this, "can't get all license on repo", ex); return Response.serverError().build(); } }</code><technical_language>![CRITICAL](<LINK_0> 'Severity: CRITICAL') Define a constant instead of duplicating this literal "serverid" 3 times. [![rule](<LINK_1>](<LINK_2></technical_language>

Target:
public Response getAll(@Context HttpServletRequest request, @PathParam("params") String params) { webResource.init(params, true, request, true, PortletID.CONFIGURATION.toString()); try { JSONArray array=new JSONArray(); for ( Map<String, Object> lic : LicenseUtil.getLicenseRepoList() ) { JSONObject obj = new JSONObject(); for ( Map.Entry<String, Object> entry : lic.entrySet() ) { String key = entry.getKey(); String value = (entry.getValue()==null) ? "" : String.valueOf(entry.getValue()); obj.put(key, value ); if ( SERVER_ID.equals(key) ) { obj.put(SERVER_ID, LicenseUtil.getDisplayServerId(value) ); obj.put( "fullserverid", value ); } else if ( "id".equals(key) ) { obj.put( "idDisplay", LicenseUtil.getDisplaySerial(value) ); } } array.put( obj ); } return Response.ok(array.toString(), MediaType.APPLICATION_JSON_TYPE).build(); } catch(Exception ex) { Logger.error(this, "can't get all license on repo", ex); return Response.serverError().build(); } }
Source:
<code>public void shouldThrowTopologyExceptionIfStoreNameExceedsMaxAllowedLength() { final StringBuffer invalidStoreNameBuffer = new StringBuffer(); final int maxNameLength = Named.MAX_NAME_LENGTH; for (int i = 0; i < maxNameLength + 1; i++) { invalidStoreNameBuffer.append('a'); } <START> Materialized.as(invalidStoreNameBuffer.toString()); <END> }</code><technical_language>above: assertThrows verify error message</technical_language>

Target:
public void shouldThrowTopologyExceptionIfStoreNameExceedsMaxAllowedLength() { final StringBuffer invalidStoreNameBuffer = new StringBuffer(); final int maxNameLength = 249; for (int i = 0; i < maxNameLength + 1; i++) { invalidStoreNameBuffer.append('a'); } final String invalidStoreName = invalidStoreNameBuffer.toString(); final TopologyException e = assertThrows(TopologyException.class, () -> Materialized.as(invalidStoreName)); assertEquals(e.getMessage(), "Invalid topology: Name is illegal, it can't be longer than " + maxNameLength + " characters, name: " + invalidStoreName); }
Source:
<code>public String getLoginStatusString() { switch (userInfo.getStatus()) { case NOT_RETRIEVED: <START> return cgeoapplication.getInstance().getString(R.string.init_login_popup_working); <END> case SUCCESSFUL: return cgeoapplication.getInstance().getString(R.string.init_login_popup_ok); case FAILED: return cgeoapplication.getInstance().getString(R.string.init_login_popup_failed); case NOT_SUPPORTED: return cgeoapplication.getInstance().getString(R.string.init_login_popup_not_authorized); default: return "Error"; } }</code><technical_language>I suggest move strings UserInfoStatus enum (like do for cache sizes similar enums). forced compiler strings enum entries in sync default case of this switch claus</technical_language>

Target:
public String getLoginStatusString() { return cgeoapplication.getInstance().getString(userInfo.getStatus().resId); }
Source:
<code><START> public static Date getGmtDate() { <END> final SimpleDateFormat dateFormatGmt = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss"); dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT")); final SimpleDateFormat dateFormatLocal = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss"); try { return dateFormatLocal.parse(dateFormatGmt.format(new Date())); } catch (final ParseException e) { LOGGER.error("error getting Gmt date " + e); throw new RuntimeException(e.getMessage()); } }</code><technical_language>In Java8 this done in a simpler way: Date date = new Date(); TimeZone.setDefault(TimeZone.getTimeZone("GMT")); Calendar cal = Calendar.getInstance(TimeZone.getDefault()); date = cal.getTime();</technical_language>

Target:
public static Date getGmtDate() { TimeZone.setDefault(TimeZone.getTimeZone("GMT")); final Calendar cal = Calendar.getInstance(TimeZone.getDefault()); return cal.getTime(); }
Source:
<code>private void maintenance() { ConfirmationModel model = new ConfirmationModel(); model.setTitle(ConstantsManager.getInstance().getConstants().maintenanceStorageDomainsTitle()); model.setMessage(ConstantsManager.getInstance().getConstants().areYouSureYouWantToPlaceFollowingStorageDomainsIntoMaintenanceModeMsg()); model.setHashName("maintenance_storage_domain"); setWindow(model); <START> model.getLatch().setEntity(false); <END> ArrayList<String> items = new ArrayList<String>(); for (Object selected : getSelectedItems()) { items.add(((StorageDomain) selected).getName()); } model.setItems(items); UICommand maintenance = new UICommand("OnMaintenance", this); maintenance.setTitle(ConstantsManager.getInstance().getConstants().ok()); maintenance.setIsDefault(true); model.getCommands().add(maintenance); UICommand cancel = new UICommand("Cancel", this); cancel.setTitle(ConstantsManager.getInstance().getConstants().cancel()); cancel.setIsCancel(true); model.getCommands().add(cancel); }</code><technical_language>do need a latch in dialog</technical_language>

Target:
private void maintenance() { ConfirmationModel model = new ConfirmationModel(); model.setTitle(ConstantsManager.getInstance().getConstants().maintenanceStorageDomainsTitle()); model.setMessage(ConstantsManager.getInstance().getConstants().areYouSureYouWantToPlaceFollowingStorageDomainsIntoMaintenanceModeMsg()); model.setHashName("maintenance_storage_domain"); setWindow(model); ArrayList<String> items = new ArrayList<String>(); for (Object selected : getSelectedItems()) { items.add(((StorageDomain) selected).getName()); } model.setItems(items); UICommand maintenance = new UICommand("OnMaintenance", this); maintenance.setTitle(ConstantsManager.getInstance().getConstants().ok()); maintenance.setIsDefault(true); model.getCommands().add(maintenance); UICommand cancel = new UICommand("Cancel", this); cancel.setTitle(ConstantsManager.getInstance().getConstants().cancel()); cancel.setIsCancel(true); model.getCommands().add(cancel); }
Source:
<code>private void addIAMFilters(WebAppContext webApp) { String context = webApp.getContextPath(); if ((context.equals("/studio") || context.equals("/scheduler") || context.equals("/rm") || context.equals("/automation-dashboard"))) { webApp.setInitParameter("org.eclipse.jetty.servlet.SessionIdPathParameterName", "none"); webApp.setInitParameter("configurationStrategy", "SYSTEM_PROPERTIES"); webApp.addEventListener(new org.jasig.cas.client.session.SingleSignOutHttpSessionListener()); webApp.addFilter(org.jasig.cas.client.session.SingleSignOutFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST, DispatcherType.INCLUDE, DispatcherType.FORWARD, DispatcherType.ASYNC, DispatcherType.ERROR)); webApp.addFilter(org.jasig.cas.client.authentication.AuthenticationFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST, DispatcherType.INCLUDE, DispatcherType.FORWARD, DispatcherType.ASYNC, DispatcherType.ERROR)); webApp.addFilter(org.jasig.cas.client.validation.Cas30ProxyReceivingTicketValidationFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST, DispatcherType.INCLUDE, DispatcherType.FORWARD, DispatcherType.ASYNC, DispatcherType.ERROR)); webApp.addFilter(org.jasig.cas.client.util.HttpServletRequestWrapperFilter.class, "/*", <START> EnumSet.of(DispatcherType.REQUEST, <END> DispatcherType.INCLUDE, DispatcherType.FORWARD, DispatcherType.ASYNC, DispatcherType.ERROR)); logger.debug("IAM authentication and authorization filters added to web application " + webApp.getContextPath()); } }</code><technical_language>EnumSet repeat 4 times. re-use</technical_language>

Target:
private void addIAMFilters(WebAppContext webApp) { String context = webApp.getContextPath(); if ((context.equals("/studio") || context.equals("/scheduler") || context.equals("/rm") || context.equals("/automation-dashboard"))) { webApp.setInitParameter("org.eclipse.jetty.servlet.SessionIdPathParameterName", "none"); webApp.setInitParameter("configurationStrategy", "SYSTEM_PROPERTIES"); webApp.addEventListener(new org.jasig.cas.client.session.SingleSignOutHttpSessionListener()); webApp.addFilter(org.jasig.cas.client.session.SingleSignOutFilter.class, IAM_FILTERS_CONTEXT_PATH, IAM_FILTERS_DISPATCHERS); webApp.addFilter(org.jasig.cas.client.authentication.AuthenticationFilter.class, IAM_FILTERS_CONTEXT_PATH, IAM_FILTERS_DISPATCHERS); webApp.addFilter(org.jasig.cas.client.validation.Cas30ProxyReceivingTicketValidationFilter.class, IAM_FILTERS_CONTEXT_PATH, IAM_FILTERS_DISPATCHERS); webApp.addFilter(org.jasig.cas.client.util.HttpServletRequestWrapperFilter.class, IAM_FILTERS_CONTEXT_PATH, IAM_FILTERS_DISPATCHERS); logger.debug("IAM authentication and authorization filters added to web application " + webApp.getContextPath()); } }
Source:
<code>public void refresh(final KuzzleOptions options, final KuzzleResponseListener<KuzzleDataMapping> listener) { JSONObject data = new JSONObject(); try { this.kuzzle.addHeaders(data, this.headers); this.kuzzle.query(this.dataCollection.makeQueryArgs("admin", "getMapping"), data, options, new OnQueryDoneListener() { @Override public void onSuccess(JSONObject args) { try { <START> KuzzleDataMapping newMapping = new KuzzleDataMapping(KuzzleDataMapping.this.dataCollection); <END> newMapping.headers = KuzzleDataMapping.this.headers; newMapping.kuzzle = KuzzleDataMapping.this.kuzzle; newMapping.collection = KuzzleDataMapping.this.collection; newMapping.dataCollection = KuzzleDataMapping.this.dataCollection; newMapping.mapping = KuzzleDataMapping.this.mapping; if (!args.isNull(KuzzleDataMapping.this.kuzzle.getDefaultIndex())) { JSONObject mappings = args.getJSONObject(KuzzleDataMapping.this.kuzzle.getDefaultIndex()).getJSONObject("mappings"); if (!mappings.isNull(KuzzleDataMapping.this.collection)) newMapping.mapping = mappings.getJSONObject(KuzzleDataMapping.this.collection); if (listener != null) listener.onSuccess(newMapping); } } catch (JSONException e) { throw new RuntimeException(e); } } @Override public void onError(JSONObject object) { if (listener != null) listener.onError(object); } }); } catch (JSONException e) { throw new RuntimeException(e); } }</code><technical_language>Suggestion: easier KuzzleDataMapping(KuzzleDataCollection, JSONObject) constructor? Moreover, I next 5 lines of code duplicating constructor behavior. edit: yet, a copy constructor useful</technical_language>

Target:
public void refresh(final KuzzleOptions options, final KuzzleResponseListener<KuzzleDataMapping> listener) { JSONObject data = new JSONObject(); try { this.kuzzle.addHeaders(data, this.headers); this.kuzzle.query(this.dataCollection.makeQueryArgs("admin", "getMapping"), data, options, new OnQueryDoneListener() { @Override public void onSuccess(JSONObject args) { try { KuzzleDataMapping newMapping = new KuzzleDataMapping(KuzzleDataMapping.this); if (!args.isNull(KuzzleDataMapping.this.kuzzle.getDefaultIndex())) { JSONObject mappings = args.getJSONObject(KuzzleDataMapping.this.kuzzle.getDefaultIndex()).getJSONObject("mappings"); if (!mappings.isNull(KuzzleDataMapping.this.collection)) newMapping.mapping = mappings.getJSONObject(KuzzleDataMapping.this.collection); if (listener != null) listener.onSuccess(newMapping); } } catch (JSONException e) { throw new RuntimeException(e); } } @Override public void onError(JSONObject object) { if (listener != null) listener.onError(object); } }); } catch (JSONException e) { throw new RuntimeException(e); } }
Source:
<code>public int compare(String o1, String o2) { int a = -1; int b = -1; for (int i = 0; i < Scenario.S_NUM; i++) { if (Scenario.getStatusName(i).equals(o1)) { a = i; <START> } else if (Scenario.getStatusName(i).equals(o2)) { <END> b = i; } } switch (a) { case 3: a = 5; break; case 5: a = 3; break; } switch (b) { case 3: b = 5; break; case 5: b = 3; break; } return a - b; }</code><technical_language>o1 o2 equal</technical_language>

Target:
public int compare(String o1, String o2) { if (Objects.equals(o1, o2)) { return 0; } int a = getStatusInt(o1); int b = getStatusInt(o2); return a - b; }
Source:
<code>public static RegistrationPortType getRegistrationPort(final W3CEndpointReference endpointReference, String action, String messageID) { final RegistrationService service = getRegistrationService(); final WSCEnvironmentBean wscEnvironmentBean = XTSPropertyManager.getWSCEnvironmentBean(); final RegistrationPortType port = PrivilegedServiceHelper.getInstance().getPort(service, endpointReference, RegistrationPortType.class, new AddressingFeature(true, true)); BindingProvider bindingProvider = (BindingProvider)port; Map<String, Object> requestContext = bindingProvider.getRequestContext(); MAP map; if (WSCEnvironmentBean.SECURE_AYNCH_REQUEST.equals(wscEnvironmentBean.getUseAsynchronousRequest())) { String responseService = PrivilegedServiceRegistryFactory.getInstance().getServiceRegistry() .getSecureServiceURI(CoordinationConstants.REGISTRATION_RESPONSE_SERVICE_NAME); String faultService = PrivilegedServiceRegistryFactory.getInstance().getServiceRegistry() .getSecureServiceURI(CoordinationConstants.SOAP_FAULT_SERVICE_NAME); WSCLogger.logger.tracev("WSCOORClient Using secure endpoints {0} {1}", responseService, faultService); map = AddressingHelper.outboundMap(requestContext, responseService, faultService); <START> } else if (WSCEnvironmentBean.PLAIN_AYNCH_REQUEST.equals(wscEnvironmentBean.getUseAsynchronousRequest())) { <END> String responseService = PrivilegedServiceRegistryFactory.getInstance().getServiceRegistry() .getServiceURI(CoordinationConstants.REGISTRATION_RESPONSE_SERVICE_NAME); String faultService = PrivilegedServiceRegistryFactory.getInstance().getServiceRegistry() .getServiceURI(CoordinationConstants.SOAP_FAULT_SERVICE_NAME); WSCLogger.logger.tracev("WSCOORClient Using plain endpoints {0} {1}", responseService, faultService); map = AddressingHelper.outboundMap(requestContext, responseService, faultService); } else { WSCLogger.logger.tracev("WSCOORClient Using anonymous endpoints"); map = AddressingHelper.outboundMap(requestContext); } AddressingHelper.installActionMessageID(map, action, messageID); AddressingHelper.configureRequestContext(requestContext, map.getTo(), action); return port; }</code><technical_language>this is feeling: is a lot a new code in comparison one. considering some method this logic</technical_language>

Target:
public static RegistrationPortType getRegistrationPort(final W3CEndpointReference endpointReference, String action, String messageID) { final RegistrationService service = getRegistrationService(); final RegistrationPortType port = PrivilegedServiceHelper.getInstance().getPort(service, endpointReference, RegistrationPortType.class, new AddressingFeature(true, true)); BindingProvider bindingProvider = (BindingProvider)port; Map<String, Object> requestContext = bindingProvider.getRequestContext(); MAP map = getRegistrationPortMap(requestContext); AddressingHelper.installActionMessageID(map, action, messageID); AddressingHelper.configureRequestContext(requestContext, map.getTo(), action); return port; }
Source:
<code><START> private Path savePOM() throws IOException, XmlPullParserException { <END> savePOM(path, content, metadata); return path; }</code><technical_language>reason return Path here. This helper is private return anywhere.</technical_language>

Target:
private void savePOM() throws IOException, XmlPullParserException { savePOM(pomPath, pom, metadata); }
Source:
<code>private void notifyAllListeners(String remoteServerName){ <START> RemoteServerState remoteServerState = actualStateMap.get(remoteServerName); <END> for (RemoteServerStateListener listener : listeners) { logger.info("Remote server has new state {}", remoteServerName, remoteServerState); listener.onRemoteServerStateChange(remoteServerName, remoteServerState); } }</code><technical_language>final</technical_language>

Target:
private void notifyAllListeners(String remoteServerName){ final RemoteServerState remoteServerState = actualStateMap.get(remoteServerName); for (RemoteServerStateListener listener : listeners) { logger.info("Remote server has new state {}", remoteServerName, remoteServerState); listener.onRemoteServerStateChange(remoteServerName, remoteServerState); } }
Source:
<code><START> public VersionOrdinal getVersionObject() { <END> return memberIdentifier.getVersionObject(); }</code><technical_language>This continue return a Version, a VersionOrdinal. a method for ordinal</technical_language>

Target:
public Version getVersionObject() { return Version.fromOrdinalNoThrow(getVersionOrdinalObject().ordinal(), false); }