auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static void openEditorForReblog( Activity activity, @Nullable SiteModel site, @Nullable ReaderPost post, PagePostCreationSourcesDetail reblogSource ) { if (post == null) { ToastUtils.showToast(activity, R.string.post_not_found, ToastUtils.Duration.SHORT); return; } if (site == null) { ToastUtils.showToast(activity, R.string.blog_not_found, ToastUtils.Duration.SHORT); return; } Map<String, Object> properties = new HashMap<>(); properties.put("source_post_id", post.postId); properties.put("source_blog_id", post.blogId); properties.put("target_blog_id", site.getSiteId()); AnalyticsTracker.track( reblogSource == PagePostCreationSourcesDetail.POST_FROM_REBLOG ? READER_ARTICLE_REBLOGGED : READER_ARTICLE_DETAIL_REBLOGGED, properties ); Intent editorIntent = new Intent(activity, EditPostActivity.class); editorIntent.putExtra(EditPostActivity.EXTRA_REBLOG_POST_TITLE, post.getTitle()); editorIntent.putExtra(EditPostActivity.EXTRA_REBLOG_POST_QUOTE, post.getExcerpt()); editorIntent.putExtra(EditPostActivity.EXTRA_REBLOG_POST_IMAGE, post.getFeaturedImage()); editorIntent.putExtra(EditPostActivity.EXTRA_REBLOG_POST_CITATION, post.getUrl()); editorIntent.setAction(EditPostActivity.ACTION_REBLOG); addNewPostForResult(editorIntent, activity, site, false, reblogSource); }

Target:
public static void openEditorForReblog( Activity activity, @Nullable SiteModel site, @Nullable ReaderPost post, PagePostCreationSourcesDetail reblogSource ) { if (post == null) { ToastUtils.showToast(activity, R.string.post_not_found, ToastUtils.Duration.SHORT); return; } if (site == null) { ToastUtils.showToast(activity, R.string.blog_not_found, ToastUtils.Duration.SHORT); return; } AnalyticsUtils.trackWithReblogDetails( reblogSource == PagePostCreationSourcesDetail.POST_FROM_REBLOG ? READER_ARTICLE_REBLOGGED : READER_ARTICLE_DETAIL_REBLOGGED, post.blogId, post.postId, site.getSiteId() ); Intent editorIntent = new Intent(activity, EditPostActivity.class); editorIntent.putExtra(EditPostActivity.EXTRA_REBLOG_POST_TITLE, post.getTitle()); editorIntent.putExtra(EditPostActivity.EXTRA_REBLOG_POST_QUOTE, post.getExcerpt()); editorIntent.putExtra(EditPostActivity.EXTRA_REBLOG_POST_IMAGE, post.getFeaturedImage()); editorIntent.putExtra(EditPostActivity.EXTRA_REBLOG_POST_CITATION, post.getUrl()); editorIntent.setAction(EditPostActivity.ACTION_REBLOG); addNewPostForResult(editorIntent, activity, site, false, reblogSource); }
Source:
private boolean isLiquid(Block block) { BlockData data = block.getBlockData(); if (data instanceof Levelled) { return ((Levelled) data).getLevel == 0; } return false; }

Target:
private boolean isLiquid(Block block) { if (!block.isLiquid()) return false; BlockData data = block.getBlockData(); if (data instanceof Levelled) { return ((Levelled) data).getLevel() == 0; } return false; }
Source:
public void start() { processorListener.beforeStart(); synchronized (lock) { if (state == State.NEW) { state = State.STARTED; jobCoordinator.start(); } else { LOGGER.info("Start is no-op, since the current state is and not {}.", state, State.NEW); } } }

Target:
public void start() { synchronized (lock) { if (state == State.NEW) { processorListener.beforeStart(); state = State.STARTED; jobCoordinator.start(); } else { LOGGER.info("Start is no-op, since the current state is and not {}.", state, State.NEW); } } }
Source:
private ListenableFuture<Response> sendRequestToAsyncHandler( final AsyncRequestHandler asyncHandler, final Request request) { final Span span = Tracing.startInboundSpan(request, topChannel.getTracer(), topChannel.getTracingContext()); final SettableFuture<Response> responseFuture = SettableFuture.create(); ListenableFuture<Response> handlerResponseFuture = (ListenableFuture<Response>) asyncHandler.handleAsync(request); Futures.addCallback(handlerResponseFuture, new FutureCallback<Response>() { @Override public void onSuccess(Response response) { doRequestEndProcessing(); responseFuture.set(response); } @Override public void onFailure(Throwable e) { span.log("exception", e); doRequestEndProcessing(); responseFuture.setException(e); } private void doRequestEndProcessing() { span.finish(); request.release(); topChannel.getTracingContext().clear(); } }); return responseFuture; }

Target:
private ListenableFuture<Response> sendRequestToAsyncHandler( final AsyncRequestHandler asyncHandler, final Request request) { final Span span; if (topChannel.getTracer() != null) { span = Tracing.startInboundSpan(request, topChannel.getTracer(), topChannel.getTracingContext()); } else { span = null; } final SettableFuture<Response> responseFuture = SettableFuture.create(); ListenableFuture<Response> handlerResponseFuture = (ListenableFuture<Response>) asyncHandler.handleAsync(request); Futures.addCallback(handlerResponseFuture, new FutureCallback<Response>() { @Override public void onSuccess(Response response) { doRequestEndProcessing(); responseFuture.set(response); } @Override public void onFailure(Throwable e) { if (span != null) { span.log("exception", e); } doRequestEndProcessing(); responseFuture.setException(e); } private void doRequestEndProcessing() { if (span != null) { span.finish(); } request.release(); topChannel.getTracingContext().clear(); } }); return responseFuture; }
Source:
private static String formatErrorMessageBefore(WindupRuleProvider provider, WindupRuleProvider otherProvider) { return "Rule \"" + provider.getID() + "\" from phase \"" + provider.getPhase() + "\" is to set to execute before\n" + "rule \"" + otherProvider.getID() + "\"" + " from earlier phase \"" + otherProvider.getPhase() + "\".\nPossible solution is to specify phase " + otherProvider.getPhase() + " or earlier for the first rule."; }

