text:
namespace neu {
	namespace layer {
		class convolution_optimized_wr {
		public:
			convolution_optimized_wr() = default;

			convolution_optimized_wr(
				geometric_layer_property const& glp,
				int batch_size,
				scalar c,
				cpu_vector const& filters,
				optimizer::any_optimizer const& optimizer,
				boost::compute::command_queue& queue)
			: glp_(glp), batch_size_(batch_size), c_(c),
			filters_(filters.begin(), filters.end(), queue),
			squared_filters_(filters.size(),
				std::numeric_limits<cl_float>::quiet_NaN(), queue),
			optimizer_(optimizer),
			output_width_(output_width(glp)),
			forward_kernel_(make_kernel(convolution_optimized_wr_kernel_source,
				"forward", queue.get_context())),
			backward_kernel_(make_kernel(convolution_optimized_wr_kernel_source,
				"backward", queue.get_context())),
			update_kernel_(make_kernel(convolution_optimized_wr_kernel_source,
				"update_tile32",
				queue.get_context())),
			input_(layer::input_dim(glp)*batch_size_,
				std::numeric_limits<cl_float>::quiet_NaN(), queue),
			delta_(layer::output_dim(glp)*batch_size_,
				std::numeric_limits<cl_float>::quiet_NaN(), queue),
			del_filters_(filters_.size(),
				std::numeric_limits<cl_float>::quiet_NaN(), queue) {}

			decltype(auto) batch_size() const { return batch_size_; }

			decltype(auto) input_rank() const { return 3; }
			decltype(auto) output_rank() const { return 3; }

			decltype(auto) input_size(rank_id ri) const {
				return ri == rank_id::width || ri == rank_id::height ? glp_.input_width :
					ri == rank_id::channel_num ? glp_.input_channel_num : 0;
			}
			decltype(auto) output_size(rank_id ri) const {
				return ri == rank_id::width || ri == rank_id::height ? output_width_ :
					ri == rank_id::channel_num ? glp_.output_channel_num : 0;
			}

			decltype(auto) filters(boost::compute::command_queue& queue) const {
				return neu::to_cpu_vector(filters_, queue);
			}
			decltype(auto) del_filters(boost::compute::command_queue& queue) const {
				return neu::to_cpu_vector(del_filters_, queue);
			}

			template<typename InputRange, typename OutputRange>
			decltype(auto) test_forward(int test_batch_size,
					InputRange const& input, OutputRange& output,
					boost::compute::command_queue& queue) {
				NEU_ASSERT(neu::range::distance(input) ==
					neu::layer::input_dim(*this)*test_batch_size);
				NEU_ASSERT(neu::range::distance(output) ==
					neu::layer::output_dim(*this)*test_batch_size);
				NEU_ASSERT_FOR_HEAVY_CALCULATION(is_all_of_finite(input, queue));

				neu::layer::convolution_optimized_wr_forward(
					forward_kernel_,
					input, filters_, output,
					batch_size_,
					glp_.input_width, glp_.filter_width, output_width_,
					glp_.input_channel_num, glp_.output_channel_num,
					glp_.stride, glp_.pad, queue);
				NEU_ASSERT_FOR_HEAVY_CALCULATION(is_all_of_finite(output, queue));
			}
			template<typename InputRange, typename OutputRange>
			decltype(auto) forward(
					InputRange const& input, OutputRange& output,
					boost::compute::command_queue& queue) {
				NEU_ASSERT(neu::range::distance(input)
					== neu::layer::input_dim(glp_)*batch_size_);
				NEU_ASSERT_FOR_HEAVY_CALCULATION(is_all_of_finite(input, queue));

				neu::range::copy(input, input_, queue);
				test_forward(batch_size_, input, output, queue);
			}

			template<typename InputRange>
			decltype(auto) backward_top(
					InputRange const& delta,
					boost::compute::command_queue& queue) {
				NEU_ASSERT(neu::range::distance(delta)
					== static_cast<int>(delta_.size()));
				NEU_ASSERT_FOR_HEAVY_CALCULATION(is_all_of_finite(delta, queue));
				neu::range::copy(delta, delta_, queue);
			}
			template<typename InputRange, typename OutputRange>
			decltype(auto) backward(
					InputRange const& delta, OutputRange& prev_delta,
					boost::compute::command_queue& queue) {
				backward_top(delta, queue);
				neu::layer::convolution_optimized_wr_backward(
					backward_kernel_,
					delta, filters_, prev_delta,
					batch_size_,
					glp_.input_width, glp_.filter_width, output_width_,
					glp_.input_channel_num, glp_.output_channel_num,
					glp_.stride, glp_.pad, queue);
				NEU_ASSERT_FOR_HEAVY_CALCULATION(is_all_of_finite(prev_delta, queue));
			}

			decltype(auto) update(boost::compute::command_queue& queue) {
				//neu::layer::convolution_optimized_wr_update_tile64_wpt2_reg(
				neu::layer::convolution_optimized_wr_update_tile32(
					update_kernel_,
					delta_, input_, del_filters_,
					batch_size_,
					glp_.input_width, glp_.filter_width, output_width_,
					glp_.input_channel_num, glp_.output_channel_num,
					glp_.stride, glp_.pad, queue);
				NEU_ASSERT_FOR_HEAVY_CALCULATION(is_all_of_finite(del_filters_, queue));

				optimizer_.apply(filters_, del_filters_, queue);

				// weight regularization
				scalar sum_of_squared = 0.f;
				using boost::compute::lambda::_1;
				boost::compute::transform(filters_.begin(), filters_.end(),
					squared_filters_.begin(), _1*_1, queue);
				boost::compute::reduce(squared_filters_.begin(), squared_filters_.end(),
					&sum_of_squared, queue);
				if(sum_of_squared > c_*c_) {
					boost::compute::transform(filters_.begin(), filters_.end(),
						filters_.begin(), c_*_1/std::sqrt(sum_of_squared), queue);
				}
				NEU_ASSERT_FOR_HEAVY_CALCULATION(is_all_of_finite(filters_, queue));
			}

