auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private BlobReadOptions getDeletedBlobReadOptions(IndexValue value, StoreKey key, ConcurrentSkipListMap<Offset, IndexSegment> indexSegments) throws StoreException { BlobReadOptions readOptions; IndexValue putValue = findKey(key, new FileSpan(getStartOffset(indexSegments), value.getOffset()), EnumSet.of(IndexEntryType.PUT), indexSegments); if (putValue != null) { readOptions = new BlobReadOptions(log, putValue.getOffset(), new MessageInfo(key, putValue.getSize(), true, value.isFlagSet(IndexValue.Flags.Ttl_Update_Index), value.getExpiresAtMs(), putValue.getAccountId(), putValue.getContainerId(), putValue.getOperationTimeInMs())); } else { throw new StoreException("Did not find PUT index entry for key [" + key <START> + "] and the the original offset in value of the DELETE entry was [" + value.getOriginalMessageOffset() + "]", <END> StoreErrorCodes.ID_Deleted); } return readOptions; }</code><technical_language>I error code is ID_Deleted ID_Not_Found</technical_language>

Target:
private BlobReadOptions getDeletedBlobReadOptions(IndexValue value, StoreKey key, ConcurrentSkipListMap<Offset, IndexSegment> indexSegments) throws StoreException { BlobReadOptions readOptions; IndexValue putValue = findKey(key, new FileSpan(getStartOffset(indexSegments), value.getOffset()), EnumSet.of(IndexEntryType.PUT), indexSegments); if (putValue != null) { readOptions = new BlobReadOptions(log, putValue.getOffset(), new MessageInfo(key, putValue.getSize(), true, value.isTTLUpdate(), value.getExpiresAtMs(), putValue.getAccountId(), putValue.getContainerId(), putValue.getOperationTimeInMs())); } else { throw new StoreException("Did not find PUT index entry for key [" + key + "] and the the original offset in value of the DELETE entry was [" + value.getOriginalMessageOffset() + "]", StoreErrorCodes.ID_Deleted); } return readOptions; }
Source:
<code>public void onViewStateRestored(Bundle savedInstanceState) { super.onViewStateRestored(savedInstanceState); if (savedInstanceState != null) { FormFieldsWrapper formFieldsWrapper = (FormFieldsWrapper) savedInstanceState.getSerializable(ApplicationConstants.BundleKeys.FORM_FIELDS_BUNDLE); inputFields = formFieldsWrapper.getInputFields(); for(InputField field:inputFields){ <START> if(field.getIsRed()==true){ <END> RangeEditText ed = (RangeEditText) getActivity().findViewById(field.getId()); ed.setTextColor(ContextCompat.getColor(OpenMRS.getInstance(), R.color.red)); } } selectOneFields = formFieldsWrapper.getSelectOneFields(); } }</code><technical_language>==true is redundant, try avoid comparing boolean true :)</technical_language>

Target:
public void onViewStateRestored(Bundle savedInstanceState) { super.onViewStateRestored(savedInstanceState); if (savedInstanceState != null) { FormFieldsWrapper formFieldsWrapper = (FormFieldsWrapper) savedInstanceState.getSerializable(ApplicationConstants.BundleKeys.FORM_FIELDS_BUNDLE); inputFields = formFieldsWrapper.getInputFields(); for(InputField field:inputFields){ if(field.isRed()){ RangeEditText ed = (RangeEditText) getActivity().findViewById(field.getId()); ed.setTextColor(ContextCompat.getColor(OpenMRS.getInstance(), R.color.red)); } } selectOneFields = formFieldsWrapper.getSelectOneFields(); } }
Source:
<code>public Object parseExpressionNoContext(String input) throws ParseException { InterpreterState state = getLocalThreadInterpreter(); GenContext genContext = Globals.getGenContext(state); try { <START> TypedAST typAST = TestUtil.getNewAST(input.trim() + "\n", "TSL Parse"); <END> if (typAST instanceof Script) { Script script = (Script) typAST; List<ImportDeclaration> importDecls = new ArrayList<>(); importDecls.addAll(script.getImports()); importDecls.addAll(script.getRequires()); List<TypedModuleSpec> dependencies = getDependencies(importDecls, genContext); Expression expr = (Expression) (script.generateIL(genContext, Util.unitType(), dependencies)); expr = state.getResolver().wrap(expr, dependencies); return expr; } else { return parseExpression(input, genContext); } } catch (ParseException e) { System.err.println("Error when running parseExpression on input \"" + input + "\""); throw e; } }</code><technical_language>Please change parameter of getNewAST() function more appropriate</technical_language>

Target:
public IExpr parseExpressionNoContext(String input) throws ParseException { InterpreterState state = getLocalThreadInterpreter(); GenContext genContext = Globals.getGenContext(state); try { TypedAST typAST = TestUtil.getNewAST(input.trim() + "\n", "Parse expressions"); if (typAST instanceof Script) { Script script = (Script) typAST; List<ImportDeclaration> importDecls = new ArrayList<>(); importDecls.addAll(script.getImports()); importDecls.addAll(script.getRequires()); List<TypedModuleSpec> dependencies = getDependencies(importDecls, genContext); Expression expr = (Expression) (script.generateIL(genContext, Util.unitType(), dependencies)); expr = state.getResolver().wrap(expr, dependencies); return expr; } else { return parseExpression(input, genContext); } } catch (ParseException e) { System.err.println("Error when running parseExpression on input \"" + input + "\""); throw e; } }
Source:
<code>public ArrayAggregationState createGroupedState() { if (mode == NEW) { return new GroupArrayAggregationState(type); } if (mode == LEGACY) { return new LegacyArrayAggregationGroupState(type); } <START> throw new PrestoException(FUNCTION_IMPLEMENTATION_ERROR, format("Unexpected group enum type %s", mode)); <END> }</code><technical_language>switch instead of ifs</technical_language>

