auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private <T> CloseableIterator<T> decorateShutdownTimeout( ScheduledExecutorService exec, CloseableIterator<T> delegateIterator ) { final Closer closer = Closer.create(); closer.register(delegateIterator); closer.register(exec::shutdownNow); final CloseableIterator<T> wrappingIterator = new CloseableIterator<T>() { volatile boolean closed; @Override public boolean hasNext() { return !closed && delegateIterator.hasNext(); } @Override public T next() { if (!hasNext()) { throw new NoSuchElementException(); } return delegateIterator.next(); } @Override public void close() throws IOException { closed = true; closer.close(); } }; exec.schedule( () -> { LOG.info("Closing delegate inputSource."); try { wrappingIterator.close(); } catch (IOException e) { LOG.warn(e, "Failed to close delegate inputSource, ignoring."); } }, shutoffTime.getMillis() - System.currentTimeMillis(), TimeUnit.MILLISECONDS ); return wrappingIterator; }

Target:
private <T> CloseableIterator<T> decorateShutdownTimeout( ScheduledExecutorService exec, CloseableIterator<T> delegateIterator ) { final Closer closer = Closer.create(); closer.register(delegateIterator); closer.register(exec::shutdownNow); final CloseableIterator<T> wrappingIterator = new CloseableIterator<T>() { volatile boolean closed; T next = null; @Override public boolean hasNext() { if (next != null) { return true; } if (!closed && delegateIterator.hasNext()) { next = delegateIterator.next(); return true; } else { return false; } } @Override public T next() { if (next != null) { final T returnValue = next; next = null; return returnValue; } else { throw new NoSuchElementException(); } } @Override public void close() throws IOException { closed = true; closer.close(); } }; exec.schedule( () -> { LOG.info("Closing delegate inputSource."); try { wrappingIterator.close(); } catch (IOException e) { LOG.warn(e, "Failed to close delegate inputSource, ignoring."); } }, shutoffTime.getMillis() - System.currentTimeMillis(), TimeUnit.MILLISECONDS ); return wrappingIterator; }
Source:
public void execute() throws MojoExecutionException { if (!outputDirectory.exists()) { outputDirectory.mkdirs(); } List<String> list = new ArrayList<>(); for (File jsonFile : cucumberFiles(cucumberOutput)) { list.add(jsonFile.getAbsolutePath()); } if (list.isEmpty()) { getLog().warn(cucumberOutput.getAbsolutePath() + " does not exist."); return; } try { Configuration configuration = new Configuration(outputDirectory,projectName); configuration.setBuildNumber(buildNumber); configuration.setStatusFlags(skippedFails,pendingFails,undefinedFails,missingFails); configuration.setParallelTesting(parallelTesting); configuration.setRunWithJenkins(false); ReportBuilder reportBuilder = new ReportBuilder(list,configuration); getLog().info("About to generate Cucumber report."); reportBuilder.generateReports(); if (checkBuildResult) { boolean buildResult = reportBuilder.hasBuildPassed(); if (!buildResult) { throw new MojoExecutionException("BUILD FAILED - Check Report For Details"); } } } catch (Exception e) { throw new MojoExecutionException("Error Found:", e); } }

Target:
public void execute() throws MojoExecutionException { if (!outputDirectory.exists()) { outputDirectory.mkdirs(); } List<String> list = new ArrayList<>(); for (File jsonFile : cucumberFiles(cucumberOutput)) { list.add(jsonFile.getAbsolutePath()); } if (list.isEmpty()) { getLog().warn(cucumberOutput.getAbsolutePath() + " does not exist."); return; } try { Configuration configuration = new Configuration(outputDirectory,projectName); configuration.setBuildNumber(buildNumber); configuration.setStatusFlags(skippedFails,pendingFails,undefinedFails,missingFails); configuration.setParallelTesting(parallelTesting); ReportBuilder reportBuilder = new ReportBuilder(list,configuration); getLog().info("About to generate Cucumber report."); reportBuilder.generateReports(); if (checkBuildResult) { boolean buildResult = reportBuilder.hasBuildPassed(); if (!buildResult) { throw new MojoExecutionException("BUILD FAILED - Check Report For Details"); } } } catch (Exception e) { throw new MojoExecutionException("Error Found:", e); } }
Source:
protected void changeThingType(ThingTypeUID thingTypeUID, Configuration configuration) { if (this.callback != null) { this.callback.changeThingType(getThing(), thingTypeUID, configuration); } else { throw new IllegalStateException("Could change thing type because callback is missing"); } }

Target:
protected void changeThingType(ThingTypeUID thingTypeUID, Configuration configuration) { if (this.callback != null) { this.callback.changeThingType(getThing(), thingTypeUID, configuration); } else { throw new IllegalStateException("Could not change thing type because callback is missing"); } }
Source:
public void testNullBinding() throws Exception { Map<String, Object> args = Collections.singletonMap("foo", null); new MapArguments(args, ctx).find("foo").get().apply(3, stmt, null); verify(stmt).setNull(3, ((NullArgument)new Arguments().getUntypedNullArgument()).getSqlType()); }

Target:
public void testNullBinding() throws Exception { Map<String, Object> args = Collections.singletonMap("foo", null); new MapArguments(args, ctx).find("foo").get().apply(3, stmt, null); verify(stmt).setNull(3, Types.OTHER); }
Source:
public boolean isExpired() { if (mIsExtendedLifeTimeToken) { return TokenCacheItem.isTokenExpired(getExtendedExpiresOn()); } else { return TokenCacheItem.isTokenExpired(getExpiresOn()); } }

Target:
public boolean isExpired() { if (mIsExtendedLifeTimeToken) { return TokenCacheItem.isTokenExpired(getExtendedExpiresOn()); } return TokenCacheItem.isTokenExpired(getExpiresOn()); }
Source:
private static IBlockState asBlockState(crafttweaker.api.block.IBlockState blockstate) { Object internal = blockstate.getInternal(); if (!(internal instanceof IBlockState)) { CraftTweakerAPI.logError("Not a valid blockstate: " + blockstate); } return (IBlockState) internal; }

