auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static Integer getConceptIdForUnits(String units) { String appDataDir = OpenmrsUtil.getApplicationDataDirectory(); Properties props = new Properties(); String conceptId = null; try { FileInputStream fis = new FileInputStream(appDataDir + System.getProperty("file.separator") + DatabaseUtil.ORDER_ENTRY_UPGRADE_SETTINGS_FILENAME); props.load(fis); for (Map.Entry prop : props.entrySet()) { if (prop.getKey().equals(units)) { conceptId = prop.getValue().toString(); if (conceptId != null) { fis.close(); return Integer.valueOf(conceptId); } else { fis.close(); return null; } } } } catch (NumberFormatException e) { throw new APIException("upgrade.settings.file.invalid.mapping", new Object[] { units, conceptId }, e); } catch (IOException e) { if (e instanceof FileNotFoundException) { throw new APIException("upgrade.settings.unable.find.file", new Object[] { appDataDir }, e); } else { throw new APIException(e); } } throw new APIException("upgrade.settings.file.not.have.mapping", new Object[] { units }); }

Target:
public static Integer getConceptIdForUnits(String units) { String appDataDir = OpenmrsUtil.getApplicationDataDirectory(); Properties props = new Properties(); String conceptId = null; try { FileInputStream fis = new FileInputStream(appDataDir + System.getProperty("file.separator") + DatabaseUtil.ORDER_ENTRY_UPGRADE_SETTINGS_FILENAME); props.load(fis); for (Map.Entry prop : props.entrySet()) { if (prop.getKey().equals(units)) { conceptId = prop.getValue().toString(); if (conceptId != null) { return Integer.valueOf(conceptId); } else { return null; } } } fis.close(); } catch (NumberFormatException e) { throw new APIException("upgrade.settings.file.invalid.mapping", new Object[] { units, conceptId }, e); } catch (IOException e) { if (e instanceof FileNotFoundException) { throw new APIException("upgrade.settings.unable.find.file", new Object[] { appDataDir }, e); } else { throw new APIException(e); } } throw new APIException("upgrade.settings.file.not.have.mapping", new Object[] { units }); }
Source:
private void assertWritable() { Assert.isLegal(!hasStyle(widget, SWT.READ_ONLY), "TextBox is read-only"); }

Target:
private void assertWritable() { assertEnabled(); SWTBotAssert.assertVisible(this); Assert.isLegal(!hasStyle(widget, SWT.READ_ONLY), "TextBox is read-only"); }
Source:
public FeatureIterator(final Path inputPath, final FeatureCodec<FEATURE_TYPE, SOURCE> codec) { if (inputPath == null) { throw new IllegalArgumentException("FeatureIterator input file cannot be null"); } this.codec = codec; this.inputPath = Paths.get(codec.getPathToDataFile(inputPath.toUri().toString())); try { if (IOUtil.hasBlockCompressedExtension(inputPath)) { final BlockCompressedInputStream bcs = initIndexableBlockCompressedStream(inputPath); source = (SOURCE) codec.makeIndexableSourceFromStream(bcs); } else { final PositionalBufferedStream ps = initIndexablePositionalStream(inputPath); source = (SOURCE) codec.makeIndexableSourceFromStream(ps); } this.codec.readHeader(source); readNextFeature(); } catch (final IOException e) { throw new TribbleException.InvalidHeader("Error reading header " + e.getMessage()); } }

Target:
public FeatureIterator(final Path inputPath, final FeatureCodec<FEATURE_TYPE, SOURCE> codec) { ValidationUtils.nonNull(inputPath, "FeatureIterator input path cannot be null"); this.codec = codec; final String filePath = codec.getPathToDataFile(inputPath.toUri().toString()); try { this.inputPath = IOUtil.getPath(filePath); } catch (final IOException e) { throw new TribbleException("Failed while constructing a FeatureIterator due to a problem converting String to Path", e); } try { if (IOUtil.hasBlockCompressedExtension(this.inputPath)) { final BlockCompressedInputStream bcs = initIndexableBlockCompressedStream(this.inputPath); source = (SOURCE) codec.makeIndexableSourceFromStream(bcs); } else { final PositionalBufferedStream ps = initIndexablePositionalStream(this.inputPath); source = (SOURCE) codec.makeIndexableSourceFromStream(ps); } this.codec.readHeader(source); readNextFeature(); } catch (final IOException e) { throw new TribbleException.InvalidHeader("Error reading header " + e.getMessage()); } }
Source:
public void closeEnvironment() throws IOException { final EC2Environment env = this.mockEnvironment(); env.close(); MatcherAssert.assertThat( env.toString(), Matchers .containsString( "EC2 `instance` instance accessed with Mock for EC2Client" ) ); }

Target:
public void closeEnvironment() throws IOException { final EC2Environment env = this.mockEnvironment(); env.close(); }
Source:
private ICPPEvaluation createOperatorOverloadEvaluation(ICPPFunction overload, IASTNode point, ICPPEvaluation arg1, ICPPEvaluation arg2) { EvalFunctionCall operatorCall; if(overload instanceof ICPPMethod) { EvalMemberAccess opAccess = new EvalMemberAccess(arg1.getType(point), ValueCategory.LVALUE, overload, arg1, false, point); ICPPEvaluation[] args = new ICPPEvaluation[]{opAccess, arg2}; operatorCall = new EvalFunctionCall(args, arg1, point); } else { ICPPASTName name = new CPPASTName(overload.getNameCharArray()); name.setBinding(overload); IASTIdExpression idExpr = new CPPASTIdExpression(name); ICPPEvaluation op = EvalID.create(idExpr); ICPPEvaluation[] args = new ICPPEvaluation[]{op, arg1, arg2}; operatorCall = new EvalFunctionCall(args, null, point); } return operatorCall; }

Target:
private ICPPEvaluation createOperatorOverloadEvaluation(ICPPFunction overload, IASTNode point, ICPPEvaluation arg1, ICPPEvaluation arg2) { EvalFunctionCall operatorCall; if(overload instanceof ICPPMethod) { EvalMemberAccess opAccess = new EvalMemberAccess(arg1.getType(point), ValueCategory.LVALUE, overload, arg1, false, point); ICPPEvaluation[] args = new ICPPEvaluation[]{opAccess, arg2}; operatorCall = new EvalFunctionCall(args, arg1, point); } else { EvalBinding op = new EvalBinding(overload, overload.getType(), point); ICPPEvaluation[] args = new ICPPEvaluation[]{op, arg1, arg2}; operatorCall = new EvalFunctionCall(args, null, point); } return operatorCall; }
Source:
public static String authoriseChargeUrlForApplePay(String chargeId) { return "/v1/frontend/charges/{chargeId}/wallets/apple-pay".replace("{chargeId}", chargeId); }