Target:
public ArrayAggregationState createGroupedState() { switch (mode) { case NEW: return new GroupArrayAggregationState(type); case LEGACY: return new LegacyArrayAggregationGroupState(type); default: throw new PrestoException(FUNCTION_IMPLEMENTATION_ERROR, format("Unexpected group enum type %s", mode)); } }
Source:
<code>public String loginPageURL(Context context, HttpServletRequest request, HttpServletResponse response) { boolean lazySession = configurationService.getBooleanProperty("authentication-shibboleth.lazysession", false); if ( lazySession ) { String shibURL = configurationService.getProperty("authentication-shibboleth.lazysession.loginurl"); boolean forceHTTPS = configurationService.getBooleanProperty("authentication-shibboleth.lazysession.secure",true); if (shibURL == null || shibURL.length() == 0) { shibURL = "/Shibboleth.sso/Login"; } shibURL = shibURL.trim(); String host = request.getServerName(); int port = request.getServerPort(); String contextPath = request.getContextPath(); String redirectUrl = null; if (request.getHeader("Referer") != null && StringUtils.isNotBlank(request.getHeader("Referer"))) { redirectUrl = request.getHeader("Referer"); } else if (request.getHeader("X-Requested-With") != null && StringUtils.isNotBlank(request.getHeader("X-Requested-With"))) { redirectUrl = request.getHeader("X-Requested-With"); } <START> String returnURL = ConfigurationManager.getProperty("dspace.baseUrl") + "/api/authn/shibboleth" <END> + ((redirectUrl != null) ? "?redirectUrl=" + redirectUrl : ""); try { shibURL += "?target=" + URLEncoder.encode(returnURL, "UTF-8"); } catch (UnsupportedEncodingException uee) { log.error("Unable to generate lazysession authentication",uee); } log.debug("Redirecting user to Shibboleth initiator: " + shibURL); return response.encodeRedirectURL(shibURL); } else { return response.encodeRedirectURL(request.getContextPath() + "/shibboleth-login"); } }</code><technical_language>Please note this property changed to: dspace.server.url</technical_language>

Target:
public String loginPageURL(Context context, HttpServletRequest request, HttpServletResponse response) { boolean lazySession = configurationService.getBooleanProperty("authentication-shibboleth.lazysession", false); if ( lazySession ) { String shibURL = getShibURL(request); String redirectUrl = null; if (request.getHeader("Referer") != null && StringUtils.isNotBlank(request.getHeader("Referer"))) { redirectUrl = request.getHeader("Referer"); } else if (request.getHeader("X-Requested-With") != null && StringUtils.isNotBlank(request.getHeader("X-Requested-With"))) { redirectUrl = request.getHeader("X-Requested-With"); } String returnURL = configurationService.getProperty("dspace.server.url") + "/api/authn/shibboleth" + ((redirectUrl != null) ? "?redirectUrl=" + redirectUrl : ""); try { shibURL += "?target=" + URLEncoder.encode(returnURL, "UTF-8"); } catch (UnsupportedEncodingException uee) { log.error("Unable to generate lazysession authentication",uee); } log.debug("Redirecting user to Shibboleth initiator: " + shibURL); return response.encodeRedirectURL(shibURL); } else { return response.encodeRedirectURL(request.getContextPath() + "/shibboleth-login"); } }
Source:
<code>public void verifyNoSpotlights() { for (WebElement spotlight: spotlights) { if (spotlight.isDisplayed()) { PageObjectLogging.log("SpotlightVisible", "Spotlight visible, should be hidden", false); <START> throw new NoSuchElementException("Spotlight visible, should be hidden"); <END> } } PageObjectLogging.log("SpotlightsHidden", "Spotlights are hidden", true); }</code><technical_language>Consider throwing a exception. Throwing a NoSuchElementException is a bit misleading element is found</technical_language>

Target:
public void verifyNoSpotlights() { for (WebElement spotlight: spotlights) { if (spotlight.isDisplayed()) { PageObjectLogging.log("SpotlightVisible", "Spotlight visible, should be hidden", false); throw new WebDriverException("Spotlight visible, should be hidden"); } } PageObjectLogging.log("SpotlightsHidden", "Spotlights are hidden", true); }
Source:
<code>public void setExcludedPaths(Collection<String> paths) { <START> paths.forEach(path -> excludePath(path)); <END> }</code><technical_language>if this method remove previous values? is called set add... :)</technical_language>

Target:
public void setExcludedPaths(Collection<String> paths) { excludedPaths.clear(); paths.forEach(path -> excludePath(path)); }
Source:
<code>private FilterDef interpretFullTextFilterDef(FullTextFilterDef defAnn) { FilterDef filterDef = new FilterDef( defAnn ); if ( filterDef.getImpl().equals( ShardSensitiveOnlyFilter.class ) ) { return filterDef; } try { ClassLoaderHelper.untypedInstanceFromClass( filterDef.getImpl(), "filter definition" ); } <START> catch (Exception e) { <END> throw new SearchException( "Unable to create Filter class: " + filterDef.getImpl().getName(), e ); } for ( Method method : filterDef.getImpl().getMethods() ) { if ( method.isAnnotationPresent( Factory.class ) ) { if ( filterDef.getFactoryMethod() != null ) { throw new SearchException( "Multiple @Factory methods found" + defAnn.name() + ": " + filterDef.getImpl().getName() + "." + method.getName() ); } ReflectionHelper.setAccessible( method ); filterDef.setFactoryMethod( method ); } if ( method.isAnnotationPresent( Key.class ) ) { if ( filterDef.getKeyMethod() != null ) { throw new SearchException( "Multiple @Key methods found" + defAnn.name() + ": " + filterDef.getImpl().getName() + "." + method.getName() ); } ReflectionHelper.setAccessible( method ); filterDef.setKeyMethod( method ); } String name = method.getName(); if ( name.startsWith( "set" ) && method.getParameterTypes().length == 1 ) { filterDef.addSetter( Introspector.decapitalize( name.substring( 3 ) ), method ); } } return filterDef; }</code><technical_language>This catch RuntimeException: reason catch Exception if checked exception is thrown, this a compile-time error if add a checked exception ClassLoaderHelper.untypedInstanceFromClass</technical_language>