Target:
private static IBlockState asBlockState(crafttweaker.api.block.IBlockState blockstate) { Object internal = blockstate.getInternal(); if (!(internal instanceof IBlockState)) { CraftTweakerAPI.logError("Not a valid blockstate: " + blockstate); return null; } return (IBlockState) internal; }
Source:
public void writeConfiguration(String host) throws IOException { Lock readLock = configLock.readLock(); try { readLock.lock(); Response r = ClientBuilder.newClient() .target(host) .path("api") .path("v1") .path("configuration") .queryParam("reindex", true) .request() .put(Entity.xml(configuration.getXMLRepresentationAsString())); if (r.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) { throw new IOException(r.toString()); } } finally { readLock.unlock(); } }

Target:
public void writeConfiguration(String host) throws IOException { String configXML; try { configLock.readLock().lock(); configXML = configuration.getXMLRepresentationAsString(); } finally { configLock.readLock().unlock(); } Response r = ClientBuilder.newClient() .target(host) .path("api") .path("v1") .path("configuration") .queryParam("reindex", true) .request() .put(Entity.xml(configXML)); if (r.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) { throw new IOException(r.toString()); } }
Source:
private ReflectionMappers(ReflectionMappers that) { columnNameMatchers.addAll(that.columnNameMatchers); strictMatching = that.strictMatching; }

Target:
private ReflectionMappers(ReflectionMappers that) { columnNameMatchers = new ArrayList<>(that.columnNameMatchers); strictMatching = that.strictMatching; }
Source:
public void onAssignmentChange(List<DatastreamTask> tasks) { HashSet<DatastreamTask> toCancel = new HashSet<>(_runningTasks.keySet()); toCancel.removeAll(tasks); for (DatastreamTask task : toCancel) { KafkaConnectorTask connectorTask = _runningTasks.remove(task); connectorTask.stop(); } for (DatastreamTask task : tasks) { if (_runningTasks.containsKey(task)) { continue; } LOG.info("creating task for {}.", task); KafkaConnectorTask connectorTask = new KafkaConnectorTask(task); _runningTasks.put(task, connectorTask); _executor.submit(connectorTask); } }

Target:
public void onAssignmentChange(List<DatastreamTask> tasks) { HashSet<DatastreamTask> toCancel = new HashSet<>(_runningTasks.keySet()); toCancel.removeAll(tasks); for (DatastreamTask task : toCancel) { KafkaConnectorTask connectorTask = _runningTasks.remove(task); connectorTask.stop(); } for (DatastreamTask task : tasks) { if (_runningTasks.containsKey(task)) { continue; } LOG.info("creating task for {}.", task); KafkaConnectorTask connectorTask = new KafkaConnectorTask(task, 100); _runningTasks.put(task, connectorTask); _executor.submit(connectorTask); } }
Source:
public boolean equals(Object column) { if (column == null) { return false; } else if (column instanceof Column) { Column col = (Column)column; return (getType() == col.getType()); } else { return false; } }

Target:
public boolean equals(Object column) { if (!(column instanceof Column)) { return false; } Column col = (Column)column; return (getType() == col.getType()); }
Source:
public void break_outside_loop() { cfgForBlock("" + " break 2;"); }

Target:
public void break_outside_loop() { cfgForBlock("break 2;"); }
Source:
public static long toMillisFromJavaEpoch(int year, int month, int day, TimeZone currentTimeZone) { int daysFromMinDay = countDaysFromMinDay(year, month, day); long millisFromMinDay = daysFromMinDay * UniversalDate.MILLIS_IN_DAY; int timezoneOffsetFromGMT = currentTimeZone.getOffset(millisFromMinDay); return millisFromMinDay + MIN_MILLIS_FROM_JAVA_EPOCH - timezoneOffsetFromGMT; }

Target:
public static long toMillisFromJavaEpoch(int year, int month, int day, TimeZone currentTimeZone) { int daysFromMinDay = countDaysFromMinDay(year, month, day); long millisFromMinDay = daysFromMinDay * UniversalDate.MILLIS_IN_DAY; int timezoneOffsetFromUTC = currentTimeZone.getOffset(millisFromMinDay); long millisNormalizedToUTC = millisFromMinDay - timezoneOffsetFromUTC; return millisNormalizedToUTC + MIN_MILLIS_FROM_JAVA_EPOCH; }
Source:
public boolean removeAll(Collection<?> c) { boolean changed = false; for (Object name : c) changed |= remove(name); return changed; }

Target:
public boolean removeAll(Collection<?> c) { boolean changed = false; for (Object element : c) changed |= remove(element); return changed; }
Source:
private BigInteger evaluateExpression(IDMContext ctx, String expression) throws Throwable { final IExpressionDMContext expressionDMC = SyncUtil.createExpression(ctx, expression); final FormattedValueDMContext formattedValueDMC = SyncUtil.getFormattedValue(fExpressionService, expressionDMC, IFormattedValues.DECIMAL_FORMAT); Query<FormattedValueDMData> query = new Query<IFormattedValues.FormattedValueDMData>() { @Override protected void execute(DataRequestMonitor<FormattedValueDMData> rm) { fExpressionService.getFormattedExpressionValue(formattedValueDMC, rm); } }; fExpressionService.getExecutor().submit(query); FormattedValueDMData result = query.get(); return new BigInteger(result.getFormattedValue()); }

Target:
private BigInteger evaluateExpression(IDMContext ctx, String expression) throws Throwable { final IExpressionDMContext expressionDMC = SyncUtil.createExpression(ctx, expression); final FormattedValueDMContext formattedValueDMC = SyncUtil.getFormattedValue(fExpressionService, expressionDMC, IFormattedValues.DECIMAL_FORMAT); Query<FormattedValueDMData> query = new Query<FormattedValueDMData>() { @Override protected void execute(DataRequestMonitor<FormattedValueDMData> rm) { fExpressionService.getFormattedExpressionValue(formattedValueDMC, rm); } }; fExpressionService.getExecutor().submit(query); FormattedValueDMData result = query.get(TestsPlugin.massageTimeout(2000), TimeUnit.MILLISECONDS); return new BigInteger(result.getFormattedValue()); }
Source:
public synchronized Optional<ILauncher> getLauncher() { return model.getLauncher().map(launcher -> launcher); }

Target:
public synchronized Optional<? extends ILauncher> getLauncher() { return model.getLauncher(); }
Source:
private static boolean isUnaryValid(CallExpression callExpression) { return callExpression.getChildren().size() == 1 && callExpression.getChildren().get(0) instanceof FieldReferenceExpression; }

