ronantakizawa/codereview-bench huggingface dataset:
Repository: paritytech/substrate
File: core/consensus/slots/src/aux_schema.rs (Rust)

Code before:
		// A proof of equivocation consists of two headers:
		// 1) signed by the same voter,
		if *prev_signer == signer {
			// 2) with different hash
			if header.hash() != prev_header.hash() {
				return Ok(Some(EquivocationProof {
					slot, // 3) and mentioning the same slot.
					fst_header: prev_header.clone(),
					snd_header: header.clone(),
				}));
			} else {
				//  We don't need to continue in case of duplicated header,
				// since it's already saved and a possible equivocation
				// would have been detected before.
				return Ok(None)
			}
		}
	}

	let mut keys_to_delete = vec![];

	if slot_now % PRUNING_BOUND == 0 {
		let prefix = SLOT_HEADER_MAP_KEY.to_vec();

		let first_slot = slot_now - PRUNING_BOUND;
		let last_slot = slot_now - MAX_SLOT_CAPACITY;
		for s in first_slot..last_slot {
			let mut p = prefix.clone();
			s.using_encoded(|s| p.extend(s));
			keys_to_delete.push(p);
		}
	}

	headers_with_sig.push((header, signer));

	backend.insert_aux(
		&[(&curr_slot_key[..], headers_with_sig.encode().as_slice())],
		&keys_to_delete.iter().map(|k| &k[..]).collect::<Vec<&[u8]>>()[..],
	)?;

	Ok(None)
}


Review comment (suggestion):
```suggestion
		let last_slot = slot_now.saturating_sub(MAX_SLOT_CAPACITY);
```

Code after:
	// Get headers of this slot.
	let mut headers_with_sig = load_decode::<_, Vec<(H, P)>>(backend.clone(), &curr_slot_key[..])?
		.unwrap_or_else(Vec::new);

	// Get first slot saved.
	let slot_header_start = SLOT_HEADER_START.to_vec();
	let first_saved_slot = load_decode::<_, u64>(backend.clone(), &slot_header_start[..])?
		.unwrap_or(slot);

	for (prev_header, prev_signer) in headers_with_sig.iter() {
		// A proof of equivocation consists of two headers:
		// 1) signed by the same voter,
		if *prev_signer == signer {
			// 2) with different hash
			if header.hash() != prev_header.hash() {
				return Ok(Some(EquivocationProof {
					slot, // 3) and mentioning the same slot.
					fst_header: prev_header.clone(),
					snd_header: header.clone(),
				}));
			} else {
				//  We don't need to continue in case of duplicated header,
				// since it's already saved and a possible equivocation
				// would have been detected before.
				return Ok(None)
			}
		}
	}

	let mut keys_to_delete = vec![];
	let mut new_first_saved_slot = first_saved_slot;

	if slot_now - first_saved_slot >= PRUNING_BOUND {
		let prefix = SLOT_HEADER_MAP_KEY.to_vec();
		new_first_saved_slot = slot_now.saturating_sub(MAX_SLOT_CAPACITY);

		for s in first_saved_slot..new_first_saved_slot {
			let mut p = prefix.clone();
			s.using_encoded(|s| p.extend(s));
			keys_to_delete.push(p);
		}
	}

	headers_with_sig.push((header, signer));

	backend.insert_aux(
		&[
			(&curr_slot_key[..], headers_with_sig.encode().as_slice()),
			(&slot_header_start[..], new_first_saved_slot.encode().as_slice()),
		],
		&keys_to_delete.iter().map(|k| &k[..]).collect::<Vec<&[u8]>>()[..],
Repository: paritytech/substrate
File: client/network/src/service/out_events.rs (Rust)

Code before:
			}))
		}
	}

	/// Adds a new [`Sender`] to the collection.
	pub fn push(&mut self, sender: Sender) {
		let mut stats = sender.stats.lock();
		debug_assert!(stats.is_none());
		*stats = Some(self.stats.clone());
		drop(stats);
		self.event_streams.push(sender);
	}

	/// Returns the number of senders in the collection.
	pub fn len(&self) -> usize {
		self.event_streams.len()
	}

	/// Sends an event.
	pub fn send(&mut self, event: Event) {
		self.event_streams.retain(|sender| {
			sender.inner.unbounded_send(event.clone()).is_ok()
		});

		// The number of elements remaining in `event_streams` corresponds to the number of times
		// we have sent an element on the channel.
		let mut stats = self.stats.lock();
		for _ in 0..self.event_streams.len() {
			increase_stats(&mut stats, &event);
		}
	}

	/// Returns statistics about the content of the channel.
	///
	/// > **Important**: This function returns a mutex lock. As long as it is not disposed of,
	/// >				 receivers will block receiving any message.
	pub fn lock_stats<'a>(&'a self) -> impl Deref<Target = StatsCollect> + 'a {
		self.stats.lock()
	}
}

