auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public ChannelHandler storeListingRequestHandler( CatchupServerProtocol catchupServerProtocol ) { return new SimpleChannelInboundHandler<PrepareStoreCopyRequest>() { @Override protected void channelRead0( ChannelHandlerContext channelHandlerContext, PrepareStoreCopyRequest prepareStoreCopyRequest ) { channelHandlerContext.writeAndFlush( ResponseMessageType.PREPARE_STORE_COPY_RESPONSE ); List<File> list = filesystem.stream().map( FakeFile::getFile ).collect( Collectors.toList() ); File[] files = new File[list.size()]; files = list.toArray( files ); long transactionId = 123L; MutableLongSet indexIds = new LongHashSet(); indexIds.add( 13 ); channelHandlerContext.writeAndFlush( PrepareStoreCopyResponse.success( files, indexIds, transactionId ) ); catchupServerProtocol.expect( CatchupServerProtocol.State.MESSAGE_TYPE ); } }; }

Target:
public ChannelHandler storeListingRequestHandler( CatchupServerProtocol catchupServerProtocol ) { return new SimpleChannelInboundHandler<PrepareStoreCopyRequest>() { @Override protected void channelRead0( ChannelHandlerContext channelHandlerContext, PrepareStoreCopyRequest prepareStoreCopyRequest ) { channelHandlerContext.writeAndFlush( ResponseMessageType.PREPARE_STORE_COPY_RESPONSE ); List<File> list = filesystem.stream().map( FakeFile::getFile ).collect( Collectors.toList() ); File[] files = new File[list.size()]; files = list.toArray( files ); long transactionId = 123L; LongSet indexIds = LongSets.immutable.of( 13 ); channelHandlerContext.writeAndFlush( PrepareStoreCopyResponse.success( files, indexIds, transactionId ) ); catchupServerProtocol.expect( CatchupServerProtocol.State.MESSAGE_TYPE ); } }; }
Source:
public void searchHalf(ThreadState state) { String predicate = "actionCode = " + (state.random.nextBoolean() ? ActionCode.CODE_0000.toCode() : ActionCode.CODE_9280.toCode()); map.values(new SqlPredicate(predicate)); }

Target:
public Collection<Transaction> searchHalf(ThreadState state) { String predicate = "actionCode = " + (state.random.nextBoolean() ? ActionCode.CODE_0000.toCode() : ActionCode.CODE_9280.toCode()); return map.values(new SqlPredicate(predicate)); }
Source:
public void testCollectionWithImage() throws Exception { String derivativeFinalPath = "de/75/d8/11/" + RESC_ID; Path uploadedFilePath = Paths.get(dataDir, derivativeFinalPath); Files.createDirectories(uploadedFilePath.getParent()); imgFile = new File(uploadedFilePath.toString()); FileWriter fileWriter = new FileWriter(imgFile.getAbsoluteFile()); BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); bufferedWriter.write("image file"); bufferedWriter.close(); processor.process(exchange); verify(message).setHeader(CdrBinaryMimeType, "image/*"); verify(message).setHeader(CdrBinaryPath, imgFile.getAbsolutePath()); imgFile.delete(); }

Target:
public void testCollectionWithImage() throws Exception { String derivativeFinalPath = "de/75/d8/11/" + RESC_ID; Path uploadedFilePath = Paths.get(dataDir, derivativeFinalPath); Files.createDirectories(uploadedFilePath.getParent()); imgFile = new File(uploadedFilePath.toString()); FileUtils.writeStringToFile(imgFile, "image file", StandardCharsets.UTF_8); processor.process(exchange); verify(message).setHeader(CdrBinaryMimeType, "image/*"); verify(message).setHeader(CdrBinaryPath, imgFile.getAbsolutePath()); }
Source:
private Component finalizeBuilder(final Component text, final TextComponent.Builder build) { return build.style(text.style().toBuilder().build()).build(); }

Target:
private Component finalizeBuilder(final Component text, final TextComponent.Builder build) { return build.style(text.style()).build(); }
Source:
public void close() { lastUsed.set(System.currentTimeMillis()); useCnt.decrementAndGet(); if (!RepositoryCache.isCached(this)) { evict(0); } }

Target:
public void close() { lastUsed.set(System.currentTimeMillis()); if (useCnt.decrementAndGet() == 0 && !RepositoryCache.isCached(this)) { doClose(); } }
Source:
public int globalToLocal(int globalType) { int index = mGlobalToLocalMapping.indexOfKey(globalType); if (index < 0) { throw new IllegalStateException("requested global type " + globalType + " does" + " not belong to the adapter:" + mWrapper.delegate); } return mGlobalToLocalMapping.valueAt(index); }

Target:
public int globalToLocal(int globalType) { int index = mGlobalToLocalMapping.indexOfKey(globalType); if (index < 0) { throw new IllegalStateException("requested global type " + globalType + " does" + " not belong to the adapter:" + mWrapper.adapter); } return mGlobalToLocalMapping.valueAt(index); }
Source:
public void testWithServiceSuperclassAnnotatedMethodOverridePE() throws Exception { ConfigurableApplicationContext ac = new ClassPathXmlApplicationContext("GatewayInterfaceTests2-context.xml", getClass()); DirectChannel channel = ac.getBean("requestChannelFoo", DirectChannel.class); final Method fooMethod = Foo.class.getMethod("foo", String.class); final AtomicBoolean called = new AtomicBoolean(); MessageHandler handler = message -> { assertThat(message.getHeaders().get("name"), equalTo("foo")); assertThat(message.getHeaders().get("string"), equalTo("public abstract void org.springframework.integration.gateway.GatewayInterfaceTests$Foo.foo(java.lang.String)")); assertThat(message.getHeaders().get("object"), equalTo(fooMethod)); assertThat(message.getPayload(), equalTo("foo")); called.set(true); }; channel.subscribe(handler); Bar bar = ac.getBean(Bar.class); bar.foo("hello"); assertTrue(called.get()); ac.close(); }