Target:
private static boolean isUnaryValid(CallExpression callExpression) { return callExpression.getChildren().size() == 1 && isRef(callExpression.getChildren().get(0)); }
Source:
public String doPost(String api, HashMap<String, String> mapHeaders, String body, HashMap<String, String> queries) { try { HttpHeaders headers = new HttpHeaders(); for (String i : mapHeaders.keySet()) { headers.add(i, mapHeaders.get(i).toString()); } HttpEntity<String> request; if (body != null) { request = new HttpEntity<>(body, headers); } else { request = new HttpEntity<String>(headers); } RestTemplate rest = new RestTemplate(); ResponseEntity<String> response; if (queries != null) { response = rest.postForEntity(api, request, String.class, queries); } else { response = rest.postForEntity(api, request, String.class); } return response.getBody(); } catch (Exception e) { System.out.println("## Error :: "+e.getMessage()); return null; } }

Target:
public String doPost(String api, HashMap<String, String> mapHeaders, String body, HashMap<String, String> queries) { try { HttpHeaders headers = new HttpHeaders(); for (String i : mapHeaders.keySet()) { headers.add(i, mapHeaders.get(i).toString()); } HttpEntity<String> request; if (body != null) { request = new HttpEntity<>(body, headers); } else { request = new HttpEntity<String>(headers); } RestTemplate rest = new RestTemplate(); ResponseEntity<String> response; if (queries != null) { response = rest.postForEntity(api, request, String.class, queries); } else { response = rest.postForEntity(api, request, String.class); } return response.getBody(); } catch (Exception e) { logger.error("Error sending request : ", e); return null; } }
Source:
protected void printCalendar(Calendar value, CSVPrinter printer) throws IOException { if (value != null) { printer.print(format.format(ZonedDateTime.ofInstant(value.toInstant(), value.getTimeZone().toZoneId()))); } else { printer.print(null); } }

Target:
protected void printCalendar(Calendar value, CSVPrinter printer) throws IOException { if (value != null) { printer.print(((GregorianCalendar) value).toZonedDateTime()); } else { printer.print(null); } }
Source:
public static void main(String[] args) throws Exception { PatentReaderJobParameters params = new PatentReaderJobParameters(); JCommander jcommander = new JCommander(params); jcommander.parse(args); SparkSession session = SparkSessionFactory.withConfAndKryo(new SparkConf()); try { JavaSparkContext sc = JavaSparkContext.fromSparkContext(session.sparkContext()); HdfsUtils.remove(sc.hadoopConfiguration(), params.outputPath); HdfsUtils.remove(sc.hadoopConfiguration(), params.outputReportPath); JavaRDD<ImportedPatent> results = session.read() .option("sep", "\t") .option("header","true") .csv(params.inputTsvLocation) .toJavaRDD() .map(PatentReaderJob::buildEntry); storeInOutput(results, generateReportEntries(sc, results), params.outputPath, params.outputReportPath); } finally { if (Objects.nonNull(session)) { session.stop(); } } }

Target:
public static void main(String[] args) throws Exception { PatentReaderJobParameters params = new PatentReaderJobParameters(); JCommander jcommander = new JCommander(params); jcommander.parse(args); try (SparkSession session = SparkSessionFactory.withConfAndKryo(new SparkConf())) { JavaSparkContext sc = JavaSparkContext.fromSparkContext(session.sparkContext()); HdfsUtils.remove(sc.hadoopConfiguration(), params.outputPath); HdfsUtils.remove(sc.hadoopConfiguration(), params.outputReportPath); JavaRDD<ImportedPatent> results = session.read() .option("sep", "\t") .option("header","true") .csv(params.inputTsvLocation) .toJavaRDD() .map(PatentReaderJob::buildEntry); storeInOutput(results, generateReportEntries(sc, results), params.outputPath, params.outputReportPath); } }
Source:
public Resource parse() throws InvalidStructureException, IOException, XmlPullParserException { checkNode("resource"); String id = parser.getAttributeValue(null, "id"); int version = parseInt(parser.getAttributeValue(null, "version")); String descriptor = parser.getAttributeValue(null, "descriptor"); String lazy = parser.getAttributeValue(null, "lazy"); Vector<ResourceLocation> locations = new Vector<>(); while (nextTagInBlock("resource")) { String sAuthority = parser.getAttributeValue(null, "authority"); String location = parser.nextText(); int authority = Resource.RESOURCE_AUTHORITY_REMOTE; if (sAuthority.toLowerCase().equals("local")) { authority = Resource.RESOURCE_AUTHORITY_LOCAL; } else if (sAuthority.toLowerCase().equals("remote")) { authority = Resource.RESOURCE_AUTHORITY_REMOTE; } if (authority >= maximumAuthority) { locations.addElement(new ResourceLocation(authority, location)); } } return new Resource(version, id, locations, descriptor, lazy != null && lazy.contentEquals("true")); }

Target:
public Resource parse() throws InvalidStructureException, IOException, XmlPullParserException { checkNode("resource"); String id = parser.getAttributeValue(null, "id"); int version = parseInt(parser.getAttributeValue(null, "version")); String descriptor = parser.getAttributeValue(null, "descriptor"); String lazy = parser.getAttributeValue(null, "lazy"); Vector<ResourceLocation> locations = new Vector<>(); while (nextTagInBlock("resource")) { String sAuthority = parser.getAttributeValue(null, "authority"); String location = parser.nextText(); int authority = Resource.RESOURCE_AUTHORITY_REMOTE; if (sAuthority.toLowerCase().equals("local")) { authority = Resource.RESOURCE_AUTHORITY_LOCAL; } else if (sAuthority.toLowerCase().equals("remote")) { authority = Resource.RESOURCE_AUTHORITY_REMOTE; } if (authority >= maximumAuthority) { locations.addElement(new ResourceLocation(authority, location)); } } return new Resource(version, id, locations, descriptor, lazy == null ? LAZY_VAL_FALSE : lazy); }
Source:
public void testVariablesAvailableInView() throws CoreException, IOException { new ProjectExplorer().getProject("nodejs-ex").getProjectItem("server.js").open(); new WaitUntil(new EditorWithTitleIsActive("server.js")); TextEditor editor = new TextEditor("server.js"); setLineBreakpoint(editor, BREAKPOINT_LINE); triggerDebugSession(); TreeItem var_db = getVariable(VAR_db); TreeItem var_initDb = getVariable(VAR_initDb); TreeItem var_require = getVariable(VAR_require); assertTrue("Variable '" + VAR_db + "' not found in view!", var_db != null); assertThat(var_db.getCell(0), is(VAR_db)); assertThat(var_db.getCell(1), containsString(VAR_VALUE_db)); assertTrue("Variable '" + VAR_initDb + "' not found in view!", var_initDb != null); assertThat(var_initDb.getCell(0), is(VAR_initDb)); assertThat(var_initDb.getCell(1), containsString(VAR_VALUE_initDb)); assertTrue("Variable '" + VAR_require + "' not found in view!", var_require != null); assertThat(var_require.getCell(0), is(VAR_require)); assertThat(var_require.getCell(1), containsString(VAR_VALUE_require)); }