Target:
private static String formatErrorMessageBefore(WindupRuleProvider provider, WindupRuleProvider otherProvider) { return WindupRuleProvider.class.getSimpleName() + '[' + provider.getID() + "] from phase " + provider.getPhase() + " is to set to execute before\n" + WindupRuleProvider.class.getSimpleName() + '[' + otherProvider.getID() + "] from earlier phase " + otherProvider.getPhase() + ".\nPossible solution is to specify phase " + otherProvider.getPhase() + " or earlier for the former."; }
Source:
public void testStandardClientsUseTextDelegateEncoder() { assertThat(service.getString("string"), is("string")); }

Target:
public void testStandardClientsUseTextDelegateEncoder() { assertThat(service.getString("string"), is("string")); assertThat(service.getString(null), is((String) null)); }
Source:
public String getNamespace() { return namespaceName; }

Target:
public String getNamespace() { return namespace; }
Source:
public IStatus validate(IProject project, String path) { File file = new File(path); if (!file.exists()) { return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "File not found: " + path); } if (!file.isFile()) { return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Not a file. It's a directory: " + path); } int confidence = 0; try { if (!TmfTraceUtils.isText(file)) { return new TraceValidationStatus(confidence, Activator.PLUGIN_ID); } } catch (IOException e) { Activator.getInstance().logError("Error validating file: " + path, e); return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "IOException validating file: " + path, e); } try (BufferedRandomAccessFile rafile = new BufferedRandomAccessFile(path, "r")) { goToCorrectStart(rafile); int lineCount = 0; int matches = 0; String line = readNextEventString(() -> rafile.read()); while ((line != null) && (lineCount++ < MAX_LINES)) { try { OpenTracingField field = OpenTracingField.parseJson(line, ""); if (field != null) { matches++; } } catch (RuntimeException e) { confidence = Integer.MIN_VALUE; } confidence = MAX_CONFIDENCE * matches / lineCount; line = readNextEventString(() -> rafile.read()); } if (matches == 0) { return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Most assuredly NOT a Open-Tracing trace"); } } catch (IOException e) { Activator.getInstance().logError("Error validating file: " + path, e); return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "IOException validating file: " + path, e); } return new TraceValidationStatus(confidence, Activator.PLUGIN_ID); }

Target:
public IStatus validate(IProject project, String path) { File file = new File(path); if (!file.exists()) { return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "File not found: " + path); } if (!file.isFile()) { return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Not a file. It's a directory: " + path); } int confidence = 0; try { if (!TmfTraceUtils.isText(file)) { return new TraceValidationStatus(confidence, Activator.PLUGIN_ID); } } catch (IOException e) { Activator.getInstance().logError("Error validating file: " + path, e); return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "IOException validating file: " + path, e); } try (BufferedRandomAccessFile rafile = new BufferedRandomAccessFile(path, "r")) { goToCorrectStart(rafile); int lineCount = 0; int matches = 0; String line = readNextEventString(() -> rafile.read()); while ((line != null) && (lineCount++ < MAX_LINES)) { try { OpenTracingField field = OpenTracingField.parseJson(line, null); if (field != null) { matches++; } } catch (RuntimeException e) { confidence = Integer.MIN_VALUE; } confidence = MAX_CONFIDENCE * matches / lineCount; line = readNextEventString(() -> rafile.read()); } if (matches == 0) { return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Most assuredly NOT a Open-Tracing trace"); } } catch (IOException e) { Activator.getInstance().logError("Error validating file: " + path, e); return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "IOException validating file: " + path, e); } return new TraceValidationStatus(confidence, Activator.PLUGIN_ID); }
Source:
public void noPropertiesThrowsMeaningfulException() { try { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); context.register(Conf.class); context.refresh(); fail("should throw exception"); context.close(); } catch (Exception e) { assertThat(e.getCause(), instanceOf(BindException.class)); BindException bindException = (BindException) e.getCause(); FieldError fieldError = (FieldError) bindException.getAllErrors().get(0); assertThat(fieldError.getArguments()[0].toString(), containsString("username")); assertThat(fieldError.getDefaultMessage(), equalTo("may not be empty")); } }

Target:
public void noPropertiesThrowsMeaningfulException() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); try { context.register(Conf.class); context.refresh(); fail("exception expected"); } catch (Exception e) { assertThat(e.getCause(), instanceOf(BindException.class)); BindException bindException = (BindException) e.getCause(); FieldError fieldError = (FieldError) bindException.getAllErrors().get(0); assertThat(fieldError.getArguments()[0].toString(), containsString("username")); assertThat(fieldError.getDefaultMessage(), equalTo("may not be empty")); } finally { context.close(); } }
Source:
public boolean isPaused() { synchronized (fSynchObject) { return fIsPaused; } }

Target:
public boolean isPaused() { return fIsPaused; }
Source:
private static Slice internalDoubleToLongDecimal(double value, long precision, long scale) { if (Double.isInfinite(value) || Double.isNaN(value)) { throw new PrestoException(INVALID_CAST_ARGUMENT, format("Cannot cast DOUBLE '%s' to DECIMAL(%s, %s)", value, precision, scale)); } try { BigDecimal bigDecimal = BigDecimal.valueOf(value).setScale((int) scale, BigDecimal.ROUND_HALF_UP); Slice decimal = Decimals.encodeScaledValue(bigDecimal); if (overflows(decimal, intScale(precision))) { throw new PrestoException(INVALID_CAST_ARGUMENT, format("Cannot cast DOUBLE '%s' to DECIMAL(%s, %s)", value, precision, scale)); } return decimal; } catch (ArithmeticException e) { throw new PrestoException(INVALID_CAST_ARGUMENT, format("Cannot cast DOUBLE '%s' to DECIMAL(%s, %s)", value, precision, scale)); } }