Target:
public static String authoriseChargeUrlForApplePay(String chargeId) { return "/v1/frontend/charges/{chargeId}/wallets/apple".replace("{chargeId}", chargeId); }
Source:
public void removeAndRestoreManyLogs() { gaeSimulation.loginAsAdmin("admin"); gaeSimulation.clearLogs(); Instant today = TimeHelper.getInstantDaysOffsetFromNow(0); insertLogMessageAtTimeWithInterval(logMessages.get(LOG_MESSAGE_INDEX_MANY_LOGS), today.toEpochMilli(), LOG_MESSAGE_INTERVAL_MANY_LOGS); }

Target:
public void removeAndRestoreManyLogs() { gaeSimulation.loginAsAdmin("admin"); gaeSimulation.clearLogs(); insertLogMessageAtTimeWithInterval(logMessages.get(LOG_MESSAGE_INDEX_MANY_LOGS), Instant.now().toEpochMilli(), LOG_MESSAGE_INTERVAL_MANY_LOGS); }
Source:
protected ListenableFuture<Map<Long, Long>> getCommitTimestamps( @Nullable TableReference tableRef, Iterable<Long> startTimestamps, boolean shouldWaitForCommitterToComplete, AsyncTransactionService asyncTransactionService) { if (Iterables.isEmpty(startTimestamps)) { return Futures.immediateFuture(ImmutableMap.of()); } Map<Long, Long> startToCommitTimestamps = Maps.newHashMap(); Set<Long> gets = Sets.newHashSet(); for (Long startTs : startTimestamps) { Long cached = timestampValidationReadCache.getCommitTimestampIfPresent(startTs); if (cached != null) { startToCommitTimestamps.put(startTs, cached); } else { gets.add(startTs); } } if (gets.isEmpty()) { return Futures.immediateFuture(startToCommitTimestamps); } if (shouldWaitForCommitterToComplete) { waitForCommitterToComplete(tableRef, startTimestamps); } traceGetCommitTimestamps(tableRef, gets); if (gets.size() > transactionConfig.get().getThresholdForLoggingLargeNumberOfTransactionLookups()) { logLargeNumberOfTransactions(tableRef, gets); } getCounter(AtlasDbMetricNames.NUMBER_OF_TRANSACTIONS_READ_FROM_DB, tableRef).inc(gets.size()); return Futures.transform(loadCommitTimestamps(asyncTransactionService, gets), rawResults -> { for (Map.Entry<Long, Long> e : rawResults.entrySet()) { if (e.getValue() != null) { Long startTs = e.getKey(); Long commitTs = e.getValue(); startToCommitTimestamps.put(startTs, commitTs); timestampValidationReadCache.putAlreadyCommittedTransaction(startTs, commitTs); } } return startToCommitTimestamps; }, MoreExecutors.directExecutor()); }

Target:
protected ListenableFuture<Map<Long, Long>> getCommitTimestamps( @Nullable TableReference tableRef, Iterable<Long> startTimestamps, boolean shouldWaitForCommitterToComplete, AsyncTransactionService asyncTransactionService) { if (Iterables.isEmpty(startTimestamps)) { return Futures.immediateFuture(ImmutableMap.of()); } Map<Long, Long> startToCommitTimestamps = Maps.newHashMap(); Set<Long> gets = Sets.newHashSet(); for (Long startTs : startTimestamps) { Long cached = timestampValidationReadCache.getCommitTimestampIfPresent(startTs); if (cached != null) { startToCommitTimestamps.put(startTs, cached); } else { gets.add(startTs); } } if (gets.isEmpty()) { return Futures.immediateFuture(startToCommitTimestamps); } if (shouldWaitForCommitterToComplete) { waitForCommitterToComplete(tableRef, startTimestamps); } traceGetCommitTimestamps(tableRef, gets); if (gets.size() > transactionConfig.get().getThresholdForLoggingLargeNumberOfTransactionLookups()) { logLargeNumberOfTransactions(tableRef, gets); } getHistogram(AtlasDbMetricNames.NUMBER_OF_TRANSACTIONS_READ_FROM_DB, tableRef).update(gets.size()); return Futures.transform(loadCommitTimestamps(asyncTransactionService, gets), rawResults -> { for (Map.Entry<Long, Long> e : rawResults.entrySet()) { if (e.getValue() != null) { Long startTs = e.getKey(); Long commitTs = e.getValue(); startToCommitTimestamps.put(startTs, commitTs); timestampValidationReadCache.putAlreadyCommittedTransaction(startTs, commitTs); } } return startToCommitTimestamps; }, MoreExecutors.directExecutor()); }
Source:
private void compute() { log.trace("Start compute continuous {}", summary.variable.getName()); double variance = summary.descriptiveStats.getVariance(); if(Double.isNaN(variance) || Double.isInfinite(variance) || variance <= 0) return; IntervalFrequency intervalFrequency = new IntervalFrequency(summary.descriptiveStats.getMin(), summary.descriptiveStats.getMax(), summary.intervals, summary.getVariable().getValueType() == IntegerType.get()); for(double d : summary.descriptiveStats.getSortedValues()) { intervalFrequency.add(d); } for(IntervalFrequency.Interval interval : intervalFrequency.intervals()) { summary.intervalFrequencies.add(interval); } RealDistribution realDistribution = summary.distribution.getDistribution(summary.descriptiveStats); for(Double p : summary.defaultPercentiles) { summary.percentiles.add(summary.descriptiveStats.getPercentile(p)); if(realDistribution != null) { summary.distributionPercentiles.add(realDistribution.inverseCumulativeProbability(p / 100d)); } } Iterator<String> concat = freqNames(summary.frequencyDist); while(concat.hasNext()) { String value = concat.next(); summary.frequencies.add(new Frequency(value, summary.frequencyDist.getCount(value), Double.isNaN(summary.frequencyDist.getPct(value)) ? 0.0 : summary.frequencyDist.getPct(value), !value.equals(NOT_NULL_NAME))); } }