Target:
public void testVariablesAvailableInView() throws CoreException, IOException { ProjectExplorer pe = new ProjectExplorer(); pe.open(); pe.getProject(OpenShiftResources.NODEJS_GIT_NAME).getProjectItem("server.js").open(); new WaitUntil(new EditorWithTitleIsActive("server.js")); TextEditor editor = new TextEditor("server.js"); setLineBreakpoint(editor, BREAKPOINT_LINE); triggerDebugSession(); TreeItem var_db = getVariable(VAR_db); TreeItem var_initDb = getVariable(VAR_initDb); TreeItem var_require = getVariable(VAR_require); assertTrue("Variable '" + VAR_db + "' not found in view!", var_db != null); assertThat(var_db.getCell(0), is(VAR_db)); assertThat(var_db.getCell(1), containsString(VAR_VALUE_db)); assertTrue("Variable '" + VAR_initDb + "' not found in view!", var_initDb != null); assertThat(var_initDb.getCell(0), is(VAR_initDb)); assertThat(var_initDb.getCell(1), containsString(VAR_VALUE_initDb)); assertTrue("Variable '" + VAR_require + "' not found in view!", var_require != null); assertThat(var_require.getCell(0), is(VAR_require)); assertThat(var_require.getCell(1), containsString(VAR_VALUE_require)); }
Source:
public void should_mark_regular_node_down_when_no_more_connections() { simulacronRegularNode.rejectConnections(0, RejectScope.UNBIND); simulacronRegularNode.closeConnections(CloseType.DISCONNECT); ConditionChecker.checkThat(() -> metadataRegularNode.getState() == NodeState.DOWN) .as("Node going down") .before(10, TimeUnit.SECONDS) .becomesTrue(); assertThat(metadataRegularNode).hasState(NodeState.DOWN).hasOpenConnections(0).isReconnecting(); expect(NodeStateEvent.changed(NodeState.UP, NodeState.DOWN, metadataRegularNode)); }

Target:
public void should_mark_regular_node_down_when_no_more_connections() { simulacronRegularNode.stop(); ConditionChecker.checkThat( () -> assertThat(metadataRegularNode).isDown().hasOpenConnections(0).isReconnecting()) .as("Node going down") .before(10, TimeUnit.SECONDS) .becomesTrue(); expect(NodeStateEvent.changed(NodeState.UP, NodeState.DOWN, metadataRegularNode)); }
Source:
public static void main(final String[] args) throws Exception { final UnsafeBuffer buffer = new UnsafeBuffer(ByteBuffer.allocateDirect(512)); final String channel = new String("udp://localhost:40123"); final int streamId = 10; System.out.println("Publishing to " + channel + " on stream Id " + streamId); final Aeron.Context ctx = new Aeron.Context(); Publication publication = null; Aeron aeron = null; try { aeron = Aeron.connect(ctx); publication = aeron.addPublication(channel, streamId); final String message = "Hello World! "; buffer.putBytes(0, message.getBytes()); final long result = publication.offer(buffer, 0, message.getBytes().length); if (result < 0L) { if (result == Publication.BACK_PRESSURE) { System.out.println(" Offer failed due to back pressure"); } else if (result == Publication.NOT_CONNECTED) { System.out.println(" Offer failed because publisher is not yet connected to subscriber"); } else { System.out.println(" Offer failed due to unknown reason"); } } else { System.out.println(" yay !!"); } System.out.println("Done sending."); } finally { publication.close(); aeron.close(); } }

Target:
public static void main(final String[] args) throws Exception { final UnsafeBuffer buffer = new UnsafeBuffer(ByteBuffer.allocateDirect(512)); final String channel = "udp://localhost:40123"; final int streamId = 10; System.out.println("Publishing to " + channel + " on stream Id " + streamId); final Aeron.Context ctx = new Aeron.Context(); try (final Aeron aeron = Aeron.connect(ctx); final Publication publication = aeron.addPublication(channel, streamId);) { final String message = "Hello World! "; buffer.putBytes(0, message.getBytes()); final long result = publication.offer(buffer, 0, message.getBytes().length); if (result < 0L) { if (result == Publication.BACK_PRESSURE) { System.out.println(" Offer failed due to back pressure"); } else if (result == Publication.NOT_CONNECTED) { System.out.println(" Offer failed because publisher is not yet connected to subscriber"); } else { System.out.println(" Offer failed due to unknown reason"); } } else { System.out.println(" yay !!"); } System.out.println("Done sending."); } finally { ctx.close(); } }
Source:
protected void run() throws Exception { ResetCommand command = new Git(db).reset(); command.setRef(commit); ResetType mode = null; if(soft) mode = ResetType.SOFT; else if(mixed) mode = ResetType.MIXED; else if(hard) mode = ResetType.HARD; if (mode != null) command.setMode(mode); command.call(); }

Target:
protected void run() throws Exception { ResetCommand command = new Git(db).reset(); command.setRef(commit); ResetType mode = null; if (soft) mode = selectMode(mode, ResetType.SOFT); if (mixed) mode = selectMode(mode, ResetType.MIXED); if (hard) mode = selectMode(mode, ResetType.HARD); if (mode == null) throw die("no reset mode set"); command.setMode(mode); command.call(); }
Source:
public String toString() { return "NationalIdentityNumber{" + "value='" + value + '\'' + '}'; }

