<commit_before>/*
 * One Controller per layout view
 */

const express = require('express');
const feedr = require('feedr').create();

const router = express.Router();
const api = require('../api');
const authHelper = require('../helpers/authentication');
const userConsentVersions = require('../helpers/consentVersions');

const logger = require('../helpers/logger');

const getSelectOptions = (req, service, query) => api(req).get(`/${service}`, {
	qs: query,
}).then(data => data.data);

// SSO Login

router.get('/tsp-login/', (req, res, next) => {
	const { ticket, redirect: redirectParam } = req.query;
	const redirect = Array.isArray(redirectParam) ? redirectParam[0] : redirectParam;
	return authHelper.login({ strategy: 'tsp', ticket, redirect }, req, res, next);
});

// Login

router.post('/login/', (req, res, next) => {
	const {
		username,
		password,
		systemId,
		schoolId,
		redirect,
	} = req.body;

	if (systemId) {
		return api(req).get(`/systems/${req.body.systemId}`).then(system => authHelper.login({
			strategy: system.type, username, password, systemId, schoolId, redirect,
		}, req, res, next));
	}
	return authHelper.login({
		strategy: 'local', username, password, redirect,
	}, req, res, next);
});

const redirectAuthenticated = (req, res) => {
	let redirectUrl = '/login/success';
	if (req.query && req.query.redirect) {
		redirectUrl = `${redirectUrl}?redirect=${req.query.redirect}`;
	}
	return res.redirect(redirectUrl);
};

const determineRedirectUrl = (req) => {
	if (req.query && req.query.redirect) {
		return req.query.redirect;
	}
	if (req.session.login_challenge) {
		return '/oauth2/login/success';
	}
	return '/dashboard';
};

router.all('/', (req, res, next) => {
	authHelper.isAuthenticated(req).then((isAuthenticated) => {
		if (isAuthenticated) {
			return redirectAuthenticated(req, res);
		}
		return new Promise((resolve) => {
			feedr.readFeed('https://blog.schul-cloud.org/rss', {
				requestOptions: { timeout: 2000 },
			}, (err, data /* , headers */) => {
				let blogFeed;
				try {
					blogFeed = data.rss.channel[0].item
						.filter(item => (item['media:content'] || []).length && (item.link || []).length)
						.slice(0, 3)
						.map((e) => {
							const date = new Date(e.pubDate);
							const locale = 'en-us';
							const month = date.toLocaleString(locale, { month: 'long' });
							e.pubDate = `${date.getDate()}. ${month}`;
							e.description = e.description.join(' ');
							e.url = e.link[0];
							e.img = {
								src: e['media:content'][0].$.url,
								alt: e.title,
							};
							return e;
						});
				} catch (e) {
					// just catching the blog-error
					blogFeed = [];
				}
				const schoolsPromise = getSelectOptions(
					req, 'schools',
					{
						purpose: { $ne: 'expert' },
						$limit: false,
						$sort: 'name',
					},
				);
				resolve(schoolsPromise.then(schools => res.render('authentication/home', {
					schools,
					blogFeed,
					inline: true,
					systems: [],
				})));
			});
		});
	});
});

router.all('/login/', (req, res, next) => {
	authHelper.isAuthenticated(req).then((isAuthenticated) => {
		if (isAuthenticated) {
			return redirectAuthenticated(req, res);
		}
		return getSelectOptions(req,
			'schools', {
				purpose: { $ne: 'expert' },
				$limit: false,
				$sort: 'name',
			})
			.then((schools) => {
				authHelper.clearCookie(req, res);
				res.render('authentication/login', {
					schools,
					systems: [],
					redirect: req.query && req.query.redirect ? req.query.redirect : '',
				});
			});
	}).catch((error) => {
		logger.error(error);
		authHelper.clearCookie(req, res, { destroySession: true });
		return res.redirect('/');
	});
});

const ssoSchoolData = (req, systemId) => api(req).get('/schools/', {
	qs: {
		systems: systemId,
	},
}).then((schools) => {
	if (schools.data.length > 0) {
		return schools.data[0];
	}
	return undefined;
}).catch(() => undefined); // fixme this is a very bad error catch
// so we can do proper redirecting and stuff :)

router.get('/login/success', authHelper.authChecker, (req, res, next) => {
	if (res.locals.currentUser) {
		const user = res.locals.currentUser;
		api(req).get('/consents/', { qs: { userId: user._id } })
			.then((consents) => {
				if (consents.data.length === 0) {
					// user has no consent; create one and try again to get the proper redirect.
					return api(req).post('/consents/', { json: { userId: user._id } })
						.then(() => {
							res.redirect('/login/success');
						});
				}
				const consent = consents.data[0];
				const redirectUrl = determineRedirectUrl(req);
				// check consent versions
				return userConsentVersions(res.locals.currentUser, consent, req).then((consentUpdates) => {
					if (consent.access && !consentUpdates.haveBeenUpdated) {
						return res.redirect(redirectUrl);
					}
					// make sure fistLogin flag is not set
					return res.redirect('/firstLogin');
				});
			});
	} else {
		// if this happens: SSO
		const { accountId, systemId } = (res.locals.currentPayload || {});

		ssoSchoolData(req, systemId).then((school) => {
			if (school === undefined) {
				const redirectUrl = determineRedirectUrl(req);
				res.redirect(redirectUrl);
			} else {
				res.redirect(`/registration/${school._id}/sso/${accountId}`);
			}
		});
	}
});

router.get('/login/systems/:schoolId', (req, res, next) => {
	api(req).get(
		`/schools/${req.params.schoolId}`,
		{
			qs: { $populate: ['systems'] },
		},
	).then((data) => {
		const systems = data.systems.filter(value => value.type !== 'ldap' || value.ldapConfig.active === true);
		return res.send(systems);
	});
});

router.get('/logout/', (req, res, next) => {
	api(req).del('/authentication')
		.then(() => {
			authHelper.clearCookie(req, res, { destroySession: true });
			return res.redirect('/');
		}).catch(() => res.redirect('/'));
});

module.exports = router;
<commit_msg>Handle all redirect cases correctly<commit_after>/*
 * One Controller per layout view
 */

const express = require('express');
const feedr = require('feedr').create();

const router = express.Router();
const api = require('../api');
const authHelper = require('../helpers/authentication');
const userConsentVersions = require('../helpers/consentVersions');

const logger = require('../helpers/logger');

const getSelectOptions = (req, service, query) => api(req).get(`/${service}`, {
	qs: query,
}).then(data => data.data);

// SSO Login

router.get('/tsp-login/', (req, res, next) => {
	const { ticket, redirect: redirectParam } = req.query;
	let redirect = '/dashboard';
	if (redirectParam) {
		if (Array.isArray(redirectParam)) {
			const redirects = redirectParam.filter(v => v !== 'true');
			if (redirects.length > 0) {
				redirect = redirects[0];
			}
		} else if (String(redirectParam) !== 'true') {
			redirect = redirectParam;
		}
	}
	return authHelper.login({ strategy: 'tsp', ticket, redirect }, req, res, next);
});

// Login

router.post('/login/', (req, res, next) => {
	const {
		username,
		password,
		systemId,
		schoolId,
		redirect,
	} = req.body;

	if (systemId) {
		return api(req).get(`/systems/${req.body.systemId}`).then(system => authHelper.login({
			strategy: system.type, username, password, systemId, schoolId, redirect,
		}, req, res, next));
	}
	return authHelper.login({
		strategy: 'local', username, password, redirect,
	}, req, res, next);
});

const redirectAuthenticated = (req, res) => {
	let redirectUrl = '/login/success';
	if (req.query && req.query.redirect) {
		redirectUrl = `${redirectUrl}?redirect=${req.query.redirect}`;
	}
	return res.redirect(redirectUrl);
};

const determineRedirectUrl = (req) => {
	if (req.query && req.query.redirect) {
		return req.query.redirect;
	}
	if (req.session.login_challenge) {
		return '/oauth2/login/success';
	}
	return '/dashboard';
};

router.all('/', (req, res, next) => {
	authHelper.isAuthenticated(req).then((isAuthenticated) => {
		if (isAuthenticated) {
			return redirectAuthenticated(req, res);
		}
		return new Promise((resolve) => {
			feedr.readFeed('https://blog.schul-cloud.org/rss', {
				requestOptions: { timeout: 2000 },
			}, (err, data /* , headers */) => {
				let blogFeed;
				try {
					blogFeed = data.rss.channel[0].item
						.filter(item => (item['media:content'] || []).length && (item.link || []).length)
						.slice(0, 3)
						.map((e) => {
							const date = new Date(e.pubDate);
							const locale = 'en-us';
							const month = date.toLocaleString(locale, { month: 'long' });
							e.pubDate = `${date.getDate()}. ${month}`;
							e.description = e.description.join(' ');
							e.url = e.link[0];
							e.img = {
								src: e['media:content'][0].$.url,
								alt: e.title,
							};
							return e;
						});
				} catch (e) {
					// just catching the blog-error
					blogFeed = [];
				}
				const schoolsPromise = getSelectOptions(
					req, 'schools',
					{
						purpose: { $ne: 'expert' },
						$limit: false,
						$sort: 'name',
					},
				);
				resolve(schoolsPromise.then(schools => res.render('authentication/home', {
					schools,
					blogFeed,
					inline: true,
					systems: [],
				})));
			});
		});
	});
});