Target:
private FilterDef interpretFullTextFilterDef(FullTextFilterDef defAnn) { FilterDef filterDef = new FilterDef( defAnn ); if ( filterDef.getImpl().equals( ShardSensitiveOnlyFilter.class ) ) { return filterDef; } try { ClassLoaderHelper.untypedInstanceFromClass( filterDef.getImpl(), "filter definition" ); } catch (RuntimeException e) { throw new SearchException( "Unable to create Filter class: " + filterDef.getImpl().getName(), e ); } for ( Method method : filterDef.getImpl().getMethods() ) { if ( method.isAnnotationPresent( Factory.class ) ) { if ( filterDef.getFactoryMethod() != null ) { throw new SearchException( "Multiple @Factory methods found" + defAnn.name() + ": " + filterDef.getImpl().getName() + "." + method.getName() ); } ReflectionHelper.setAccessible( method ); filterDef.setFactoryMethod( method ); } if ( method.isAnnotationPresent( Key.class ) ) { if ( filterDef.getKeyMethod() != null ) { throw new SearchException( "Multiple @Key methods found" + defAnn.name() + ": " + filterDef.getImpl().getName() + "." + method.getName() ); } ReflectionHelper.setAccessible( method ); filterDef.setKeyMethod( method ); } String name = method.getName(); if ( name.startsWith( "set" ) && method.getParameterTypes().length == 1 ) { filterDef.addSetter( Introspector.decapitalize( name.substring( 3 ) ), method ); } } return filterDef; }
Source:
<code>protected void checkOperation(String operationId) { if (StringUtils.isBlank(operationId)) { log.warn("No operationId provided skipping command: " + getCurrentCommand().getId()); return; } if (!service.hasOperation(operationId)) { log.warn("Operation " + operationId + " not found, skipping command: " + getCurrentCommand().getId()); return; } try { OperationType op = service.getOperation(operationId); inputType = op.getInputType(); if (inputType == null || DOC_INPUT_TYPE.equals(inputType)) { inputType = DOC_INPUT_TYPE; } else if (DOCS_INPUT_TYPE.equals(inputType)) { inputType = DOCS_INPUT_TYPE; } else { log.warn(String.format("Unsupported operation input type %s for command: %s", inputType, <START> getCurrentCommand().getId())); <END> return; } } catch (OperationNotFoundException e) { log.warn(String.format("Operation '%s' not found, skipping command: %s", operationId, getCurrentCommand().getId())); return; } this.operationId = operationId; }</code><technical_language>Is needed called service.hasOperation(operationId)</technical_language>

Target:
protected void checkOperation(String operationId) { if (StringUtils.isBlank(operationId)) { log.warn("No operationId provided skipping command: " + getCurrentCommand().getId()); return; } try { OperationType op = service.getOperation(operationId); inputType = op.getInputType(); if (inputType == null || DOC_INPUT_TYPE.equals(inputType)) { inputType = DOC_INPUT_TYPE; } else if (DOCS_INPUT_TYPE.equals(inputType)) { inputType = DOCS_INPUT_TYPE; } else { log.warn(String.format("Unsupported operation input type %s for command: %s", inputType, getCurrentCommand().getId())); return; } } catch (OperationNotFoundException e) { log.warn(String.format("Operation '%s' not found, skipping command: %s", operationId, getCurrentCommand().getId())); return; } this.operationId = operationId; }
Source:
<code>public void discard() { <START> synchronized (lock) { if (stateDiscarded) { Preconditions.checkState(discarded, "Checkpoint should be disposed before being discarded"); return; } else { stateDiscarded = true; } } try { <END> StateUtil.bestEffortDiscardAllStateObjects(operatorStates.values()); targetLocation.disposeOnFailure(); } catch (Throwable t) { LOG.warn( "Could not properly dispose the private states in the pending checkpoint of job {}.", checkpointId, jobId, t); } finally { operatorStates.clear(); } }</code><technical_language>do need this check now? I tell, previously needed</technical_language>

Target:
public void discard() { synchronized (lock) { if (discarded) { Preconditions.checkState(disposed, "Checkpoint should be disposed before being discarded"); return; } else { discarded = true; } } try { StateUtil.bestEffortDiscardAllStateObjects(operatorStates.values()); targetLocation.disposeOnFailure(); } catch (Throwable t) { LOG.warn( "Could not properly dispose the private states in the pending checkpoint of job {}.", checkpointId, jobId, t); } finally { operatorStates.clear(); } }
Source:
<code>protected void binary(byte[] payload, int offset, int len) { LOGGER.finest(() -> "reading block of length " + len + " from " + agent); try { transport.receive(ByteBuffer.wrap(payload, offset, len)); <START> } catch (IOException e) { error(e); } catch (InterruptedException e) { <END> error(e); } }</code><technical_language>suggestion } catch (IOException | InterruptedException e) {</technical_language>

Target:
protected void binary(byte[] payload, int offset, int len) { LOGGER.finest(() -> "reading block of length " + len + " from " + agent); try { transport.receive(ByteBuffer.wrap(payload, offset, len)); } catch (IOException | InterruptedException e) { error(e); } }
Source:
<code>public void instrumentForCoverage() { checkState(moduleGraph != null, "No inputs. Did you call init() or initModules()?"); checkState(!hasErrors()); runInCompilerThread( () -> { checkState(options.getInstrumentForCoverageOnly()); checkState(!hasErrors()); if(options.instrumentForCoverageOption != InstrumentOption.NONE) { instrumentForCoverageInternal(options.instrumentForCoverageOption); <START> }else if(options.instrumentForCoverage){ <END> instrumentForCoverageInternal(InstrumentOption.LINE_ONLY); }else if(options.instrumentForCoverage && options.instrumentBranchCoverage){ instrumentForCoverageInternal(InstrumentOption.BRANCH_ONLY); } return null; }); }</code><technical_language>add spaces } else</technical_language>

Target:
public void instrumentForCoverage() { checkState(moduleGraph != null, "No inputs. Did you call init() or initModules()?"); checkState(!hasErrors()); runInCompilerThread( () -> { checkState(options.getInstrumentForCoverageOnly()); checkState(!hasErrors()); if (options.getInstrumentForCoverageOption() != InstrumentOption.NONE) { instrumentForCoverageInternal(options.getInstrumentForCoverageOption()); } else if (options.instrumentForCoverage) { instrumentForCoverageInternal(InstrumentOption.LINE_ONLY); } else if (options.instrumentForCoverage && options.instrumentBranchCoverage) { instrumentForCoverageInternal(InstrumentOption.BRANCH_ONLY); } return null; }); }
Source:
<code>protected <T> Observable buildUseCaseObservable(Map<String, T> parameters) { if (parameters == null || parameters.get(PARAM_USER) == null) { return Observable.error(new IllegalArgumentException("missing user")); } final User user = (User) parameters.get(PARAM_USER); return userRepository.getSelectedUser() .concatMap(new Function<Long, Observable<Boolean>>() { @Override public Observable<Boolean> apply(Long selectedUserId) { <START> if (selectedUserId == user.getId()) { <END> return userRepository.clearSelectedUser().concatMap( new Function<Boolean, Observable<Boolean>>() { @Override public Observable<Boolean> apply(Boolean aBoolean) { return deleteUser(user); } }); } else { return deleteUser(user); } } }); }</code><technical_language>selectedUserId.equals() instead? i.e. objects primitives</technical_language>

