auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void reload(final Repository repository) { if (form.isDisposed()) return; if (repository == null) { asyncExec(new Runnable() { public void run() { clearRepository(); } }); return; } if (!isValidRepo(repository)) return; final boolean repositoryChanged = currentRepository != repository; asyncExec(new Runnable() { public void run() { if (form.isDisposed()) return; final IndexDiffData indexDiff = doReload(repository); final StagingViewUpdate update = new StagingViewUpdate(currentRepository, indexDiff, null); unstagedTableViewer.setInput(update); stagedTableViewer.setInput(update); enableCommitWidgets(true); commitAction.setEnabled(repository.getRepositoryState() .canCommit()); form.setText(StagingView.getRepositoryName(repository)); updateCommitMessageComponent(repositoryChanged); updateSectionText(); } }); }

Target:
private void reload(final Repository repository) { if (form.isDisposed()) return; if (repository == null) { asyncExec(new Runnable() { public void run() { clearRepository(); } }); return; } if (!isValidRepo(repository)) return; final boolean repositoryChanged = currentRepository != repository; asyncExec(new Runnable() { public void run() { if (form.isDisposed()) return; final IndexDiffData indexDiff = doReload(repository); if(indexDiff == null) return; final StagingViewUpdate update = new StagingViewUpdate(currentRepository, indexDiff, null); unstagedTableViewer.setInput(update); stagedTableViewer.setInput(update); enableCommitWidgets(true); commitAction.setEnabled(repository.getRepositoryState() .canCommit()); form.setText(StagingView.getRepositoryName(repository)); updateCommitMessageComponent(repositoryChanged); updateSectionText(); } }); }
Source:
public void testTryLockAfterTaskComplete() throws InterruptedException { Task task = NoopTask.create(); exception.expect(IllegalStateException.class); lockbox.add(task); lockbox.remove(task); Assert.assertFalse(lockbox.tryLock(task, new Interval("2015-01-01/2015-01-02")).isPresent()); }

Target:
public void testTryLockAfterTaskComplete() { Task task = NoopTask.create(); exception.expect(ISE.class); exception.expectMessage("Unable to grant lock to inactive Task"); lockbox.add(task); lockbox.remove(task); Assert.assertFalse(lockbox.tryLock(task, new Interval("2015-01-01/2015-01-02")).isPresent()); }
Source:
private long updateCardCurrentDid(Card card) { if(card == null) { return -1; } card.setDid(mCurrentDid); return mCurrentDid; }

Target:
private long updateCardCurrentDid(Card card) { if(card == null) { return -1; } mLastDid = card.getDid(); card.setDid(mCurrentDid); return mCurrentDid; }
Source:
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { Log.d(TAG, "onUpdate() called with: " + "context = [" + context + "], appWidgetManager = [" + appWidgetManager + "], appWidgetIds = [" + Arrays.toString(appWidgetIds) + "]"); for (int appWidgetId : appWidgetIds) { SharedPreferences prefs = context.getSharedPreferences(WIDGET_PREFS, Context.MODE_PRIVATE); String backgroundColor = prefs.getString(WIDGET_COLOR + appWidgetId, "#7F262C31"); RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.player_widget); views.setInt(R.id.widgetLayout,"setBackgroundColor", Color.parseColor(backgroundColor)); appWidgetManager.updateAppWidget(appWidgetId, views); } PlayerWidgetJobService.updateWidget(context); }

Target:
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { Log.d(TAG, "onUpdate() called with: " + "context = [" + context + "], appWidgetManager = [" + appWidgetManager + "], appWidgetIds = [" + Arrays.toString(appWidgetIds) + "]"); PlayerWidgetJobService.updateWidget(context); }
Source:
private void sleepForAWhile() { try { Thread.sleep(1000); } catch (InterruptedException e) { assertThat(e).isNull(); } }

Target:
private void sleepForAWhile() { SystemClock.sleep(1000); }
Source:
public void testGroupByFloatColumn() { if (config.getDefaultStrategy().equals(GroupByStrategySelector.STRATEGY_V1)) { return; } GroupByQuery query = GroupByQuery .builder() .setDataSource(QueryRunnerTestHelper.dataSource) .setQuerySegmentSpec(QueryRunnerTestHelper.firstToThird) .setDimensions(Lists.<DimensionSpec>newArrayList(new DefaultDimensionSpec("index", "index_alias", ValueType.FLOAT))) .setDimFilter(new SelectorDimFilter("quality", "entertainment", null)) .setAggregatorSpecs( Arrays.asList( QueryRunnerTestHelper.rowsCount, new LongSumAggregatorFactory("idx", "index") ) ) .setGranularity(QueryRunnerTestHelper.dayGran) .build(); List<Row> expectedResults; if (config.getDefaultStrategy().equals(GroupByStrategySelector.STRATEGY_V1)) { expectedResults = Arrays.asList( GroupByQueryRunnerTestHelper.createExpectedRow( "2011-04-01", "index_alias", "158.74722", "rows", 1L, "idx", 158L ), GroupByQueryRunnerTestHelper.createExpectedRow( "2011-04-02", "index_alias", "166.01605", "rows", 1L, "idx", 166L ) ); } else { expectedResults = Arrays.asList( GroupByQueryRunnerTestHelper.createExpectedRow( "2011-04-01", "index_alias", 158.747224f, "rows", 1L, "idx", 158L ), GroupByQueryRunnerTestHelper.createExpectedRow( "2011-04-02", "index_alias", 166.016049f, "rows", 1L, "idx", 166L ) ); } Iterable<Row> results = GroupByQueryRunnerTestHelper.runQuery(factory, runner, query); TestHelper.assertExpectedObjects(expectedResults, results, ""); }