Target:
private void compute() { log.trace("Start compute continuous {}", summary.variable.getName()); double variance = summary.descriptiveStats.getVariance(); if(Double.isNaN(variance) || Double.isInfinite(variance) || variance <= 0) return; IntervalFrequency intervalFrequency = new IntervalFrequency(summary.descriptiveStats.getMin(), summary.descriptiveStats.getMax(), summary.intervals, summary.getVariable().getValueType() == IntegerType.get()); for(double d : summary.descriptiveStats.getSortedValues()) { intervalFrequency.add(d); } for(IntervalFrequency.Interval interval : intervalFrequency.intervals()) { summary.intervalFrequencies.add(interval); } RealDistribution realDistribution = summary.distribution.getDistribution(summary.descriptiveStats); for(Double p : summary.defaultPercentiles) { summary.percentiles.add(summary.descriptiveStats.getPercentile(p)); if(realDistribution != null) { summary.distributionPercentiles.add(realDistribution.inverseCumulativeProbability(p / 100d)); } } Iterator<String> concat = freqNames(summary.frequencyDist); while(concat.hasNext()) { String value = concat.next(); summary.frequencies.add(new Frequency(value, summary.frequencyDist.getCount(value), Double.isNaN(summary.frequencyDist.getPct(value)) ? 0.0 : summary.frequencyDist.getPct(value), !NOT_NULL_NAME.equals(value))); } }
Source:
private static int getInCoreLimit(Config config) { return config.getInt( ConfigConstants.CONFIG_MERGE_SECTION, ConfigConstants.CONFIG_KEY_IN_CORE_LIMIT, 10); }

Target:
private static int getInCoreLimit(Config config) { return config.getInt( ConfigConstants.CONFIG_MERGE_SECTION, ConfigConstants.CONFIG_KEY_IN_CORE_LIMIT, 10 << 20); }
Source:
public String getQuestionResultStatisticsCsv( List<FeedbackResponseAttributes> responses, FeedbackQuestionAttributes question, FeedbackSessionResultsBundle bundle) { if (responses.isEmpty()) { return ""; } StringBuilder csv = new StringBuilder(); csv.append(getResponseSummaryStatsCsv(responses, bundle)); if (hasAssignedWeights) { csv.append(System.lineSeparator()); csv.append("Per Recipient Statistics").append(System.lineSeparator()); csv.append(getPerRecipientResponseStatsCsv(responses, bundle)); } return csv.toString(); }

Target:
public String getQuestionResultStatisticsCsv( List<FeedbackResponseAttributes> responses, FeedbackQuestionAttributes question, FeedbackSessionResultsBundle bundle) { if (responses.isEmpty()) { return ""; } StringBuilder csv = new StringBuilder(); McqStatistics mcqStats = new McqStatistics(this); csv.append(mcqStats.getResponseSummaryStatsCsv(responses, bundle)); if (hasAssignedWeights) { csv.append(System.lineSeparator()) .append("Per Recipient Statistics").append(System.lineSeparator()) .append(mcqStats.getPerRecipientResponseStatsCsv(responses, bundle)); } return csv.toString(); }
Source:
public final Object[] getChildren(Object element) { final Object[] children; if (element instanceof CompareInputAdapter) { children = getCompareInputAdapterChildren((CompareInputAdapter)element); } else if (element instanceof ICompareInput) { children = new Object[] {}; } else { children = super.getChildren(element); } Iterable<?> compareInputs = adapt(children, getAdapterFactory(), ICompareInput.class); return toArray(compareInputs, Object.class); }

Target:
public final synchronized Object[] getChildren(Object element) { final Object[] children; if (element instanceof CompareInputAdapter) { children = getCompareInputAdapterChildren((CompareInputAdapter)element); } else if (element instanceof ICompareInput) { children = new Object[] {}; } else { children = super.getChildren(element); } final Object[] compareInputChildren; if (!Iterables.all(Arrays.asList(children), Predicates.instanceOf(PendingUpdateAdapter.class))) { Iterable<?> compareInputs = adapt(children, getAdapterFactory(), ICompareInput.class); compareInputChildren = toArray(compareInputs, Object.class); } else { compareInputChildren = children; } return compareInputChildren; }
Source:
public void testRequestsWithContent() throws Exception { HttpClient mockClient = mock(HttpClient.class); HttpResponse mockResponse = mock(HttpResponse.class); when(mockClient.execute(any(HttpUriRequest.class))).thenReturn(mockResponse); ApacheHttpTransport transport = new ApacheHttpTransport(mockClient); subtestUnsupportedRequestsWithContent( transport.buildRequest("GET", "<LINK_0>"), "GET"); subtestUnsupportedRequestsWithContent( transport.buildRequest("DELETE", "<LINK_0>"), "DELETE"); subtestUnsupportedRequestsWithContent( transport.buildRequest("HEAD", "<LINK_0>"), "HEAD"); execute(transport.buildRequest("PATCH", "<LINK_0>")); execute(transport.buildRequest("PUT", "<LINK_0>")); execute(transport.buildRequest("POST", "<LINK_0>")); execute(transport.buildRequest("PATCH", "<LINK_0>")); }

Target:
public void testRequestsWithContent() throws IOException { HttpClient mockClient = mock(HttpClient.class); HttpResponse mockResponse = mock(HttpResponse.class); when(mockClient.execute(any(HttpUriRequest.class))).thenReturn(mockResponse); ApacheHttpTransport transport = new ApacheHttpTransport(mockClient); subtestUnsupportedRequestsWithContent( transport.buildRequest("GET", "<LINK_0>"), "GET"); subtestUnsupportedRequestsWithContent( transport.buildRequest("DELETE", "<LINK_0>"), "DELETE"); subtestUnsupportedRequestsWithContent( transport.buildRequest("HEAD", "<LINK_0>"), "HEAD"); execute(transport.buildRequest("PATCH", "<LINK_0>")); execute(transport.buildRequest("PUT", "<LINK_0>")); execute(transport.buildRequest("POST", "<LINK_0>")); execute(transport.buildRequest("PATCH", "<LINK_0>")); }
Source:
public void handleRequests(Request request) throws InterruptedException { try { logger.trace("{}", request); DataInputStream stream = new DataInputStream(request.getInputStream()); RequestResponseType type = RequestResponseType.values()[stream.readShort()]; switch (type) { case PutRequest: handlePutRequest(request); break; case GetRequest: handleGetRequest(request); break; case DeleteRequest: handleDeleteRequest(request); break; case TTLRequest: handleTTLRequest(request); break; case ReplicaMetadataRequest: handleReplicaMetadataRequest(request); break; default: throw new UnsupportedOperationException("Request type not supported"); } } catch (Exception e) { e.printStackTrace(); logger.error("Error while handling request" + request + "Closing connection", e); requestResponseChannel.closeConnection(request); } }