			decltype(auto) serialize(
					YAML::Emitter& emitter, boost::compute::command_queue& queue) const {
				emitter << YAML::BeginMap
					<< YAML::Key << "layer_type"
						<< YAML::Value << "convolution_optimized_wr";
				layer::serialize(glp_, emitter);
				emitter
					<< YAML::Key << "output_width(calculated)"
						<< YAML::Value << output_width_
					<< YAML::Key << "batch_size"
						<< YAML::Value << batch_size_
					<< YAML::Key << "c"
						<< YAML::Value << c_
#ifndef NEU_LAYER_SERIALIZE_WITHOUT_LONG_VECTOR
					<< YAML::Key << "filters"
						<< YAML::Value << YAML::Flow << filters(queue)
#endif
					<< YAML::Key << "optimizer"
						<< YAML::Value;
				optimizer::serialize(optimizer_, emitter, queue);
				emitter << YAML::EndMap;
			}

		private:
			geometric_layer_property glp_;
			int batch_size_;
			scalar c_;

			gpu_vector filters_, squared_filters_;

			optimizer::any_optimizer optimizer_;

			int output_width_;

			kernel forward_kernel_;
			kernel backward_kernel_;
			kernel update_kernel_;

			gpu_vector input_;
			gpu_vector delta_;
			gpu_vector del_filters_;
		};

		template<typename FilterGen>
		decltype(auto) make_convolution_optimized_wr(
			geometric_layer_property const& glp,
			int batch_size, scalar c,
			FilterGen const& fg,
			optimizer::any_optimizer const& optimizer,
			boost::compute::command_queue& queue
		) {
			cpu_vector cpu_filters(neu::layer::filters_size(glp));
			std::generate(cpu_filters.begin(), cpu_filters.end(), fg);
			return convolution_optimized_wr(glp, batch_size, c, cpu_filters, optimizer, queue);
		}

		template<typename Rng>
		decltype(auto) make_convolution_optimized_wr_xavier(
			geometric_layer_property const& glp,
			int batch_size,
			scalar c,
			Rng&& rng,
			optimizer::any_optimizer const& optimizer,
			boost::compute::command_queue& queue
		) {
			auto dist = std::normal_distribution<neu::scalar>(
				0.f, std::sqrt(1.f/neu::layer::input_dim(glp)));
			return neu::layer::make_convolution_optimized_wr(glp, batch_size, c,
				[&rng, dist]() mutable { return dist(rng); },
				optimizer, queue);
		}

		decltype(auto) deserialize_convolution_optimized_wr(YAML::Node const& node,
				boost::compute::command_queue& queue) {
			const auto glp = deserialize_geometric_layer_property(node);
			return convolution_optimized_wr(
				glp, node["batch_size"].as<int>(), node["c"].as<scalar>(),
				node["filters"].as<cpu_vector>(),
				optimizer::deserialize(node["optimizer"], queue),
				queue
			);
		}
	}
}// namespace neu

#endif //NEU_LAYER_CONVOLUTION_OPTIMIZED_WR_IMPL_HPP


text:
import CustomElements from '../../Platform/CustomElements'

const throttleToFrame = (fn) => {
  let scheduled = false
  let args = null
  return function () {
    args = Array.from(arguments)
    if (scheduled) return
    scheduled = true
    requestAnimationFrame(() => {
      scheduled = false
      fn.apply(null, args)
    })
  }
}

const start = (app) => {
  CustomElements.define('ellie-ui-split-pane-group', (HTMLElement) => class extends HTMLElement {
    constructor() {
      super()
      this.onDocumentMouseMove = this.onDocumentMouseMove.bind(this)
      this.updatePosition = throttleToFrame(this.updatePosition.bind(this))
      this.onWindowResize = throttleToFrame(this.onWindowResize.bind(this))
      this.onDocumentMouseUp = this.onDocumentMouseUp.bind(this)
      this.onDividerMouseDown = this.onDividerMouseDown.bind(this)
      this.onDividerDoubleClick = this.onDividerDoubleClick.bind(this)
      this._dragging = false
      this._isVertical = false
      this._ratio = 0.5
      this._originalRatio = 0.5
      this._minSize = 0
    }

    get minSize() {
      return this._minSize
    }

    set minSize(value) {
      if (value === this._minSize) return
      this._minSize = value
      this.forceLayout()
    }

    get originalRatio() {
      return this._originalRatio
    }

    set originalRatio(value) {
      this._originalRatio = value
    }

    get isVertical() {
      return this._isVertical
    }

    set isVertical(value) {
      if (value === this._isVertical) return
      this._isVertical = value
      if (this.childElementCount) this.forceLayout()
      if (this._dragging) this.style.cursor = value ? 'ns-resize' : 'ew-resize'
    }

    get ratio() {
      return this._ratio
    }

    set ratio(value) {
      if (value === this._ratio) return
      this._ratio = value
      this.forceLayout()
    }

    onWindowResize() {
      this.forceLayout()
    }

    onDocumentMouseMove(event) {
      this.updatePosition(event.pageX, event.pageY)
    }

    forceLayout() {
      this.layout(this.getBoundingClientRect())
    }

    updatePosition(pageX, pageY) {
      const rect = this.getBoundingClientRect()
      let nextRatio = this._isVertical ?
        (pageY - rect.top - this._minSize - 2) / rect.height :
        (pageX - rect.left - this._minSize - 2) / rect.width
      if (nextRatio === this._ratio) return
      this._ratio = nextRatio
      this.layout(rect)
    }

    layout(rect) {
      if (!this.childElementCount) return
      if (this._isVertical) {
        const minSizeRatio = (this._minSize + 1) / rect.height
        const adjustedRatio = Math.min(1 - (2 * minSizeRatio), Math.max(this._ratio, 0))
        this.children[0].style.height = this.children[1].style.top = `${(adjustedRatio + minSizeRatio) * 100}%`
        this.children[2].style.height = `${(1 - (adjustedRatio + minSizeRatio)) * 100}%`
      } else {
        const minSizeRatio = (this._minSize + 1) / rect.width
        const adjustedRatio = Math.min(1 - (2 * minSizeRatio), Math.max(this._ratio, 0))
        this.children[0].style.width = this.children[1].style.left = `${(adjustedRatio + minSizeRatio) * 100}%`
        this.children[2].style.width = `${(1 - (adjustedRatio + minSizeRatio)) * 100}%`
      }
    }

    onDocumentMouseUp() {
      this.style.cursor = null
      this.style.userSelect = null
      this.children[0].style.pointerEvents = this.children[2].style.pointerEvents = null
      this._dragging = false
      this.dispatchEvent(new Event('resize'))
      document.removeEventListener('mousemove', this.onDocumentMouseMove)
      document.removeEventListener('mouseup', this.onDocumentMouseUp)
    }

    onDividerMouseDown() {
      this.style.cursor = this._isVertical ? 'ns-resize' : 'ew-resize'
      this.style.userSelect = 'none'
      this.children[0].style.pointerEvents = this.children[2].style.pointerEvents = 'none'
      this._dragging = true
      document.addEventListener('mousemove', this.onDocumentMouseMove)
      document.addEventListener('mouseup', this.onDocumentMouseUp)
    }

    onDividerDoubleClick() {
      if (this._ratio === this._originalRatio) return
      this.ratio = this._originalRatio
      this.dispatchEvent(new Event('resize'))
    }

    connectedCallback() {
      this.children[1].addEventListener('mousedown', this.onDividerMouseDown)
      this.children[1].addEventListener('dblclick', this.onDividerDoubleClick)
      window.addEventListener('resize', this.onWindowResize)
      this.forceLayout()
    }

    disconnectedCallback() {
      document.removeEventListener('mousemove', this.onDocumentMouseMove)
      document.removeEventListener('mouseup', this.onDocumentMouseUp)
      window.removeEventListener('resize', this.onWindowResize)
    }
  })
}

