auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public List<String> getArguments() { return Lists.newArrayList(_incomingTimeColumn, _outgoingTimeColumn); }

Target:
public List<String> getArguments() { return Collections.singletonList(_incomingTimeColumn); }
Source:
public boolean isEnabled() { PerfPlugin plugin = PerfPlugin.getDefault(); IPath workingDir = plugin.getWorkingDir(); URI curStatDataURI = null; URI prevStatDataURI = null; if (workingDir != null) { IPath curStatData = plugin.getPerfFile(PerfPlugin.PERF_DEFAULT_STAT); IPath prevStatData = plugin.getPerfFile(PerfPlugin.PERF_DEAFULT_OLD_STAT); IRemoteFileProxy proxy = null; try { curStatDataURI = new URI(curStatData.toPortableString()); prevStatDataURI = new URI(prevStatData.toPortableString()); proxy = RemoteProxyManager.getInstance().getFileProxy(curStatDataURI); } catch (URISyntaxException e) { e.printStackTrace(); } catch (CoreException e) { e.printStackTrace(); } IFileStore curFileStore = proxy.getResource(curStatDataURI.getPath()); IFileStore prevFileStore = proxy.getResource(prevStatDataURI.getPath()); return (curFileStore.fetchInfo().exists() && prevFileStore.fetchInfo().exists()); } return false; }

Target:
public boolean isEnabled() { PerfPlugin plugin = PerfPlugin.getDefault(); IPath workingDir = plugin.getWorkingDir(); URI curStatDataURI = null; URI prevStatDataURI = null; if (workingDir != null) { IPath curStatData = plugin.getPerfFile(PerfPlugin.PERF_DEFAULT_STAT); IPath prevStatData = plugin.getPerfFile(PerfPlugin.PERF_DEAFULT_OLD_STAT); IRemoteFileProxy proxy = null; try { curStatDataURI = new URI(curStatData.toPortableString()); prevStatDataURI = new URI(prevStatData.toPortableString()); proxy = RemoteProxyManager.getInstance().getFileProxy(curStatDataURI); } catch (URISyntaxException e) { MessageDialog.openError(Display.getCurrent().getActiveShell(), Messages.MsgProxyError, Messages.MsgProxyError); } catch (CoreException e) { MessageDialog.openError(Display.getCurrent().getActiveShell(), Messages.MsgProxyError, Messages.MsgProxyError); } IFileStore curFileStore = proxy.getResource(curStatDataURI.getPath()); IFileStore prevFileStore = proxy.getResource(prevStatDataURI.getPath()); return (curFileStore.fetchInfo().exists() && prevFileStore.fetchInfo().exists()); } return false; }
Source:
public final void start() throws LifecycleException { final ModelControllerClientConfiguration.Builder clientConfigBuilder = new ModelControllerClientConfiguration.Builder() .setProtocol(containerConfig.getManagementProtocol()) .setHostName(containerConfig.getManagementAddress()) .setPort(containerConfig.getManagementPort()) .setAuthenticationConfigUri(authenticationConfig); final int connectionTimeout = containerConfig.getConnectionTimeout(); if(0 != connectionTimeout) { clientConfigBuilder.setConnectionTimeout(connectionTimeout); } if(containerConfig.getUsername() != null) { Authentication.username = containerConfig.getUsername(); Authentication.password = containerConfig.getPassword(); clientConfigBuilder.setHandler(getCallbackHandler()); } mccProvider.setDelegate(ModelControllerClient.Factory.create(clientConfigBuilder.build())); try { final Properties jndiProps = new Properties(); jndiProps.setProperty(Context.URL_PKG_PREFIXES, JBOSS_URL_PKG_PREFIX); jndiContext.set(new InitialContext(jndiProps)); } catch (final NamingException ne) { throw new LifecycleException("Could not set JNDI Naming Context", ne); } try { startInternal(); } catch (LifecycleException e) { safeCloseClient(); throw e; } }

Target:
public final void start() throws LifecycleException { final ModelControllerClientConfiguration.Builder clientConfigBuilder = new ModelControllerClientConfiguration.Builder() .setProtocol(containerConfig.getManagementProtocol()) .setHostName(containerConfig.getManagementAddress()) .setPort(containerConfig.getManagementPort()) .setAuthenticationConfigUri(authenticationConfig); final int connectionTimeout = containerConfig.getConnectionTimeout(); if(connectionTimeout > 0) { clientConfigBuilder.setConnectionTimeout(connectionTimeout); } if(containerConfig.getUsername() != null) { Authentication.username = containerConfig.getUsername(); Authentication.password = containerConfig.getPassword(); clientConfigBuilder.setHandler(getCallbackHandler()); } mccProvider.setDelegate(ModelControllerClient.Factory.create(clientConfigBuilder.build())); try { final Properties jndiProps = new Properties(); jndiProps.setProperty(Context.URL_PKG_PREFIXES, JBOSS_URL_PKG_PREFIX); jndiContext.set(new InitialContext(jndiProps)); } catch (final NamingException ne) { throw new LifecycleException("Could not set JNDI Naming Context", ne); } try { startInternal(); } catch (LifecycleException e) { safeCloseClient(); throw e; } }
Source:
public void setLogsUrl(String logsUrl) { this.logsUrl = logsUrl; }

Target:
public void setLogsUrl(String logsUrl) { if (!StringUtils.isEmpty(logsUrl)) { this.logsUrl = logsUrl; } }
Source:
public @NonNull ByteBuffer getBody() { return fBody; }

Target:
public ByteBuffer getBody() { return fBody; }
Source:
@Override public View getView(int position, View convertView, ViewGroup parent) { SquaredImageView view = (SquaredImageView) convertView; if (view == null) { view = new SquaredImageView(context); view.setScaleType(CENTER_CROP); } String url = getItem(position); Picasso.with(context) .load(url) .key(Uri.parse(url).getLastPathSegment()) .placeholder(R.drawable.placeholder) .error(R.drawable.error) .fit() .into(view); return view; }