router.all('/login/', (req, res, next) => {
	authHelper.isAuthenticated(req).then((isAuthenticated) => {
		if (isAuthenticated) {
			return redirectAuthenticated(req, res);
		}
		return getSelectOptions(req,
			'schools', {
				purpose: { $ne: 'expert' },
				$limit: false,
				$sort: 'name',
			})
			.then((schools) => {
				authHelper.clearCookie(req, res);
				res.render('authentication/login', {
					schools,
					systems: [],
					redirect: req.query && req.query.redirect ? req.query.redirect : '',
				});
			});
	}).catch((error) => {
		logger.error(error);
		authHelper.clearCookie(req, res, { destroySession: true });
		return res.redirect('/');
	});
});

const ssoSchoolData = (req, systemId) => api(req).get('/schools/', {
	qs: {
		systems: systemId,
	},
}).then((schools) => {
	if (schools.data.length > 0) {
		return schools.data[0];
	}
	return undefined;
}).catch(() => undefined); // fixme this is a very bad error catch
// so we can do proper redirecting and stuff :)

router.get('/login/success', authHelper.authChecker, (req, res, next) => {
	if (res.locals.currentUser) {
		const user = res.locals.currentUser;
		api(req).get('/consents/', { qs: { userId: user._id } })
			.then((consents) => {
				if (consents.data.length === 0) {
					// user has no consent; create one and try again to get the proper redirect.
					return api(req).post('/consents/', { json: { userId: user._id } })
						.then(() => {
							res.redirect('/login/success');
						});
				}
				const consent = consents.data[0];
				const redirectUrl = determineRedirectUrl(req);
				// check consent versions
				return userConsentVersions(res.locals.currentUser, consent, req).then((consentUpdates) => {
					if (consent.access && !consentUpdates.haveBeenUpdated) {
						return res.redirect(redirectUrl);
					}
					// make sure fistLogin flag is not set
					return res.redirect('/firstLogin');
				});
			});
	} else {
		// if this happens: SSO
		const { accountId, systemId } = (res.locals.currentPayload || {});

		ssoSchoolData(req, systemId).then((school) => {
			if (school === undefined) {
				const redirectUrl = determineRedirectUrl(req);
				res.redirect(redirectUrl);
			} else {
				res.redirect(`/registration/${school._id}/sso/${accountId}`);
			}
		});
	}
});

router.get('/login/systems/:schoolId', (req, res, next) => {
	api(req).get(
		`/schools/${req.params.schoolId}`,
		{
			qs: { $populate: ['systems'] },
		},
	).then((data) => {
		const systems = data.systems.filter(value => value.type !== 'ldap' || value.ldapConfig.active === true);
		return res.send(systems);
	});
});

router.get('/logout/', (req, res, next) => {
	api(req).del('/authentication')
		.then(() => {
			authHelper.clearCookie(req, res, { destroySession: true });
			return res.redirect('/');
		}).catch(() => res.redirect('/'));
});

module.exports = router;
<|endoftext|>


<commit_before>import {
  RECEIVE_REVISIONS,
  REVISIONS_LOADING,
  RECEIVE_COURSE_SCOPED_REVISIONS,
  COURSE_SCOPED_REVISIONS_LOADING,
  SORT_REVISIONS,
  API_FAIL
} from '../constants';
import { fetchWikidataLabelsForRevisions } from './wikidata_actions';
import logErrorMessage from '../utils/log_error_message';
import request from '../utils/request';
import API from '../utils/api';
import moment from 'moment';
import { stringify } from 'query-string';
import { PageAssessmentGrades, PageAssessmentSupportedWiki } from '../utils/article_finder_language_mappings';
import { url } from '../utils/wiki_utils';

const fetchClassFromRevisions = async (wiki, API_URL, revisions) => {
  // remove duplicates -> each article occurs only once after this
  const uniqueArticles = [...new Set(revisions.map(revision => revision.title))];
  const titles = uniqueArticles.join('|');

  const params = {
    action: 'query',
    format: 'json',
    titles,
    prop: 'pageassessments',
    pasubprojects: false,
    palimit: 50
  };
  const response = await request(`${API_URL}?${stringify(params)}&origin=*`);
  const ratings = (await response.json()).query.pages;

  /* eslint-disable no-restricted-syntax */
  for (const revision of revisions) {
    // if pageassessments exists
    if (ratings[revision.pageid].pageassessments) {
      // pick the first key of the object pageassessments
      let rating;
      for (const value of Object.values(ratings[revision.pageid].pageassessments)) {
        if (value.class) {
          rating = value.class;
          break;
        }
      }
      if (rating) {
        const mapping = PageAssessmentGrades[wiki.project][wiki.language][rating];
        if (mapping) {
          revision.rating_num = mapping.score;
          revision.pretty_rating = mapping.pretty;
          revision.rating = mapping.class;
        }
      }
    }
  }
  /* eslint-enable no-restricted-syntax */
};
const fetchRevisionsFromWiki = async (wiki, usernames, start_time, prevContinueToken) => {
  const params = {
    action: 'query',
    format: 'json',
    list: 'usercontribs',
    ucuser: usernames,
    ucprop: 'ids|title|sizediff|timestamp',
    uclimit: 50,
    ucend: start_time,
    ucdir: 'older',
  };

  if (prevContinueToken) {
    // if token exists, add it.
    params.uccontinue = prevContinueToken.uccontinue;
    params.continue = prevContinueToken.continue;
  }

  let prefix;
  if (wiki.language) {
    prefix = `https://${wiki.language}.${wiki.project}.org`;
  } else {
    prefix = `https://${wiki.project}.org`;
  }

  const API_URL = `${prefix}/w/api.php`;

  const response = await request(`${API_URL}?${stringify(params)}&origin=*`);
  const json = await response.json();
  const revisions = json.query.usercontribs;
  const continueToken = json.continue;
  /* eslint-disable no-restricted-syntax */

  for (const revision of revisions) {
    revision.wiki = wiki;
    const diff_params = {
      title: revision.title,
      diff: 'prev',
      oldid: revision.parentid
    };

    // url for the diff
    revision.url = `${prefix}/w/index.php?${stringify(diff_params)}`;

    // main article url - we use stringify to ensure that its encoded properly
    revision.article_url = `${prefix}/w/index.php?${stringify({ title: revision.title })}`;

    // to maintain the old structure of the revision object
    revision.characters = revision.sizediff;
    revision.mw_rev_id = revision.revid;
    revision.id = revision.revid;
    revision.revisor = revision.user;
    revision.date = revision.timestamp;
    revision.mw_page_id = revision.pageid;
  }
  /* eslint-enable no-restricted-syntax */

  if (PageAssessmentSupportedWiki?.[wiki.project]?.includes(wiki.language)) {
    // the wiki supports page assessments
    await fetchClassFromRevisions(wiki, API_URL, revisions);
  }

  return { revisions, continueToken, wiki };
};

const fetchRevisionsFromUsers = async (course, users, continueTokens = {}) => {
  const usernames = users.map(user => user.username).join('|');

  // Converting to ISO 8601 format
  // the Media Wiki API doesn't accept fractional seconds. This gets rid of that
  const start_time = moment.utc(course.timeline_start).format();

  const revisions = [];
  const wikiPromises = [];
  /* eslint-disable no-restricted-syntax */
  for (const wiki of course.wikis) {
    if (continueTokens[url(wiki)] === 'no-continue') {
      // eslint-disable-next-line no-continue
      continue;
    }
    wikiPromises.push(fetchRevisionsFromWiki(wiki, usernames, start_time, continueTokens?.[url(wiki)]));
  }
  const resolvedValues = await Promise.all(wikiPromises);
  for (const value of resolvedValues) {
    const { revisions: items, continueToken, wiki } = value;
    revisions.push(...items);
    if (continueToken) {
      continueTokens[url(wiki)] = (continueToken);
    } else {
      continueTokens[url(wiki)] = 'no-continue';
    }
  }

  /* eslint-enable no-restricted-syntax */
  return { revisions, continueTokens };
};

const fetchRevisionsPromise = async (course, limit, isCourseScoped, users, contTokens) => {
  if (!isCourseScoped) {
    const { revisions, continueTokens } = await fetchRevisionsFromUsers(course, users, contTokens);
    if (course.revisions) {
      course.revisions = course.revisions.concat(revisions);
    } else {
      course.revisions = revisions;
    }
    course.revisions = course.revisions.sort((revision1, revision2) => {
      const date1 = new Date(revision1.date);
      const date2 = new Date(revision2.date);
      return date2.getTime() - date1.getTime();
    });
    return { course, continueTokens };
  }
  const response = await request(`/courses/${course.slug}/revisions.json?limit=${limit}&course_scoped=${isCourseScoped}`);
  if (!response.ok) {
    logErrorMessage(response);
    const data = await response.text();
    response.responseText = data;
    throw response;
  }
  return response.json();
};

export const fetchRevisions = (course, limit, isCourseScoped = false) => async (dispatch, getState) => {
  const courseId = course.slug;
  let actionType;
  if (isCourseScoped) {
    actionType = RECEIVE_COURSE_SCOPED_REVISIONS;
    dispatch({ type: COURSE_SCOPED_REVISIONS_LOADING });
  } else {
    actionType = RECEIVE_REVISIONS;
    dispatch({ type: REVISIONS_LOADING });
  }
  const state = getState();
  let users;
  if (state.users.users.length) {
    // the users list has already been fetched
    users = state.users.users;
  } else {
    try {
      const response = await API.fetch(courseId, 'users');
      users = response.course.users;
    } catch (e) {
      dispatch({ type: API_FAIL, data: e });
      return;
    }
  }
  return (
    fetchRevisionsPromise(course, limit, isCourseScoped, users, state.revisions.continueTokens)
      .then((resp) => {
        dispatch({
          type: actionType,
          data: resp,
          limit: limit
        });
        // Now that we received the revisions data, query wikidata.org for the labels
        // of any Wikidata entries that are among the revisions.
        fetchWikidataLabelsForRevisions(resp.course.revisions, dispatch);
      })
      .catch(response => (dispatch({ type: API_FAIL, data: response })))
  );
};