export default { start }

redpajama_set_name: RedPajamaGithub


text:
import * as React from 'react';
import Switch, { SwitchProps } from '@material-ui/core/Switch';
import FormGroup from '@material-ui/core/FormGroup';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import { stylesheet } from 'typestyle';
import { ExternalLink } from '../atoms/ExternalLink';
import { CardTooltip } from '../atoms/CardTooltip';

const css = stylesheet({
  reduceGraphPosition: {
    position: 'absolute',
    top: 0,
    left: 0,
  },
});

interface ReduceGraphSwitchProps extends SwitchProps {}

const ReduceGraphSwitch = (props: ReduceGraphSwitchProps) => {
  return (

      <CardTooltip
        helpText={

              Enables a{' '}
              <ExternalLink href='https://en.wikipedia.org/wiki/Transitive_reduction'>
                transitive reduction
              </ExternalLink>{' '}
              of the pipeline graph, hiding all the redundant edges. This option is just a
              visualization helper and does not have any permanent effect on the pipeline itself.

              Note that edges are removed regardless of their function in the pipeline, so the
              reduced form might not provide enough details to understand how the pipeline really
              behaves.

        }
      >
        <FormGroup>
          <FormControlLabel
            control={<Switch color={'primary'} {...props} />}
            label={'Simplify Graph'}
            labelPlacement='end'
          />
        </FormGroup>
      </CardTooltip>

  );
};

export default ReduceGraphSwitch;


text:
'use strict';

var models = require('./index');

var util = require('util');

/**
 * @class
 * Initializes a new instance of the NotificationHubProperties class.
 * @constructor
 * NotificationHub properties.
 * @member {string} [name] The NotificationHub name.
 *
 * @member {string} [registrationTtl] The RegistrationTtl of the created
 * NotificationHub
 *
 * @member {array} [authorizationRules] The AuthorizationRules of the created
 * NotificationHub
 *
 * @member {object} [apnsCredential] The ApnsCredential of the created
 * NotificationHub
 *
 * @member {object} [apnsCredential.properties] Gets or sets properties of
 * NotificationHub ApnsCredential.
 *
 * @member {string} [apnsCredential.properties.apnsCertificate] Gets or sets
 * the APNS certificate.
 *
 * @member {string} [apnsCredential.properties.certificateKey] Gets or sets
 * the certificate key.
 *
 * @member {string} [apnsCredential.properties.endpoint] Gets or sets the
 * endpoint of this credential.
 *
 * @member {string} [apnsCredential.properties.thumbprint] Gets or sets the
 * Apns certificate Thumbprint
 *
 * @member {object} [wnsCredential] The WnsCredential of the created
 * NotificationHub
 *
 * @member {object} [wnsCredential.properties] Gets or sets properties of
 * NotificationHub WnsCredential.
 *
 * @member {string} [wnsCredential.properties.packageSid] Gets or sets the
 * package ID for this credential.
 *
 * @member {string} [wnsCredential.properties.secretKey] Gets or sets the
 * secret key.
 *
 * @member {string} [wnsCredential.properties.windowsLiveEndpoint] Gets or
 * sets the Windows Live endpoint.
 *
 * @member {object} [gcmCredential] The GcmCredential of the created
 * NotificationHub
 *
 * @member {object} [gcmCredential.properties] Gets or sets properties of
 * NotificationHub GcmCredential.
 *
 * @member {string} [gcmCredential.properties.gcmEndpoint] Gets or sets the
 * GCM endpoint.
 *
 * @member {string} [gcmCredential.properties.googleApiKey] Gets or sets the
 * Google API key.
 *
 * @member {object} [mpnsCredential] The MpnsCredential of the created
 * NotificationHub
 *
 * @member {object} [mpnsCredential.properties] Gets or sets properties of
 * NotificationHub MpnsCredential.
 *
 * @member {string} [mpnsCredential.properties.mpnsCertificate] Gets or sets
 * the MPNS certificate.
 *
 * @member {string} [mpnsCredential.properties.certificateKey] Gets or sets
 * the certificate key for this credential.
 *
 * @member {string} [mpnsCredential.properties.thumbprint] Gets or sets the
 * Mpns certificate Thumbprint
 *
 * @member {object} [admCredential] The AdmCredential of the created
 * NotificationHub
 *
 * @member {object} [admCredential.properties] Gets or sets properties of
 * NotificationHub AdmCredential.
 *
 * @member {string} [admCredential.properties.clientId] Gets or sets the
 * client identifier.
 *
 * @member {string} [admCredential.properties.clientSecret] Gets or sets the
 * credential secret access key.
 *
 * @member {string} [admCredential.properties.authTokenUrl] Gets or sets the
 * URL of the authorization token.
 *
 * @member {object} [baiduCredential] The BaiduCredential of the created
 * NotificationHub
 *
 * @member {object} [baiduCredential.properties] Gets or sets properties of
 * NotificationHub BaiduCredential.
 *
 * @member {string} [baiduCredential.properties.baiduApiKey] Get or Set Baidu
 * Api Key.
 *
 * @member {string} [baiduCredential.properties.baiduEndPoint] Get or Set
 * Baidu Endpoint.
 *
 * @member {string} [baiduCredential.properties.baiduSecretKey] Get or Set
 * Baidu Secret Key
 *
 */