Target:
public void testWithServiceSuperclassAnnotatedMethodOverridePE() throws Exception { ConfigurableApplicationContext ac = new ClassPathXmlApplicationContext("GatewayInterfaceTests2-context.xml", getClass()); DirectChannel channel = ac.getBean("requestChannelFoo", DirectChannel.class); final Method fooMethod = Foo.class.getMethod("foo", String.class); final AtomicBoolean called = new AtomicBoolean(); MessageHandler handler = message -> { assertThat(message.getHeaders().get("name"), equalTo("foo")); assertThat(message.getHeaders().get("string"), equalTo("public abstract void org.springframework.integration.gateway." + "GatewayInterfaceTests$Foo.foo(java.lang.String)")); assertThat(message.getHeaders().get("object"), equalTo(fooMethod)); assertThat(message.getPayload(), equalTo("foo")); called.set(true); }; channel.subscribe(handler); Bar bar = ac.getBean(Bar.class); bar.foo("hello"); assertTrue(called.get()); ac.close(); }
Source:
public void ShouldConvertActivity_WhenStartMainViewIsCalled() throws Exception { activity.startMainView(); ShadowActivity shadowActivity = shadowOf(activity); Intent startedIntent = shadowActivity.getNextStartedActivity(); assertEquals(MainActivity.class.getName(), startedIntent.getComponent().getClassName()); shadowActivity.finish(); }

Target:
public void ShouldConvertActivity_WhenStartMainViewIsCalled() throws Exception { activity.startMainView(); Intent expectedIntent = new Intent(activity, MainActivity.class); assertThat(new Intent(RuntimeEnvironment.application, MainActivity.class)).isEqualTo(expectedIntent); }
Source:
private void handleAttemptLockout(long elapsedRealtimeDeadline) { mLockPatternView.clearPattern(); mLockPatternView.setEnabled(false); final long elapsedRealtime = SystemClock.elapsedRealtime(); mCountdownTimer = new CountDownTimer(elapsedRealtimeDeadline - elapsedRealtime, 200) { @Override public void onTick(long millisUntilFinished) { final int secondsRemaining = (int) Math.ceil(millisUntilFinished / 1000.0); mSecurityMessageDisplay.setMessage( R.string.kg_too_many_failed_attempts_countdown, true, secondsRemaining); } @Override public void onFinish() { mLockPatternView.setEnabled(true); displayDefaultSecurityMessage(true); } }.start(); }

Target:
private void handleAttemptLockout(long elapsedRealtimeDeadline) { mLockPatternView.clearPattern(); mLockPatternView.setEnabled(false); final long elapsedRealtime = SystemClock.elapsedRealtime(); final long millisInFuture = ((long) Math.ceil( (elapsedRealtimeDeadline - elapsedRealtime) / 1000.0) + 2) * 1000; mCountdownTimer = new CountDownTimer(millisInFuture, 1000) { @Override public void onTick(long millisUntilFinished) { final int secondsRemaining = (int) Math.round(millisUntilFinished / 1000.0) - 2; if (secondsRemaining > 0) { mSecurityMessageDisplay.setMessage( R.string.kg_too_many_failed_attempts_countdown, true, secondsRemaining); } else { mLockPatternView.setEnabled(true); displayDefaultSecurityMessage(true ); cancel(); } } @Override public void onFinish() { } }.start(); }
Source:
protected AliasAnalysis[] createAliasAnalyses(@UnderInitialization AccumulationChecker this) { return new AliasAnalysis[] {AliasAnalysis.RETURNS_RECEIVER}; }

Target:
protected EnumSet<AliasAnalysis> createAliasAnalyses( @UnderInitialization AccumulationChecker this) { return EnumSet.of(AliasAnalysis.RETURNS_RECEIVER); }
Source:
public ToolUseHandler getItemHandler() { return (e, tool, fortune, drops) -> { if (e.isCancelled()) return; Player p = e.getPlayer(); Block b = e.getBlock(); b.getWorld().createExplosion(b.getLocation(), 0.0F); b.getWorld().playSound(b.getLocation(), Sound.ENTITY_GENERIC_EXPLODE, 0.2F, 1F); List<Block> blocks = findBlocks(b); breakBlocks(p, tool, b, blocks, fortune, drops); }; }

Target:
public ToolUseHandler getItemHandler() { return (e, tool, fortune, drops) -> { Player p = e.getPlayer(); Block b = e.getBlock(); b.getWorld().createExplosion(b.getLocation(), 0.0F); b.getWorld().playSound(b.getLocation(), Sound.ENTITY_GENERIC_EXPLODE, 0.2F, 1F); List<Block> blocks = findBlocks(b); breakBlocks(p, tool, b, blocks, fortune, drops); }; }
Source:
public synchronized MetricNames getMeticNames(){ if(metricNames == null){ try { String hostname = InetAddress.getLocalHost().getHostName(); int idx = hostname.indexOf('.'); if(idx > 0){ hostname = hostname.substring(0, idx); } metricNames = new MetricNames(hostname+"."+getSharedResources().getTransactorID()); } catch (UnknownHostException e) { throw new RuntimeException(e); } } return metricNames; }

Target:
public synchronized MetricNames getMeticNames(){ if(metricNames == null){ String mid = System.getProperty(MetricNames.METRICS_ID_PROP); if(mid == null){ try { String hostname = InetAddress.getLocalHost().getHostName(); int idx = hostname.indexOf('.'); if(idx > 0){ hostname = hostname.substring(0, idx); } mid = hostname+"_"+getSharedResources().getTransactorID(); } catch (UnknownHostException e) { throw new RuntimeException(e); } } mid = mid.replace('.', '_'); metricNames = new MetricNames(mid); } return metricNames; }
Source:
@Nullable HashMap<Integer, GroupKeyEncrypted> getAll() { if (F.isEmpty(grpKeys)) return null; HashMap<Integer, GroupKeyEncrypted> Keys = new HashMap<>(); for (Map.Entry<Integer, List<GroupKey>> entry : grpKeys.entrySet()) { int grpId = entry.getKey(); GroupKey grpKey = entry.getValue().get(0); Keys.put(grpId, new GroupKeyEncrypted(grpKey.unsignedId(), encSpi.encryptKey(grpKey.key()))); } return Keys; }

