auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static List<Path> split(Path walRootDir, Path walsDir, Path archiveDir, FileSystem walFS, Configuration conf, final WALFactory factory) throws IOException { Path rootDir = CommonFSUtils.getRootDir(conf); FileSystem rootFS = rootDir.getFileSystem(conf); WALSplitter splitter = new WALSplitter(factory, conf, walRootDir, walFS, rootDir, rootFS); final List<FileStatus> wals = SplitLogManager.getFileList(conf, Collections.singletonList(walsDir), null); List<Path> splits = new ArrayList<>(); <START> if (CollectionUtils.isNotEmpty(wals)) { <END> for (FileStatus wal: wals) { SplitWALResult splitWALResult = splitter.splitWAL(wal, null); if (splitWALResult.isFinished()) { WALSplitUtil.archive(wal.getPath(), splitWALResult.isCorrupt(), archiveDir, walFS, conf); splits.addAll(splitter.outputSink.splits); } } } if (!walFS.delete(walsDir, true)) { throw new IOException("Unable to delete src dir " + walsDir); } return splits; }</code><technical_language>wals.isEmpty()</technical_language>

Target:
public static List<Path> split(Path walRootDir, Path walsDir, Path archiveDir, FileSystem walFS, Configuration conf, final WALFactory factory) throws IOException { Path rootDir = CommonFSUtils.getRootDir(conf); FileSystem rootFS = rootDir.getFileSystem(conf); WALSplitter splitter = new WALSplitter(factory, conf, walRootDir, walFS, rootDir, rootFS); final List<FileStatus> wals = SplitLogManager.getFileList(conf, Collections.singletonList(walsDir), null); List<Path> splits = new ArrayList<>(); if (!wals.isEmpty()) { for (FileStatus wal: wals) { SplitWALResult splitWALResult = splitter.splitWAL(wal, null); if (splitWALResult.isFinished()) { WALSplitUtil.archive(wal.getPath(), splitWALResult.isCorrupt(), archiveDir, walFS, conf); splits.addAll(splitter.outputSink.splits); } } } if (!walFS.delete(walsDir, true)) { throw new IOException("Unable to delete src dir " + walsDir); } return splits; }
Source:
<code>public Response saveResourcesWithId(String[] resources) { <START> if (m_jsonStore == null) { <END> throw getException(Status.NOT_FOUND, "No JsonStore registered."); } String resourcesInJson = new Gson().toJson(resources); String key = UUID.nameUUIDFromBytes(resourcesInJson.getBytes()).toString(); m_jsonStore.put(key, resourcesInJson, RESOURCE_IDS_CONTEXT); String jsonKey = new Gson().toJson(key); return Response.ok(jsonKey).build(); }</code><technical_language>Is this condition necessary? If JsonStore wire in this bean created Spring</technical_language>

Target:
public Response saveResourcesWithId(String[] resources) { String resourcesInJson = m_gson.toJson(resources); String key = UUID.nameUUIDFromBytes(resourcesInJson.getBytes()).toString(); m_jsonStore.put(key, resourcesInJson, RESOURCE_IDS_CONTEXT); String jsonKey = m_gson.toJson(key); return Response.ok(jsonKey).build(); }
Source:
<code>@Override public void onDisconnected(IgniteFuture reconnectFut) { IgniteCheckedException err = new IgniteClientDisconnectedCheckedException(reconnectFut, "Failed to wait for topology update, client disconnected."); <START> if (aff != null) { <END> aff.cancelFutures(err); } }</code><technical_language>Add empty line if()</technical_language>

Target:
@Override public void onDisconnected(IgniteFuture reconnectFut) { IgniteCheckedException err = new IgniteClientDisconnectedCheckedException(reconnectFut, "Failed to wait for topology update, client disconnected."); if (aff != null) aff.cancelFutures(err); }
Source:
<code>public void run() { running = true; try { while (running) { if ((trigger || (System.currentTimeMillis() - scanIntervalMillis >= lastScanMillis)) && isIterationCompleted()) { trigger = false; lastScannedInfo = null; numDiscoveredPerIteration = 0; for (String afile : files) { Path filePath = new Path(afile); <START> LOG.debug("Scan started for input {}", filePath.toString()); <END> Map<String, Long> lastModifiedTimesForInputDir; lastModifiedTimesForInputDir = referenceTimes.get(fs.getFileStatus(filePath).getPath().toString()); scan(filePath, null, lastModifiedTimesForInputDir); } scanIterationComplete(); } else { Thread.sleep(sleepMillis); } } } catch (Throwable throwable) { LOG.error("service", throwable); running = false; atomicThrowable.set(throwable); DTThrowable.rethrow(throwable); } }</code><technical_language>toString() required.. afile</technical_language>

Target:
public void run() { running = true; try { while (running) { if ((trigger || (System.currentTimeMillis() - scanIntervalMillis >= lastScanMillis)) && isIterationCompleted()) { trigger = false; lastScannedInfo = null; numDiscoveredPerIteration = 0; for (String afile : files) { Path filePath = new Path(afile); LOG.debug("Scan started for input {}", filePath); Map<String, Long> lastModifiedTimesForInputDir = null; if (fs.exists(filePath)) { FileStatus fileStatus = fs.getFileStatus(filePath); lastModifiedTimesForInputDir = referenceTimes.get(fileStatus.getPath().toUri().getPath()); } scan(filePath, null, lastModifiedTimesForInputDir); } scanIterationComplete(); } else { Thread.sleep(sleepMillis); } } } catch (Throwable throwable) { LOG.error("service", throwable); running = false; atomicThrowable.set(throwable); DTThrowable.rethrow(throwable); } }
Source:
<code>public void base64EncodedPasswordWithAlgorithmShouldFail() { <START> ldapUserDetailsService.setUserDetailsMapper(userDetailsMapper); userDetailsMapper.setBase64EncodedPassword(false); UserDetails ldapUser = ldapUserDetailsService.loadUserByUsername("base64withalgorithm-issue-1840"); assertThat(ldapUser).isInstanceOf(LdapUserDetailsImpl.class); LdapUserDetails ldapUserDetails = (LdapUserDetailsImpl) ldapUser; Exception thrown = assertThrows( IllegalArgumentException.class, () -> passwordEncoder.matches("password", ldapUserDetails.getPassword()), "There is no PasswordEncoder mapped for the id \"null\""); <END> assertTrue(thrown.getMessage().contains("There is no PasswordEncoder mapped for the id \"null\"")); }</code><technical_language>suggestion ldapUserDetailsService.setUserDetailsMapper(userDetailsMapper); userDetailsMapper.setBase64EncodedPassword(false); UserDetails ldapUser = ldapUserDetailsService.loadUserByUsername("base64withalgorithm-issue-1840"); assertThat(ldapUser).isInstanceOf(LdapUserDetailsImpl.class); LdapUserDetails ldapUserDetails = (LdapUserDetailsImpl) ldapUser; Exception thrown = assertThrows( IllegalArgumentException.class, () -> passwordEncoder.matches("password", ldapUserDetails.getPassword()), "There is PasswordEncoder mapped for id \"null\"");</technical_language>