export const sortRevisions = key => ({ type: SORT_REVISIONS, key: key });
<commit_msg>Fix request URL<commit_after>import {
  RECEIVE_REVISIONS,
  REVISIONS_LOADING,
  RECEIVE_COURSE_SCOPED_REVISIONS,
  COURSE_SCOPED_REVISIONS_LOADING,
  SORT_REVISIONS,
  API_FAIL
} from '../constants';
import { fetchWikidataLabelsForRevisions } from './wikidata_actions';
import logErrorMessage from '../utils/log_error_message';
import request from '../utils/request';
import API from '../utils/api';
import moment from 'moment';
import { stringify } from 'query-string';
import { PageAssessmentGrades, PageAssessmentSupportedWiki } from '../utils/article_finder_language_mappings';
import { url } from '../utils/wiki_utils';

const fetchClassFromRevisions = async (wiki, API_URL, revisions) => {
  // remove duplicates -> each article occurs only once after this
  const uniqueArticles = [...new Set(revisions.map(revision => revision.title))];
  const titles = uniqueArticles.join('|');

  const params = {
    action: 'query',
    format: 'json',
    titles,
    prop: 'pageassessments',
    pasubprojects: false,
    palimit: 50
  };
  const response = await request(`${API_URL}?${stringify(params)}&origin=*`);
  const ratings = (await response.json()).query.pages;

  /* eslint-disable no-restricted-syntax */
  for (const revision of revisions) {
    // if pageassessments exists
    if (ratings[revision.pageid].pageassessments) {
      // pick the first key of the object pageassessments
      let rating;
      for (const value of Object.values(ratings[revision.pageid].pageassessments)) {
        if (value.class) {
          rating = value.class;
          break;
        }
      }
      if (rating) {
        const mapping = PageAssessmentGrades[wiki.project][wiki.language][rating];
        if (mapping) {
          revision.rating_num = mapping.score;
          revision.pretty_rating = mapping.pretty;
          revision.rating = mapping.class;
        }
      }
    }
  }
  /* eslint-enable no-restricted-syntax */
};
const fetchRevisionsFromWiki = async (wiki, usernames, start_time, prevContinueToken) => {
  const params = {
    action: 'query',
    format: 'json',
    list: 'usercontribs',
    ucuser: usernames,
    ucprop: 'ids|title|sizediff|timestamp',
    uclimit: 50,
    ucend: start_time,
    ucdir: 'older',
  };

  if (prevContinueToken) {
    // if token exists, add it.
    params.uccontinue = prevContinueToken.uccontinue;
    params.continue = prevContinueToken.continue;
  }

  const prefix = `https://${url(wiki)}`;

  const API_URL = `${prefix}/w/api.php`;

  let response;
  try {
    response = await request(`${API_URL}?${stringify(params)}&origin=*`);
    if (!response.ok) {
      throw response;
    }
  } catch (e) {
    return { revisions: [], continueToken: undefined, wiki };
  }
  const json = await response.json();
  const revisions = json.query.usercontribs;
  const continueToken = json.continue;
  /* eslint-disable no-restricted-syntax */

  for (const revision of revisions) {
    revision.wiki = wiki;
    const diff_params = {
      title: revision.title,
      diff: 'prev',
      oldid: revision.parentid
    };

    // url for the diff
    revision.url = `${prefix}/w/index.php?${stringify(diff_params)}`;

    // main article url - we use stringify to ensure that its encoded properly
    revision.article_url = `${prefix}/w/index.php?${stringify({ title: revision.title })}`;

    // to maintain the old structure of the revision object
    revision.characters = revision.sizediff;
    revision.mw_rev_id = revision.revid;
    revision.id = revision.revid;
    revision.revisor = revision.user;
    revision.date = revision.timestamp;
    revision.mw_page_id = revision.pageid;
  }
  /* eslint-enable no-restricted-syntax */

  if (PageAssessmentSupportedWiki?.[wiki.project]?.includes(wiki.language)) {
    // the wiki supports page assessments
    await fetchClassFromRevisions(wiki, API_URL, revisions);
  }

  return { revisions, continueToken, wiki };
};

const fetchRevisionsFromUsers = async (course, users, continueTokens = {}) => {
  const usernames = users.map(user => user.username).join('|');

  // Converting to ISO 8601 format
  // the Media Wiki API doesn't accept fractional seconds. This gets rid of that
  const start_time = moment.utc(course.timeline_start).format();

  const revisions = [];
  const wikiPromises = [];
  /* eslint-disable no-restricted-syntax */
  for (const wiki of course.wikis) {
    if (continueTokens[url(wiki)] === 'no-continue') {
      // eslint-disable-next-line no-continue
      continue;
    }
    wikiPromises.push(fetchRevisionsFromWiki(wiki, usernames, start_time, continueTokens?.[url(wiki)]));
  }
  const resolvedValues = await Promise.all(wikiPromises);
  for (const value of resolvedValues) {
    const { revisions: items, continueToken, wiki } = value;
    revisions.push(...items);
    if (continueToken) {
      continueTokens[url(wiki)] = (continueToken);
    } else {
      continueTokens[url(wiki)] = 'no-continue';
    }
  }

  /* eslint-enable no-restricted-syntax */
  return { revisions, continueTokens };
};

const fetchRevisionsPromise = async (course, limit, isCourseScoped, users, contTokens) => {
  if (!isCourseScoped) {
    const { revisions, continueTokens } = await fetchRevisionsFromUsers(course, users, contTokens);
    if (course.revisions) {
      course.revisions = course.revisions.concat(revisions);
    } else {
      course.revisions = revisions;
    }
    course.revisions = course.revisions.sort((revision1, revision2) => {
      const date1 = new Date(revision1.date);
      const date2 = new Date(revision2.date);
      return date2.getTime() - date1.getTime();
    });
    return { course, continueTokens };
  }
  const response = await request(`/courses/${course.slug}/revisions.json?limit=${limit}&course_scoped=${isCourseScoped}`);
  if (!response.ok) {
    logErrorMessage(response);
    const data = await response.text();
    response.responseText = data;
    throw response;
  }
  return response.json();
};

export const fetchRevisions = (course, limit, isCourseScoped = false) => async (dispatch, getState) => {
  const courseId = course.slug;
  let actionType;
  if (isCourseScoped) {
    actionType = RECEIVE_COURSE_SCOPED_REVISIONS;
    dispatch({ type: COURSE_SCOPED_REVISIONS_LOADING });
  } else {
    actionType = RECEIVE_REVISIONS;
    dispatch({ type: REVISIONS_LOADING });
  }
  const state = getState();
  let users;
  if (state.users.users.length) {
    // the users list has already been fetched
    users = state.users.users;
  } else {
    try {
      const response = await API.fetch(courseId, 'users');
      users = response.course.users;
    } catch (e) {
      dispatch({ type: API_FAIL, data: e });
      return;
    }
  }
  return (
    fetchRevisionsPromise(course, limit, isCourseScoped, users, state.revisions.continueTokens)
      .then((resp) => {
        dispatch({
          type: actionType,
          data: resp,
          limit: limit
        });
        // Now that we received the revisions data, query wikidata.org for the labels
        // of any Wikidata entries that are among the revisions.
        fetchWikidataLabelsForRevisions(resp.course.revisions, dispatch);
      })
      .catch(response => (dispatch({ type: API_FAIL, data: response })))
  );
};

export const sortRevisions = key => ({ type: SORT_REVISIONS, key: key });
<|endoftext|>


<commit_before>'use strict';

angular.module('sllp.app')
  .directive('editMix', function () {
    return {
      restrict: 'E',
      scope: {exercise: "="},
      controller: function ($scope) {
        $scope.init = function () {
          if (!exercise.text) {
            exercise.text = '';
          }
          if (!exercise.distraction) {
            exercise.distraction = '';
          }
          if (!exercise.items) {
            exercise.items = [];
          }
        };
        $scope.init();
      },
      templateUrl: '/static/partials/directives/mix/edit.html'
    };
  })
  .directive('previewMix', function () {
    return {
      restrict: 'E',
      scope: { exercise: '='},
      templateUrl: '/static/partials/directives/mix/preview.html'
    };

  });
<commit_msg>mix basic functionality<commit_after>'use strict';