Target:
public void testGroupByFloatColumn() { if (config.getDefaultStrategy().equals(GroupByStrategySelector.STRATEGY_V1)) { expectedException.expect(UnsupportedOperationException.class); expectedException.expectMessage("GroupBy v1 only supports dimensions with an outputType of STRING."); } GroupByQuery query = GroupByQuery .builder() .setDataSource(QueryRunnerTestHelper.dataSource) .setQuerySegmentSpec(QueryRunnerTestHelper.firstToThird) .setDimensions(Lists.<DimensionSpec>newArrayList(new DefaultDimensionSpec("index", "index_alias", ValueType.FLOAT))) .setDimFilter(new SelectorDimFilter("quality", "entertainment", null)) .setAggregatorSpecs( Arrays.asList( QueryRunnerTestHelper.rowsCount, new LongSumAggregatorFactory("idx", "index") ) ) .addOrderByColumn(new OrderByColumnSpec( "index_alias", OrderByColumnSpec.Direction.ASCENDING, StringComparators.NUMERIC )) .setGranularity(QueryRunnerTestHelper.dayGran) .build(); Assert.assertEquals( Functions.<Sequence<Row>>identity(), query.getLimitSpec().build( query.getDimensions(), query.getAggregatorSpecs(), query.getPostAggregatorSpecs() ) ); List<Row> expectedResults = Arrays.asList( GroupByQueryRunnerTestHelper.createExpectedRow( "2011-04-01", "index_alias", 158.747224f, "rows", 1L, "idx", 158L ), GroupByQueryRunnerTestHelper.createExpectedRow( "2011-04-02", "index_alias", 166.016049f, "rows", 1L, "idx", 166L ) ); Iterable<Row> results = GroupByQueryRunnerTestHelper.runQuery(factory, runner, query); TestHelper.assertExpectedObjects(expectedResults, results, ""); }
Source:
static Optional<ACLHandle> getEffectiveAcl(final FedoraResource resource) { try { final IdentifierConverter<Resource, FedoraResource> translator = new DefaultIdentifierTranslator(resource.getNode().getSession()); final List<String> acls = resource.getTriples(translator, PROPERTIES) .filter(triple -> triple.getPredicate().equals(createURI(WEBAC_ACCESS_CONTROL_VALUE))) .map(triple -> { if (triple.getObject().isURI()) { return triple.getObject().getURI(); } else { final String error = String.format("The value %s of the %s on this resource must be a URI", triple.getObject(), WEBAC_ACCESS_CONTROL_VALUE); LOGGER.error(error); throw new MalformedRdfException(error); } }).collect(toList()); if (!acls.isEmpty()) { if (acls.size() > 1) { LOGGER.warn("Found multiple ACLs defined for this node. Using: {}", acls.get(0)); } return Optional.of(new ACLHandle(URI.create(acls.get(0)), resource)); } else if (resource.getNode().getDepth() == 0) { LOGGER.debug("No ACLs defined on this node or in parent hierarchy"); return Optional.empty(); } else { LOGGER.trace("Checking parent resource for ACL. No ACL found at {}", resource.getPath()); return getEffectiveAcl(resource.getContainer()); } } catch (final RepositoryException ex) { LOGGER.debug("Exception finding effective ACL: {}", ex.getMessage()); return Optional.empty(); } }

Target:
static Optional<ACLHandle> getEffectiveAcl(final FedoraResource resource) { try { final IdentifierConverter<Resource, FedoraResource> translator = new DefaultIdentifierTranslator(resource.getNode().getSession()); final List<String> acls = resource.getTriples(translator, PROPERTIES) .filter(triple -> triple.getPredicate().equals(createURI(WEBAC_ACCESS_CONTROL_VALUE))) .map(triple -> { if (triple.getObject().isURI()) { return triple.getObject().getURI(); } final String error = String.format("The value %s of the %s on this resource must be a URI", triple.getObject(), WEBAC_ACCESS_CONTROL_VALUE); LOGGER.error(error); throw new MalformedRdfException(error); }).collect(toList()); if (!acls.isEmpty()) { if (acls.size() > 1) { LOGGER.warn("Found multiple ACLs defined for this node. Using: {}", acls.get(0)); } return Optional.of(new ACLHandle(URI.create(acls.get(0)), resource)); } else if (resource.getNode().getDepth() == 0) { LOGGER.debug("No ACLs defined on this node or in parent hierarchy"); return Optional.empty(); } else { LOGGER.trace("Checking parent resource for ACL. No ACL found at {}", resource.getPath()); return getEffectiveAcl(resource.getContainer()); } } catch (final RepositoryException ex) { LOGGER.debug("Exception finding effective ACL: {}", ex.getMessage()); return Optional.empty(); } }
Source:
HiveSplitSource( String connectorId, String databaseName, String tableName, TupleDomain<? extends ColumnHandle> compactEffectivePredicate, int maxOutstandingSplits, DataSize maxOutstandingSplitsSize, HiveSplitLoader splitLoader, Executor executor) { this.connectorId = requireNonNull(connectorId, "connectorId is null"); this.databaseName = requireNonNull(databaseName, "databaseName is null"); this.tableName = requireNonNull(tableName, "tableName is null"); this.compactEffectivePredicate = requireNonNull(compactEffectivePredicate, "compactEffectivePredicate is null"); this.queue = new AsyncQueue<>(maxOutstandingSplits, executor); this.maxOutstandingSplitsBytes = Ints.checkedCast(maxOutstandingSplitsSize.toBytes()); this.splitLoader = splitLoader; }

Target:
HiveSplitSource( String connectorId, String databaseName, String tableName, TupleDomain<? extends ColumnHandle> compactEffectivePredicate, int maxOutstandingSplits, DataSize maxOutstandingSplitsSize, HiveSplitLoader splitLoader, Executor executor) { this.connectorId = requireNonNull(connectorId, "connectorId is null"); this.databaseName = requireNonNull(databaseName, "databaseName is null"); this.tableName = requireNonNull(tableName, "tableName is null"); this.compactEffectivePredicate = requireNonNull(compactEffectivePredicate, "compactEffectivePredicate is null"); this.queue = new AsyncQueue<>(maxOutstandingSplits, executor); this.maxOutstandingSplitsBytes = toIntExact(maxOutstandingSplitsSize.toBytes()); this.splitLoader = splitLoader; }
Source:
public VariableInstance<?> assignVariableInstance(String variableName, ValueReference reference) { VariableScope variableScope = getVariableScope(); Variable variable = variableScope.findVariable(variableName); if (variable == null) { variable = new Variable(variableName); variable.setMetaData("on-the-fly", true); } variableScope.validateVariable( getProcessInstance().getProcessName(), variableName, reference.get()); VariableInstance<?> instance = addVariableInstance(variableName); instance.setReference(reference); return instance; }