Target:
protected <T> Observable buildUseCaseObservable(Map<String, T> parameters) { if (parameters == null || parameters.get(PARAM_USER) == null) { return Observable.error(new IllegalArgumentException("missing user")); } final User user = (User) parameters.get(PARAM_USER); return userRepository.getSelectedUser() .concatMap(new Function<Long, Observable<Boolean>>() { @Override public Observable<Boolean> apply(Long selectedUserId) { if (selectedUserId.equals(user.getId())) { return userRepository.clearSelectedUser().concatMap( new Function<Boolean, Observable<Boolean>>() { @Override public Observable<Boolean> apply(Boolean aBoolean) { return deleteUser(user); } }); } else { return deleteUser(user); } } }); }
Source:
<code><START> private boolean isChimericReadPair(final QuerySortedReadPairIteratorUtil.ReadPair readPair, final int minimumMappingQuality) { <END> return (!readPair.read1.getReadUnmappedFlag() && !readPair.read2.getReadUnmappedFlag() && readPair.read1.getMappingQuality() >= minimumMappingQuality && readPair.read2.getMappingQuality() >= minimumMappingQuality && (Math.abs(readPair.read1.getInferredInsertSize()) > MAX_INSERT_SIZE || !readPair.read1.getReferenceIndex().equals(readPair.read2.getReferenceIndex()) || SamPairUtil.getPairOrientation(readPair.read1) != SamPairUtil.PairOrientation.FR || readPair.read1.getAttribute("SA") != null)); }</code><technical_language>@nh13 similar in CollectAlignmentSummaryMetrics good extract this a re-usable spot a reasonable fixed definition of Chimeras somewhere. I imagine: java public class ChimeraUtil { public static int DEFAULT_INSERT_SIZE_LIMIT = 100000; public static int DEFAULT_MAPQ_LIMIT = 20; public Set<PairOrientation> DEFAULT_EXPECTED_ORIENTATIONS = EnumSet.of(PairOrientation.FR); public void isChimeric(final SAMRecord rec); public void isChimeric(final SAMRecord r1, final SAMRecord r2); }</technical_language>

Target:
private boolean isChimericReadPair(final QuerySortedReadPairIteratorUtil.ReadPair readPair, final int minimumMappingQuality) { return (readPair.read1.getMappingQuality() >= minimumMappingQuality && readPair.read2.getMappingQuality() >= minimumMappingQuality && ChimeraUtil.isChimeric(readPair.read1, readPair.read2, ChimeraUtil.DEFAULT_INSERT_SIZE_LIMIT, ChimeraUtil.DEFAULT_EXPECTED_ORIENTATIONS)); }
Source:
<code>public static void cleanUp() throws IOException, SQLException { logger.info("Running with Hibernate " + org.hibernate.Version.getVersionString()); TestsUtil.clearSchema(); ScriptsBase sb = new ScriptsBase(); <START> sb.executeScriptRunner(DB_DDL_SCRIPTS_RESOURCE_PATH, false); <END> }</code><technical_language>methods static</technical_language>

Target:
public static void cleanUp() throws IOException, SQLException { logger.info("Running with Hibernate " + org.hibernate.Version.getVersionString()); TestsUtil.clearSchema(); executeScriptRunner(DB_DDL_SCRIPTS_RESOURCE_PATH, false); }
Source:
<code>public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); connectionServiceLocator = new ServiceLocator<ConnectionService>( this.getActivity(), ConnectionService.class, ConnectionServiceBinder.class); connectionServiceLocator.setOnBindListener(new ServiceLocator.IOnBindListener() { @Override public void onServiceBound() { setDisconnectDisbandVisibility(); } }); <START> NetworkFragment.this.adapter = new UserListAdapter(getActivity(), new UserList(), false ); <END> userListServiceLocator = new ServiceLocator<UserListService>( this.getActivity(), UserListService.class, UserListServiceBinder.class); userListServiceLocator.setOnBindListener(new ServiceLocator.IOnBindListener() { @Override public void onServiceBound() { NetworkFragment.this.adapter.updateUsers(getUserListFromService()); } }); registerReceivers(); }</code><technical_language>Is a reason include NetworkFragment this.adapter</technical_language>

Target:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); connectionServiceLocator = new ServiceLocator<ConnectionService>( this.getActivity(), ConnectionService.class, ConnectionServiceBinder.class); connectionServiceLocator.setOnBindListener(new ServiceLocator.IOnBindListener() { @Override public void onServiceBound() { setDisconnectDisbandVisibility(); } }); adapter = new UserListAdapter(getActivity(), new UserList(), false); userListServiceLocator = new ServiceLocator<UserListService>( this.getActivity(), UserListService.class, UserListServiceBinder.class); userListServiceLocator.setOnBindListener(new ServiceLocator.IOnBindListener() { @Override public void onServiceBound() { NetworkFragment.this.adapter.updateUsers(getUserListFromService()); } }); registerReceivers(); }
Source:
<code>public static String getIp() { if (null != cachedIpAddress) { return cachedIpAddress; } NetworkInterface networkInterface = findNetworkInterface(); <START> if (networkInterface != null) { <END> Enumeration<InetAddress> ipAddresses = networkInterface.getInetAddresses(); while (ipAddresses.hasMoreElements()) { InetAddress ipAddress = ipAddresses.nextElement(); if (isValidAddress(ipAddress)) { cachedIpAddress = ipAddress.getHostAddress(); return cachedIpAddress; } } } return null; }</code><technical_language>prefer null != xxx</technical_language>