angular.module('sllp.app')
  .directive('editMix', function () {
    return {
      restrict: 'E',
      scope: {exercise: "="},
      controller: function ($scope) {
        $scope.init = function () {
          if (!$scope.exercise.text) {
            $scope.exercise.text = '';
          }
          if (!$scope.exercise.distraction) {
            $scope.exercise.distraction = '';
          }
          if (!$scope.exercise.words) {
            $scope.exercise.words = [];
          }
        };
        $scope.init();
        $scope.setWords = function(){
            $scope.exercise.words = $scope.exercise.text.split(" ");
        }

      },
      template: '
<input ng-change="setWords()" ng-model="exercise.text" placeholder"text">\
      <input ng-model="exercise.distraction" placeholder"distraction">\

'
    };
  })
  .directive('previewMix', function () {
    return {
      restrict: 'E',
      //scope: { exercise: '='},
      controller : function($scope) {
        $scope.exercise.answerWords = [];
        //$scope.exercise.mixWords = $scope.exercise.words;
        //$scope.words = $scope.exercise.text.split();

        $scope.checkCorrect = function(idx,part2,id){
        };
        $scope.moveAnswer = function(idx){
           var w = $scope.exercise.words.splice(idx,1);
           $scope.exercise.answerWords.push(w[0]);

        };
        $scope.moveBack = function(idx){
           var w = $scope.exercise.answerWords.splice(idx,1);
           $scope.exercise.words.push(w[0]);
        };

      },
      //templateUrl: '/static/partials/directives/mix/preview.html'
      template:
'
<button ng-click="moveBack($index)" ng-repeat="a in exercise.answerWords track by $index">{{a}}</button>
\

<button ng-click="moveAnswer($index)" ng-repeat="a in exercise.words track by $index">{{a}}</button>
'
    };

  });
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2010 Nils Schneider
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

function Bitcoin(settings, user, password) {
	this.settings = {url: null, auth: null, account: null};

	this.prepareAuth = function(user, password) {
		return "Basic " + jQuery.base64_encode(user + ":" + password);
	}

	this.RPC = function(method, params, callback, context) {
		var request;
		var auth = this.settings.auth;

		if(params != null) {
			request = {method: method, params: params};
		} else {
			request = {method: method};
		}

		jQuery.ajax({url: this.settings.url, dataType: 'json', type: 'POST',
					contentType: 'application/json',
					data: JSON.stringify(request),
					timeout: 15000,
					beforeSend: function(req){
                		req.setRequestHeader("Authorization", auth);
					},
					success:
						 function(data) {
							callback(data.result, data.error, context);
						},
					error:
						 function(req, textStatus, error) {
							var data;
							try  {
								if (!req.responseText)
									throw "no responseText";

								data = jQuery.parseJSON(req.responseText);
							} catch (err) {
								data = {result: null, error: {code: req.status}};

								if (data.error.code === 0 && !req.status)
									data.error.message = "RPC not found";
								else {
									if (req.statusText)
										data.error.message = req.statusText;
									else
										data.error.message = data.error.code.toString();
								}
							}

							callback(data.result, data.error, context);
						}
					});
	}

	this.listAccounts = function(callback, context) {
		this.RPC("listaccounts", null, callback, context);
	}

	this.listTransactions = function(callback, context) {
		this.RPC("listtransactions", [this.settings.account, 999999], callback, context);
	}

	this.validateAddress = function(callback, address, context) {
		this.RPC("validateaddress", [address], callback, context);
	}

	this.sendBTC = function(callback, address, amount, context) {
		this.RPC("sendfrom", [this.settings.account, address, amount], callback, context);
	}

	this.getAddress = function(callback, context) {
		this.RPC("getaccountaddress", [this.settings.account], callback, context);
	}

	this.getBalance = function(callback, context) {
		this.RPC("getbalance", [this.settings.account], callback, context);
	}

	this.getInfo = function(callback, context) {
		this.RPC("getinfo", null, callback, context);
	}

	this.selectAccount = function(account) {
		if (account != undefined)
			this.settings.account = account;
		else
			this.settings.account = "";
	}

	this.init = function(settings, user, password) {
		this.settings = settings;

		if (!this.settings.auth && user && password)
			this.settings.auth = this.prepareAuth(user, password);

		this.selectAccount(settings.account);
	}

	this.init(settings, user, password);
}
<commit_msg>fix empty url in settings<commit_after>/*
 * Copyright (c) 2010 Nils Schneider
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

function Bitcoin(settings, user, password) {
	this.settings = {url: null, auth: null, account: null};

	this.prepareAuth = function(user, password) {
		return "Basic " + jQuery.base64_encode(user + ":" + password);
	}

	this.RPC = function(method, params, callback, context) {
		var request;
		var auth = this.settings.auth;

		if(params != null) {
			request = {method: method, params: params};
		} else {
			request = {method: method};
		}

		jQuery.ajax({url: this.settings.url, dataType: 'json', type: 'POST',
					contentType: 'application/json',
					data: JSON.stringify(request),
					timeout: 15000,
					beforeSend: function(req){
                		req.setRequestHeader("Authorization", auth);
					},
					success:
						 function(data) {
							callback(data.result, data.error, context);
						},
					error:
						 function(req, textStatus, error) {
							var data;
							try  {
								if (!req.responseText)
									throw "no responseText";

								data = jQuery.parseJSON(req.responseText);
							} catch (err) {
								data = {result: null, error: {code: req.status}};

								if (data.error.code === 0 && !req.status)
									data.error.message = "RPC not found";
								else {
									if (req.statusText)
										data.error.message = req.statusText;
									else
										data.error.message = data.error.code.toString();
								}
							}

							callback(data.result, data.error, context);
						}
					});
	}

	this.listAccounts = function(callback, context) {
		this.RPC("listaccounts", null, callback, context);
	}

	this.listTransactions = function(callback, context) {
		this.RPC("listtransactions", [this.settings.account, 999999], callback, context);
	}

	this.validateAddress = function(callback, address, context) {
		this.RPC("validateaddress", [address], callback, context);
	}

	this.sendBTC = function(callback, address, amount, context) {
		this.RPC("sendfrom", [this.settings.account, address, amount], callback, context);
	}

	this.getAddress = function(callback, context) {
		this.RPC("getaccountaddress", [this.settings.account], callback, context);
	}

	this.getBalance = function(callback, context) {
		this.RPC("getbalance", [this.settings.account], callback, context);
	}

	this.getInfo = function(callback, context) {
		this.RPC("getinfo", null, callback, context);
	}

	this.selectAccount = function(account) {
		if (account != undefined)
			this.settings.account = account;
		else
			this.settings.account = "";
	}

	this.init = function(settings, user, password) {
		this.settings = settings;

		if (this.settings.url == "")
			this.settings.url = window.location.href;

		if (!this.settings.auth && user && password)
			this.settings.auth = this.prepareAuth(user, password);

		this.selectAccount(settings.account);
	}

	this.init(settings, user, password);
}
<|endoftext|>


<commit_before>var Observer = require('../src/observer/observer')
var _ = require('../src/util')

function Vue (options) {

  var data = options.data
  var scope = this._scope = options.parent
    ? Object.create(options.parent._scope)
    : {}

  // copy instantiation data into scope
  for (var key in data) {
    if (key in scope) {
      // key exists on the scope prototype chain
      // cannot use direct set here, because in the parent
      // scope everything is already getter/setter and we
      // need to overwrite them with Object.defineProperty.
      _.define(scope, key, data[key], true)
    } else {
      scope[key] = data[key]
    }
  }

  // create observer
  // pass in noProto:true to avoid mutating the __proto__
  var ob = this._observer = Observer.create(this._scope, true)
  var dob = Observer.create(data)
  var locked = false

  // sync scope and original data.
  ob
  .on('set', guard(function (key, val) {
    data[key] = val
  }))
  .on('added', guard(function (key, val) {
    data.$add(key, val)
  }))
  .on('deleted', guard(function (key) {
    data.$delete(key)
  }))

  // also need to sync data object changes to scope...
  // this would cause cycle updates, so we need to lock
  // stuff when one side updates the other
  dob
  .on('set', guard(function (key, val) {
    scope[key] = val
  }))
  .on('added', guard(function (key, val) {
    scope.$add(key, val)
  }))
  .on('deleted', guard(function (key) {
    scope.$delete(key)
  }))

  function guard (fn) {
    return function (key, val) {
      if (locked || key.indexOf(Observer.pathDelimiter) > -1) {
        return
      }
      locked = true
      fn(key, val)
      locked = false
    }
  }

  // relay change events from parent scope.
  // this ensures the current Vue instance is aware of
  // stuff going on up in the scope chain.
  if (options.parent) {
    var po = options.parent._observer
    ;['set', 'mutate', 'added', 'deleted'].forEach(function (event) {
      po.on(event, function (key, a, b) {
        if (!scope.hasOwnProperty(key)) {
          ob.emit(event, key, a, b)
        }
      })
    })
  }

  // proxy everything on self
  for (var key in scope) {
    _.proxy(this, scope, key)
  }

  // also proxy newly added keys.
  var self = this
  ob
  .on('added', function (key) {
    if (!self.hasOwnProperty(key)) {
      _.proxy(self, scope, key)
    }
  })

}

Vue.prototype.$add = function (key, val) {
  this._scope.$add.call(this._scope, key, val)
}

Vue.prototype.$delete = function (key) {
  this._scope.$delete.call(this._scope, key)
}

window.model = {
  a: 'go!',
  b: 2,
  c: {
    d: 3
  },
  arr: [{a:1}, {a:2}, {a:3}],
  go: function () {
    console.log(this.a)
  }
}

window.vm = new Vue({
  data: model
})

window.child = new Vue({
  parent: vm,
  data: {
    a: 1,
    change: function () {
      this.c.d = 4
      this.b = 456 // Unlike Angular, setting primitive values in Vue WILL affect outer scope,
                   // unless you overwrite it in the instantiation data!
    }
  }
})

window.v2 = new Vue({
  data: model.arr[0]
})

vm._observer.on('set', function (key, val) {
  console.log('vm set:' + key.replace(/[\b]/g, '.'), val)
})

child._observer.on('set', function (key, val) {
  console.log('child set:' + key.replace(/[\b]/g, '.'), val)
})

vm._observer.on('mutate', function (key, val) {
  console.log('vm mutate:' + key.replace(/[\b]/g, '.'), val)
})

child._observer.on('mutate', function (key, val) {
  console.log('child mutate:' + key.replace(/[\b]/g, '.'), val)
})<commit_msg>fix inheritance test<commit_after>var Observer = require('../src/observer/observer')
var _ = require('../src/util')

function Vue (options) {

  var data = options.data
  var parent = options.parent
  var scope = this._scope = parent
    ? Object.create(parent._scope)
    : {}

  // copy instantiation data into scope
  for (var key in data) {
    if (key in scope) {
      // key exists on the scope prototype chain
      // cannot use direct set here, because in the parent
      // scope everything is already getter/setter and we
      // need to overwrite them with Object.defineProperty.
      _.define(scope, key, data[key], true)
    } else {
      scope[key] = data[key]
    }
  }

  // create observer
  // pass in noProto:true to avoid mutating the __proto__
  var ob = this._observer = Observer.create(scope, { noProto: true })
  var dob = Observer.create(data)
  var locked = false

  // sync scope and original data.
  ob
    .on('set', guard(function (key, val) {
      data[key] = val
    }))
    .on('added', guard(function (key, val) {
      data.$add(key, val)
    }))
    .on('deleted', guard(function (key) {
      data.$delete(key)
    }))

  // also need to sync data object changes to scope...
  // this would cause cycle updates, so we need to lock
  // stuff when one side updates the other
  dob
    .on('set', guard(function (key, val) {
      scope[key] = val
    }))
    .on('added', guard(function (key, val) {
      scope.$add(key, val)
    }))
    .on('deleted', guard(function (key) {
      scope.$delete(key)
    }))

  function guard (fn) {
    return function (key, val) {
      if (locked || key.indexOf(Observer.pathDelimiter) > -1) {
        return
      }
      locked = true
      fn(key, val)
      locked = false
    }
  }

  // relay change events from parent scope.
  // this ensures the current Vue instance is aware of
  // stuff going on up in the scope chain.
  if (parent) {
    var po = parent._observer
    ;['set', 'mutate', 'added', 'deleted'].forEach(function (event) {
      po.on(event, function (key, a, b) {
        if (!scope.hasOwnProperty(key)) {
          ob.emit(event, key, a, b)
        }
      })
    })
  }

  // proxy everything on self
  for (var key in scope) {
    _.proxy(this, scope, key)
  }

  // also proxy newly added keys.
  var self = this
  ob.on('added', function (key) {
    if (!self.hasOwnProperty(key)) {
      _.proxy(self, scope, key)
    }
  })

}

Vue.prototype.$add = function (key, val) {
  this._scope.$add.call(this._scope, key, val)
}

Vue.prototype.$delete = function (key) {
  this._scope.$delete.call(this._scope, key)
}

Vue.prototype.$toJSON = function () {
  return JSON.stringify(this._scope)
}

Vue.prototype.$log = function (key) {
  var data = key
    ? this._scope[key]
    : this._scope
  console.log(JSON.parse(JSON.stringify(data)))
}

window.model = {
  a: 'go!',
  b: 2,
  c: {
    d: 3
  },
  arr: [{a:1}, {a:2}, {a:3}],
  go: function () {
    console.log(this.a)
  }
}

window.vm = new Vue({
  data: model
})

window.child = new Vue({
  parent: vm,
  data: {
    a: 1,
    change: function () {
      this.c.d = 4
      this.b = 456 // Unlike Angular, setting primitive values in Vue WILL affect outer scope,
                   // unless you overwrite it in the instantiation data!
    }
  }
})

window.item = new Vue({
  parent: vm,
  data: model.arr[0]
})

vm._observer.on('set', function (key, val) {
  console.log('vm set:' + key.replace(/[\b]/g, '.'), val)
})

vm._observer.on('mutate', function (key, val) {
  console.log('vm mutate:' + key.replace(/[\b]/g, '.'), val)
})

child._observer.on('set', function (key, val) {
  console.log('child set:' + key.replace(/[\b]/g, '.'), val)
})

child._observer.on('mutate', function (key, val) {
  console.log('child mutate:' + key.replace(/[\b]/g, '.'), val)
})

item._observer.on('set', function (key, val) {
  console.log('item set:' + key.replace(/[\b]/g, '.'), val)
})

item._observer.on('mutate', function (key, val) {
  console.log('item mutate:' + key.replace(/[\b]/g, '.'), val)
})<|endoftext|>


<commit_before>'use strict';

// Standards controller
angular.module('standards').controller('StandardsController', ['$scope', '$stateParams', '$location', 'Authentication', 'Standards',
    function ($scope, $stateParams, $location, Authentication, Standards) {
        $scope.authentication = Authentication;
        $scope.init = function () {
            if ($scope.authentication.user) {
                if ($scope.authentication.user.roles[0] != "commander" && $scope.authentication.user.roles[0] != "agency") {
                    $http.get('/user/checkCurrentUser').success(function (data) {
                        if (data != "okie") {
                            sweetAlert("Truy cập vùng không hợp lệ");
                            window.location.reload();
                        }
                        ;
                    });
                }
                if (window.location.pathname != "/administrator") {
                    $http.get('/findCompanyByShortName' + window.location.pathname).success(function (data) {
                        //$http.get('findCompany/'+data[0]._id).success(function(data1){
                        $scope.company = data[0];
                        document.getElementById('site-head').style.backgroundColor = $scope.company.colorBackground;
                        document.getElementById('onclick-change-showname').style.backgroundColor = $scope.company.colorBackground;
                        //});
                    });
                }
            } else {
                $http.get('/findCompanyByShortName' + window.location.pathname).success(function (data) {
                    //$http.get('findCompany/'+data[0]._id).success(function(data1){
                    $scope.company = data[0];
                    document.getElementById('site-head').style.backgroundColor = $scope.company.colorBackground;
                    document.getElementById('onclick-change-showname').style.backgroundColor = $scope.company.colorBackground;
                    //});
                });
            }

        };
        $scope.init();
        // Create new Standard
        $scope.create = function () {
            // Create new Standard object
            var standard = new Standards({
                name: this.name,
                description: this.description
            });
            // Redirect after save
            standard.$save(function (response) {
                console.log('i saved standards');
                $location.path('standards/' + response._id);
                // Clear form fields
                $scope.name = '';
                $scope.description = '';
            }, function (errorResponse) {
                $scope.error = errorResponse.data.message;
            });
            /*$http.post('/standards',$scope.standard).success(function(response){
             console.log(response);
             $scope.standards.push(response);
             });*/
        };
        /*$http.get('/standards').success(function(data){
         $scope.standard=[0];
         });*/

        // Remove existing Standard
        $scope.remove = function (standard) {
            if (standard) {
                standard.$remove();

                for (var i in $scope.standards) {
                    if ($scope.standards [i] === standard) {
                        $scope.standards.splice(i, 1);
                    }
                }
            } else {
                $scope.standard.$remove(function () {
                    $location.path('standards');
                });
            }
        };

        // Update existing Standard
        $scope.update = function () {
            var standard = $scope.standard;

            standard.$update(function () {
                $location.path('standards/' + standard._id);
                /*$http.put('/standards/'+$scope.standard._id,$scope.standard).success(function(response){
                 $scope.standards.push(response);
                 });*/
            }, function (errorResponse) {
                $scope.error = errorResponse.data.message;
            });
        };
        // Find a list of Standards
        $scope.find = function () {
            $scope.standards = Standards.query();
        };

        // Find existing Standard
        $scope.findOne = function () {
            $scope.standard = Standards.get({
                standardId: $stateParams.standardId
            });
        };
    }
]);<commit_msg>edit module standards<commit_after>'use strict';