Target:
private static Slice internalDoubleToLongDecimal(double value, long precision, long scale) { if (Double.isInfinite(value) || Double.isNaN(value)) { throw new PrestoException(INVALID_CAST_ARGUMENT, format("Cannot cast DOUBLE '%s' to DECIMAL(%s, %s)", value, precision, scale)); } try { BigDecimal bigDecimal = BigDecimal.valueOf(value).setScale(intScale(scale), HALF_UP); Slice decimal = Decimals.encodeScaledValue(bigDecimal); if (overflows(decimal, intScale(precision))) { throw new PrestoException(INVALID_CAST_ARGUMENT, format("Cannot cast DOUBLE '%s' to DECIMAL(%s, %s)", value, precision, scale)); } return decimal; } catch (ArithmeticException e) { throw new PrestoException(INVALID_CAST_ARGUMENT, format("Cannot cast DOUBLE '%s' to DECIMAL(%s, %s)", value, precision, scale)); } }
Source:
public CloseableExecutorService(ExecutorService executorService, boolean shutdownOnClose) { this.executorService = Preconditions.checkNotNull(executorService); this.shutdownOnClose = shutdownOnClose; }

Target:
public CloseableExecutorService(ExecutorService executorService, boolean shutdownOnClose) { this.executorService = Preconditions.checkNotNull(executorService, "executorService cannot be null"); this.shutdownOnClose = shutdownOnClose; }
Source:
public Future<Void> truncateTableAsync(TableName tableName, boolean preserveSplits) throws IOException { if (!preserveSplits) { LOG.info("truncate will preserveSplits. The passed in variable is ignored."); } return FutureUtils.toCompletableFuture( tableAdminClientWrapper .dropRowRangeAsync(tableName.getNameAsString(), ByteString.EMPTY.toStringUtf8())) .thenApply(r -> null); }

Target:
public Future<Void> truncateTableAsync(TableName tableName, boolean preserveSplits) throws IOException { if (!preserveSplits) { LOG.info("truncate will preserveSplits. The passed in variable is ignored."); } return FutureUtils.toCompletableFuture( tableAdminClientWrapper .dropRowRangeAsync(tableName.getNameAsString(), "")) .thenApply(r -> null); }
Source:
public void run() { try { assert(m_registeredStateMachineInstances == ByteBuffer.wrap(m_zk.getData(m_stateMachineRoot, false, null)).getInt()); new ZKAsyncCreateHandler(m_stateMachineMemberPath, null, CreateMode.PERSISTENT) { @Override public void run() { if (checkForCommonKeeperExceptions(m_resultCode)) { addMemberIdIfMissing(); } } }; } catch (InterruptedException e) { m_done.set(true); m_initComplete.set(false); } catch (Exception e) { org.voltdb.VoltDB.crashLocalVoltDB( "Unexpected failure in initializeInstances.", true, e); m_done.set(true); m_initComplete.set(false); } }

Target:
public void run() { try { assert(m_registeredStateMachineInstances == ByteBuffer.wrap(m_zk.getData(m_stateMachineRoot, false, null)).getInt()); new ZKAsyncCreateHandler(m_stateMachineMemberPath, null, CreateMode.PERSISTENT) { @Override public void run() { if (noCommonKeeperExceptions(m_resultCode)) { addMemberIdIfMissing(); } } }; } catch (InterruptedException e) { initializationFailed(); } catch (Exception e) { org.voltdb.VoltDB.crashLocalVoltDB( "Unexpected failure in initializeInstances.", true, e); } }
Source:
protected MessageType getProjectedSchema(FieldProjectionFilter fieldProjectionFilter) { ThriftType.StructType thriftStruct = new ScroogeStructConverter().convert(thriftClass); return getProjectedSchema(null, fieldProjectionFilter); }

Target:
protected MessageType getProjectedSchema(FieldProjectionFilter fieldProjectionFilter) { return getProjectedSchema(new Configuration(), fieldProjectionFilter); }
Source:
public AuthConfigurations getAuthConfigurations() { File dockerCfgFile = new File(getDockerConfig() + File.separator + DOCKER_CFG); if (dockerCfgFile.exists()) { AuthConfigFile authConfigFile; try { authConfigFile = AuthConfigFile.loadConfig(dockerCfgFile); } catch (IOException e) { throw new DockerClientException("Failed to parse dockerCfgFile", e); } return authConfigFile.getAuthConfigurations(); } return new AuthConfigurations(); }

Target:
public AuthConfigurations getAuthConfigurations() { File dockerCfgFile = new File(getDockerConfig() + File.separator + DOCKER_CFG); if (dockerCfgFile.exists() && dockerCfgFile.isFile()) { AuthConfigFile authConfigFile; try { authConfigFile = AuthConfigFile.loadConfig(dockerCfgFile); } catch (IOException e) { throw new DockerClientException("Failed to parse dockerCfgFile", e); } return authConfigFile.getAuthConfigurations(); } return new AuthConfigurations(); }
Source:
private PrivateKeyEntry getPrivateKeyEntry(String alias) throws CertificateManagerException { LOG.debug("SamlCallbackHandler.getDefaultPrivKeyCert() -- Begin"); KeyStore.PrivateKeyEntry pkEntry = null; final String clientkeyAlias = StringUtils.isNotBlank(alias) ? alias : StoreUtil.getInstance().getPrivateKeyAlias(); LOG.debug("debug--getPrivateKeyEntry-clientkeyAlias:{}", clientkeyAlias); if (clientkeyAlias != null) { final String password = getKeyStoreSystemProperties().get(KEY_STORE_PASSWORD_KEY); if (password != null) { try { pkEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(clientkeyAlias, new KeyStore.PasswordProtection(password.toCharArray())); } catch (final NoSuchAlgorithmException | KeyStoreException | UnrecoverableEntryException ex) { LOG.error("Error initializing Private Key: {}", ex.getLocalizedMessage(), ex); throw new CertificateManagerException(ex.getLocalizedMessage(), ex); } } else { LOG.error("{} is not a defined system property.", KEY_STORE_PASSWORD_KEY); } } else { LOG.error("{} is not a defined system property.", NhincConstants.CLIENT_KEY_ALIAS); } LOG.debug("SamlCallbackHandler.getDefaultPrivKeyCert() -- End"); return pkEntry; }