Target:
@Nullable HashMap<Integer, GroupKeyEncrypted> getAll() { if (F.isEmpty(grpKeys)) return null; HashMap<Integer, GroupKeyEncrypted> keys = U.newHashMap(grpKeys.size()); for (Map.Entry<Integer, List<GroupKey>> entry : grpKeys.entrySet()) { int grpId = entry.getKey(); GroupKey grpKey = entry.getValue().get(0); keys.put(grpId, new GroupKeyEncrypted(grpKey.unsignedId(), encSpi.encryptKey(grpKey.key()))); } return keys; }
Source:
public List<TokenCredential> getCredentials() { return Collections.unmodifiableList(tokenCredentials); }

Target:
public List<TokenCredential> getCredentials() { return super.getCredentials(); }
Source:
public void prepareCollection() { for (int i = 0; i < DATA_AMOUNT; i++) streamingCol.add(new HashMap.SimpleEntry<>(ThreadLocalRandom.current().nextInt(DATA_AMOUNT), ThreadLocalRandom.current().nextInt(DATA_AMOUNT))); }

Target:
public void prepareCollection() { for (int i = 0; i < DATA_AMOUNT; i++) streamingCol.add(new HashMap.SimpleEntry<>(ThreadLocalRandom.current().nextInt(), ThreadLocalRandom.current().nextInt())); }
Source:
private static List<TimeGraphState> getCurrentThreads(@NonNull ITmfStateSystem ss, ITmfStateInterval userModeInterval, @NonNull NavigableSet<ITmfStateInterval> currentThreadIntervals) throws StateSystemDisposedException { List<TimeGraphState> list = new ArrayList<>(); for (ITmfStateInterval currentThread : currentThreadIntervals) { if (currentThread.getStartTime() <= userModeInterval.getEndTime() && currentThread.getEndTime() >= userModeInterval.getStartTime()) { long start = Long.max(userModeInterval.getStartTime(), currentThread.getStartTime()); long end = Long.min(userModeInterval.getEndTime(), currentThread.getEndTime()); long duration = end - start + 1; Object tid = currentThread.getValue(); if (tid instanceof Integer) { int execNameQuark = ss.optQuarkAbsolute(Attributes.THREADS, String.valueOf(tid), Attributes.EXEC_NAME); if (execNameQuark != ITmfStateSystem.INVALID_ATTRIBUTE) { Object currentThreadName = ss.querySingleState(currentThread.getEndTime(), execNameQuark).getValue(); if (currentThreadName instanceof String) { list.add(new TimeGraphState(start, duration, StateValues.CPU_STATUS_RUN_USERMODE, (String) currentThreadName)); continue; } } } list.add(new TimeGraphState(start, duration, StateValues.CPU_STATUS_RUN_USERMODE)); } } return list; }

Target:
private static List<TimeGraphState> getCurrentThreads(@NonNull ITmfStateSystem ss, ITmfStateInterval userModeInterval, @NonNull NavigableSet<ITmfStateInterval> currentThreadIntervals) throws StateSystemDisposedException { List<TimeGraphState> list = new ArrayList<>(); for (ITmfStateInterval currentThread : currentThreadIntervals) { if (currentThread.getStartTime() <= userModeInterval.getEndTime() && currentThread.getEndTime() >= userModeInterval.getStartTime()) { long start = Long.max(userModeInterval.getStartTime(), currentThread.getStartTime()); long end = Long.min(userModeInterval.getEndTime(), currentThread.getEndTime()); long duration = end - start + 1; Object tid = currentThread.getValue(); if (tid instanceof Integer) { int execNameQuark = ss.optQuarkAbsolute(Attributes.THREADS, String.valueOf(tid), Attributes.EXEC_NAME); if (execNameQuark != ITmfStateSystem.INVALID_ATTRIBUTE) { Object currentThreadName = ss.querySingleState(currentThread.getEndTime(), execNameQuark).getValue(); if (currentThreadName instanceof String) { list.add(new TimeGraphState(start, duration, StateValues.CPU_STATUS_RUN_USERMODE, Messages.Usermode)); continue; } } } list.add(new TimeGraphState(start, duration, StateValues.CPU_STATUS_RUN_USERMODE)); } } return list; }
Source:
private StripePaymentIntent getPaymentIntent(RefundGatewayRequest request) throws GatewayException.GenericGatewayException, GatewayErrorException, GatewayException.GatewayConnectionTimeoutException{ final String refundResponse = client.postRequestFor(StripeGetPaymentIntentRequest.of(request, stripeGatewayConfig)).getEntity(); StripePaymentIntent stripePaymentIntent = jsonObjectMapper.getObject(refundResponse, StripePaymentIntent.class); logger.info("As part of refund to refund charge id refunded stripe charge id {}", request.getTransactionId(), request.getChargeExternalId(), request.getRefundExternalId() ); return stripePaymentIntent; }

Target:
private StripePaymentIntent getPaymentIntent(RefundGatewayRequest request) throws GatewayException.GenericGatewayException, GatewayErrorException, GatewayException.GatewayConnectionTimeoutException{ final String refundResponse = client.postRequestFor(StripeGetPaymentIntentRequest.of(request, stripeGatewayConfig)).getEntity(); StripePaymentIntent stripePaymentIntent = jsonObjectMapper.getObject(refundResponse, StripePaymentIntent.class); return stripePaymentIntent; }
Source:
public void refresh() { control("details/validate-button").click(); waitFor(driver, hasContent("Items refreshed successfully"), 10); elasticSleep(1000); }

Target:
public void refresh() { control("details/validate-button").click(); waitFor(hasContent("Items refreshed successfully")); control("details/deployReleaseRepository/validate-button").click(); control("details/deployReleaseRepository/keyFromText").sendKeys(DEFAULT_REPO); control("details/deploySnapshotRepository/validate-button").click(); control("details/deploySnapshotRepository/keyFromText").sendKeys(DEFAULT_REPO); }
Source:
protected static void assertAttAuthzStatements(final Assertion assertion) throws WSSecurityException { if ((assertion.getAttributeStatements() == null || assertion.getAttributeStatements().isEmpty()) && (assertion.getAuthnStatements() == null || assertion.getAuthnStatements().isEmpty())) { assertAuthzDecisionStatements(assertion); } }