Target:
public void handleRequests(Request request) throws InterruptedException { try { logger.trace("{}", request); DataInputStream stream = new DataInputStream(request.getInputStream()); RequestResponseType type = RequestResponseType.values()[stream.readShort()]; switch (type) { case PutRequest: handlePutRequest(request); break; case GetRequest: handleGetRequest(request); break; case DeleteRequest: handleDeleteRequest(request); break; case TTLRequest: handleTTLRequest(request); break; case ReplicaMetadataRequest: handleReplicaMetadataRequest(request); break; default: throw new UnsupportedOperationException("Request type not supported"); } } catch (Exception e) { logger.error("Error while handling request" + request + "Closing connection", e); requestResponseChannel.closeConnection(request); } }
Source:
public void load() { if (CoreModule.user.isSystemAdministrator() || CoreModule.user.hasGroupAccess(GateLabConstants.GROUP_GATELAB)) { for(String GateLabClass:ApplicationModule.reservedGateClasses){ CoreModule.addApplicationsTileGrid(new GateLabTileGrid(GateLabClass)); } } if (CoreModule.user.isSystemAdministrator() || CoreModule.user.hasGroupAccess(GateLabConstants.GROUP_GATELABTEST)) { for(String GateLabClass:ApplicationModule.reservedTestClasses){ CoreModule.addApplicationsTileGrid(new GateLabTileGrid(GateLabClass)); } } TimelineParser.getInstance().addParser(new GateLabTimelineParser()); MonitorParser.getInstance().addParser(new GateLabMonitorParser()); }

Target:
public void load() { if (CoreModule.user.isSystemAdministrator() || CoreModule.user.hasGroupAccess(GateLabConstants.GROUP_GATELAB)) { for(String GateLabClass:ApplicationModule.reservedClasses.keySet()){ if(ApplicationModule.reservedClasses.get(GateLabClass)==0){ CoreModule.addApplicationsTileGrid(new GateLabTileGrid(GateLabClass)); } } } if (CoreModule.user.isSystemAdministrator() || CoreModule.user.hasGroupAccess(GateLabConstants.GROUP_GATELABTEST)) { for(String GateLabClass:ApplicationModule.reservedClasses.keySet()){ if(ApplicationModule.reservedClasses.get(GateLabClass)==1){ CoreModule.addApplicationsTileGrid(new GateLabTileGrid(GateLabClass)); } } } TimelineParser.getInstance().addParser(new GateLabTimelineParser()); MonitorParser.getInstance().addParser(new GateLabMonitorParser()); }
Source:
public void testSizeLimitReachWaits() throws InterruptedException { ExecutorService pool = Executors.newCachedThreadPool(); try { ResourceLimiter resourceLimiter = new ResourceLimiter(1l, 1); final RpcThrottler underTest = new RpcThrottler(resourceLimiter); long id = underTest.registerOperationWithHeapSize(5l); assertTrue(underTest.hasInflightRequests()); assertTrue(resourceLimiter.isFull()); final CountDownLatch secondRequestRegisteredLatch = new CountDownLatch(1); pool.submit(new Runnable() { @Override public void run() { try { underTest.registerOperationWithHeapSize(5l); secondRequestRegisteredLatch.countDown(); } catch (InterruptedException e) { throw new RuntimeException(e); } } }); Thread.sleep(10); assertEquals(1, secondRequestRegisteredLatch.getCount()); resourceLimiter.markCanBeCompleted(id); secondRequestRegisteredLatch.await(1, TimeUnit.MINUTES); } finally { pool.shutdownNow(); } }

Target:
public void testSizeLimitReachWaits() throws InterruptedException { ExecutorService pool = Executors.newCachedThreadPool(); try { ResourceLimiter resourceLimiter = new ResourceLimiter(1l, 1); final RpcThrottler underTest = new RpcThrottler(resourceLimiter); long id = underTest.registerOperationWithHeapSize(5l); assertTrue(underTest.hasInflightRequests()); assertTrue(resourceLimiter.isFull()); final CountDownLatch secondRequestRegisteredLatch = new CountDownLatch(1); pool.submit(new Runnable() { @Override public void run() { try { underTest.registerOperationWithHeapSize(5l); secondRequestRegisteredLatch.countDown(); } catch (InterruptedException e) { throw new RuntimeException(e); } } }); Thread.sleep(10); assertEquals(1, secondRequestRegisteredLatch.getCount()); resourceLimiter.markCanBeCompleted(id); assertTrue(secondRequestRegisteredLatch.await(1, TimeUnit.MINUTES)); } finally { pool.shutdownNow(); } }
Source:
public void testBroadcastWithMaintenance() { final ForeverBroadcastDistributionRule rule = new ForeverBroadcastDistributionRule(ImmutableList.of("large_source")); CoordinatorStats stats = rule.run( null, DruidCoordinatorRuntimeParams.newBuilder() .withDruidCluster(secondCluster) .withSegmentReplicantLookup(SegmentReplicantLookup.make(secondCluster)) .withBalancerReferenceTimestamp(DateTimes.of("2013-01-01")) .withAvailableSegments(Lists.newArrayList( smallSegment, largeSegments.get(0), largeSegments.get(1) )).build(), smallSegment ); assertEquals(1L, stats.getGlobalStat(LoadRule.ASSIGNED_COUNT)); assertEquals(false, stats.hasPerTierStats()); assertEquals(1, generalServer.getPeon().getSegmentsToLoad().size()); assertEquals(1, maintenanceServer1.getPeon().getSegmentsToDrop().size()); assertEquals(0, maintenanceServer2.getPeon().getSegmentsToLoad().size()); }

Target:
public void testBroadcastWithMaintenance() { final ForeverBroadcastDistributionRule rule = new ForeverBroadcastDistributionRule(ImmutableList.of("large_source")); CoordinatorStats stats = rule.run( null, DruidCoordinatorRuntimeParams.newBuilder() .withDruidCluster(secondCluster) .withSegmentReplicantLookup(SegmentReplicantLookup.make(secondCluster)) .withBalancerReferenceTimestamp(DateTimes.of("2013-01-01")) .withAvailableSegments( smallSegment, largeSegments.get(0), largeSegments.get(1) ).build(), smallSegment ); assertEquals(1L, stats.getGlobalStat(LoadRule.ASSIGNED_COUNT)); assertEquals(false, stats.hasPerTierStats()); assertEquals(1, generalServer.getPeon().getSegmentsToLoad().size()); assertEquals(1, maintenanceServer1.getPeon().getSegmentsToDrop().size()); assertEquals(0, maintenanceServer2.getPeon().getSegmentsToLoad().size()); }
Source:
private static void printStream(InputStream in) throws Exception { byte[] buffer = new byte[1024]; try { for (int i = in.read(buffer); i != -1; i = in.read(buffer)) System.err.write(buffer, 0, i); } finally { in.close(); } }