Target:
public void base64EncodedPasswordWithAlgorithmShouldFail() { UserDetails ldapUser = ldapUserDetailsService.loadUserByUsername("issue1840-type-2"); assertThat(ldapUser).isInstanceOf(LdapUserDetailsImpl.class); LdapUserDetails ldapUserDetails = (LdapUserDetailsImpl) ldapUser; Exception thrown = assertThrows(IllegalArgumentException.class, () -> passwordEncoder.matches("password", ldapUserDetails.getPassword()), "There is no PasswordEncoder mapped for the id \"null\""); assertTrue(thrown.getMessage().contains("There is no PasswordEncoder mapped for the id \"null\"")); }
Source:
<code>private Rule.Context ruleContext(Context context) { StatsProvider statsProvider = new CachingStatsProvider(statsCalculator, Optional.of(context.memo), context.lookup, context.session, context.symbolAllocator::getTypes); CostProvider costProvider = new CachingCostProvider(costCalculator, statsProvider, Optional.of(context.memo), context.lookup, context.session, context.symbolAllocator::getTypes); return new Rule.Context() { @Override public Lookup getLookup() { return context.lookup; } @Override public PlanNodeIdAllocator getIdAllocator() { return context.idAllocator; } @Override public SymbolAllocator getSymbolAllocator() { return context.symbolAllocator; } @Override public Session getSession() { return context.session; } @Override public StatsProvider getStatsProvider() { return statsProvider; } @Override public CostProvider getCostProvider() { return costProvider; } @Override public long getTimeoutInMillis() { <START> return context.timeoutInMilliseconds; <END> } }; }</code><technical_language>expose this a void check throws exception if time limit is exhausted, s want for anyway, include timeout in error message. I thought of context passing relevant objects exposing "black box" methods</technical_language>

Target:
private Rule.Context ruleContext(Context context) { StatsProvider statsProvider = new CachingStatsProvider(statsCalculator, Optional.of(context.memo), context.lookup, context.session, context.symbolAllocator::getTypes); CostProvider costProvider = new CachingCostProvider(costCalculator, statsProvider, Optional.of(context.memo), context.lookup, context.session, context.symbolAllocator::getTypes); return new Rule.Context() { @Override public Lookup getLookup() { return context.lookup; } @Override public PlanNodeIdAllocator getIdAllocator() { return context.idAllocator; } @Override public SymbolAllocator getSymbolAllocator() { return context.symbolAllocator; } @Override public Session getSession() { return context.session; } @Override public StatsProvider getStatsProvider() { return statsProvider; } @Override public CostProvider getCostProvider() { return costProvider; } @Override public void checkTimeoutNotExhausted() { if (((System.nanoTime() - context.startTimeInNanos) / 1_000_000) >= context.timeoutInMilliseconds) { throw new PrestoException(OPTIMIZER_TIMEOUT, format("The optimizer exhausted the time limit of %d ms", context.timeoutInMilliseconds)); } } }; }
Source:
<code>public void start() throws Throwable { boolean useEpoll = USE_EPOLL && Epoll.isAvailable(); ServerConfigurationProvider configurationProvider = useEpoll ? EpollConfigurationProvider.INSTANCE : NioConfigurationProvider.INSTANCE; bossGroup = configurationProvider.createEventLoopGroup(1, tf); selectorGroup = configurationProvider.createEventLoopGroup( NUM_SELECTOR_THREADS, tf ); for ( Map.Entry<BoltConnector, ProtocolInitializer> bootstrapEntry : bootstrappersMap.entrySet() ) { try { ProtocolInitializer protocolInitializer = bootstrapEntry.getValue(); BoltConnector boltConnector = bootstrapEntry.getKey(); ChannelFuture channelFuture = new ServerBootstrap().option( ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT ) .group( bossGroup, selectorGroup ).channel( configurationProvider.getChannelClass() ) .childHandler( protocolInitializer.channelInitializer() ) .bind( protocolInitializer.address().socketAddress() ).sync(); InetSocketAddress localAddress = (InetSocketAddress) channelFuture.channel().localAddress(); connectionRegister.register( boltConnector.key(), localAddress ); ListenSocketAddress listenSocketAddress = new ListenSocketAddress( protocolInitializer.address().getHostname(), localAddress.getPort() ); <START> log.info( "Bolt enabled on %s.", listenSocketAddress ); <END> } catch ( Throwable e ) { throw new PortBindException( bootstrapEntry.getValue().address(), e ); } } }</code><technical_language>Is log localAddress create listenSocketAddress</technical_language>

Target:
public void start() throws Throwable { boolean useEpoll = USE_EPOLL && Epoll.isAvailable(); ServerConfigurationProvider configurationProvider = useEpoll ? EpollConfigurationProvider.INSTANCE : NioConfigurationProvider.INSTANCE; bossGroup = configurationProvider.createEventLoopGroup(1, tf); selectorGroup = configurationProvider.createEventLoopGroup( NUM_SELECTOR_THREADS, tf ); for ( Map.Entry<BoltConnector, ProtocolInitializer> bootstrapEntry : bootstrappersMap.entrySet() ) { try { ProtocolInitializer protocolInitializer = bootstrapEntry.getValue(); BoltConnector boltConnector = bootstrapEntry.getKey(); ChannelFuture channelFuture = new ServerBootstrap().option( ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT ) .group( bossGroup, selectorGroup ).channel( configurationProvider.getChannelClass() ) .childHandler( protocolInitializer.channelInitializer() ) .bind( protocolInitializer.address().socketAddress() ).sync(); InetSocketAddress localAddress = (InetSocketAddress) channelFuture.channel().localAddress(); connectionRegister.register( boltConnector.key(), localAddress ); String host = protocolInitializer.address().getHostname(); int port = localAddress.getPort(); if ( host.contains( ":" ) ) { log.info( "Bolt enabled on [%s]:%s.", host, port ); } else { log.info( "Bolt enabled on %s:%s.", host, port ); } } catch ( Throwable e ) { throw new PortBindException( bootstrapEntry.getValue().address(), e ); } } }
Source:
<code>public String index(Model model) { List<Event> upcoming = eventService.getUpcoming(); model.addAttribute(MODEL_ATTR_CUSTOMER, authenticationService.getCurrentCustomer()); model.addAttribute(MODEL_ATTR_EVENTS, webshopService.filterEventProductNotSalable(upcoming)); model.addAttribute(MODEL_ATTR_ORDER_PRODUCT, new OrderProductDto()); model.addAttribute(MODEL_ALLOWED_BUTTONS, authenticationService.getAuthLevel()); <START> System.out.println(authenticationService.getAuthLevel()); <END> return "webshop/index"; }</code><technical_language>Remove</technical_language>