Target:
protected static void assertAttAuthzStatements(final Assertion assertion) throws WSSecurityException { if (CollectionUtils.isEmpty(assertion.getAttributeStatements()) && CollectionUtils.isEmpty(assertion.getAuthnStatements())) { assertAuthzDecisionStatements(assertion); } }
Source:
protected ProgressStep makeProgressStep(String input, Set<InputType> inputTypes) throws IOException { for (FactoryType factoryType : getFactoryTypes(inputTypes)) { ProgressStep step = progressStepFactoryMap.get(factoryType).create(input, inputTypes); if (step != null) { return step; } } throw new ValidationException(Collections.singletonList(new ValidationError("Could not construct ProgressStep"))); }

Target:
protected ProgressStep makeProgressStep(String input, Set<InputType> inputTypes) throws IOException { for (FactoryType factoryType : getFactoryTypes(inputTypes)) { ProgressStep step = progressStepFactoryMap.get(factoryType).create(input, inputTypes); if (step != null) { return step; } } throw new ValidationException(Collections.singletonList( new ValidationError(String.format("No %s found matching '%s'", LimsUtils.joinWithConjunction(getNames(inputTypes), "or"), input)))); }
Source:
public CustomModel(CustomModel toCopy) { this.maxSpeedFallback = toCopy.maxSpeedFallback; this.vehicleWeight = toCopy.vehicleWeight; this.vehicleWidth = toCopy.vehicleWidth; this.vehicleLength = toCopy.vehicleLength; this.vehicleHeight = toCopy.vehicleHeight; this.headingPenalty = toCopy.headingPenalty; this.distanceInfluence = toCopy.distanceInfluence; speedFactor = deepCopy(toCopy.getSpeedFactor()); maxSpeed = deepCopy(toCopy.getMaxSpeed()); priorityMap = deepCopy(toCopy.getPriority()); areas.putAll(toCopy.getAreas()); }

Target:
public CustomModel(CustomModel toCopy) { this.maxSpeedFallback = toCopy.maxSpeedFallback; this.headingPenalty = toCopy.headingPenalty; this.distanceInfluence = toCopy.distanceInfluence; speedFactorMap = deepCopy(toCopy.getSpeedFactor()); maxSpeedMap = deepCopy(toCopy.getMaxSpeed()); priorityMap = deepCopy(toCopy.getPriority()); areas.putAll(toCopy.getAreas()); }
Source:
public void clearAllStats() { commandsProcessed.set(0); opsPerSecond.set(0); totalNetworkBytesRead.set(0); connectionsReceived.set(0); expirations.set(0); keyspaceHits.set(0); keyspaceMisses.set(0); stats.setLong(clientId, 0); }

Target:
public void clearAllStats() { commandsProcessed.set(0); opsPerSecond.set(0); totalNetworkBytesRead.set(0); connectionsReceived.set(0); expirations.set(0); keyspaceHits.set(0); keyspaceMisses.set(0); stats.setLong(clientId, 0); stats.setLong(passiveExpirationChecksId, 0); stats.setLong(passiveExpirationCheckTimeId, 0); stats.setLong(passiveExpirationsId, 0); stats.setLong(expirationsId, 0); stats.setLong(expirationTimeId, 0); }
Source:
public static RequestStatus deleteComponent(PortletRequest request, Logger log) { String id = request.getParameter(PortalConstants.COMPONENT_ID); if (id != null) { try { String deleteComment_encoded = request.getParameter(PortalConstants.MODERATION_REQUEST_COMMENT); User user = UserCacheHolder.getUserFromRequest(request); if(deleteComment_encoded != null) { String deleteComment = new String(Base64.getDecoder().decode(deleteComment_encoded)); user.setCommentMadeDuringModerationRequest(deleteComment); } ComponentService.Iface client = new ThriftClients().makeComponentClient(); return client.deleteComponent(id, user); } catch (TException e) { log.error("Could not delete component from DB", e); } } return RequestStatus.FAILURE; }

Target:
public static RequestStatus deleteComponent(PortletRequest request, Logger log) { String id = request.getParameter(PortalConstants.COMPONENT_ID); if (id != null) { try { String deleteCommentEncoded = request.getParameter(PortalConstants.MODERATION_REQUEST_COMMENT); User user = UserCacheHolder.getUserFromRequest(request); if(deleteCommentEncoded != null) { String deleteComment = new String(Base64.getDecoder().decode(deleteCommentEncoded)); user.setCommentMadeDuringModerationRequest(deleteComment); } ComponentService.Iface client = new ThriftClients().makeComponentClient(); return client.deleteComponent(id, user); } catch (TException e) { log.error("Could not delete component from DB", e); } } return RequestStatus.FAILURE; }
Source:
public RemoteTableDescriptor<K, V> withRateLimiter(RateLimiter rateLimiter, TableRateLimiter.CreditFunction<K, V> readCreditFn, TableRateLimiter.CreditFunction<K, V> writeCreditFn) { Preconditions.checkNotNull(rateLimiter, "null read rate limiter"); this.rateLimiter = rateLimiter; this.readCreditFn = readCreditFn; this.writeCreditFn = writeCreditFn; if (this.readCreditFn != null) { this.readCreditFn.setTableId(String.format("%s.%s", tableId, READ_CREDIT_FN)); } if (this.writeCreditFn != null) { this.writeCreditFn.setTableId(String.format("%s.%s", tableId, WRITE_CREDIT_FN)); } return this; }

Target:
public RemoteTableDescriptor<K, V> withRateLimiter(RateLimiter rateLimiter, TableRateLimiter.CreditFunction<K, V> readCreditFn, TableRateLimiter.CreditFunction<K, V> writeCreditFn) { Preconditions.checkNotNull(rateLimiter, "null read rate limiter"); this.rateLimiter = rateLimiter; this.readCreditFn = readCreditFn; this.writeCreditFn = writeCreditFn; return this; }
Source:
public Term resolveFunctionAndAnywhere(KItem kItem, boolean copyOnShareSubstAndEval, TermContext context) { try { Term result = kItem.isEvaluable(context) ? evaluateFunction(kItem, copyOnShareSubstAndEval, context) : kItem.applyAnywhereRules(copyOnShareSubstAndEval, context); if (result instanceof KItem && ((KItem) result).isEvaluable(context) && result.isGround()) { if (options.warnings.includesExceptionType(ExceptionType.HIDDENWARNING) && tool != Tool.KOMPILE) { StringBuilder sb = new StringBuilder(); sb.append("Unable to resolve function symbol:\n\t\t"); sb.append(result); sb.append('\n'); if (!context.definition().functionRules().isEmpty()) { sb.append("\tDefined function rules:\n"); for (Rule rule : context.definition().functionRules().get((KLabelConstant) ((KItem) result).kLabel())) { sb.append("\t\t"); sb.append(rule); sb.append('\n'); } } kem.registerCriticalWarning(sb.toString(), kItem); } if (RuleAuditing.isAuditBegun()) { System.err.println("Function failed to evaluate: returned " + result); } } return result; } catch (StackOverflowError e) { throw KExceptionManager.criticalError(TRACE_MSG, e); } catch (KEMException e) { e.exception.addTraceFrame("while evaluating function " + kItem.kLabel().toString()); throw e; } }