function NotificationHubProperties() {
}

/**
 * Defines the metadata of NotificationHubProperties
 *
 * @returns {object} metadata of NotificationHubProperties
 *
 */
NotificationHubProperties.prototype.mapper = function () {
  return {
    required: false,
    serializedName: 'NotificationHubProperties',
    type: {
      name: 'Composite',
      className: 'NotificationHubProperties',
      modelProperties: {
        name: {
          required: false,
          serializedName: 'name',
          type: {
            name: 'String'
          }
        },
        registrationTtl: {
          required: false,
          serializedName: 'registrationTtl',
          type: {
            name: 'String'
          }
        },
        authorizationRules: {
          required: false,
          serializedName: 'authorizationRules',
          type: {
            name: 'Sequence',
            element: {
                required: false,
                serializedName: 'SharedAccessAuthorizationRulePropertiesElementType',
                type: {
                  name: 'Composite',
                  className: 'SharedAccessAuthorizationRuleProperties'
                }
            }
          }
        },
        apnsCredential: {
          required: false,
          serializedName: 'apnsCredential',
          type: {
            name: 'Composite',
            className: 'ApnsCredential'
          }
        },
        wnsCredential: {
          required: false,
          serializedName: 'wnsCredential',
          type: {
            name: 'Composite',
            className: 'WnsCredential'
          }
        },
        gcmCredential: {
          required: false,
          serializedName: 'gcmCredential',
          type: {
            name: 'Composite',
            className: 'GcmCredential'
          }
        },
        mpnsCredential: {
          required: false,
          serializedName: 'mpnsCredential',
          type: {
            name: 'Composite',
            className: 'MpnsCredential'
          }
        },
        admCredential: {
          required: false,
          serializedName: 'admCredential',
          type: {
            name: 'Composite',
            className: 'AdmCredential'
          }
        },
        baiduCredential: {
          required: false,
          serializedName: 'baiduCredential',
          type: {
            name: 'Composite',
            className: 'BaiduCredential'
          }
        }
      }
    }
  };
};

module.exports = NotificationHubProperties;


text:
var HttpError = require('error').HttpError;

module.exports = function(req, res, next) {
    if (!req.user) {
        res.redirect('/login');
        return;
    }

    next();
};


text:
import type {
  AlgoliaSearchHelper,
  SearchParameters,
  SearchResults,
} from 'algoliasearch-helper';
import {
  checkRendering,
  escapeFacetValue,
  createDocumentationMessageGenerator,
  find,
  noop,
  toArray,
} from '../../lib/utils';
import type {
  Connector,
  CreateURL,
  InstantSearch,
  WidgetRenderState,
} from '../../types';

const withUsage = createDocumentationMessageGenerator({
  name: 'toggle-refinement',
  connector: true,
});

const $$type = 'ais.toggleRefinement';

type BuiltInSendEventForToggle = (
  eventType: string,
  isRefined: boolean,
  eventName?: string
) => void;
type CustomSendEventForToggle = (customPayload: any) => void;

export type SendEventForToggle = BuiltInSendEventForToggle &
  CustomSendEventForToggle;

const createSendEvent = ({
  instantSearchInstance,
  helper,
  attribute,
  on,
}: {
  instantSearchInstance: InstantSearch;
  helper: AlgoliaSearchHelper;
  attribute: string;
  on: string[] | undefined;
}) => {
  const sendEventForToggle: SendEventForToggle = (...args: any[]) => {
    if (args.length === 1) {
      instantSearchInstance.sendEventToInsights(args[0]);
      return;
    }
    const [eventType, isRefined, eventName = 'Filter Applied'] = args;
    if (eventType !== 'click' || on === undefined) {
      return;
    }

    // only send an event when the refinement gets applied,
    // not when it gets removed
    if (!isRefined) {
      instantSearchInstance.sendEventToInsights({
        insightsMethod: 'clickedFilters',
        widgetType: $$type,
        eventType,
        payload: {
          eventName,
          index: helper.getIndex(),
          filters: on.map((value) => `${attribute}:${value}`),
        },
        attribute,
      });
    }
  };
  return sendEventForToggle;
};

export type ToggleRefinementValue = {
  /**
   * Whether this option is enabled.
   */
  isRefined: boolean;
  /**
   * Number of result if this option is toggled.
   */
  count: number | null;
};

export type ToggleRefinementConnectorParams = {
  /**
   * Name of the attribute for faceting (e.g., "free_shipping").
   */
  attribute: string;
  /**
   * Value to filter on when toggled.
   * @default "true"
   */
  on?: FacetValue | FacetValue[];
  /**
   * Value to filter on when not toggled.
   */
  off?: FacetValue | FacetValue[];
};

type FacetValue = string | boolean | number;

export type ToggleRefinementRenderState = {
  /** The current toggle value */
  value: {
    /**
     * The attribute name of this toggle.
     */
    name: string;
    /**
     * Whether the current option is "on" (true) or "off" (false)
     */
    isRefined: boolean;
    /**
     * Number of results if this option is toggled.
     */
    count: number | null;
    /**
     * Information about the "on" toggle.
     */
    onFacetValue: ToggleRefinementValue;
    /**
     * Information about the "off" toggle.
     */
    offFacetValue: ToggleRefinementValue;
  };
  /**
   * Creates an URL for the next state.
   */
  createURL: CreateURL<string>;
  /**
   * Send a "Facet Clicked" Insights event.
   */
  sendEvent: SendEventForToggle;
  /**
   * Indicates if search state can be refined.
   */
  canRefine: boolean;
  /**
   * Updates to the next state by applying the toggle refinement.
   */
  refine: (value?: { isRefined: boolean }) => void;
};

