<commit_before>/* @flow */

import type {Reporter} from '../../reporters/index.js';
import type Config from '../../config.js';
import NpmRegistry from '../../registries/npm-registry.js';

let semver = require('semver');

function clean(object: any): any {
  if (Array.isArray(object)) {
    const result = [];
    object.forEach((item) => {
      item = clean(item);
      if (item) {
        result.push(item);
      }
    });
    return result;
  } else if (typeof object === 'object') {
    const result = {};
    for (const key in object) {
      if (key.startsWith('_')) {
        continue;
      }

      const item = clean(object[key]);
      if (item) {
        result[key] = item;
      }
    }
    return result;
  } else if (object) {
    return object;
  } else {
    return null;
  }
}

export async function run(
 config: Config,
 reporter: Reporter,
 flags: Object,
 args: Array<string>,
): Promise<void> {
  if (args.length !== 1 && args.length !== 2) {
    return;
  }

  let moduleName = NpmRegistry.escapeName(args.shift());
  let version;
  const field = args.shift();
  const parts = moduleName.split('@');
  if (parts.length > 1) {
    moduleName = parts.shift();
    version = parts.join('@');
  }

  let result = await config.registries.npm.request(moduleName);
  if (!result) {
    reporter.error(reporter.lang('infoFail'));
    return;
  }

  result = clean(result);

  const versions = result.versions;
  // $FlowFixMe
  result.versions = Object.keys(versions).sort(semver.compareLoose);
  result.version = version || result.versions[result.versions.length - 1];
  result = Object.assign(result, versions[result.version]);

  // Readmes can be long so exclude them unless explicitly asked for.
  if (field !== 'readme') {
    delete result.readme;
  }

  reporter.inspect(field ? result[field] : result);
}
<commit_msg>fix: support scoped packages with yarn info<commit_after>/* @flow */

import type {Reporter} from '../../reporters/index.js';
import type Config from '../../config.js';
import NpmRegistry from '../../registries/npm-registry.js';

let semver = require('semver');
const PKG_INPUT = /(^\S[^\s@]+)(?:@(\S+))?$/;

function clean(object: any): any {
  if (Array.isArray(object)) {
    const result = [];
    object.forEach((item) => {
      item = clean(item);
      if (item) {
        result.push(item);
      }
    });
    return result;
  } else if (typeof object === 'object') {
    const result = {};
    for (const key in object) {
      if (key.startsWith('_')) {
        continue;
      }

      const item = clean(object[key]);
      if (item) {
        result[key] = item;
      }
    }
    return result;
  } else if (object) {
    return object;
  } else {
    return null;
  }
}

export async function run(
 config: Config,
 reporter: Reporter,
 flags: Object,
 args: Array<string>,
): Promise<void> {
  if (args.length !== 1 && args.length !== 2) {
    return;
  }

  let packageInput = NpmRegistry.escapeName(args.shift());
  const field = args.shift();

  const parts = PKG_INPUT.exec(packageInput);
  const packageName = parts[1];
  const packageVersion = parts[2];

  let result = await config.registries.npm.request(packageName);
  if (!result) {
    reporter.error(reporter.lang('infoFail'));
    return;
  }

  result = clean(result);

  const versions = result.versions;
  // $FlowFixMe
  result.versions = Object.keys(versions).sort(semver.compareLoose);
  result.version = packageVersion || result.versions[result.versions.length - 1];
  result = Object.assign(result, versions[result.version]);

  // Readmes can be long so exclude them unless explicitly asked for.
  if (field !== 'readme') {
    delete result.readme;
  }

  reporter.inspect(field ? result[field] : result);
}
<|endoftext|>


<commit_before>'use strict';

//  TODO - test

var baseUrl = '/api/player/';
var restUrl = '/new';

angular.module('twistedHangmanApp').controller('CreateCtrl', function ($rootScope, $scope, twGameFeatureService, twCurrentPlayerService, $http) {
  $scope.url = baseUrl + twCurrentPlayerService.currentID() + restUrl;
  $scope.featureData = {};
  twGameFeatureService.features().then(function (data) {
    $scope.featureData = data;
  });
  $scope.thieving = 'Thieving';
  $scope.drawGallows = '';
  $scope.drawFace = '';
  $scope.gamePace = '';

  $scope.setSinglePlayer = function () {
    $scope.playerCount = 'SinglePlayer';
    $scope.players = [];
    $scope.gamePace = '';
    $scope.puzzleSetter = 'SystemPuzzles';
    $scope.winners = 'SingleWinner';
    $scope.h2hEnabled = false;
    $scope.alternatingEnabled = false;
    $scope.allFinishedEnabled = false;
    $scope.turnBasedEnabled = false;
  };

  $scope.setTwoPlayers = function () {
    $scope.playerCount = 'TwoPlayer';
    if ($scope.players.length > 1) {
      $scope.players = [];
    }
    $scope.h2hEnabled = true;
    $scope.alternatingEnabled = true;
    $scope.allFinishedEnabled = true;
    $scope.turnBasedEnabled = true;
  };

  $scope.setThreePlayers = function () {
    $scope.playerCount = 'ThreePlus';
    if ($scope.puzzleSetter === '') {
      $scope.puzzleSetter = 'SystemPuzzles';
    }
    $scope.h2hEnabled = false;
    $scope.alternatingEnabled = true;
    $scope.allFinishedEnabled = true;
    $scope.turnBasedEnabled = true;
  };

  $scope.createGame = function () {
    var featureNames = ['puzzleSetter', 'playerCount', 'thieving', 'drawGallows', 'drawFace', 'gamePace'];
    var featureSet = [];
    var players = [];
    featureNames.forEach(function (name) {
      var data = $scope[name];
      if ((typeof data !== 'undefined') && (data !== '')) {
        featureSet.push(data);
      }
    });
    $http.post($scope.url, {'players': players, 'features': featureSet}).success(function (data) {
      $rootScope.$broadcast('refreshGames', '');
      console.log(data);
    }).error(function (data, status, headers, config) {
      //  TODO
      console.log(data + status + headers + config);
    });
  };

  //  Initialize
  $scope.setSinglePlayer();
});
<commit_msg>refresh game broadcast<commit_after>'use strict';

//  TODO - test

var baseUrl = '/api/player/';
var restUrl = '/new';

angular.module('twistedHangmanApp').controller('CreateCtrl', function ($rootScope, $scope, twGameFeatureService, twCurrentPlayerService, $http) {
  $scope.url = baseUrl + twCurrentPlayerService.currentID() + restUrl;
  $scope.featureData = {};
  twGameFeatureService.features().then(function (data) {
    $scope.featureData = data;
  });
  $scope.thieving = 'Thieving';
  $scope.drawGallows = '';
  $scope.drawFace = '';
  $scope.gamePace = '';

  $scope.setSinglePlayer = function () {
    $scope.playerCount = 'SinglePlayer';
    $scope.players = [];
    $scope.gamePace = '';
    $scope.puzzleSetter = 'SystemPuzzles';
    $scope.winners = 'SingleWinner';
    $scope.h2hEnabled = false;
    $scope.alternatingEnabled = false;
    $scope.allFinishedEnabled = false;
    $scope.turnBasedEnabled = false;
  };

  $scope.setTwoPlayers = function () {
    $scope.playerCount = 'TwoPlayer';
    if ($scope.players.length > 1) {
      $scope.players = [];
    }
    $scope.h2hEnabled = true;
    $scope.alternatingEnabled = true;
    $scope.allFinishedEnabled = true;
    $scope.turnBasedEnabled = true;
  };

  $scope.setThreePlayers = function () {
    $scope.playerCount = 'ThreePlus';
    if ($scope.puzzleSetter === '') {
      $scope.puzzleSetter = 'SystemPuzzles';
    }
    $scope.h2hEnabled = false;
    $scope.alternatingEnabled = true;
    $scope.allFinishedEnabled = true;
    $scope.turnBasedEnabled = true;
  };

  $scope.createGame = function () {
    var featureNames = ['puzzleSetter', 'playerCount', 'thieving', 'drawGallows', 'drawFace', 'gamePace'];
    var featureSet = [];
    var players = [];
    featureNames.forEach(function (name) {
      var data = $scope[name];
      if ((typeof data !== 'undefined') && (data !== '')) {
        featureSet.push(data);
      }
    });
    $http.post($scope.url, {'players': players, 'features': featureSet}).success(function (data) {
      $rootScope.$broadcast('refreshGames', '');
      // TODO
      console.log(data);
    }).error(function (data, status, headers, config) {
      //  TODO
      console.log(data + status + headers + config);
    });
  };

  //  Initialize
  $scope.setSinglePlayer();
});
<|endoftext|>


<commit_before>'use strict';

/**
 * A very simple Flash "socket policy server". The Flash runtime needs
 * to read this policy from any server before allowing the SWF file
 * (the game client in our case) to establish a TCP socket connection
 * to that server.
 *
 * @see https://www.adobe.com/devnet/flashplayer/articles/socket_policy_files.html
 *
 * @module
 */

// public interface
module.exports = {
	start: start,
};

var net = require('net');
var config = require('config');

var POLICY = '\
<cross-domain-policy>\n\
	<site-control permitted-cross-domain-policies="all" />\n\
	<allow-access-from domain="*" to-ports="*" />\n\
</cross-domain-policy>\n\x00';

function start() {
	var host = config.get('net:gameServers:' + config.getGsid() + ':host');
	var port = config.get('net:flashPolicyPort');
	var server = net.createServer(handleConnect);
	server.listen(port, host, function onListening() {
		log.info('policy server listening on %s:%s', host, port);
	});
}

function handleConnect(socket) {
	socket.on('data', function onData(data) {
		if (data.toString().slice(0, 20) === '<policy-file-request') {
			log.info('Flash policy request from %s:%s',
				socket.remoteAddress, socket.remotePort);
			socket.write(POLICY, 'binary');
		}
		socket.end();
	});
}
<commit_msg>Handle errors on the policy server<commit_after>'use strict';