Target:
private PrivateKeyEntry getPrivateKeyEntry(String alias) throws CertificateManagerException { LOG.debug("SamlCallbackHandler.getDefaultPrivKeyCert() -- Begin"); PrivateKeyEntry pkEntry = null; final String clientkeyAlias = StringUtils.isNotBlank(alias) ? alias : StoreUtil.getInstance().getPrivateKeyAlias(); LOG.debug("getPrivateKeyEntry-clientkeyAlias:{}", clientkeyAlias); final String password = getKeyStoreSystemProperties().get(KEY_STORE_PASSWORD_KEY); if (password != null) { try { pkEntry = (PrivateKeyEntry) keyStore.getEntry(clientkeyAlias, new KeyStore.PasswordProtection(password.toCharArray())); } catch (final NoSuchAlgorithmException | KeyStoreException | UnrecoverableEntryException ex) { throw new CertificateManagerException(ex.getLocalizedMessage(), ex); } } else { LOG.error("{} is not a defined system property.", KEY_STORE_PASSWORD_KEY); } LOG.debug("SamlCallbackHandler.getDefaultPrivKeyCert() -- End"); return pkEntry; }
Source:
public void testLenientFromJson() { String json = gson.fromJson("\"Hello\"", String.class); assertEquals("Hello", json); }

Target:
public void testLenientFromJson() { List<String> json = gson.fromJson("" + "[ # One!\n" + " 'Hi' #Element!\n" + "] # Array!", new TypeToken<List<String>>() {}.getType()); assertEquals(singletonList("Hi"), json); }
Source:
public void testNowWithComplexPeriod() throws Exception { Collection<CompoundVariable> params = makeParams("YYYY-MM-dd'T'HH:mm:ss", "", "+1M+1d-1H-5m5s", ""); function.setParameters(params); value = function.execute(result, null); LocalDateTime futureDate = LocalDateTime.now().plusMonths(1).plusDays(1).plusHours(-1).plusMinutes(-5).plusSeconds(5); LocalDateTime futureDateFromFunction = LocalDateTime.parse(value); assertThat(futureDateFromFunction, within(1, ChronoUnit.SECONDS, futureDate)); }

Target:
public void testNowWithComplexPeriod() throws Exception { Collection<CompoundVariable> params = makeParams("YYYY-MM-dd'T'HH:mm:ss", "", "P10DT-1H-5M5S", ""); function.setParameters(params); value = function.execute(result, null); LocalDateTime futureDate = LocalDateTime.now().plusDays(10).plusHours(-1).plusMinutes(-5).plusSeconds(5); LocalDateTime futureDateFromFunction = LocalDateTime.parse(value); assertThat(futureDateFromFunction, within(1, ChronoUnit.SECONDS, futureDate)); }
Source:
protected Assertion parseResponseFromServer(final String response) throws TicketValidationException { try { final TicketValidationJsonResponse json = new JsonValidationResponseParser().parse(response); return json.getAssertion(getProxyGrantingTicketStorage(), getProxyRetriever()); } catch (final Exception e) { logger.warn("Unable parse the JSON response", e); return super.parseResponseFromServer(response); } }

Target:
protected Assertion parseResponseFromServer(final String response) throws TicketValidationException { try { final TicketValidationJsonResponse json = new JsonValidationResponseParser().parse(response); return json.getAssertion(getProxyGrantingTicketStorage(), getProxyRetriever()); } catch (final JsonProcessingException e) { logger.warn("Unable parse the JSON response. Falling back to XML", e); return super.parseResponseFromServer(response); } catch (final IOException e) { throw new TicketValidationException(e.getMessage(), e); } }
Source:
private synchronized void handleFinishedServerContext(final String contextId) { serverContexts.remove(contextId); final String jobState = jobStateMachine.getCurrentState(); switch (jobState) { case RUNNING: LOG.log(Level.WARNING, "Server context {0} is closed when the job is not in shutdown phase", contextId); break; case CLOSING_WORKERS: LOG.log(Level.WARNING, "Server context {0} is closed after starting close of root contexts", contextId); break; case CLOSING_SERVERS: if (serverContexts.isEmpty()) { jobStateMachine.setState(CLOSING_ROOTS); LOG.info("Start closing root contexts"); for (final ActiveContext rootContext : rootContexts.values()) { rootContext.close(); } } break; case CLOSING_ROOTS: LOG.log(Level.WARNING, "Server context {0} is closed after starting close of root contexts", contextId); break; default: throw new RuntimeException("Unexpected state"); } }

Target:
private synchronized void handleFinishedServerContext(final String contextId) { contextIdToServerContexts.remove(contextId); final String jobState = jobStateMachine.getCurrentState(); switch (jobState) { case STATE_RUNNING: LOG.log(Level.WARNING, "Server context {0} is closed when the job is not in shutdown phase", contextId); break; case STATE_CLOSING_WORKERS: LOG.log(Level.WARNING, "Server context {0} is closed before starting close of servers", contextId); break; case STATE_CLOSING_SERVERS: if (contextIdToServerContexts.isEmpty()) { jobStateMachine.setState(STATE_CLOSING_ROOT_CONTEXTS); LOG.info("Start closing root contexts"); for (final ActiveContext rootContext : contextIdToRootContexts.values()) { rootContext.close(); } } break; case STATE_CLOSING_ROOT_CONTEXTS: LOG.log(Level.WARNING, "Server context {0} is closed after starting close of root contexts", contextId); break; default: throw new RuntimeException("Unexpected state"); } }
Source:
private ServerSocket connectToPort() throws Exception { int port = findAvailablePort(); LOG.info("acquired port on "+port+" for test "+JavaClassNames.niceClassAndMethod()); return new ServerSocket(port); }

Target:
private ServerSocket connectToPort() throws Exception { ServerSocket result = new ServerSocket(0); LOG.info("Acquired port "+result+" for test "+JavaClassNames.niceClassAndMethod()); return result; }
Source:
public void createsTree() throws Exception { final MkContainer container = new MkGrizzlyContainer().next( new MkAnswer.Simple( HttpURLConnection.HTTP_CREATED, "{\"sha\":\"0abcd89jcabitest\",\"url\":\"http://localhost/1\"}" ) ).start(); final Trees trees = new RtTrees( new ApacheRequest(container.home()), repo() ); final JsonObject tree = Json.createObjectBuilder() .add("path", "/path").add("mode", "100644 ") .add("type", "blob").add("sha", "sha1") .add("content", "content1").build(); final JsonObject input = Json.createObjectBuilder() .add("tree", tree).add("base_tree", "SHA1") .build(); try { MatcherAssert.assertThat( trees.create(input), Matchers.instanceOf(Tree.class) ); MatcherAssert.assertThat( container.take().method(), Matchers.equalTo(Request.POST) ); } finally { container.stop(); } }