Target:
private static void printStream(InputStream in) throws Exception { byte[] buffer = new byte[1024]; for (int i = in.read(buffer); i != -1; i = in.read(buffer)) System.err.write(buffer, 0, i); }
Source:
private void sendResource(JarFile jar, JarEntry entry, ResourceKey key, HttpServletResponse res) throws IOException { byte[] data = null; if (entry.getSize() <= SMALL_RESOURCE) { data = readWholeEntry(jar, entry); } String contentType = null; String charEnc = null; Attributes atts = entry.getAttributes(); if (atts != null) { contentType = Strings.emptyToNull(atts.getValue("Content-Type")); charEnc = Strings.emptyToNull(atts.getValue("Character-Encoding")); } if (contentType == null) { contentType = mimeUtil.getMimeType(entry.getName(), data).toString(); if ("application/octet-stream".equals(contentType) && entry.getName().endsWith(".js")) { contentType = "application/javascript"; } } long time = entry.getTime(); if (0 < time) { res.setDateHeader("Last-Modified", time); } res.setHeader("Content-Length", Long.toString(entry.getSize())); res.setContentType(contentType); if (charEnc != null) { res.setCharacterEncoding(charEnc); } if (data != null) { resourceCache.put(key, new SmallResource(data) .setContentType(contentType) .setCharacterEncoding(charEnc) .setLastModified(time)); res.getOutputStream().write(data); } else { InputStream in = jar.getInputStream(entry); writeToResponse(res, in); } }

Target:
private void sendResource(JarFile jar, JarEntry entry, ResourceKey key, HttpServletResponse res) throws IOException { byte[] data = null; if (entry.getSize() <= SMALL_RESOURCE) { data = readWholeEntry(jar, entry); } String contentType = null; String charEnc = null; Attributes atts = entry.getAttributes(); if (atts != null) { contentType = Strings.emptyToNull(atts.getValue("Content-Type")); charEnc = Strings.emptyToNull(atts.getValue("Character-Encoding")); } if (contentType == null) { contentType = mimeUtil.getMimeType(entry.getName(), data).toString(); if ("application/octet-stream".equals(contentType) && entry.getName().endsWith(".js")) { contentType = "application/javascript"; } } long time = entry.getTime(); if (0 < time) { res.setDateHeader("Last-Modified", time); } res.setHeader("Content-Length", Long.toString(entry.getSize())); res.setContentType(contentType); if (charEnc != null) { res.setCharacterEncoding(charEnc); } if (data != null) { resourceCache.put(key, new SmallResource(data) .setContentType(contentType) .setCharacterEncoding(charEnc) .setLastModified(time)); res.getOutputStream().write(data); } else { writeToResponse(res, jar.getInputStream(entry)); } }
Source:
public void expressionListVerifyResultTest() { String expressionCollectionJsonString = new TextNode("JsonText").toString(); expressionEvaluator.verifyResult(expressionCollectionJsonString, new ArrayList<>(), null); }

Target:
public void expressionListVerifyResultTest() { String expressionCollectionJsonString = new TextNode("10").toString(); List<BigDecimal> contextValue = Collections.singletonList(BigDecimal.valueOf(10)); assertTrue(expressionEvaluator.verifyResult(expressionCollectionJsonString, contextValue, List.class)); }
Source:
public String rewriteQuery(Query query) { Integer maxRows = query.getMaxRows(); Integer firstRow = query.getFirstRow(); if(firstRow != null && firstRow > 1) { if(query.getOrderByClause().getItemCount() == 0) { throw new MetaModelException("OFFSET requires an ORDER BY clause"); } } if (maxRows == null && (firstRow == null || firstRow.intValue() == 1)) { return super.rewriteQuery(query); } if ((firstRow == null || firstRow.intValue() == 1) && maxRows != null && maxRows > 0) { return super.rewriteQuery(query) + " LIMIT " + maxRows; } final Query innerQuery = query.clone(); innerQuery.setFirstRow(null); innerQuery.setMaxRows(null); final Query outerQuery = new Query(); final FromItem subQuerySelectItem = new FromItem(innerQuery).setAlias("metamodel_subquery"); outerQuery.from(subQuerySelectItem); final List<SelectItem> innerSelectItems = innerQuery.getSelectClause().getItems(); for (SelectItem selectItem : innerSelectItems) { outerQuery.select(new SelectItem(selectItem, subQuerySelectItem)); } final String rewrittenOrderByClause = rewriteOrderByClause(innerQuery, innerQuery.getOrderByClause()); final String rowOver = "ROW_NUMBER() " + "OVER(" + rewrittenOrderByClause + ")"; innerQuery.select(new SelectItem(rowOver, "metamodel_row_number")); innerQuery.getOrderByClause().removeItems(); final String baseQueryString = rewriteQuery(outerQuery); if (maxRows == null) { return baseQueryString + " WHERE metamodel_row_number > " + (firstRow - 1); } return baseQueryString + " WHERE metamodel_row_number BETWEEN " + firstRow + " AND " + (firstRow - 1 + maxRows); }

Target:
public String rewriteQuery(Query query) { Integer maxRows = query.getMaxRows(); Integer firstRow = query.getFirstRow(); if (maxRows == null && (firstRow == null || firstRow.intValue() == 1)) { return super.rewriteQuery(query); } if ((firstRow == null || firstRow.intValue() == 1) && maxRows != null && maxRows > 0) { return super.rewriteQuery(query) + " LIMIT " + maxRows; } else { return getRowNumberSql(query, maxRows, firstRow); } }
Source:
private void updateExpiryTimeForAllPuts(List<IndexEntry> indexEntries) throws StoreException { for (IndexEntry entry : indexEntries) { IndexValue entryValue = entry.getValue(); if (!entryValue.isFlagSet(IndexValue.Flags.Ttl_Update_Index) && !entryValue.isFlagSet( IndexValue.Flags.Delete_Index)) { IndexValue indexValue = index.findKey(entry.getKey()); if (indexValue != null) { entryValue.setExpiresAtMs(indexValue.getExpiresAtMs()); } else { logger.info("No index value found for {}", entry.getKey().getID()); } } } }