Target:
public static String getIp() { if (null != cachedIpAddress) { return cachedIpAddress; } NetworkInterface networkInterface = findNetworkInterface(); if (null != networkInterface) { Enumeration<InetAddress> ipAddresses = networkInterface.getInetAddresses(); while (ipAddresses.hasMoreElements()) { InetAddress ipAddress = ipAddresses.nextElement(); if (isValidAddress(ipAddress)) { cachedIpAddress = ipAddress.getHostAddress(); return cachedIpAddress; } } } throw new HostException("ip is null"); }
Source:
<code>private Geometry onlyPolygon(Geometry result) { if ((result instanceof Polygon) || (result instanceof MultiPolygon)) return result; List polys = com.vividsolutions.jts.geom.util.PolygonExtracter.getPolygons(result); if (polys.size() == 0) return null; if (polys.size() == 1) <START> return (Polygon) polys.get(0); <END> return new MultiPolygon((Polygon[]) polys.toArray(new Polygon[polys.size()]), result.getFactory()); }</code><technical_language>More missing braces</technical_language>

Target:
private Geometry onlyPolygon(Geometry result) { if ((result instanceof Polygon) || (result instanceof MultiPolygon)) { return result; } List polys = com.vividsolutions.jts.geom.util.PolygonExtracter.getPolygons(result); if (polys.size() == 0) { return null; } if (polys.size() == 1) { return (Polygon) polys.get(0); } return new MultiPolygon((Polygon[]) polys.toArray(new Polygon[polys.size()]), result.getFactory()); }
Source:
<code>public boolean deleteEntityInTable(String tableName, ODataEntry entity) { String keyValue = entity.getValue(DOCUMENT_ID); <START> WriteResult delete = jongo.getCollection(tableName).remove(new ObjectId(keyValue)); <END> return delete.wasAcknowledged(); }</code><technical_language>meaningful names</technical_language>

Target:
public boolean deleteEntityInTable(String tableName, ODataEntry entity) throws ODataServiceFault { String documentId = entity.getValue(DOCUMENT_ID); WriteResult delete = jongo.getCollection(tableName).remove(new ObjectId(documentId)); int wasDeleted = delete.getN(); if (wasDeleted == 1) { return delete.wasAcknowledged(); } else { throw new ODataServiceFault("Document ID: " + documentId + " does not exist in " + "collection: " + tableName + "."); } }
Source:
<code>protected String getServiceEventActionCodeResponder() { <START> return DocSubmissionAuditTransformsConstants.EVENT_ACTION_CODE_RECIPIENT; <END> }</code><technical_language>returning DocSubmissionAuditTransformsConstants.EVENT_ACTION_CODE_RECIPIENT in getServiceEventActionCodeResponder(). EVENT_ACTION_CODE_SOURCE</technical_language>

Target:
protected String getServiceEventActionCodeResponder() { return DocSubmissionAuditTransformsConstants.EVENT_ACTION_CODE_SOURCE; }
Source:
<code>public void close() throws IOException { if (s3Object != null) { <START> s3Object.close(); <END> } }</code><technical_language>I need super.close() here</technical_language>

Target:
public void close() throws IOException { super.close(); if (s3Object != null) { s3Object.close(); } }
Source:
<code>public void testCreateWithBlockDeviceMapping() { <START> String serverId = null; <END> String flavorRef = "performance1-2"; String imageRef = "3ab30cc6-c503-41d3-8a37-106fda7848a7"; for (String regionId : regions) { ServerApi serverApi = api.getServerApi(regionId); try { BlockDeviceMapping blockDeviceMappings = BlockDeviceMapping.builder() .uuid(imageRef).sourceType("image").destinationType("volume") .volumeSize(100).bootIndex(0).build(); CreateServerOptions options = CreateServerOptions.Builder .blockDeviceMappings(ImmutableSet.of(blockDeviceMappings)); ServerCreated server = serverApi.create(hostName, "", flavorRef, options); serverId = server.getId(); awaitActive(serverApi).apply(server.getId()); Server serverCheck = serverApi.get(serverId); assertEquals(serverCheck.getStatus(), ACTIVE); } finally { if (serverId != null) { serverApi.delete(serverId); } } } }</code><technical_language>prefer this guarded extensionApi check namespace. disabled tests more debt. I understand hard-coded ids work in place, put a TODO: guard extensionApi os-block-device-mapping-v2-boot throw SkipException</technical_language>

Target:
public void testCreateWithBlockDeviceMapping() { String serverId = null; String flavorRef = "performance1-2"; String imageRef = "3ab30cc6-c503-41d3-8a37-106fda7848a7"; for (String regionId : regions) { ServerApi serverApi = api.getServerApi(regionId); ExtensionApi extensionApi = api.getExtensionApi(regionId); if (extensionApi.get("os-block-device-mapping-v2-boot") != null) { try { BlockDeviceMapping blockDeviceMappings = BlockDeviceMapping.builder() .uuid(imageRef).sourceType("image").destinationType("volume") .volumeSize(100).bootIndex(0).build(); CreateServerOptions options = CreateServerOptions.Builder .blockDeviceMappings(ImmutableSet.of(blockDeviceMappings)); ServerCreated server = serverApi.create(hostName, "", flavorRef, options); serverId = server.getId(); awaitActive(serverApi).apply(server.getId()); Server serverCheck = serverApi.get(serverId); assertEquals(serverCheck.getStatus(), ACTIVE); } finally { if (serverId != null) { serverApi.delete(serverId); } } } } }
Source:
<code>protected Control createContents(Composite parent) { Composite displayArea = new Composite(parent, SWT.NONE); GridLayoutFactory.fillDefaults().applyTo(displayArea); GridDataFactory.fillDefaults().applyTo(displayArea); final Repository repo = (Repository) getElement() .getAdapter(Repository.class); if (repo == null) return displayArea; StoredConfig config = repo.getConfig(); if (config instanceof FileBasedConfig) { File configFile = ((FileBasedConfig) config).getFile(); config = new FileBasedConfig(configFile, repo.getFS()); config.addChangeListener(new ConfigChangedListener() { public void onConfigChanged(ConfigChangedEvent event) { <START> repo.getListenerList().dispatch(new ConfigChangedEvent()); <END> } }); } else { config = repo.getConfig(); } editor = new ConfigurationEditorComponent(displayArea, config, true, false) { @Override protected void setErrorMessage(String message) { RepositoryPropertyPage.this.setErrorMessage(message); } }; editor.createContents(); return displayArea; }</code><technical_language>Repository fireEvent, that</technical_language>