/**
 * A very simple Flash "socket policy server". The Flash runtime needs
 * to read this policy from any server before allowing the SWF file
 * (the game client in our case) to establish a TCP socket connection
 * to that server.
 *
 * @see https://www.adobe.com/devnet/flashplayer/articles/socket_policy_files.html
 *
 * @module
 */

// public interface
module.exports = {
	start: start,
};

var net = require('net');
var config = require('config');

var POLICY = '\
<cross-domain-policy>\n\
	<site-control permitted-cross-domain-policies="all" />\n\
	<allow-access-from domain="*" to-ports="*" />\n\
</cross-domain-policy>\n\x00';

function start() {
	var host = config.get('net:gameServers:' + config.getGsid() + ':host');
	var port = config.get('net:flashPolicyPort');
	var server = net.createServer(handleConnect);
	server.listen(port, host, function onListening() {
		log.info('policy server listening on %s:%s', host, port);
	});
}

function handleConnect(socket) {
	socket.on('data', function onData(data) {
		if (data.toString().slice(0, 20) === '<policy-file-request') {
			log.info('Flash policy request from %s:%s',
				socket.remoteAddress, socket.remotePort);
			socket.write(POLICY, 'binary');
		}
		socket.end();
	});
	socket.on('error', function onError(err) {
		log.error(err, 'policy server error: %s', err.message);
	});
}
<|endoftext|>


<commit_before>import * as actions from './actions';

// This isn't really common across platforms
import {Actions} from 'react-native-router-flux';

import * as routes from '../lib/routes';
import {
  assoc,
  findLast,
  is,
  map,
  merge,
  pick,
  pickBy,
  propEq,
} from 'ramda';

const initialState = {
  currentPath: null,
  currentRoute: null,
  drawerEnabled: true,
  drawerOpen: false,
  primaryRoute: {
    name: 'logAgenda',
  },
};

// pick a subset able to be passed around
function pickRoute(route) {
  const top = pick(
    [
      'name',
      'title',
      'type',
    ],
    route
  );
  const props = pickBy(
    p => is(String, p) || is(Function, p),
    route.props
  );
  return assoc('props', props, top);
};

function setCurrentRoute(base, state) {
  const currentRoute = routes.current(base);
  const route = pickRoute(currentRoute);
  const path = map(pickRoute, routes.path(currentRoute));
  const primary = findLast(propEq('type', 'replace'), path);
  return merge(
    state,
    {
      currentRoute: route,
      currentPath: path,
      primaryRoute: primary,
    }
  );
}

export default function uiReducer(state = initialState, action) {

  switch (action.type) {

    case actions.CLOSE_DRAWER: {
      return assoc('drawerOpen', false, state);
    }

    case actions.OPEN_DRAWER: {
      return assoc('drawerOpen', true, state);
    }

    case actions.ON_DRAWER_CHANGE: {
      return assoc('drawerOpen', action.payload, state);
    }

    case actions.SET_DRAWER_ENABLED: {
      return assoc('drawerEnabled', action.payload, state);
    }

    // Routing Actions
    case Actions.AFTER_ROUTE:
    case Actions.AFTER_POP: {
      return setCurrentRoute(action.route, state);
    }

    case actions.SET_ROUTE: {
      return setCurrentRoute(action.payload, state);
    }

  }

  return state;
}
<commit_msg>fix primary route settings by handling when there is no new primary route<commit_after>import * as actions from './actions';

// This isn't really common across platforms
import {Actions} from 'react-native-router-flux';

import * as routes from '../lib/routes';
import {
  assoc,
  findLast,
  is,
  map,
  merge,
  pick,
  pickBy,
  propEq,
} from 'ramda';

const initialState = {
  currentPath: null,
  currentRoute: null,
  drawerEnabled: true,
  drawerOpen: false,
  primaryRoute: {
    name: 'logAgenda',
  },
};

// pick a subset able to be passed around
function pickRoute(route) {
  const top = pick(
    [
      'name',
      'title',
      'type',
    ],
    route
  );
  const props = pickBy(
    p => is(String, p) || is(Function, p),
    route.props
  );
  return assoc('props', props, top);
};

function setCurrentRoute(base, state) {
  const currentRoute = routes.current(base);
  const route = pickRoute(currentRoute);
  const path = map(pickRoute, routes.path(currentRoute));
  const primary = findLast(propEq('type', 'replace'), path);
  return merge(
    state,
    {
      currentRoute: route,
      currentPath: path,
      primaryRoute: primary || state.primaryRoute,
    }
  );
}

export default function uiReducer(state = initialState, action) {

  switch (action.type) {

    case actions.CLOSE_DRAWER: {
      return assoc('drawerOpen', false, state);
    }

    case actions.OPEN_DRAWER: {
      return assoc('drawerOpen', true, state);
    }

    case actions.ON_DRAWER_CHANGE: {
      return assoc('drawerOpen', action.payload, state);
    }

    case actions.SET_DRAWER_ENABLED: {
      return assoc('drawerEnabled', action.payload, state);
    }

    // Routing Actions
    case Actions.AFTER_ROUTE:
    case Actions.AFTER_POP: {
      return setCurrentRoute(action.route, state);
    }

    case actions.SET_ROUTE: {
      return setCurrentRoute(action.payload, state);
    }

  }

  return state;
}
<|endoftext|>


<commit_before>import { Record } from 'immutable';

// Record is like class, but immutable and with default values.
// https://facebook.github.io/immutable-js/docs/#/Record
const User = Record({
  authenticatedAt: null,
  displayName: '',
  email: '',
  id: '',
  profileImageURL: '',
  provider: ''
});

export default User;
<commit_msg>Little example for compound keys<commit_after>import { Record } from 'immutable';

// Record is like class, but immutable and with default values.
// https://facebook.github.io/immutable-js/docs/#/Record
const User = Record({
  authenticatedAt: null,
  displayName: '',
  email: '',
  id: '',
  profileImageURL: '',
  provider: ''
});

export default User;

// // Note we can subclass Record to add en.wikipedia.org/wiki/Compound_key
// export default class extends User {

//   static id(email, provider) {
//     return [email, email].join();
//   }

//   get id() {
//     return [this.email, this.provider].join();
//   }

// }
<|endoftext|>


<commit_before>require('styles/main.scss');
require('styles/footer.scss');

var React = require('react');

var FooterComponent = React.createClass({

  render: function() {
    return (

Done with ♥

Tembusu College

    );
  }

});

module.exports = FooterComponent;

<commit_msg>Update footer content<commit_after>require('styles/main.scss');
require('styles/footer.scss');

var React = require('react');

var FooterComponent = React.createClass({

  render: function() {
    return (

Done with ♥

Tembusu College, UTC2101

    );
  }

});

module.exports = FooterComponent;

<|endoftext|>


<commit_before>import React from 'react';
import { Link } from 'react-router-dom';
import { HashLink } from 'react-router-hash-link';
import styled from '@emotion/styled';

import Box from './Box';
import Text from './Text';

import config from '../config';

import domestosLogo from '../images/domestos_logo3.png';
import domestosUseLoos from '../images/domestos_use_our_loos_logo.png';

const DomestosLogo = styled((props) => (

))`
  height: 2rem;
`;

const UseOurLoosLogo = styled((props) => (

))`
  height: 2rem;
`;

const Footer = ({ children }) => (
  <Box
    as="footer"
    display="flex"
    flexDirection={['column', 'row']}
    justifyContent="space-between"
    alignItems="center"
    px={[3, 4]}
    py={[0, 2]}
    bg={['transparent', 'lightGrey']}
    color="primary"
    minHeight={60}
  >
    {config.shouldShowSponsor() && (
      <HashLink
        to="/use-our-loos"
        title="Domestos: Use Our Loos Campaign"
        scroll={(el) => el.scrollIntoView(true)}
      >
        <Box
          display="flex"
          flexDirection={['column', 'row']}
          alignItems="center"
        >
          <Text fontSize={14}>
            Proudly sponsored by Domestos
          </Text>

          <Box display="flex" ml={[0, 3]} mb={[3, 0]} order={[-1, 0]}>
            <UseOurLoosLogo />
            <Box ml={2}>
              <DomestosLogo />
            </Box>
          </Box>
        </Box>
      </HashLink>
    )}

    <Box order={[-1, 0]} mb={[4, 0]}>
      <Text fontSize={[12, 16]}>
        <Box as="ul" display={['block', 'flex']} alignItems="center">
          {React.Children.toArray(children, (child, index) => (

{child}

          ))}

          <Box as="li" ml={[0, 4]}>
            <Link to="/privacy">Privacy Policy</Link>
          </Box>
        </Box>
      </Text>
    </Box>
  </Box>
);

export default Footer;
<commit_msg>fix: correct footer semantics<commit_after>import React from 'react';
import { Link } from 'react-router-dom';
import { HashLink } from 'react-router-hash-link';
import styled from '@emotion/styled';

import Box from './Box';
import Text from './Text';

import config from '../config';

import domestosLogo from '../images/domestos_logo3.png';
import domestosUseLoos from '../images/domestos_use_our_loos_logo.png';

const DomestosLogo = styled((props) => (

))`
  height: 2rem;
`;

const UseOurLoosLogo = styled((props) => (

))`
  height: 2rem;
`;

const Footer = ({ children }) => (
  <Box
    as="footer"
    display="flex"
    flexDirection={['column', 'row']}
    justifyContent="space-between"
    alignItems="center"
    px={[3, 4]}
    py={[0, 2]}
    bg={['transparent', 'lightGrey']}
    color="primary"
    minHeight={60}
  >
    {config.shouldShowSponsor() && (
      <HashLink
        to="/use-our-loos"
        title="Domestos: Use Our Loos Campaign"
        scroll={(el) => el.scrollIntoView(true)}
      >
        <Box
          display="flex"
          flexDirection={['column', 'row']}
          alignItems="center"
        >
          <Text fontSize={14}>
            Proudly sponsored by Domestos
          </Text>

          <Box display="flex" ml={[0, 3]} mb={[3, 0]} order={[-1, 0]}>
            <UseOurLoosLogo />
            <Box ml={2}>
              <DomestosLogo />
            </Box>
          </Box>
        </Box>
      </HashLink>
    )}

    <Box order={[-1, 0]} mb={[4, 0]}>
      <Text fontSize={[12, 16]}>
        <Box as="ul" display={['block', 'flex']} alignItems="center">
          {React.Children.map(children, (child, index) => (

{child}

          ))}

          <Box as="li" ml={[0, 4]}>
            <Link to="/privacy">Privacy Policy</Link>
          </Box>
        </Box>
      </Text>
    </Box>
  </Box>
);