export type ToggleRefinementWidgetDescription = {
  $$type: 'ais.toggleRefinement';
  renderState: ToggleRefinementRenderState;
  indexRenderState: {
    toggleRefinement: {
      [attribute: string]: WidgetRenderState<
        ToggleRefinementRenderState,
        ToggleRefinementConnectorParams
      >;
    };
  };
  indexUiState: {
    toggle: {
      [attribute: string]: boolean;
    };
  };
};

export type ToggleRefinementConnector = Connector<
  ToggleRefinementWidgetDescription,
  ToggleRefinementConnectorParams
>;

/**
 * **Toggle** connector provides the logic to build a custom widget that will provide
 * an on/off filtering feature based on an attribute value or values.
 *
 * Two modes are implemented in the custom widget:
 *  - with or without the value filtered
 *  - switch between two values.
 */
const connectToggleRefinement: ToggleRefinementConnector =
  function connectToggleRefinement(renderFn, unmountFn = noop) {
    checkRendering(renderFn, withUsage());

    return (widgetParams) => {
      const { attribute, on: userOn = true, off: userOff } = widgetParams || {};

      if (!attribute) {
        throw new Error(withUsage('The `attribute` option is required.'));
      }

      const hasAnOffValue = userOff !== undefined;
      // even though facet values can be numbers and boolean,
      // the helper methods only accept string in the type
      const on = toArray(userOn).map(escapeFacetValue) as string[];
      const off = hasAnOffValue
        ? (toArray(userOff).map(escapeFacetValue) as string[])
        : undefined;

      let sendEvent: SendEventForToggle;

      const toggleRefinementFactory =
        (helper: AlgoliaSearchHelper) =>
        (
          {
            isRefined,
          }: {
            isRefined: boolean;
          } = { isRefined: false }
        ) => {
          if (!isRefined) {
            sendEvent('click', isRefined);
            if (hasAnOffValue) {
              off!.forEach((v) =>
                helper.removeDisjunctiveFacetRefinement(attribute, v)
              );
            }

            on.forEach((v) =>
              helper.addDisjunctiveFacetRefinement(attribute, v)
            );
          } else {
            on.forEach((v) =>
              helper.removeDisjunctiveFacetRefinement(attribute, v)
            );

            if (hasAnOffValue) {
              off!.forEach((v) =>
                helper.addDisjunctiveFacetRefinement(attribute, v)
              );
            }
          }

          helper.search();
        };

      const connectorState = {
        createURLFactory:
          (
            isRefined: boolean,
            {
              state,
              createURL,
            }: {
              state: SearchParameters;
              createURL(parameters: SearchParameters): string;
            }
          ) =>
          () => {
            state = state.resetPage();

            const valuesToRemove = isRefined ? on : off;
            if (valuesToRemove) {
              valuesToRemove.forEach((v) => {
                state = state.removeDisjunctiveFacetRefinement(attribute, v);
              });
            }

            const valuesToAdd = isRefined ? off : on;
            if (valuesToAdd) {
              valuesToAdd.forEach((v) => {
                state = state.addDisjunctiveFacetRefinement(attribute, v);
              });
            }

            return createURL(state);
          },
      };

      return {
        $$type,

        init(initOptions) {
          const { instantSearchInstance } = initOptions;

          renderFn(
            {
              ...this.getWidgetRenderState(initOptions),
              instantSearchInstance,
            },
            true
          );
        },

        render(renderOptions) {
          const { instantSearchInstance } = renderOptions;

          renderFn(
            {
              ...this.getWidgetRenderState(renderOptions),
              instantSearchInstance,
            },
            false
          );
        },

        dispose({ state }) {
          unmountFn();

          return state.removeDisjunctiveFacet(attribute);
        },

        getRenderState(renderState, renderOptions) {
          return {
            ...renderState,
            toggleRefinement: {
              ...renderState.toggleRefinement,
              [attribute]: this.getWidgetRenderState(renderOptions),
            },
          };
        },

        getWidgetRenderState({
          state,
          helper,
          results,
          createURL,
          instantSearchInstance,
        }) {
          const isRefined = results
            ? on.every((v) => state.isDisjunctiveFacetRefined(attribute, v))
            : on.every((v) => state.isDisjunctiveFacetRefined(attribute, v));

          let onFacetValue: ToggleRefinementValue = {
            isRefined,
            count: 0,
          };

          let offFacetValue: ToggleRefinementValue = {
            isRefined: hasAnOffValue && !isRefined,
            count: 0,
          };

          if (results) {
            const offValue = toArray(off || false);
            const allFacetValues = (results.getFacetValues(attribute, {}) ||
              []) as SearchResults.FacetValue[];

            const onData = on
              .map((v) =>
                find(
                  allFacetValues,
                  ({ escapedValue }) =>
                    escapedValue === escapeFacetValue(String(v))
                )
              )
              .filter((v): v is SearchResults.FacetValue => v !== undefined);

            const offData = hasAnOffValue
              ? offValue
                  .map((v) =>
                    find(
                      allFacetValues,
                      ({ escapedValue }) =>
                        escapedValue === escapeFacetValue(String(v))
                    )
                  )
                  .filter((v): v is SearchResults.FacetValue => v !== undefined)
              : [];

            onFacetValue = {
              isRefined: onData.length
                ? onData.every((v) => v.isRefined)
                : false,
              count: onData.reduce((acc, v) => acc + v.count, 0) || null,
            };

            offFacetValue = {
              isRefined: offData.length
                ? offData.every((v) => v.isRefined)
                : false,
              count:
                offData.reduce((acc, v) => acc + v.count, 0) ||
                allFacetValues.reduce((total, { count }) => total + count, 0),
            };
          }

          if (!sendEvent) {
            sendEvent = createSendEvent({
              instantSearchInstance,
              attribute,
              on,
              helper,
            });
          }
          const nextRefinement = isRefined ? offFacetValue : onFacetValue;

          return {
            value: {
              name: attribute,
              isRefined,
              count: results ? nextRefinement.count : null,
              onFacetValue,
              offFacetValue,
            },
            createURL: connectorState.createURLFactory(isRefined, {
              state,
              createURL,
            }),
            sendEvent,
            canRefine: Boolean(results ? nextRefinement.count : null),
            refine: toggleRefinementFactory(helper),
            widgetParams,
          };
        },

        getWidgetUiState(uiState, { searchParameters }) {
          const isRefined =
            on &&
            on.every((v) =>
              searchParameters.isDisjunctiveFacetRefined(attribute, v)
            );

          if (!isRefined) {
            return uiState;
          }

          return {
            ...uiState,
            toggle: {
              ...uiState.toggle,
              [attribute]: isRefined,
            },
          };
        },

        getWidgetSearchParameters(searchParameters, { uiState }) {
          let withFacetConfiguration = searchParameters
            .clearRefinements(attribute)
            .addDisjunctiveFacet(attribute);

          const isRefined = Boolean(
            uiState.toggle && uiState.toggle[attribute]
          );

          if (isRefined) {
            if (on) {
              on.forEach((v) => {
                withFacetConfiguration =
                  withFacetConfiguration.addDisjunctiveFacetRefinement(
                    attribute,
                    v
                  );
              });
            }

            return withFacetConfiguration;
          }

          // It's not refined with an `off` value
          if (hasAnOffValue) {
            if (off) {
              off.forEach((v) => {
                withFacetConfiguration =
                  withFacetConfiguration.addDisjunctiveFacetRefinement(
                    attribute,
                    v
                  );
              });
            }
            return withFacetConfiguration;
          }

          // It's not refined without an `off` value
          return withFacetConfiguration.setQueryParameters({
            disjunctiveFacetsRefinements: {
              ...searchParameters.disjunctiveFacetsRefinements,
              [attribute]: [],
            },
          });
        },
      };
    };
  };