Target:
@Override public View getView(int position, View convertView, ViewGroup parent) { SquaredImageView view = (SquaredImageView) convertView; if (view == null) { view = new SquaredImageView(context); view.setScaleType(CENTER_CROP); } String url = getItem(position); Picasso.with(context) .load(url) .placeholder(R.drawable.placeholder) .error(R.drawable.error) .fit() .into(view); return view; }
Source:
public void validate(Object obj, Errors errors) { super.validate(obj, errors); DrugOrder order = (DrugOrder) obj; if (order == null) { errors.reject("error.general"); } else { ValidationUtils.rejectIfEmpty(errors, "asNeeded", "error.null"); if (order.getAction() != Order.Action.DISCONTINUE) { ValidationUtils.rejectIfEmpty(errors, "dosingType", "error.null"); } if (order.getDrug() == null || order.getDrug().getConcept() == null) { ValidationUtils.rejectIfEmpty(errors, "concept", "error.null"); } if (order.getConcept() != null && order.getDrug() != null && order.getDrug().getConcept() != null && !order.getDrug().getConcept().equals(order.getConcept())) { errors.rejectValue("drug", "error.general"); errors.rejectValue("concept", "error.concept"); } if (order.getAction() != Order.Action.DISCONTINUE && order.getDosingType() != null) { DosingInstructions dosingInstructions = order.getDosingInstructionsInstance(); dosingInstructions.validate(order, errors); } if (order.getConcept() == null && order.getDrugNonCoded() != null) { if (order.getDrugNonCoded().equals(Context.getOrderService().getNonCodedDrugConcept())) { order.setConcept(Context.getOrderService().getNonCodedDrugConcept()); } } validateFieldsForOutpatientCareSettingType(order, errors); validatePairedFields(order, errors); validateUnitsAreAmongAllowedConcepts(errors, order); validateForRequireDrug(errors, order); ValidateUtil.validateFieldLengths(errors, obj.getClass(), "asNeededCondition", "brandName"); } }

Target:
public void validate(Object obj, Errors errors) { super.validate(obj, errors); DrugOrder order = (DrugOrder) obj; if (order == null) { errors.reject("error.general"); } else { ValidationUtils.rejectIfEmpty(errors, "asNeeded", "error.null"); if (order.getAction() != Order.Action.DISCONTINUE) { ValidationUtils.rejectIfEmpty(errors, "dosingType", "error.null"); } if (order.getDrug() == null || order.getDrug().getConcept() == null) { ValidationUtils.rejectIfEmpty(errors, "concept", "error.null"); } if (order.getConcept() != null && order.getDrug() != null && order.getDrug().getConcept() != null && !order.getDrug().getConcept().equals(order.getConcept())) { errors.rejectValue("drug", "error.general"); errors.rejectValue("concept", "error.concept"); } if (order.getAction() != Order.Action.DISCONTINUE && order.getDosingType() != null) { DosingInstructions dosingInstructions = order.getDosingInstructionsInstance(); dosingInstructions.validate(order, errors); } if (order.getDrug() == null && order.getDrugNonCoded() != null) { order.setConcept(Context.getOrderService().getNonCodedDrugConcept()); } } validateFieldsForOutpatientCareSettingType(order, errors); validatePairedFields(order, errors); validateUnitsAreAmongAllowedConcepts(errors, order); validateForRequireDrug(errors, order); ValidateUtil.validateFieldLengths(errors, obj.getClass(), "asNeededCondition", "brandName"); }
Source:
Optional<String> selectTableToCompactInternal(Transaction tx) { Map<String, Long> tableToLastTimeSwept = sweepHistoryProvider.getHistory(tx); Map<String, Long> tableToLastTimeCompacted = compactionHistoryProvider.getHistory(tx); Optional<String> tableToCompact = maybeChooseUncompactedTable(tableToLastTimeSwept, tableToLastTimeCompacted); if (!tableToCompact.isPresent()) { tableToCompact = maybeChooseTableSweptAfterCompact(tableToLastTimeSwept,tableToLastTimeCompacted); } if (!tableToCompact.isPresent()) { tableToCompact = maybeChooseTableCompactedOver1HourAgo(tableToLastTimeSwept, tableToLastTimeCompacted); } if (!tableToCompact.isPresent()) { log.info("Not compacting, because it does not appear that any table has been swept" + " or they were compacted too recently (the past hour)."); } return tableToCompact; }

Target:
Optional<String> selectTableToCompactInternal(Transaction tx) { Map<String, Long> tableToLastTimeSwept = sweepHistoryProvider.getHistory(tx); Map<String, Long> tableToLastTimeCompacted = compactionHistoryProvider.getHistory(tx); Optional<String> tableToCompact = maybeChooseUncompactedTable(tableToLastTimeSwept, tableToLastTimeCompacted); if (!tableToCompact.isPresent()) { tableToCompact = maybeChooseTableSweptAfterCompact(tableToLastTimeSwept, tableToLastTimeCompacted); } if (!tableToCompact.isPresent()) { tableToCompact = maybeChooseTableCompactedOver1HourAgo(tableToLastTimeCompacted); } if (!tableToCompact.isPresent()) { log.info("Not compacting, because it does not appear that any table has been swept" + " or they were compacted too recently (the past hour)."); } return tableToCompact; }
Source:
private void initDatesBanner(CourseBannerInfoModel courseBannerInfo) { LayoutCourseDatesBannerBinding bannerViewBinding = DataBindingUtil.inflate(getLayoutInflater(), R.layout.layout_course_dates_banner, listView, false); if (courseBannerInfo != null && !isVideoMode && isOnCourseOutline && !courseBannerInfo.getHasEnded()) { String buttonText = ""; switch (courseBannerInfo.getDatesBannerInfo().getCourseBannerType()) { case UPGRADE_TO_GRADED: bannerViewBinding.bannerInfo.setText(getText(R.string.course_dates_banner_upgrade_to_graded)); break; case UPGRADE_TO_RESET: bannerViewBinding.bannerInfo.setText(getText(R.string.course_dates_banner_upgrade_to_reset)); break; case RESET_DATES: bannerViewBinding.bannerInfo.setText(getText(R.string.course_dates_banner_reset_date)); buttonText = getContextOrThrow().getString(R.string.course_dates_banner_reset_date_button); break; case INFO_BANNER: bannerViewBinding.bannerInfo.setText(getText(R.string.course_dates_info_banner)); break; case BLANK: break; } if (listView.getHeaderViewsCount() == 0 && !TextUtils.isEmpty(bannerViewBinding.bannerInfo.getText())) { if (!TextUtils.isEmpty(buttonText)) { bannerViewBinding.btnShiftDates.setText(buttonText); bannerViewBinding.btnShiftDates.setVisibility(View.VISIBLE); bannerViewBinding.btnShiftDates.setOnClickListener(v -> { resetCourseDatesBanner(true); }); } listView.addHeaderView(bannerViewBinding.getRoot()); isBannerVisible = true; } } else { listView.removeHeaderView(bannerViewBinding.getRoot()); isBannerVisible = false; } }