Target:
private void updateExpiryTimeForAllPuts(List<IndexEntry> indexEntries) throws StoreException { for (IndexEntry entry : indexEntries) { IndexValue entryValue = entry.getValue(); if (!entryValue.isFlagSet(IndexValue.Flags.Ttl_Update_Index) && !entryValue.isFlagSet( IndexValue.Flags.Delete_Index)) { IndexValue indexValue = index.findKey(entry.getKey()); if (indexValue != null) { entryValue.setExpiresAtMs(indexValue.getExpiresAtMs()); } else { logger.warn("No index value found for {}", entry.getKey().getID()); } } } }
Source:
public void gatewayDiagnosticsOnException() throws CosmosClientException { CosmosItemProperties cosmosItemProperties = getCosmosItemProperties(); CosmosItemResponse createResponse = null; try { createResponse = this.container.createItem(cosmosItemProperties); CosmosItemRequestOptions cosmosItemRequestOptions = new CosmosItemRequestOptions(); cosmosItemRequestOptions.setPartitionKey(new PartitionKey("wrongPartitionKey")); CosmosItemResponse readResponse = this.container.getItem(createResponse.getItem().getId(), null).read(cosmosItemRequestOptions); fail("request should fail as partition key is wrong"); } catch (CosmosClientException exception) { String diagnostics = exception.getCosmosResponseDiagnostics().toString(); assertThat(exception.getStatusCode()).isEqualTo(HttpConstants.StatusCodes.NOTFOUND); assertThat(diagnostics).contains("Connection Mode : " + ConnectionMode.GATEWAY); assertThat(diagnostics).contains("Gateway statistics"); assertThat(diagnostics).contains("Status Code : 404"); assertThat(diagnostics).contains("Operation Type : " + OperationType.Read); assertThat(exception.getCosmosResponseDiagnostics().getRequestLatency()).isNotNull(); System.out.println(diagnostics); } }

Target:
public void gatewayDiagnosticsOnException() throws CosmosClientException { CosmosItemProperties cosmosItemProperties = getCosmosItemProperties(); CosmosItemResponse createResponse = null; try { createResponse = this.container.createItem(cosmosItemProperties); CosmosItemRequestOptions cosmosItemRequestOptions = new CosmosItemRequestOptions(); cosmosItemRequestOptions.setPartitionKey(new PartitionKey("wrongPartitionKey")); CosmosItemResponse readResponse = this.container.getItem(createResponse.getItem().getId(), null).read(cosmosItemRequestOptions); fail("request should fail as partition key is wrong"); } catch (CosmosClientException exception) { String diagnostics = exception.getCosmosResponseDiagnostics().toString(); assertThat(exception.getStatusCode()).isEqualTo(HttpConstants.StatusCodes.NOTFOUND); assertThat(diagnostics).contains("Connection Mode : " + ConnectionMode.GATEWAY); assertThat(diagnostics).contains("Gateway statistics"); assertThat(diagnostics).contains("Status Code : 404"); assertThat(diagnostics).contains("Operation Type : " + OperationType.Read); assertThat(exception.getCosmosResponseDiagnostics().getRequestLatency()).isNotNull(); } }
Source:
public void propertyChange(PropertyChangeEvent evt) { if(evt.getPropertyName().equals(switchToOrFromIOCLogProperty)) { start(); } }

Target:
public void propertyChange(PropertyChangeEvent evt) { if(Objects.equals(evt.getPropertyName(), switchToOrFromIOCLogProperty)) { start(); } }
Source:
protected void doStart() throws Exception { super.doStart(); if (configuration.isWebhookAutoRegister()) { log.info("Registering webhook for endpoint " + delegateEndpoint); delegateEndpoint.registerWebhook(); } }

Target:
protected void doStart() throws Exception { super.doStart(); if (configuration.isWebhookAutoRegister()) { log.info("Registering webhook for endpoint {}", delegateEndpoint); delegateEndpoint.registerWebhook(); } }
Source:
public Run getLastRun() { Run lastRun = null; for (Run thisRun : getRuns()) { if (thisRun == null) continue; if (lastRun == null) { lastRun = thisRun; } else if (thisRun.getStatus() != null && thisRun.getStatus().getStartDate().after(lastRun.getStatus().getStartDate())) { lastRun = thisRun; } } return lastRun; }

Target:
public Run getLastRun() { Run lastRun = null; for (Run thisRun : getRuns()) { if (lastRun == null) { lastRun = thisRun; } else if (lastRun.getStatus().getStartDate() == null && thisRun.getStatus().getStartDate() == null) { if (thisRun.getLastUpdated().after(lastRun.getLastUpdated())) lastRun = thisRun; } else if (lastRun.getStatus().getStartDate() == null && thisRun.getStatus().getStartDate() != null) { lastRun = thisRun; } else if (lastRun.getStatus().getStartDate() != null && thisRun.getStatus().getStartDate() == null) { continue; } else if (thisRun.getStatus().getStartDate().after(lastRun.getStatus().getStartDate())) { lastRun = thisRun; } } return lastRun; }
Source:
public LogReplicationConfig(Set<String> streamsToReplicate) { this.streamsToReplicate = streamsToReplicate; this.maxNumMsgPerBatch = DEFAULT_MAX_NUM_MSG_PER_BATCH; this.maxMsgSize = MAX_LOG_REPLICATION_DATA_MSG_SIZE_SUPPORTED; this.maxDataSizePerMsg = maxMsgSize * DATA_FRACTION_PER_MSG / 100; }

Target:
public LogReplicationConfig(Set<String> streamsToReplicate) { this(streamsToReplicate, DEFAULT_MAX_NUM_MSG_PER_BATCH, MAX_DATA_MSG_SIZE_SUPPORTED); }
Source:
public void testAbortRunningMatrixProject() throws Exception { MockFolder folder = j.createFolder("folder"); MatrixProject job1 = folder.createProject(MatrixProject.class, "project1"); job1.setDisplayName("project1 display name"); job1.setConcurrentBuild(true); job1.getBuildersList().add(new SleepBuilder()); job1.setAxes( new AxisList( new TextAxis("first_axis", "first_value1"), new TextAxis("second_axis", "sec_value1") ) ); configRoundTripUnsecure(job1); job1.save(); MatrixProject job2 = folder.createProject(MatrixProject.class, "project2"); job2.setDisplayName("project1 display name"); job2.setConcurrentBuild(true); job2.getBuildersList().add(new SleepBuilder()); job2.setAxes( new AxisList( new TextAxis("first_axis", "first_value1"), new TextAxis("second_axis", "sec_value1") ) ); configRoundTripUnsecure(job2); job2.save(); MatrixProject job3 = folder.createProject(MatrixProject.class, "project3"); job3.setDisplayName("project1 display name"); job3.setConcurrentBuild(true); job3.getBuildersList().add(new SleepBuilder()); job3.setAxes( new AxisList( new TextAxis("first_axis", "first_value1"), new TextAxis("second_axis", "sec_value1") ) ); configRoundTripUnsecure(job3); job3.save(); testAbortRunning(job1, job2, job3); j.waitUntilNoActivityUpTo(1000); assertThat(job1.getBuilds(), hasSize(3)); for (MatrixBuild matrixBuild : job1.getBuilds()) { assertThat(matrixBuild.getResult(), is(Result.ABORTED)); assertThat(matrixBuild.getRuns(), not(empty())); for (MatrixRun matrixRun : matrixBuild.getRuns()) { assertThat(matrixRun.getResult(), is(Result.ABORTED)); } } }