Target:
public String index(Model model) { List<Event> upcoming = eventService.getUpcoming(); model.addAttribute(MODEL_ATTR_CUSTOMER, authenticationService.getCurrentCustomer()); model.addAttribute(MODEL_ATTR_EVENTS, webshopService.filterEventProductNotSalable(upcoming)); model.addAttribute(MODEL_ATTR_ORDER_PRODUCT, new OrderProductDto()); return "webshop/index"; }
Source:
<code>private ApiResponse buildResponseFromAuthSession(WebSession session) { ApiResponseList list = new ApiResponseList("authenticationSession"); if (session == null) { return list; } HttpState state = session.getHttpState(); ApiResponseList cookieList = new ApiResponseList("cookies"); for (Cookie cookie : state.getCookies()) { Map<String, String> fields = new HashMap<>(); fields.put(PARAM_COOKIE_DOMAIN, cookie.getDomain()); fields.put(PARAM_COOKIE_NAME, cookie.getName()); fields.put(PARAM_COOKIE_VALUE, cookie.getValue()); fields.put(PARAM_COOKIE_PATH, cookie.getPath()); <START> fields.put("expires", "" + cookie.getExpiryDate()); <END> fields.put(PARAM_COOKIE_SECURE, "" + cookie.getSecure()); fields.put("comment", cookie.getComment()); cookieList.addItem(new ApiResponseSet<>("cookie", fields)); } list.addItem(cookieList); try { Map<String, String> credMap = new HashMap<>(); Field credMapField = state.getClass().getDeclaredField("credMap"); credMapField.setAccessible(true); Object obj = credMapField.get(state); if (obj instanceof HashMap) { ((HashMap<?, ?>) obj) .forEach( (k, v) -> { credMap.put(k.toString(), v.toString()); }); } ApiResponseList credList = new ApiResponseList("credentials"); credList.addItem(new ApiResponseSet<>("credentials", credMap)); list.addItem(credList); } catch (Exception e) { log.error("Failed to access HttpState credMap", e); } return list; }</code><technical_language>toString()</technical_language>

Target:
private ApiResponse buildResponseFromAuthSession(WebSession session) { ApiResponseList list = new ApiResponseList("authenticationSession"); if (session == null) { return list; } HttpState state = session.getHttpState(); ApiResponseList cookieList = new ApiResponseList("cookies"); for (Cookie cookie : state.getCookies()) { Map<String, String> fields = new HashMap<>(); fields.put(PARAM_COOKIE_DOMAIN, cookie.getDomain()); fields.put(PARAM_COOKIE_NAME, cookie.getName()); fields.put(PARAM_COOKIE_VALUE, cookie.getValue()); fields.put(PARAM_COOKIE_PATH, cookie.getPath()); fields.put("expires", String.valueOf(cookie.getExpiryDate())); fields.put(PARAM_COOKIE_SECURE, Boolean.toString(cookie.getSecure())); fields.put("comment", cookie.getComment()); cookieList.addItem(new ApiResponseSet<>("cookie", fields)); } list.addItem(cookieList); try { Map<String, String> credMap = new HashMap<>(); Field credMapField = state.getClass().getDeclaredField("credMap"); credMapField.setAccessible(true); Object obj = credMapField.get(state); if (obj instanceof HashMap) { ((HashMap<?, ?>) obj) .forEach( (k, v) -> { credMap.put(k.toString(), v.toString()); }); } ApiResponseList credList = new ApiResponseList("credentials"); credList.addItem(new ApiResponseSet<>("credentials", credMap)); list.addItem(credList); } catch (Exception e) { log.error("Failed to access HttpState credMap", e); } return list; }
Source:
<code>public static List<String> getSentences(String text, Site site) { List<String> sentenceList = new ArrayList<>(); BreakIterator iterator = BreakIterator.getSentenceInstance(new Locale(site.getLanguageCode())); <START> text = text.replaceAll("(\r|\n)", ""); <END> iterator.setText(text); int start = iterator.first(); int end = iterator.next(); while (end != BreakIterator.DONE) { String sentence = text.substring(start, end).trim(); if (!TextUtils.isEmpty(sentence)) { if (sentenceList.size() == 0) { sentenceList.add(removeParens(sentence)); } else { sentenceList.add(sentence); } } start = end; end = iterator.next(); } if (sentenceList.size() == 0) { sentenceList.add(text); } return sentenceList; }</code><technical_language>replace spaces instead</technical_language>