Target:
private void initDatesBanner(CourseBannerInfoModel courseBannerInfo) { LayoutCourseDatesBannerBinding bannerViewBinding = DataBindingUtil.inflate(getLayoutInflater(), R.layout.layout_course_dates_banner, listView, false); if (courseBannerInfo != null && !isVideoMode && isOnCourseOutline && !courseBannerInfo.getHasEnded()) { String buttonText = ""; switch (courseBannerInfo.getDatesBannerInfo().getCourseBannerType()) { case UPGRADE_TO_GRADED: bannerViewBinding.bannerInfo.setText(getText(R.string.course_dates_banner_upgrade_to_graded)); break; case UPGRADE_TO_RESET: bannerViewBinding.bannerInfo.setText(getText(R.string.course_dates_banner_upgrade_to_reset)); break; case RESET_DATES: bannerViewBinding.bannerInfo.setText(getText(R.string.course_dates_banner_reset_date)); buttonText = getContextOrThrow().getString(R.string.course_dates_banner_reset_date_button); break; case INFO_BANNER: bannerViewBinding.bannerInfo.setText(getText(R.string.course_dates_info_banner)); break; case BLANK: listView.removeHeaderView(bannerViewBinding.getRoot()); isBannerVisible = false; break; } if (listView.getHeaderViewsCount() == 0 && !TextUtils.isEmpty(bannerViewBinding.bannerInfo.getText())) { if (!TextUtils.isEmpty(buttonText)) { bannerViewBinding.btnShiftDates.setText(buttonText); bannerViewBinding.btnShiftDates.setVisibility(View.VISIBLE); bannerViewBinding.btnShiftDates.setOnClickListener(v -> { resetCourseDatesBanner(); }); } listView.addHeaderView(bannerViewBinding.getRoot()); isBannerVisible = true; } } else { listView.removeHeaderView(bannerViewBinding.getRoot()); isBannerVisible = false; } }
Source:
private synchronized void handleSeal(RequestMsg req, ChannelHandlerContext ctx, IServerRouter r) { try { final long epoch = req.getPayload().getSealRequest().getEpoch(); String remoteHostAddress; try { remoteHostAddress = ((InetSocketAddress)ctx.channel().remoteAddress()).getAddress().getHostAddress(); } catch(NullPointerException ex) { remoteHostAddress = "unavailable"; } log.info("handleSeal[{}]: Received SEAL from (clientId={}:{}), moving to new epoch {},", req.getHeader().getRequestId(), req.getHeader().getClientId(), remoteHostAddress, epoch); serverContext.setServerEpoch(epoch, r); HeaderMsg responseHeader = getHeaderMsg(req.getHeader(), false, true); ResponseMsg response = getResponseMsg(responseHeader, getSealResponseMsg()); r.sendResponse(response, ctx); } catch (WrongEpochException e) { log.debug("handleSeal[{}]: Rejected SEAL current={}, requested={}", req.getHeader().getRequestId(), e.getCorrectEpoch(), req.getPayload().getSealRequest().getEpoch()); r.sendWrongEpochError(req.getHeader(), ctx, e.getCorrectEpoch()); } }

Target:
private synchronized void handleSeal(RequestMsg req, ChannelHandlerContext ctx, IServerRouter r) { try { final long epoch = req.getPayload().getSealRequest().getEpoch(); String remoteHostAddress; try { remoteHostAddress = ((InetSocketAddress)ctx.channel().remoteAddress()).getAddress().getHostAddress(); } catch (NullPointerException ex) { remoteHostAddress = "unavailable"; } log.info("handleSeal[{}]: Received SEAL from (clientId={}:{}), moving to new epoch {},", req.getHeader().getRequestId(), req.getHeader().getClientId(), remoteHostAddress, epoch); serverContext.setServerEpoch(epoch, r); HeaderMsg responseHeader = getHeaderMsg(req.getHeader(), false, true); ResponseMsg response = getResponseMsg(responseHeader, getSealResponseMsg()); r.sendResponse(response, ctx); } catch (WrongEpochException e) { log.debug("handleSeal[{}]: Rejected SEAL current={}, requested={}", req.getHeader().getRequestId(), e.getCorrectEpoch(), req.getPayload().getSealRequest().getEpoch()); HeaderMsg responseHeader = getHeaderMsg(req.getHeader(), false, true); ResponseMsg response = getResponseMsg(responseHeader, getWrongEpochErrorMsg(e.getCorrectEpoch())); r.sendResponse(response, ctx); } }
Source:
private ImmutableList<String> createCommand() { final ImmutableList.Builder<String> command = ImmutableList.builder(); command.addAll(groovyc.getCommandPrefix(resolver)); String classpath = Joiner.on(":").join(transform(declaredClasspathEntries, toStringFunction())); command .add("-cp") .add(classpath.isEmpty() ? "''" : classpath) .add("-d") .add(outputDirectory.toString()); addCrossCompilationOptions(command); command.addAll(extraArguments.or(ImmutableList.<String>of())) .addAll(transform(sourceFilePaths, toStringFunction())); return command.build(); }

Target:
private ImmutableList<String> createCommand() { final ImmutableList.Builder<String> command = ImmutableList.builder(); command.addAll(groovyc.getCommandPrefix(resolver)); String classpath = Joiner.on(File.pathSeparator).join(transform(declaredClasspathEntries, toStringFunction())); command .add("-cp") .add(classpath.isEmpty() ? "''" : classpath) .add("-d") .add(outputDirectory.toString()); addCrossCompilationOptions(command); command.addAll(extraArguments.or(ImmutableList.<String>of())) .addAll(transform(sourceFilePaths, toStringFunction())); return command.build(); }
Source:
private void initialize() { if(!customHttpClient) { this.connectionManager = connectionManagerFactory.newConnectionManager( !this.sslHostnameValidationEnabled, this.hostProperties.getMaxTotalConnections(), this.hostProperties.getMaxPerRouteConnections(), this.hostProperties.getTimeToLive(), this.hostProperties.getTimeUnit(), null); this.httpClient = newClient(); this.connectionManagerTimer.schedule(new TimerTask() { @Override public void run() { if (SimpleHostRoutingFilter.this.connectionManager == null) { return; } SimpleHostRoutingFilter.this.connectionManager.closeExpiredConnections(); } }, 30000, 5000); try { HttpServletRequest.class.getMethod("getContentLengthLong"); } catch(NoSuchMethodException e) { useServlet31 = false; } } }

Target:
private void initialize() { if(!customHttpClient) { this.connectionManager = connectionManagerFactory.newConnectionManager( !this.sslHostnameValidationEnabled, this.hostProperties.getMaxTotalConnections(), this.hostProperties.getMaxPerRouteConnections(), this.hostProperties.getTimeToLive(), this.hostProperties.getTimeUnit(), null); this.httpClient = newClient(); this.connectionManagerTimer.schedule(new TimerTask() { @Override public void run() { if (SimpleHostRoutingFilter.this.connectionManager == null) { return; } SimpleHostRoutingFilter.this.connectionManager.closeExpiredConnections(); } }, 30000, 5000); } }
Source:
public void encodedData() throws Exception { WebTarget target = client.target(generateURL()); String data = target.path("test/signed/text").request().get(String.class); logger.info(data); client.close(); }