Target:
public void testAbortRunningMatrixProject() throws Exception { MockFolder folder = j.createFolder("Matrix_folder"); MatrixProject job1 = folder.createProject(MatrixProject.class, "project1"); job1.setDisplayName("project1 display name"); job1.setConcurrentBuild(true); job1.getBuildersList().add(new SleepBuilder()); job1.setAxes( new AxisList( new TextAxis("first_axis", "first_value1"), new TextAxis("second_axis", "sec_value1") ) ); configRoundTripUnsecure(job1); job1.save(); MatrixProject job2 = folder.createProject(MatrixProject.class, "project2"); job2.setDisplayName("project1 display name"); job2.setConcurrentBuild(true); job2.getBuildersList().add(new SleepBuilder()); job2.setAxes( new AxisList( new TextAxis("first_axis", "first_value1"), new TextAxis("second_axis", "sec_value1") ) ); configRoundTripUnsecure(job2); job2.save(); MatrixProject job3 = folder.createProject(MatrixProject.class, "project3"); job3.setDisplayName("project1 display name"); job3.setConcurrentBuild(true); job3.getBuildersList().add(new SleepBuilder()); job3.setAxes( new AxisList( new TextAxis("first_axis", "first_value1"), new TextAxis("second_axis", "sec_value1") ) ); configRoundTripUnsecure(job3); job3.save(); testAbortRunning(job1, job2, job3); assertThat(job1.getBuilds(), hasSize(3)); for (MatrixBuild matrixBuild : job1.getBuilds()) { assertThat(matrixBuild.getResult(), is(Result.ABORTED)); assertThat(matrixBuild.getRuns(), not(empty())); for (MatrixRun matrixRun : matrixBuild.getRuns()) { assertThat(matrixRun.getResult(), is(Result.ABORTED)); } } }
Source:
public void authenticateUser(UserDao mockedUserDao) throws AuthenticationException, RecordNotFoundException { String email = "user@example.com"; String password = "secret"; Credentials credentials = createCredentials(email, password); User fakeUser = new User(); fakeUser.setEmail(email); fakeUser.setPassword(password); when(mockedUserDao.findByEmail(email)).thenReturn(fakeUser); User user = authenticationInteractor.authenticate(credentials); assertEquals(fakeUser.getEmail(), user.getEmail()); }

Target:
public void authenticateUser(UserDao mockedUserDao) throws AuthenticationException, RecordNotFoundException { Credentials credentials = createMockedCredentials(AN_EMAIL, A_PASSWORD); User mockedUser = mock(User.class); when(mockedUser.getEmail()).thenReturn(AN_EMAIL); when(mockedUser.getPassword()).thenReturn(A_PASSWORD); when(mockedUserDao.findByEmail(AN_EMAIL)).thenReturn(mockedUser); User user = authenticationInteractor.authenticate(credentials); assertEquals(mockedUser.getEmail(), user.getEmail()); }
Source:
static void flushUIEvents() { final Display display = Display.getCurrent(); for (;;) { if (!display.readAndDispatch()) { break; } } }

Target:
static void flushUIEvents() { final Display display = Display.getCurrent(); while (display.readAndDispatch()) { } }
Source:
public void testMainMethodExclusionForJunit() { XmlSuite xmlSuite = createXmlSuite("suite"); xmlSuite.setJunit(true); createXmlTest(xmlSuite, "test", JUnitTestClassSample.class); TestNG tng = create(); tng.setXmlSuites(Collections.singletonList(xmlSuite)); tng.run(); Assert.assertEquals(tng.getStatus(), 0); }

Target:
public void testMainMethodExclusionForJunit() { XmlSuite xmlSuite = createXmlSuite("suite"); xmlSuite.setJunit(true); createXmlTest(xmlSuite, "test", JUnitTestClassSample.class); TestNG tng = create(xmlSuite); tng.run(); Assert.assertEquals(tng.getStatus(), 0); }
Source:
public void testAssignServerIp() throws InterruptedException { assertNodeAvailable(currentServer); currentServer = updateServerStatus(currentServer); List<String> ips = new ArrayList<String>(); ips.add(currentServer.ips().get(0).id()); LoadBalancer.ServerIp.CreateServerIp toAdd = LoadBalancer.ServerIp.CreateServerIp.create(ips); LoadBalancer updateResult = loadBalancerApi().assignServerIp(currentLoadBalancer.id(), toAdd); assertEquals(updateResult.serverIps().get(0).id(), currentServer.ips().get(0).id()); assertNotNull(updateResult); }

Target:
public void testAssignServerIp() throws InterruptedException { assertNodeAvailable(currentServer); currentServer = updateServerStatus(currentServer); List<String> ips = new ArrayList<String>(); ips.add(currentServer.ips().get(0).id()); LoadBalancer.ServerIp.CreateServerIp toAdd = LoadBalancer.ServerIp.CreateServerIp.create(ips); LoadBalancer updateResult = loadBalancerApi().assignServerIp(currentLoadBalancer.id(), toAdd); assertEquals(updateResult.serverIps().get(0).id(), currentServer.ips().get(0).id()); }
Source:
private boolean checkWMSLayerMinMaxScale(WMSLayerInfo wmsLayerInfo, double mapScale) { if (wmsLayerInfo.getMinScale() == null && wmsLayerInfo.getMaxScale() == null) return true; if (wmsLayerInfo.getMinScale() != null) if (mapScale < wmsLayerInfo.getMinScale()) return false; if (wmsLayerInfo.getMaxScale() != null) if (mapScale > wmsLayerInfo.getMaxScale()) return false; return true; }

Target:
private boolean checkWMSLayerMinMaxScale(WMSLayerInfo wmsLayerInfo, double mapScale) { if (wmsLayerInfo.getMinScale() == null && wmsLayerInfo.getMaxScale() == null) return true; if (wmsLayerInfo.getMinScale() != null && mapScale < wmsLayerInfo.getMinScale()) return false; if (wmsLayerInfo.getMaxScale() != null && mapScale > wmsLayerInfo.getMaxScale()) return false; return true; }
Source:
public ITmfTimestampTransform composeWith(ITmfTimestampTransform composeWith) { if (composeWith.equals(TmfTimestampTransform.IDENTITY)) { return this; } else if (composeWith instanceof TmfConstantTransform) { TmfConstantTransform tct = (TmfConstantTransform) composeWith; return new TmfConstantTransform(fOffset.getValue() + tct.fOffset.getValue()); } else if (composeWith instanceof TmfTimestampTransformLinear) { TmfTimestampTransformLinear ttl = (TmfTimestampTransformLinear) composeWith; BigDecimal newBeta = ttl.getOffset().add(new BigDecimal(fOffset.getValue())); return new TmfTimestampTransformLinear(ttl.getSlope(), newBeta); } else { return this; } }