Target:
public VariableInstance<?> assignVariableInstance(String variableName, ValueReference reference) { VariableScope variableScope = getVariableScope(); Variable variable = variableScope.findVariable(variableName); if (variable == null) { variable = new Variable(variableName); variable.setMetaData("on-the-fly", true); } variableScope.validateVariable( getProcessInstance().getProcessName(), variableName, reference.get()); VariableInstance<?> instance = getVariableInstance(variableName); instance.setReference(reference); return instance; }
Source:
Set<EMOperation> markOperationComplete(final EMOperation op) { final OpExecutionStatus prevStatus = emOperationsRequested.replace(op, OpExecutionStatus.Complete); if (prevStatus == null) { throw new RuntimeException("The operation " + op + " was never in the request queue"); } planExecutionLatch.countDown(); return plan.onComplete(op); }

Target:
Set<EMOperation> markOperationComplete(final EMOperation op) { planExecutionLatch.countDown(); final boolean wasInProgress = emOperationsRequested.replace(op, OpExecutionStatus.IN_PROGRESS, OpExecutionStatus.COMPLETE); if (!wasInProgress) { throw new RuntimeException("The operation " + op + " was never in the request queue"); } return plan.onComplete(op); }
Source:
private void testQosAppendedToResultSet(List<VdsNetworkInterface> result) { result.forEach(r-> { if (r.getQos() == null) { HostNetworkQos hostNetworkQos = new HostNetworkQos(); hostNetworkQos.setId(r.getId()); hostNetworkQos.setOutAverageLinkshare(31); hostNetworkQos.setOutAverageUpperlimit(31); hostNetworkQos.setOutAverageRealtime(31); hostNetworkQosDao.save(hostNetworkQos); } else { r.getQos().setOutAverageLinkshare(31); r.getQos().setOutAverageUpperlimit(31); r.getQos().setOutAverageRealtime(31); hostNetworkQosDao.update(r.getQos()); } }); result = dao.getAllInterfacesForVds(VDS_ID); assertNotNull(result); assertEquals(2, result.size()); result.forEach(r -> { assertNotNull(r.getQos()); assertEquals(r.getId(), r.getQos().getId()); assertEquals(QosType.HOSTNETWORK, r.getQos().getQosType()); assertEquals(31, r.getQos().getOutAverageLinkshare().intValue()); assertEquals(31, r.getQos().getOutAverageRealtime().intValue()); assertEquals(31, r.getQos().getOutAverageUpperlimit().intValue()); }); }

Target:
private void testQosAppendedToResultSet(List<VdsNetworkInterface> result) { result.forEach(r-> { if (r.getQos() == null) { HostNetworkQos hostNetworkQos = new HostNetworkQos(); hostNetworkQos.setId(r.getId()); hostNetworkQos.setOutAverageLinkshare(31); hostNetworkQos.setOutAverageUpperlimit(32); hostNetworkQos.setOutAverageRealtime(33); hostNetworkQosDao.save(hostNetworkQos); } else { r.getQos().setOutAverageLinkshare(31); r.getQos().setOutAverageUpperlimit(32); r.getQos().setOutAverageRealtime(33 ); hostNetworkQosDao.update(r.getQos()); } }); result = dao.getAllInterfacesForVds(VDS_ID); assertNotNull(result); assertEquals(2, result.size()); result.forEach(r -> { assertNotNull(r.getQos()); assertEquals(r.getId(), r.getQos().getId()); assertEquals(QosType.HOSTNETWORK, r.getQos().getQosType()); assertEquals(31, r.getQos().getOutAverageLinkshare().intValue()); assertEquals(32, r.getQos().getOutAverageUpperlimit().intValue()); assertEquals(33, r.getQos().getOutAverageRealtime().intValue()); }); }
Source:
private void addToSpec(Map<String, Object> inputs, T output) { T reference = consistentInputs().get(inputs); if (consistentInputs().size() == 0) { consistentInputs().put(inputs, output); this.keys = inputs.keySet(); return; } if (reference == null && this.keys.equals(inputs.keySet())) { consistentInputs().put(inputs, output); return; } if (output.equals(reference) && this.keys.equals(inputs.keySet())) { this.logger.warn("You may have some redundant test: same input and same outcome, only one will be used: discarded."); return; } this.inconsistentInputs.add(inputs); if (!this.keys.equals(inputs.keySet())) { this.logger.debug("Malformed problems: the same input value has different outcome: discarded."); consistentInputs().remove(inputs); } else { this.logger.debug("Inconsistent specification: same input with same outcome, the condition can be flipped with no impact: discarded."); } }

Target:
private void addToSpec(Map<String, Object> inputs, T output) { T reference = consistentInputs().get(inputs); if (consistentInputs().size() == 0) { consistentInputs().put(inputs, output); this.keys = inputs.keySet(); return; } if (reference == null && this.keys.equals(inputs.keySet())) { consistentInputs().put(inputs, output); return; } if (output.equals(reference) && this.keys.equals(inputs.keySet())) { this.logger.warn("You have redundant tests: same input and same outcome, only one will be used to speed-up synthesis: discarded inputs={} : output={}.", inputs, output); return; } if (!this.keys.equals(inputs.keySet())) { this.logger.debug("Ill-formed problem: not the input variables in input={} reference={}", inputs, this.keys); this.inconsistentInputs.add(inputs); consistentInputs().remove(inputs); } else { this.logger.debug("Same input with different outcome, logical contradiction, discarding the second one discarded={}, current output={}, reference output={}", inputs, output, consistentInputs.get(inputs)); this.inconsistentInputs.add(inputs); } }
Source:
public Mono<AreaCodes> getAllAreaCodes( String locationType, String countryCode, String phonePlanId, List<LocationOptionsQuery> locationOptions) { LocationOptionsQueries locationOptionsQueries = new LocationOptionsQueries(); locationOptionsQueries.setLocationOptions(locationOptions); return phoneNumberAdminClient.getPhoneNumberAdministrations().getAllAreaCodesAsync( locationType, countryCode, phonePlanId, locationOptionsQueries); }