Target:
public void encodedData() throws Exception { WebTarget target = client.target(generateURL()); String data = target.path("test/signed/text").request().get(String.class); logger.info(data); }
Source:
public void testParagraphs() throws Exception { CollectionReaderDescription reader = createReaderDescription( ConllUReader.class, ConllUReader.PARAM_LANGUAGE, "en", ConllUReader.PARAM_SOURCE_LOCATION, "src/test/resources/conll/u_v2/", ConllUReader.PARAM_PATTERNS, "conllu-multiple_paragraphs.conll"); JCas jcas = new JCasIterable(reader).iterator().next(); AnnotationIndex<Paragraph> index = jcas.getAnnotationIndex(Paragraph.class); List<String> paragraphIDs = new LinkedList<>(); Iterator<Paragraph> iterator = index.iterator(); while(iterator.hasNext()) { Paragraph p = iterator.next(); paragraphIDs.add(p.getId()); } List<String> expectedParagraphIDs = new ArrayList<String>(){{ add("mf920901-001-p1"); add("mf920901-001-p2"); }}; Assert.assertEquals(expectedParagraphIDs, paragraphIDs); final String expectedTextContent = "Slovenská ústava: pro i proti Slovenská ústava: pro i" + " proti\n" + "\n" + "Slovenská ústava: pro i proti"; final String actualTextContent = jcas.getDocumentText(); Assert.assertEquals(expectedTextContent, actualTextContent); String[] sentences = { "Slovenská ústava: pro i proti", "Slovenská ústava: pro i proti", "Slovenská ústava: pro i proti" }; assertSentence(sentences, select(jcas, Sentence.class)); }

Target:
public void testParagraphs() throws Exception { CollectionReaderDescription reader = createReaderDescription( ConllUReader.class, ConllUReader.PARAM_LANGUAGE, "en", ConllUReader.PARAM_SOURCE_LOCATION, "src/test/resources/conll/u_v2/", ConllUReader.PARAM_PATTERNS, "conllu-multiple_paragraphs.conll"); JCas jcas = new JCasIterable(reader).iterator().next(); AnnotationIndex<Paragraph> index = jcas.getAnnotationIndex(Paragraph.class); List<String> paragraphIDs = new ArrayList<>(); Iterator<Paragraph> iterator = index.iterator(); while (iterator.hasNext()) { Paragraph p = iterator.next(); paragraphIDs.add(p.getId()); } List<String> expectedParagraphIDs = new ArrayList<String>() { { add("mf920901-001-p1"); add("mf920901-001-p2"); } }; Assert.assertEquals(expectedParagraphIDs, paragraphIDs); final String expectedTextContent = "Slovenská ústava: pro i proti Slovenská ústava: pro i" + " proti\n" + "\n" + "Slovenská ústava: pro i proti"; final String actualTextContent = jcas.getDocumentText(); Assert.assertEquals(expectedTextContent, actualTextContent); String[] sentences = { "Slovenská ústava: pro i proti", "Slovenská ústava: pro i proti", "Slovenská ústava: pro i proti" }; assertSentence(sentences, select(jcas, Sentence.class)); }
Source:
private boolean isIllegalImport(String importText) { boolean isIllegal = false; for (String element : illegalPkgs) { if (importText.startsWith(element + ".")) { isIllegal = true; } } return isIllegal; }

Target:
private boolean isIllegalImport(String importText) { boolean isIllegal = false; for (String element : illegalPkgs) { if (importText.startsWith(element + ".")) { isIllegal = true; break; } } return isIllegal; }
Source:
protected boolean checkStorageDomainStatusNotEqual(StorageDomainStatus status) { boolean returnValue = false; if (getStorageDomainStatus() != null && getStorageDomainStatus() != null) { returnValue = (getStorageDomainStatus() != status); if (!returnValue) { addStorageDomainStatusIllegalMessage(); } } return returnValue; }

Target:
protected boolean checkStorageDomainStatusNotEqual(StorageDomainStatus status) { boolean returnValue = false; if (getStorageDomainStatus() != null) { returnValue = (getStorageDomainStatus() != status); if (!returnValue) { addStorageDomainStatusIllegalMessage(); } } return returnValue; }
Source:
protected String getPairs(Map<String, String> data, int page) { StringBuilder pairs = new StringBuilder(); if (data == null || data.isEmpty()) { pairs.append(IGitHubConstants.PARAM_PAGE).append("=").append(page); pairs.append("&"); pairs.append(IGitHubConstants.PARAM_PER_PAGE).append("=") .append(PER_PAGE); } else { int i = 1; for (Entry<String, String> entry : data.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); pairs.append(key).append("=").append(value); if (i < data.size()) { pairs.append("&"); } i++; } } return pairs.toString(); }

Target:
protected String getPairs(Map<String, String> data, int page) { StringBuilder pairs = new StringBuilder(); if (data == null || data.isEmpty()) { pairs.append(IGitHubConstants.PARAM_PAGE).append('=').append(page); pairs.append('&'); pairs.append(IGitHubConstants.PARAM_PER_PAGE).append('=') .append(PER_PAGE); } else { int i = 1; for (Entry<String, String> entry : data.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); pairs.append(key).append('=').append(value); if (i < data.size()) pairs.append('&'); i++; } } return pairs.toString(); }
Source:
private static boolean isFeatureFinderMetaboHere(String path) throws FeatureFinderMetaboException { return execShellCommand(path).contains(FEATURE_FINDER_METABO_EVAL); }