Target:
public static List<String> getSentences(String text, Site site) { List<String> sentenceList = new ArrayList<>(); BreakIterator iterator = BreakIterator.getSentenceInstance(new Locale(site.getLanguageCode())); text = text.replaceAll("(\r|\n)", " "); iterator.setText(text); int start = iterator.first(); int end = iterator.next(); while (end != BreakIterator.DONE) { String sentence = text.substring(start, end).trim(); if (TextUtils.isGraphic(sentence)) { if (sentenceList.size() == 0) { sentenceList.add(removeParens(sentence)); } else { sentenceList.add(sentence); } } start = end; end = iterator.next(); } if (sentenceList.size() == 0) { sentenceList.add(text); } return sentenceList; }
Source:
<code>public UriImage(Context context, Uri uri) { if ((null == context) || (null == uri)) { throw new IllegalArgumentException(); } String scheme = uri.getScheme(); if (scheme.equals("content")) { initFromContentUri(context, uri); } else if (uri.getScheme().equals("file")) { initFromFile(context, uri); } mSrc = mPath.substring(mPath.lastIndexOf('/') + 1); <START> if(mSrc.startsWith(".") && mSrc.length() > 1) { <END> mSrc = mSrc.substring(1); } mSrc = mSrc.replace(' ', '_'); mContext = context; mUri = uri; decodeBoundsInfo(); }</code><technical_language>Need a space if ( this "if (mSrc..."</technical_language>

Target:
public UriImage(Context context, Uri uri) { if ((null == context) || (null == uri)) { throw new IllegalArgumentException(); } String scheme = uri.getScheme(); if (scheme.equals("content")) { initFromContentUri(context, uri); } else if (uri.getScheme().equals("file")) { initFromFile(context, uri); } mSrc = mPath.substring(mPath.lastIndexOf('/') + 1); mSrc = mSrc.replace(' ', '_'); mContext = context; mUri = uri; decodeBoundsInfo(); }
Source:
<code>public HttpResponse doChangeToken(@AncestorInPath User u, StaplerResponse rsp) throws IOException { u.checkPermission(Jenkins.ADMINISTER); <START> LOGGER.log(Level.WARNING, "Deprecated action /changeToken used, consider using /generateNewToken instead"); <END> ApiTokenProperty p = u.getProperty(ApiTokenProperty.class); if (p == null) { p = forceNewInstance(u, true); u.addProperty(p); } else { p.changeApiToken(); } rsp.setHeader("script","document.getElementById('apiToken').value='"+p.getApiToken()+"'"); return HttpResponses.html(p.hasPermissionToSeeToken() ? Messages.ApiTokenProperty_ChangeToken_Success() : Messages.ApiTokenProperty_ChangeToken_SuccessHidden()); }</code><technical_language>This enabling legacy token options in security configuration, inappropriate for a warning</technical_language>

Target:
public HttpResponse doChangeToken(@AncestorInPath User u, StaplerResponse rsp) throws IOException { u.checkPermission(Jenkins.ADMINISTER); LOGGER.log(Level.FINE, "Deprecated action /changeToken used, consider using /generateNewToken instead"); if(!mustDisplayLegacyApiToken(u)){ return HttpResponses.html(Messages.ApiTokenProperty_ChangeToken_CapabilityNotAllowed()); } ApiTokenProperty p = u.getProperty(ApiTokenProperty.class); if (p == null) { p = forceNewInstance(u, true); p.setUser(u); u.addProperty(p); } else { p.changeApiToken(); } rsp.setHeader("script","document.getElementById('apiToken').value='"+p.getApiToken()+"'"); return HttpResponses.html(p.hasPermissionToSeeToken() ? Messages.ApiTokenProperty_ChangeToken_Success() : Messages.ApiTokenProperty_ChangeToken_SuccessHidden()); }
Source:
<code>public ProviderViewHolder(View itemView) { super(itemView); mRowLayout = (LinearLayout) itemView; <START> mIdentifier = (TextView) itemView.findViewById(R.id.providerManagementIdentifier); <END> mName = (TextView) itemView.findViewById(R.id.providerManagementName); }</code><technical_language>Redundant casting</technical_language>

Target:
public ProviderViewHolder(View itemView) { super(itemView); mRowLayout = (ConstraintLayout) itemView; mIdentifier = itemView.findViewById(R.id.providerManagementIdentifier); mName = itemView.findViewById(R.id.providerManagementName); }
Source:
<code><START> void sendMetricsToDashboard(final String request) { <END> try { final HttpPost httpPost = new HttpPost(dashboardURL); httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded"); httpPost.setEntity(new StringEntity(request)); final HttpResponse response = metricsSendingPool.execute(httpPost); if (response.getStatusLine().getStatusCode() == 200) { LOG.log(Level.INFO, "Dashboard: post succeeded."); } else { LOG.log(Level.WARNING, "Dashboard: post failed."); } } catch (IOException e) { LOG.log(Level.WARNING, "Dashboard: post failed."); } }</code><technical_language>Is reason remove 'private' access modifier</technical_language>

Target:
private void sendMetricsToDashboard(final String request) { try { final HttpPost httpPost = new HttpPost(dashboardSetupStatus.dashboardURL); httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded"); httpPost.setEntity(new StringEntity(request)); dashboardSetupStatus.reusableHttpClient.execute(httpPost, new DashboardResponseCallback()); } catch (IOException e) { LOG.log(Level.WARNING, "Dashboard: post request failed.", e); } }
Source:
<code>public static String toBase64String(Serializable object) { String encoded = null; try { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); objectOutputStream.writeObject(object); objectOutputStream.close(); encoded = Base64.encodeToString(byteArrayOutputStream.toByteArray(), 0); } catch (IOException e) { <START> e.printStackTrace(); <END> } return encoded; }</code><technical_language>logcat</technical_language>

Target:
public static String toBase64String(Serializable object) { String encoded = null; try { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); objectOutputStream.writeObject(object); objectOutputStream.close(); encoded = Base64.encodeToString(byteArrayOutputStream.toByteArray(), 0); } catch (IOException e) { LogExt.e(SerializableUtils.class, e.getLocalizedMessage()); } return encoded; }
Source:
<code>public boolean getGlobalVariableConflicts(List<UserVariable> project1GlobalVars, List<UserVariable> project2GlobalVars) { List<UserVariable> conflicts = new ArrayList<>(); for (UserVariable project1GlobalVar : project1GlobalVars) { for (UserVariable project2GlobalVar : project2GlobalVars) { if (project1GlobalVar.getName().equals(project2GlobalVar.getName()) && !project1GlobalVar.getValue() .equals(project2GlobalVar.getValue())) { conflicts.add(project1GlobalVar); } } } <START> return conflicts.isEmpty(); <END> }</code><technical_language>optimize this in a saving extra list conflicts added. This implemented in a ticket resolve tickets. understand, creating a new list returning a property of this list. (Pseudo Code): WHILE iterate_over_lists: IF conflict_found RETURN true; END IF END WHILE return false;</technical_language>

Target:
public boolean getGlobalVariableConflicts(List<UserVariable> project1GlobalVars, List<UserVariable> project2GlobalVars) { List<UserVariable> conflicts = new ArrayList<>(); for (UserVariable project1GlobalVar : project1GlobalVars) { for (UserVariable project2GlobalVar : project2GlobalVars) { if (project1GlobalVar.getName().equals(project2GlobalVar.getName())) { conflicts.add(project1GlobalVar); } } } return !conflicts.isEmpty(); }
Source:
<code>private List<String> getErrors(List<Integer> givenPoints, int totalPoints) { List<String> errors = new ArrayList<>(); int sum = 0; for (int i : givenPoints) { if (i < 0) { errors.add(Const.FeedbackQuestion.CONST_SUM_ERROR_NEGATIVE); return errors; } sum += i; } if (sum != totalPoints) { errors.add(Const.FeedbackQuestion.CONST_SUM_ERROR_MISMATCH); return errors; } Set<Integer> answerSet = new HashSet<>(); if (distributePointsFor.equals( FeedbackConstantSumDistributePointsType.DISTRIBUTE_SOME_UNEVENLY.getDisplayedOption())) { boolean hasDifferentPoints = false; for (int i : givenPoints) { if (!answerSet.isEmpty() && !answerSet.contains(i)) { hasDifferentPoints = true; break; } answerSet.add(i); } <START> if (!hasDifferentPoints) { <END> errors.add(Const.FeedbackQuestion.CONST_SUM_ERROR_SOME_UNIQUE); return errors; } } else if (forceUnevenDistribution || distributePointsFor.equals( FeedbackConstantSumDistributePointsType.DISTRIBUTE_ALL_UNEVENLY.getDisplayedOption())) { for (int i : givenPoints) { if (answerSet.contains(i)) { errors.add(Const.FeedbackQuestion.CONST_SUM_ERROR_UNIQUE); return errors; } answerSet.add(i); } } return errors; }</code><technical_language>If is answer, show error right</technical_language>

Target:
private List<String> getErrors(List<Integer> givenPoints, int totalPoints) { List<String> errors = new ArrayList<>(); int sum = 0; for (int i : givenPoints) { if (i < 0) { errors.add(Const.FeedbackQuestion.CONST_SUM_ERROR_NEGATIVE); return errors; } sum += i; } if (sum != totalPoints) { errors.add(Const.FeedbackQuestion.CONST_SUM_ERROR_MISMATCH); return errors; } Set<Integer> answerSet = new HashSet<>(); if (givenPoints.size() > 1 && distributePointsFor.equals( FeedbackConstantSumDistributePointsType.DISTRIBUTE_SOME_UNEVENLY.getDisplayedOption())) { boolean hasDifferentPoints = false; for (int i : givenPoints) { if (!answerSet.isEmpty() && !answerSet.contains(i)) { hasDifferentPoints = true; break; } answerSet.add(i); } if (!hasDifferentPoints) { errors.add(Const.FeedbackQuestion.CONST_SUM_ERROR_SOME_UNIQUE); return errors; } } else if (givenPoints.size() > 1 && (forceUnevenDistribution || distributePointsFor.equals( FeedbackConstantSumDistributePointsType.DISTRIBUTE_ALL_UNEVENLY.getDisplayedOption()))) { for (int i : givenPoints) { if (answerSet.contains(i)) { errors.add(Const.FeedbackQuestion.CONST_SUM_ERROR_UNIQUE); return errors; } answerSet.add(i); } } return errors; }
Source:
<code>public void foo(StringBuilder sb, byte b, int c) { sb.append(Integer.toHexString( b & 0xFF )); System.out.println(Integer.toHexString( b & 0xFF )); sb.append(Integer.toHexString( b )); sb.append(Integer.toHexString( c )); sb.append(Integer.toHexString( 12 )); System.out.print(Integer.toHexString( b & 0xFF )); System.out.print(Integer.toHexString( 0Xff & 23 )); System.out.print(Integer.toHexString( b & c )); <START> System.out.println(Integer.toHexString( b & 0xFF )); <END> }</code><technical_language>this is present line 4 well, removed</technical_language>

Target:
public void foo(StringBuilder sb, byte b, int c) { sb.append(Integer.toHexString( b & 0xFF )); System.out.println(Integer.toHexString( b & 0xFF )); sb.append(Integer.toHexString( b )); sb.append(Integer.toHexString( c )); sb.append(Integer.toHexString( 12 )); System.out.print(Integer.toHexString( b & 0xFF )); System.out.print(Integer.toHexString( 0Xff & 23 )); System.out.print(Integer.toHexString( b & c )); StringJoiner joiner = new StringJoiner(""); joiner.add(Integer.toHexString( b )); joiner.add(Integer.toHexString( c )); }
Source:
<code>public void verifyComponentRemoved(Components component) { driver.switchTo().frame(iframe); switch (component) { case Photo: waitForElementNotPresent(imageBy); break; case Gallery: waitForElementNotPresent(galleryBy); break; case Slideshow: waitForElementNotPresent(slideshowBy); break; case Slider: waitForElementNotPresent(sliderBy); break; case Video: waitForElementNotPresent(videoBy); break; default: <START> break; <END> } driver.switchTo().defaultContent(); PageObjectLogging.log("verifyGalleryRemoved", "Click on 'remove button' on gallery", true); }</code><technical_language>need for empty default, throw a viable exception log a message</technical_language>

Target:
public void verifyComponentRemoved(Components component) { driver.switchTo().frame(iframe); switch (component) { case Photo: waitForElementNotPresent(imageBy); break; case Gallery: waitForElementNotPresent(galleryBy); break; case Slideshow: waitForElementNotPresent(slideshowBy); break; case Slider: waitForElementNotPresent(sliderBy); break; case Video: waitForElementNotPresent(videoBy); break; default: PageObjectLogging.log( "verifyComponentRemoved", "Invalid component: " + component.name() +" selected", false ); break; } driver.switchTo().defaultContent(); PageObjectLogging.log("verifyGalleryRemoved", "Click on 'remove button' on gallery", true); }
Source:
<code>private static SystemMetrics getSystemMetrics() { if (!System.getProperty("os.name").toLowerCase().startsWith("linux")) { return null; } try { SystemMetrics m = new SystemMetrics(); final String stat = FileUtils.readFileToString(SELF_STAT); String[] s = stat.split(" "); long utime = Long.parseLong(s[13]) + Long.parseLong(s[15]); long stime = Long.parseLong(s[14]) + Long.parseLong(s[16]); m.cputime = (utime + stime) / Hertz; m.time = System.currentTimeMillis(); s = FileUtils.readFileToString(STAT).split(" "); m.iowait = Long.parseLong(s[5]) / Hertz; if (SELF_IO.exists() && SELF_IO.canRead()) { final LineIterator lineIterator = FileUtils.lineIterator(SELF_IO); while (lineIterator.hasNext()) { final String line = lineIterator.next(); if (line.startsWith("read_bytes: ")) { m.read_bytes = Long.parseLong(line.substring(12)); } } } return m; } catch (IOException e) { <START> e.printStackTrace(); <END> return null; } }</code><technical_language>output is lost - please a Logger</technical_language>

Target:
private static SystemMetrics getSystemMetrics() { if (!Platform.isLinux()) { return null; } try { SystemMetrics m = new SystemMetrics(); final String stat = FileUtils.readFileToString(SELF_STAT); String[] s = stat.split(" "); long utime = Long.parseLong(s[13]) + Long.parseLong(s[15]); long stime = Long.parseLong(s[14]) + Long.parseLong(s[16]); m.cputime = (utime + stime) / Hertz; m.time = System.currentTimeMillis(); s = FileUtils.readFileToString(STAT).split(" "); m.iowait = Long.parseLong(s[5]) / Hertz; if (SELF_IO.exists() && SELF_IO.canRead()) { final LineIterator lineIterator = FileUtils.lineIterator(SELF_IO); while (lineIterator.hasNext()) { final String line = lineIterator.next(); if (line.startsWith("read_bytes: ")) { m.read_bytes = Long.parseLong(line.substring(12)); } } } return m; } catch (IOException e) { LOGGER.log(Level.WARNING, "Failed to collect system metrics", e); return null; } }
Source:
<code>public static boolean isPrivilegeNameValid(String privilegeName) { boolean isValid = false; switch(privilegeName) { case Const.ParamsNames.INSTRUCTOR_PERMISSION_MODIFY_COURSE: isValid = true; break; case Const.ParamsNames.INSTRUCTOR_PERMISSION_MODIFY_INSTRUCTOR: isValid = true; break; case Const.ParamsNames.INSTRUCTOR_PERMISSION_MODIFY_SESSION: isValid = true; break; case Const.ParamsNames.INSTRUCTOR_PERMISSION_MODIFY_STUDENT: isValid = true; break; case Const.ParamsNames.INSTRUCTOR_PERMISSION_VIEW_STUDENT_IN_SECTION: isValid = true; break; case Const.ParamsNames.INSTRUCTOR_PERMISSION_VIEW_COMMENT_IN_SECTION: isValid = true; break; case Const.ParamsNames.INSTRUCTOR_PERMISSION_GIVE_COMMENT_IN_SECTION: isValid = true; break; case Const.ParamsNames.INSTRUCTOR_PERMISSION_MODIFY_COMMENT_IN_SECTION: isValid = true; break; case Const.ParamsNames.INSTRUCTOR_PERMISSION_VIEW_SESSION_IN_SECTION: isValid = true; break; case Const.ParamsNames.INSTRUCTOR_PERMISSION_SUBMIT_SESSION_IN_SECTION: isValid = true; break; case Const.ParamsNames.INSTRUCTOR_PERMISSION_MODIFY_SESSION_COMMENT_IN_SECTION: isValid = true; break; default: isValid = false; break; <START> } <END> return isValid; }</code><technical_language>put values a set/map method in set/map find if is in set? Cleaner switch statements</technical_language>

Target:
public static boolean isPrivilegeNameValid(String privilegeName) { return COURSE_LEVEL_ONLY_PRIVILEGES.contains(privilegeName) || SECTION_LEVEL_ONLY_PRIVILEGES.contains(privilegeName) || SESSION_LEVEL_ONLY_PRIVILEGES.contains(privilegeName); }
Source:
<code>public static void output(@AggregationState DifferentialEntropyState state, BlockBuilder out) { DifferentialEntropyStateStrategy strategy = state.getStrategy(); <START> double result = strategy == null ? Double.NaN : strategy.calculateEntropy(); <END> DOUBLE.writeDouble(out, result); }</code><technical_language>inline result variable: DOUBLE.writeDouble(out, strategy == null ? Double.NaN : strategy.calculateEntropy());</technical_language>

Target:
public static void output(@AggregationState DifferentialEntropyState state, BlockBuilder out) { DifferentialEntropyStateStrategy strategy = state.getStrategy(); DOUBLE.writeDouble(out, strategy == null ? Double.NaN : strategy.calculateEntropy()); }
Source:
<code><START> public void testUnmarshallSubprocessLevelEventFilledProperties() throws Exception { <END> final String EVENT_NAME = "It is also not empty ~`!@#$%^&*()_+=-{}|\\][:\";'?><,./"; final String EVENT_DOCUMENTATION = "Some documentation as well\n~`!@#$%^&*()_+=-{}|\\][:\";'?><,./\n"; Diagram<Graph, Metadata> diagram = unmarshall(marshaller, BPMN_START_EVENT_FILE_PATH); assertDiagram(diagram, AMOUNT_OF_NODES_IN_DIAGRAM); StartNoneEvent filledSubprocess = getStartNodeById(diagram, FILLED_SUBPROCESS_LEVEL_EVENT_ID, StartNoneEvent.class); assertGeneralSet(filledSubprocess.getGeneral(), EVENT_NAME, EVENT_DOCUMENTATION); assertStartEventSlaDueDate(filledSubprocess.getExecutionSet(), SLA_DUE_DATE); }</code><technical_language>Missing assertNotNull for executionSet here</technical_language>

Target:
public void testUnmarshallSubprocessLevelEventFilledProperties() throws Exception { final String EVENT_NAME = "It is also not empty ~`!@#$%^&*()_+=-{}|\\][:\";'?><,./"; final String EVENT_DOCUMENTATION = "Some documentation as well\n~`!@#$%^&*()_+=-{}|\\][:\";'?><,./\n"; Diagram<Graph, Metadata> diagram = unmarshall(marshaller, BPMN_START_EVENT_FILE_PATH); assertDiagram(diagram, AMOUNT_OF_NODES_IN_DIAGRAM); StartNoneEvent filledSubprocess = getStartNodeById(diagram, FILLED_SUBPROCESS_LEVEL_EVENT_ID, StartNoneEvent.class); assertGeneralSet(filledSubprocess.getGeneral(), EVENT_NAME, EVENT_DOCUMENTATION); assertNotNull(filledSubprocess.getExecutionSet()); assertStartEventSlaDueDate(filledSubprocess.getExecutionSet(), SLA_DUE_DATE); }
Source:
<code>private void createPrePopulatedDocs(int numberOfPreCreatedDocuments) { for (CosmosAsyncContainer container : containers) { AtomicLong successCount = new AtomicLong(0); AtomicLong failureCount = new AtomicLong(0); ArrayList<Flux<PojoizedJson>> createDocumentObservables = new ArrayList<>(); for (int i = 0; i < numberOfPreCreatedDocuments; i++) { String uId = UUID.randomUUID().toString(); PojoizedJson newDoc = BenchmarkHelper.generateDocument(uId, dataFieldValue, partitionKey, configuration.getDocumentDataFieldCount()); Flux<PojoizedJson> obs = container.createItem(newDoc).map(resp -> { PojoizedJson x = resp.getItem(); return x; }).onErrorResume(throwable -> { failureCount.incrementAndGet(); <START> logger.error("Error during pre populating item "+throwable.getMessage()); <END> return Mono.empty(); }).doOnSuccess(pojoizedJson -> { successCount.incrementAndGet(); }).flux(); createDocumentObservables.add(obs); } docsToRead.put(container.getId(), Flux.merge(Flux.fromIterable(createDocumentObservables), 100).collectList().block()); logger.info("Finished pre-populating documents for container {}", successCount.get()-failureCount.get(), container.getId()); if(failureCount.get() > 0) { logger.info("Failed pre-populating documents for container {}", failureCount.get(), container.getId()); } } }</code><technical_language>please do concat in logger suggestion logger.error("Error pre populating item", throwable);</technical_language>

Target:
private void createPrePopulatedDocs(int numberOfPreCreatedDocuments) { for (CosmosAsyncContainer container : containers) { AtomicLong successCount = new AtomicLong(0); AtomicLong failureCount = new AtomicLong(0); ArrayList<Flux<PojoizedJson>> createDocumentObservables = new ArrayList<>(); for (int i = 0; i < numberOfPreCreatedDocuments; i++) { String uId = UUID.randomUUID().toString(); PojoizedJson newDoc = BenchmarkHelper.generateDocument(uId, dataFieldValue, partitionKey, configuration.getDocumentDataFieldCount()); Flux<PojoizedJson> obs = container.createItem(newDoc).map(resp -> { PojoizedJson x = resp.getItem(); return x; }).onErrorResume(throwable -> { failureCount.incrementAndGet(); logger.error("Error during pre populating item ", throwable.getMessage()); return Mono.empty(); }).doOnSuccess(pojoizedJson -> { successCount.incrementAndGet(); }).flux(); createDocumentObservables.add(obs); } docsToRead.put(container.getId(), Flux.merge(Flux.fromIterable(createDocumentObservables), 100).collectList().block()); logger.info("Finished pre-populating documents for container {}", successCount.get() - failureCount.get(), container.getId()); if (failureCount.get() > 0) { logger.info("Failed pre-populating documents for container {}", failureCount.get(), container.getId()); } } }
Source:
<code>public static int getDefaultAudioFormat(Context context, List<AudioStream> audioStreams) { MediaFormat defaultFormat = getDefaultFormat(context, R.string.default_audio_format_key, R.string.default_audio_format_value); int result; <START> if (isLimitingDataUsage(context)) { <END> result = getMostCompactAudioIndex(defaultFormat, audioStreams); } else { result = getHighestQualityAudioIndex(defaultFormat, audioStreams); } return result; }</code><technical_language>if (isLimitingDataUsage(context)) { return getMostCompactAudioIndex(defaultFormat, audioStreams); } else { return getHighestQualityAudioIndex(defaultFormat, audioStreams); }</technical_language>

Target:
public static int getDefaultAudioFormat(Context context, List<AudioStream> audioStreams) { MediaFormat defaultFormat = getDefaultFormat(context, R.string.default_audio_format_key, R.string.default_audio_format_value); if (isLimitingDataUsage(context)) { return getMostCompactAudioIndex(defaultFormat, audioStreams); } else { return getHighestQualityAudioIndex(defaultFormat, audioStreams); } }
Source:
<code>private static List<Type> intersection(List<Set<Type>> supertypes) { <START> List<Type> results = new ArrayList<>(supertypes.get(0)); <END> for (int i = 1; i < supertypes.size(); i++) { results.retainAll(supertypes.get(i)); } return results; }</code><technical_language>flatMap stuff</technical_language>

Target:
private static List<Type> intersection(List<Set<Type>> supertypes) { return new ArrayList<>(supertypes.stream().reduce(Sets::intersection).get()); }
Source:
<code>private void postLaunchProcessing(RequestCriteria requestCriteria, String externalExecutionId) { TransactionTemplate template = new TransactionTemplate(transactionManager); template.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) { TaskDefinition taskDefinition = requestCriteria.getTaskDefinition(); taskExecutionRepository.updateExternalExecutionId( requestCriteria.getTaskExecution().getExecutionId(), externalExecutionId); <START> auditRecordService.populateAndSaveAuditRecordUsingMapData( <END> AuditOperationType.TASK, AuditActionType.DEPLOY, taskDefinition.getName(), getAuditData(taskDefinition, requestCriteria.getLaunchTaskDeploymentProperties(), requestCriteria.getAppDeploymentRequest().getCommandlineArguments())); } }); }</code><technical_language>intentional AuditRecordService implementation is annotated @Transactional? @ghillert need manual tx mgmt here</technical_language>