Target:
public Mono<AreaCodes> getAllAreaCodes( String locationType, String countryCode, String phonePlanId, List<LocationOptionsQuery> locationOptions) { LocationOptionsQueries locationOptionsQueries = new LocationOptionsQueries(); locationOptionsQueries.setLocationOptions(locationOptions); return phoneNumberAdministrations.getAllAreaCodesAsync( locationType, countryCode, phonePlanId, locationOptionsQueries); }
Source:
private String setBuildEnvironmentText(Object[] environments){ String result = ""; String actualEnvironment = ""; buildEnvironments = new ArrayList<String>(); for(int i = 0; i < environments.length; ++i){ actualEnvironment = environments[i].toString(); buildEnvironments.add(actualEnvironment); if(i == 0) { result += actualEnvironment; continue; } result += "; " + actualEnvironment; } return result; }

Target:
private String setBuildEnvironmentText(Object[] environments){ StringBuilder result = new StringBuilder(); String actualEnvironment = ""; buildEnvironments = new ArrayList<String>(); for(int i = 0; i < environments.length; ++i){ actualEnvironment = environments[i].toString(); buildEnvironments.add(actualEnvironment); if(i == 0) { result.append(actualEnvironment); continue; } result.append("; "); result.append(actualEnvironment); } return result.toString(); }
Source:
public void testGetCourses() throws InvalidParametersException { CourseAttributes c = createNewCourse(); List<String> courseIds = new ArrayList<>(); ______TS("Success: get existent courses"); courseIds.add(c.getId()); List<CourseAttributes> retrieved = coursesDb.getCourses(courseIds); assertEquals(1, retrieved.size()); ______TS("Failure: get a non-existent course"); courseIds.remove(c.getId()); courseIds.add("non-existent-course"); retrieved = coursesDb.getCourses(courseIds); assertEquals(0, retrieved.size()); ______TS("Failure: get null parameters"); try { coursesDb.getCourse(null); signalFailureToDetectException(); } catch (AssertionError e) { assertEquals(Const.StatusCodes.DBLEVEL_NULL_INPUT, e.getMessage()); } }

Target:
public void testGetCourses() throws InvalidParametersException { CourseAttributes c = createNewCourse(); List<String> courseIds = new ArrayList<>(); ______TS("Success: get an existent course"); courseIds.add(c.getId()); List<CourseAttributes> retrieved = coursesDb.getCourses(courseIds); assertEquals(1, retrieved.size()); ______TS("Failure: get a non-existent course"); courseIds.remove(c.getId()); courseIds.add("non-existent-course"); retrieved = coursesDb.getCourses(courseIds); assertEquals(0, retrieved.size()); ______TS("Failure: get null parameters"); try { coursesDb.getCourse(null); signalFailureToDetectException(); } catch (AssertionError e) { assertEquals(Const.StatusCodes.DBLEVEL_NULL_INPUT, e.getMessage()); } }
Source:
static Challenge parseChallenge(final String challenge) throws ResourceAuthenticationChallengeException { final String scheme = parseScheme(challenge); Logger.d(TAG, "Parsing scheme: " + scheme); final String challengeSansScheme = challenge.substring(scheme.length() + 1); final Map<String, String> params = parseParams(challengeSansScheme); return new Challenge(scheme, params); }

Target:
static Challenge parseChallenge(final String challenge) throws ResourceAuthenticationChallengeException { final String methodName = ":parseChallenge"; if (StringExtensions.isNullOrBlank(challenge)) { Logger.w(TAG + methodName, "Cannot parse null/empty challenge."); throw new ResourceAuthenticationChallengeException(AUTH_HEADER_MISSING); } final String scheme = parseScheme(challenge); Logger.i(TAG + methodName, "Parsing scheme", "Scheme value [" + scheme + "]"); Logger.i(TAG + methodName, "Removing scheme from source challenge", "[" + challenge + "]"); Logger.v(TAG + methodName, "Parsing challenge substr. Total length: " + challenge.length() + " Scheme index: " + scheme.length() + 1); final String challengeSansScheme = challenge.substring(scheme.length() + 1); final Map<String, String> params = parseParams(challengeSansScheme); return new Challenge(scheme, params); }
Source:
public void removeDestination(String... destination) { this.destinationLock.lock(); try { for (String d : destination) { if (this.destinations.remove(d)) { if (this.logger.isDebugEnabled()) { logger.debug("Removed '" + d + "' from subscriptions."); } StompSession.Subscription subscription = this.subscriptions.get(d); if (subscription != null) { subscription.unsubscribe(); } } } } finally { this.destinationLock.unlock(); } }

Target:
public void removeDestination(String... destination) { Assert.notNull(destination, "'destination' cannot be null"); this.destinationLock.lock(); try { for (String d : destination) { if (this.destinations.remove(d)) { if (this.logger.isDebugEnabled()) { logger.debug("Removed '" + d + "' from subscriptions."); } StompSession.Subscription subscription = this.subscriptions.get(d); if (subscription != null) { subscription.unsubscribe(); } else { if (this.logger.isDebugEnabled()) { logger.debug("No subscription for destination '" + d + "'."); } } } } } finally { this.destinationLock.unlock(); } }
Source:
private void commitUpToCheckpoint(long checkpointId) throws Exception { helper.commitUpToCheckpoint(checkpointId); NavigableMap<Long, Set<String>> newPartitions = this.newPartitions.headMap(checkpointId, true); Set<String> partitions = new HashSet<>(committablePartitions); committablePartitions.clear(); newPartitions.values().forEach(partitions::addAll); newPartitions.clear(); CommitMessage message = new CommitMessage( checkpointId, getRuntimeContext().getIndexOfThisSubtask(), getRuntimeContext().getNumberOfParallelSubtasks(), new ArrayList<>(partitions)); output.collect(new StreamRecord<>(message)); }