Target:
private static boolean isFeatureFinderMetaboHere(String path) throws MSDKException { return execShellCommand(path).contains(FEATURE_FINDER_METABO_EVAL); }
Source:
public void testGetMcqWeights_allChoicesNull_weightsListShouldBeEmpty() { ______TS("Failure: Weights enabled, null choices, custom weights, other disabled"); FeedbackMcqQuestionDetails mcqDetails = new FeedbackMcqQuestionDetails(); HashMap<String, String[]> requestParams = new HashMap<>(); requestParams.put(Const.ParamsNames.FEEDBACK_QUESTION_TYPE, new String[] { "MCQ" }); requestParams.put(Const.ParamsNames.FEEDBACK_QUESTION_TEXT, new String[] { "mcq question text" }); requestParams.put(Const.ParamsNames.FEEDBACK_QUESTION_MCQ_GENERATED_OPTIONS, new String[] { "NONE" }); requestParams.put(Const.ParamsNames.FEEDBACK_QUESTION_NUMBEROFCHOICECREATED, new String[] { "2" }); requestParams.put(Const.ParamsNames.FEEDBACK_QUESTION_MCQ_WEIGHTS_ASSIGNED, new String[] { "on" }); requestParams.put(Const.ParamsNames.FEEDBACK_QUESTION_MCQ_WEIGHT + "-0", new String[] { "1.50" }); requestParams.put(Const.ParamsNames.FEEDBACK_QUESTION_MCQ_WEIGHT + "-1", new String[] { "2.50" }); assertTrue(mcqDetails.extractQuestionDetails(requestParams, FeedbackQuestionType.MCQ)); assertEquals(mcqDetails.getQuestionType(), FeedbackQuestionType.MCQ); assertTrue(mcqDetails instanceof FeedbackMcqQuestionDetails); assertTrue(mcqDetails.hasAssignedWeights()); assertTrue(mcqDetails.getMcqChoices().isEmpty()); assertTrue(mcqDetails.getMcqWeights().isEmpty()); assertFalse(mcqDetails.getOtherEnabled()); assertEquals(0.0, mcqDetails.getMcqOtherWeight()); }

Target:
public void testGetMcqWeights_allChoicesNull_weightsListShouldBeEmpty() { FeedbackMcqQuestionDetails mcqDetails = new FeedbackMcqQuestionDetails(); HashMap<String, String[]> requestParams = new HashMap<>(); requestParams.put(Const.ParamsNames.FEEDBACK_QUESTION_TYPE, new String[] { "MCQ" }); requestParams.put(Const.ParamsNames.FEEDBACK_QUESTION_TEXT, new String[] { "mcq question text" }); requestParams.put(Const.ParamsNames.FEEDBACK_QUESTION_MCQ_GENERATED_OPTIONS, new String[] { "NONE" }); requestParams.put(Const.ParamsNames.FEEDBACK_QUESTION_NUMBEROFCHOICECREATED, new String[] { "2" }); requestParams.put(Const.ParamsNames.FEEDBACK_QUESTION_MCQ_HAS_WEIGHTS_ASSIGNED, new String[] { "on" }); requestParams.put(Const.ParamsNames.FEEDBACK_QUESTION_MCQ_WEIGHT + "-0", new String[] { "1.50" }); requestParams.put(Const.ParamsNames.FEEDBACK_QUESTION_MCQ_WEIGHT + "-1", new String[] { "2.50" }); assertTrue(mcqDetails.extractQuestionDetails(requestParams, FeedbackQuestionType.MCQ)); assertEquals(mcqDetails.getQuestionType(), FeedbackQuestionType.MCQ); assertTrue(mcqDetails instanceof FeedbackMcqQuestionDetails); assertTrue(mcqDetails.hasAssignedWeights()); assertTrue(mcqDetails.getMcqChoices().isEmpty()); assertTrue(mcqDetails.getMcqWeights().isEmpty()); assertFalse(mcqDetails.getOtherEnabled()); assertEquals(0.0, mcqDetails.getMcqOtherWeight()); }
Source:
public final ClientBuilder connectTimeout(long connectTimeout, TimeUnit unit) { if (thisConnectTimeout.isPresent()) { Preconditions.checkArgument(!thisConnectTimeout.isPresent(), "connectTimeout already set"); } thisConnectTimeout = Optional.of(Duration.millis(TimeUnit.MILLISECONDS.convert(connectTimeout, unit))); return this; }

Target:
public final ClientBuilder connectTimeout(long connectTimeout, TimeUnit unit) { Preconditions.checkArgument(!thisConnectTimeout.isPresent(), "connectTimeout already set"); thisConnectTimeout = Optional.of(Duration.millis(TimeUnit.MILLISECONDS.convert(connectTimeout, unit))); return this; }
Source:
private <R> R performWithConnection(Function<Object, R> function) { Optional<MutableConfigurationStats> stats = getMutableConfigurationStats(executionContext); RetryPolicyTemplate retryPolicy = (RetryPolicyTemplate) executionContext.getRetryPolicyTemplate().orElseGet(NoRetryPolicyTemplate::new); CompletableFuture<R> future = retryPolicy.applyPolicy(() -> completedFuture(withConnection(function)), e -> shouldRetry(e, executionContext), e -> { }, e -> stats.ifPresent(s -> s.discountInflightOperation()), identity(), executionContext.getCurrentScheduler()); try { return future.get(); } catch (Exception e) { throw new MuleRuntimeException(createStaticMessage(COULD_NOT_RECONNECT), e); } }

Target:
private <R> R performWithConnection(Function<Object, R> function) { Optional<MutableConfigurationStats> stats = getMutableConfigurationStats(executionContext); RetryPolicyTemplate retryPolicy = (RetryPolicyTemplate) executionContext.getRetryPolicyTemplate().orElseGet(NoRetryPolicyTemplate::new); CompletableFuture<R> future = retryPolicy.applyPolicy(() -> completedFuture(withConnection(function)), e -> !isFirstPage && !delegate.useStickyConnections() && shouldRetry(e, executionContext), e -> { }, e -> stats.ifPresent(s -> s.discountInflightOperation()), identity(), executionContext.getCurrentScheduler()); try { return future.get(); } catch (Exception e) { throw new MuleRuntimeException(createStaticMessage(COULD_NOT_EXECUTE), e); } }
Source:
public Storage.Buckets.Delete deleteBucketRequest(String bucket) throws IOException { return storage.buckets().delete(bucket); }

Target:
public Storage.Buckets.Delete deleteBucketRequest(String bucket) throws IOException { Preconditions.checkArgument(!Strings.isNullOrEmpty(bucket)); return storage.buckets().delete(bucket); }
Source:
public void testDefaultNormalizerEmailURL() { String[] testSentence = new String[] {"a", "abc0io@examlpe.com", "c", "d", "e", "f", "<LINK_0>", "h"}; String[] testResult = new String[] {"a", "$EMAIL$", "c", "d", "e", "f", "$URL$", "h"}; TokenNormalizerFeatureGenerator featureGenerator = new TokenNormalizerFeatureGenerator(new IdentityFeatureGenerator()); for (int i = 0; i < testSentence.length; i++) { featureGenerator.createFeatures(features, testSentence, i, null); Assert.assertEquals(features.get(i), testResult[i]); } }