export default connectToggleRefinement;


text:
import numpy as np

def sigmoid(x):
    """
    Calculate sigmoid
    """
    return 1/(1+np.exp(-x))

def sigmoid_prime(x):
    """
    # Derivative of the sigmoid function
    """
    return sigmoid(x) * (1 - sigmoid(x))

learnrate = 0.5
x = np.array([1, 2, 3, 4])
y = np.array(0.5)

# Initial weights
w = np.array([0.5, -0.5, 0.3, 0.1])

### Calculate one gradient descent step for each weight
### Note: Some steps have been consilated, so there are
###       fewer variable names than in the above sample code

# TODO: Calculate the node's linear combination of inputs and weights
h = np.dot(x, w)

# TODO: Calculate output of neural network
nn_output = sigmoid(h)

# TODO: Calculate error of neural network
error = y - nn_output

# TODO: Calculate the error term
#       Remember, this requires the output gradient, which we haven't
#       specifically added a variable for.
error_term = error * sigmoid_prime(h)

# TODO: Calculate change in weights
del_w = learnrate * error_term * x

print('Neural Network output:')
print(nn_output)
print('Amount of Error:')
print(error)
print('Change in Weights:')
print(del_w)


text:
package logs

import (
	"fmt"
	"time"

	"github.com/aws/aws-sdk-go/service/cloudwatchlogs"
	"github.com/tj/cobra"

	"github.com/apex/apex/cmd/apex/root"
	"github.com/apex/apex/logs"
	"github.com/apex/apex/stats"
)

// filter pattern.
var filter string

// follow via polling.
var follow bool

// duration of results.
var duration time.Duration

// example output.
const example = `
    Print logs for all functions
    $ apex logs

    Follow the output
    $ apex logs -f

    Follow output with no historical logs
    $ apex logs -f --since 0

    Print logs for a single function
    $ apex logs api

    Print logs for all functions starting with "auth"
    $ apex logs auth*

    Print logs for functions with a specified start time, e.g. 5 minutes
    $ apex logs foo bar --since 5m`

// Command config.
var Command = &cobra.Command{
	Use:     "logs [<name>...] [<duration>]",
	Short:   "Output function logs",
	Example: example,
	RunE:    run,
}

// Initialize.
func init() {
	root.Register(Command)

	f := Command.Flags()
	f.DurationVarP(&duration, "since", "s", 5*time.Minute, "Start time of the search")
	f.StringVarP(&filter, "filter", "F", "", "Filter logs with pattern")
	f.BoolVarP(&follow, "follow", "f", false, "Follow tails logs for updates")
}

// Run command.
func run(c *cobra.Command, args []string) error {
	stats.Track("Logs", map[string]interface{}{
		"has_filter": filter != "",
		"since":      duration,
		"follow":     follow,
	})

	if err := root.Project.LoadFunctions(args...); err != nil {
		return err
	}

	config := logs.Config{
		Service:       cloudwatchlogs.New(root.Session),
		StartTime:     time.Now().Add(-duration).UTC(),
		PollInterval:  5 * time.Second,
		Follow:        follow,
		FilterPattern: filter,
	}

	l := &logs.Logs{
		Config: config,
	}

	for _, fn := range root.Project.Functions {
		l.GroupNames = append(l.GroupNames, fn.GroupName())
	}

	for event := range l.Start() {
		fmt.Printf("\033[34m%s\033[0m %s", event.GroupName, event.Message)
	}

	return l.Err()
}


text:
package eveapi.xml.account.account.APIKeyInfo

case class Eveapi(currentTime: String,
                  result: eveapi.xml.account.account.APIKeyInfo.Result,
                  cachedUntil: String,
                  attributes: Map[String, scalaxb.DataRecord[Any]] = Map()) {
  lazy val version = attributes("@version").as[BigInt]
}

case class Result(key: eveapi.xml.account.account.APIKeyInfo.Key)