Target:
public Term resolveFunctionAndAnywhere(KItem kItem, boolean copyOnShareSubstAndEval, TermContext context) { try { Term result = kItem.isEvaluable(context) ? evaluateFunction(kItem, copyOnShareSubstAndEval, context) : kItem.applyAnywhereRules(copyOnShareSubstAndEval, context); if (result instanceof KItem && ((KItem) result).isEvaluable(context) && result.isGround()) { if (options.warnings.includesExceptionType(ExceptionType.HIDDENWARNING) && tool != Tool.KOMPILE) { StringBuilder sb = new StringBuilder(); sb.append("Unable to resolve function symbol:\n\t\t"); sb.append(result); sb.append('\n'); if (!context.definition().functionRules().isEmpty()) { sb.append("\tDefined function rules:\n"); for (Rule rule : context.definition().functionRules().get((KLabelConstant) ((KItem) result).kLabel())) { sb.append("\t\t"); sb.append(rule); sb.append('\n'); } } kem.registerInternalHiddenWarning(sb.toString(), kItem); } if (RuleAuditing.isAuditBegun()) { System.err.println("Function failed to evaluate: returned " + result); } } return result; } catch (StackOverflowError e) { throw KExceptionManager.criticalError(TRACE_MSG, e); } catch (KEMException e) { e.exception.addTraceFrame("while evaluating function " + kItem.kLabel().toString()); throw e; } }
Source:
public List<VdsNetworkInterface> getAllInterfacesByLabelForDataCenter(Guid dataCenterId, String label) { List<VdsNetworkInterface> result = new ArrayList<>(); for (VdsNetworkInterface vdsNetworkInterface : getAllInterfacesByDataCenterId(dataCenterId)) { final Set<String> labels = vdsNetworkInterface.getLabels(); if (labels != null && labels.contains(label)) { result.add(vdsNetworkInterface); } } return result; }

Target:
public List<VdsNetworkInterface> getAllInterfacesByLabelForDataCenter(Guid dataCenterId, String label) { return nicsContainingLabel(getAllInterfacesByDataCenterId(dataCenterId), label); }
Source:
private Response getS3Preview(URI fileURI, int numLines) { val filename = getFilename(fileURI); val outputKey = getOutputKey(filename); val request = new GetObjectRequest( outputBucket, outputKey ).withRange(0, 100 * 1024); val object = s3Client.getObject(request); ObjectMetadata objectMetadata = object.getObjectMetadata(); boolean gzip = "gzip".equalsIgnoreCase(objectMetadata.getContentEncoding()); try (val s3Reader = new CSVReader(new BufferedReader(new InputStreamReader(gzip ? new GZIPInputStream(object.getObjectContent()) : object.getObjectContent())))) { return getPreviewFromCSV(s3Reader, numLines); } catch (IOException e) { return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); } }

Target:
private Response getS3Preview(URI fileURI, int numLines) { val filename = getFilename(fileURI); val outputKey = getOutputKey(filename); val request = new GetObjectRequest( outputBucket, outputKey ).withRange(0, 100 * 1024); val object = s3Client.getObject(request); ObjectMetadata objectMetadata = object.getObjectMetadata(); boolean gzip = "gzip".equalsIgnoreCase(objectMetadata.getContentEncoding()); try (InputStream input = object.getObjectContent()) { InputStreamReader reader; if (gzip) { reader = new InputStreamReader(new GZIPInputStream(input)); } else { reader = new InputStreamReader(input); } return getPreviewFromCSV(new CSVReader(reader), numLines); } catch (IOException e) { return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); } }
Source:
protected Object[] createParameters(Class<?>[] paramTypes, GitTestSupport gitTestsSupport) throws Throwable { Builder<Object> builder = ImmutableSet.builder(); for (Class<?> paramType : paramTypes) { if (paramType.equals(GitTestSupport.class)) { builder.add(gitTestsSupport); } else if (paramType.equals(MergeResult.class)) { builder.add(gitTestsSupport.getMergeResult()); } else if (paramType.equals(List.class)) { builder.add(gitTestsSupport.getProjects()); } else if (paramType.equals(Repository.class)) { builder.add(gitTestsSupport.getRepository()); } else if (paramType.equals(Status.class)) { builder.add(gitTestsSupport.getStatus()); } else { throw new IllegalArgumentException("Unknown parameter " + paramType.getCanonicalName()); } } return builder.build().toArray(); }

Target:
protected Object[] createParameters(Class<?>[] paramTypes, GitTestSupport gitTestsSupport) throws Throwable { final Builder<Object> builder = ImmutableList.builder(); for (Class<?> paramType : paramTypes) { if (paramType.equals(GitTestSupport.class)) { builder.add(gitTestsSupport); } else if (paramType.equals(MergeResult.class)) { builder.add(gitTestsSupport.getMergeResult()); } else if (isCollectionCompatible(paramType)) { builder.add(gitTestsSupport.getProjects()); } else if (paramType.equals(Repository.class)) { builder.add(gitTestsSupport.getRepository()); } else if (paramType.equals(Status.class)) { builder.add(gitTestsSupport.getStatus()); } else { throw new IllegalArgumentException( "Unsupported parameter type " + paramType.getCanonicalName()); } } return builder.build().toArray(); }
Source:
public void requestStop() { taskState.requestStop(); try { pubsub.shutdown(); } catch (Exception e) { LOGGER.error("Failed to shutdown Pubsub publisher: " + e.getLocalizedMessage()); LOGGER.error(" projectId: " + projectId); LOGGER.error(" topic: " + topic.getTopic()); } if ( ddlPubsub != null ) { try { ddlPubsub.shutdown(); } catch (Exception e) { LOGGER.error("Failed to shutdown Pubsub publisher: " + e.getLocalizedMessage()); LOGGER.error(" projectId: " + projectId); LOGGER.error(" topic: " + ddlTopic.getTopic()); } } }