Target:
public void testDefaultNormalizerEmailURL() { String[] testSentence = new String[] {"a", "abc0io@example.com", "c", "d", "e", "f", "<LINK_0>", "h"}; String[] testResult = new String[] {"a", "$EMAIL$", "c", "d", "e", "f", "$URL$", "h"}; TokenNormalizerFeatureGenerator featureGenerator = new TokenNormalizerFeatureGenerator(new IdentityFeatureGenerator()); List<String> features = new ArrayList<>(); for (int i = 0; i < testSentence.length; i++) { featureGenerator.createFeatures(features, testSentence, i, null); Assert.assertEquals(features.get(i), testResult[i]); } }
Source:
public static TestingSemiTransactionalHiveMetastore create() { HiveClientConfig config = new HiveClientConfig(); HdfsConfiguration hdfsConfiguration = new HiveHdfsConfiguration(new HdfsConfigurationInitializer(config), ImmutableSet.of()); HdfsEnvironment hdfsEnvironment = new HdfsEnvironment(hdfsConfiguration, config, new NoHdfsAuthentication()); HiveCluster hiveCluster = new TestingHiveCluster(config, "dummy", 1111); ExtendedHiveMetastore delegate = new BridgingHiveMetastore(new ThriftHiveMetastore(hiveCluster)); ExecutorService executor = newCachedThreadPool(daemonThreadsNamed("hive-%s")); ListeningExecutorService renameExecutor = listeningDecorator(executor); return new TestingSemiTransactionalHiveMetastore(hdfsEnvironment, delegate, renameExecutor, false, false); }

Target:
public static TestingSemiTransactionalHiveMetastore create() { HiveClientConfig config = new HiveClientConfig(); HdfsConfiguration hdfsConfiguration = new HiveHdfsConfiguration(new HdfsConfigurationInitializer(config), ImmutableSet.of()); HdfsEnvironment hdfsEnvironment = new HdfsEnvironment(hdfsConfiguration, config, new NoHdfsAuthentication()); HiveCluster hiveCluster = new TestingHiveCluster(config, HOST, PORT); ExtendedHiveMetastore delegate = new BridgingHiveMetastore(new ThriftHiveMetastore(hiveCluster)); ExecutorService executor = newCachedThreadPool(daemonThreadsNamed("hive-%s")); ListeningExecutorService renameExecutor = listeningDecorator(executor); return new TestingSemiTransactionalHiveMetastore(hdfsEnvironment, delegate, renameExecutor, false, false); }
Source:
default List<T> intersperse(T element) { return isEmpty() ? Nil.instance() : foldRight(empty(), (x, xs) -> xs.isEmpty() ? xs.prepend(x) : xs.prepend(element).prepend(x)); }

Target:
default List<T> intersperse(T element) { return ofAll(iterator().intersperse(element)); }
Source:
private boolean isProtocolNameInconsistent(String protocolName) { return protocolName != null && !protocolName.equals(generation().protocol); }

Target:
private boolean isProtocolNameInconsistent(String protocolName) { return protocolName != null && !protocolName.equals(generation().protocolName); }
Source:
public String toString(){ if (this.extra == null) { return "NullInfoRegistry<" + this.nullBit1 + this.nullBit2 + this.nullBit3 + this.nullBit4 + ">"; } else { StringBuilder sb = new StringBuilder("NullInfoRegistry<["); sb.append(this.nullBit1); sb.append(this.nullBit2); sb.append(this.nullBit3); sb.append(this.nullBit4); int i, ceil; for (i = 0, ceil = this.extra[0].length > 3 ? 3 : this.extra[0].length; i < ceil; i++) { sb.append(","); sb.append(this.extra[2][i]); sb.append(this.extra[3][i]); sb.append(this.extra[4][i]); sb.append(this.extra[5][i]); } if (ceil < this.extra[0].length) { sb.append(",..."); } sb.append("]>"); return sb.toString(); } }

Target:
public String toString(){ if (this.extra == null) { StringBuilder sb = new StringBuilder("NullInfoRegistry<"); sb.append(this.nullBit1); sb.append(this.nullBit2); sb.append(this.nullBit3); sb.append(this.nullBit4); sb.append(">"); return sb.toString(); } else { StringBuilder sb = new StringBuilder("NullInfoRegistry<["); sb.append(this.nullBit1); sb.append(this.nullBit2); sb.append(this.nullBit3); sb.append(this.nullBit4); int i, ceil; for (i = 0, ceil = this.extra[0].length > 3 ? 3 : this.extra[0].length; i < ceil; i++) { sb.append(","); sb.append(this.extra[2][i]); sb.append(this.extra[3][i]); sb.append(this.extra[4][i]); sb.append(this.extra[5][i]); } if (ceil < this.extra[0].length) { sb.append(",..."); } sb.append("]>"); return sb.toString(); } }
Source:
private static Looper newLooper(boolean canQuit) { return ReflectionHelpers.callConstructor( Looper.class, ReflectionHelpers.ClassParameter.from(boolean.class, canQuit)); }

Target:
private static Looper newLooper(boolean canQuit) { return ReflectionHelpers.callConstructor( Looper.class, ClassParameter.from(boolean.class, canQuit)); }
Source:
public DBObject getSortObject() { BasicDBObject sort = (BasicDBObject) getOptions().getSortDBObject(); return (sort == null) ? null : new BasicDBObject(sort); }

Target:
public DBObject getSortObject() { DBObject sort = getOptions().getSortDBObject(); return (sort == null) ? null : new BasicDBObject(sort.toMap()); }
Source:
private void simulateFileUpload(final String mediaId, final String mediaUrl) { Thread thread = new Thread() { @Override public void run() { try { float count = (float) 0.1; while (count < 1.1) { sleep(500); ((EditorMediaUploadListener) mEditorFragment).onMediaUploadProgress(mediaId, false, count); count += 0.1; } MediaFile mediaFile = new MediaFile(); mediaFile.setMediaId(MEDIA_REMOTE_ID_SAMPLE); mediaFile.setFileURL(mediaUrl); ((EditorMediaUploadListener) mEditorFragment).onMediaUploadSucceeded(mediaId, mediaFile); if (mFailedUploads.containsKey(mediaId)) { mFailedUploads.remove(mediaId); } } catch (InterruptedException e) { e.printStackTrace(); } } }; thread.start(); }