Target:
private void commitUpToCheckpoint(long checkpointId) throws Exception { helper.commitUpToCheckpoint(checkpointId); NavigableMap<Long, Set<String>> headPartitions = this.newPartitions.headMap(checkpointId, true); Set<String> partitions = new HashSet<>(committablePartitions); committablePartitions.clear(); headPartitions.values().forEach(partitions::addAll); headPartitions.clear(); CommitMessage message = new CommitMessage( checkpointId, getRuntimeContext().getIndexOfThisSubtask(), getRuntimeContext().getNumberOfParallelSubtasks(), new ArrayList<>(partitions)); output.collect(new StreamRecord<>(message)); }
Source:
public GlowEntity spawn(Location location, Class<? extends GlowEntity> clazz, SpawnReason reason) throws IllegalArgumentException { GlowEntity entity = null; if (TNTPrimed.class.isAssignableFrom(clazz)) { entity = new GlowTNTPrimed(location, null); } if (entity == null) { try { Constructor<? extends GlowEntity> constructor = clazz.getConstructor(Location.class); entity = constructor.newInstance(location); if (entity instanceof LivingEntity) { CreatureSpawnEvent spawnEvent = new CreatureSpawnEvent((LivingEntity) entity, reason); if (!spawnEvent.isCancelled()) { entity.createSpawnMessage(); } else { entity.remove(); } } else { entity.createSpawnMessage(); } } catch (NoSuchMethodException e) { GlowServer.logger.log(Level.WARNING, "Invalid entity spawn: ", e); } catch (IllegalAccessException | InstantiationException | InvocationTargetException e) { GlowServer.logger.log(Level.SEVERE, "Unable to spawn entity: ", e); } } if (entity != null) { return entity; } throw new UnsupportedOperationException("Not supported yet."); }

Target:
public GlowEntity spawn(Location location, Class<? extends GlowEntity> clazz, SpawnReason reason) throws IllegalArgumentException { GlowEntity entity = null; if (TNTPrimed.class.isAssignableFrom(clazz)) { entity = new GlowTNTPrimed(location, null); } if (entity == null) { try { Constructor<? extends GlowEntity> constructor = clazz.getConstructor(Location.class); entity = constructor.newInstance(location); GlowEntity impl = entity; EntitySpawnEvent spawnEvent; if (entity instanceof LivingEntity) { spawnEvent = EventFactory.callEvent(new CreatureSpawnEvent((LivingEntity) entity, reason)); } else { spawnEvent = EventFactory.callEvent(new EntitySpawnEvent(entity)); } if (!spawnEvent.isCancelled()) { List<Message> spawnMessage = entity.createSpawnMessage(); getRawPlayers().stream().filter(player -> player.canSeeEntity(impl)).forEach(player -> player.getSession().sendAll(spawnMessage.toArray(new Message[spawnMessage.size()]))); } else { entity.remove(); } } catch (NoSuchMethodException e) { GlowServer.logger.log(Level.WARNING, "Invalid entity spawn: ", e); } catch (IllegalAccessException | InstantiationException | InvocationTargetException e) { GlowServer.logger.log(Level.SEVERE, "Unable to spawn entity: ", e); } } if (entity != null) { return entity; } throw new UnsupportedOperationException("Not supported yet."); }
Source:
private void checkOutput() throws IOException { String validationOutput; File folder = new File(directory); FilenameFilter filenameFilter = new FilenameFilter() { @Override public boolean accept(File dir, String name) { if (name.split("_")[0].equals("validation.txt")) { return true; } return false; } }; File validationFile = folder.listFiles(filenameFilter)[0]; FileInputStream inputStream = new FileInputStream(validationFile); try { validationOutput = IOUtils.toString(inputStream); System.out.println("Validation output: " + validationOutput); } finally { inputStream.close(); } Assert.assertTrue(validationOutput.contains("exactly-once: 0")); Assert.assertEquals("Duplicates: exactly-once: 0, at-least-once: " + tuplesUntilKill, validationOutput); }

Target:
private void checkOutput() throws IOException { String validationOutput; File folder = new File(directory); FilenameFilter filenameFilter = new FilenameFilter() { @Override public boolean accept(File dir, String name) { if (name.split("_")[0].equals("validation.txt")) { return true; } return false; } }; File validationFile = folder.listFiles(filenameFilter)[0]; try (FileInputStream inputStream = new FileInputStream(validationFile)) { validationOutput = IOUtils.toString(inputStream); logger.info("Validation output: {}", validationOutput); } Assert.assertTrue(validationOutput.contains("exactly-once: 0")); Assert.assertEquals("Duplicates: exactly-once: 0, at-least-once: " + tuplesUntilKill, validationOutput); }
Source:
public AbstractLunRemoveColumn(SanStorageModelBase model) { super(new AbstractToggleButtonCell<LunModel>() { @Override public void onClickEvent(LunModel lunModel) { if (lunModel != null) { lunModel.setRemoveLunSelected(!lunModel.isRemoveLunSelected()); } } @Override public void render(Context context, LunModel value, SafeHtmlBuilder sb, String id) { String inputId = id + "_input"; SafeHtml input; boolean lastLunAvailable = model.getNumOfLUNsToRemove() == model.getItems().size() - 1; model.getRequireTableRefresh().setEntity(lastLunAvailable); if (value.isRemoveLunSelected()) { input = templates.toggledDown(inputId, "Remove"); } else if (model.getMetadataDevices().contains(value.getLunId()) || model.getSelectedLuns().size() == 1 || lastLunAvailable) { input = templates.disabled(inputId, constants.notAvailableLabel()); } else { input = templates.toggledUp(inputId, "Remove"); } sb.append(templates.span(id, input)); } }); }

Target:
public AbstractLunRemoveColumn(SanStorageModelBase model) { super(new AbstractToggleButtonCell<LunModel>() { @Override public void onClickEvent(LunModel lunModel) { if (lunModel != null && !model.getMetadataDevices().contains(lunModel.getLunId())) { lunModel.setRemoveLunSelected(!lunModel.isRemoveLunSelected()); } } @Override public void render(Context context, LunModel value, SafeHtmlBuilder sb, String id) { String inputId = id + "_input"; SafeHtml input; boolean lastLunAvailable = false; if (model.getMetadataDevices().size() == 0) { lastLunAvailable = model.getNumOfLUNsToRemove() == model.getItems().size() - 1; } model.getRequireTableRefresh().setEntity(lastLunAvailable); if (model.getMetadataDevices().contains(value.getLunId()) || model.getSelectedLuns().size() == 1 || lastLunAvailable) { input = templates.disabled(inputId, constants.notAvailableLabel()); } else if (value.isRemoveLunSelected()) { input = templates.toggledDown(inputId, "Remove"); } else { input = templates.toggledUp(inputId, "Remove"); } sb.append(templates.span(id, input)); } }); }
Source:
public SocketAddress remoteAddress() { SocketAddress address = remoteAddress; if (address == null) { java.net.SocketAddress addr = chctx.channel().attr(REMOTE_ADDRESS_OVERRIDE).getAndSet(null); if (addr == null) addr = chctx.channel().remoteAddress(); if (addr != null) { address = vertx.transport().convert(addr); remoteAddress = address; } } return address; }