Target:
public void createsTree() throws Exception { final MkContainer container = new MkGrizzlyContainer().next( new MkAnswer.Simple( HttpURLConnection.HTTP_CREATED, "{\"sha\":\"0abcd89jcabitest\",\"url\":\"http://localhost/1\"}" ) ).start(); final Trees trees = new RtTrees( new ApacheRequest(container.home()), repo() ); final JsonObject tree = Json.createObjectBuilder() .add("path", "/path").add("mode", "100644 ") .add("type", "blob").add("sha", "sha1") .add("content", "content1").build(); final JsonObject input = Json.createObjectBuilder() .add("tree", tree).add("base_tree", "SHA1") .build(); try { final Tree tri = trees.create(input); MatcherAssert.assertThat( tri, Matchers.instanceOf(Tree.class) ); MatcherAssert.assertThat( trees.get(tri.sha()), Matchers.equalTo(tri) ); MatcherAssert.assertThat( container.take().method(), Matchers.equalTo(Request.POST) ); } finally { container.stop(); } }
Source:
public int getImageselector () { return imageSelectorIndex; }

Target:
int getImageselector () { return imageSelectorIndex; }
Source:
public RepositoryConfigurationSourceSupport(Environment environment, ClassLoader classLoader) { Assert.notNull(environment, "Environment must not be null!"); this.environment = environment; this.beanNameGenerator = new RepositoryBeanNameGenerator(classLoader); }

Target:
public RepositoryConfigurationSourceSupport(Environment environment, ClassLoader classLoader) { Assert.notNull(environment, "Environment must not be null!"); Assert.notNull(classLoader, "ClassLoader must not be null!"); this.environment = environment; this.beanNameGenerator = new RepositoryBeanNameGenerator(classLoader); }
Source:
public boolean onTouchEvent(MotionEvent event) { if (mScrollDirectionListener != null) { mDetector.onTouchEvent(event); } return super.onTouchEvent(event); }

Target:
public boolean onTouchEvent(MotionEvent event) { if (mScrollDirectionListener != null && event.getActionMasked() == MotionEvent.ACTION_MOVE && event.getHistorySize() > 0) { float initialY = event.getHistoricalY(event.getHistorySize() - 1); float distanceY = initialY - event.getY(); if (distanceY < 0) { mScrollDirectionListener.onScrollUp(distanceY); startScrollCheck(); } else if (distanceY > 0) { mScrollDirectionListener.onScrollDown(distanceY); startScrollCheck(); } } return super.onTouchEvent(event); }
Source:
public static Set<String> planTags() { List<Map<String, Object>> blogs = WordPress.wpDB.getBlogsBy("dotcomFlag=1",new String[]{"plan_product_id"}); Set<String> tags = new HashSet<String>(); for (Map<String, Object> blog : blogs) { Integer planId = MapUtils.getMapInt(blog, "plan_product_id"); if (planId == null) { continue; } String tag = String.format("plan:%d", planId); tags.add(tag); } return tags; }

Target:
public static Set<String> planTags() { String[] extraFields = {"plan_product_id"}; List<Map<String, Object>> blogs = WordPress.wpDB.getBlogsBy("dotcomFlag=1", extraFields); Set<String> tags = new HashSet<>(); for (Map<String, Object> blog : blogs) { int planId = MapUtils.getMapInt(blog, "plan_product_id"); if (planId == 0) { continue; } String tag = String.format("plan:%d", planId); tags.add(tag); } return tags; }
Source:
public List<OAuth2ServiceProvider> getProviders() { List<DocumentModel> providers = queryProviders(Collections.emptyMap(), 0); return providers.stream().map(provider -> buildProvider(provider)).collect(Collectors.toList()); }

Target:
public List<OAuth2ServiceProvider> getProviders() { List<DocumentModel> providers = queryProviders(Collections.emptyMap(), 0); return providers.stream().map(this::buildProvider).collect(Collectors.toList()); }
Source:
public List<Notification> notifications() throws IOException { final List<Notification> notifs = new LinkedList<Notification>(); final JsonResponse resp = this.github().entry().uri() .path("notifications") .back() .fetch() .as(JsonResponse.class); final JsonArray jsnnotifs = resp.json().readArray(); for (final JsonValue jsnnotif : jsnnotifs) { final JsonObject notifobj = (JsonObject) jsnnotif; final Notification notif = this.createNotification(notifobj); notifs.add(notif); } return notifs; }

Target:
public List<Notification> notifications() throws IOException { final List<Notification> list = new LinkedList<Notification>(); final JsonResponse resp = this.github().entry().uri() .path("notifications") .back() .fetch() .as(JsonResponse.class); final JsonArray array = resp.json().readArray(); for (final JsonValue value : array) { final JsonObject notif = (JsonObject) value; list.add(this.createNotification(notif)); } return list; }
Source:
public void validate() { if (enabled && getBuilder().transaction().transactionMode != null && getBuilder().transaction().transactionMode.equals(NON_TRANSACTIONAL)) throw log.invocationBatchingNeedsTransactionalCache(); if (enabled && getBuilder().transaction().recovery().enabled) throw log.invocationBatchingCannotBeRecovable(); }

Target:
public void validate() { if (enabled && getBuilder().transaction().transactionMode != null && getBuilder().transaction().transactionMode.equals(NON_TRANSACTIONAL)) throw log.invocationBatchingNeedsTransactionalCache(); if (enabled && getBuilder().transaction().recovery().enabled && !getBuilder().transaction().useSynchronization()) throw log.invocationBatchingCannotBeRecoverable(); }
Source:
public void onPreMerge(Repository repo, CodeReviewCommit commit, ProjectState destProject, NameKey destBranch, Id patchSetId) throws MergeValidationException { PatchSetApproval psa = approvalsUtil.getSubmitter(reviewDb.get(), commit.notes(), patchSetId); if (psa == null) { throw new MergeValidationException( CommitMergeStatus.SETTING_PARENT_PROJECT_ONLY_ALLOWED_BY_ADMIN); } final IdentifiedUser submitter = identifiedUserFactory.create(psa.getAccountId()); if (!submitter.getCapabilities().canAdministrateServer()) { throw new MergeValidationException(CommitMergeStatus.MISSING_DEPENDENCY); } }