export default Footer;
<|endoftext|>


<commit_before>import React from 'react';
import { Link } from 'gatsby';
import PropTypes from 'prop-types';
import {
  SprkMasthead,
  SprkTextInput,
  SprkLink,
} from '@sparkdesignsystem/spark-react';
import SiteLogo from './site-logo';
import { useInstallingSparkData } from '../hooks/use-installing-spark';
import { useUsingSparkData } from '../hooks/use-using-spark';
import { usePrincipleSparkData } from '../hooks/use-principle-spark';

const Header = ({ setContext }) => {
  const utilityItems = [
    <SprkLink
      onClick={() => {
        setContext('installing-spark');
      }}
      additionalClasses="sprk-c-Masthead__link"
      variant="simple"
      element={Link}
      to="/installing-spark"
    >
      Installing Spark
    </SprkLink>,
    <SprkLink
      onClick={() => {
        setContext('using-spark');
      }}
      additionalClasses="sprk-c-Masthead__link"
      variant="simple"
      element={Link}
      to="/using-spark"
    >
      Using Spark
    </SprkLink>,
    <SprkLink
      onClick={() => {
        setContext('principles');
      }}
      additionalClasses="sprk-c-Masthead__link"
      variant="simple"
      element={Link}
      to="/principles/design-principles"
    >
      Principles
    </SprkLink>,
    <SprkTextInput
      additionalClasses="docs-header-search--wide sprk-u-mbn"
      leadingIcon="search"
      hiddenLabel
      name="InlineSearch"
      placeholder="Search"
    />,
  ];

  const installingSparkPages = useInstallingSparkData().map((page) => ({
    text: page.node.frontmatter.title,
    to: `/installing-spark/${page.node.parent.name}`,
    element: Link,
  }));

  const usingSparkComponents = useUsingSparkData().components.map((page) => ({
    text: page.node.frontmatter.title,
    to: `/using-spark/components/${page.node.parent.name}`,
    element: Link,
  }));

  const usingSparkExamples = useUsingSparkData().examples.map((page) => ({
    text: page.node.frontmatter.title,
    to: `/using-spark/examples/${page.node.parent.name}`,
    element: Link,
  }));

  const usingSparkFoundations = useUsingSparkData().foundations.map((page) => ({
    text: page.node.frontmatter.title,
    to: `/using-spark/foundations/${page.node.parent.name}`,
    element: Link,
  }));

  const usingSparkGuides = useUsingSparkData().guides.map((page) => ({
    text: page.node.frontmatter.title,
    to: `/using-spark/guides/${page.node.parent.name}`,
    element: Link,
  }));

  const usingSparkPages = usingSparkFoundations.concat(
    usingSparkGuides,
    usingSparkComponents,
    usingSparkExamples,
  );

  const principlePages = usePrincipleSparkData().map((page) => ({
    text: page.node.frontmatter.title,
    to: `/principles/${page.node.parent.name}`,
    element: Link,
  }));

  const narrowNavLinks = [
    {
      element: Link,
      text: 'Installing Spark',
      to: '/installing-spark/html-environment-setup',
      onClick: () => {
        setContext('installing-spark');
      },
      subNavLinks: installingSparkPages,
    },
    {
      element: Link,
      text: 'Using Spark',
      to: '/using-spark/foundations/color',
      onClick: () => {
        setContext('using-spark');
      },
      subNavLinks: usingSparkPages,
    },
    {
      element: Link,
      text: 'Principles',
      to: '/principles/accessibility-guidelines',
      onClick: () => {
        setContext('principles');
      },
      subNavLinks: principlePages,
    },
  ];

  return (
    <SprkMasthead
      siteLogo={
        <SiteLogo
          onClick={() => {
            setContext('homepage');
          }}
        />
      }
      additionalClasses="docs-masthead"
      utilityContents={utilityItems}
      navLink={
        <SprkTextInput
          additionalClasses="docs-header-search sprk-u-Width-100"
          leadingIcon="search"
          hiddenLabel
          name="InlineSearch"
          placeholder="Search"
        />
      }
      narrowNavLinks={narrowNavLinks}
    />
  );
};

Header.propTypes = {
  setContext: PropTypes.func,
};

export default Header;
<commit_msg>Add guides section to narrow links<commit_after>import React from 'react';
import { Link } from 'gatsby';
import PropTypes from 'prop-types';
import {
  SprkMasthead,
  SprkTextInput,
  SprkLink,
} from '@sparkdesignsystem/spark-react';
import SiteLogo from './site-logo';
import { useInstallingSparkData } from '../hooks/use-installing-spark';
import { useUsingSparkData } from '../hooks/use-using-spark';
import { usePrincipleSparkData } from '../hooks/use-principle-spark';

const Header = ({ setContext }) => {
  const utilityItems = [
    <SprkLink
      onClick={() => {
        setContext('installing-spark');
      }}
      additionalClasses="sprk-c-Masthead__link"
      variant="simple"
      element={Link}
      to="/installing-spark"
    >
      Installing Spark
    </SprkLink>,
    <SprkLink
      onClick={() => {
        setContext('using-spark');
      }}
      additionalClasses="sprk-c-Masthead__link"
      variant="simple"
      element={Link}
      to="/using-spark"
    >
      Using Spark
    </SprkLink>,
    <SprkLink
      onClick={() => {
        setContext('principles');
      }}
      additionalClasses="sprk-c-Masthead__link"
      variant="simple"
      element={Link}
      to="/principles/design-principles"
    >
      Principles
    </SprkLink>,
    <SprkTextInput
      additionalClasses="docs-header-search--wide sprk-u-mbn"
      leadingIcon="search"
      hiddenLabel
      name="InlineSearch"
      placeholder="Search"
    />,
  ];

  const installingSparkPages = useInstallingSparkData().map((page) => ({
    text: page.node.frontmatter.title,
    to: `/installing-spark/${page.node.parent.name}`,
    element: Link,
  }));

  const usingSparkComponents = useUsingSparkData().components.map((page) => ({
    text: page.node.frontmatter.title,
    to: `/using-spark/components/${page.node.parent.name}`,
    element: Link,
  }));

  const usingSparkExamples = useUsingSparkData().examples.map((page) => ({
    text: page.node.frontmatter.title,
    to: `/using-spark/examples/${page.node.parent.name}`,
    element: Link,
  }));

  const usingSparkFoundations = useUsingSparkData().foundations.map((page) => ({
    text: page.node.frontmatter.title,
    to: `/using-spark/foundations/${page.node.parent.name}`,
    element: Link,
  }));

  // So we don't see a "Guides" landing page link under "the Guides section"
  const processedSparkGuides = useUsingSparkData().guides.filter(
    (item) => item.node.parent.name !== 'guides',
  );

  const usingSparkGuides = processedSparkGuides.map((page) => ({
    text: page.node.frontmatter.title,
    to: `/using-spark/guides/${page.node.parent.name}`,
    element: Link,
  }));

  const usingSparkPages = usingSparkFoundations.concat(
    usingSparkGuides,
    usingSparkComponents,
    usingSparkExamples,
  );

  const principlePages = usePrincipleSparkData().map((page) => ({
    text: page.node.frontmatter.title,
    to: `/principles/${page.node.parent.name}`,
    element: Link,
  }));

  const narrowNavLinks = [
    {
      element: Link,
      text: 'Installing Spark',
      to: '/installing-spark/html-environment-setup',
      onClick: () => {
        setContext('installing-spark');
      },
      subNavLinks: installingSparkPages,
    },
    {
      element: Link,
      text: 'Using Spark',
      to: '/using-spark/foundations/color',
      onClick: () => {
        setContext('using-spark');
      },
      subNavLinks: usingSparkPages,
    },
    {
      element: Link,
      text: 'Guides',
      to: '/using-spark/guides',
      onClick: () => {
        setContext('guides');
      },
      subNavLinks: usingSparkGuides,
    },
    {
      element: Link,
      text: 'Principles',
      to: '/principles/accessibility-guidelines',
      onClick: () => {
        setContext('principles');
      },
      subNavLinks: principlePages,
    },
  ];

  return (
    <SprkMasthead
      siteLogo={
        <SiteLogo
          onClick={() => {
            setContext('homepage');
          }}
        />
      }
      additionalClasses="docs-masthead"
      utilityContents={utilityItems}
      navLink={
        <SprkTextInput
          additionalClasses="docs-header-search sprk-u-Width-100"
          leadingIcon="search"
          hiddenLabel
          name="InlineSearch"
          placeholder="Search"
        />
      }
      narrowNavLinks={narrowNavLinks}
    />
  );
};

Header.propTypes = {
  setContext: PropTypes.func,
};

export default Header;
<|endoftext|>


<commit_before>import React, { Component } from 'react';

class MyPoll extends Component {
  constructor(props){
    super(props);
  }

  componentDidMount(){
    let svg = d3.select("svg")
    let g = svg.append("g")
    .attr("transform", `translation("10", "10")`)
    .attr("class", "bar")

    // const data = ['thing1', 'more', 'foo'];
    const data = [
      {value: 5, name: "apples"},
      {value: 3, name: "bananas"},
      {value: 7, name: "strawberrys"}
    ];

    g.selectAll(".bar")
      .data(data)
      .enter().append("rect")
      .attr("width", 10)
      .attr("height", (d) => d.value * 10)
      .attr("x", (d, i) => i * 15)
  }

  render(){
    return(
      <svg/>
    )
  }
}
export default MyPoll;
<commit_msg>Chart is now right side up<commit_after>import React, { Component } from 'react';

class MyPoll extends Component {
  constructor(props){
    super(props);
  }