Target:
private void postLaunchProcessing(RequestCriteria requestCriteria, String externalExecutionId) { TransactionTemplate template = new TransactionTemplate(transactionManager); template.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) { TaskDefinition taskDefinition = requestCriteria.getTaskDefinition(); auditRecordService.populateAndSaveAuditRecordUsingMapData( AuditOperationType.TASK, AuditActionType.DEPLOY, taskDefinition.getName(), getAuditData(taskDefinition, requestCriteria.getAppDeploymentRequest().getDeploymentProperties(), requestCriteria.getAppDeploymentRequest().getCommandlineArguments())); } }); }
Source:
<code>public DocumentModel fromAvro(Schema schema, GenericRecord input) { if (!DOCUMENT_MODEL.equals(getLogicalType(schema))) { throw new RuntimeServiceException("Schema does not match DocumentModel"); } String path = (String) input.get(PATH); GenericRecord documentTypeRecord = (GenericRecord) input.get(PRIMARY_TYPE); DocumentModel doc = new DocumentModelImpl((String) null, path, documentTypeRecord.getSchema().getName()); for (Field schemaField : documentTypeRecord.getSchema().getFields()) { GenericRecord schemaRecord = (GenericRecord) documentTypeRecord.get(schemaField.name()); List<Field> fields = schemaField.schema().getFields(); Map<String, Object> data = new HashMap<>(fields.size()); for (Field field : fields) { Object value = service.fromAvro(field.schema(), Property.class, schemaRecord.get(field.name())); data.put(service.decodeName(field.name()), value); <START> } <END> doc.setProperties(service.decodeName(schemaField.name()), data); } return doc; }</code><technical_language>This replaced sthg Map<String, Object> data = fields.stream().collect(Collectors.toMap(f -> service.decodeName(f.name()), f -> service.fromAvro(f.schema(), Property.class, schemaRecord.get(f.name()))))</technical_language>