Target:
public String toString() { return "NationalIdentityNumber{" + value + "}"; }
Source:
public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { finish(); } else if(item.getTitle().equals(getString(R.string.comment_reply_send))) { String subreddit = subredditEdit.getText().toString(); String postTitle = titleEdit.getText().toString(); String text = textEdit.getText().toString(); if (subreddit.isEmpty()) { Toast.makeText(this, "Specify subreddit", Toast.LENGTH_SHORT).show(); subredditEdit.requestFocus(); } else if (postTitle.isEmpty()) { Toast.makeText(this, "Title cannot be empty", Toast.LENGTH_SHORT).show(); titleEdit.requestFocus(); } else if ("URL".equals(textEdit.getHint().toString()) && text.isEmpty()) { Toast.makeText(this, "URL cannot be empty", Toast.LENGTH_SHORT).show(); textEdit.requestFocus(); } else { final Intent captchaIntent = new Intent(this, CaptchaActivity.class); captchaIntent.putExtra("username", (String)usernameSpinner.getSelectedItem()); startActivityForResult(captchaIntent, REQUEST_CAPTCHA); } } else if(item.getTitle().equals(getString(R.string.comment_reply_preview))) { MarkdownPreviewDialog.newInstance(textEdit.getText().toString()).show(getSupportFragmentManager(), null); } return true; }

Target:
public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { finish(); } else if(item.getTitle().equals(getString(R.string.comment_reply_send))) { String subreddit = subredditEdit.getText().toString(); String postTitle = titleEdit.getText().toString(); String text = textEdit.getText().toString(); if (subreddit.isEmpty()) { Toast.makeText(this, R.string.submit_post_specify_subreddit, Toast.LENGTH_SHORT).show(); subredditEdit.requestFocus(); } else if (postTitle.isEmpty()) { Toast.makeText(this, R.string.submit_post_title_empty, Toast.LENGTH_SHORT).show(); titleEdit.requestFocus(); } else if (getString(R.string.submit_post_url_hint).equals(textEdit.getHint().toString()) && text.isEmpty()) { Toast.makeText(this, R.string.submit_post_url_empty, Toast.LENGTH_SHORT).show(); textEdit.requestFocus(); } else { final Intent captchaIntent = new Intent(this, CaptchaActivity.class); captchaIntent.putExtra("username", (String)usernameSpinner.getSelectedItem()); startActivityForResult(captchaIntent, REQUEST_CAPTCHA); } } else if(item.getTitle().equals(getString(R.string.comment_reply_preview))) { MarkdownPreviewDialog.newInstance(textEdit.getText().toString()).show(getSupportFragmentManager(), null); } return true; }
Source:
private Method findMethod(Class<?> testClass, String methodName) { if (methodName.contains("[") && methodName.endsWith("]")) { return findMethod(testClass, methodName.substring(0, methodName.indexOf("["))); } List<Method> methods = methodsCache.computeIfAbsent(testClass, clazz -> findMethods(clazz, m -> true)).stream() .filter(where(Method::getName, isEqual(methodName))) .collect(toList()); if (methods.isEmpty()) { return null; } if (methods.size() == 1) { return methods.get(0); } methods = methods.stream().filter(ModifierSupport::isPublic).collect(toList()); if (methods.size() == 1) { return methods.get(0); } return null; }

Target:
private Method findMethod(Class<?> testClass, String methodName) { List<Method> methods = methodsCache.computeIfAbsent(testClass, clazz -> findMethods(clazz, m -> true)).stream() .filter(where(Method::getName, isEqual(methodName))) .collect(toList()); if (methods.isEmpty()) { return null; } if (methods.size() == 1) { return methods.get(0); } methods = methods.stream().filter(ModifierSupport::isPublic).collect(toList()); if (methods.size() == 1) { return methods.get(0); } return null; }
Source:
public ParseObject(String theClassName) { String objectIdForPointer = isCreatingPointerForObjectId.get(); if (theClassName == null) { throw new IllegalArgumentException( "You must specify a Parse class name when creating a new ParseObject."); } if (AUTO_CLASS_NAME.equals(theClassName)) { theClassName = getSubclassingController().getClassName(getClass()); } if (!getSubclassingController().isTypeValid(theClassName, getClass())) { throw new IllegalArgumentException( "You must create this type of ParseObject using ParseObject.create() or the proper subclass."); } operationSetQueue = new LinkedList<>(); operationSetQueue.add(new ParseOperationSet()); estimatedData = new HashMap<>(); State.Init<?> builder = newStateBuilder(theClassName); if (objectIdForPointer == null) { setDefaultValues(); builder.isComplete(true); } else { if (!objectIdForPointer.equals(NEW_OFFLINE_OBJECT_ID_PLACEHOLDER)) { builder.objectId(objectIdForPointer); } builder.isComplete(false); } state = builder.build(); OfflineStore store = Parse.getLocalDatastore(); if (store != null) { store.registerNewObject(this); } }

Target:
public ParseObject(String theClassName) { String objectIdForPointer = isCreatingPointerForObjectId.get(); if (theClassName == null) { throw new IllegalArgumentException( "You must specify a Parse class name when creating a new ParseObject."); } if (AUTO_CLASS_NAME.equals(theClassName)) { theClassName = getSubclassingController().getClassName(getClass()); } if (!getSubclassingController().isSubclassValid(theClassName, getClass())) { throw new IllegalArgumentException( "You must create this type of ParseObject using ParseObject.create() or the proper subclass."); } operationSetQueue = new LinkedList<>(); operationSetQueue.add(new ParseOperationSet()); estimatedData = new HashMap<>(); State.Init<?> builder = newStateBuilder(theClassName); if (objectIdForPointer == null) { setDefaultValues(); builder.isComplete(true); } else { if (!objectIdForPointer.equals(NEW_OFFLINE_OBJECT_ID_PLACEHOLDER)) { builder.objectId(objectIdForPointer); } builder.isComplete(false); } state = builder.build(); OfflineStore store = Parse.getLocalDatastore(); if (store != null) { store.registerNewObject(this); } }
Source:
public Row next() throws IOException { while (true) { try { Row result = currentDelegate.next(); if (result != null) { lastRowKey = result.getKey(); rowCount++; } currentBackoff.reset(); return result; } catch (ScanTimeoutException rte) { if (logWarningsBeforeRetry) { LOG.warn("ReadTimeoutException: ", rte); } backOffAndRetry(rte); } catch (IOExceptionWithStatus ioe) { if (logWarningsBeforeRetry) { LOG.warn("IOExceptionWithStatus: ", ioe); } Status.Code code = ioe.getStatus().getCode(); if (retryOptions.isRetryableRead(code)) { backOffAndRetry(ioe); } else { throw ioe; } } } }