Target:
public SocketAddress remoteAddress() { SocketAddress address = remoteAddress; if (address == null) { if (chctx.channel().hasAttr(REMOTE_ADDRESS_OVERRIDE)) { address = chctx.channel().attr(REMOTE_ADDRESS_OVERRIDE).getAndSet(null); } else { java.net.SocketAddress addr = chctx.channel().remoteAddress(); if (addr != null) { address = vertx.transport().convert(addr); } } if (address != null) remoteAddress = address; } return address; }
Source:
protected List<String> getEnabledProtocols() { return getAttribute(JavaWebAppSoftwareProcessImpl.ENABLED_PROTOCOLS); }

Target:
protected Set<String> getEnabledProtocols() { return getAttribute(JavaWebAppSoftwareProcess.ENABLED_PROTOCOLS); }
Source:
public Mono<CosmosAsyncContainerResponse> replace( CosmosContainerProperties containerProperties, CosmosContainerRequestOptions options) { ModelBridgeInternal.validateResource(containerProperties); if (options == null) { options = new CosmosContainerRequestOptions(); } final CosmosContainerRequestOptions requestOptions = options; return withContext(context -> replace(containerProperties, requestOptions, context)).subscriberContext(reactorContext -> { Optional<String> master = reactorContext.getOrEmpty(TracerProvider.MASTER_CALL); if (master.isPresent()) { reactorContext = reactorContext.put(TracerProvider.NESTED_CALL, true); } return reactorContext.put(TracerProvider.MASTER_CALL, true); }); }

Target:
public Mono<CosmosContainerResponse> replace( CosmosContainerProperties containerProperties, CosmosContainerRequestOptions options) { if (options == null) { options = new CosmosContainerRequestOptions(); } if(!database.getClient().getTracerProvider().isEnabled()) { return replaceInternal(containerProperties, options); } final CosmosContainerRequestOptions requestOptions = options; return withContext(context -> replaceInternal(containerProperties, requestOptions, context)); }
Source:
public boolean withinBounds() { if (!baseOffset.withinBounds()) { return false; } if (allWithinThreshold) { return true; } long current = timestamps.getLongSingleValueRow(baseOffset.getOffset()); return current >= timeStart && current < timeEnd; }

Target:
public boolean withinBounds() { if (!baseOffset.withinBounds()) { return false; } if (allWithinThreshold) { return true; } return timeInRange(timestamps.getLongSingleValueRow(baseOffset.getOffset())); }
Source:
public Response recreateToken() { User u; try { u = findUserOrDie(); } catch (WrappedResponse ex) { return ex.getResponse(); } AuthenticatedUser au; try{ au = (AuthenticatedUser) u; } catch (ClassCastException e){ return notFound("Token for " + u.getIdentifier() + " not found."); } if (au == null) { return notFound("Token for " + u.getIdentifier() + " not found."); } authSvc.removeApiToken(au); ApiToken newToken = authSvc.generateApiTokenForUser(au); authSvc.save(newToken); return ok("New token for " + au.getUserIdentifier() + " is " + newToken.getTokenString()); }

Target:
public Response recreateToken() { User u; try { u = findUserOrDie(); } catch (WrappedResponse ex) { return ex.getResponse(); } AuthenticatedUser au; try{ au = (AuthenticatedUser) u; } catch (ClassCastException e){ return notFound("Token for " + u.getIdentifier() + " is not eligible for recreation."); } authSvc.removeApiToken(au); ApiToken newToken = authSvc.generateApiTokenForUser(au); authSvc.save(newToken); return ok("New token for " + au.getUserIdentifier() + " is " + newToken.getTokenString()); }
Source:
public void showAllergens(List<AllergenName> allergens) { if (allergens.isEmpty()) { return; } if (!product.getStatesTags().contains("en:ingredients-completed")) { productAllergenAlert.setText(R.string.product_incomplete_message); productAllergenAlertLayout.setVisibility(View.VISIBLE); return; } Set<String> productAllergens = new HashSet<>(product.getAllergensHierarchy()); productAllergens.addAll(product.getTracesTags()); List<String> allergenMatch = new ArrayList<>(); for (AllergenName allergenName : allergens) { if (productAllergens.contains(allergenName.getAllergenTag())) { allergenMatch.add(allergenName.getName()); } } if (allergenMatch.isEmpty()) { return; } StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append( String.format("%s\n", getResources().getString(R.string.product_allergen_prompt))); boolean first = true; for (String allergenName : allergenMatch) { String formattedAllergen; if (first) { formattedAllergen = allergenName; } else { formattedAllergen = String.format(", %s", allergenName); } stringBuilder.append(formattedAllergen); first = false; } productAllergenAlert.setText(stringBuilder.toString()); productAllergenAlertLayout.setVisibility(View.VISIBLE); }

Target:
public void showAllergens(List<AllergenName> allergens) { if (allergens.isEmpty()) { return; } if (!product.getStatesTags().contains("en:complete")) { productAllergenAlert.setText(R.string.product_incomplete_message); productAllergenAlertLayout.setVisibility(View.VISIBLE); return; } Set<String> productAllergens = new HashSet<>(product.getAllergensHierarchy()); productAllergens.addAll(product.getTracesTags()); List<String> allergenMatch = new ArrayList<>(); for (AllergenName allergenName : allergens) { if (productAllergens.contains(allergenName.getAllergenTag())) { allergenMatch.add(allergenName.getName()); } } if (allergenMatch.isEmpty()) { return; } StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append( String.format("%s\n", getResources().getString(R.string.product_allergen_prompt))); boolean first = true; for (String allergenName : allergenMatch) { String formattedAllergen; if (first) { formattedAllergen = allergenName; } else { formattedAllergen = String.format(", %s", allergenName); } stringBuilder.append(formattedAllergen); first = false; } productAllergenAlert.setText(stringBuilder.toString()); productAllergenAlertLayout.setVisibility(View.VISIBLE); }
Source:
private void createGroupIfNecessary(InternalResourceGroup resourceGroup, Executor executor, int version) { synchronized (lockObj) { if (resourceGroup.getVersion() == version) { return; } InternalResourceGroup newGroup; ResourceGroupId resourceGroupId = resourceGroup.getId(); if (resourceGroupId.getParent().isPresent()) { createGroupIfNecessary(groups.get(resourceGroupId.getParent().get()).getLatest(), executor, version); InternalResourceGroup parent = groups.get(resourceGroupId.getParent().get()).getLatest(); newGroup = parent.getOrCreateSubGroup(resourceGroupId.getLastSegment(), version); } else { RootInternalResourceGroup newRootVersion = new RootInternalResourceGroup(resourceGroup.getId().getSegments().get(0), this::exportGroup, executor, resourceGroup.getRoot(), version); newGroup = newRootVersion; } configurationManager.get().configure(newGroup); resourceGroup.setNext(newGroup); newGroup.setPrev(resourceGroup); } }