  componentDidMount(){
    let svg = d3.select("svg")
    let g = svg.append("g")
    .attr("transform", `translation("10", "10")`)
    .attr("class", "bar")

    // const data = ['thing1', 'more', 'foo'];
    const data = [
      {value: 5, name: "apples"},
      {value: 3, name: "bananas"},
      {value: 7, name: "strawberrys"}
    ];

    g.selectAll(".bar")
      .data(data)
      .enter().append("rect")
      .attr("width", 10)
      .attr("height", (d) => d.value * 10)
      .attr("x", (d, i) => i * 15)
      .attr("y", d => 70 - d.value * 10)
  }

  render(){
    return(
      <svg/>
    )
  }
}
export default MyPoll;
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react'
var Menu = require('react-burger-menu').slide;

if (process.env.BROWSER) {
    require("./NavBar.css");
    require("./NavBurg.css");
}

export default class NaviBar extends Component {
    constructor(props) {
        super(props)
    }
    render() {
        return (

台灣

國際

評論

文化

影像

專題

媒體

                    <Menu right>
                        台灣
                        國際
                        評論
                        文化
                        影像
                        專題
                        媒體
                    </Menu>

        )
    }
}

<commit_msg>use better resolution logo file<commit_after>import React, { Component, PropTypes } from 'react'
var Menu = require('react-burger-menu').slide;

if (process.env.BROWSER) {
    require("./NavBar.css");
    require("./NavBurg.css");
}

export default class NaviBar extends Component {
    constructor(props) {
        super(props)
    }
    render() {
        return (

台灣

國際

評論

文化

影像

專題

媒體

                    <Menu right>
                        台灣
                        國際
                        評論
                        文化
                        影像
                        專題
                        媒體
                    </Menu>

        )
    }
}

<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { Link } from 'react-router-dom';

export default class NavBar extends Component {
    render() {
        const elements = [
            {path: '/', text: 'Homepage'},
            {path: '/agreementform', text: 'AgreementForm'},
            {path: '/agreement', text: 'Agreement'},
            {path: '/theses', text: 'Theses'},
            {path: '/graderManagement', text: 'Supervisor management'},
        ]
        const linkElements = elements.map(elem => {
            if(this.props.active === elem.text)
                return <Link key={elem.text} to={elem.path} className="item active">{elem.text}</Link>;
            else
                return <Link key={elem.text} to={elem.path} className="item">{elem.text}</Link>
         });

        return (

                {linkElements}

                    <Link to="/" className="item"> Logout </Link>

        );
    }
}
<commit_msg>navbar now stacks on mobile<commit_after>import React, { Component } from 'react';
import { Link } from 'react-router-dom';

export default class NavBar extends Component {
    render() {
        const elements = [
            {path: '/', text: 'Homepage'},
            {path: '/agreementform', text: 'AgreementForm'},
            {path: '/agreement', text: 'Agreement'},
            {path: '/theses', text: 'Theses'},
            {path: '/graderManagement', text: 'Supervisor management'},
        ]
        const linkElements = elements.map(elem => {
            if(this.props.active === elem.text)
                return <Link key={elem.text} to={elem.path} className="item active">{elem.text}</Link>;
            else
                return <Link key={elem.text} to={elem.path} className="item">{elem.text}</Link>
         });

        return (

                {linkElements}

                    <Link to="/" className="item"> Logout </Link>

        );
    }
}
<|endoftext|>


<commit_before>import React from 'react';

export default props => (

                <button type="button" className="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                    Toggle navigation

                </button>

                BackEnd Brasil

Repositórios

Sobre

Vagas

Forum

);
<commit_msg>adicionando links no navbar<commit_after>import React from 'react';

export default props => (

                <button type="button" className="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                    Toggle navigation

                </button>

                BackEnd Brasil

Repositórios

Sobre

Vagas

Forum

);
<|endoftext|>


<commit_before>import { createEffect, createMemo, Match, onCleanup, onMount, Switch } from 'solid-js';
import { createStore, reconcile } from 'solid-js/store';
import Core from '../core';
import Terminal from './Terminal';
import ControlBar from './ControlBar';
import LoaderOverlay from './LoaderOverlay';
import StartOverlay from './StartOverlay';

export default props => {
  const [state, setState] = createStore({
    state: 'initial',
    cols: props.cols,
    rows: props.rows,
    lines: [],
    cursor: undefined,
    charW: null,
    charH: null,
    bordersW: null,
    bordersH: null,
    containerW: null,
    containerH: null,
    showControls: false,
    isPausable: true,
    isSeekable: true,
    currentTime: null,
    remainingTime: null,
    progress: null,
    blink: true,
    cursorHold: false
  });

  const autoPlay = props.autoPlay ?? props.autoplay;

  let frameRequestId;
  let userActivityTimeoutId;
  let timeUpdateIntervalId;
  let blinkIntervalId;

  let wrapperRef;
  let playerRef;
  let terminalRef;

  let resizeObserver;

  const terminalCols = () => state.cols || 80;
  const terminalRows = () => state.rows || 24;

  const core = new Core(props.driverFn, {
    cols: props.cols,
    rows: props.rows,
    loop: props.loop,
    speed: props.speed,
    preload: props.preload,
    startAt: props.startAt,
    poster: props.poster,
    idleTimeLimit: props.idleTimeLimit,

    onSize: (cols, rows) => {
      if (rows < state.rows) {
        setState('lines', state.lines.slice(0, rows));
      }

      setState({ cols, rows });
    },

    onTerminalUpdate: () => {
      if (frameRequestId === undefined) {
        frameRequestId = requestAnimationFrame(updateTerminal);
      }
    },

    onFinish: () => {
      setState('state', 'paused');
    }
  });

  const measureDomElements = () => {
    setState({
      charW: terminalRef.clientWidth / terminalCols(),
      charH: terminalRef.clientHeight / terminalRows(),
      bordersW: terminalRef.offsetWidth - terminalRef.clientWidth,
      bordersH: terminalRef.offsetHeight - terminalRef.clientHeight,
      containerW: wrapperRef.offsetWidth,
      containerH: wrapperRef.offsetHeight
    });
  }

  const setupResizeObserver = () => {
    resizeObserver = new ResizeObserver(_entries => {
      setState({
        containerW: wrapperRef.offsetWidth,
        containerH: wrapperRef.offsetHeight
      });

      wrapperRef.dispatchEvent(new CustomEvent('resize', {detail: {el: playerRef}}));
    });

    resizeObserver.observe(wrapperRef);
  }

  onMount(async () => {
    console.debug('player mounted');

    measureDomElements();
    setupResizeObserver();

    const { isPausable, isSeekable, poster } = await core.init();

    setState({ isPausable, isSeekable });

    if (poster !== undefined && !autoPlay) {
      setState({
        lines: poster.lines,
        cursor: poster.cursor
      });
    }

    if (autoPlay) {
      play();
    }
  });

  onCleanup(() => {
    core.stop()
    stopBlinking();
    stopTimeUpdates();
    resizeObserver.disconnect();
  });

  createEffect(() => {
    const s = state.state;

    if (s === 'playing') {
      startBlinking();
      startTimeUpdates();
    } else if (s === 'paused') {
      stopBlinking();
      stopTimeUpdates();
      updateTime();
    }
  });

  const play = async () => {
    setState('state', 'loading');

    const timeoutId = setTimeout(() => {
      setState('state', 'waiting');
    }, 1000);

    await core.play();
    clearTimeout(timeoutId);
    setState('state', 'playing');
  }

  const pauseOrResume = async () => {
    const isPlaying = await core.pauseOrResume();
    setState('state', isPlaying ? 'playing' : 'paused');
  }

  const seek = async pos => {
    if (await core.seek(pos)) {
      updateTime();
    }
  }

  const updateTerminal = () => {
    const changedLines = core.getChangedLines();

    if (changedLines) {
      changedLines.forEach((line, i) => {
        setState('lines', i, reconcile(line));
      });
    }

    setState('cursor', reconcile(core.getCursor()));
    setState('cursorHold', true);

    frameRequestId = undefined;
  }

  const terminalSize = createMemo(() => {
    if (!state.charW) {
      return;
    }

    console.debug(`containerW = ${state.containerW}`);

    const terminalW = (state.charW * terminalCols()) + state.bordersW;
    const terminalH = (state.charH * terminalRows()) + state.bordersH;

    let fit = props.fit ?? 'width';

    if (fit === 'both' || !!document.fullscreenElement) {
      const containerRatio = state.containerW / state.containerH;
      const terminalRatio = terminalW / terminalH;

      if (containerRatio > terminalRatio) {
        fit = 'height';
      } else {
        fit = 'width';
      }
    }

    if (fit === false || fit === 'none') {
      return {};
    } else if (fit === 'width') {
      const scale = state.containerW / terminalW;

      return {
        scale: scale,
        width: state.containerW,
        height: terminalH * scale
      };
    } else if (fit === 'height') {
      const scale = state.containerH / terminalH;

      return {
        scale: scale,
        width: terminalW * scale,
        height: state.containerH
      };
    } else {
      throw `unsupported fit mode: ${fit}`;
    }
  });

  const toggleFullscreen = () => {
    if (document.fullscreenElement ?? document.webkitFullscreenElement) {
      (document.exitFullscreen ??
       document.webkitExitFullscreen ??
       (() => {})).apply(document);
    } else {
      (wrapperRef.requestFullscreen ??
       wrapperRef.webkitRequestFullscreen ??
       (() => {})).apply(wrapperRef);
    }
  }

  const onKeyPress = (e) => {
    console.debug(e);

    if (e.altKey || e.shiftKey || e.metaKey || e.ctrlKey) {
      return;
    }

    if (e.key == ' ') {
      pauseOrResume();
    } else if (e.key == 'f') {
      toggleFullscreen();
    } else if (e.key == 'ArrowLeft') {
      seek('<<');
    } else if (e.key == 'ArrowRight') {
      seek('>>');
    } else if (e.key.charCodeAt(0) >= 48 && e.key.charCodeAt(0) <= 57) {
      const pos = (e.key.charCodeAt(0) - 48) / 10;
      seek(`${pos * 100}%`);
    } else {
      return;
    }

    e.preventDefault();
  }

  const startTimeUpdates = () => {
    timeUpdateIntervalId = setInterval(updateTime, 100);
  }

  const stopTimeUpdates = () => {
    clearInterval(timeUpdateIntervalId);
  }

  const updateTime = () => {
    const currentTime = core.getCurrentTime();
    const remainingTime = core.getRemainingTime();
    const progress = core.getProgress();

    setState({ currentTime, remainingTime, progress });
  }

  const startBlinking = () => {
    blinkIntervalId = setInterval(() => {
      setState(state => {
        const changes = { blink: !state.blink };

        if (changes.blink) {
          changes.cursorHold = false;
        }

        return changes;
      });
    }, 500);
  }

  const stopBlinking = () => {
    clearInterval(blinkIntervalId);
    setState('blink', true);
  }

  const showControls = (show) => {
    clearTimeout(userActivityTimeoutId);

    if (show) {
      userActivityTimeoutId = setTimeout(() => showControls(false), 2000);
    }

    setState('showControls', show);
  }

  const playerStyle = () => {
    const style = {};

    if ((props.fit === false || props.fit === 'none') && props.fontSize !== undefined) {
      if (props.fontSize === 'small') {
        style['font-size'] = '12px';
      } else if (props.fontSize === 'medium') {
        style['font-size'] = '18px';
      } else if (props.fontSize === 'big') {
        style['font-size'] = '24px';
      } else {
        style['font-size'] = props.fontSize;
      }
    }

    const size = terminalSize();

    if (size === undefined) {
      style['height'] = 0;
      return style;
    }

    if (size.width !== undefined) {
      style['width'] = `${size.width}px`;
      style['height'] = `${size.height}px`;
    }

    return style;
  }

  const playerClass = () =>
    `asciinema-player asciinema-theme-${props.theme ?? 'asciinema'}`;

  const terminalScale = () => terminalSize()?.scale;

  return (

 showControls(true)} onMouseLeave={() => showControls(false)} onMouseMove={() => showControls(true)} ref={playerRef}>
        <Terminal cols={terminalCols()} rows={terminalRows()} scale={terminalScale()} blink={state.blink} lines={state.lines} cursor={state.cursor} cursorHold={state.cursorHold} ref={terminalRef} />
        <ControlBar currentTime={state.currentTime} remainingTime={state.remainingTime} progress={state.progress} isPlaying={state.state == 'playing'} isPausable={state.isPausable} isSeekable={state.isSeekable} onPlayClick={pauseOrResume} onFullscreenClick={toggleFullscreen} onSeekClick={seek} />
        <Switch>
          <Match when={state.state == 'initial' && !autoPlay}><StartOverlay onClick={play} /></Match>
          <Match when={state.state == 'waiting'}><LoaderOverlay /></Match>
        </Switch>

  );
}
<commit_msg>Don't log all key presses<commit_after>import { createEffect, createMemo, Match, onCleanup, onMount, Switch } from 'solid-js';
import { createStore, reconcile } from 'solid-js/store';
import Core from '../core';
import Terminal from './Terminal';
import ControlBar from './ControlBar';
import LoaderOverlay from './LoaderOverlay';
import StartOverlay from './StartOverlay';