case class Key(rowset: eveapi.xml.account.account.APIKeyInfo.Rowset,
               attributes: Map[String, scalaxb.DataRecord[Any]] = Map()) {
  lazy val accessMask = attributes("@accessMask").as[BigInt]
  lazy val expires = attributes("@expires").as[String]
  lazy val typeValue = attributes("@type").as[String]
}

case class Rowset(row: Seq[eveapi.xml.account.account.APIKeyInfo.Row] = Nil,
                  attributes: Map[String, scalaxb.DataRecord[Any]] = Map()) {
  lazy val columns = attributes("@columns").as[String]
  lazy val key = attributes("@key").as[String]
  lazy val name = attributes("@name").as[String]
}

case class Row(attributes: Map[String, scalaxb.DataRecord[Any]] = Map()) {
  lazy val allianceID = attributes("@allianceID").as[BigInt]
  lazy val allianceName = attributes("@allianceName").as[String]
  lazy val characterID = attributes("@characterID").as[BigInt]
  lazy val characterName = attributes("@characterName").as[String]
  lazy val corporationID = attributes("@corporationID").as[BigInt]
  lazy val corporationName = attributes("@corporationName").as[String]
  lazy val factionID = attributes("@factionID").as[BigInt]
  lazy val factionName = attributes("@factionName").as[String]
}


text:
static const float DAY_VIEW_CELL_HEIGHT   = 30.0;
static const float HOUR_GRID_HEIGHT       = 48.0;
static const float EVENT_INDENTATION      = 55.0;

static const NSArray *hours;

@interface EventDayScrollView ()
@property (nonatomic, strong) NSArray *dayEvents;
@property (nonatomic, strong) NSMutableArray *allEventViews;
@property (nonatomic, strong) UITableView *dayEventsView;               // Display day events
@property (nonatomic, strong) UITableView *hourGridTableView;           // Display hourly events
@property (nonatomic, strong) UIView *nowLine;
@end

@implementation EventDayScrollView

@synthesize calendarColor = _calendarColor;

// |-----------------------|
// |- day events table ----|
// |                       |
// |  |-- hour grids ---|  |
// |  |                 |  |
// |  |                 |  |
// -------------------------
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];

    if (self) {
        self.backgroundColor = [UIColor lightBlue];

        self.dayEventsView = [[UITableView alloc] initWithFrame:frame style:UITableViewStylePlain];

        self.dayEventsView.tag = 100;
        self.dayEventsView.delegate = self;
        self.dayEventsView.dataSource = self;
        self.dayEventsView.backgroundView = nil;
        self.dayEventsView.backgroundColor = [UIColor darkBlue];

        [self addSubview:self.dayEventsView];

        self.hourGridTableView = [[UITableView alloc] initWithFrame:frame style:UITableViewStylePlain];
        self.hourGridTableView.tag = 200;
        self.hourGridTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        self.hourGridTableView.delegate = self;
        self.hourGridTableView.dataSource = self;

        [self addSubview:self.hourGridTableView];
    }

    hours = [NSArray arrayWithObjects:@"12 AM", @"1 AM", @"2 AM", @"3 AM", @"4 AM", @"5 AM", @"6 AM", @"7 AM", @"8 AM", @"9 AM", @"10 AM", @"11 AM", @"Noon", @"1 PM", @"2 PM", @"3 PM", @"4 PM", @"5 PM", @"6 PM", @"7 PM", @"8 PM", @"9 PM", @"10 PM", @"11 PM", @"12 PM", nil];

    return self;
}

- (void)setCalendarColor:(UIColor *)calendarColor {
    _calendarColor = calendarColor;
    self.backgroundColor = _calendarColor;
    self.dayEventsView.backgroundColor = _calendarColor;
}

#pragma mark - Table view data source

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath: (NSIndexPath *)indexPath {
    if (tableView.tag == 100) {
        return DAY_VIEW_CELL_HEIGHT;
    }
    return HOUR_GRID_HEIGHT/2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (tableView.tag == 100) {         // The day event table
        return self.dayEvents.count;
    }
    return 50;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)aTableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleNone;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView.tag == 100) {         // The day event table
        NSString *CellIdentifier = [NSString stringWithFormat:@"DayEventCell"];

        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
        }

        NPEvent *e = [self.dayEvents objectAtIndex:indexPath.row];
        NSString *timeStr = [e eventDisplayTime];

        if (timeStr.length > 0) {
            cell.textLabel.text = [NSString stringWithFormat:@" %@ ", [e eventDisplayTime]];
        } else {
            cell.textLabel.text = [NSString stringWithFormat:@" %@ ", [DateUtil displayDate:e.startTime]];
        }

        cell.detailTextLabel.text = e.title;

        cell.detailTextLabel.textColor = [UIColor blackColor];
        cell.detailTextLabel.font = [UIFont systemFontOfSize:14.0];

        return cell;
    }

    NSString *CellIdentifier = [NSString stringWithFormat:@"HourGridCell%li", (long)indexPath.row];

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.userInteractionEnabled = NO;

    [self showHourMarks:indexPath];

    return cell;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView.tag == 100) {
        NPEvent *e = [self.dayEvents objectAtIndex:indexPath.row];

        cell.backgroundColor = [UIColor whiteColor];

        UIColor *eventBgColor = [[UIColor colorFromHexString:e.colorLabel] colorWithAlphaComponent:0.75];
        UIColor *textColor = [UIColor textColorFromBackground:eventBgColor];

        cell.textLabel.backgroundColor = eventBgColor;
        cell.textLabel.textColor = textColor;
        cell.textLabel.layer.cornerRadius = 4.0;
        cell.textLabel.layer.masksToBounds = YES;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView.tag == 100) {
        [self openEventDetail:[self.dayEvents objectAtIndex:indexPath.row]];
    }
}

# pragma mark - display hour labels.