Target:
private void createGroupIfNecessary(InternalResourceGroup resourceGroup, Executor executor, int version) { synchronized (this) { if (resourceGroup.getVersion() == version) { return; } InternalResourceGroup newGroup; ResourceGroupId resourceGroupId = resourceGroup.getId(); if (resourceGroupId.getParent().isPresent()) { createGroupIfNecessary(groups.get(resourceGroupId.getParent().get()).getLatest(), executor, version); InternalResourceGroup parent = groups.get(resourceGroupId.getParent().get()).getLatest(); newGroup = parent.getOrCreateSubGroup(resourceGroupId.getLastSegment(), resourceGroup.isStaticResourceGroup(), version); } else { newGroup = new RootInternalResourceGroup(resourceGroup.getId().getSegments().get(0), this::exportGroup, executor, resourceGroup.getRoot(), version); } configurationManager.get().configure(newGroup); resourceGroup.setNext(newGroup); newGroup.setPrev(resourceGroup); groups.put(resourceGroupId, newGroup); } }
Source:
public InputStream getAttachmentData(String attachmentId, IProgressMonitor monitor) throws IOException, CoreException { String url = repositoryUrl + IBugzillaConstants.URL_GET_ATTACHMENT_DOWNLOAD + attachmentId; GetMethod method = getConnect(url, monitor); try { if (method.getStatusCode() == HttpStatus.SC_OK) { Header contentDisposition = method.getResponseHeader("Content-disposition"); if (contentDisposition == null) { parseHtmlError(method.getResponseBodyAsStream()); throw new CoreException( new Status( IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN, "No Exception from parseHtmlError, should throw an Exception" + method.getResponseBodyAsStream())); } return method.getResponseBodyAsStream(); } else { parseHtmlError(method.getResponseBodyAsStream()); throw new CoreException( new Status( IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN, "No Exception from parseHtmlError, should throw an Exception" + method.getResponseBodyAsStream())); } } catch (Exception e) { WebUtil.releaseConnection(method, monitor); throw new CoreException(new Status(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN, "Unable to retrieve attachment", e)); } }

Target:
public InputStream getAttachmentData(String attachmentId, IProgressMonitor monitor) throws IOException, CoreException { String url = repositoryUrl + IBugzillaConstants.URL_GET_ATTACHMENT_DOWNLOAD + attachmentId; GetMethod method = getConnect(url, monitor); Status status = null; try { if (method.getStatusCode() == HttpStatus.SC_OK) { Header contentDisposition = method.getResponseHeader("Content-disposition"); if (contentDisposition == null) { status = parseHtmlError(method.getResponseBodyAsStream()); } else { return method.getResponseBodyAsStream(); } } else { status = parseHtmlError(method.getResponseBodyAsStream()); } } catch (Exception e) { status = new Status(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN, "Unable to retrieve attachment", e); } finally { WebUtil.releaseConnection(method, monitor); if (status != null) { throw new CoreException(status); } } return null; }
Source:
public static Node getNodeBySystemSession(Node node) throws RepositoryException { node.getSession().save(); SessionProvider systemSessionProvider = getSystemSessionProvider(); return (Node) systemSessionProvider.getSession(node.getSession().getWorkspace().getName(), getRepository()) .getItem(node.getPath()); }

Target:
public static Node getNodeBySystemSession(Node node) throws RepositoryException { SessionProvider systemSessionProvider = getSystemSessionProvider(); return (Node) systemSessionProvider.getSession(node.getSession().getWorkspace().getName(), getRepository()) .getItem(node.getPath()); }
Source:
public IllegalTableTransitionException(TableState oldState, TableState newState, String message) { this.oldState = oldState; this.newState = newState; String defaultMessage = "Error transitioning from " + oldState + " state to " + newState + " state"; if (message != null && !message.isEmpty()) this.message = message; else this.message = defaultMessage; }

Target:
public IllegalTableTransitionException(TableState oldState, TableState newState, String message) { this.oldState = oldState; this.newState = newState; if (StringUtils.isNotEmpty(message)) this.message = message; else { String defaultMessage = "Error transitioning from " + oldState + " state to " + newState + " state"; this.message = defaultMessage; } }
Source:
public final String consoleClientResourcesUrl() { String url = getString(DynamicMessageKey.CONSOLE_CLIENT_RESOURCES_URL); boolean isAbsolute = url.contains("://"); return isAbsolute ? url : "/" + BaseContextPathData.getInstance().getRelativePath() + url; }

Target:
public final String consoleClientResourcesUrl() { String url = getString(DynamicMessageKey.CONSOLE_CLIENT_RESOURCES_URL); boolean isAbsolute = UriUtils.extractScheme(url) != null; return isAbsolute ? url : "/" + BaseContextPathData.getInstance().getRelativePath() + url; }
Source:
protected void index() { List<WorkQueueDescriptor> descriptors = getDescriptors(QUEUES_EP); descriptors.forEach(d -> d.categories.forEach(c -> { categoryToQueueId.putIfAbsent(c, d.getId()); categoryToQueueId.computeIfPresent(c, (k, v) -> { if (!v.equals(d.getId())) { getLog().error("Work category '" + c + "' cannot be assigned to work queue '" + d.getId() + "' because it is already assigned to work queue '" + v + "'"); } return v; }); })); }