export default props => {
  const [state, setState] = createStore({
    state: 'initial',
    cols: props.cols,
    rows: props.rows,
    lines: [],
    cursor: undefined,
    charW: null,
    charH: null,
    bordersW: null,
    bordersH: null,
    containerW: null,
    containerH: null,
    showControls: false,
    isPausable: true,
    isSeekable: true,
    currentTime: null,
    remainingTime: null,
    progress: null,
    blink: true,
    cursorHold: false
  });

  const autoPlay = props.autoPlay ?? props.autoplay;

  let frameRequestId;
  let userActivityTimeoutId;
  let timeUpdateIntervalId;
  let blinkIntervalId;

  let wrapperRef;
  let playerRef;
  let terminalRef;

  let resizeObserver;

  const terminalCols = () => state.cols || 80;
  const terminalRows = () => state.rows || 24;

  const core = new Core(props.driverFn, {
    cols: props.cols,
    rows: props.rows,
    loop: props.loop,
    speed: props.speed,
    preload: props.preload,
    startAt: props.startAt,
    poster: props.poster,
    idleTimeLimit: props.idleTimeLimit,

    onSize: (cols, rows) => {
      if (rows < state.rows) {
        setState('lines', state.lines.slice(0, rows));
      }

      setState({ cols, rows });
    },

    onTerminalUpdate: () => {
      if (frameRequestId === undefined) {
        frameRequestId = requestAnimationFrame(updateTerminal);
      }
    },

    onFinish: () => {
      setState('state', 'paused');
    }
  });

  const measureDomElements = () => {
    setState({
      charW: terminalRef.clientWidth / terminalCols(),
      charH: terminalRef.clientHeight / terminalRows(),
      bordersW: terminalRef.offsetWidth - terminalRef.clientWidth,
      bordersH: terminalRef.offsetHeight - terminalRef.clientHeight,
      containerW: wrapperRef.offsetWidth,
      containerH: wrapperRef.offsetHeight
    });
  }

  const setupResizeObserver = () => {
    resizeObserver = new ResizeObserver(_entries => {
      setState({
        containerW: wrapperRef.offsetWidth,
        containerH: wrapperRef.offsetHeight
      });

      wrapperRef.dispatchEvent(new CustomEvent('resize', {detail: {el: playerRef}}));
    });

    resizeObserver.observe(wrapperRef);
  }

  onMount(async () => {
    console.debug('player mounted');

    measureDomElements();
    setupResizeObserver();

    const { isPausable, isSeekable, poster } = await core.init();

    setState({ isPausable, isSeekable });

    if (poster !== undefined && !autoPlay) {
      setState({
        lines: poster.lines,
        cursor: poster.cursor
      });
    }

    if (autoPlay) {
      play();
    }
  });

  onCleanup(() => {
    core.stop()
    stopBlinking();
    stopTimeUpdates();
    resizeObserver.disconnect();
  });

  createEffect(() => {
    const s = state.state;

    if (s === 'playing') {
      startBlinking();
      startTimeUpdates();
    } else if (s === 'paused') {
      stopBlinking();
      stopTimeUpdates();
      updateTime();
    }
  });

  const play = async () => {
    setState('state', 'loading');

    const timeoutId = setTimeout(() => {
      setState('state', 'waiting');
    }, 1000);

    await core.play();
    clearTimeout(timeoutId);
    setState('state', 'playing');
  }

  const pauseOrResume = async () => {
    const isPlaying = await core.pauseOrResume();
    setState('state', isPlaying ? 'playing' : 'paused');
  }

  const seek = async pos => {
    if (await core.seek(pos)) {
      updateTime();
    }
  }

  const updateTerminal = () => {
    const changedLines = core.getChangedLines();

    if (changedLines) {
      changedLines.forEach((line, i) => {
        setState('lines', i, reconcile(line));
      });
    }

    setState('cursor', reconcile(core.getCursor()));
    setState('cursorHold', true);

    frameRequestId = undefined;
  }

  const terminalSize = createMemo(() => {
    if (!state.charW) {
      return;
    }

    console.debug(`containerW = ${state.containerW}`);

    const terminalW = (state.charW * terminalCols()) + state.bordersW;
    const terminalH = (state.charH * terminalRows()) + state.bordersH;

    let fit = props.fit ?? 'width';

    if (fit === 'both' || !!document.fullscreenElement) {
      const containerRatio = state.containerW / state.containerH;
      const terminalRatio = terminalW / terminalH;

      if (containerRatio > terminalRatio) {
        fit = 'height';
      } else {
        fit = 'width';
      }
    }

    if (fit === false || fit === 'none') {
      return {};
    } else if (fit === 'width') {
      const scale = state.containerW / terminalW;

      return {
        scale: scale,
        width: state.containerW,
        height: terminalH * scale
      };
    } else if (fit === 'height') {
      const scale = state.containerH / terminalH;

      return {
        scale: scale,
        width: terminalW * scale,
        height: state.containerH
      };
    } else {
      throw `unsupported fit mode: ${fit}`;
    }
  });

  const toggleFullscreen = () => {
    if (document.fullscreenElement ?? document.webkitFullscreenElement) {
      (document.exitFullscreen ??
       document.webkitExitFullscreen ??
       (() => {})).apply(document);
    } else {
      (wrapperRef.requestFullscreen ??
       wrapperRef.webkitRequestFullscreen ??
       (() => {})).apply(wrapperRef);
    }
  }

  const onKeyPress = (e) => {
    if (e.altKey || e.shiftKey || e.metaKey || e.ctrlKey) {
      return;
    }

    if (e.key == ' ') {
      pauseOrResume();
    } else if (e.key == 'f') {
      toggleFullscreen();
    } else if (e.key == 'ArrowLeft') {
      seek('<<');
    } else if (e.key == 'ArrowRight') {
      seek('>>');
    } else if (e.key.charCodeAt(0) >= 48 && e.key.charCodeAt(0) <= 57) {
      const pos = (e.key.charCodeAt(0) - 48) / 10;
      seek(`${pos * 100}%`);
    } else {
      return;
    }

    e.preventDefault();
  }

  const startTimeUpdates = () => {
    timeUpdateIntervalId = setInterval(updateTime, 100);
  }

  const stopTimeUpdates = () => {
    clearInterval(timeUpdateIntervalId);
  }

  const updateTime = () => {
    const currentTime = core.getCurrentTime();
    const remainingTime = core.getRemainingTime();
    const progress = core.getProgress();

    setState({ currentTime, remainingTime, progress });
  }

  const startBlinking = () => {
    blinkIntervalId = setInterval(() => {
      setState(state => {
        const changes = { blink: !state.blink };

        if (changes.blink) {
          changes.cursorHold = false;
        }

        return changes;
      });
    }, 500);
  }

  const stopBlinking = () => {
    clearInterval(blinkIntervalId);
    setState('blink', true);
  }

  const showControls = (show) => {
    clearTimeout(userActivityTimeoutId);

    if (show) {
      userActivityTimeoutId = setTimeout(() => showControls(false), 2000);
    }

    setState('showControls', show);
  }

  const playerStyle = () => {
    const style = {};

    if ((props.fit === false || props.fit === 'none') && props.fontSize !== undefined) {
      if (props.fontSize === 'small') {
        style['font-size'] = '12px';
      } else if (props.fontSize === 'medium') {
        style['font-size'] = '18px';
      } else if (props.fontSize === 'big') {
        style['font-size'] = '24px';
      } else {
        style['font-size'] = props.fontSize;
      }
    }

    const size = terminalSize();

    if (size === undefined) {
      style['height'] = 0;
      return style;
    }

    if (size.width !== undefined) {
      style['width'] = `${size.width}px`;
      style['height'] = `${size.height}px`;
    }

    return style;
  }

  const playerClass = () =>
    `asciinema-player asciinema-theme-${props.theme ?? 'asciinema'}`;

  const terminalScale = () => terminalSize()?.scale;

  return (

 showControls(true)} onMouseLeave={() => showControls(false)} onMouseMove={() => showControls(true)} ref={playerRef}>
        <Terminal cols={terminalCols()} rows={terminalRows()} scale={terminalScale()} blink={state.blink} lines={state.lines} cursor={state.cursor} cursorHold={state.cursorHold} ref={terminalRef} />
        <ControlBar currentTime={state.currentTime} remainingTime={state.remainingTime} progress={state.progress} isPlaying={state.state == 'playing'} isPausable={state.isPausable} isSeekable={state.isSeekable} onPlayClick={pauseOrResume} onFullscreenClick={toggleFullscreen} onSeekClick={seek} />
        <Switch>
          <Match when={state.state == 'initial' && !autoPlay}><StartOverlay onClick={play} /></Match>
          <Match when={state.state == 'waiting'}><LoaderOverlay /></Match>
        </Switch>

  );
}
<|endoftext|>