Target:
protected Control createContents(Composite parent) { Composite displayArea = new Composite(parent, SWT.NONE); GridLayoutFactory.fillDefaults().applyTo(displayArea); GridDataFactory.fillDefaults().applyTo(displayArea); final Repository repo = (Repository) getElement() .getAdapter(Repository.class); if (repo == null) return displayArea; StoredConfig config = repo.getConfig(); if (config instanceof FileBasedConfig) { File configFile = ((FileBasedConfig) config).getFile(); config = new FileBasedConfig(configFile, repo.getFS()); config.addChangeListener(new ConfigChangedListener() { public void onConfigChanged(ConfigChangedEvent event) { repo.fireEvent(new ConfigChangedEvent()); } }); } editor = new ConfigurationEditorComponent(displayArea, config, true, false) { @Override protected void setErrorMessage(String message) { RepositoryPropertyPage.this.setErrorMessage(message); } }; editor.createContents(); return displayArea; }
Source:
<code>public final String getSecurityUncompressed() throws NitfFormatException { if (getSecurityFieldCompression().equals("GZIP")) { byte[] security = getSecurity(); StringBuilder sb = new StringBuilder(); try (ByteArrayInputStream bis = new ByteArrayInputStream(security); GZIPInputStream gis = new GZIPInputStream(bis); <START> BufferedReader br = new BufferedReader(new InputStreamReader(gis, StandardCharsets.ISO_8859_1))) { <END> String line; while ((line = br.readLine()) != null) { sb.append(line); } } catch (IOException e) { throw new NitfFormatException("Could not uncompress SECURITY field." + e.getLocalizedMessage()); } return sb.toString(); } return getFieldValue("SECURITY"); }</code><technical_language>encoding here? some UTF-8 references earlier</technical_language>

Target:
public final String getSecurityUncompressed() throws NitfFormatException { if (getSecurityFieldCompression().equals("GZIP")) { byte[] security = getSecurity(); StringBuilder sb = new StringBuilder(); try (ByteArrayInputStream bis = new ByteArrayInputStream(security); GZIPInputStream gis = new GZIPInputStream(bis); BufferedReader br = new BufferedReader(new InputStreamReader(gis, StandardCharsets.UTF_8))) { String line; while ((line = br.readLine()) != null) { sb.append(line); } } catch (IOException e) { throw new NitfFormatException("Could not uncompress SECURITY field." + e.getLocalizedMessage()); } return sb.toString(); } return new String(getSecurity(), StandardCharsets.UTF_8); }
Source:
<code>public void close() { <START> coordinatorStreamStore.close(); <END> }</code><technical_language>This closing underlying store shared other 'NamespaceAwareCoordinatorStreamStore' instances</technical_language>

Target:
public void close() { }
Source:
<code>public Response register(Action action) { validateParameters(action, "cluster.id|name"); <START> BackendVnicProfileHelper.validateVnicMappings(action, this); <END> ImportVmTemplateFromConfParameters params = new ImportVmTemplateFromConfParameters(); ExternalRegistrationConfigurationMapper.mapFromModel(action.getRegistrationConfiguration(), params); params.setContainerId(guid); params.setStorageDomainId(parent.getStorageDomainId()); params.setClusterId(getClusterId(action)); params.setImagesExistOnTargetStorageDomain(true); params.setExternalVnicProfileMappings(ExternalVnicProfileMappingMapper.mapFromModel(action.getVnicProfileMappings())); if (action.isSetClone()) { params.setImportAsNewEntity(action.isClone()); if (action.isSetVm() && action.getTemplate().isSetName()) { params.getVmTemplate().setName(action.getTemplate().getName()); } } if (action.isSetAllowPartialImport()) { params.setAllowPartialImport(action.isAllowPartialImport()); } return doAction(ActionType.ImportVmTemplateFromConfiguration, params, action); }</code><technical_language>add 'ExternalRegistrationConfigurationMapper' other mappers</technical_language>

Target:
public Response register(Action action) { BackendVnicProfileHelper.validateVnicMappings(action, this); ImportVmTemplateFromConfParameters params = new ImportVmTemplateFromConfParameters(); ExternalRegistrationConfigurationMapper.mapFromModel(action.getRegistrationConfiguration(), params); params.setContainerId(guid); params.setStorageDomainId(parent.getStorageDomainId()); if (action.isSetCluster()) { params.setClusterId(getClusterId(action)); } params.setImagesExistOnTargetStorageDomain(true); params.setExternalVnicProfileMappings(ExternalVnicProfileMappingMapper.mapFromModel(action.getVnicProfileMappings())); if (action.isSetClone()) { params.setImportAsNewEntity(action.isClone()); if (action.isSetVm() && action.getTemplate().isSetName()) { params.getVmTemplate().setName(action.getTemplate().getName()); } } if (action.isSetAllowPartialImport()) { params.setAllowPartialImport(action.isAllowPartialImport()); } return doAction(ActionType.ImportVmTemplateFromConfiguration, params, action); }
Source:
<code>public void addPamAuthentication(UserEntity userEntity, String userName, boolean persist) throws AmbariException { addAuthentication(userEntity, UserAuthenticationType.PAM, userName, <START> new Validator() { <END> @Override public void validate(UserEntity userEntity, String key) throws AmbariException { List<UserAuthenticationEntity> authenticationEntities = userEntity.getAuthenticationEntities(); for (UserAuthenticationEntity entity : authenticationEntities) { if (entity.getAuthenticationType() == UserAuthenticationType.PAM) { throw new AmbariException("The authentication type already exists for this user"); } } } }, persist); }</code><technical_language>do lambda approach</technical_language>

Target:
public void addPamAuthentication(UserEntity userEntity, String userName, boolean persist) throws AmbariException { addAuthentication(userEntity, UserAuthenticationType.PAM, userName, (user, key) -> { List<UserAuthenticationEntity> authenticationEntities = user.getAuthenticationEntities(); for (UserAuthenticationEntity entity : authenticationEntities) { if (entity.getAuthenticationType() == UserAuthenticationType.PAM) { throw new AmbariException("The authentication type already exists for this user"); } } }, persist); }
Source:
<code>public <R, X extends Exception> R withHandle(HandleCallback<R, X> callback) throws X { <START> if (threadHandle.get() != null) { <END> return callback.withHandle(threadHandle.get()); } try (Handle h = this.open()) { threadHandle.set(h); return callback.withHandle(h); } finally { threadHandle.remove(); } }</code><technical_language>slightly worried some user code expects able nest withHandle get separate database connections</technical_language>