impl fmt::Debug for OutChannels {
	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
		f.debug_struct("OutChannels")
			.field("num_channels", &self.event_streams.len())
			.finish()
	}
}

fn increase_stats(stats: &mut StatsCollect, event: &Event) {
	match event {

Review comment (suggestion):
```suggestion
		// we have sent an element on the channels.
```

Code after:
		drop(metrics);
		self.event_streams.push(sender);

		if let Some(metrics) = &*self.metrics {
			metrics.num_channels.inc();
		}
	}

	/// Sends an event.
	pub fn send(&mut self, event: Event) {
		self.event_streams.retain(|sender| {
			sender.inner.unbounded_send(event.clone()).is_ok()
		});

		if let Some(metrics) = &*self.metrics {
			metrics.event_in(&event, self.event_streams.len() as u64);
		}
	}
}

impl fmt::Debug for OutChannels {
	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
		f.debug_struct("OutChannels")
			.field("num_channels", &self.event_streams.len())
			.finish()
	}
}

struct Metrics {
	// This list is ordered alphabetically
	events_total: CounterVec<U64>,
	notifications_sizes: CounterVec<U64>,
	num_channels: Gauge<U64>,
}

impl Metrics {
	fn register(registry: &Registry) -> Result<Self, PrometheusError> {
		Ok(Self {
			events_total: register(CounterVec::new(
				Opts::new(
					"sub_libp2p_out_events_events_total",
					"Number of broadcast network events that have been sent or received across all \
					 channels"
				),
				&["event_name", "action"]
			)?, registry)?,
			notifications_sizes: register(CounterVec::new(
				Opts::new(
					"sub_libp2p_out_events_notifications_sizes",
					"Size of notification events that have been sent or received across all \
					 channels"
Repository: paritytech/substrate
File: frame/system/src/lib.rs (Rust)

Code before:
		o.into().and_then(|o| match o {
			RawOrigin::None => Ok(()),
			r => Err(O::from(r)),
		})
	}

	#[cfg(feature = "runtime-benchmarks")]
	fn successful_origin() -> O {
		O::from(RawOrigin::None)
	}
}

pub struct EnsureNever<T>(sp_std::marker::PhantomData<T>);
impl<O, T> EnsureOrigin<O> for EnsureNever<T> {
	type Success = T;
	fn try_origin(o: O) -> Result<Self::Success, O> {
		Err(o)
	}

	#[cfg(feature = "runtime-benchmarks")]
	fn successful_origin() -> O {
		unimplemented!()
	}
}

pub struct EnsureOneOf<AccountId, A, B>(A, B, sp_std::marker::PhantomData<AccountId>);
impl<
	AccountId,
	O: Into<Result<RawOrigin<AccountId>, O>> + From<RawOrigin<AccountId>>,
	A: EnsureOrigin<O>,
	B: EnsureOrigin<O>,
> EnsureOrigin<O> for EnsureOneOf<AccountId, A, B> {
	type Success = ();
	fn try_origin(o: O) -> Result<Self::Success, O> {
		A::try_origin(o).map_or_else(
			|o| B::try_origin(o).map(|_| ()),
			|_| Ok(()),
		)
	}

	#[cfg(feature = "runtime-benchmarks")]
	fn successful_origin() -> O {
		A::successful_origin()
	}
}

/// Ensure that the origin `o` represents a signed extrinsic (i.e. transaction).
/// Returns `Ok` with the account that signed the extrinsic or an `Err` otherwise.
pub fn ensure_signed<OuterOrigin, AccountId>(o: OuterOrigin) -> Result<AccountId, BadOrigin>
	where OuterOrigin: Into<Result<RawOrigin<AccountId>, OuterOrigin>>
{

Review comment (bug):
Docs are missing. 

You don't need `AccountId` as generic parameter here:
https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=52be76900f8b1dc497681e1c1e33f352


Code after:
		o.into().and_then(|o| match o {
			RawOrigin::None => Ok(()),
			r => Err(O::from(r)),
		})
	}

	#[cfg(feature = "runtime-benchmarks")]
	fn successful_origin() -> O {
		O::from(RawOrigin::None)
	}
}

pub struct EnsureNever<T>(sp_std::marker::PhantomData<T>);
impl<O, T> EnsureOrigin<O> for EnsureNever<T> {
	type Success = T;
	fn try_origin(o: O) -> Result<Self::Success, O> {
		Err(o)
	}

	#[cfg(feature = "runtime-benchmarks")]
	fn successful_origin() -> O {
		unimplemented!()
	}
}

/// The "OR gate" implementation of `EnsureOrigin`.
///
/// Origin check will pass if `L` or `R` origin check passes. `L` is tested first.
pub struct EnsureOneOf<AccountId, L, R>(sp_std::marker::PhantomData<(AccountId, L, R)>);
impl<
	AccountId,
	O: Into<Result<RawOrigin<AccountId>, O>> + From<RawOrigin<AccountId>>,
	L: EnsureOrigin<O>,
	R: EnsureOrigin<O>,
> EnsureOrigin<O> for EnsureOneOf<AccountId, L, R> {
	type Success = Either<L::Success, R::Success>;
	fn try_origin(o: O) -> Result<Self::Success, O> {
		L::try_origin(o).map_or_else(
			|o| R::try_origin(o).map(|o| Either::Right(o)),
			|o| Ok(Either::Left(o)),
		)
	}

	#[cfg(feature = "runtime-benchmarks")]
	fn successful_origin() -> O {
		L::successful_origin()
	}
}

/// Ensure that the origin `o` represents a signed extrinsic (i.e. transaction).
/// Returns `Ok` with the account that signed the extrinsic or an `Err` otherwise.
Repository: paritytech/substrate
File: frame/system/src/lib.rs (Rust)

Code before:
	fn successful_origin() -> O {
		O::from(RawOrigin::None)
	}
}

pub struct EnsureNever<T>(sp_std::marker::PhantomData<T>);
impl<O, T> EnsureOrigin<O> for EnsureNever<T> {
	type Success = T;
	fn try_origin(o: O) -> Result<Self::Success, O> {
		Err(o)
	}

	#[cfg(feature = "runtime-benchmarks")]
	fn successful_origin() -> O {
		unimplemented!()
	}
}

pub struct EnsureOneOf<AccountId, A, B>(A, B, sp_std::marker::PhantomData<AccountId>);
impl<
	AccountId,
	O: Into<Result<RawOrigin<AccountId>, O>> + From<RawOrigin<AccountId>>,
	A: EnsureOrigin<O>,
	B: EnsureOrigin<O>,
> EnsureOrigin<O> for EnsureOneOf<AccountId, A, B> {
	type Success = ();
	fn try_origin(o: O) -> Result<Self::Success, O> {
		A::try_origin(o).map_or_else(
			|o| B::try_origin(o).map(|_| ()),
			|_| Ok(()),
		)
	}

	#[cfg(feature = "runtime-benchmarks")]
	fn successful_origin() -> O {
		A::successful_origin()
	}
}

/// Ensure that the origin `o` represents a signed extrinsic (i.e. transaction).
/// Returns `Ok` with the account that signed the extrinsic or an `Err` otherwise.
pub fn ensure_signed<OuterOrigin, AccountId>(o: OuterOrigin) -> Result<AccountId, BadOrigin>
	where OuterOrigin: Into<Result<RawOrigin<AccountId>, OuterOrigin>>
{
	match o.into() {
		Ok(RawOrigin::Signed(t)) => Ok(t),
		_ => Err(BadOrigin),
	}
}

/// Ensure that the origin `o` represents the root. Returns `Ok` or an `Err` otherwise.

Review comment (suggestion):
I would change this `Success` to:

```
enum Either<L, R> {
    Left(L),
    Right(R),
}

type Success = Either<A::Success, B::Success>;
```

Code after:
	fn successful_origin() -> O {
		O::from(RawOrigin::None)
	}
}

pub struct EnsureNever<T>(sp_std::marker::PhantomData<T>);
impl<O, T> EnsureOrigin<O> for EnsureNever<T> {
	type Success = T;
	fn try_origin(o: O) -> Result<Self::Success, O> {
		Err(o)
	}

	#[cfg(feature = "runtime-benchmarks")]
	fn successful_origin() -> O {
		unimplemented!()
	}
}

/// The "OR gate" implementation of `EnsureOrigin`.
///
/// Origin check will pass if `L` or `R` origin check passes. `L` is tested first.
pub struct EnsureOneOf<AccountId, L, R>(sp_std::marker::PhantomData<(AccountId, L, R)>);
impl<
	AccountId,
	O: Into<Result<RawOrigin<AccountId>, O>> + From<RawOrigin<AccountId>>,
	L: EnsureOrigin<O>,
	R: EnsureOrigin<O>,
> EnsureOrigin<O> for EnsureOneOf<AccountId, L, R> {
	type Success = Either<L::Success, R::Success>;
	fn try_origin(o: O) -> Result<Self::Success, O> {
		L::try_origin(o).map_or_else(
			|o| R::try_origin(o).map(|o| Either::Right(o)),
			|o| Ok(Either::Left(o)),
		)
	}

	#[cfg(feature = "runtime-benchmarks")]
	fn successful_origin() -> O {
		L::successful_origin()
	}
}

/// Ensure that the origin `o` represents a signed extrinsic (i.e. transaction).
/// Returns `Ok` with the account that signed the extrinsic or an `Err` otherwise.
pub fn ensure_signed<OuterOrigin, AccountId>(o: OuterOrigin) -> Result<AccountId, BadOrigin>
	where OuterOrigin: Into<Result<RawOrigin<AccountId>, OuterOrigin>>
{
	match o.into() {
		Ok(RawOrigin::Signed(t)) => Ok(t),
		_ => Err(BadOrigin),
	}
Repository: paritytech/substrate
File: frame/election-provider-multi-phase/src/unsigned.rs (Rust)

Code before:
		})
	}

	#[test]
	fn ocw_can_submit_to_pool() {
		let (mut ext, pool) = ExtBuilder::default().build_offchainify(0);
		ext.execute_with(|| {
			roll_to_with_ocw(25);
			assert_eq!(MultiPhase::current_phase(), Phase::Unsigned((true, 25)));
			// OCW must have submitted now

			let encoded = pool.read().transactions[0].clone();
			let extrinsic: Extrinsic = Decode::decode(&mut &*encoded).unwrap();
			let call = extrinsic.call;
			assert!(matches!(call, OuterCall::MultiPhase(Call::submit_unsigned(_, _))));
		})
	}

	#[test]
	fn trim_compact_length_does_not_modify_when_short_enough() {
		let (mut ext, _) = ExtBuilder::default().build_offchainify(0);
		ext.execute_with(|| {
			roll_to(25);

			let RoundSnapshot { voters, ..} =
				MultiPhase::snapshot().unwrap();

			let RawSolution { mut compact, .. } = raw_solution();
			let encoded_len = compact.encode().len() as u32;
			let compact_clone = compact.clone();

			compact = MultiPhase::trim_compact_length(
				encoded_len,
				compact,
				voter_index_fn_linear::<Runtime>(&voters),
			).unwrap();

			assert_eq!(compact, compact_clone);
		});
	}

	#[test]
	fn trim_compact_length_modifies_when_too_long() {
		let (mut ext, _) = ExtBuilder::default().build_offchainify(0);
		ext.execute_with(|| {
			roll_to(25);

			let RoundSnapshot { voters, ..} =
				MultiPhase::snapshot().unwrap();

			let RawSolution { mut compact, .. } = raw_solution();

Review comment (suggestion):
```suggestion
			let RoundSnapshot { voters, ..} = MultiPhase::snapshot().unwrap();
```

Code after:

			MultiPhase::offchain_worker(24);
			assert!(pool.read().transactions.len().is_zero());
			storage.clear();

			MultiPhase::offchain_worker(26);
			assert!(pool.read().transactions.len().is_zero());
			storage.clear();

			// submits!
			MultiPhase::offchain_worker(25);
			assert!(!pool.read().transactions.len().is_zero());
		})
	}

	#[test]
	fn ocw_can_submit_to_pool() {
		let (mut ext, pool) = ExtBuilder::default().build_offchainify(0);
		ext.execute_with(|| {
			roll_to_with_ocw(25);
			assert_eq!(MultiPhase::current_phase(), Phase::Unsigned((true, 25)));
			// OCW must have submitted now

			let encoded = pool.read().transactions[0].clone();
			let extrinsic: Extrinsic = Decode::decode(&mut &*encoded).unwrap();
			let call = extrinsic.call;
			assert!(matches!(call, OuterCall::MultiPhase(Call::submit_unsigned(_, _))));
		})
	}

	#[test]
	fn trim_compact_length_does_not_modify_when_short_enough() {
		let mut ext = ExtBuilder::default().build();
		ext.execute_with(|| {
			roll_to(25);

			// given
			let RoundSnapshot { voters, ..} = MultiPhase::snapshot().unwrap();
			let RawSolution { mut compact, .. } = raw_solution();
			let encoded_len = compact.encode().len() as u32;
			let compact_clone = compact.clone();

			// when
			assert!(encoded_len < <Runtime as Config>::MinerMaxLength::get());

			// then
			compact = MultiPhase::trim_compact_length(
				encoded_len,
				compact,
				voter_index_fn_linear::<Runtime>(&voters),
			).unwrap();
Repository: paritytech/substrate
File: primitives/trie/src/storage_proof.rs (Rust)

Code before:
}

impl CompactProof {
	/// Return an iterator on the compact encoded nodes.
	pub fn iter_compact_encoded_nodes(&self) -> impl Iterator<Item = &[u8]> {
		self.encoded_nodes.iter().map(Vec::as_slice)
	}

	/// Returns the estimated encoded size of the compact proof.
	///
	/// Runing this operation is a slow operation (build the whole compact proof) and should only be
	/// in non sensitive path.
	/// Return `None` on error.
	pub fn encoded_compact_size<H: Hasher>(
		proof: StorageProof,
		root: H::Out,
	) -> Option<usize> {
		let compact_proof = crate::encode_compact::<crate::Layout<H>>(
			proof,
			root,
		);
		if let Ok(proof) = compact_proof {
			Some(proof.encoded_size())
		} else {
			None
		}
	}
}

/// An iterator over trie nodes constructed from a storage proof. The nodes are not guaranteed to
/// be traversed in any particular order.
pub struct StorageProofNodeIterator {
	inner: <Vec<Vec<u8>> as IntoIterator>::IntoIter,
}

impl StorageProofNodeIterator {
	fn new(proof: StorageProof) -> Self {
		StorageProofNodeIterator {
			inner: proof.trie_nodes.into_iter(),
		}
	}
}

impl Iterator for StorageProofNodeIterator {
	type Item = Vec<u8>;

	fn next(&mut self) -> Option<Self::Item> {
		self.inner.next()
	}
}


Review comment (suggestion):
```suggestion
		compact_proof.ok().map(|p| p.encoded_size())
```

Code after:

	/// Encode as a compact proof with default
	/// trie layout.
	pub fn into_compact_proof<H: Hasher>(
		self,
		root: H::Out,
	) -> Result<CompactProof, crate::CompactProofError<crate::Layout<H>>> {
		crate::encode_compact::<crate::Layout<H>>(self, root)
	}
	
	/// Returns the estimated encoded size of the compact proof.
	///
	/// Runing this operation is a slow operation (build the whole compact proof) and should only be
	/// in non sensitive path.
	/// Return `None` on error.
	pub fn encoded_compact_size<H: Hasher>(self, root: H::Out) -> Option<usize> {
		let compact_proof = self.into_compact_proof::<H>(root);
		compact_proof.ok().map(|p| p.encoded_size())
	}

}

impl CompactProof {
	/// Return an iterator on the compact encoded nodes.
	pub fn iter_compact_encoded_nodes(&self) -> impl Iterator<Item = &[u8]> {
		self.encoded_nodes.iter().map(Vec::as_slice)
	}

	/// Decode to a full storage_proof.
	///
	/// Method use a temporary `HashDB`, and `sp_trie::decode_compact`
	/// is often better.
	pub fn to_storage_proof<H: Hasher>(
		&self,
		expected_root: Option<&H::Out>,
	) -> Result<(StorageProof, H::Out), crate::CompactProofError<crate::Layout<H>>> {
		let mut db = crate::MemoryDB::<H>::new(&[]);
		let root = crate::decode_compact::<crate::Layout<H>, _, _>(
			&mut db,
			self.iter_compact_encoded_nodes(),
			expected_root,
		)?;
		Ok((StorageProof::new(db.drain().into_iter().filter_map(|kv|
			if (kv.1).1 > 0 {
				Some((kv.1).0)
			} else {
				None
			}
		).collect()), root))
	}
}
Repository: paritytech/substrate
File: frame/authority-discovery/src/lib.rs (Rust)

Code before:
		keys.extend(next);
		keys.sort();
		keys.dedup();

		keys.to_vec()
	}

	/// Retrieve authority identifiers of the current authority set in the original order.
	pub fn current_authorities() -> BoundedVec<AuthorityId, T::MaxAuthorities> {
		Keys::<T>::get()
	}

	/// Retrieve authority identifiers of the next authority set in the original order.
	pub fn next_authorities() -> BoundedVec<AuthorityId, T::MaxAuthorities> {
		NextKeys::<T>::get()
	}

	fn initialize_keys(keys: &Vec<AuthorityId>) {
		if !keys.is_empty() {
			assert!(Keys::<T>::get().is_empty(), "Keys are already initialized!");

			let bounded_keys =
				BoundedVec::<AuthorityId, T::MaxAuthorities>::try_from((*keys).clone())
					.expect("Keys vec too big");

			Keys::<T>::put(bounded_keys.clone());
			NextKeys::<T>::put(bounded_keys);
		}
	}
}