Target:
public void requestStop() throws Exception { taskState.requestStop(); pubsub.shutdown(); if ( ddlPubsub != null ) { ddlPubsub.shutdown(); } }
Source:
private Record dequeueRecord() { if ( records.size() < LOW_RECORD_WATERMARK ) { if ( state() != State.STREAMING_STATE ) { request( fetchSize ); } isAutoPullEnabled = true; } return records.poll(); }

Target:
private Record dequeueRecord() { Record record = records.poll(); if ( records.size() <= lowRecordWatermark ) { if ( state() != State.STREAMING_STATE ) { request( fetchSize ); } isAutoPullEnabled = true; } return record; }
Source:
public HttpResponse doDoLogin( @QueryParameter String userid, @QueryParameter String password, @QueryParameter String from ) { if (Strings.isNullOrEmpty(userid)) { throw new UserError("Missing username"); } if (Strings.isNullOrEmpty(password)) { throw new UserError("Missing password"); } String dn = "cn=" + userid + "," + params.newUserBaseDN(); try { LdapContext context = connect(dn, password); try { Stapler.getCurrentRequest().getSession().setAttribute(Myself.class.getName(), new Myself(this, dn, context.getAttributes(dn), getGroups(dn,context))); } finally { context.close(); } } catch (Exception e) { throw new UserError(String.format("User \"%s\" not found or password incorrect %n", userid) ); } if (from==null || !from.startsWith("/")) from="/"; return HttpResponses.redirectTo(from); }

Target:
public HttpResponse doDoLogin( @QueryParameter String userid, @QueryParameter String password, @QueryParameter String from ) { if (Strings.isNullOrEmpty(userid)) { throw new UserError("Missing username"); } if (Strings.isNullOrEmpty(password)) { throw new UserError("Missing password"); } String dn = "cn=" + userid + "," + params.newUserBaseDN(); try { LdapContext context = connect(dn, password); try { Stapler.getCurrentRequest().getSession().setAttribute(Myself.class.getName(), new Myself(this, dn, context.getAttributes(dn), getGroups(dn,context))); } finally { context.close(); } } catch (AuthenticationException e) { throw new UserError(String.format("User \"%s\" not found or password incorrect %n", userid) ); } catch (Exception e) { String errorId = String.valueOf(Math.round(Math.random() * 1e8)); LOGGER.log(Level.SEVERE, "Login error " + errorId, e); throw new UserError("Something went wrong. Please try again later.", errorId); } if (from==null || !from.startsWith("/")) from="/"; return HttpResponses.redirectTo(from); }
Source:
public String[] marshal(final List<String> value) throws Exception { System.err.println("unmarshal: " + value); if (value == null) return null; return value.stream().map(String::trim).collect(Collectors.toList()).toArray(TYPE); }

Target:
public String[] marshal(final List<String> value) throws Exception { if (value == null) return null; return value.stream().map(String::trim).collect(Collectors.toList()).toArray(TYPE); }
Source:
public long getStartOfLastLinearBin() { return -1; }

Target:
public long getStartOfLastLinearBin() { if (metaDataPos > 0 && position() != metaDataPos) { seek(metaDataPos); } final int sequenceIndex = getNumberOfReferences(); long loffset = -1L; for (int i = 0; i < sequenceIndex; i++) { final int nBins = readInteger(); for (int j = 0; j < nBins; j++) { readInteger(); loffset = readLong(); final int nChunks = readInteger(); skipBytes(BAMFileConstants.CSI_CHUNK_SIZE * nChunks); } } return loffset; }
Source:
public String toString() { if(customName == "") { if (lowNumber == 0) { return String.format("%s.%s", bigNumber, intermediateNumber); } return String.format("%s.%s.%s", bigNumber, intermediateNumber, lowNumber); } else { if (lowNumber == 0) { return String.format("%s.%s-%s", bigNumber, intermediateNumber, customName); } return String.format("%s.%s.%s-%s", bigNumber, intermediateNumber, lowNumber, customName); } }

Target:
public String toString() { if(StringUtils.isBlank(customName)) { if (lowNumber == 0) { return String.format("%s.%s", bigNumber, intermediateNumber); } return String.format("%s.%s.%s", bigNumber, intermediateNumber, lowNumber); } else { if (lowNumber == 0) { return String.format("%s.%s-%s", bigNumber, intermediateNumber, customName); } return String.format("%s.%s.%s-%s", bigNumber, intermediateNumber, lowNumber, customName); } }
Source:
public RankingFilter withObjUriQualifiers(final ObjQualifierConverter objQualifierConverter) { Validate.notNull(objQualifierConverter, "objQualifierConverter"); return new RankingFilter( translateIdentifierQualifiers(this.measures, objQualifierConverter), attributes == null ? null : translateIdentifierQualifiers(this.attributes, objQualifierConverter), operator, value ); }

Target:
public RankingFilter withObjUriQualifiers(final ObjQualifierConverter objQualifierConverter) { notNull(objQualifierConverter, "objQualifierConverter"); return new RankingFilter( translateIdentifierQualifiers(this.measures, objQualifierConverter), attributes == null ? null : translateIdentifierQualifiers(this.attributes, objQualifierConverter), operator, value ); }
Source:
protected Position handlePosition(Position position) { String attributesString = Context.getDeviceManager().lookupAttributeString( position.getDeviceId(), "processing.copyAttributes", "", true); Position last = getLastPosition(position.getDeviceId()); if (attributesString.isEmpty()) { attributesString = Position.KEY_DRIVER_UNIQUE_ID; } else { if (attributesString.equals("all")) { position.setAttributes(last.getAttributes()); return position; } else { attributesString += "," + Position.KEY_DRIVER_UNIQUE_ID; } } if (last != null) { for (String attribute : attributesString.split("[ ,]")) { if (last.getAttributes().containsKey(attribute) && !position.getAttributes().containsKey(attribute)) { position.getAttributes().put(attribute, last.getAttributes().get(attribute)); } } } return position; }