Target:
public Row next() throws IOException { while (true) { try { Row result = currentDelegate.next(); if (result != null) { lastRowKey = result.getKey(); rowCount++; } currentBackoff.reset(); return result; } catch (ScanTimeoutException rte) { logger.warn("ReadTimeoutException: ", rte); backOffAndRetry(rte); } catch (IOExceptionWithStatus ioe) { logger.warn("IOExceptionWithStatus: ", ioe); Status.Code code = ioe.getStatus().getCode(); if (retryOptions.isRetryableRead(code)) { backOffAndRetry(ioe); } else { throw ioe; } } } }
Source:
public boolean isFetchOnFeatureStart() { StoredConfig config = repository.getConfig(); String result = config.getString(GITFLOW_SECTION, FEATURE_START_SUBSECTION, FEATURE_START_FETCH_KEY); return (result == null) ? false : Boolean.valueOf(result).booleanValue(); }

Target:
public boolean isFetchOnFeatureStart() { StoredConfig config = repository.getConfig(); return config.getBoolean(GITFLOW_SECTION, FEATURE_START_SUBSECTION, FEATURE_START_FETCH_KEY, false); }
Source:
protected void addCommonColumnSettings(FilterSettingsBuilderHelper builder) { builder.setColumn(COLUMN_ACTIVATION_TIME, constants.ActivationTime(), DateUtils.getDateTimeFormatMask()); builder.setColumn(COLUMN_ACTUAL_OWNER, constants.Actual_Owner()); builder.setColumn(COLUMN_CREATED_BY, constants.CreatedBy()); builder.setColumn(COLUMN_CREATED_ON, constants.Created_On(), DateUtils.getDateTimeFormatMask()); builder.setColumn(COLUMN_DEPLOYMENT_ID, constants.DeploymentId()); builder.setColumn(COLUMN_DESCRIPTION, constants.Description()); builder.setColumn(COLUMN_DUE_DATE, constants.DueDate(), DateUtils.getDateTimeFormatMask()); builder.setColumn(COLUMN_NAME, constants.Task()); builder.setColumn(COLUMN_PARENT_ID, constants.ParentId()); builder.setColumn(COLUMN_PRIORITY, constants.Priority()); builder.setColumn(COLUMN_PROCESS_ID, constants.Process_Definition_Id()); builder.setColumn(COLUMN_PROCESS_INSTANCE_ID, constants.Process_Instance_Id()); builder.setColumn(COLUMN_PROCESS_SESSION_ID, constants.ProcessSessionId()); builder.setColumn(COLUMN_STATUS, constants.Status()); builder.setColumn(COLUMN_TASK_ID, constants.Id()); builder.setColumn(COLUMN_WORK_ITEM_ID, constants.WorkItemId()); builder.setColumn(COLUMN_LAST_MODIFICATION_DATE, constants.Last_Modification_Date()); builder.setColumn(COLUMN_PROCESS_INSTANCE_CORRELATION_KEY, constants.Process_Instance_Correlation_Key()); builder.setColumn(COLUMN_PROCESS_INSTANCE_DESCRIPTION, constants.Process_Instance_Description()); builder.setColumn(COLUMN_ERROR_COUNT, constants.Error_Count()); builder.filterOn(true, true, true); builder.tableOrderEnabled(true); builder.tableOrderDefault(COLUMN_CREATED_ON, SortOrder.DESCENDING); }

Target:
protected void addCommonColumnSettings(FilterSettingsBuilderHelper builder) { builder.setColumn(COLUMN_ERROR_COUNT, constants.Error_Count()); super.addCommonColumnSettings(builder); }
Source:
public void dontRequestIfDownstreamRequestsLate() { final List<Long> requested = new ArrayList<Long>(); Action1<Long> empty = Actions.empty(); final AtomicReference<Producer> producer = new AtomicReference<Producer>(); Observable.create(new OnSubscribe<Integer>() { @Override public void call(Subscriber<? super Integer> t) { t.setProducer(new Producer() { @Override public void request(long n) { requested.add(n); } }); } }).doOnRequest(empty).subscribe(new Subscriber<Object>() { @Override public void onNext(Object t) { } @Override public void onError(Throwable e) { } @Override public void onCompleted() { } @Override public void setProducer(Producer p) { producer.set(p); } }); producer.get().request(1); System.out.println(requested); Assert.assertEquals(2, requested.size()); Assert.assertEquals(Arrays.asList(0L, 1L), requested); }

Target:
public void dontRequestIfDownstreamRequestsLate() { final List<Long> requested = new ArrayList<Long>(); Action1<Long> empty = Actions.empty(); final AtomicReference<Producer> producer = new AtomicReference<Producer>(); Observable.create(new OnSubscribe<Integer>() { @Override public void call(Subscriber<? super Integer> t) { t.setProducer(new Producer() { @Override public void request(long n) { requested.add(n); } }); } }).doOnRequest(empty).subscribe(new Subscriber<Object>() { @Override public void onNext(Object t) { } @Override public void onError(Throwable e) { } @Override public void onCompleted() { } @Override public void setProducer(Producer p) { producer.set(p); } }); producer.get().request(1); int s = requested.size(); if (s == 1) { Assert.assertEquals(Arrays.asList(1L), requested); } else { Assert.assertEquals(Arrays.asList(0L, 1L), requested); } }
Source:
public void visitWhileStatement(WhileStatementTree tree) { ConditionalState conditionalState = visitCondition(tree.condition()); currentState = conditionalState.trueState; scan(tree.statement()); currentState = currentState.parentState.merge(conditionalState.trueState, conditionalState.falseState); }