// Standards controller
angular.module('standards').controller('StandardsController', ['$scope','$stateParams', '$location', 'Authentication', 'Standards',
    function ($scope, $stateParams, $location, Authentication, Standards) {
        $scope.authentication = Authentication;
        $scope.init = function () {
            if ($scope.authentication.user) {
                if ($scope.authentication.user.roles[0] != "commander" && $scope.authentication.user.roles[0] != "agency") {
                    $http.get('/user/checkCurrentUser').success(function (data) {
                        if (data != "okie") {
                            sweetAlert("Truy cập vùng không hợp lệ");
                            window.location.reload();
                        }
                        ;
                    });
                }
                if (window.location.pathname != "/administrator") {
                    $http.get('/findCompanyByShortName' + window.location.pathname).success(function (data) {
                        //$http.get('findCompany/'+data[0]._id).success(function(data1){
                        $scope.company = data[0];
                        document.getElementById('site-head').style.backgroundColor = $scope.company.colorBackground;
                        document.getElementById('onclick-change-showname').style.backgroundColor = $scope.company.colorBackground;
                        //});
                    });
                }
            } else {
                $http.get('/findCompanyByShortName' + window.location.pathname).success(function (data) {
                    //$http.get('findCompany/'+data[0]._id).success(function(data1){
                    $scope.company = data[0];
                    document.getElementById('site-head').style.backgroundColor = $scope.company.colorBackground;
                    document.getElementById('onclick-change-showname').style.backgroundColor = $scope.company.colorBackground;
                    //});
                });
            }

        };
        $scope.init();
        // Create new Standard
        $scope.create = function () {
            // Create new Standard object
            var standard = new Standards({
                name: this.name,
                description: this.description
            });
            // Redirect after save
            standard.$save(function (response) {
                console.log('i saved standards');
                $location.path('standards/' + response._id);
                // Clear form fields
                $scope.name = '';
                $scope.description = '';
            }, function (errorResponse) {
                $scope.error = errorResponse.data.message;
            });
            /*$http.post('/standards',$scope.standard).success(function(response){
             console.log(response);
             $scope.standards.push(response);
             });*/
        };
        /*$http.get('/standards').success(function(data){
         $scope.standard=[0];
         });*/

        // Remove existing Standard
        $scope.remove = function (standard) {
            if (standard) {
                standard.$remove();

                for (var i in $scope.standards) {
                    if ($scope.standards [i] === standard) {
                        $scope.standards.splice(i, 1);
                    }
                }
            } else {
                $scope.standard.$remove(function () {
                    $location.path('standards');
                });
            }
        };

        // Update existing Standard
        $scope.update = function () {
            var standard = $scope.standard;

            standard.$update(function () {
                $location.path('standards/' + standard._id);
                /*$http.put('/standards/'+$scope.standard._id,$scope.standard).success(function(response){
                 $scope.standards.push(response);
                 });*/
            }, function (errorResponse) {
                $scope.error = errorResponse.data.message;
            });
        };
        // Find a list of Standards
        $scope.find = function () {
            $scope.standards = Standards.query();
        };

        // Find existing Standard
        $scope.findOne = function () {
            $scope.standard = Standards.get({
                standardId: $stateParams.standardId
            });
        };
    }
]);<|endoftext|>