Target:
public DocumentModel fromAvro(Schema schema, GenericRecord input) { if (!DOCUMENT_MODEL.equals(getLogicalType(schema))) { throw new RuntimeServiceException("Schema does not match DocumentModel"); } String path = (String) input.get(PATH); GenericRecord documentTypeRecord = (GenericRecord) input.get(PRIMARY_TYPE); DocumentModel doc = new DocumentModelImpl((String) null, path, documentTypeRecord.getSchema().getName()); for (Field schemaField : documentTypeRecord.getSchema().getFields()) { GenericRecord schemaRecord = (GenericRecord) documentTypeRecord.get(schemaField.name()); List<Field> fields = schemaField.schema().getFields(); Map<String, Object> data = new HashMap<>(fields.size()); for (Field field : fields) { data.put(service.decodeName(field.name()), service.fromAvro(field.schema(), Property.class, schemaRecord.get(field.name()))); } doc.setProperties(service.decodeName(schemaField.name()), data); } return doc; }
Source:
<code>public ElideResponse delete(String baseUrlEndPoint, String path, String jsonApiDocument, MultivaluedMap<String, String> queryParams, User opaqueUser, String apiVersion, UUID requestId) { <START> return delete(baseUrlEndPoint, path, jsonApiDocument, queryParams, null, opaqueUser, apiVersion, requestId); <END> }</code><technical_language>empty hashmap</technical_language>