Target:
public <R, X extends Exception> R withHandle(HandleCallback<R, X> callback) throws X { if (threadHandleSupplier.get() != null) { return callback.withHandle(threadHandleSupplier.get().getHandle()); } try (Handle h = this.open()) { threadHandleSupplier.set(new ConstantHandleSupplier(h)); return callback.withHandle(h); } finally { threadHandleSupplier.remove(); } }
Source:
<code>public void selectProduct(String nameToken) { String className = $("a[href=#" + nameToken + "]", productHead).attr("data-resource"); <START> String productSelected; <END> switch(className){ case "gwtp": productSelected = pageProductResources.style().gwtp(); break; case "jukito": productSelected = pageProductResources.style().jukito(); break; case "gae": default: productSelected = pageProductResources.style().gae(); break; } $(productHead).find("a").removeClass(pageProductResources.style().active()); $("a[href=#" + nameToken + "]", productHead).addClass(pageProductResources.style().active()); $(productHead).removeClass(); $(productHead).addClass(headClassNames); $(productHead).addClass(productSelected); }</code><technical_language>rm 63 76</technical_language>

Target:
public void selectProduct(String nameToken) { String className = $("a[href=#" + nameToken + "]", productHead).attr("data-style"); $(productHead).find("a").removeClass(pageProductResources.style().active()); $("a[href=#" + nameToken + "]", productHead).addClass(pageProductResources.style().active()); $(productHead).removeClass(); $(productHead).addClass(headClassNames); $(productHead).addClass(className); }
Source:
<code>public ArrayList<Pair<String, QueryMetric>> getRunningQueries() { ArrayList<Pair<String, QueryMetric>> runningQueriesList = new ArrayList<Pair<String, QueryMetric>>(); lock.lock(); ArrayList<String> queryKeys = new ArrayList<String>(); queryKeys.addAll(runningQueries.keySet()); try { <START> for (String key : queryKeys) <END> { runningQueriesList.add(new Pair<String, QueryMetric>(key, runningQueries.get(key).getFirst())); } } finally { lock.unlock(); } return runningQueriesList; }</code><technical_language>put runningQueries.keySet() in for loop. need for extra queryKeys array list copy into</technical_language>

Target:
public ArrayList<Pair<String, QueryMetric>> getRunningQueries() { ArrayList<Pair<String, QueryMetric>> runningQueriesList = new ArrayList<Pair<String, QueryMetric>>(); lock.lock(); try { for (String key : runningQueries.keySet()) { runningQueriesList.add(new Pair<String, QueryMetric>(key, runningQueries.get(key).getFirst())); } } finally { lock.unlock(); } return runningQueriesList; }
Source:
<code>public void read(CorfuPayloadMsg<ReadRequest> msg, ChannelHandlerContext ctx, IServerRouter r) { long address = msg.getPayload().getAddress(); boolean cacheable = msg.getPayload().isCacheReadResult(); log.trace("read: {}, cacheable: {}", msg.getPayload().getAddress(), cacheable); Lock lock = resetLock.readLock(); lock.lock(); try { <START> if (msg.getEpoch() != serverContext.getServerEpoch()) { throw new WrongEpochException(serverContext.getServerEpoch()); <END> } ReadResponse rr = new ReadResponse(); try { ILogData logData = dataCache.get(address, cacheable); if (logData == null) { rr.put(address, LogData.getEmpty(address)); } else { rr.put(address, (LogData) logData); } r.sendResponse(ctx, msg, CorfuMsgType.READ_RESPONSE.payloadMsg(rr)); } catch (DataCorruptionException e) { log.error("Data corruption exception while reading address {}", address, e); r.sendResponse(ctx, msg, CorfuMsgType.ERROR_DATA_CORRUPTION.payloadMsg(address)); } } finally { lock.unlock(); } }</code><technical_language>this based serverContext.getLogUnitEpochWaterMark()</technical_language>

Target:
public void read(CorfuPayloadMsg<ReadRequest> msg, ChannelHandlerContext ctx, IServerRouter r) { boolean cacheable = msg.getPayload().isCacheReadResult(); if (log.isTraceEnabled()) { log.trace("read: {}, cacheable: {}", msg.getPayload().getAddresses(), cacheable); } ReadResponse rr = new ReadResponse(); for (long address : msg.getPayload().getAddresses()) { try { ILogData logData = dataCache.get(address, cacheable); if (logData == null) { rr.put(address, LogData.getEmpty(address)); } else { rr.put(address, (LogData) logData); } } catch (DataCorruptionException e) { log.error( "Data corruption exception while reading addresses {}", msg.getPayload().getAddresses(), e); r.sendResponse(ctx, msg, CorfuMsgType.ERROR_DATA_CORRUPTION.payloadMsg(address)); return; } } r.sendResponse(ctx, msg, CorfuMsgType.READ_RESPONSE.payloadMsg(rr)); }
Source:
<code>public @Nullable Integer resolve(ITmfEvent event) { Integer cpu = TmfTraceUtils.resolveIntEventAspectOfClassForEvent(event.getTrace(), TmfCpuAspect.class, event); if (cpu == null) { return null; } TidAnalysisModule analysis = TmfTraceUtils.getAnalysisModuleOfClass(event.getTrace(), TidAnalysisModule.class, TidAnalysisModule.ID); if (analysis == null) { return null; } <START> Integer tid = analysis.getThreadOnCpuAtTime(cpu, event.getTimestamp().toNanos()); if (tid != null) { return tid; } return null; <END> }</code><technical_language>I need condition here</technical_language>