<commit_before>import React, { Component } from 'react';

export default class Search extends Component {

	constructor(props) {
		super(props);
		this.handleFormSubmit = this.handleFormSubmit.bind(this);
	}

	handleFormSubmit(event) {
		event.preventDefault();
		this.props.getSearchResults(this.refs.keyword.value);
		this.refs.keyword.value = '';
	}

	render() {
		return (
			<form onSubmit={this.handleFormSubmit}>
				<input ref="keyword" type="text" placeholder="Search" />
				<button>Submit</button>
			</form>
		);
	}
}<commit_msg>add onChange event listener to input keyword<commit_after>import React, { Component } from 'react';

export default class Search extends Component {

	constructor(props) {
		super(props);
		this.handleFormSubmit = this.handleFormSubmit.bind(this);
		this.handleInputChange = this.handleInputChange.bind(this);
	}

	handleFormSubmit(event) {
		event.preventDefault();
		this.props.getSearchResults(this.refs.keyword.value);
		this.refs.keyword.value = '';
	}

	handleInputChange() {
		this.props.getSearchResults(this.refs.keyword.value);
	}

	render() {
		return (
			<form onSubmit={this.handleFormSubmit}>
				<input onChange={this.handleInputChange} ref="keyword" type="text" placeholder="Search" />
				<button>Submit</button>
			</form>
		);
	}
}<|endoftext|>


<commit_before>import React from "react";
import PropTypes from "prop-types";
import { useStaticQuery, graphql } from "gatsby";
import Header from "./header";
import styled from "@emotion/styled";
import { Global, css } from "@emotion/core";

const Footer = styled.footer`
  text-align: center;
  font-size: 0.86rem;
  margin: 22px;
`;

const Layout = ({ children, volumeNumbers, volumeNumber }) => {
  const data = useStaticQuery(graphql`
    query SiteTitleQuery {
      site {
        siteMetadata {
          title
          description
        }
      }
    }
  `);

  React.useLayoutEffect(() => {
    localStorage.probablyHasFont = "1";
  });

  return (
    <>
      <Global
        styles={css`
          body {
            font-family: ${typeof window !== "undefined" &&
                  window.localStorage.probablyHasFont === "1" &&
                  `"Lexend Deca", `}
                "Trebuchet MS",
              Arial, Helvetica;
            background-color: #f0eee1;
            margin: 0;
          }

          a {
            color: #0066cc;
          }
        `}
      />

        {children}

          A project of{" "}
          Mormonism Research Ministry

    </>
  );
};

Layout.propTypes = {
  children: PropTypes.node.isRequired
};

export default Layout;
<commit_msg>font-display<commit_after>import React from "react";
import PropTypes from "prop-types";
import { useStaticQuery, graphql } from "gatsby";
import Header from "./header";
import styled from "@emotion/styled";
import { Global, css } from "@emotion/core";

const Footer = styled.footer`
  text-align: center;
  font-size: 0.86rem;
  margin: 22px;
`;

const Layout = ({ children, volumeNumbers, volumeNumber }) => {
  const data = useStaticQuery(graphql`
    query SiteTitleQuery {
      site {
        siteMetadata {
          title
          description
        }
      }
    }
  `);

  React.useLayoutEffect(() => {
    localStorage.probablyHasFont = "1";
  });

  return (
    <>
      <Global
        styles={css`
          body {
            font-family: ${typeof window !== "undefined" &&
                  window.localStorage.probablyHasFont === "1" &&
                  `"Lexend Deca", `}
                "Trebuchet MS",
              Arial, Helvetica;
            font-display: optional;
            background-color: #f0eee1;
            margin: 0;
          }

          a {
            color: #0066cc;
          }
        `}
      />

        {children}

          A project of{" "}
          Mormonism Research Ministry

    </>
  );
};

Layout.propTypes = {
  children: PropTypes.node.isRequired
};

export default Layout;
<|endoftext|>


<commit_before>import React from 'react';
import {AsyncTypeahead} from 'react-bootstrap-typeahead';
import Navbar from 'react-bootstrap/lib/Navbar';

export default class Search extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      searchResults: [],
      searchQuery: '',
      lat: this.props.lat,
      lon: this.props.lon,
      zoom: this.props.zoom,
    };
  }

  doSearch(searchQuery) {
    if (!searchQuery) {
      return;
    }
    this.setState({searchQuery});

    const { lat, lon, zoom } = this.state;
    // fetch(`https://www.freemap.sk/api/0.1/q/${encodeURIComponent(searchQuery)}&lat=${lat}&lon=${lon}&zoom=${zoom}`, {
    fetch(`https://nominatim.openstreetmap.org/search/${encodeURIComponent(searchQuery)}`
        + `?format=jsonv2&lat=${lat}&lon=${lon}&zoom=${zoom}&namedetails=1&extratags=1`, {
      method: 'GET'
    }).then(res => res.json()).then(data => {
      const searchResults = data.map((d, id) => {
        const name = d.namedetails.name;
        const tags = { name, type: d.type };
        return { id, label: name, lat: d.lat, lon: d.lon, tags  };
      });
      this.setState({searchResults});
    });
  }

  clearSearch() {
    this.setState({ searchQuery: null, searchResults: []  });
  }

  searchResultSelected(result) {
    console.log(result);
  }

  render() {
    const b = (fn, ...args) => fn.bind(this, ...args);
    return (
      <Navbar.Form pullLeft>
          <AsyncTypeahead
            labelKey="label"
            useCache={false}
            minLength={3}
            delay={500}
            ignoreDiacritics={true}
            onSearch={b(this.doSearch)}
            options={this.state.searchResults}
            searchText="Hľadám ..."
            placeholder="Brusno"
            clearButton={true}
            emptyLabel={'Nenašli sme žiadne výsledky' + this.state.searchResults.length}
            renderMenuItemChildren={(result) => (

                {result.tags.name}

                ({result.tags.type})

            )}
          />
      </Navbar.Form>
    );
  }
}

Search.propTypes = {
  lat: React.PropTypes.string,
  lon: React.PropTypes.string,
  zoom: React.PropTypes.number,
  onSearchResultsUpdate: React.PropTypes.func.isRequired
};<commit_msg>#1: show poi on search result selection<commit_after>import React from 'react';
import {AsyncTypeahead} from 'react-bootstrap-typeahead';
import Navbar from 'react-bootstrap/lib/Navbar';

export default class Search extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      searchSuggestions: [],
      searchQuery: '',
      lat: this.props.lat,
      lon: this.props.lon,
      zoom: this.props.zoom,
    };
  }

  doSearch(searchQuery) {
    if (!searchQuery) {
      return;
    }
    this.setState({searchQuery});

    const { lat, lon, zoom } = this.state;
    // fetch(`https://www.freemap.sk/api/0.1/q/${encodeURIComponent(searchQuery)}&lat=${lat}&lon=${lon}&zoom=${zoom}`, {
    fetch(`https://nominatim.openstreetmap.org/search/${encodeURIComponent(searchQuery)}`
        + `?format=jsonv2&lat=${lat}&lon=${lon}&zoom=${zoom}&namedetails=1&extratags=1`, {
      method: 'GET'
    }).then(res => res.json()).then(data => {
      const searchSuggestions = data.map((d, id) => {
        const name = d.namedetails.name;
        const tags = { name, type: d.type };
        return { id, label: name, lat: d.lat, lon: d.lon, tags  };
      });
      this.setState({searchSuggestions});
    });
  }

  onSelectionChange(selectedResults) {
    this.props.onSearchResultsUpdate(selectedResults);
  }

  render() {
    const b = (fn, ...args) => fn.bind(this, ...args);
    return (
      <Navbar.Form pullLeft>
          <AsyncTypeahead
            labelKey="label"
            useCache={false}
            minLength={3}
            delay={500}
            ignoreDiacritics={true}
            onSearch={b(this.doSearch)}
            options={this.state.searchSuggestions}
            searchText="Hľadám ..."
            placeholder="Brusno"
            clearButton={true}
            onChange={b(this.onSelectionChange)}
            emptyLabel={'Nenašli sme žiadne výsledky'}
            renderMenuItemChildren={(result) => (

                {result.tags.name}

                ({result.tags.type})

            )}
          />
      </Navbar.Form>
    );
  }
}