Target:
protected Position handlePosition(Position position) { Position last = getLastPosition(position.getDeviceId()); String attributesString = Context.getDeviceManager().lookupAttributeString( position.getDeviceId(), "processing.copyAttributes", null, true); return copyAttributes(attributesString, position, last); }
Source:
public void banCommit() throws Exception { add(git, "a.txt", "some content"); Commit c = createCommit(git, admin.getIdent(), "subject"); RestResponse r = adminSession.put("/projects/" + project.get() + "/ban/", BanCommit.Input.fromCommits(c.getCommit().getName())); assertThat(r.getStatusCode()).isEqualTo(HttpStatus.SC_OK); BanResultInfo info = newGson().fromJson(r.getReader(), BanResultInfo.class); assertThat(Iterables.getOnlyElement(info.newlyBanned)) .isEqualTo(c.getCommit().getName()); assertThat(info.alreadyBanned).isNull(); assertThat(info.ignored).isNull(); PushResult pushResult = pushHead(git, "refs/heads/master", false); assertThat(pushResult.getRemoteUpdate("refs/heads/master").getMessage() .startsWith("contains banned commit")); }

Target:
public void banCommit() throws Exception { add(git, "a.txt", "some content"); Commit c = createCommit(git, admin.getIdent(), "subject"); RestResponse r = adminSession.put("/projects/" + project.get() + "/ban/", BanCommit.Input.fromCommits(c.getCommit().getName())); assertThat(r.getStatusCode()).isEqualTo(HttpStatus.SC_OK); BanResultInfo info = newGson().fromJson(r.getReader(), BanResultInfo.class); assertThat(Iterables.getOnlyElement(info.newlyBanned)) .isEqualTo(c.getCommit().getName()); assertThat(info.alreadyBanned).isNull(); assertThat(info.ignored).isNull(); PushResult pushResult = pushHead(git, "refs/heads/master", false); assertThat(pushResult.getRemoteUpdate("refs/heads/master").getMessage()) .startsWith("contains banned commit"); }
Source:
private void lockVmSnapshotsWithWait(VM vm) { Map<String, String> snapshotsExlusiveLockMap = new HashMap<String, String>(); snapshotsExlusiveLockMap.put(vm.getId().toString(), LockingGroup.VM_SNAPSHOTS.name()); snapshotsEngineLock.setExclusiveLocks(snapshotsExlusiveLockMap); getLockManager().acquireLockWait(snapshotsEngineLock); }

Target:
private void lockVmSnapshotsWithWait(VM vm) { Map<String, String> snapshotsExlusiveLockMap = Collections.singletonMap(vm.getId().toString(), LockingGroup.VM_SNAPSHOTS.name()); snapshotsEngineLock.setExclusiveLocks(snapshotsExlusiveLockMap); getLockManager().acquireLockWait(snapshotsEngineLock); }
Source:
public void verify(byte[] contentBytes, byte[] signatureBytes) throws SignatureVerificationException { try { if (publicKey == null) { throw new IllegalArgumentException("The given Public Key is null."); } boolean valid = crypto.verifySignatureFor(getDescription(), publicKey, contentBytes, signatureBytes); if (!valid) { throw new SignatureVerificationException(this); } } catch (NoSuchAlgorithmException | SignatureException | InvalidKeyException | IllegalArgumentException e) { throw new SignatureVerificationException(this, e); } }

Target:
public void verify(byte[] contentBytes, byte[] signatureBytes) throws SignatureVerificationException { try { if (publicKey == null) { throw new IllegalStateException("The given Public Key is null."); } boolean valid = crypto.verifySignatureFor(getDescription(), publicKey, contentBytes, signatureBytes); if (!valid) { throw new SignatureVerificationException(this); } } catch (NoSuchAlgorithmException | SignatureException | InvalidKeyException | IllegalStateException e) { throw new SignatureVerificationException(this, e); } }
Source:
ConstrainedElement build(ConstraintHelper constraintHelper, TypeResolutionHelper typeResolutionHelper, ValueExtractorManager valueExtractorManager) { if ( property.getKind() == Property.Kind.FIELD ) { return ConstrainedProperty.forField( ConfigurationSource.API, property, getConstraints( constraintHelper, typeResolutionHelper, valueExtractorManager ), getTypeArgumentConstraints( constraintHelper, typeResolutionHelper, valueExtractorManager ), getCascadingMetaDataBuilder() ); } else { return new ConstrainedExecutable( ConfigurationSource.API, property.as( Callable.class ), getConstraints( constraintHelper, typeResolutionHelper, valueExtractorManager ), getTypeArgumentConstraints( constraintHelper, typeResolutionHelper, valueExtractorManager ), getCascadingMetaDataBuilder() ); } }

Target:
ConstrainedElement build(ConstraintHelper constraintHelper, TypeResolutionHelper typeResolutionHelper, ValueExtractorManager valueExtractorManager) { if ( property instanceof JavaBeanField ) { return ConstrainedProperty.forField( ConfigurationSource.API, property, getConstraints( constraintHelper, typeResolutionHelper, valueExtractorManager ), getTypeArgumentConstraints( constraintHelper, typeResolutionHelper, valueExtractorManager ), getCascadingMetaDataBuilder() ); } else { return new ConstrainedExecutable( ConfigurationSource.API, property.as( Callable.class ), getConstraints( constraintHelper, typeResolutionHelper, valueExtractorManager ), getTypeArgumentConstraints( constraintHelper, typeResolutionHelper, valueExtractorManager ), getCascadingMetaDataBuilder() ); } }
Source:
private RequestFuture<Map<TopicPartition, OffsetAndMetadata>> sendOffsetFetchRequest(Set<TopicPartition> partitions) { Node coordinator = checkAndGetCoordinator(); if (coordinator == null) return RequestFuture.coordinatorNotAvailable(); log.debug("Fetching committed offsets for partitions: {}", partitions); OffsetFetchRequest.Builder requestBuilder = new OffsetFetchRequest.Builder(this.rebalanceConfig.groupId, false, new ArrayList<>(partitions)); return client.send(coordinator, requestBuilder) .compose(new OffsetFetchResponseHandler()); }