Target:
public void visitWhileStatement(WhileStatementTree tree) { ConditionalState conditionalState = visitCondition(tree.condition()); currentState = conditionalState.trueState; scan(tree.statement()); currentState = currentState.parentState.mergeValues(conditionalState.trueState, conditionalState.falseState); }
Source:
private Request redirectRequest(Request request, String redirectToUri) { final String currentUrl = request.url().toString(); String matchingUri = null; for (String uri : uris) { if (currentUrl.startsWith(uri)) { matchingUri = uri; break; } } if (matchingUri == null) { throw new IllegalStateException( String.format("None of the URIs %s matched request URL %s", uris, currentUrl)); } final String newUrl = currentUrl.replaceFirst(matchingUri, redirectToUri); return request.newBuilder() .url(HttpUrl.parse(newUrl)) .tag(request.tag().equals(request) ? null : request.tag()) .build(); }

Target:
private Request redirectRequest(Request request, String redirectToUri) { String requestUri = request.url().toString(); String matchingUri = null; for (String uri : uris) { if (requestUri.startsWith(uri)) { matchingUri = uri; break; } } if (matchingUri == null) { throw new IllegalStateException(String.format("Unrecognized server URI in the request %s. " + "Supported servers are %s. Did you use different server URI for the initial request?", requestUri, uris)); } String newRequestUrl = requestUri.replaceFirst(matchingUri, redirectToUri); return request.newBuilder() .url(HttpUrl.parse(newRequestUrl)) .tag(request.tag().equals(request) ? null : request.tag()) .build(); }
Source:
private String firstNonOptionArgument(String[] line) { int i; for (i = 1; i < line.length; i++) { String component = line[i]; if (!component.startsWith("--")) { return line[i]; } } return null; }

Target:
private String firstNonOptionArgument(String[] line) { return Arrays.stream(line) .skip(1) .filter(component -> !component.startsWith("--")) .findFirst() .orElse(null); }
Source:
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException { String aadIssuedBearerToken = Optional.of(httpServletRequest) .map(r -> r.getHeader(HttpHeaders.AUTHORIZATION)) .map(String::trim) .filter(s -> s.startsWith(Constants.BEARER_PREFIX)) .map(s -> s.replace(Constants.BEARER_PREFIX, "")) .filter(principalManager::isTokenIssuedByAAD) .orElse(null); if (aadIssuedBearerToken == null || alreadyAuthenticated()) { filterChain.doFilter(httpServletRequest, httpServletResponse); return; } try { final UserPrincipal userPrincipal = principalManager.buildUserPrincipal(aadIssuedBearerToken); Set<SimpleGrantedAuthority> authorities = toSimpleGrantedAuthoritySet(userPrincipal); if(userPrincipal.getClaim(AADTokenClaim.SCP) != null){ authorities.addAll(scopeToSimpleGrantedAuthoritySet(userPrincipal)); } final Authentication authentication = new PreAuthenticatedAuthenticationToken( userPrincipal, null, authorities ); LOGGER.info("Request token verification success. {}", authentication); SecurityContextHolder.getContext().setAuthentication(authentication); try { filterChain.doFilter(httpServletRequest, httpServletResponse); } finally { SecurityContextHolder.clearContext(); } } catch (BadJWTException ex) { httpServletResponse.sendError(HttpStatus.UNAUTHORIZED.value()); } catch (ParseException | BadJOSEException | JOSEException ex) { LOGGER.error("Failed to initialize UserPrincipal.", ex); throw new ServletException(ex); } }

Target:
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException { String aadIssuedBearerToken = Optional.of(httpServletRequest) .map(r -> r.getHeader(HttpHeaders.AUTHORIZATION)) .map(String::trim) .filter(s -> s.startsWith(Constants.BEARER_PREFIX)) .map(s -> s.replace(Constants.BEARER_PREFIX, "")) .filter(principalManager::isTokenIssuedByAAD) .orElse(null); if (aadIssuedBearerToken == null || alreadyAuthenticated()) { filterChain.doFilter(httpServletRequest, httpServletResponse); return; } try { final UserPrincipal userPrincipal = principalManager.buildUserPrincipal(aadIssuedBearerToken); final Authentication authentication = new PreAuthenticatedAuthenticationToken( userPrincipal, null, toSimpleGrantedAuthoritySet(userPrincipal) ); LOGGER.info("Request token verification success. {}", authentication); SecurityContextHolder.getContext().setAuthentication(authentication); try { filterChain.doFilter(httpServletRequest, httpServletResponse); } finally { SecurityContextHolder.clearContext(); } } catch (BadJWTException ex) { httpServletResponse.sendError(HttpStatus.UNAUTHORIZED.value()); } catch (ParseException | BadJOSEException | JOSEException ex) { LOGGER.error("Failed to initialize UserPrincipal.", ex); throw new ServletException(ex); } }
Source:
public void setTypeBasedOptimizationOptions(CompilerOptions options) { switch (this) { case ADVANCED_OPTIMIZATIONS: options.inferTypes = true; options.disambiguateProperties = true; options.ambiguateProperties = true; options.inlineProperties = true; options.useTypesForOptimization = true; break; case SIMPLE_OPTIMIZATIONS: options.useTypesForOptimization = true; break; case WHITESPACE_ONLY: break; } }

Target:
public void setTypeBasedOptimizationOptions(CompilerOptions options) { switch (this) { case ADVANCED_OPTIMIZATIONS: options.inferTypes = true; options.disambiguateProperties = true; options.ambiguateProperties = true; options.inlineProperties = true; options.useTypesForOptimization = true; break; case SIMPLE_OPTIMIZATIONS: case WHITESPACE_ONLY: break; } }
Source:
protected void updateEnvironmentVariables() throws OpenShiftException { if (!canGetEnvironmentVariables()) { return; } if (environmentVariablesMap == null) { environmentVariablesMap = loadEnvironmentVariables(); } else { environmentVariablesMap.clear(); environmentVariablesMap.putAll(loadEnvironmentVariables()); } }

Target:
protected void updateEnvironmentVariables() throws OpenShiftException { if (!canGetEnvironmentVariables()) return; else { environmentVariablesMap.clear(); environmentVariablesMap = loadEnvironmentVariables(); } }
Source:
public static Archive<?> deployment() { final Archive<?> deployment = ShrinkWrap.create(JavaArchive.class, "JMSMessageDrivenBeanTestCase.jar") .addClasses(ReplyingMDB.class,JMSMessagingUtil.class) .addClass(CreateQueueSetupTask.class) .addClass(TimeoutUtil.class); return deployment; }