Target:
public void onPreMerge(Repository repo, CodeReviewCommit commit, ProjectState destProject, NameKey destBranch, Id patchSetId) throws MergeValidationException { PatchSetApproval psa = approvalsUtil.getSubmitter(reviewDb.get(), commit.notes(), patchSetId); if (psa == null) { throw new MergeValidationException( CommitMergeStatus.NO_PATCH_SET); } final IdentifiedUser submitter = identifiedUserFactory.create(psa.getAccountId()); if (!submitter.getCapabilities().canAdministrateServer()) { throw new MergeValidationException(CommitMergeStatus.MISSING_DEPENDENCY); } }
Source:
private BulkActionView findBulkActionByQuery(final String luceneQuery, final User user) throws DotDataException, DotSecurityException { final String cleanedUpQuery = QueryUtil.removeQueryPrefix(luceneQuery); final String query = "{\n" + " \"query\" : { \n" + " \"query_string\" : {\n" + " \"query\" : \"" + cleanedUpQuery + "\"\n" + " } \n" + "\n" + " },\n" + " \"aggs\" : {\n" + " \"tag\" : {\n" + " \"terms\" : {\n" + " \"field\" : \"wfstep\",\n" + " \"size\" : 1000 \n" + " }\n" + " }\n" + " },\n" + "\t\"size\":0 \n" + "}"; final ESSearchResults results = this.contentletAPI.esSearch(query, false, user, false); Logger.debug(getClass(),"luceneQuery: "+ cleanedUpQuery); Logger.debug(getClass(),"esSearch: "+ query); return this.buildBulkActionView(results, user); }

Target:
private BulkActionView findBulkActionByQuery(final String luceneQuery, final User user) throws DotDataException, DotSecurityException { final String cleanedUpQuery = QueryUtil.removeQueryPrefix(luceneQuery); final String query = "{\n" + " \"query\" : { \n" + " \"query_string\" : {\n" + " \"query\" : \"%s\"\n" + " } \n" + "\n" + " },\n" + " \"aggs\" : {\n" + " \"tag\" : {\n" + " \"terms\" : {\n" + " \"field\" : \"wfstep\",\n" + " \"size\" : 1000 \n" + " }\n" + " }\n" + " },\n" + "\t\"size\":0 \n" + "}"; final String preparedQuery = String.format(query,cleanedUpQuery); final ESSearchResults results = this.contentletAPI.esSearch(preparedQuery, false, user, false); Logger.debug(getClass(),()-> "luceneQuery: "+ cleanedUpQuery); Logger.debug(getClass(),()-> "esSearch: "+ query); return this.buildBulkActionView(results, user); }
Source:
public void deleteAllFromRealm_outsideTransaction() { try { list.deleteAllFromRealm(); fail("deleteAllFromRealm should be called in a transaction."); } catch (IllegalStateException e) { assertThat(e.getMessage(), containsString("Must be in a write transaction ")); } }

Target:
public void deleteAllFromRealm_outsideTransaction() { thrown.expect(IllegalStateException.class); thrown.expectMessage("Must be in a write transaction "); list.deleteAllFromRealm(); }
Source:
public Map<File, IndexProcessingResults> processIndex(Set<File> replicaDirs, Set<StoreKey> filterSet, int parallelism, boolean detectDuplicatesAcrossKeys) { if (detectDuplicatesAcrossKeys && parallelism != 1) { throw new IllegalArgumentException("Parallelism cannot be > 1 because StoreKeyConverter is not thread safe"); } if (replicaDirs == null || replicaDirs.size() == 0) { return Collections.emptyMap(); } long currentTimeMs = time.milliseconds(); ConcurrentMap<File, IndexProcessingResults> resultsByReplica = new ConcurrentHashMap<>(); ExecutorService executorService = Executors.newFixedThreadPool(Math.min(parallelism, replicaDirs.size())); for (File replicaDir : replicaDirs) { executorService.submit(() -> { logger.info("Processing segment files for replica ", replicaDir); IndexProcessingResults results = null; try { results = processIndex(replicaDir, filterSet, currentTimeMs, detectDuplicatesAcrossKeys); } catch (Throwable e) { results = new IndexProcessingResults(e); } finally { resultsByReplica.put(replicaDir, results); } }); } return resultsByReplica; }

Target:
public Map<File, IndexProcessingResults> processIndex(Set<File> replicaDirs, Set<StoreKey> filterSet, int parallelism, boolean detectDuplicatesAcrossKeys) { if (detectDuplicatesAcrossKeys && parallelism != 1) { throw new IllegalArgumentException("Parallelism cannot be > 1 because StoreKeyConverter is not thread safe"); } if (replicaDirs == null || replicaDirs.size() == 0) { return Collections.emptyMap(); } long currentTimeMs = time.milliseconds(); ConcurrentMap<File, IndexProcessingResults> resultsByReplica = new ConcurrentHashMap<>(); ExecutorService executorService = Executors.newFixedThreadPool(Math.min(parallelism, replicaDirs.size())); List<Future<?>> taskFutures = new ArrayList<>(replicaDirs.size()); for (File replicaDir : replicaDirs) { Future<?> taskFuture = executorService.submit(() -> { logger.info("Processing segment files for replica ", replicaDir); IndexProcessingResults results = null; try { results = processIndex(replicaDir, filterSet, currentTimeMs, detectDuplicatesAcrossKeys); } catch (Throwable e) { results = new IndexProcessingResults(e); } finally { resultsByReplica.put(replicaDir, results); } }); taskFutures.add(taskFuture); } for (Future<?> taskFuture : taskFutures) { try { taskFuture.get(); } catch (Exception e) { throw new IllegalStateException("Future encountered error while waiting", e); } } return resultsByReplica; }
Source:
public void execute(Context context) throws SQLException { Map<String, PropertyRow> rows = context .prepareSelect("select id, prop_key, resource_id, text_value, created_at from properties") .list(row -> new PropertyRow( row.getLong(1), row.getString(2), row.getLong(3), row.getString(4), row.getLong(5))) .stream() .filter(row -> row.key().startsWith("sonar.webhooks")) .collect(toMap(PropertyRow::key, Function.identity())); if (!rows.isEmpty()) { final List<Long> toBeDeleted = new ArrayList<>(); toBeDeleted.addAll(migrateGlobalWebhooks(context, rows)); toBeDeleted.addAll(migrateProjectsWebhooks(context, rows, getProjectsUuids(context))); deleteFromProperties(context, toBeDeleted); } }