Target:
private void simulateFileUpload(final String mediaId, final String mediaUrl) { Thread thread = new Thread() { @Override public void run() { try { float count = (float) 0.1; while (count < 1.1) { sleep(500); ((EditorMediaUploadListener) mEditorFragment).onMediaUploadProgress(mediaId, count); count += 0.1; } MediaFile mediaFile = new MediaFile(); mediaFile.setMediaId(MEDIA_REMOTE_ID_SAMPLE); mediaFile.setFileURL(mediaUrl); ((EditorMediaUploadListener) mEditorFragment).onMediaUploadSucceeded(mediaId, mediaFile); if (mFailedUploads.containsKey(mediaId)) { mFailedUploads.remove(mediaId); } } catch (InterruptedException e) { e.printStackTrace(); } } }; thread.start(); }
Source:
private static Optional<FirstStrikeStepOrder> calculateAttackerSteps( final @NonNull BattleState battleState) { final ReturnFire returnFireAgainstAttackingSubs = returnFireAgainstAttackingSubs( battleState.getAttackingUnits(), battleState.getDefendingUnits(), battleState.getGameData()); switch (returnFireAgainstAttackingSubs) { case ALL: return Optional.of(OFFENDER_NO_SNEAK_ATTACK); case SUBS: return Optional.of(OFFENDER_SNEAK_ATTACK_WITH_OPPOSING_FIRST_STRIKE); case NONE: return Optional.of(OFFENDER_SNEAK_ATTACK); default: return Optional.empty(); } }

Target:
private static FirstStrikeStepOrder calculateAttackerSteps( final @NonNull BattleState battleState) { final ReturnFire returnFireAgainstAttackingSubs = returnFireAgainstAttackingSubs( battleState.getAttackingUnits(), battleState.getDefendingUnits(), battleState.getGameData()); switch (returnFireAgainstAttackingSubs) { case ALL: return OFFENDER_NO_SNEAK_ATTACK; case SUBS: return OFFENDER_SNEAK_ATTACK_WITH_OPPOSING_FIRST_STRIKE; case NONE: return OFFENDER_SNEAK_ATTACK; default: return NOT_APPLICABLE; } }
Source:
protected boolean validateContent(AzureBlobFileSystem fs, Path path, byte[] originalByteArray) throws IOException { FSDataInputStream in = fs.open(path); byte[] contentByteArray = new byte[originalByteArray.length]; int seekPos = 0; while (in.read() != -1) { in.seek(seekPos); contentByteArray[seekPos] = (byte) (in.read()); seekPos++; } return Arrays.equals(contentByteArray, originalByteArray); }

Target:
protected boolean validateContent(AzureBlobFileSystem fs, Path path, byte[] originalByteArray) throws IOException { int pos = 0; int lenOfOriginalByteArray = originalByteArray.length; try (FSDataInputStream in = fs.open(path)) { byte valueOfContentAtPos = (byte) in.read(); while (valueOfContentAtPos != -1 && pos < lenOfOriginalByteArray) { if (originalByteArray[pos] != valueOfContentAtPos) { assertEquals("Mismatch in content validation at position {}", pos, originalByteArray[pos], valueOfContentAtPos); return false; } valueOfContentAtPos = (byte) in.read(); pos++; } if (valueOfContentAtPos != -1) { assertEquals("Expected end of file", -1, valueOfContentAtPos); return false; } return true; } }
Source:
public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException { if (session.getAccesstoken() == null) throw new AccessDeniedException("There is no accesstoken in session!"); }

Target:
public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException { if (session.getAccesstoken() == null) { throw new AccessDeniedException("There is no accesstoken in session!"); } }
Source:
private List<FieldInfo> processSasFile(String filename) { StringUtilities.outputWithTime("Scanning table " + filename); List<FieldInfo> fieldInfos = new ArrayList<>(); FileInputStream inputStream; try { inputStream = new FileInputStream(new File(filename)); SasFileReader sasFileReader = new SasFileReaderImpl(inputStream); SasFileProperties sasFileProperties = sasFileReader.getSasFileProperties(); for (Column column : sasFileReader.getColumns()) { fieldInfos.add(new FieldInfo(column.getName())); } for (int i = 0; i < sasFileProperties.getRowCount(); i++) { Object[] row = sasFileReader.readNext(); if (row.length == fieldInfos.size()) { for (int j = 0; j < row.length; j++) { fieldInfos.get(j).processValue(row[j] == null ? "" : row[j].toString()); } } if (sampleSize != -1 && i == sampleSize) break; } inputStream.close(); } catch (IOException e) { e.printStackTrace(); } for (FieldInfo fieldInfo : fieldInfos) { fieldInfo.trim(); } return fieldInfos; }

Target:
private List<FieldInfo> processSasFile(String filename) { StringUtilities.outputWithTime("Scanning table " + filename); List<FieldInfo> fieldInfos = new ArrayList<>(); try(FileInputStream inputStream = new FileInputStream(new File(filename))) { SasFileReader sasFileReader = new SasFileReaderImpl(inputStream); SasFileProperties sasFileProperties = sasFileReader.getSasFileProperties(); for (Column column : sasFileReader.getColumns()) { fieldInfos.add(new FieldInfo(column.getName())); } for (int lineNr = 0; lineNr < sasFileProperties.getRowCount(); lineNr++) { Object[] row = sasFileReader.readNext(); if (row.length == fieldInfos.size()) { for (int i = 0; i < row.length; i++) { fieldInfos.get(i).processValue(row[i] == null ? "" : row[i].toString()); } } if (lineNr == sampleSize) break; } inputStream.close(); } catch (IOException e) { e.printStackTrace(); } for (FieldInfo fieldInfo : fieldInfos) { fieldInfo.trim(); } return fieldInfos; }
Source:
public default void inc() { inc(1); }

Target:
default void inc() { inc(1); }
Source:
protected abstract void remoteGetBeforeWrite(InvocationContext ctx, WriteCommand command, Object key) throws Throwable; protected boolean readNeedsRemoteGet(InvocationContext ctx, AbstractDataCommand command) { if (command.hasFlag(Flag.CACHE_MODE_LOCAL) || command.hasFlag(Flag.SKIP_REMOTE_LOOKUP)) { return false; } Object key = command.getKey(); ConsistentHash ch = stateTransferManager.getCacheTopology().getReadConsistentHash(); boolean shouldFetchFromRemote = ctx.isOriginLocal() && !isValueAvailableLocally(ch, key); if (!shouldFetchFromRemote && getLog().isTraceEnabled()) { getLog().tracef("Not doing a remote get for key %s since entry is mapped to current node (%s) or is in L1. Owners are %s", toStr(key), rpcManager.getAddress(), ch.locateOwners(key)); } return shouldFetchFromRemote; }