<commit_before>/* global define */

(function (root, pluralize) {
  /* istanbul ignore else */
  if (typeof require === 'function' && typeof exports === 'object' && typeof module === 'object') {
    // Node.
    module.exports = pluralize();
  } else if (typeof define === 'function' && define.amd) {
    // AMD, registers as an anonymous module.
    define(function () {
      return pluralize();
    });
  } else {
    // Browser global.
    root.pluralize = pluralize();
  }
})(this, function () {
  // Rule storage - pluralize and singularize need to be run sequentially,
  // while other rules can be optimized using an object for instant lookups.
  var pluralRules = [];
  var singularRules = [];
  var uncountables = {};
  var irregularPlurals = {};
  var irregularSingles = {};

  /**
   * Title case a string.
   *
   * @param  {string} str
   * @return {string}
   */
  function toTitleCase (str) {
    return str.charAt(0).toUpperCase() + str.substr(1).toLowerCase();
  }

  /**
   * Sanitize a pluralization rule to a usable regular expression.
   *
   * @param  {(RegExp|string)} rule
   * @return {RegExp}
   */
  function sanitizeRule (rule) {
    if (typeof rule === 'string') {
      return new RegExp('^' + rule + '$', 'i');
    }

    return rule;
  }

  /**
   * Pass in a word token to produce a function that can replicate the case on
   * another word.
   *
   * @param  {string}   word
   * @param  {string}   token
   * @return {Function}
   */
  function restoreCase (word, token) {
    // Upper cased words. E.g. "HELLO".
    if (word === word.toUpperCase()) {
      return token.toUpperCase();
    }

    // Title cased words. E.g. "Title".
    if (word[0] === word[0].toUpperCase()) {
      return toTitleCase(token);
    }

    // Lower cased words. E.g. "test".
    return token.toLowerCase();
  }

  /**
   * Interpolate a regexp string.
   *
   * @param  {string} str
   * @param  {Array}  args
   * @return {string}
   */
  function interpolate (str, args) {
    return str.replace(/\$(\d{1,2})/g, function (match, index) {
      return args[index] || '';
    });
  }

  /**
   * Sanitize a word by passing in the word and sanitization rules.
   *
   * @param  {String}   token
   * @param  {String}   word
   * @param  {Array}    collection
   * @return {String}
   */
  function sanitizeWord (token, word, collection) {
    // Empty string or doesn't need fixing.
    if (!token.length || uncountables.hasOwnProperty(token)) {
      return word;
    }

    var len = collection.length;

    // Iterate over the sanitization rules and use the first one to match.
    while (len--) {
      var rule = collection[len];

      // If the rule passes, return the replacement.
      if (rule[0].test(word)) {
        return word.replace(rule[0], function (match, index, word) {
          var result = interpolate(rule[1], arguments);

          if (match === '') {
            return restoreCase(word[index - 1], result);
          }

          return restoreCase(match, result);
        });
      }
    }

    return word;
  }

  /**
   * Replace a word with the updated word.
   *
   * @param  {Object}   replaceMap
   * @param  {Object}   keepMap
   * @param  {Array}    rules
   * @return {Function}
   */
  function replaceWord (replaceMap, keepMap, rules) {
    return function (word) {
      // Get the correct token and case restoration functions.
      var token = word.toLowerCase();

      // Check against the keep object map.
      if (keepMap.hasOwnProperty(token)) {
        return restoreCase(word, token);
      }

      // Check against the replacement map for a direct word replacement.
      if (replaceMap.hasOwnProperty(token)) {
        return restoreCase(word, replaceMap[token]);
      }

      // Run all the rules against the word.
      return sanitizeWord(token, word, rules);
    };
  }

  /**
   * Pluralize or singularize a word based on the passed in count.
   *
   * @param  {String}  word
   * @param  {Number}  count
   * @param  {Boolean} inclusive
   * @return {String}
   */
  function pluralize (word, count, inclusive) {
    var pluralized = count === 1
      ? pluralize.singular(word) : pluralize.plural(word);

    return (inclusive ? count + ' ' : '') + pluralized;
  }

  /**
   * Pluralize a word.
   *
   * @type {Function}
   */
  pluralize.plural = replaceWord(
    irregularSingles, irregularPlurals, pluralRules
  );

  /**
   * Singularize a word.
   *
   * @type {Function}
   */
  pluralize.singular = replaceWord(
    irregularPlurals, irregularSingles, singularRules
  );

  /**
   * Add a pluralization rule to the collection.
   *
   * @param {(string|RegExp)} rule
   * @param {string}          replacement
   */
  pluralize.addPluralRule = function (rule, replacement) {
    pluralRules.push([sanitizeRule(rule), replacement]);
  };

  /**
   * Add a singularization rule to the collection.
   *
   * @param {(string|RegExp)} rule
   * @param {string}          replacement
   */
  pluralize.addSingularRule = function (rule, replacement) {
    singularRules.push([sanitizeRule(rule), replacement]);
  };

  /**
   * Add an uncountable word rule.
   *
   * @param {(string|RegExp)} word
   */
  pluralize.addUncountableRule = function (word) {
    if (typeof word === 'string') {
      uncountables[word.toLowerCase()] = true;
      return;
    }

    // Set singular and plural references for the word.
    pluralize.addPluralRule(word, '$0');
    pluralize.addSingularRule(word, '$0');
  };

  /**
   * Add an irregular word definition.
   *
   * @param {String} single
   * @param {String} plural
   */
  pluralize.addIrregularRule = function (single, plural) {
    plural = plural.toLowerCase();
    single = single.toLowerCase();

    irregularSingles[single] = plural;
    irregularPlurals[plural] = single;
  };

  /**
   * Irregular rules.
   */
  [
    // Pronouns.
    ['I', 'we'],
    ['me', 'us'],
    ['he', 'they'],
    ['she', 'they'],
    ['them', 'them'],
    ['myself', 'ourselves'],
    ['yourself', 'yourselves'],
    ['itself', 'themselves'],
    ['herself', 'themselves'],
    ['himself', 'themselves'],
    ['themself', 'themselves'],
    ['is', 'are'],
    ['this', 'these'],
    ['that', 'those'],
    // Words ending in with a consonant and `o`.
    ['echo', 'echoes'],
    ['dingo', 'dingoes'],
    ['volcano', 'volcanoes'],
    ['tornado', 'tornadoes'],
    ['torpedo', 'torpedoes'],
    // Ends with `us`.
    ['genus', 'genera'],
    ['viscus', 'viscera'],
    // Ends with `ma`.
    ['stigma', 'stigmata'],
    ['stoma', 'stomata'],
    ['dogma', 'dogmata'],
    ['lemma', 'lemmata'],
    ['schema', 'schemata'],
    ['anathema', 'anathemata'],
    // Other irregular rules.
    ['ox', 'oxen'],
    ['axe', 'axes'],
    ['die', 'dice'],
    ['yes', 'yeses'],
    ['foot', 'feet'],
    ['eave', 'eaves'],
    ['goose', 'geese'],
    ['tooth', 'teeth'],
    ['quiz', 'quizzes'],
    ['human', 'humans'],
    ['proof', 'proofs'],
    ['carve', 'carves'],
    ['valve', 'valves'],
    ['thief', 'thieves'],
    ['genie', 'genies'],
    ['groove', 'grooves'],
    ['pickaxe', 'pickaxes'],
    ['whiskey', 'whiskies']
  ].forEach(function (rule) {
    return pluralize.addIrregularRule(rule[0], rule[1]);
  });

  /**
   * Pluralization rules.
   */
  [
    [/s?$/i, 's'],
    [/([^aeiou]ese)$/i, '$1'],
    [/(ax|test)is$/i, '$1es'],
    [/(alias|[^aou]us|tlas|gas|ris)$/i, '$1es'],
    [/(e[mn]u)s?$/i, '$1s'],
    [/([^l]ias|[aeiou]las|[emjzr]as|[iu]am)$/i, '$1'],
    [/(alumn|syllab|octop|vir|radi|nucle|fung|cact|stimul|termin|bacill|foc|uter|loc|strat)(?:us|i)$/i, '$1i'],
    [/(alumn|alg|vertebr)(?:a|ae)$/i, '$1ae'],
    [/(seraph|cherub)(?:im)?$/i, '$1im'],
    [/(her|at|gr)o$/i, '$1oes'],
    [/(agend|addend|millenni|dat|extrem|bacteri|desiderat|strat|candelabr|errat|ov|symposi|curricul|automat|quor)(?:a|um)$/i, '$1a'],
    [/(apheli|hyperbat|periheli|asyndet|noumen|phenomen|criteri|organ|prolegomen|hedr|automat)(?:a|on)$/i, '$1a'],
    [/sis$/i, 'ses'],
    [/(?:(kni|wi|li)fe|(ar|l|ea|eo|oa|hoo)f)$/i, '$1$2ves'],
    [/([^aeiouy]|qu)y$/i, '$1ies'],
    [/([^ch][ieo][ln])ey$/i, '$1ies'],
    [/(x|ch|ss|sh|zz)$/i, '$1es'],
    [/(matr|cod|mur|sil|vert|ind|append)(?:ix|ex)$/i, '$1ices'],
    [/(m|l)(?:ice|ouse)$/i, '$1ice'],
    [/(pe)(?:rson|ople)$/i, '$1ople'],
    [/(child)(?:ren)?$/i, '$1ren'],
    [/eaux$/i, '$0'],
    [/m[ae]n$/i, 'men'],
    ['thou', 'you']
  ].forEach(function (rule) {
    return pluralize.addPluralRule(rule[0], rule[1]);
  });

  /**
   * Singularization rules.
   */
  [
    [/s$/i, ''],
    [/(ss)$/i, '$1'],
    [/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)(?:sis|ses)$/i, '$1sis'],
    [/(^analy)(?:sis|ses)$/i, '$1sis'],
    [/(wi|kni|(?:after|half|high|low|mid|non|night|[^\w]|^)li)ves$/i, '$1fe'],
    [/(ar|(?:wo|[ae])l|[eo][ao])ves$/i, '$1f'],
    [/([^aeiouy]|qu)ies$/i, '$1y'],
    [/(^[pl]|zomb|^(?:neck)?t|[aeo][lt]|cut)ies$/i, '$1ie'],
    [/(\b(?:mon|smil))ies$/i, '$1ey'],
    [/(m|l)ice$/i, '$1ouse'],
    [/(seraph|cherub)im$/i, '$1'],
    [/(x|ch|ss|sh|zz|tto|go|cho|alias|[^aou]us|tlas|gas|(?:her|at|gr)o|ris)(?:es)?$/i, '$1'],
    [/(e[mn]u)s?$/i, '$1'],
    [/(movie|twelve)s$/i, '$1'],
    [/(cris|test|diagnos)(?:is|es)$/i, '$1is'],
    [/(alumn|syllab|octop|vir|radi|nucle|fung|cact|stimul|termin|bacill|foc|uter|loc|strat)(?:us|i)$/i, '$1us'],
    [/(agend|addend|millenni|dat|extrem|bacteri|desiderat|strat|candelabr|errat|ov|symposi|curricul|quor)a$/i, '$1um'],
    [/(apheli|hyperbat|periheli|asyndet|noumen|phenomen|criteri|organ|prolegomen|hedr|automat)a$/i, '$1on'],
    [/(alumn|alg|vertebr)ae$/i, '$1a'],
    [/(cod|mur|sil|vert|ind)ices$/i, '$1ex'],
    [/(matr|append)ices$/i, '$1ix'],
    [/(pe)(rson|ople)$/i, '$1rson'],
    [/(child)ren$/i, '$1'],
    [/(eau)x?$/i, '$1'],
    [/men$/i, 'man']
  ].forEach(function (rule) {
    return pluralize.addSingularRule(rule[0], rule[1]);
  });

  /**
   * Uncountable rules.
   */
  [
    // Check with https://en.wiktionary.org/wiki/{{word}}
    // Singular words with no plurals.
    'agenda',
    'ammo',
    'athletics',
    'bison',
    'bream',
    'buffalo',
    'carp',
    'cash',
    'chassis',
    'clothing',
    'cooperation',
    'corps',
    'digestion',
    'debris',
    'diabetes',
    'excretion',
    'expertise',
    'flounder',
    'fun',
    'gallows',
    'garbage',
    'graffiti',
    'headquarters',
    'health',
    'herpes',
    'highjinks',
    'homework',
    'housework',
    'information',
    'jeans',
    'justice',
    'kudos',
    'labour',
    'literature',
    'machinery',
    'mackerel',
    'media',
    'mews',
    'moose',
    'music',
    'news',
    'pike',
    'plankton',
    'pliers',
    'pollution',
    'premises',
    'rain',
    'research',
    'rice',
    'salmon',
    'scissors',
    'series',
    'sewage',
    'shambles',
    'shrimp',
    'species',
    'staff',
    'swine',
    'trout',
    'traffic',
    'transporation',
    'tuna',
    'wealth',
    'welfare',
    'whiting',
    'wildebeest',
    'wildlife',
    'you',
    // Regexes.
    /pox$/i, // "chickpox", "smallpox"
    /ois$/i,
    /deer$/i, // "deer", "reindeer"
    /fish$/i, // "fish", "blowfish", "angelfish"
    /sheep$/i,
    /measles$/i,
    /[^aeiou]ese$/i // "chinese", "japanese"
  ].forEach(pluralize.addUncountableRule);

  return pluralize;
});
<commit_msg>removing comment for source<commit_after>/* global define */