Target:
protected void index() { List<WorkQueueDescriptor> descriptors = getDescriptors(QUEUES_EP); descriptors.forEach(d -> d.categories.forEach(c -> { categoryToQueueId.computeIfPresent(c, (k, v) -> { if (!v.equals(d.getId())) { getLog().error("Work category '" + c + "' cannot be assigned to work queue '" + d.getId() + "' because it is already assigned to work queue '" + v + "'"); } return v; }); categoryToQueueId.putIfAbsent(c, d.getId()); })); }
Source:
public <V extends Visualization> V getVisualization(String identifier, Class<V> visualizationClass) { Visualization vis = getVisualizationInternal(identifier); if (!visualizationClass.isInstance(vis)) { throw new IllegalArgumentException("Visualization identified by " + identifier + " is not of expected type " + visualizationClass.getName() + " but of type " + vis.getClass().getName()); } return (V) vis; }

Target:
public <V extends Visualization> V getVisualization(String identifier, Class<V> visualizationClass) { Visualization vis = getVisualizationInternal(identifier); if (!visualizationClass.isInstance(vis)) { throw new IllegalArgumentException("Visualization identified by " + identifier + " is not of expected type " + visualizationClass.getName() + " but of type " + vis.getClass().getName()); } return visualizationClass.cast(vis); }
Source:
private void startBranchComparison(RayMessage msg) { VKmer id = getVertexId(); RayValue vertex = getVertexValue(); if (vertex.visited) { vertex.intersection = true; vertex.stopSearch = true; return; } vertex.visited = true; vertex.flippedFromInitialDirection = msg.isCandidateFlipped(); DIR nextDir = msg.getEdgeTypeBackToFrontier().mirror().neighborDir(); msg.visitNode(id, vertex); if (vertex.degree(nextDir) == 0) { return; } else if (vertex.degree(nextDir) == 1) { NeighborInfo next = vertex.getSingleNeighbor(nextDir); msg.setEdgeTypeBackToFrontier(next.et.mirror()); msg.setFrontierFlipped(vertex.flippedFromInitialDirection); sendMsg(next.kmer, msg); } else { msg.setMessageType(RayMessageType.REQUEST_KMER); msg.setFrontierFlipped(vertex.flippedFromInitialDirection); msg.setSourceVertexId(id); for (EDGETYPE et : nextDir.edgeTypes()) { for (VKmer next : vertex.getEdges(et)) { msg.setEdgeTypeBackToFrontier(et.mirror()); sendMsg(next, msg); } } } }

Target:
private void startBranchComparison(RayMessage msg) { VKmer id = getVertexId(); RayValue vertex = getVertexValue(); if (vertex.visited) { vertex.intersection = true; vertex.stopSearch = true; LOG.info("start branch comparison had to stop at " + id + " with total length " + msg.getWalkLength()); return; } vertex.visited = true; vertex.flippedFromInitialDirection = msg.isCandidateFlipped(); DIR nextDir = msg.getEdgeTypeBackToFrontier().mirror().neighborDir(); msg.visitNode(id, vertex); if (vertex.degree(nextDir) == 0) { LOG.info("reached dead end at " + id + " with total length " + msg.getWalkLength()); return; } else if (vertex.degree(nextDir) == 1) { NeighborInfo next = vertex.getSingleNeighbor(nextDir); msg.setEdgeTypeBackToFrontier(next.et.mirror()); msg.setFrontierFlipped(vertex.flippedFromInitialDirection); sendMsg(next.kmer, msg); LOG.info("bouncing over path node: " + id); } else { msg.setMessageType(RayMessageType.REQUEST_KMER); msg.setFrontierFlipped(vertex.flippedFromInitialDirection); msg.setSourceVertexId(id); for (EDGETYPE et : nextDir.edgeTypes()) { for (VKmer next : vertex.getEdges(et)) { msg.setEdgeTypeBackToFrontier(et.mirror()); sendMsg(next, msg); LOG.info("evaluating branch: " + next); } } } }
Source:
public SyslogProcessor call() { try { LOG.debug("Converting syslog message into event ({} bytes)", m_bytes.remaining()); try { SyslogdIPMgrJDBCImpl.getInstance().dataSourceSync(); } catch (SQLException e) { LOG.debug("Database Sync failed"); } ConvertToEvent re = new ConvertToEvent( m_systemId, m_sourceAddress, m_port, StandardCharsets.US_ASCII.decode(m_bytes).toString(), m_config ); LOG.debug("Sending syslog event to the SyslogProcessor queue"); return new SyslogProcessor(re.getEvent(), m_config.getNewSuspectOnMessage()); } catch (final UnsupportedEncodingException e) { LOG.info("Failure to convert package", e); } catch (final MessageDiscardedException e) { LOG.info("Message discarded, returning without enqueueing event.", e); } catch (final Throwable e) { LOG.error("Unexpected exception while processing SyslogConnection", e); } return null; }

Target:
public SyslogProcessor call() { try { LOG.debug("Converting syslog message into event ({} bytes)", m_bytes.remaining()); ConvertToEvent re = new ConvertToEvent( m_systemId, m_location, m_sourceAddress, m_port, StandardCharsets.US_ASCII.decode(m_bytes).toString(), m_config ); LOG.debug("Sending syslog event to the SyslogProcessor queue"); return new SyslogProcessor(re.getEvent(), m_config.getNewSuspectOnMessage()); } catch (final UnsupportedEncodingException e) { LOG.info("Failure to convert package", e); } catch (final MessageDiscardedException e) { LOG.info("Message discarded, returning without enqueueing event.", e); } catch (final Throwable e) { LOG.error("Unexpected exception while processing SyslogConnection", e); } return null; }
Source:
public void onSearch(String query, SuggestionAnimation suggestionAnimation) { storeQuery(query); ((PostSearchFragment) getSupportFragmentManager().findFragmentById(R.id.postsearch)) .setUrl("<LINK_0>" + Uri.encode(query)); if (suggestionAnimation != null) { animateSuggestion(query, suggestionAnimation); } else { startPostsearch(); } }

Target:
public void onSearch(String query, SuggestionAnimation suggestionAnimation) { storeQuery(query); ((PostSearchFragment) getSupportFragmentManager().findFragmentById(R.id.postsearch)) .startSearch(query); if (suggestionAnimation != null) { animateSuggestion(query, suggestionAnimation); } else { startPostsearch(); } }