Target:
private RequestFuture<Map<TopicPartition, OffsetAndMetadata>> sendOffsetFetchRequest(Set<TopicPartition> partitions) { Node coordinator = checkAndGetCoordinator(); if (coordinator == null) return RequestFuture.coordinatorNotAvailable(); log.debug("Fetching committed offsets for partitions: {}", partitions); OffsetFetchRequest.Builder requestBuilder = new OffsetFetchRequest.Builder(this.rebalanceConfig.groupId, true, new ArrayList<>(partitions)); return client.send(coordinator, requestBuilder) .compose(new OffsetFetchResponseHandler()); }
Source:
public void each(MatrixProcedure procedure) { int l = 0; for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { if (j == rowIndices[l]) { procedure.apply(i,j,values[l++]); } else { procedure.apply(i,j,0); } } } }

Target:
public void each(MatrixProcedure procedure) { int k = 0; for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { if (j == rowIndices[k]) { procedure.apply(i, j, values[k]); k++; } else { procedure.apply(i, j, 0); } } } }
Source:
public Api getAPIForSite(Site site) { if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean(WikipediaApp.PREFERENCE_EVENTLOGGING_ENABLED, true)) { if (!MccMncStateHandler.hasMccMncBeenSent()) { Api api = MccMncStateHandler.makeApiWithMccMncHeaderEnrichment(this, site, getUserAgent()); if (api != null) { return api; } } } if (!apis.containsKey(site.getDomain())) { apis.put(site.getDomain(), new Api(site.getApiDomain(), getUserAgent())); } return apis.get(site.getDomain()); }

Target:
public Api getAPIForSite(Site site) { Api api = mccMncStateHandler.makeApiWithMccMncHeaderEnrichment(this, site, getUserAgent()); if (api != null) { return api; } if (!apis.containsKey(site.getDomain())) { apis.put(site.getDomain(), new Api(site.getApiDomain(), getUserAgent())); } return apis.get(site.getDomain()); }
Source:
protected AbstractCachingAuthenticator(long allowedTimestampSlop, long cacheTimeout, TimeUnit timeUnit, long maxCacheElements) { super(allowedTimestampSlop, timeUnit); cache = CacheBuilder.newBuilder() .maximumSize(maxCacheElements) .expireAfterWrite(cacheTimeout, timeUnit) .build(new CacheLoader<Credentials, Optional<Principal>>() { @Override public Optional<Principal> load(Credentials credentials) throws Exception { return Optional.fromNullable(loadPrincipal(credentials)); } }); }

Target:
protected AbstractCachingAuthenticator(long allowedTimestampSlop, long cacheTimeout, TimeUnit timeUnit, long maxCacheElements) { super(allowedTimestampSlop, timeUnit); cache = CacheBuilder.newBuilder() .maximumSize(maxCacheElements) .expireAfterWrite(cacheTimeout, timeUnit) .build(); }
Source:
public Collection<SearchPlanForBody> plan(PQuery querySpec, Set<Integer> boundVarIndices) throws QueryProcessingException { Set<PBody> normalizedBodies = prepareNormalizedBodies(querySpec); plansForBodies = Lists.newArrayList(); for (PBody normalizedBody : normalizedBodies) { Set<PVariable> boundVariables = calculatePatternAdornmentForPlanner(boundVarIndices, normalizedBody); SubPlan plan = plannerStrategy.plan(normalizedBody, logger, boundVariables, metaContext, runtimeContext, hints); List<ISearchOperation> compiledOperations = operationCompiler.compile(plan, boundVarIndices); SearchPlanForBody compiledPlan = new SearchPlanForBody(normalizedBody, operationCompiler.getVariableMappings(), plan, compiledOperations); plansForBodies.add(compiledPlan); } return plansForBodies; }

Target:
public Collection<SearchPlanForBody> plan(PQuery querySpec, Set<Integer> boundVarIndices) throws QueryProcessingException { Set<PBody> normalizedBodies = prepareNormalizedBodies(querySpec); plansForBodies = Lists.newArrayListWithExpectedSize(normalizedBodies.size()); for (PBody normalizedBody : normalizedBodies) { Set<PVariable> boundVariables = calculatePatternAdornmentForPlanner(boundVarIndices, normalizedBody); SubPlan plan = plannerStrategy.plan(normalizedBody, logger, boundVariables, metaContext, runtimeContext, hints); List<ISearchOperation> compiledOperations = operationCompiler.compile(plan, boundVarIndices); SearchPlanForBody compiledPlan = new SearchPlanForBody(normalizedBody, operationCompiler.getVariableMappings(), plan, compiledOperations); plansForBodies.add(compiledPlan); } return plansForBodies; }
Source:
public static void untar(InputStream in, File targetDir) throws IOException { try (TarArchiveInputStream tarIn = new TarArchiveInputStream(in)) { byte[] b = new byte[BUF_SIZE]; TarArchiveEntry tarEntry; while ((tarEntry = tarIn.getNextTarEntry()) != null) { final File file = new File(targetDir, tarEntry.getName()); if (tarEntry.isDirectory()) { if (!file.mkdirs()) { throw new IOException("Unable to create folder " + file.getAbsolutePath()); } } else { final File parent = file.getParentFile(); if (!parent.exists()) { if (!parent.mkdirs()) { throw new IOException("Unable to create folder " + parent.getAbsolutePath()); } } try (FileOutputStream fos = new FileOutputStream(file)) { int r; while ((r = tarIn.read(b)) != -1) { fos.write(b, 0, r); } } } } } }

Target:
public static void untar(InputStream in, File targetDir) throws IOException { final TarArchiveInputStream tarIn = new TarArchiveInputStream(in); byte[] b = new byte[BUF_SIZE]; TarArchiveEntry tarEntry; while ((tarEntry = tarIn.getNextTarEntry()) != null) { final File file = new File(targetDir, tarEntry.getName()); if (tarEntry.isDirectory()) { if (!file.mkdirs()) { throw new IOException("Unable to create folder " + file.getAbsolutePath()); } } else { final File parent = file.getParentFile(); if (!parent.exists()) { if (!parent.mkdirs()) { throw new IOException("Unable to create folder " + parent.getAbsolutePath()); } } try (FileOutputStream fos = new FileOutputStream(file)) { int r; while ((r = tarIn.read(b)) != -1) { fos.write(b, 0, r); } } } } }