Target:
public ITmfTimestampTransform composeWith(ITmfTimestampTransform composeWith) { if (composeWith.equals(TmfTimestampTransform.IDENTITY)) { return this; } else if (composeWith instanceof TmfConstantTransform) { TmfConstantTransform tct = (TmfConstantTransform) composeWith; return new TmfConstantTransform(fOffset.getValue() + tct.fOffset.getValue()); } else if (composeWith instanceof TmfTimestampTransformLinear) { throw new UnsupportedOperationException("Cannot compose a constant and linear transform yet"); } else { return this; } }
Source:
public Object convertFromInternal(Message<?> message, Class<?> targetClass) { Object result = null; try { if (isPrettyPrint == false) { result = mapper.writeValueAsString(message.getPayload()); } else { result = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(message.getPayload()); } } catch (JsonProcessingException e) { logger.error(e.getMessage(), e); return null; } return buildConvertedMessage(result, message.getHeaders(), MimeTypeUtils.APPLICATION_JSON); }

Target:
public Object convertFromInternal(Message<?> message, Class<?> targetClass) { Object result = null; try { if (prettyPrint) { result = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(message.getPayload()); } else { result = mapper.writeValueAsString(message.getPayload()); } } catch (JsonProcessingException e) { logger.error(e.getMessage(), e); return null; } return buildConvertedMessage(result, message.getHeaders(), MimeTypeUtils.APPLICATION_JSON); }
Source:
private void init(List<HelixRestNamespace> namespaces, int port, String urlPrefix, List<AuditLogger> auditLoggers) { if (namespaces.size() == 0) { throw new IllegalArgumentException( "No namespace specified! Please provide ZOOKEEPER address or namespace manifest."); } _server = new Server(port); _auditLoggers = auditLoggers; _resourceConfigMap = new HashMap<>(); _servletContextHandler = new ServletContextHandler(_server, urlPrefix); _helixNamespaces = namespaces; try { for (HelixRestNamespace namespace : _helixNamespaces) { if (namespace.isDefault()) { LOG.info("Creating default servlet for default namespace."); prepareServlet(namespace, ServletType.DEFAULT_SERVLET); } else { LOG.info("Creating common servlet for namespace: " + namespace.getName()); prepareServlet(namespace, ServletType.COMMON_SERVLET); } } } catch (Exception e) { LOG.error("Failed to initialize helix rest server. Tearing down."); cleanupResourceConfigs(); throw e; } Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { @Override public void run() { shutdown(); } })); }

Target:
private void init(List<HelixRestNamespace> namespaces, int port, String urlPrefix, List<AuditLogger> auditLoggers) { if (namespaces.size() == 0) { throw new IllegalArgumentException( "No namespace specified! Please provide ZOOKEEPER address or namespace manifest."); } _port = port; _urlPrefix = urlPrefix; _server = new Server(_port); _auditLoggers = auditLoggers; _resourceConfigMap = new HashMap<>(); _servletContextHandler = new ServletContextHandler(_server, _urlPrefix); _helixNamespaces = namespaces; try { for (HelixRestNamespace namespace : _helixNamespaces) { if (namespace.isDefault()) { LOG.info("Creating default servlet for default namespace"); prepareServlet(namespace, ServletType.DEFAULT_SERVLET); } else { LOG.info("Creating common servlet for namespace {}", namespace.getName()); prepareServlet(namespace, ServletType.COMMON_SERVLET); } } } catch (Exception e) { LOG.error("Failed to initialize helix rest server. Tearing down."); cleanupResourceConfigs(); throw e; } Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { @Override public void run() { shutdown(); } })); }
Source:
private void setupViewPager() { viewPager = (ViewPager) findViewById(R.id.viewpager); viewPager.setOffscreenPageLimit(PAGE_LIMIT); viewPager.setOnPageChangeListener( new ViewPager.SimpleOnPageChangeListener() { @Override public void onPageSelected(int position) { getActionBar().setSelectedNavigationItem(position); } } ); viewPager.setAdapter(viewPagerAdapter); viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { postToGoogleAnalytics(position); } @Override public void onPageScrollStateChanged(int state) { } }); }

Target:
private void setupViewPager() { viewPager = (ViewPager) findViewById(R.id.viewpager); viewPager.setOffscreenPageLimit(getOffscreenPageLimit()); viewPager.setOnPageChangeListener( new ViewPager.SimpleOnPageChangeListener() { @Override public void onPageSelected(int position) { getActionBar().setSelectedNavigationItem(position); postToGoogleAnalytics(position); } } ); viewPager.setAdapter(viewPagerAdapter); }
Source:
private FetchResult fetch(Repository repo, URIish u) throws URISyntaxException, JGitInternalException, InvalidRemoteException, IOException { RemoteConfig config = new RemoteConfig(repo.getConfig(), remote); config.addURI(u); final String dst = Constants.R_REMOTES + config.getName(); RefSpec refSpec = new RefSpec(); refSpec = refSpec.setForceUpdate(true); refSpec = refSpec.setSourceDestination(Constants.R_HEADS + "*", dst + "/*"); config.addFetchRefSpec(refSpec); config.update(repo.getConfig()); repo.getConfig().setString("branch", branch, "remote", remote); repo.getConfig().setString("branch", branch, "merge", branch); repo.getConfig().save(); FetchCommand command = new FetchCommand(repo); command.setRemote(remote); command.setProgressMonitor(monitor); if (credentialsProvider != null) command.setCredentialsProvider(credentialsProvider); return command.call(); }

Target:
private FetchResult fetch(Repository repo, URIish u) throws URISyntaxException, JGitInternalException, InvalidRemoteException, IOException { RemoteConfig config = new RemoteConfig(repo.getConfig(), remote); config.addURI(u); final String dst = Constants.R_REMOTES + config.getName(); RefSpec refSpec = new RefSpec(); refSpec = refSpec.setForceUpdate(true); refSpec = refSpec.setSourceDestination(Constants.R_HEADS + "*", dst + "/*"); config.addFetchRefSpec(refSpec); config.update(repo.getConfig()); repo.getConfig().setString(ConfigConstants.CONFIG_BRANCH_SECTION, branch, ConfigConstants.CONFIG_REMOTE_SECTION, remote); repo.getConfig().setString(ConfigConstants.CONFIG_BRANCH_SECTION, branch, ConfigConstants.CONFIG_KEY_MERGE, branch); repo.getConfig().save(); FetchCommand command = new FetchCommand(repo); command.setRemote(remote); command.setProgressMonitor(monitor); if (credentialsProvider != null) command.setCredentialsProvider(credentialsProvider); return command.call(); }