Target:
public void execute(Context context) throws SQLException { Map<String, PropertyRow> rows = context .prepareSelect("select id, prop_key, resource_id, text_value, created_at from properties where prop_key like 'sonar.webhooks%'") .list(row -> new PropertyRow( row.getLong(1), row.getString(2), row.getLong(3), row.getString(4), row.getLong(5))) .stream() .collect(toMap(PropertyRow::key, Function.identity())); if (!rows.isEmpty()) { migrateGlobalWebhooks(context, rows); migrateProjectsWebhooks(context, rows); context .prepareUpsert("delete from properties where prop_key like 'sonar.webhooks.global%' or prop_key like 'sonar.webhooks.project%'") .execute() .commit(); } }
Source:
private List<Object> scan(Collection<ByteArrayWrapper> list, Pattern matchPattern, int count, BigInteger cursor) { List<Object> returnList = new ArrayList<>(); int size = list.size(); BigInteger beforeCursor = new BigInteger("0"); int numElements = 0; int i = -1; for (ByteArrayWrapper key : list) { i++; if (beforeCursor.compareTo(cursor) < 0) { beforeCursor = beforeCursor.add(new BigInteger("1")); continue; } if (matchPattern != null) { if (matchPattern.matcher(key.toString()).matches()) { returnList.add(key); numElements++; } } else { returnList.add(key); numElements++; } if (numElements == count) { break; } } if (i >= size - 1) { returnList.add(0, String.valueOf(0)); } else { returnList.add(0, String.valueOf(i + 1)); } return returnList; }

Target:
private Pair<BigInteger, List<Object>> scan(Collection<ByteArrayWrapper> list, Pattern matchPattern, int count, BigInteger cursor) { List<Object> returnList = new ArrayList<>(); int size = list.size(); BigInteger beforeCursor = new BigInteger("0"); int numElements = 0; int i = -1; for (ByteArrayWrapper key : list) { i++; if (beforeCursor.compareTo(cursor) < 0) { beforeCursor = beforeCursor.add(new BigInteger("1")); continue; } if (matchPattern != null) { if (matchPattern.matcher(key.toString()).matches()) { returnList.add(key); numElements++; } } else { returnList.add(key); numElements++; } if (numElements == count) { break; } } Pair<BigInteger, List<Object>> scanResult; if (i >= size - 1) { scanResult = new ImmutablePair<>(new BigInteger("0"), returnList); } else { scanResult = new ImmutablePair<>(new BigInteger(String.valueOf(i + 1)), returnList); } return scanResult; }
Source:
public String toString() { StringBuilder sb = new StringBuilder(); sb.append("DimensionSelectorHavingSpec"); sb.append("{dimension='").append(dimension).append('\''); sb.append(", value='").append(value); if (getExtractionFn() != null) { sb.append("', extractionFunction='").append(getExtractionFn()); } sb.append("'}"); return sb.toString(); }

Target:
public String toString() { StringBuilder sb = new StringBuilder(); sb.append("DimensionSelectorHavingSpec"); sb.append("{dimension='").append(dimension).append('\''); sb.append(", value='").append(value); sb.append("', extractionFunction='").append(getExtractionFn()); sb.append("'}"); return sb.toString(); }
Source:
protected synchronized void handleMessageInternal(Message<?> message) throws Exception { String payloadString = message.getPayload().toString(); Class<?> type = (payloadString.contains("\"composite\":true")) ? CompositeModuleDeploymentRequest.class : ModuleDeploymentRequest.class; Object deserialized = this.mapper.readValue(payloadString, type); if (deserialized instanceof CompositeModuleDeploymentRequest) { handleCompositeModuleDeployment((CompositeModuleDeploymentRequest) deserialized, message); } else { handleDeploymentRequest((ModuleDeploymentRequest) deserialized, message); } }

Target:
protected synchronized void handleMessageInternal(Message<?> message) throws Exception { String payloadString = message.getPayload().toString(); ModuleDeploymentRequest deserialized = this.mapper.readValue(payloadString, ModuleDeploymentRequest.class); if (deserialized instanceof CompositeModuleDeploymentRequest) { handleCompositeModuleDeployment((CompositeModuleDeploymentRequest) deserialized, message); } else { handleDeploymentRequest(deserialized, message); } }
Source:
private void share() { lumberYard.save() .doOnError(new Action1<Throwable>() { @Override public void call(Throwable throwable) { Toast.makeText(getContext(), "Couldn't save the logs for sharing.", Toast.LENGTH_SHORT).show(); } }) .subscribe(new Action1<File>() { @Override public void call(File file) { Intent sendIntent = new Intent(Intent.ACTION_SEND); sendIntent.setType("text/plain"); sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file)); Intents.maybeStartActivity(getContext(), sendIntent); } }); }

Target:
private void share() { lumberYard.save() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Subscriber<File>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { Toast.makeText(getContext(), "Couldn't save the logs for sharing.", Toast.LENGTH_SHORT) .show(); } @Override public void onNext(File file) { Intent sendIntent = new Intent(Intent.ACTION_SEND); sendIntent.setType("text/plain"); sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file)); Intents.maybeStartActivity(getContext(), sendIntent); } }); }
Source:
public boolean clearContainerBlockContents(BlockVector3 position) { checkNotNull(position); BlockEntity tile = getWorld().getBlockEntity(FabricAdapter.toBlockPos(position)); if ((tile instanceof Inventory)) { Inventory inv = (Inventory) tile; int size = inv.getInvSize(); for (int i = 0; i < size; i++) { inv.setInvStack(i, ItemStack.EMPTY); } return true; } return false; }