Search.propTypes = {
  lat: React.PropTypes.string,
  lon: React.PropTypes.string,
  zoom: React.PropTypes.number,
  onSearchResultsUpdate: React.PropTypes.func.isRequired
};<|endoftext|>


<commit_before>/**
 * @fileoverview Route component for app.
 */
import React    from 'react';
import Calendar from 'components/calendar-component';
import { uniqueId } from 'lodash';

const dummyData = [
  { day: 26, isCurrent: false, fulldate: uniqueId() },
  { day: 27, isCurrent: false, fulldate: uniqueId()  },
  { day: 28, isCurrent: false, fulldate: uniqueId()  },
  { day: 29, isCurrent: false, fulldate: uniqueId()  },
  { day: 30, isCurrent: false, fulldate: uniqueId()  },
  { day: 1, isCurrent: true, fulldate: uniqueId()  },
  { day: 2, isCurrent: true, fulldate: uniqueId()  },
  { day: 3, isCurrent: true, fulldate: uniqueId()  },
  { day: 4, isCurrent: true, fulldate: uniqueId()  },
  { day: 5, isCurrent: true, fulldate: uniqueId()  },
  { day: 6, isCurrent: true, fulldate: uniqueId()  },
  { day: 7, isCurrent: true, fulldate: uniqueId()  },
  { day: 8, isCurrent: true, fulldate: uniqueId()  },
  { day: 9, isCurrent: true, fulldate: uniqueId()  },
];

const App = () => (

Miser

    <Calendar calendars={ dummyData } />

);

export default App;
<commit_msg>modify: mount calendar-footer component with dummy data<commit_after>/**
 * @fileoverview Route component for app.
 */
import React          from 'react';
import Calendar       from 'components/calendar-component';
import CalendarFooter from 'components/calendar-footer-component';
import { uniqueId }   from 'lodash';

const dummyData = [
  { day: 26, isCurrent: false, fulldate: uniqueId() },
  { day: 27, isCurrent: false, fulldate: uniqueId()  },
  { day: 28, isCurrent: false, fulldate: uniqueId()  },
  { day: 29, isCurrent: false, fulldate: uniqueId()  },
  { day: 30, isCurrent: false, fulldate: uniqueId()  },
  { day: 1, isCurrent: true, fulldate: uniqueId()  },
  { day: 2, isCurrent: true, fulldate: uniqueId()  },
  { day: 3, isCurrent: true, fulldate: uniqueId()  },
  { day: 4, isCurrent: true, fulldate: uniqueId()  },
  { day: 5, isCurrent: true, fulldate: uniqueId()  },
  { day: 6, isCurrent: true, fulldate: uniqueId()  },
  { day: 7, isCurrent: true, fulldate: uniqueId()  },
  { day: 8, isCurrent: true, fulldate: uniqueId()  },
  { day: 9, isCurrent: true, fulldate: uniqueId()  },
];

const dummyLinks = {
  prevMonth: '/?year=2016&month=5',
  nextMonth: '/?year=2016&month=7',
};

const App = () => (

Miser

    <Calendar calendars={ dummyData } />
    <CalendarFooter links={ dummyLinks } />

);

export default App;
<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 */

$.ajaxSetup({
    async: false
});

var cdv;

$(function(){

    setTimeout(function(){

        cdv = wd.cdv.cdv({
            isServerSide: false
        });

        // Register tests

        cdv.registerTest({
            id: 1,
            type: "query",
            name: "Test 1",
            group: "CDV Sample Tests",
            createdBy: "Pedro",
            createdAt: 1339430893246,
            validation: [
            {
                cdaFile: "/plugin-samples/cda/cdafiles/sql-jndi.cda",
                dataAccessId: "1" ,
                parameters: {}
            },
            {
                cdaFile: "/plugin-samples/cda/cdafiles/sql-jndi.cda",
                dataAccessId: "1" ,
                parameters: {
                    status:"Cancelled"
                }
            }
            ],
            validations:
            [
            {
                validationName: "Test Existence",
                validationType: "custom",
                validationFunction:  function(rs, conf) {

                    var _conf = {
                        testAll: true
                    };
                    conf = _.extend({},_conf,conf);
                    var exists = !!conf.testAll;

                    exists = _.reduce(_.map(rs,function(r){
                        return r.resultset.length > 0
                    }),function(prev, curr, exists){
                        return conf.testAll ? (curr && prev) : (curr || prev);
                    });

                    return exists ? "OK" : "ERROR";

                }
            },
            {
                validationName: "Test Existence 2",
                validationType: "custom",
                validationFunction:  function(rs, conf) {

                    var _conf = {
                        testAll: true
                    };
                    conf = _.extend({},_conf,conf);
                    var exists = !!conf.testAll;

                    exists = _.reduce(_.map(rs,function(r){
                        return r.resultset.length > 0
                    }),function(prev, curr, exists){
                        return conf.testAll ? (curr && prev) : (curr || prev);
                    });

                    return exists ? "ERROR" : "OK";

                }
            }
            ],
            executionTimeValidation: {
                expected: 100,
                warnPercentage: 0.30,
                errorPercentage: 0.70,
                errorOnLow: true
            },

            cron: "0 2 * * ? *"
        });

        cdv.registerTest({
            id: 2,
            type: "query",
            name: "Test 2",
            group: "CDV Sample Tests",
            createdBy: "Pedro",
            createdAt: 1339430893246,
            validation: [
            {
                cdaFile: "/plugin-samples/cda/cdafiles/mondrian-jndi.cda",
                dataAccessId: "1" ,
                parameters: {}
            },
            {
                cdaFile: "/plugin-samples/cda/cdafiles/mondrian-jndi.cda",
                dataAccessId: "1" ,
                parameters: {
                    status:"Cancelled"
                }
            }
            ],
            validations:
            [{
                validationName: "Test Existence",
                validationType: "custom",
                validationFunction:  function(rs, conf) {

                    var _conf = {
                        testAll: true
                    };
                    conf = _.extend({},_conf,conf);
                    var exists = !!conf.testAll;

                    exists = _.reduce(_.map(rs,function(r){
                        return r.resultset.length > 0
                    }),function(prev, curr, exists){
                        return conf.testAll ? (curr && prev) : (curr || prev);
                    });
                    return exists ? "ERROR" : "OK";

                }
            }],
            executionTimeValidation: {
                expected: 100,
                warnPercentage: 0.30,
                errorPercentage: 0.70,
                errorOnLow: true
            },

            cron: "0 2 * * ? *"
        });

        // Test 1: List
        $(".results").text(JSON.stringify( cdv.listTestsFlatten("CDV Sample Tests")  ));

        // Call again to make sure we're not overriding something
        //$(".results").text(JSON.stringify( cdv.listTestsFlatten("CDV Sample Tests")  ));

        // Test 2: Execute a test

        /*
        var callback = function(result){
            $(".results").text(JSON.stringify(result));
        }

        cdv.runTest(cdv.getTest("CDV Sample Tests","Test 1") , {
            callback: callback
        });
        */

    },100)

})

<commit_msg>- CDV playground points to test execution<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 */

$.ajaxSetup({
    async: false
});

var cdv;

$(function(){

    setTimeout(function(){

        cdv = wd.cdv.cdv({
            isServerSide: false
        });

        // Register tests

        cdv.registerTest({
            id: 1,
            type: "query",
            name: "Test 1",
            group: "CDV Sample Tests",
            createdBy: "Pedro",
            createdAt: 1339430893246,
            validation: [
            {
                cdaFile: "/plugin-samples/cda/cdafiles/sql-jndi.cda",
                dataAccessId: "1" ,
                parameters: {}
            },
            {
                cdaFile: "/plugin-samples/cda/cdafiles/sql-jndi.cda",
                dataAccessId: "1" ,
                parameters: {
                    status:"Cancelled"
                }
            }
            ],
            validations:
            [
            {
                validationName: "Test Existence",
                validationType: "custom",
                validationFunction:  function(rs, conf) {

                    var _conf = {
                        testAll: true
                    };
                    conf = _.extend({},_conf,conf);
                    var exists = !!conf.testAll;

                    exists = _.reduce(_.map(rs,function(r){
                        return r.resultset.length > 0
                    }),function(prev, curr, exists){
                        return conf.testAll ? (curr && prev) : (curr || prev);
                    });

                    return exists ? "OK" : "ERROR";

                }
            },
            {
                validationName: "Test Existence 2",
                validationType: "custom",
                validationFunction:  function(rs, conf) {

                    var _conf = {
                        testAll: true
                    };
                    conf = _.extend({},_conf,conf);
                    var exists = !!conf.testAll;

                    exists = _.reduce(_.map(rs,function(r){
                        return r.resultset.length > 0
                    }),function(prev, curr, exists){
                        return conf.testAll ? (curr && prev) : (curr || prev);
                    });

                    return exists ? "ERROR" : "OK";

                }
            }
            ],
            executionTimeValidation: {
                expected: 100,
                warnPercentage: 0.30,
                errorPercentage: 0.70,
                errorOnLow: true
            },

            cron: "0 2 * * ? *"
        });

        cdv.registerTest({
            id: 2,
            type: "query",
            name: "Test 2",
            group: "CDV Sample Tests",
            createdBy: "Pedro",
            createdAt: 1339430893246,
            validation: [
            {
                cdaFile: "/plugin-samples/cda/cdafiles/mondrian-jndi.cda",
                dataAccessId: "1" ,
                parameters: {}
            },
            {
                cdaFile: "/plugin-samples/cda/cdafiles/mondrian-jndi.cda",
                dataAccessId: "1" ,
                parameters: {
                    status:"Cancelled"
                }
            }
            ],
            validations:
            [{
                validationName: "Test Existence",
                validationType: "custom",
                validationFunction:  function(rs, conf) {

                    var _conf = {
                        testAll: true
                    };
                    conf = _.extend({},_conf,conf);
                    var exists = !!conf.testAll;

                    exists = _.reduce(_.map(rs,function(r){
                        return r.resultset.length > 0
                    }),function(prev, curr, exists){
                        return conf.testAll ? (curr && prev) : (curr || prev);
                    });
                    return exists ? "ERROR" : "OK";

                }
            }],
            executionTimeValidation: {
                expected: 100,
                warnPercentage: 0.30,
                errorPercentage: 0.70,
                errorOnLow: true
            },

            cron: "0 2 * * ? *"
        });

        // Test 1: List
        //$(".results").text(JSON.stringify( cdv.listTestsFlatten("CDV Sample Tests")  ));

        // Call again to make sure we're not overriding something
        //$(".results").text(JSON.stringify( cdv.listTestsFlatten("CDV Sample Tests")  ));

        // Test 2: Execute a test

        var callback = function(result){
            $(".results").text(JSON.stringify(result));
        }

        cdv.runTest(cdv.getTest("CDV Sample Tests","Test 1") , {
            callback: callback
        });

    },100)

})