Target:
public ElideResponse delete(String baseUrlEndPoint, String path, String jsonApiDocument, MultivaluedMap<String, String> queryParams, User opaqueUser, String apiVersion, UUID requestId) { return delete(baseUrlEndPoint, path, jsonApiDocument, queryParams, Collections.emptyMap(), opaqueUser, apiVersion, requestId); }
Source:
<code>private Page processColumnSource() { DriverAbortSignal signal = operatorContext.getDriverContext().getAbortSignal(); if (!finishing && !signal.isAborted()) { int rowsProcessed = cursorProcessor.process(operatorContext.getSession().toConnectorSession(), signal, cursor, ROWS_PER_PAGE, pageBuilder); pageSourceMemoryContext.setBytes(cursor.getSystemMemoryUsage()); long bytesProcessed = cursor.getCompletedBytes() - completedBytes; long elapsedNanos = cursor.getReadTimeNanos() - readTimeNanos; operatorContext.recordGeneratedInput(bytesProcessed, rowsProcessed, elapsedNanos); completedBytes = cursor.getCompletedBytes(); readTimeNanos = cursor.getReadTimeNanos(); if (rowsProcessed == 0) { finishing = true; } } Page page = null; <START> if (!pageBuilder.isEmpty() && (finishing || signal.isAborted() || pageBuilder.isFull())) { <END> page = pageBuilder.build(); pageBuilder.reset(); } pageBuilderMemoryContext.setBytes(pageBuilder.getRetainedSizeInBytes()); return page; }</code><technical_language>if signal.isAborted() bother producing a page. OTOH, I understand check isAborted() in loops, loop yielding anyway</technical_language>