Target:
public @Nullable Integer resolve(ITmfEvent event) { Integer cpu = TmfTraceUtils.resolveIntEventAspectOfClassForEvent(event.getTrace(), TmfCpuAspect.class, event); if (cpu == null) { return null; } TidAnalysisModule analysis = TmfTraceUtils.getAnalysisModuleOfClass(event.getTrace(), TidAnalysisModule.class, TidAnalysisModule.ID); if (analysis == null) { return null; } return analysis.getThreadOnCpuAtTime(cpu, event.getTimestamp().toNanos()); }
Source:
<code>public short undeleteBlob(BlobId blobId, short lifeVersion, CloudUpdateValidator cloudUpdateValidator) throws CloudStorageException { Map<String, Object> updateFields = new HashMap<>(); updateFields.put(CloudBlobMetadata.FIELD_LIFE_VERSION, lifeVersion); updateFields.put(CloudBlobMetadata.FIELD_DELETION_TIME, Utils.Infinite_Time); UpdateResponse updateResponse = updateBlobMetadata(blobId, updateFields, cloudUpdateValidator); return updateResponse.metadata.containsKey(CloudBlobMetadata.FIELD_LIFE_VERSION) ? Short.parseShort( <START> updateResponse.metadata.get(CloudBlobMetadata.FIELD_LIFE_VERSION)) : 0; <END> }</code><technical_language>I Map.getOrDefault() here</technical_language>

Target:
public short undeleteBlob(BlobId blobId, short lifeVersion, CloudUpdateValidator cloudUpdateValidator) throws CloudStorageException { Map<String, Object> updateFields = new HashMap<>(); updateFields.put(CloudBlobMetadata.FIELD_LIFE_VERSION, lifeVersion); updateFields.put(CloudBlobMetadata.FIELD_DELETION_TIME, Utils.Infinite_Time); UpdateResponse updateResponse = updateBlobMetadata(blobId, updateFields, cloudUpdateValidator); return Short.parseShort(updateResponse.metadata.getOrDefault(CloudBlobMetadata.FIELD_LIFE_VERSION, "0")); }
Source:
<code>public Tuple getNext() throws IOException { try { if (!reader.nextKeyValue()) return null; List<Object> tuple = tuple0; if (readKey) { if (readValue) { tuple = tuple2; tuple.set(0, getCurrentKeyObject()); tuple.set(1, getCurrentValueObject()); } else { tuple = tuple1; tuple.set(0, getCurrentKeyObject()); } } else if (readValue) { tuple = tuple1; tuple.set(0, getCurrentValueObject()); } return tupleFactory.newTupleNoCopy(tuple); } catch (EOFException e) { if (valueArguments.hasOption(SKIP_EOF_ERRORS_PARAM)) { LOG.warn("EOFException encountered while reading input", e); counterHelper_.incrCounter(SequenceFileLoaderCounters.EOFError, 1L); } else { <START> throw e; <END> } } catch (InterruptedException e) { throw new ExecException("Error while reading input", 6018, PigException.REMOTE_ENVIRONMENT, e); } return null; }</code><technical_language>please fix spacing</technical_language>

Target:
public Tuple getNext() throws IOException { try { if (!reader.nextKeyValue()) return null; List<Object> tuple = tuple0; if (readKey) { if (readValue) { tuple = tuple2; tuple.set(0, getCurrentKeyObject()); tuple.set(1, getCurrentValueObject()); } else { tuple = tuple1; tuple.set(0, getCurrentKeyObject()); } } else if (readValue) { tuple = tuple1; tuple.set(0, getCurrentValueObject()); } return tupleFactory.newTupleNoCopy(tuple); } catch (EOFException e) { if (otherArguments.hasOption(SKIP_EOF_ERRORS_PARAM)) { LOG.warn("EOFException encountered while reading input", e); counterHelper_.incrCounter(SequenceFileLoaderCounters.EOFError, 1L); } else { throw e; } } catch (InterruptedException e) { throw new ExecException("Error while reading input", 6018, PigException.REMOTE_ENVIRONMENT, e); } return null; }
Source:
<code>public MarshallableEntry next() { try { while (hasNext()) { if (file < 0) { file = iterator.next(); handle = fileProvider.getFile(file); } for (; ; ) { EntryHeader header = EntryRecord.readOldEntryHeader(handle, offset); if (header == null) { handle.close(); file = -1; break; } if (header.valueLength() > 0) { byte[] serializedKey = EntryRecord.readKey(handle, header, offset); byte[] serializedValue = EntryRecord.readValue(handle, header, offset); offset += header.totalLength(); <START> if (EntryRecord.readOldEntryHeader(handle, offset) == null) { <END> handle.close(); file = -1; } return entryFactory.create(new ByteBufferImpl(serializedKey), new ByteBufferImpl(serializedValue)); } offset += header.totalLength(); } } throw new NoSuchElementException(); } catch (Exception e) { throw new CacheException(e); } }</code><technical_language>if user is migrating a store existing version of Infinispan, i.e. 11.x</technical_language>

Target:
public MarshallableEntry next() { try { while (hasNext()) { if (file < 0) { file = iterator.next(); handle = fileProvider.getFile(file); } for (; ; ) { EntryHeader header = reader.read(handle, offset); if (header == null) { handle.close(); file = -1; break; } if (header.valueLength() > 0) { byte[] serializedKey = EntryRecord.readKey(handle, header, offset); byte[] serializedValue = EntryRecord.readValue(handle, header, offset); offset += header.totalLength(); if (reader.read(handle, offset) == null) { handle.close(); file = -1; } return entryFactory.create(ByteBufferImpl.create(serializedKey), ByteBufferImpl.create(serializedValue)); } offset += header.totalLength(); } } throw new NoSuchElementException(); } catch (Exception e) { throw new CacheException(e); } }
Source:
<code>public static String generateHeaderFileName(String fileNameBase) { <START> return StringUtils.safeFormat("%s_header", fileNameBase); <END> }</code><technical_language>crash if bad format string</technical_language>

Target:
public static String generateHeaderFileName(String fileNameBase) { return StringUtils.format("%s_header", fileNameBase); }
Source:
<code>private Object doWithOutputStream(OutputStreamFunction f) { if (cacheOutputStream == null) { return null; } try { f.apply(cacheOutputStream); } catch (IOException t) { try { cacheOutputStream.close(); } <START> catch (IOException e) <END> { } cacheOutputStream = null; } return null; }</code><technical_language>![CRITICAL](<LINK_0> log rethrow this exception. [![rule](<LINK_1>](<LINK_2></technical_language>

Target:
private Object doWithOutputStream(OutputStreamFunction f) { if (cacheOutputStream == null) { return null; } try { f.apply(cacheOutputStream); } catch (IOException t) { logger.error(String.format("Failed to operate with additional artifact stream: coordinates-[%s]", coordinates), t); try { cacheOutputStream.close(); } catch (IOException e) { } cacheOutputStream = null; } return null; }