Target:
public static Archive<?> deployment() { final Archive<?> deployment = ShrinkWrap.create(JavaArchive.class, "JMSMessageDrivenBeanTestCase.jar") .addClasses(ReplyingMDB.class,JMSMessagingUtil.class) .addClass(CreateQueueSetupTask.class) .addClass(TimeoutUtil.class) .addAsResource(createPermissionsXmlAsset(new PropertyPermission("ts.timeout.factor", "read")), "META-INF/jboss-permissions.xml"); return deployment; }
Source:
private String getFileName(Attr source) throws MimeTypeException { String value = source.getValue(); String fileName = null; @SuppressWarnings("unchecked") Map<String, byte[]> embeddedImages = (Map<String, byte[]>) source.getOwnerDocument().getUserData(EMBEDDED_IMAGES); if (embeddedImages != null && value.startsWith("data:")) { DataUri dataURI = DataUri.parse(value, Charset.forName(UTF_8)); fileName = dataURI.getFilename(); if (StringUtils.isEmpty(fileName)) { fileName = String.valueOf(Math.abs(dataURI.hashCode())); if (!StringUtils.isEmpty(dataURI.getMime())) { String extension = MimeTypes.getDefaultMimeTypes().forName(dataURI.getMime()).getExtension(); fileName += extension; } } embeddedImages.put(fileName, dataURI.getData()); } else if (!value.contains("://")) { int separator = value.lastIndexOf('/'); fileName = separator < 0 ? value : value.substring(separator + 1); try { fileName = URLDecoder.decode(fileName, UTF_8); fileName = fileName.replaceAll("&amp;", "&"); } catch (Exception e) { } } return fileName; }

Target:
private String getFileName(Attr source) throws MimeTypeException { String value = source.getValue(); String fileName = null; @SuppressWarnings("unchecked") Map<String, byte[]> embeddedImages = (Map<String, byte[]>) source.getOwnerDocument().getUserData(EMBEDDED_IMAGES); if (embeddedImages != null && value.startsWith("data:")) { DataUri dataURI = DataUri.parse(value, Charset.forName(UTF_8)); fileName = dataURI.getFilename(); if (StringUtils.isEmpty(fileName)) { fileName = String.valueOf(Math.abs(dataURI.hashCode())); if (!StringUtils.isEmpty(dataURI.getMime())) { String extension = MimeTypes.getDefaultMimeTypes().forName(dataURI.getMime()).getExtension(); fileName += extension; } } embeddedImages.put(fileName, dataURI.getData()); } else if (!value.contains("://")) { int separator = value.lastIndexOf('/'); fileName = separator < 0 ? value : value.substring(separator + 1); try { fileName = fileName.replaceAll("\\+", "%2B"); fileName = URLDecoder.decode(fileName, UTF_8); fileName = fileName.replaceAll("&amp;", "&"); fileName = fileName.replaceAll("@", "\\\\@"); } catch (Exception e) { } } return fileName; }
Source:
public static ByteBuf metadata(final ByteBuf byteBuf) { boolean hasMetadata = FrameHeaderFlyweight.hasMetadata(byteBuf); FrameHeaderFlyweight.ensureFrameType(FrameType.LEASE, byteBuf); byteBuf.markReaderIndex(); byteBuf.skipBytes(FrameHeaderFlyweight.size() + Integer.BYTES * 2); ByteBuf metadata = DataAndMetadataFlyweight.metadataWithoutMarking(byteBuf, hasMetadata); byteBuf.resetReaderIndex(); return metadata; }

Target:
public static ByteBuf metadata(final ByteBuf byteBuf) { FrameHeaderFlyweight.ensureFrameType(FrameType.LEASE, byteBuf); if (FrameHeaderFlyweight.hasMetadata(byteBuf)) { byteBuf.markReaderIndex(); byteBuf.skipBytes(FrameHeaderFlyweight.size() + Integer.BYTES * 2); ByteBuf metadata = byteBuf.slice(); byteBuf.resetReaderIndex(); return metadata; } else { return Unpooled.EMPTY_BUFFER; } }
Source:
TableDataBuilder addRowsFrom(File file, FileParser fileParser) { if (fileParser.hasColumnNames()) { if (names != schema.getFieldNames()) { throw new IllegalArgumentException("Mixing manual column selection and header column names is not supported."); } List<String> columns = fileParser.getColumnNames(file); withColumns(columns.toArray(new String[columns.size()])); } return addRows(fileParser.parse(file, schema, names)); }

Target:
TableDataBuilder addRowsFrom(File file, FileParser fileParser) { if (fileParser.hasColumnNames()) { checkArgument(names.equals(schema.getFieldNames()), "Manual column spec and header column spec are mutually exclusive"); List<String> columns = fileParser.getColumnNames(file); withColumns(columns.toArray(new String[columns.size()])); } return addRows(fileParser.parse(file, schema, names)); }
Source:
public boolean shouldEmitContainer( final int currentReferenceContextID, final int nextRecordIndex, final int numberOfSliceEntries) { return numberOfSliceEntries == encodingStrategy.getSlicesPerContainer() || currentReferenceContextID == ReferenceContext.MULTIPLE_REFERENCE_ID || currentReferenceContextID != nextRecordIndex; }

Target:
public boolean shouldEmitContainer( final int currentReferenceContextID, final int nextRecordIndex, final int numberOfSliceEntries) { return numberOfSliceEntries >= encodingStrategy.getSlicesPerContainer() || currentReferenceContextID == ReferenceContext.MULTIPLE_REFERENCE_ID || currentReferenceContextID != nextRecordIndex; }
Source:
public Publisher<T> apply(Publisher<T> publisher) { if (publisher instanceof Mono) { return withTimeout((Mono<T>) publisher); } else if (publisher instanceof Flux) { return withTimeout((Flux<T>) publisher); } else { throw new IllegalStateException("Publisher of type <" + publisher.getClass().getSimpleName() + "> is not supported by this operator"); } }

Target:
public Publisher<T> apply(Publisher<T> publisher) { if (publisher instanceof Mono) { return withTimeout((Mono<T>) publisher); } else if (publisher instanceof Flux) { return withTimeout((Flux<T>) publisher); } else { throw new IllegalPublisherException(publisher); } }