Target:
public boolean clearContainerBlockContents(BlockVector3 position) { checkNotNull(position); BlockEntity tile = getWorld().getBlockEntity(FabricAdapter.toBlockPos(position)); if ((tile instanceof Clearable)) { ((Clearable) tile).clear(); return true; } return false; }
Source:
public void setStandby(final boolean onOrOff, final String... deviceNames) { neoHubConnector.sendMessage("{\"FROST_" + (onOrOff ? "ON" : "OFF") + "\":[\"" + StringUtils.join(deviceNames, "\",\"") + "\"]}", null); }

Target:
public void setStandby(final boolean onOrOff, final String... deviceNames) { neoHubConnector.sendMessage( String.format("{\"FROST_%s\":[\"%s\"]}", onOrOff ? "ON" : "OFF", StringUtils.join(deviceNames, "\",\"")), null); }
Source:
public boolean shouldPull(ImageData image) { log.trace("Should pull image with tags: {}", Arrays.asList(image.getRepoTags())); return true; }

Target:
public boolean shouldPull(ImageData image) { log.trace("Unconditionally pulling an image with tags: {}", Arrays.asList(image.getRepoTags())); return true; }
Source:
public void run(String[] args) throws Exception { try { options = parser.parse(args); } catch (OptionException e) { exitWithError(LOGGER, e.getMessage() + ". Use --help to get overview of the help options."); return; } if (options.has(helpSpec)) { parser.printHelpOn(System.out); System.exit(0); } provisioner.props.init(getPropertiesFile()); if (options.has(gitSpec)) { String git = options.valueOf(gitSpec); provisioner.props.forceGit(git); } provisioner.init(); if (options.has(restartSpec)) { boolean enterpriseEnabled = options.valueOf(enterpriseEnabledSpec); provisioner.restart(enterpriseEnabled); provisioner.startAgents(); } else if (options.has(killSpec)) { provisioner.killAgents(); } else if (options.has(downloadSpec)) { String dir = options.valueOf(downloadSpec); provisioner.download(dir); } else if (options.has(cleanSpec)) { provisioner.clean(); } else if (options.has(terminateSpec)) { provisioner.terminate(); } else if (options.has(scaleSpec)) { int size = options.valueOf(scaleSpec); boolean enterpriseEnabled = options.valueOf(enterpriseEnabledSpec); provisioner.scale(size, enterpriseEnabled); } else if (options.has(listAgentsSpec)) { provisioner.listAgents(); } else { parser.printHelpOn(System.out); } provisioner.shutdown(); }

Target:
public void run(String[] args) throws Exception { try { options = parser.parse(args); } catch (OptionException e) { exitWithError(LOGGER, e.getMessage() + ". Use --help to get overview of the help options."); return; } if (options.has(helpSpec)) { parser.printHelpOn(System.out); System.exit(0); } provisioner.props.init(getPropertiesFile()); if (options.has(gitSpec)) { String git = options.valueOf(gitSpec); provisioner.props.forceGit(git); } try { provisioner.init(); if (options.has(restartSpec)) { boolean enterpriseEnabled = options.valueOf(enterpriseEnabledSpec); provisioner.restart(enterpriseEnabled); provisioner.startAgents(); } else if (options.has(killSpec)) { provisioner.killAgents(); } else if (options.has(downloadSpec)) { String dir = options.valueOf(downloadSpec); provisioner.download(dir); } else if (options.has(cleanSpec)) { provisioner.clean(); } else if (options.has(terminateSpec)) { provisioner.terminate(); } else if (options.has(scaleSpec)) { int size = options.valueOf(scaleSpec); boolean enterpriseEnabled = options.valueOf(enterpriseEnabledSpec); provisioner.scale(size, enterpriseEnabled); } else if (options.has(listAgentsSpec)) { provisioner.listAgents(); } else { parser.printHelpOn(System.out); } } finally { provisioner.shutdown(); } }
Source:
private boolean isSessionScopeMetric(MetricNameDto metricNameDto) { return (metricNameDto.getOrigin().equals(MetricNameDto.Origin.SESSION_SCOPE_TG) || metricNameDto.getOrigin().equals(MetricNameDto.Origin.SESSION_SCOPE_MONITORING)); }

Target:
private boolean isSessionScopeMetric(MetricNameDto metricNameDto) { return metricNameDto.getOrigin() == MetricNameDto.Origin.SESSION_SCOPE_TG; }
Source:
private List<StatementGroup> getStatementGroups(JSONArray jsonStatements, EntityIdValue entityIdValue) throws JSONException { List<StatementGroup> result; List<Statement> statementsFromJson = new ArrayList<Statement>( jsonStatements.length()); for (int i = 0; i < jsonStatements.length(); i++) { JSONObject statementJson = jsonStatements.getJSONObject(i); try { Statement statement = this.getStatement(statementJson, entityIdValue); statementsFromJson.add(statement); } catch( Exception e){ logger.debug("Encountered an exception during statement parsing:\n" + e.getMessage() + "\nIn statement\n" + statementJson.toString(2)); } } result = this.statementGroupBuilder .buildFromStatementList(statementsFromJson); return result; }

Target:
private List<StatementGroup> getStatementGroups(JSONArray jsonStatements, EntityIdValue entityIdValue) throws JSONException { List<StatementGroup> result; List<Statement> statementsFromJson = new ArrayList<Statement>( jsonStatements.length()); for (int i = 0; i < jsonStatements.length(); i++) { JSONObject statementJson = jsonStatements.getJSONObject(i); try { Statement statement = this.getStatement(statementJson, entityIdValue); statementsFromJson.add(statement); } catch( IllegalArgumentException | JSONException e){ logger.debug("Encountered an exception during statement parsing:\n" + e.getMessage() + "\nIn statement\n" + statementJson.toString(2)); } } result = this.statementGroupBuilder .buildFromStatementList(statementsFromJson); return result; }