- (void)showHourMarks:(NSIndexPath*)atIndex {
    if (atIndex.row%2 == 0) {
        NSString *hourMark = [hours objectAtIndex:(atIndex.row/2)];

        UILabel *hourLabel = [[UILabel alloc] init];

        hourLabel.backgroundColor = [UIColor whiteColor];

        hourLabel.text = [NSString stringWithFormat:@" %@ ", hourMark];

        int yPos = HOUR_GRID_HEIGHT/2 * atIndex.row - 10;

        hourLabel.frame = CGRectMake(12.0, yPos, 43.0, 20.0);
        hourLabel.font = [UIFont boldSystemFontOfSize:12.0];
        hourLabel.textAlignment = NSTextAlignmentLeft;

        hourLabel.layer.zPosition = 1;

        [self.hourGridTableView addSubview:hourLabel];
    }
}

#pragma mark - display events

- (void)displayEvents:(NSArray*)dayEvents hourEventsInfo:(NSArray*)hourEventsInfo {
    [self clearEventViews];

    // Only reload table with animation under certain circumstance.
    if (self.dayEvents.count != dayEvents.count) {
        self.dayEvents = dayEvents;
        [self.dayEventsView reloadData:NO];

    } else {
        self.dayEvents = dayEvents;
        [self.dayEventsView reloadData:NO];
    }

    float yPos = 3;
    if (self.dayEvents.count > 0) {
        yPos = (DAY_VIEW_CELL_HEIGHT) * dayEvents.count + 3;
    }

    if (yPos > 160.0) {
        yPos = 160.0;

        // Reduce the height of the day event table
        CGRect dayEventRect = self.dayEventsView.frame;
        dayEventRect.size.height = 158.0;
        self.dayEventsView.frame = dayEventRect;
    }

    // Adjust the hour grid view position if necessary
    CGRect rect = self.hourGridTableView.frame;
    rect.origin.y = yPos;
    self.hourGridTableView.frame = rect;

    for (NSDictionary *eventInfo in hourEventsInfo) {
        NPEvent *e = [eventInfo objectForKey:@"EVENT"];
        int overlaps = [[eventInfo valueForKey:@"OVERLAPS"] intValue];
        int indentation = [[eventInfo valueForKey:@"INDENTATION"] intValue];

        [self showHourlyEventView:e overlaps:overlaps index:indentation];
    }

    [self scrollToCurrentHour];
}

- (void)showHourlyEventView:(NPEvent*)event overlaps:(int)overlaps index:(int)index {
    float yOffset = ([DateUtil minutesSinceMidnight:event.startTime]) * (HOUR_GRID_HEIGHT/60.0);

    float height = 20.0;

    if (!event.singleTimeEvent) {
        // Find out the height of the event
        int minutes = ([event.endTime timeIntervalSince1970] - [event.startTime timeIntervalSince1970])/60;
        height = (minutes/15) * HOUR_GRID_HEIGHT/4.0f;
    }

    // Find out the width of the event
    float fullWidth = [self eventFullWidth];

    float width = fullWidth/overlaps;

    float xOffset = EVENT_INDENTATION + (fullWidth/overlaps)*index;

    CGRect eventRect = CGRectMake(xOffset, yOffset, width, height);
    [self.hourGridTableView addSubview:[self getEventViewBlock:eventRect event:event]];
}

- (void)scrollToCurrentHour {
    NSInteger hour = [DateUtil getHour:[NSDate date]];
    NSIndexPath *scrollIndexPath = [NSIndexPath indexPathForRow:hour*2 inSection:0];
    [self.hourGridTableView scrollToRowAtIndexPath:scrollIndexPath atScrollPosition:UITableViewScrollPositionMiddle animated:NO];

    [self showCurrentTime];
}

- (void)showCurrentTime
{
    NSDate *currentDate = [NSDate date];
    NSInteger minutes = [DateUtil minutesSinceMidnight:currentDate];
    float yOffset = minutes * HOUR_GRID_HEIGHT / 60;

    CGRect lineRect = CGRectMake(10.0, yOffset, [ViewDisplayHelper screenWidth], 1.0);

    if (self.nowLine == nil) {
        self.nowLine = [[UIView alloc] initWithFrame:lineRect];
        self.nowLine.backgroundColor = [UIColor redColor];
        self.nowLine.layer.opacity = 0.6;
        [self.hourGridTableView addSubview:self.nowLine];

    } else {
        // It's already drawn, just re-position it.
        [self.hourGridTableView addSubview:self.nowLine];
        self.nowLine.frame = lineRect;
    }
}

# pragma mark - clear the views.

- (void)clearEventViews {
    NSInteger cnt = [self.allEventViews count];

    for (int i=0; i<cnt; i++) {
        EventHourGridView *eventView = [self.allEventViews objectAtIndex:i];
        while (eventView.gestureRecognizers.count) {
            [eventView removeGestureRecognizer:[eventView.gestureRecognizers objectAtIndex:0]];
        }

        [UIView animateWithDuration:0.4
                         animations:^{ eventView.alpha = 0.0; }
                         completion:^(BOOL finished) { [eventView removeFromSuperview]; }];
    }

    [self.allEventViews removeAllObjects];

    [self.nowLine removeFromSuperview];
}

- (EventHourGridView*)getEventViewBlock:(CGRect)eventRect event:(NPEvent*)event {
    EventHourGridView *eventView = [[EventHourGridView alloc] initWithFrameAndEvent:eventRect event:event];

    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(openEventDetail:)];
    singleTap.delegate = self;
    [eventView addGestureRecognizer:singleTap];

    if (self.allEventViews == nil) {
        self.allEventViews = [[NSMutableArray alloc] init];
    }
    [self.allEventViews addObject:eventView];

    return eventView;
}

- (int)eventFullWidth {
    return [ViewDisplayHelper screenWidth] - EVENT_INDENTATION - 10;
}

- (void)openEventDetail:(id)sender {
    if ([sender isKindOfClass:[UITapGestureRecognizer class]]) {
        EventHourGridView *eventView = (EventHourGridView*)((UITapGestureRecognizer*)sender).view;
        [self.eventViewDelegate openEventDetail:eventView.event];

        NSIndexPath *tableSelection = [self.dayEventsView indexPathForSelectedRow];
        [self.dayEventsView deselectRowAtIndexPath:tableSelection animated:NO];

    } else if ([sender isKindOfClass:[NPEvent class]]) {
        [self.eventViewDelegate openEventDetail:(NPEvent*)sender];
    }
}

@end