(function (root, pluralize) {
  /* istanbul ignore else */
  if (typeof require === 'function' && typeof exports === 'object' && typeof module === 'object') {
    // Node.
    module.exports = pluralize();
  } else if (typeof define === 'function' && define.amd) {
    // AMD, registers as an anonymous module.
    define(function () {
      return pluralize();
    });
  } else {
    // Browser global.
    root.pluralize = pluralize();
  }
})(this, function () {
  // Rule storage - pluralize and singularize need to be run sequentially,
  // while other rules can be optimized using an object for instant lookups.
  var pluralRules = [];
  var singularRules = [];
  var uncountables = {};
  var irregularPlurals = {};
  var irregularSingles = {};

  /**
   * Title case a string.
   *
   * @param  {string} str
   * @return {string}
   */
  function toTitleCase (str) {
    return str.charAt(0).toUpperCase() + str.substr(1).toLowerCase();
  }

  /**
   * Sanitize a pluralization rule to a usable regular expression.
   *
   * @param  {(RegExp|string)} rule
   * @return {RegExp}
   */
  function sanitizeRule (rule) {
    if (typeof rule === 'string') {
      return new RegExp('^' + rule + '$', 'i');
    }

    return rule;
  }

  /**
   * Pass in a word token to produce a function that can replicate the case on
   * another word.
   *
   * @param  {string}   word
   * @param  {string}   token
   * @return {Function}
   */
  function restoreCase (word, token) {
    // Upper cased words. E.g. "HELLO".
    if (word === word.toUpperCase()) {
      return token.toUpperCase();
    }

    // Title cased words. E.g. "Title".
    if (word[0] === word[0].toUpperCase()) {
      return toTitleCase(token);
    }

    // Lower cased words. E.g. "test".
    return token.toLowerCase();
  }

  /**
   * Interpolate a regexp string.
   *
   * @param  {string} str
   * @param  {Array}  args
   * @return {string}
   */
  function interpolate (str, args) {
    return str.replace(/\$(\d{1,2})/g, function (match, index) {
      return args[index] || '';
    });
  }

  /**
   * Sanitize a word by passing in the word and sanitization rules.
   *
   * @param  {String}   token
   * @param  {String}   word
   * @param  {Array}    collection
   * @return {String}
   */
  function sanitizeWord (token, word, collection) {
    // Empty string or doesn't need fixing.
    if (!token.length || uncountables.hasOwnProperty(token)) {
      return word;
    }

    var len = collection.length;

    // Iterate over the sanitization rules and use the first one to match.
    while (len--) {
      var rule = collection[len];

      // If the rule passes, return the replacement.
      if (rule[0].test(word)) {
        return word.replace(rule[0], function (match, index, word) {
          var result = interpolate(rule[1], arguments);

          if (match === '') {
            return restoreCase(word[index - 1], result);
          }

          return restoreCase(match, result);
        });
      }
    }

    return word;
  }

  /**
   * Replace a word with the updated word.
   *
   * @param  {Object}   replaceMap
   * @param  {Object}   keepMap
   * @param  {Array}    rules
   * @return {Function}
   */
  function replaceWord (replaceMap, keepMap, rules) {
    return function (word) {
      // Get the correct token and case restoration functions.
      var token = word.toLowerCase();

      // Check against the keep object map.
      if (keepMap.hasOwnProperty(token)) {
        return restoreCase(word, token);
      }

      // Check against the replacement map for a direct word replacement.
      if (replaceMap.hasOwnProperty(token)) {
        return restoreCase(word, replaceMap[token]);
      }

      // Run all the rules against the word.
      return sanitizeWord(token, word, rules);
    };
  }

  /**
   * Pluralize or singularize a word based on the passed in count.
   *
   * @param  {String}  word
   * @param  {Number}  count
   * @param  {Boolean} inclusive
   * @return {String}
   */
  function pluralize (word, count, inclusive) {
    var pluralized = count === 1
      ? pluralize.singular(word) : pluralize.plural(word);

    return (inclusive ? count + ' ' : '') + pluralized;
  }

  /**
   * Pluralize a word.
   *
   * @type {Function}
   */
  pluralize.plural = replaceWord(
    irregularSingles, irregularPlurals, pluralRules
  );

  /**
   * Singularize a word.
   *
   * @type {Function}
   */
  pluralize.singular = replaceWord(
    irregularPlurals, irregularSingles, singularRules
  );

  /**
   * Add a pluralization rule to the collection.
   *
   * @param {(string|RegExp)} rule
   * @param {string}          replacement
   */
  pluralize.addPluralRule = function (rule, replacement) {
    pluralRules.push([sanitizeRule(rule), replacement]);
  };

  /**
   * Add a singularization rule to the collection.
   *
   * @param {(string|RegExp)} rule
   * @param {string}          replacement
   */
  pluralize.addSingularRule = function (rule, replacement) {
    singularRules.push([sanitizeRule(rule), replacement]);
  };

  /**
   * Add an uncountable word rule.
   *
   * @param {(string|RegExp)} word
   */
  pluralize.addUncountableRule = function (word) {
    if (typeof word === 'string') {
      uncountables[word.toLowerCase()] = true;
      return;
    }

    // Set singular and plural references for the word.
    pluralize.addPluralRule(word, '$0');
    pluralize.addSingularRule(word, '$0');
  };

  /**
   * Add an irregular word definition.
   *
   * @param {String} single
   * @param {String} plural
   */
  pluralize.addIrregularRule = function (single, plural) {
    plural = plural.toLowerCase();
    single = single.toLowerCase();

    irregularSingles[single] = plural;
    irregularPlurals[plural] = single;
  };

  /**
   * Irregular rules.
   */
  [
    // Pronouns.
    ['I', 'we'],
    ['me', 'us'],
    ['he', 'they'],
    ['she', 'they'],
    ['them', 'them'],
    ['myself', 'ourselves'],
    ['yourself', 'yourselves'],
    ['itself', 'themselves'],
    ['herself', 'themselves'],
    ['himself', 'themselves'],
    ['themself', 'themselves'],
    ['is', 'are'],
    ['this', 'these'],
    ['that', 'those'],
    // Words ending in with a consonant and `o`.
    ['echo', 'echoes'],
    ['dingo', 'dingoes'],
    ['volcano', 'volcanoes'],
    ['tornado', 'tornadoes'],
    ['torpedo', 'torpedoes'],
    // Ends with `us`.
    ['genus', 'genera'],
    ['viscus', 'viscera'],
    // Ends with `ma`.
    ['stigma', 'stigmata'],
    ['stoma', 'stomata'],
    ['dogma', 'dogmata'],
    ['lemma', 'lemmata'],
    ['schema', 'schemata'],
    ['anathema', 'anathemata'],
    // Other irregular rules.
    ['ox', 'oxen'],
    ['axe', 'axes'],
    ['die', 'dice'],
    ['yes', 'yeses'],
    ['foot', 'feet'],
    ['eave', 'eaves'],
    ['goose', 'geese'],
    ['tooth', 'teeth'],
    ['quiz', 'quizzes'],
    ['human', 'humans'],
    ['proof', 'proofs'],
    ['carve', 'carves'],
    ['valve', 'valves'],
    ['thief', 'thieves'],
    ['genie', 'genies'],
    ['groove', 'grooves'],
    ['pickaxe', 'pickaxes'],
    ['whiskey', 'whiskies']
  ].forEach(function (rule) {
    return pluralize.addIrregularRule(rule[0], rule[1]);
  });

  /**
   * Pluralization rules.
   */
  [
    [/s?$/i, 's'],
    [/([^aeiou]ese)$/i, '$1'],
    [/(ax|test)is$/i, '$1es'],
    [/(alias|[^aou]us|tlas|gas|ris)$/i, '$1es'],
    [/(e[mn]u)s?$/i, '$1s'],
    [/([^l]ias|[aeiou]las|[emjzr]as|[iu]am)$/i, '$1'],
    [/(alumn|syllab|octop|vir|radi|nucle|fung|cact|stimul|termin|bacill|foc|uter|loc|strat)(?:us|i)$/i, '$1i'],
    [/(alumn|alg|vertebr)(?:a|ae)$/i, '$1ae'],
    [/(seraph|cherub)(?:im)?$/i, '$1im'],
    [/(her|at|gr)o$/i, '$1oes'],
    [/(agend|addend|millenni|dat|extrem|bacteri|desiderat|strat|candelabr|errat|ov|symposi|curricul|automat|quor)(?:a|um)$/i, '$1a'],
    [/(apheli|hyperbat|periheli|asyndet|noumen|phenomen|criteri|organ|prolegomen|hedr|automat)(?:a|on)$/i, '$1a'],
    [/sis$/i, 'ses'],
    [/(?:(kni|wi|li)fe|(ar|l|ea|eo|oa|hoo)f)$/i, '$1$2ves'],
    [/([^aeiouy]|qu)y$/i, '$1ies'],
    [/([^ch][ieo][ln])ey$/i, '$1ies'],
    [/(x|ch|ss|sh|zz)$/i, '$1es'],
    [/(matr|cod|mur|sil|vert|ind|append)(?:ix|ex)$/i, '$1ices'],
    [/(m|l)(?:ice|ouse)$/i, '$1ice'],
    [/(pe)(?:rson|ople)$/i, '$1ople'],
    [/(child)(?:ren)?$/i, '$1ren'],
    [/eaux$/i, '$0'],
    [/m[ae]n$/i, 'men'],
    ['thou', 'you']
  ].forEach(function (rule) {
    return pluralize.addPluralRule(rule[0], rule[1]);
  });

  /**
   * Singularization rules.
   */
  [
    [/s$/i, ''],
    [/(ss)$/i, '$1'],
    [/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)(?:sis|ses)$/i, '$1sis'],
    [/(^analy)(?:sis|ses)$/i, '$1sis'],
    [/(wi|kni|(?:after|half|high|low|mid|non|night|[^\w]|^)li)ves$/i, '$1fe'],
    [/(ar|(?:wo|[ae])l|[eo][ao])ves$/i, '$1f'],
    [/([^aeiouy]|qu)ies$/i, '$1y'],
    [/(^[pl]|zomb|^(?:neck)?t|[aeo][lt]|cut)ies$/i, '$1ie'],
    [/(\b(?:mon|smil))ies$/i, '$1ey'],
    [/(m|l)ice$/i, '$1ouse'],
    [/(seraph|cherub)im$/i, '$1'],
    [/(x|ch|ss|sh|zz|tto|go|cho|alias|[^aou]us|tlas|gas|(?:her|at|gr)o|ris)(?:es)?$/i, '$1'],
    [/(e[mn]u)s?$/i, '$1'],
    [/(movie|twelve)s$/i, '$1'],
    [/(cris|test|diagnos)(?:is|es)$/i, '$1is'],
    [/(alumn|syllab|octop|vir|radi|nucle|fung|cact|stimul|termin|bacill|foc|uter|loc|strat)(?:us|i)$/i, '$1us'],
    [/(agend|addend|millenni|dat|extrem|bacteri|desiderat|strat|candelabr|errat|ov|symposi|curricul|quor)a$/i, '$1um'],
    [/(apheli|hyperbat|periheli|asyndet|noumen|phenomen|criteri|organ|prolegomen|hedr|automat)a$/i, '$1on'],
    [/(alumn|alg|vertebr)ae$/i, '$1a'],
    [/(cod|mur|sil|vert|ind)ices$/i, '$1ex'],
    [/(matr|append)ices$/i, '$1ix'],
    [/(pe)(rson|ople)$/i, '$1rson'],
    [/(child)ren$/i, '$1'],
    [/(eau)x?$/i, '$1'],
    [/men$/i, 'man']
  ].forEach(function (rule) {
    return pluralize.addSingularRule(rule[0], rule[1]);
  });

  /**
   * Uncountable rules.
   */
  [
    // Singular words with no plurals.
    'agenda',
    'ammo',
    'athletics',
    'bison',
    'bream',
    'buffalo',
    'carp',
    'cash',
    'chassis',
    'clothing',
    'cooperation',
    'corps',
    'digestion',
    'debris',
    'diabetes',
    'excretion',
    'expertise',
    'flounder',
    'fun',
    'gallows',
    'garbage',
    'graffiti',
    'headquarters',
    'health',
    'herpes',
    'highjinks',
    'homework',
    'housework',
    'information',
    'jeans',
    'justice',
    'kudos',
    'labour',
    'literature',
    'machinery',
    'mackerel',
    'media',
    'mews',
    'moose',
    'music',
    'news',
    'pike',
    'plankton',
    'pliers',
    'pollution',
    'premises',
    'rain',
    'research',
    'rice',
    'salmon',
    'scissors',
    'series',
    'sewage',
    'shambles',
    'shrimp',
    'species',
    'staff',
    'swine',
    'trout',
    'traffic',
    'transporation',
    'tuna',
    'wealth',
    'welfare',
    'whiting',
    'wildebeest',
    'wildlife',
    'you',
    // Regexes.
    /pox$/i, // "chickpox", "smallpox"
    /ois$/i,
    /deer$/i, // "deer", "reindeer"
    /fish$/i, // "fish", "blowfish", "angelfish"
    /sheep$/i,
    /measles$/i,
    /[^aeiou]ese$/i // "chinese", "japanese"
  ].forEach(pluralize.addUncountableRule);

  return pluralize;
});
<|endoftext|>