Target:
private Page processColumnSource() { DriverYieldSignal yieldSignal = operatorContext.getDriverContext().getYieldSignal(); if (!finishing && !yieldSignal.isSet()) { CursorProcessorOutput output = cursorProcessor.process(operatorContext.getSession().toConnectorSession(), yieldSignal, cursor, pageBuilder); pageSourceMemoryContext.setBytes(cursor.getSystemMemoryUsage()); long bytesProcessed = cursor.getCompletedBytes() - completedBytes; long elapsedNanos = cursor.getReadTimeNanos() - readTimeNanos; operatorContext.recordGeneratedInput(bytesProcessed, output.getProcessedRows(), elapsedNanos); completedBytes = cursor.getCompletedBytes(); readTimeNanos = cursor.getReadTimeNanos(); finishing = output.isNoMoreRows(); } Page page = null; if (!pageBuilder.isEmpty() && (finishing || pageBuilder.isFull())) { page = pageBuilder.build(); pageBuilder.reset(); } pageBuilderMemoryContext.setBytes(pageBuilder.getRetainedSizeInBytes()); return page; }
Source:
<code>public ArrayList<Brick> getBricksRequiringResources(int resource) { ArrayList<Brick> resourceBrickList = new ArrayList<Brick>(); for (Brick brick : brickList) { <START> if ((brick.getRequiredResources() & resource) > 0) { <END> resourceBrickList.add(brick); } } return resourceBrickList; }</code><technical_language>!=</technical_language>

Target:
public List<Brick> getBricksRequiringResources(int resource) { List<Brick> resourceBrickList = new ArrayList<Brick>(); for (Brick brick : brickList) { if ((brick.getRequiredResources() & resource) != 0) { resourceBrickList.add(brick); } } return resourceBrickList; }
Source:
<code><START> public void searchPayments_getsResultsFromConnector_withNoBillingAddress() { <END> String payments = aPaginatedPaymentSearchResult() .withPayments(aSuccessfulSearchPayment() .withCardDetails(new CardDetails("1234", "1234", "Card Holder", "11/21", null, "Visa")) .withNumberOfResults(1) .getResults()) .build(); connectorMock.respondOk_whenSearchCharges(GATEWAY_ACCOUNT_ID, payments); ImmutableMap<String, String> queryParams = ImmutableMap.of(); searchPayments(API_KEY, queryParams) .statusCode(200) .contentType(JSON) .body("results[0].card_details", not(hasKey("billing_address"))) .body("results[0].card_details.first_digits_card_number", is("1234")); }</code><technical_language>This is covered searchPayments_shouldOnlyReturnAllowedProperties</technical_language>

Target:
public void searchPayments_getsResultsFromConnector_withNoBillingAddress() { String payments = aPaginatedPaymentSearchResult() .withPayments(aSuccessfulSearchPayment() .withCardDetails(new CardDetails("1234", "1234", "Card Holder", "11/21", null, "Visa")) .withNumberOfResults(1) .getResults()) .build(); connectorMock.respondOk_whenSearchCharges(GATEWAY_ACCOUNT_ID, payments); ImmutableMap<String, String> queryParams = ImmutableMap.of(); searchPayments(API_KEY, queryParams) .statusCode(200) .contentType(JSON) .body("results[0].card_details", hasKey("billing_address")) .body("results[0].card_details.billing_address", is(nullValue())) .body("results[0].card_details.first_digits_card_number", is("1234")); }