impl<T: Config> sp_runtime::BoundToRuntimeAppPublic for Pallet<T> {
	type Public = AuthorityId;
}

impl<T: Config> OneSessionHandler<T::AccountId> for Pallet<T> {
	type Key = AuthorityId;

	fn on_genesis_session<'a, I: 'a>(authorities: I)
	where
		I: Iterator<Item = (&'a T::AccountId, Self::Key)>,
	{
		Self::initialize_keys(&authorities.map(|x| x.1).collect::<Vec<_>>());
	}

	fn on_new_session<'a, I: 'a>(changed: bool, validators: I, queued_validators: I)
	where
		I: Iterator<Item = (&'a T::AccountId, Self::Key)>,
	{
		// Remember who the authorities are for the new and next session.
		if changed {

Review comment (suggestion):
we can use a reference instead to avoid cloning
```suggestion
			Keys::<T>::put(&bounded_keys);
```

Code after:
		keys.sort();
		keys.dedup();

		keys.to_vec()
	}

	/// Retrieve authority identifiers of the current authority set in the original order.
	pub fn current_authorities() -> WeakBoundedVec<AuthorityId, T::MaxAuthorities> {
		Keys::<T>::get()
	}

	/// Retrieve authority identifiers of the next authority set in the original order.
	pub fn next_authorities() -> WeakBoundedVec<AuthorityId, T::MaxAuthorities> {
		NextKeys::<T>::get()
	}

	fn initialize_keys(keys: &Vec<AuthorityId>) {
		if !keys.is_empty() {
			assert!(Keys::<T>::get().is_empty(), "Keys are already initialized!");

			let bounded_keys =
				WeakBoundedVec::<AuthorityId, T::MaxAuthorities>::try_from((*keys).clone())
					.expect("Keys vec too big");

			Keys::<T>::put(&bounded_keys);
			NextKeys::<T>::put(&bounded_keys);
		}
	}
}

impl<T: Config> sp_runtime::BoundToRuntimeAppPublic for Pallet<T> {
	type Public = AuthorityId;
}

impl<T: Config> OneSessionHandler<T::AccountId> for Pallet<T> {
	type Key = AuthorityId;

	fn on_genesis_session<'a, I: 'a>(authorities: I)
	where
		I: Iterator<Item = (&'a T::AccountId, Self::Key)>,
	{
		Self::initialize_keys(&authorities.map(|x| x.1).collect::<Vec<_>>());
	}

	fn on_new_session<'a, I: 'a>(changed: bool, validators: I, queued_validators: I)
	where
		I: Iterator<Item = (&'a T::AccountId, Self::Key)>,
	{
		// Remember who the authorities are for the new and next session.
		if changed {
			let keys = validators.map(|x| x.1).collect::<Vec<_>>();
Repository: paritytech/substrate
File: frame/im-online/src/lib.rs (Rust)

Code before:
//! 			let _sender = ensure_signed(origin)?;
//! 			let _is_online = <im_online::Pallet<T>>::is_online(authority_index);
//! 			Ok(())
//! 		}
//! 	}
//! }
//! # fn main() { }
//! ```
//!
//! ## Dependencies
//!
//! This module depends on the [Session module](../pallet_session/index.html).

// Ensure we're `no_std` when compiling for Wasm.
#![cfg_attr(not(feature = "std"), no_std)]

mod benchmarking;
mod mock;
mod tests;
pub mod weights;

use codec::{Decode, Encode, MaxEncodedLen};
use core::convert::TryFrom;
use frame_support::{
	traits::{
		EstimateNextSessionRotation, OneSessionHandler, ValidatorSet,
		ValidatorSetWithIdentification, WrapperOpaque,
	},
	WeakBoundedVec,
};
use frame_system::offchain::{SendTransactionTypes, SubmitTransaction};
pub use pallet::*;
use sp_application_crypto::RuntimeAppPublic;
use sp_core::offchain::OpaqueNetworkState;
use sp_runtime::{
	offchain::storage::{MutateStorageError, StorageRetrievalError, StorageValueRef},
	traits::{AtLeast32BitUnsigned, Convert, Saturating, TrailingZeroInput},
	PerThing, Perbill, Permill, RuntimeDebug, SaturatedConversion,
};
use sp_staking::{
	offence::{Kind, Offence, ReportOffence},
	SessionIndex,
};
use sp_std::{convert::TryInto, prelude::*};

use frame_support::traits::Get;

pub use weights::WeightInfo;

pub mod sr25519 {
	mod app_sr25519 {

Review comment (suggestion):
```suggestion
		EstimateNextSessionRotation, Get, OneSessionHandler, ValidatorSet,
```

Code after:
//! 			let _sender = ensure_signed(origin)?;
//! 			let _is_online = <im_online::Pallet<T>>::is_online(authority_index);
//! 			Ok(())
//! 		}
//! 	}
//! }
//! # fn main() { }
//! ```
//!
//! ## Dependencies
//!
//! This module depends on the [Session module](../pallet_session/index.html).

// Ensure we're `no_std` when compiling for Wasm.
#![cfg_attr(not(feature = "std"), no_std)]

mod benchmarking;
mod mock;
mod tests;
pub mod weights;

use codec::{Decode, Encode, MaxEncodedLen};
use core::convert::TryFrom;
use frame_support::{
	traits::{
		EstimateNextSessionRotation, Get, OneSessionHandler, ValidatorSet,
		ValidatorSetWithIdentification, WrapperOpaque,
	},
	BoundedSlice, WeakBoundedVec,
};
use frame_system::offchain::{SendTransactionTypes, SubmitTransaction};
pub use pallet::*;
use scale_info::TypeInfo;
use sp_application_crypto::RuntimeAppPublic;
use sp_core::offchain::OpaqueNetworkState;
use sp_runtime::{
	offchain::storage::{MutateStorageError, StorageRetrievalError, StorageValueRef},
	traits::{AtLeast32BitUnsigned, Convert, Saturating, TrailingZeroInput},
	PerThing, Perbill, Permill, RuntimeDebug, SaturatedConversion,
};
use sp_staking::{
	offence::{Kind, Offence, ReportOffence},
	SessionIndex,
};
use sp_std::{convert::TryInto, prelude::*};
pub use weights::WeightInfo;

pub mod sr25519 {
	mod app_sr25519 {
		use sp_application_crypto::{app_crypto, key_types::IM_ONLINE, sr25519};
		app_crypto!(sr25519, IM_ONLINE);