<|endoftext|>


<commit_before>document.addEventListener('beforeload', onBeforeLoad, true);

var config = [
    {
        source: 'source.js',
        reSource: 'reSource.js'
    }
];

function onBeforeLoad(event) {
    if (event.srcElement.tagName == 'SCRIPT') {
        console.error(event.url);
        for(var i = 0; i < config.length; i++) {
            if (event.url == config[i].source) {
                event.preventDefault();
                var script = document.createElement('script');
                script.setAttribute('src', config[i].reSource);
                event.srcElement.parentNode.replaceChild(script, event.srcElement);
                return;
            }
        }
    }
}<commit_msg>Replace strings comparison with regexp<commit_after>document.addEventListener('beforeload', onBeforeLoad, true);

var config = [
    {
        source: 'source.js',
        reSource: 'reSource.js'
    }
];

function onBeforeLoad(event) {
    if (event.srcElement.tagName == 'SCRIPT') {
        for(var i = 0; i < config.length; i++) {
            var regexp = new RegExp(config[i].source);
            if (regexp.test(event.url)) {
                event.preventDefault();
                var script = document.createElement('script');
                script.setAttribute('src', config[i].reSource);
                event.srcElement.parentNode.replaceChild(script, event.srcElement);
                return;
            }
        }
    }
}<|endoftext|>


<commit_before>var helpful_yes = document.querySelector( '.helpful_yes' );
var helpful_no = document.querySelector( '.helpful_no' );
var helpful_text = document.querySelector( '.helpful__question' );

function thanksYes(){
	helpful_text.innerHTML = "Thanks for your response and helping us improve our content.";
	helpful_no.remove();
	helpful_yes.remove();
}

function thanksNo(){
	helpful_text.innerHTML = "Sorry about that. How can we improve it?";
	helpful_no.remove();
	helpful_yes.remove();
}

AddEvent( helpful_yes, 'click', function( event, $this ) {
	PreventEvent( event );
	thanksYes();
	ga('send', {
	  hitType: 'event',
	  eventCategory: 'helpful: yes',
	  eventAction: window.location.href,
	  eventLabel: 'helpful: yes',
		eventValue: 1
	});
});

AddEvent( helpful_no, 'click', function( event, $this ) {
	PreventEvent( event );
	thanksNo();
	ga('send', {
		hitType: 'event',
		eventCategory: 'helpful: no',
		eventAction: window.location.href,
		eventLabel: 'helpful: no',
		eventValue: -1
	});
});
<commit_msg>Add more professional words<commit_after>var helpful_yes = document.querySelector( '.helpful_yes' );
var helpful_no = document.querySelector( '.helpful_no' );
var helpful_text = document.querySelector( '.helpful__question' );

function thanksYes(){
	helpful_text.innerHTML = "Thank you for your response, it helps us improve our service.";
	helpful_no.remove();
	helpful_yes.remove();
}

function thanksNo(){
	helpful_text.innerHTML = "Sorry to hear that. How can we improve it?";
	helpful_no.remove();
	helpful_yes.remove();
}

AddEvent( helpful_yes, 'click', function( event, $this ) {
	PreventEvent( event );
	thanksYes();
	ga('send', {
	  hitType: 'event',
	  eventCategory: 'helpful: yes',
	  eventAction: window.location.href,
	  eventLabel: 'helpful: yes',
		eventValue: 1
	});
});

AddEvent( helpful_no, 'click', function( event, $this ) {
	PreventEvent( event );
	thanksNo();
	ga('send', {
		hitType: 'event',
		eventCategory: 'helpful: no',
		eventAction: window.location.href,
		eventLabel: 'helpful: no',
		eventValue: -1
	});
});
<|endoftext|>


<commit_before>const r = require('./../../../db');
const client = require('./../../');
const config = require('config');

function guildStats(guild) {
	// Guild stats!
	const bots = guild.members.filter(member => member.user.bot).length;
	const users = guild.memberCount - bots;
	const percentage = Math.floor((bots / guild.memberCount) * 100);
	const timestamp = Date.now();
	const collection = percentage > config.get('discord').collection.percentage && guild.memberCount > config.get('discord').collection.users;

	// Owner!
	const owner = client.users.get(guild.ownerID);

	return {
		guildID: guild.id,
		ownerID: owner.id,
		owner: {
			id: guild.ownerID,
			avatar: owner.dynamicAvatarURL('webp', 2048),
			name: owner.username,
			discriminator: owner.discriminator,
			bot: owner.bot,
			createdAt: owner.createdAt,
		},
		guild: {
			id: guild.id,
			name: guild.name,
			createdAt: guild.createdAt,
			icon: guild.iconURL,
			members: guild.memberCount,
			region: guild.region,
			users,
			bots,
			collection,
		},
		timestamp
	};
}

function banGuild(id, reason) {
	const guild = client.guilds.get(id);
	const stats = guildStats(guild);

	stats.reason = reason;
	r.table('collection')
		.insert(guildStats(guild))
		.run(r.conn, (err) => {
			if (err) throw new Error('Couldn\'t save banned guild.');
			console.log(`Banned ${client.guilds.get(id).name}`);
			guild.leave();
		});
}

function checkGuilds(bot) {
	bot.guilds.filter(guild => guildStats(guild).guild.collection).forEach(guild => banGuild(guild.id, {
		message: 'Bot collection guild',
		maxUsers: config.get('discord').collection.users,
		maxPercentage: config.get('discord').collection.percentage
	}));
}

client.on('guildCreate', (guild) => {
	const report = guildStats(guild);
	console.log(report);

	if (report.guild.collection) {
		console.log(`${guild.name} failed the authentication test`);
		banGuild(guild.id, {
			message: 'Bot collection guild',
			maxUsers: config.get('discord').collection.users,
			maxPercentage: config.get('discord').collection.percentage
		});
	} else {
		r.table('collection')
			.filter(
				r.row('guildID').eq(guild.id).or(r.row('ownerID').eq(guild.ownerID))
			)
			.run(r.conn, (err1, cursor) => {
				if (err1) throw new Error('Failed to search banned guild database.');
				cursor.toArray((err2, result) => {
					if (err2) throw new Error('Failed to convert banned cursor to results.');
					if (result.length < 1) {
						console.log(`${guild.name} passed the authentication test`);
					} else {
						console.log(`${guild.name} was already banned!`);
						banGuild(guild.id, {
							message: 'Already banned',
							refer: result.map(reason => reason.id) || []
						});
					}
				});
			});
	}
});

exports.ban = banGuild;
exports.check = checkGuilds;
<commit_msg>Insert stats<commit_after>const r = require('./../../../db');
const client = require('./../../');
const config = require('config');

function guildStats(guild) {
	// Guild stats!
	const bots = guild.members.filter(member => member.user.bot).length;
	const users = guild.memberCount - bots;
	const percentage = Math.floor((bots / guild.memberCount) * 100);
	const timestamp = Date.now();
	const collection = percentage > config.get('discord').collection.percentage && guild.memberCount > config.get('discord').collection.users;

	// Owner!
	const owner = client.users.get(guild.ownerID);

	return {
		guildID: guild.id,
		ownerID: owner.id,
		owner: {
			id: guild.ownerID,
			avatar: owner.dynamicAvatarURL('webp', 2048),
			name: owner.username,
			discriminator: owner.discriminator,
			bot: owner.bot,
			createdAt: owner.createdAt,
		},
		guild: {
			id: guild.id,
			name: guild.name,
			createdAt: guild.createdAt,
			icon: guild.iconURL,
			members: guild.memberCount,
			region: guild.region,
			users,
			bots,
			collection,
		},
		timestamp
	};
}

function banGuild(id, reason) {
	const guild = client.guilds.get(id);
	const stats = guildStats(guild);

	stats.reason = reason;
	r.table('collection')
		.insert(stats)
		.run(r.conn, (err) => {
			if (err) throw new Error('Couldn\'t save banned guild.');
			console.log(`Banned ${client.guilds.get(id).name}`);
			guild.leave();
		});
}

function checkGuilds(bot) {
	bot.guilds.filter(guild => guildStats(guild).guild.collection).forEach(guild => banGuild(guild.id, {
		message: 'Bot collection guild',
		maxUsers: config.get('discord').collection.users,
		maxPercentage: config.get('discord').collection.percentage
	}));
}

client.on('guildCreate', (guild) => {
	const report = guildStats(guild);
	console.log(report);

	if (report.guild.collection) {
		console.log(`${guild.name} failed the authentication test`);
		banGuild(guild.id, {
			message: 'Bot collection guild',
			maxUsers: config.get('discord').collection.users,
			maxPercentage: config.get('discord').collection.percentage
		});
	} else {
		r.table('collection')
			.filter(
				r.row('guildID').eq(guild.id).or(r.row('ownerID').eq(guild.ownerID))
			)
			.run(r.conn, (err1, cursor) => {
				if (err1) throw new Error('Failed to search banned guild database.');
				cursor.toArray((err2, result) => {
					if (err2) throw new Error('Failed to convert banned cursor to results.');
					if (result.length < 1) {
						console.log(`${guild.name} passed the authentication test`);
					} else {
						console.log(`${guild.name} was already banned!`);
						banGuild(guild.id, {
							message: 'Already banned',
							refer: result.map(reason => reason.id) || []
						});
					}
				});
			});
	}
});

exports.ban = banGuild;
exports.check = checkGuilds;
<|endoftext|>