Target:
protected abstract void remoteGetBeforeWrite(InvocationContext ctx, WriteCommand command, Object key) throws Throwable; protected boolean readNeedsRemoteValue(InvocationContext ctx, AbstractDataCommand command) { if (!ctx.isOriginLocal() || command.hasFlag(Flag.CACHE_MODE_LOCAL) || command.hasFlag(Flag.SKIP_REMOTE_LOOKUP)) { return false; } Object key = command.getKey(); ConsistentHash ch = stateTransferManager.getCacheTopology().getReadConsistentHash(); boolean shouldFetchFromRemote = !isValueAvailableLocally(ch, key); if (!shouldFetchFromRemote && getLog().isTraceEnabled()) { getLog().tracef("Not doing a remote get for key %s since entry is mapped to current node (%s) or is in L1. Owners are %s", toStr(key), rpcManager.getAddress(), ch.locateOwners(key)); } return shouldFetchFromRemote; }
Source:
private void configureImageButton(ThemeViewHolder themeViewHolder, final String themeId, final boolean isPremium, boolean isCurrent) { final PopupMenu popupMenu = new PopupMenu(mContext, themeViewHolder.mImageButton); popupMenu.getMenuInflater().inflate(R.menu.theme_more, popupMenu.getMenu()); configureMenuForTheme(popupMenu.getMenu(), isCurrent); popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { int i = item.getItemId(); if (i == R.id.menu_activate) { if (!isPremium || (mSitePlanId == PlansConstants.PREMIUM_PLAN_ID || mSitePlanId == PlansConstants.BUSINESS_PLAN_ID)) { mCallback.onActivateSelected(themeId); } else { mCallback.onDetailsSelected(themeId); } } else if (i == R.id.menu_try_and_customize) { mCallback.onTryAndCustomizeSelected(themeId); } else if (i == R.id.menu_view) { mCallback.onViewSelected(themeId); } else if (i == R.id.menu_details) { mCallback.onDetailsSelected(themeId); } else { mCallback.onSupportSelected(themeId); } return true; } }); themeViewHolder.mImageButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { popupMenu.show(); } }); }

Target:
private void configureImageButton(ThemeViewHolder themeViewHolder, final String themeId, final boolean isPremium, boolean isCurrent) { final PopupMenu popupMenu = new PopupMenu(mContext, themeViewHolder.mImageButton); popupMenu.getMenuInflater().inflate(R.menu.theme_more, popupMenu.getMenu()); configureMenuForTheme(popupMenu.getMenu(), isCurrent); popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { int i = item.getItemId(); if (i == R.id.menu_activate) { if (canActivateThemeDirectly(isPremium, mSitePlanId)) { mCallback.onActivateSelected(themeId); } else { mCallback.onDetailsSelected(themeId); } } else if (i == R.id.menu_try_and_customize) { mCallback.onTryAndCustomizeSelected(themeId); } else if (i == R.id.menu_view) { mCallback.onViewSelected(themeId); } else if (i == R.id.menu_details) { mCallback.onDetailsSelected(themeId); } else { mCallback.onSupportSelected(themeId); } return true; } }); themeViewHolder.mImageButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { popupMenu.show(); } }); }
Source:
public List<User> getUsers() { return Collections.unmodifiableList(mConnectedUsers); }

Target:
public List<User> getUsers() { return Collections.unmodifiableList(mUsers); }
Source:
public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/gui/**").addResourceLocations("/WEB-INF/static/"); super.addResourceHandlers(registry); }

Target:
public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/gui/**").addResourceLocations("/WEB-INF/static/"); registry.addResourceHandler("/webjars/**").addResourceLocations("/webjars/"); super.addResourceHandlers(registry); }
Source:
public void testListDataSetsBasics() { TestClusterPartitionReleaser partitionReleaser = new TestClusterPartitionReleaser(); final ResourceManagerPartitionTracker tracker = new ResourceManagerPartitionTrackerImpl(partitionReleaser); assertEquals(0, tracker.listDataSets().size()); tracker.processTaskExecutorClusterPartitionReport( TASK_EXECUTOR_ID_1, createClusterPartitionReport(DATA_SET_ID, 1, PARTITION_ID_1)); final Map<IntermediateDataSetID, DataSetMetaInfo> listing = tracker.listDataSets(); assertThat(listing, hasKey(DATA_SET_ID)); DataSetMetaInfo metaInfo = listing.get(DATA_SET_ID); assertEquals(1, metaInfo.getNumTotalPartitions()); tracker.processTaskExecutorClusterPartitionReport( TASK_EXECUTOR_ID_1, EMPTY_PARTITION_REPORT); assertEquals(0, tracker.listDataSets().size()); }

Target:
public void testListDataSetsBasics() { final ResourceManagerPartitionTrackerImpl tracker = new ResourceManagerPartitionTrackerImpl(new TestClusterPartitionReleaser()); assertThat(tracker.listDataSets().size(), is(0)); report(tracker, TASK_EXECUTOR_ID_1, DATA_SET_ID, 1, PARTITION_ID_1); final Map<IntermediateDataSetID, DataSetMetaInfo> listing = tracker.listDataSets(); assertThat(listing, hasKey(DATA_SET_ID)); DataSetMetaInfo metaInfo = listing.get(DATA_SET_ID); assertThat(metaInfo.getNumTotalPartitions(), is(1)); reportEmpty(tracker, TASK_EXECUTOR_ID_1); assertThat(tracker.listDataSets().size(), is(0)); assertThat(tracker.areAllMapsEmpty(), is(true)); }
Source:
public void testRebindCheckingMemoryLeak() throws Exception { TestEntity c1 = origApp.addChild(EntitySpec.create(TestEntity.class)); Entities.manage(c1); c1.setConfig(TestEntity.CONF_NAME, Strings.makeRandomId(1000000)); gcAndLog("before"); long used0 = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); for (int i=0; i<500; i++) { doPartialRebindOfIds(c1.getId()); origManagementContext.getGarbageCollector().gcIteration(); gcAndLog("iteration "+i); if (i==5) used0 = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); } gcAndLog("after"); long used1 = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); Assert.assertTrue(used1 - used0 < 5000000, "Expected leak of less than 5M; leak was: from "+Strings.makeJavaSizeString(used0)+" to "+Strings.makeJavaSizeString(used1)); }

Target:
public void testRebindCheckingMemoryLeak() throws Exception { TestEntity c1 = origApp.addChild(EntitySpec.create(TestEntity.class)); Entities.manage(c1); c1.setConfig(TestEntity.CONF_NAME, Strings.makeRandomId(1000000)); gcAndLog("before"); long used0 = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); for (int i=0; i<200; i++) { doPartialRebindOfIds(c1.getId()); origManagementContext.getGarbageCollector().gcIteration(); gcAndLog("iteration "+i); if (i==5) used0 = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); } gcAndLog("after"); long used1 = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); Assert.assertTrue(used1 - used0 < 5000000, "Expected leak of less than 5M; leak was: from "+Strings.makeJavaSizeString(used0)+" to "+Strings.makeJavaSizeString(used1)); }
Source:
public SortedSet<String> getJobNames() { return jobNames; }

Target:
public Set<String> getJobNames() { return Collections.unmodifiableSet(jobNames); }