text:
import React, {Component, PropTypes} from 'react';
import ReactDOM from 'react-dom';
import keycode from 'keycode';
import TextField from '../TextField';
import Menu from '../Menu';
import MenuItem from '../MenuItem';
import Divider from '../Divider';
import Popover from '../Popover/Popover';
import propTypes from '../utils/propTypes';

function getStyles(props, context, state) {
  const {anchorEl} = state;
  const {fullWidth} = props;

  const styles = {
    root: {
      display: 'inline-block',
      position: 'relative',
      width: fullWidth ? '100%' : 256,
    },
    menu: {
      width: '100%',
    },
    list: {
      display: 'block',
      width: fullWidth ? '100%' : 256,
    },
    innerDiv: {
      overflow: 'hidden',
    },
  };

  if (anchorEl && fullWidth) {
    styles.popover = {
      width: anchorEl.clientWidth,
    };
  }

  return styles;
}

class AutoComplete extends Component {
  static propTypes = {
    /**
     * Location of the anchor for the auto complete.
     */
    anchorOrigin: propTypes.origin,
    /**
     * If true, the auto complete is animated as it is toggled.
     */
    animated: PropTypes.bool,
    /**
     * Override the default animation component used.
     */
    animation: PropTypes.func,
    /**
     * Array of strings or nodes used to populate the list.
     */
    dataSource: PropTypes.array.isRequired,
    /**
     * Config for objects list dataSource.
     *
     * @typedef {Object} dataSourceConfig
     *
     * @property {string} text `dataSource` element key used to find a string to be matched for search
     * and shown as a `TextField` input value after choosing the result.
     * @property {string} value `dataSource` element key used to find a string to be shown in search results.
     */
    dataSourceConfig: PropTypes.object,
    /**
     * Disables focus ripple when true.
     */
    disableFocusRipple: PropTypes.bool,
    /**
     * Override style prop for error.
     */
    errorStyle: PropTypes.object,
    /**
     * The error content to display.
     */
    errorText: PropTypes.node,
    /**
     * Callback function used to filter the auto complete.
     *
     * @param {string} searchText The text to search for within `dataSource`.
     * @param {string} key `dataSource` element, or `text` property on that element if it's not a string.
     * @returns {boolean} `true` indicates the auto complete list will include `key` when the input is `searchText`.
     */
    filter: PropTypes.func,
    /**
     * The content to use for adding floating label element.
     */
    floatingLabelText: PropTypes.node,
    /**
     * If true, the field receives the property `width: 100%`.
     */
    fullWidth: PropTypes.bool,
    /**
     * The hint content to display.
     */
    hintText: PropTypes.node,
    /**
     * Override style for list.
     */
    listStyle: PropTypes.object,
    /**
     * The max number of search results to be shown.
     * By default it shows all the items which matches filter.
     */
    maxSearchResults: PropTypes.number,
    /**
     * Delay for closing time of the menu.
     */
    menuCloseDelay: PropTypes.number,
    /**
     * Props to be passed to menu.
     */
    menuProps: PropTypes.object,
    /**
     * Override style for menu.
     */
    menuStyle: PropTypes.object,
    /** @ignore */
    onBlur: PropTypes.func,
    /** @ignore */
    onFocus: PropTypes.func,
    /** @ignore */
    onKeyDown: PropTypes.func,
    /**
     * Callback function that is fired when a list item is selected, or enter is pressed in the `TextField`.
     *
     * @param {string} chosenRequest Either the `TextField` input value, if enter is pressed in the `TextField`,
     * or the text value of the corresponding list item that was selected.
     * @param {number} index The index in `dataSource` of the list item selected, or `-1` if enter is pressed in the
     * `TextField`.
     */
    onNewRequest: PropTypes.func,
    /**
     * Callback function that is fired when the user updates the `TextField`.
     *
     * @param {string} searchText The auto-complete's `searchText` value.
     * @param {array} dataSource The auto-complete's `dataSource` array.
     */
    onUpdateInput: PropTypes.func,
    /**
     * Auto complete menu is open if true.
     */
    open: PropTypes.bool,
    /**
     * If true, the list item is showed when a focus event triggers.
     */
    openOnFocus: PropTypes.bool,
    /**
     * Props to be passed to popover.
     */
    popoverProps: PropTypes.object,
    /**
     * Text being input to auto complete.
     */
    searchText: PropTypes.string,
    /**
     * Override the inline-styles of the root element.
     */
    style: PropTypes.object,
    /**
     * Origin for location of target.
     */
    targetOrigin: propTypes.origin,
    /**
     * Override the inline-styles of AutoComplete's TextField element.
     */
    textFieldStyle: PropTypes.object,
  };

  static defaultProps = {
    anchorOrigin: {
      vertical: 'bottom',
      horizontal: 'left',
    },
    animated: true,
    dataSourceConfig: {
      text: 'text',
      value: 'value',
    },
    disableFocusRipple: true,
    filter: (searchText, key) => searchText !== '' && key.indexOf(searchText) !== -1,
    fullWidth: false,
    open: false,
    openOnFocus: false,
    onUpdateInput: () => {},
    onNewRequest: () => {},
    searchText: '',
    menuCloseDelay: 300,
    targetOrigin: {
      vertical: 'top',
      horizontal: 'left',
    },
  };

  static contextTypes = {
    muiTheme: PropTypes.object.isRequired,
  };

  state = {
    anchorEl: null,
    focusTextField: true,
    open: false,
    searchText: undefined,
  };

  componentWillMount() {
    this.requestsList = [];
    this.setState({
      open: this.props.open,
      searchText: this.props.searchText,
    });
    this.timerTouchTapCloseId = null;
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.searchText !== nextProps.searchText) {
      this.setState({
        searchText: nextProps.searchText,
      });
    }
  }

  componentWillUnmount() {
    clearTimeout(this.timerTouchTapCloseId);
  }

  close() {
    this.setState({
      open: false,
      anchorEl: null,
    });
  }

  handleRequestClose = () => {
    // Only take into account the Popover clickAway when we are
    // not focusing the TextField.
    if (!this.state.focusTextField) {
      this.close();
    }
  };

  handleMouseDown = (event) => {
    // Keep the TextField focused
    event.preventDefault();
  };

  handleItemTouchTap = (event, child) => {
    const dataSource = this.props.dataSource;

    const index = parseInt(child.key, 10);
    const chosenRequest = dataSource[index];
    const searchText = this.chosenRequestText(chosenRequest);

    this.timerTouchTapCloseId = setTimeout(() => {
      this.timerTouchTapCloseId = null;

      this.setState({
        searchText: searchText,
      });
      this.close();

      this.props.onUpdateInput(searchText, dataSource);
      this.props.onNewRequest(chosenRequest, index);
    }, this.props.menuCloseDelay);
  };

  chosenRequestText = (chosenRequest) => {
    if (typeof chosenRequest === 'string') {
      return chosenRequest;
    } else {
      return chosenRequest[this.props.dataSourceConfig.text];
    }
  };

  handleEscKeyDown = () => {
    this.close();
  };

  handleKeyDown = (event) => {
    if (this.props.onKeyDown) this.props.onKeyDown(event);

    switch (keycode(event)) {
      case 'enter':
        this.close();
        const searchText = this.state.searchText;
        if (searchText !== '') {
          this.props.onNewRequest(searchText, -1);
        }
        break;

      case 'esc':
        this.close();
        break;

      case 'down':
        event.preventDefault();
        this.setState({
          open: true,
          focusTextField: false,
          anchorEl: ReactDOM.findDOMNode(this.refs.searchTextField),
        });
        break;

      default:
        break;
    }
  };

  handleChange = (event) => {
    const searchText = event.target.value;

    // Make sure that we have a new searchText.
    // Fix an issue with a Cordova Webview
    if (searchText === this.state.searchText) {
      return;
    }

    this.setState({
      searchText: searchText,
      open: true,
      anchorEl: ReactDOM.findDOMNode(this.refs.searchTextField),
    }, () => {
      this.props.onUpdateInput(searchText, this.props.dataSource);
    });
  };

  handleBlur = (event) => {
    if (this.state.focusTextField && this.timerTouchTapCloseId === null) {
      this.close();
    }

    if (this.props.onBlur) {
      this.props.onBlur(event);
    }
  };

  handleFocus = (event) => {
    if (!this.state.open && this.props.openOnFocus) {
      this.setState({
        open: true,
        anchorEl: ReactDOM.findDOMNode(this.refs.searchTextField),
      });
    }

    this.setState({
      focusTextField: true,
    });

    if (this.props.onFocus) {
      this.props.onFocus(event);
    }
  };

  blur() {
    this.refs.searchTextField.blur();
  }

  focus() {
    this.refs.searchTextField.focus();
  }

  render() {
    const {
      anchorOrigin,
      animated,
      animation,
      dataSource,
      dataSourceConfig, // eslint-disable-line no-unused-vars
      disableFocusRipple,
      errorStyle,
      floatingLabelText,
      filter,
      fullWidth,
      style,
      hintText,
      maxSearchResults,
      menuCloseDelay, // eslint-disable-line no-unused-vars
      textFieldStyle,
      menuStyle,
      menuProps,
      listStyle,
      targetOrigin,
      onNewRequest, // eslint-disable-line no-unused-vars
      onUpdateInput, // eslint-disable-line no-unused-vars
      openOnFocus, // eslint-disable-line no-unused-vars
      popoverProps,
      searchText: searchTextProp, // eslint-disable-line no-unused-vars
      ...other
    } = this.props;

    const {
      open,
      anchorEl,
      searchText,
      focusTextField,
    } = this.state;

    const {prepareStyles} = this.context.muiTheme;
    const styles = getStyles(this.props, this.context, this.state);

    const requestsList = [];

    dataSource.every((item, index) => {
      switch (typeof item) {
        case 'string':
          if (filter(searchText, item, item)) {
            requestsList.push({
              text: item,
              value: (
                <MenuItem
                  innerDivStyle={styles.innerDiv}
                  value={item}
                  primaryText={item}
                  disableFocusRipple={disableFocusRipple}
                  key={index}
                />),
            });
          }
          break;

        case 'object':
          if (item && typeof item[this.props.dataSourceConfig.text] === 'string') {
            const itemText = item[this.props.dataSourceConfig.text];
            if (!this.props.filter(searchText, itemText, item)) break;

            const itemValue = item[this.props.dataSourceConfig.value];
            if (itemValue.type && (itemValue.type.muiName === MenuItem.muiName ||
               itemValue.type.muiName === Divider.muiName)) {
              requestsList.push({
                text: itemText,
                value: React.cloneElement(itemValue, {
                  key: index,
                  disableFocusRipple: disableFocusRipple,
                }),
              });
            } else {
              requestsList.push({
                text: itemText,
                value: (
                  <MenuItem
                    innerDivStyle={styles.innerDiv}
                    primaryText={itemText}
                    disableFocusRipple={disableFocusRipple}
                    key={index}
                  />),
              });
            }
          }
          break;

        default:
          // Do nothing
      }

      return !(maxSearchResults && maxSearchResults > 0 && requestsList.length === maxSearchResults);
    });

    this.requestsList = requestsList;

    const menu = open && requestsList.length > 0 && (
      <Menu
        {...menuProps}
        ref="menu"
        autoWidth={false}
        disableAutoFocus={focusTextField}
        onEscKeyDown={this.handleEscKeyDown}
        initiallyKeyboardFocused={true}
        onItemTouchTap={this.handleItemTouchTap}
        onMouseDown={this.handleMouseDown}
        style={Object.assign(styles.menu, menuStyle)}
        listStyle={Object.assign(styles.list, listStyle)}
      >
        {requestsList.map((i) => i.value)}
      </Menu>
    );

    return (
      <div style={prepareStyles(Object.assign(styles.root, style))} >
        <TextField
          {...other}
          ref="searchTextField"
          autoComplete="off"
          value={searchText}
          onChange={this.handleChange}
          onBlur={this.handleBlur}
          onFocus={this.handleFocus}
          onKeyDown={this.handleKeyDown}
          floatingLabelText={floatingLabelText}
          hintText={hintText}
          fullWidth={fullWidth}
          multiLine={false}
          errorStyle={errorStyle}
          style={textFieldStyle}
        />
        <Popover
          {...popoverProps}
          style={styles.popover}
          canAutoPosition={false}
          anchorOrigin={anchorOrigin}
          targetOrigin={targetOrigin}
          open={open}
          anchorEl={anchorEl}
          useLayerForClickAway={false}
          onRequestClose={this.handleRequestClose}
          animated={animated}
          animation={animation}
        >
          {menu}
        </Popover>
      </div>
    );
  }
}

AutoComplete.levenshteinDistance = (searchText, key) => {
  const current = [];
  let prev;
  let value;

  for (let i = 0; i <= key.length; i++) {
    for (let j = 0; j <= searchText.length; j++) {
      if (i && j) {
        if (searchText.charAt(j - 1) === key.charAt(i - 1)) value = prev;
        else value = Math.min(current[j], current[j - 1], prev) + 1;
      } else {
        value = i + j;
      }
      prev = current[j];
      current[j] = value;
    }
  }
  return current.pop();
};

AutoComplete.noFilter = () => true;

AutoComplete.defaultFilter = AutoComplete.caseSensitiveFilter = (searchText, key) => {
  return searchText !== '' && key.indexOf(searchText) !== -1;
};

AutoComplete.caseInsensitiveFilter = (searchText, key) => {
  return key.toLowerCase().indexOf(searchText.toLowerCase()) !== -1;
};

AutoComplete.levenshteinDistanceFilter = (distanceLessThan) => {
  if (distanceLessThan === undefined) {
    return AutoComplete.levenshteinDistance;
  } else if (typeof distanceLessThan !== 'number') {
    throw 'Error: AutoComplete.levenshteinDistanceFilter is a filter generator, not a filter!';
  }

  return (s, k) => AutoComplete.levenshteinDistance(s, k) < distanceLessThan;
};

AutoComplete.fuzzyFilter = (searchText, key) => {
  const compareString = key.toLowerCase();
  searchText = searchText.toLowerCase();

  let searchTextIndex = 0;
  for (let index = 0; index < key.length; index++) {
    if (compareString[index] === searchText[searchTextIndex]) {
      searchTextIndex += 1;
    }
  }

  return searchTextIndex === searchText.length;
};

AutoComplete.Item = MenuItem;
AutoComplete.Divider = Divider;

export default AutoComplete;


text:
		Contains the Calimero tools, each providing a different functionality for a user.

		A tool shows a particular feature of the Calimero library, and aims to help
		in getting familiar with the library and interact with the necessary structures.
		Nevertheless, while hopefully allowing some insight in the APIs,
		every tool tries to offer a ready-to-use functionality on its own.

		In general, the tool implementations are console based, i.e. they are
		intended to run on a console or command line window.

		Every tool keeps all its required code in the same file to
		avoid additional file dependencies, which should help when examining the code of
		a tool in the first place. On the other hand, local copies of some
		utility functionality might therefore appear in different tool files.
		To check out the implementation and control flow of a tool, a good point
		to start is the main-method of the particular type.

		Access to the KNX network can be done with KNXnet/IP, using an
		IP network connection, or with FT1.2, using a serial port connection.

		KNXnet/IP address considerations:

		On more than one IP address assigned to the local host, and possibly
		several local network interfaces available, the default chosen local host
		might not be the one expected by the user. In this situation, the local IP
		address has to be supplied manually, using command line options.

		The KNXnet/IP protocol expects IPv4 addresses by default.

		Network Address Translation (NAT) aware communication can only be used,
		if the remote KNXnet/IP server supports it.
		Otherwise, connection timeouts will occur. With NAT enabled,
		KNXnet/IP also works with IPv6 addresses.

redpajama_set_name: RedPajamaGithub


text:
package org.innovateuk.ifs.invite.formatter;

import org.innovateuk.ifs.invite.resource.RejectionReasonResource;
import org.springframework.format.Formatter;

import java.text.ParseException;
import java.util.Locale;

/**
 * Formats {@link RejectionReasonResource} objects for display.
 */
public class RejectionReasonFormatter implements Formatter<RejectionReasonResource> {

    @Override
    public RejectionReasonResource parse(String text, Locale locale) throws ParseException {
        RejectionReasonResource rejectionReasonResource = new RejectionReasonResource();
        rejectionReasonResource.setId(Long.valueOf(text));
        return rejectionReasonResource;
    }

    @Override
    public String print(RejectionReasonResource object, Locale locale) {
        return object != null ? object.getId().toString() : "";
    }
}


text:
#include "use.h"
#include "config.h"

#include <stdbool.h>       // bool
#include <stdio.h>         // perror
#include <stdlib.h>        // malloc, free
#include <string.h>        // memset
#include <errno.h>         // perror
#include <unistd.h>        // close
#include <sys/epoll.h>     // epoll_ctl
#include <sys/signalfd.h>  // eventfd
#include <signal.h>        // SIGINT, SIGQUIT
#include <netinet/in.h>    // IPPROTO_ICMP, IPPROTO_ICMPV6

#include "pt_loop.h"

#include "algorithm.h"

#define MAXEVENTS 100

/**
 * \brief (Internal usage) Release from the memory loop->user_events;
 * \param loop The main loop
 */

static inline void pt_loop_clear_user_events(pt_loop_t * loop) {
    dynarray_clear(loop->events_user, NULL); //(ELEMENT_FREE) event_free); TODO this provoke a segfault in case of stars
}

/**
 * \brief Register a file descriptor in Paris Traceroute loop
 * \param loop The main loop
 * \param fd A file descriptor
 * \return true iif successfull
 */

static bool register_efd(pt_loop_t * loop, int fd) {
    struct epoll_event event;

    // Check whether the fd is fine or not
    if (fd == -1) goto ERR_FD;

    // Prepare epoll event structure
    memset(&event, 0, sizeof(struct epoll_event));
    event.data.fd = fd;
    event.events = EPOLLIN; // | EPOLLET;

    // Register fd in pt_loop
    if (epoll_ctl(loop->efd, EPOLL_CTL_ADD, fd, &event) == -1) {
        perror("Error epoll_ctl");
        goto ERR_EPOLL_CTL;
    }
    return true;

ERR_EPOLL_CTL:
ERR_FD:
    return false;
}

/**
 * \brief Prepare a EFD_SEMAPHORE event_fd
 * \return The correspnding file descriptor, -1 in case of failure
 */

static inline int make_event_fd() {
    int fd;

    if ((fd = eventfd(0, EFD_SEMAPHORE)) == -1) {
        perror("Error eventfd");
    }
    return fd;
}

/**
 * \brief Prepare a signal file descriptor used to handle SIGINT and SIGQUIT signals
 * \return The correspnding file descriptor, -1 in case of failure
 */

static int make_signal_fd() {
    int       sfd;
    sigset_t  mask;

    // Signal processing
    // Block signals so that they are not managed by their handlers anymore
    sigemptyset(&mask);
    sigaddset(&mask, SIGINT);
    sigaddset(&mask, SIGQUIT);

    if (sigprocmask(SIG_BLOCK, &mask, NULL) == -1) {
        goto ERR_SIGPROCMASK;
    }

    if ((sfd = signalfd(-1, &mask, 0)) == -1) {
        perror("Error signalfd");
        goto ERR_SIGNALFD;
    }

    return sfd;

ERR_SIGPROCMASK:
ERR_SIGNALFD:
    return -1;
}

/**
 * \brief Create an ALGORITHM* event carrying a nested user event.
 * \param loop The main loop
 * \param type Type of event
 */

static bool pt_raise_impl(pt_loop_t * loop, event_type_t type, event_t * nested_event) {
    // Allocate the event
    event_t * event = event_create(
        type,
        nested_event,
        loop->cur_instance,
        nested_event ? (ELEMENT_FREE) event_free : NULL
    );
    if (!event) return false;

    // Raise the event
    pt_algorithm_throw(loop, loop->cur_instance->caller, event);
    return true;
}

pt_loop_t * pt_loop_create(void (*handler_user)(pt_loop_t *, event_t *, void *), void * user_data)
{
    pt_loop_t          * loop;

    if (!(loop = malloc(sizeof(pt_loop_t)))) goto ERR_MALLOC;
    loop->handler_user = handler_user;

    // Prepare epoll file descriptor
    if ((loop->efd = epoll_create1(0)) == -1) {
        perror("Error epoll_create1");
        goto ERR_EPOLL;
    }

    // Prepare algorithm events fd and register it in loop->efd
    if ((loop->eventfd_algorithm = make_event_fd()) == -1) goto ERR_MAKE_EVENTFD_ALGORITHM;
    if (!register_efd(loop, loop->eventfd_algorithm))      goto ERR_EVENTFD_ALGORITHM;

    // Prepare user events fd and register it in loop->efd
    if ((loop->eventfd_user = make_event_fd()) == -1)      goto ERR_MAKE_EVENTFD_USER;
    if (!register_efd(loop, loop->eventfd_user))           goto ERR_EVENTFD_USER;

    // Signal processing
    if ((loop->sfd = make_signal_fd()) == -1)              goto ERR_MAKE_SIGNALFD;
    if (!register_efd(loop, loop->sfd))                    goto ERR_SIGNALFD;

    // Prepare network layer and register it in pt_loop
    if (!(loop->network = network_create()))                           goto ERR_NETWORK_CREATE;
    if (!register_efd(loop, network_get_sendq_fd(loop->network)))      goto ERR_EVENTFD_SENDQ;
    if (!register_efd(loop, network_get_recvq_fd(loop->network)))      goto ERR_EVENTFD_RECVQ;
#ifdef USE_IPV4
    if (!register_efd(loop, network_get_icmpv4_sockfd(loop->network))) goto ERR_EVENTFD_SNIFFER_ICMPV4;
#endif
#ifdef USE_IPV6
    if (!register_efd(loop, network_get_icmpv6_sockfd(loop->network))) goto ERR_EVENTFD_SNIFFER_ICMPV6;
#endif
    if (!register_efd(loop, network_get_timerfd(loop->network)))       goto ERR_EVENTFD_TIMEOUT;
    if (!register_efd(loop, network_get_group_timerfd(loop->network))) goto ERR_EVENTFD_GROUP;

    // Buffer where pending events are stored
    if (!(loop->epoll_events = calloc(MAXEVENTS, sizeof(struct epoll_event)))) {
        goto ERR_EVENTS;
    }

    if (!(loop->events_user = dynarray_create())) {
        goto ERR_EVENTS_USER;
    }

    loop->user_data = user_data;
    loop->stop = PT_LOOP_CONTINUE;
    loop->next_algorithm_id = 1; // 0 means unaffected ?
    loop->cur_instance = NULL;
    loop->algorithm_instances_root = NULL;

    return loop;

ERR_EVENTS_USER:
    free(loop->epoll_events);
ERR_EVENTS:
ERR_EVENTFD_GROUP:
ERR_EVENTFD_TIMEOUT:
ERR_EVENTFD_SNIFFER_ICMPV6:
ERR_EVENTFD_SNIFFER_ICMPV4:
ERR_EVENTFD_RECVQ:
ERR_EVENTFD_SENDQ:
    network_free(loop->network);
ERR_NETWORK_CREATE:
ERR_SIGNALFD:
    close(loop->sfd);
ERR_MAKE_SIGNALFD:
    close(loop->eventfd_user);
ERR_EVENTFD_USER:
    close(loop->eventfd_algorithm);
ERR_MAKE_EVENTFD_USER:
ERR_EVENTFD_ALGORITHM:
    close(loop->efd);
ERR_MAKE_EVENTFD_ALGORITHM:
ERR_EPOLL:
    free(loop);
ERR_MALLOC:
    return NULL;
}

void pt_loop_free(pt_loop_t * loop)
{
    if (loop) {
        if (loop->events_user)  dynarray_free(loop->events_user, (ELEMENT_FREE) event_free);
        if (loop->epoll_events) free(loop->epoll_events);
        network_free(loop->network);
        close(loop->sfd);
        close(loop->eventfd_user);
        close(loop->eventfd_algorithm);
        close(loop->efd);

        // Events are cleared while destroying algorithm instances
        pt_algorithm_instance_iter(loop, pt_free_algorithms_instance);
        free(loop);
    }
}

// Accessors

inline event_t ** pt_loop_get_user_events(pt_loop_t * loop) {
    return loop ?
        (event_t **) dynarray_get_elements(loop->events_user) :
        NULL;
}

inline size_t pt_loop_get_num_user_events(pt_loop_t * loop) {
    return loop->events_user->size;
}

/**
 * \brief Process every pending user events (e.g. pt_loop_get_num_user_events(loop) events)
 * \param loop The main loop
 * \return true iif successfull
 */

static int pt_loop_process_user_events(pt_loop_t * loop) {
    event_t      ** events        = pt_loop_get_user_events(loop);
    size_t          i, num_events = pt_loop_get_num_user_events(loop);
    uint64_t        ret;

    for (i = 0; i < num_events; i++) {
        if (read(loop->eventfd_user, &ret, sizeof(ret)) == -1) {
            return -1;
        }
        // TODO decrement the associated eventfd counter

        // Call user-defined handler and pass the current user event
        loop->handler_user(loop, events[i], loop->user_data);
    }
    return 1;
}

int pt_loop(pt_loop_t *loop, unsigned int timeout)
{
    int n, i, cur_fd;

    // TODO set a flag to avoid issues due to several threads
    // and put a critical section to manage this flag

    int network_sendq_fd      = network_get_sendq_fd(loop->network);
    int network_recvq_fd      = network_get_recvq_fd(loop->network);
#ifdef USE_IPV4
    int network_icmpv4_sockfd = network_get_icmpv4_sockfd(loop->network);
#endif
#ifdef USE_IPV6
    int network_icmpv6_sockfd = network_get_icmpv6_sockfd(loop->network);
#endif
    int network_timerfd       = network_get_timerfd(loop->network);
    int network_group_timerfd = network_get_group_timerfd(loop->network);
    ssize_t s;
    struct signalfd_siginfo fdsi;

    do {
        /* Wait for events */
        n = epoll_wait(loop->efd, loop->epoll_events, MAXEVENTS, -1);

        /* XXX What kind of events do we have
         * - sockets (packets received, timeouts, etc.)
         * - internal queues where probes and packets are stored
         * - ...
         */
        // Dispatch events
        for (i = 0; i < n; i++) {
            // cur_fd has been activated, so we have to manage
            // the corresponding event.
            cur_fd = loop->epoll_events[i].data.fd;

            // Handle errors on fds
            if ((loop->epoll_events[i].events & EPOLLERR)
            ||  (loop->epoll_events[i].events & EPOLLHUP)
            || !(loop->epoll_events[i].events & EPOLLIN)
            ) {
                // An error has occured on this fd
                perror("epoll error");
                close(cur_fd);
                continue;
            }

            if (cur_fd == network_sendq_fd) {
                if (!network_process_sendq(loop->network)) {
                    if (loop->network->is_verbose) fprintf(stderr, "pt_loop: Can't send packet\n");
                }
            } else if (cur_fd == network_recvq_fd) {
                if (!network_process_recvq(loop->network)) {
                    if (loop->network->is_verbose) fprintf(stderr, "pt_loop: Cannot fetch packet\n");
                }
            } else if (cur_fd == network_group_timerfd) {
                 //printf("pt_loop processing scheduled probes\n");
                network_process_scheduled_probe(loop->network);
#ifdef USE_IPV4
            } else if (cur_fd == network_icmpv4_sockfd) {
                network_process_sniffer(loop->network, IPPROTO_ICMP);
#endif
#ifdef USE_IPV6
            } else if (cur_fd == network_icmpv6_sockfd) {
                network_process_sniffer(loop->network, IPPROTO_ICMPV6);
#endif
            } else if (cur_fd == loop->eventfd_algorithm) {

                // There is one common queue shared by every instancied algorithms.
                // We call pt_process_algorithms_iter() to find for which instance
                // the event has been raised. Then we process this event thanks
                // to pt_process_algorithms_instance() that calls the handler.
                pt_algorithm_instance_iter(loop, pt_process_algorithms_instance);

            } else if (cur_fd == loop->eventfd_user) {

                // Throw this event to the user-defined handler
                pt_loop_process_user_events(loop);

                // Flush the queue
                pt_loop_clear_user_events(loop);
            } else if (cur_fd == loop->sfd) {
                // Handling signals
                //
                s = read(loop->sfd, &fdsi, sizeof(struct signalfd_siginfo));
                if (s != sizeof(struct signalfd_siginfo)) {
                    perror("read");
                    continue;
                }

                if (fdsi.ssi_signo == SIGINT) {
                    loop->stop = PT_LOOP_TERMINATE;
                } else if (fdsi.ssi_signo == SIGQUIT) {
                    exit(EXIT_SUCCESS);
                } else {
                    perror("Read unexpected signal\n");
                }
            } else if (cur_fd == network_timerfd) {

                // Timer managing timeout in network layer has expired
                // At least one probe has expired
                if (!network_drop_expired_flying_probe(loop->network)) {
                    fprintf(stderr, "Error while processing timeout");
                }
            }
        }
    } while (loop->stop == PT_LOOP_CONTINUE);

    // Process internal events
    return loop->stop == PT_LOOP_TERMINATE ? 0 : -1;
}

bool pt_send_probe(pt_loop_t * loop, probe_t * probe)
{
    // Annotate which algorithm has generated this probe
    probe_set_caller(probe, loop->cur_instance);

    // Tagging is achieved by network layer
    return network_send_probe(loop->network, probe);
}

void pt_loop_terminate(pt_loop_t * loop) {
    loop->stop = PT_LOOP_TERMINATE;
}

bool pt_raise_event(pt_loop_t * loop, event_t * event) {
    return pt_raise_impl(loop, ALGORITHM_EVENT, event);
}

bool pt_raise_error(pt_loop_t * loop) {
    return pt_raise_impl(loop, ALGORITHM_ERROR, NULL);
}

bool pt_raise_terminated(pt_loop_t * loop) {
    return pt_raise_impl(loop, ALGORITHM_TERMINATED, NULL);
}


text:
import { Component, ViewEncapsulation } from '@angular/core';

@Component({
  // eslint-disable-next-line @angular-eslint/component-selector
  selector: 'demo-alert-styling-global',
  templateUrl: './styling-global.html',
  encapsulation: ViewEncapsulation.None
})
export class DemoAlertStylingGlobalComponent {}


text:
import { expect } from 'chai';
import { describe, it } from 'mocha';
import { setupModelTest } from 'ember-mocha';

describe('Unit | Model | summarized statistic', function() {
  setupModelTest('summarized-statistic', { integration: true });

  // Replace this with your real tests.
  it('exists', function() {
    let model = this.subject();
    // var store = this.store();
    expect(model).to.be.ok;
  });
});


text:
/*
 * Hardware crypto support Copyright 2017-2019 Espressif Systems (Shanghai) PTE LTD
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "utils/includes.h"

#include "utils/common.h"
#ifdef USE_MBEDTLS_CRYPTO
#include "mbedtls/bignum.h"
#else /* USE_MBEDTLS_CRYPTO */
#include "bignum.h"
#endif /* USE_MBEDTLS_CRYPTO */
#include "crypto.h"

#ifdef USE_MBEDTLS_CRYPTO
int
crypto_mod_exp(const uint8_t *base, size_t base_len,
	       const uint8_t *power, size_t power_len,
	       const uint8_t *modulus, size_t modulus_len,
	       uint8_t *result, size_t *result_len)
{
	mbedtls_mpi bn_base, bn_exp, bn_modulus, bn_result, bn_rinv;
	int ret = 0;
	mbedtls_mpi_init(&bn_base);
	mbedtls_mpi_init(&bn_exp);
	mbedtls_mpi_init(&bn_modulus);
	mbedtls_mpi_init(&bn_result);
	mbedtls_mpi_init(&bn_rinv);

	mbedtls_mpi_read_binary(&bn_base, base, base_len);
	mbedtls_mpi_read_binary(&bn_exp, power, power_len);
	mbedtls_mpi_read_binary(&bn_modulus, modulus, modulus_len);

	ret = mbedtls_mpi_exp_mod(&bn_result, &bn_base, &bn_exp, &bn_modulus, &bn_rinv);
	if (ret < 0) {
		mbedtls_mpi_free(&bn_base);
		mbedtls_mpi_free(&bn_exp);
		mbedtls_mpi_free(&bn_modulus);
		mbedtls_mpi_free(&bn_result);
		mbedtls_mpi_free(&bn_rinv);
		return ret;
	}

	ret = mbedtls_mpi_write_binary(&bn_result, result, *result_len);

	mbedtls_mpi_free(&bn_base);
	mbedtls_mpi_free(&bn_exp);
	mbedtls_mpi_free(&bn_modulus);
	mbedtls_mpi_free(&bn_result);
	mbedtls_mpi_free(&bn_rinv);

	return ret;
}
#else /* USE_MBEDTLS_CRYPTO */
int
crypto_mod_exp(const u8 *base, size_t base_len,
		   const u8 *power, size_t power_len,
		   const u8 *modulus, size_t modulus_len,
		   u8 *result, size_t *result_len)
{
	struct bignum *bn_base, *bn_exp, *bn_modulus, *bn_result;
	int ret = -1;

	bn_base = bignum_init();
	bn_exp = bignum_init();
	bn_modulus = bignum_init();
	bn_result = bignum_init();

	if (bn_base == NULL || bn_exp == NULL || bn_modulus == NULL ||
	    bn_result == NULL)
		goto error;

	if (bignum_set_unsigned_bin(bn_base, base, base_len) < 0 ||
	    bignum_set_unsigned_bin(bn_exp, power, power_len) < 0 ||
	    bignum_set_unsigned_bin(bn_modulus, modulus, modulus_len) < 0)
		goto error;

	if (bignum_exptmod(bn_base, bn_exp, bn_modulus, bn_result) < 0)
		goto error;

	ret = bignum_get_unsigned_bin(bn_result, result, result_len);

error:
	bignum_deinit(bn_base);
	bignum_deinit(bn_exp);
	bignum_deinit(bn_modulus);
	bignum_deinit(bn_result);
	return ret;
}
#endif /* USE_MBEDTLS_CRYPTO */


text:
class Node():
	"""docstring for Node"""
	def __init__(self, value):
		self._value = value
		self._children = []

	def __repr__(self):
		return 'Node ({!r})'.format(self._value)

	def add_child(self, node):
		self._children.append(node)

	def __iter__(self):
		return iter(self._children)

	def depth_first(self):
		yield self
		for c in self:
			yield from c.depth_first()

def countdown(n):
	print('Starting to count from', n)
	while n > 0:
		yield n
		n -= 1
	print('Done!')

class Countdown():
	"""docstring for Countdown"""
	def __init__(self, start):
		self.start = start

	def __iter__(self):
		n = self.start
		while n > 0:
			yield n
			n -= 1

	def __reversed__(self):
		n = 1
		while n <= self.start:
			yield n
			n += 1

if __name__ == '__main__':
	root = Node(0)
	child1 = Node(1)
	child2 = Node(2)
	root.add_child(child1)
	root.add_child(child2)
	child1.add_child(Node(3))
	child1.add_child(Node(4))
	child2.add_child(Node(5))
	for ch in root:
		print(ch)
	for ch in root.depth_first():
		print(ch)
	for i in countdown(10):
		print(i)
	count = Countdown(10)
	for i in reversed(count):
		print(i)


text:
SynChrono {#module_synchrono_overview}
==============

## Project Overview

SynChrono is an autonomous vehicle simulation project developed by the Simulation Based Engineering Lab ([SBEL](https://sbel.wisc.edu/)) at the University of Wisconsin-Madison.
This simulation framework is based around the ability to simulation one or multiple robots, autonomous vehicles, or other autonomous agents together in a unified framework.
Our current motivation comes from autonomous vehicle testing, so many of our demos and examples will draw on autonomous vehicles, but since the simulation is backed by Chrono, we can support any virtual environment.

Our goal is to extend Project Chrono's physics simulation into the multi-agent realm, specifically the multi-agent realm where the dynamics of the agents are not strongly coupled.
For a simulation of say two robots underwater, where the currents created by one robot will impact the dynamics of the other robot, you are better off in Chrono, where the robots and the fluid will be contained together in a single Chrono model and where the dynamics will be jointly simulated.
SynChrono is suited for scenarios where the dynamics of each agent are important individually, but not in the way that they interact with each other.
This is the case for autonomous vehicles where, barring a collision, the dynamics of one vehicle will not impact any other.
SynChrono synchronizes the motion of all agents, but allows their dynamics to be distributed across computing nodes rather than including all dynamics in one monolithic simulation.

_Images_: On the left a convoy of autonomous vehicles navigate obstacles on offroad terrain using a policy developed through machine learning. On the right an autonomous vehicle performs a lane change in a highway setting.

## Agent Synchronization {#syn_agent_sync}

The dynamics of a "typical" Chrono system (for example one using `Chrono::Vehicle`) are handled by stepping the simulation forward in time by some timestep `Δt`, where at each timestep, new states are computed for each entity in the `ChSystem`. This is still the case in SynChrono except that each simulation node handles its own `ChSystem`, and these separate systems must be periodically synchronized. The situation is illustrated in the figure below:

Each node steps forward in time, at the same constant timestep. Some nodes may move through their timesteps in less real-world time than the others, simply because they have more processing power, a simpler system, or for any other range of reasons. However after a certain number of timesteps have elapsed in simulation, called the heartbeat, all nodes will synchronize their current state. Between heartbeats, the zombie agents in a node's `ChSystem` are not updated, and will remain static until a heartbeat is reached and updated state information for them is applied to the `ChSystem`.

Next we explain what exactly is communicated at each heartbeat ([State Information](#State-Information)), how this data is formatted ([FlatBuffers](#FlatBuffers)) and how the data is communicated between nodes ([Communication Types](#Communication-Types)).

### State Information {#syn_state_info}

The state information that is communicated at each heartbeat is specific to each type of agent, it should be the minimum required to construct a zombie agent in the world of another node. For vehicle agents we need to know two things:
- What the zombie should look like
- Where the zombie should be placed

__What__ the zombie looks like is handled through specification of the number of wheels and of mesh files to be used for the chassis and wheels, this happens just once at the beginning of the simulation. __Where__ the zombie is placed gets communicated at every heartbeat, and consists of the position and orientation (pose) of the vehicle's center of mass along with a pose for each of its wheels.

### FlatBuffers {#syn_flatbuffers}

To communicate state information between nodes, we need to move data about each agent from C++ objects, to a series of bytes that travel over the wire between nodes. [FlatBuffers](https://google.github.io/flatbuffers/) is a library that handles exactly this serialization and deserialization of data.

Any agent that will be synchronized must have a flatbuffers schema (see example below) that defines how their state data is formatted, and a corresponding class that uses this schema to pack and unpack data into a C++ class.

````protobuf
// Sample flatbuffers schema (see Agent.fbs and Utils.fbs)

table Pose {
  pos:Vector;
  rot:Quaternion;

  // more details omitted...
}

table State {
  time:double;

  chassis:Pose;

  wheels:[Pose];
}
````

## Communication Types {#syn_communication}

After the nodes reach a heartbeat and use FlatBuffers to pack their data, a `SynCommunicator` takes charge of sending this binary data to all other nodes in the simulation for consumption. Currently there are two types of communicator, one based on the Message Passing Interface (MPI) and the other based on the Data Distribution Service (DDS), but others can be defined so long as they handle the task of interchanging data between all nodes in the simulation.

### Message Passing Interface (MPI) {#syn_mpi}

Synchronization with MPI is accomplished using two MPI calls. While many types of agents will send messages of a fixed size (vehicles, for example), others (Deformable terrain) will not. For this reason, nodes don't immediately know how much space they'll need for incoming state data. MPI synchronization uses a first call to determine how much space each node will need for their state data, and a second call to collect that data after the nodes have allocated space to receive it. More details are in the [MPI synchronization section](@ref state_sync_MPI) of the manual.

### Data Distribution Service (DDS) {#syn_dds}

Synchronization can also be accomplished using DDS. Rather than the collective communication of MPI, DDS communication is point-to-point via a collection of "topics", one for each node's state data. To synchronize state, each node subscribes to topics for all other nodes. DDS takes advantage of multi-threading to handle sending and receiving from multiple nodes at once. DDS is usually preferred over MPI outside of cluster situations, where MPI is less available and more communication flexibility is required as DDS can communicate using UDP. More details are in the [DDS synchronization section](@ref state_sync_DDS) of the manual.

## Support for Other Chrono Modules {#syn_modules}

The focus during SynChrono's development has been on autonomous vehicle simulation, so SynChrono currently depends on Chrono::Vehicle for proper operation. While this is not a fundamental limitation, there are also no additional dependencies required to build Chrono::Vehicle so this dependency should not be a burden.

SynChrono supports visualization through both the Chrono::Irrlicht and Chrono::Sensor modules.


text:
using System;

namespace Oldmansoft.Html.WebMan
{
    /// <summary>
    /// 值显示
    /// </summary>
    public interface IValueDisplay
    {
        /// <summary>
        /// 处理类型
        /// </summary>
        Type DealType { get; }

        /// <summary>
        /// 转换
        /// </summary>
        /// <param name="value"></param>
        /// <param name="propertyContent"></param>
        /// <returns></returns>
        HtmlNode Convert(object value, ModelPropertyContent propertyContent);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<plasterManifest schemaVersion="0.4" xmlns="http://www.microsoft.com/schemas/PowerShell/Plaster/v1">
    <metadata>
        <id>dcd95744-8abc-4ecb-a439-bf2cd37821bb</id>
        <name>NewModule</name>
        <title>New Module</title>
        <description>Scaffolds the files required for a PowerShell module.</description>
        <version>1.0.0</version>
        <tags>Module, ModuleManifest, Build</tags>
    </metadata>

    <parameters>
        <parameter name='ModuleName'
                   type='text'
                   prompt='Enter the name of the module'/>

        <parameter name='ModuleDesc'
                   type='text'
                   prompt='Enter a description of the module (required for publishing to the PowerShell Gallery)'/>

        <parameter name='Version'
                   type='text'
                   prompt='Enter the version number of the module'
                   default='0.1.0'/>

        <parameter name='FullName'
                   type='user-fullname'
                   prompt='Enter your full name'
                   store='text' />

        <parameter name='License'
                   type='choice'
                   prompt='Select a license (see http://choosealicense.com for help choosing):'
                   default='0'
                   store='text'>
            <choice label='&None'
                    help="No license."
                    value="None"/>
            <choice label='&Apache'
                    help="Adds an Apache license file."
                    value="Apache"/>
            <choice label='&MIT'
                    help="Adds an MIT license file."
                    value="MIT"/>
        </parameter>

        <parameter name='Options'
                   type='multichoice'
                   prompt='Select one or more of the following tooling options:'
                   default='1,2,3,4'
                   store='text' >
            <choice label='&None'
                    help="No tooling options specified."
                    value="None"/>
            <choice label='Add &Git .gitignore file'
                    help="Adds a .gitignore file."
                    value="Git"/>
            <choice label='Add p&sake build script'
                    help="Adds psake build script that generates the module directory for publishing to the PowerShell Gallery."
                    value="psake"/>
            <choice label='Add &Pester test support'
                    help="Adds test directory and Pester test for the module manifest file."
                    value="Pester"/>
            <choice label='Add PSScript&Analyzer support'
                    help="Adds script analysis support using PSScriptAnalyzer."
                    value="PSScriptAnalyzer"/>
            <choice label='Add plat&yPS help generation support'
                    help="Adds help build support using platyPS."
                    value="platyPS"/>
        </parameter>

        <parameter name='Editor'
                   type='choice'
                   prompt='Select one of the supported script editors for better editor integration (or None):'
                   default='0'
                   store='text' >
            <choice label='&None'
                    help="No editor specified."
                    value="None"/>
            <choice label='Visual Studio &Code'
                    help="Your editor is Visual Studio Code."
                    value="VSCode"/>
        </parameter>
    </parameters>

    <content>
        <message>

Scaffolding your PowerShell Module...

</message>

        <newModuleManifest destination='src\${PLASTER_PARAM_ModuleName}.psd1'
                           moduleVersion='$PLASTER_PARAM_Version'
                           rootModule='${PLASTER_PARAM_ModuleName}.psm1'
                           author='$PLASTER_PARAM_FullName'
                           description='$PLASTER_PARAM_ModuleDesc'
                           encoding='UTF8-NoBOM'/>

        <file condition='$PLASTER_PARAM_Options -contains "Git"'
              source='_gitignore'
              destination='.gitignore' />
        <file condition='$PLASTER_PARAM_Options -contains "psake"'
              source='build*.ps1'
              destination='' />
        <file source='ReleaseNotes.md'
              destination=''/>
        <file source='src\Module.psm1'
              destination='src\${PLASTER_PARAM_ModuleName}.psm1'/>
        <file source='ScriptAnalyzerSettings.psd1'
              destination=''/>

        <templateFile condition="$PLASTER_PARAM_Options -contains 'platyPS'"
                      source='docs\en-US\about_Module.help.md'
                      destination='docs\en-US\about_${PLASTER_PARAM_ModuleName}.help.md'/>
        <templateFile condition="$PLASTER_PARAM_Options -notcontains 'platyPS'"
                      source='docs\en-US\about_Module.help.txt'
                      destination='src\en-US\about_${PLASTER_PARAM_ModuleName}.help.txt'/>
        <templateFile condition="$PLASTER_PARAM_Options -contains 'Pester'"
                      source='test\Module.T.ps1'
                      destination='test\${PLASTER_PARAM_ModuleName}.Tests.ps1' />
        <templateFile condition="$PLASTER_PARAM_Options -contains 'Pester'"
                      source='test\Shared.ps1'
                      destination='test\Shared.ps1' />
        <templateFile condition="$PLASTER_PARAM_License -eq 'Apache'"
                      source='license\Apache.txt'
                      destination='LICENSE.txt'
                      encoding="UTF8-NoBOM"/>
        <templateFile condition="$PLASTER_PARAM_License -eq 'MIT'"
                      source='license\MIT.txt'
                      destination='LICENSE.txt' />

        <file condition="($PLASTER_PARAM_Editor -eq 'VSCode') -and ($PLASTER_PARAM_Options -notcontains 'psake') -and ($PLASTER_PARAM_Options -contains 'Pester')"
              source='editor\VSCode\tasks_pester.json'
              destination='.vscode\tasks.json' />

        <file condition="($PLASTER_PARAM_Editor -eq 'VSCode') -and ($PLASTER_PARAM_Options -contains 'psake') -and ($PLASTER_PARAM_Options -notcontains 'Pester')"
              source='editor\VSCode\tasks_psake.json'
              destination='.vscode\tasks.json' />

        <file condition="($PLASTER_PARAM_Editor -eq 'VSCode') -and ($PLASTER_PARAM_Options -contains 'psake') -and ($PLASTER_PARAM_Options -contains 'Pester')"
              source='editor\VSCode\tasks_psake_pester.json'
              destination='.vscode\tasks.json' />

        <file condition="($PLASTER_PARAM_Editor -eq 'VSCode') -and ($PLASTER_PARAM_Options -contains 'PSScriptAnalyzer')"
              source='editor\VSCode\settings.json'
              destination='.vscode\settings.json' />

        <requireModule name="Pester" condition='$PLASTER_PARAM_Options -contains "Pester"' minimumVersion="3.4.0"
            message="Without Pester, you will not be able to run the provided Pester test to validate your module manifest file.`nWithout version 3.4.0, VS Code will not display Pester warnings and errors in the Problems panel."/>

        <requireModule name="psake" condition='$PLASTER_PARAM_Options -contains "psake"'
            message="Without psake, you will not be able to run the provided build script to build and/or publish your module."/>

        <requireModule name="PSScriptAnalyzer" condition='$PLASTER_PARAM_Options -contains "PSScriptAnalyzer"'
            message="Without PSScriptAnalyzer, you will not be able to perform script analysis, or use the provided options to control script analysis."/>

        <requireModule name="platyPS" condition='$PLASTER_PARAM_Options -contains "platyPS"' minimumVersion="0.7.2"
            message="Without platyPS, you will not be able to generate PowerShell external help for your module using markdown."/>

        <message>

Your new PowerShell module project '$PLASTER_PARAM_ModuleName' has been created.

        </message>

        <message condition="$PLASTER_PARAM_Options -contains 'Pester'">
A Pester test has been created to validate the module's manifest file.  Add additional tests to the test directory.
You can run the Pester tests in your project by executing the 'test' task.  Press Ctrl+P, then type 'task test'.

        </message>

        <message condition="$PLASTER_PARAM_Options -contains 'psake'">
You can build your project by executing the 'build' task.  Press Ctrl+P, then type 'task build'.
You can publish your project to the PSGallery by pressing Ctrl+P, then type 'task publish'.

        </message>

        <message condition="($PLASTER_PARAM_Options -contains 'psake') -and ($PLASTER_PARAM_Options -contains 'platyPS')">
You can generate help and additional documentation using platyPS by running the 'build help' task.  Press Ctrl+P,
then type 'task build help'.  Add additional documentation written in platyPS markdown to the docs directory. You can
update the help by running the 'build help' task again.

        </message>
    </content>
</plasterManifest>


text:
package com.example.bakes.login_menu;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.util.AttributeSet;
import android.view.ViewGroup;

/* Adapted from SceLus's comment on StackOverflow
 * https://stackoverflow.com/a/22987264
 *
 * modifications made:
 *      Class now extends AppCompatImageView. Because Android Studio wanted me to
 *          I won't be using tint or anything, so it doesn't really matter either way.
 *      Changed calculatePath so that it now creates flat top hexagons
 *      Changed onMeasure to better fit the size of the view to the size of the hexagon
 *      If no layoutParams are set, it defaults to 100 height (will end up being a bit less)
 *          and 100 width
 *      Removed setRadius and setBorderColor
 *
 */

//I extended it from this because it didn't like me extending ImageView. I don't think I'll be using
//tints or anything, but
public class HexagonMaskView extends android.support.v7.widget.AppCompatImageView {
    private Path hexagonPath;
    private Path hexagonBorderPath;
    private Paint mBorderPaint;

    public HexagonMaskView(Context context) {
        super(context);
        this.setLayoutParams(new ViewGroup.LayoutParams(100, 100));
        init();
    }

    public HexagonMaskView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public HexagonMaskView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        setScaleType(ScaleType.CENTER_CROP);
        this.hexagonPath = new Path();
        this.hexagonBorderPath = new Path();

        this.mBorderPaint = new Paint();
        this.mBorderPaint.setColor(Color.BLACK);
        this.mBorderPaint.setStrokeCap(Paint.Cap.ROUND);
        this.mBorderPaint.setStrokeWidth(1f);
        this.mBorderPaint.setStyle(Paint.Style.STROKE);
    }

    //Changed it from pointy to flat top hexagons
    private void calculatePath(float radius) {
        float halfRadius = radius / 2f;
        //added height offsets a bit in sort of a hackish attempt to get horizontal lines to show
        float triangleHeight = this.getMeasuredHeight()/2f;
        float centerX = getMeasuredWidth() / 2f;
        float centerY = getMeasuredHeight() / 2f;
        float offset = 1f;

        //draw hexagon which will be filled with the image
        hexagonPath.reset();
        hexagonPath.moveTo(centerX - halfRadius, centerY - triangleHeight + offset);
        hexagonPath.lineTo(centerX + halfRadius, centerY - triangleHeight + offset);
        hexagonPath.lineTo(centerX + radius, centerY);
        hexagonPath.lineTo(centerX + halfRadius, centerY + triangleHeight - offset);
        hexagonPath.lineTo(centerX - halfRadius, centerY + triangleHeight - offset);
        hexagonPath.lineTo(centerX - radius, centerY);
        hexagonPath.close();

        float radiusBorder = radius + .5f;
        float halfRadiusBorder = radiusBorder / 2f;
        float borderOffset = offset/2;

        //adds a small border to the edges of the hexagon
        hexagonBorderPath.reset();
        hexagonBorderPath.moveTo(centerX - halfRadiusBorder, centerY - triangleHeight + borderOffset);
        hexagonBorderPath.lineTo(centerX + halfRadiusBorder, centerY - triangleHeight + borderOffset);
        hexagonBorderPath.lineTo(centerX + radiusBorder, centerY);
        hexagonBorderPath.lineTo(centerX + halfRadiusBorder, centerY + triangleHeight - borderOffset);
        hexagonBorderPath.lineTo(centerX - halfRadiusBorder, centerY + triangleHeight - borderOffset);
        hexagonBorderPath.lineTo(centerX - radiusBorder, centerY);
        hexagonBorderPath.close();
        invalidate();
    }

    @Override
    public void onDraw(Canvas c) {
        c.drawPath(hexagonBorderPath, mBorderPaint);
        c.clipPath(hexagonPath);
        c.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
        super.onDraw(c);
    }

    //Since I know the hexagons are vertically aligned (flat-topped), I know r will be related to width
    //additionally, I want to change the height measurement, since I don't want empty space between hexes
    @Override
    public void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
//        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
//        int width = MeasureSpec.getSize(widthMeasureSpec);
//        int height = MeasureSpec.getSize(heightMeasureSpec);
//        setMeasuredDimension(width, height);
//        calculatePath(Math.min(width / 2f, height / 2f) - 10f);
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = MeasureSpec.getSize(heightMeasureSpec);
        //flat topped hexagons are wider than they are taller.
        height = Math.round((float)Math.sqrt(3.0)/2 * height);
        int minHeight = getSuggestedMinimumHeight();
        int minWidth = getSuggestedMinimumWidth();
        //I try to keep the same ratio between height/width
        if(height < minHeight || width < minWidth){
            int y = minHeight / height;
            int x = minWidth / width;
            width = width * Math.max(x,y);
            height = height * Math.max(x,y);
        }
        setMeasuredDimension(width, height);
        calculatePath(width/2f);
    }
}


text:
/*
  +----------------------------------------------------------------------+
  | Swoole                                                               |
  +----------------------------------------------------------------------+
  | This source file is subject to version 2.0 of the Apache license,    |
  | that is bundled with this package in the file LICENSE, and is        |
  | available through the world-wide-web at the following url:           |
  | http://www.apache.org/licenses/LICENSE-2.0.html                      |
  | If you did not receive a copy of the Apache2.0 license and are unable|
  | to obtain it through the world-wide-web, please send a note to       |
  | license@php.net so we can mail you a copy immediately.               |
  +----------------------------------------------------------------------+
  | Author: Tianfeng Han  <mikan.tenny@gmail.com>                        |
  +----------------------------------------------------------------------+
*/

#ifndef SW_WEBSOCKET_H_
#define SW_WEBSOCKET_H_

#include "http.h"

SW_EXTERN_C_BEGIN

#define SW_WEBSOCKET_SEC_KEY_LEN            16
#define SW_WEBSOCKET_GUID                   "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
#define SW_WEBSOCKET_HEADER_LEN             2
#define SW_WEBSOCKET_MASK_LEN               4
#define SW_WEBSOCKET_MASK_DATA              "258E"
#define SW_WEBSOCKET_EXT16_MAX_LEN          0xFFFF
#define SW_WEBSOCKET_EXT16_LENGTH           0x7E
#define SW_WEBSOCKET_EXT64_LENGTH           0x7F
#define SW_WEBSOCKET_CLOSE_CODE_LEN         2
#define SW_WEBSOCKET_CLOSE_REASON_MAX_LEN   125
#define SW_WEBSOCKET_OPCODE_MAX             WEBSOCKET_OPCODE_PONG

enum swWebsocket_status
{
    WEBSOCKET_STATUS_NONE = 0,
    WEBSOCKET_STATUS_CONNECTION = 1,
    WEBSOCKET_STATUS_HANDSHAKE = 2,
    WEBSOCKET_STATUS_ACTIVE = 3,
    WEBSOCKET_STATUS_CLOSING    = 4,
};

enum swWebSocket_frame_flag
{
    SW_WEBSOCKET_FLAG_FIN =  1 << 0, /* BC: must be 1 */
    SW_WEBSOCKET_FLAG_COMPRESS = 1 << 1,
    /* readonly for user */
    SW_WEBSOCKET_FLAG_RSV1 = 1 << 2,
    SW_WEBSOCKET_FLAG_RSV2 = 1 << 3,
    SW_WEBSOCKET_FLAG_RSV3 = 1 << 4,
    SW_WEBSOCKET_FLAG_MASK = 1 << 5,
};

enum swWebSocket_frame_union_flag
{
    SW_WEBSOCKET_FLAGS_ALL = /* used to prevent overflow  */
        SW_WEBSOCKET_FLAG_FIN |
        SW_WEBSOCKET_FLAG_RSV1 |
        SW_WEBSOCKET_FLAG_RSV2 |
        SW_WEBSOCKET_FLAG_RSV3 |
        SW_WEBSOCKET_FLAG_MASK |
        SW_WEBSOCKET_FLAG_COMPRESS
};

typedef struct
{
    /**
     * fin:1 rsv1:1 rsv2:1 rsv3:1 opcode:4
     */
    uchar OPCODE :4;
    uchar RSV3 :1;
    uchar RSV2 :1;
    uchar RSV1 :1;
    uchar FIN :1;
    uchar LENGTH :7;
    uchar MASK :1;

} swWebSocket_frame_header;

typedef struct
{
    swWebSocket_frame_header header;
    char mask_key[SW_WEBSOCKET_MASK_LEN];
    uint16_t header_length;
    size_t payload_length;
    char *payload;
} swWebSocket_frame;

#define WEBSOCKET_VERSION    13

enum swWebsocket_opcode
{
    WEBSOCKET_OPCODE_CONTINUATION = 0x0,
    WEBSOCKET_OPCODE_TEXT = 0x1,
    WEBSOCKET_OPCODE_BINARY = 0x2,
    WEBSOCKET_OPCODE_CLOSE = 0x8,
    WEBSOCKET_OPCODE_PING = 0x9,
    WEBSOCKET_OPCODE_PONG = 0xa,
};

enum swWebsocket_close_reason
{
    WEBSOCKET_CLOSE_NORMAL = 1000,
    WEBSOCKET_CLOSE_GOING_AWAY = 1001,
    WEBSOCKET_CLOSE_PROTOCOL_ERROR = 1002,
    WEBSOCKET_CLOSE_DATA_ERROR = 1003,
    WEBSOCKET_CLOSE_STATUS_ERROR = 1005,
    WEBSOCKET_CLOSE_ABNORMAL = 1006,
    WEBSOCKET_CLOSE_MESSAGE_ERROR = 1007,
    WEBSOCKET_CLOSE_POLICY_ERROR = 1008,
    WEBSOCKET_CLOSE_MESSAGE_TOO_BIG = 1009,
    WEBSOCKET_CLOSE_EXTENSION_MISSING = 1010,
    WEBSOCKET_CLOSE_SERVER_ERROR = 1011,
    WEBSOCKET_CLOSE_TLS = 1015,
};

static inline uchar swWebSocket_get_flags(swWebSocket_frame *frame)
{
    uchar flags = 0;
    if (frame->header.FIN)
    {
        flags |= SW_WEBSOCKET_FLAG_FIN;
    }
    if (frame->header.RSV1)
    {
        flags |= SW_WEBSOCKET_FLAG_RSV1;
    }
    if (frame->header.RSV2)
    {
        flags |= SW_WEBSOCKET_FLAG_RSV2;
    }
    if (frame->header.RSV3)
    {
        flags |= SW_WEBSOCKET_FLAG_RSV3;
    }
    if (frame->header.MASK)
    {
        flags |= SW_WEBSOCKET_FLAG_MASK;
    }
    return flags;
}

static inline uchar swWebSocket_set_flags(uchar fin, uchar mask, uchar rsv1, uchar rsv2, uchar rsv3)
{
    uchar flags = 0;
    if (fin)
    {
        flags |= SW_WEBSOCKET_FLAG_FIN;
    }
    if (mask)
    {
        flags |= SW_WEBSOCKET_FLAG_MASK;
    }
    if (rsv1)
    {
        flags |= SW_WEBSOCKET_FLAG_RSV1;
    }
    if (rsv2)
    {
        flags |= SW_WEBSOCKET_FLAG_RSV2;
    }
    if (rsv3)
    {
        flags |= SW_WEBSOCKET_FLAG_RSV3;
    }
    return flags;
}

void swWebSocket_encode(swString *buffer, const char *data, size_t length, char opcode, uint8_t flags);
void swWebSocket_decode(swWebSocket_frame *frame, swString *data);
int swWebSocket_pack_close_frame(swString *buffer, int code, char* reason, size_t length, uint8_t flags);
void swWebSocket_print_frame(swWebSocket_frame *frame);

ssize_t swWebSocket_get_package_length(swProtocol *protocol, swSocket *conn, char *data, uint32_t length);
int swWebSocket_dispatch_frame(swProtocol *protocol, swSocket *conn, char *data, uint32_t length);

SW_EXTERN_C_END

#endif /* SW_WEBSOCKET_H_ */


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
All Classes
</TITLE>

<LINK REL ="stylesheet" TYPE="text/css" HREF="stylesheet.css" TITLE="Style">

All Classes

Activity

ActivitySummary

Address

Chemotherapy

CollaborativeStaging

Diagnosis

DiseaseExtent

DistantSite

FirstCourseRadiation

FirstCourseTreatmentSummary

Followup

HemTransplantEndocrineProcedure

HormoneTherapy

Immunotherapy

NonCancerDirectedSurgery

OtherProcedure

OtherTherapy

Patient

PatientIdentifier

PrimarySiteSurgery

Procedure

Radiation

Recurrence

RegionalDistantSurgery

RegionalLymphNodeSurgery

SubstanceAdministration

Surgery


text:
	<title>Justin Punzalan</title>
	<link rel="icon" type="image/png" href="icon.png">

	<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">

	<link rel="stylesheet" type="text/css" href="css/animate.css">
	<link rel="stylesheet" type="text/css" href="css/style.css">
	<link rel="stylesheet" type="text/css" href="css/projects.css">
	<link rel="stylesheet" type="text/css" href="css/semantic.min.css">

	    Home

	    Projects &
 Experience

	    Awards

Menu

Projects & Experience

Current

Team 4 ELEMENT

FIRST ROBOTICS MENTOR

Designed a programming curriculum to teach programming to interested high school students. Implemented PID Control Loops, Vision Tracking and Motion Profiling.

Sep 2015 - Current

Past

TakeSessions

Lead Frontend Developer

Responsible for planning, building, and creating all web pages. Had to create and convert PSD UI mockups into HTML/CSS via Emberjs. Also organized and maintained SCRUM sheet and sprint meetings.

Aug 2016 - November 2016

Yudek

Intern

Full-stack web development. Web application built with Emberjs and PHP. Responsible for maintaining and creating several pages using Emberjs.

Jun 2016 to Aug 2016

RESET Content

Technical Robotic Consultant & Production Assistant

Responsible for informing set managers on what all the robots on set were capable of. Also ensured that all robots were functional. Pre-programmed several robots on set.

March 2016

Projects

StudyTime

Created a Chrome extension that blocks distracting sites defined by the user, usually social media pages. Simply turn it on to start studying and turn it back off when finished. Useful for studying and getting a lot of work done.

Jan 2015

CelverText

Hacked together an AI chatbot via the CleverBot API and Twilio SMS services. Simply text the number and have a random conversation about anything. Built with expressjs. SMS server currently down due to the cost of SMS services (someone could spam application costing me hundreds).

Dec 2016

TheBBCodeClub

Created a web application that converts text into the BBCode format. Material design themed. Adds styling to plain boring text. Useful for forum users and certain social media pages. 20 active users a day.

November 2016

Team 4 Robots

Created and implemented algorithms that smooth motion and ensure realiability Implemented PID Control Loops, Vision Tracking and Motion Profiling. Controlled via Xbox 360 controllers. Made with Java.

Sep 2015 - Aug 2016

Rocket Flight Computers

Made 2 Rocket Flight Computers that recorded Altitude, Location, Speed and Voltage Deployed Parachutes at Apogee. Made with AIM BASE & XTRA.

March 2016

Hackathons

LA Hacks

Created an Android app that lets you run a scavenger hunt around the world. Similar to GeoCaching. Completed a material design mock-up with Photoshop. Users use NFC tags to store images. Goal is to collect as many images as you can. Made with Java, Azure, Android Studio, Photoshop and MEANJs.

April 2016

Valley Economic Hackathon

Created a responsive landing page that encourages people to set up their businesses in the San Fernando Valley.

November 2015

HackingEDU

Created an app that subconsciously teaches people through text messages. The user defines the terms they want to learn. The app exposes the user to the term(s) 2-3x more often than normal Made with Java, Twilio, HTML, CSS, Skeleton and Ngrok.

October 2015

SDHacks

Created an Android app that encourages users to exercise. Spin off of Cookie Clicker, one step = one cookie. The more steps you take, the more points you get.

October 2015

Code For India @Google HQ

Created a simple SMS/Web application that helps prevent malnourishment and starvation in India. Used medical information to add specific fruits and vegetables to their diet in order to combat malnourishment. Used historical data provided by teachers to predict attendance at school.

September 2015

CodeDayLA

Created a web application that saves the user's parked car's location Never forget where you parked.

June 2015

Designed and developed by Justin Punzalan © 2017


text:
angular.module('parrotPollApp')
    .controller('indexCtrl', ['$scope', '$location', function($scope, $location) {
var indexVm = this;
        //var
        var PASW = "4321";
        //func
        //asin
        indexVm.redirect = function() {
            if (PASW == indexVm.password) {
                $scope.$parent.$broadcast('navOk', false);
                $location.path("/home");
            }
        };
        //eje
    }]);


text:
import os
from base64 import b64encode

from django.conf import settings
from django.utils.encoding import force_str

from unittest import mock
import pytest

from olympia import amo
from olympia.amo.tests import addon_factory, root_storage, version_factory
from olympia.versions.models import Version, VersionPreview
from olympia.versions.tasks import (
    generate_static_theme_preview,
    hard_delete_versions,
    UI_FIELDS,
)

HEADER_ROOT = os.path.join(settings.ROOT, 'src/olympia/versions/tests/static_themes/')

transparent_colors = [
    'class="%(field)s %(prop)s" %(prop)s="rgb(0,0,0,0)"'
    % {'field': field, 'prop': 'stroke' if field == 'tab_line' else 'fill'}
    for field in UI_FIELDS + ('tab_selected toolbar',)
    if field not in ('icons', 'tab_selected')  # bookmark_text class used instead
]

def check_render(
    svg_content,
    header_url,
    header_height,
    preserve_aspect_ratio,
    mimetype,
    valid_img,
    colors,
    svg_width,
    svg_height,
    inner_width,
):
    # check header is there.
    assert (
        'width="%s" height="%s" xmlns="http://www.w3.org/2000/'
        % (svg_width, svg_height)
        in svg_content
    )
    # check image xml is correct
    image_tag = (
        '<image id="svg-header-img" width="%s" height="%s" '
        'preserveAspectRatio="%s"' % (inner_width, header_height, preserve_aspect_ratio)
    )
    assert image_tag in svg_content, svg_content
    # and image content is included and was encoded
    if valid_img:
        with root_storage.open(HEADER_ROOT + header_url, 'rb') as header_file:
            header_blob = header_file.read()
            base_64_uri = 'data:{};base64,{}'.format(
                mimetype,
                force_str(b64encode(header_blob)),
            )
    else:
        base_64_uri = ''
    assert 'xlink:href="%s"></image>' % base_64_uri in svg_content, svg_content
    # check each of our colors above was included
    for color in colors:
        assert color in svg_content

def check_thumbnail(
    preview_instance,
    theme_size_constant,
    source_png_path,
    resize_image_mock_args_kwargs,
    png_crush_mock_args=None,
):
    (resize_path, thumb_path, thumb_size), resize_kwargs = resize_image_mock_args_kwargs
    assert resize_path == source_png_path
    assert thumb_path == preview_instance.thumbnail_path
    assert thumb_size == tuple(preview_instance.thumbnail_dimensions)
    if png_crush_mock_args:
        assert png_crush_mock_args[0] == source_png_path
    assert preview_instance.colors
    assert resize_kwargs == {
        'format': theme_size_constant['thumbnail_format'],
        'quality': 35,
    }

def check_preview(
    preview_instance,
    theme_size_constant,
):
    assert preview_instance.sizes == {
        'image': list(theme_size_constant['full']),
        'thumbnail': list(theme_size_constant['thumbnail']),
        'image_format': theme_size_constant['image_format'],
        'thumbnail_format': theme_size_constant['thumbnail_format'],
    }

def write_empty_png(svg_content, out):
    root_storage.copy_stored_file(os.path.join(HEADER_ROOT, 'empty.png'), out)
    return True

@pytest.mark.django_db
@mock.patch('olympia.addons.tasks.index_addons.delay')
@mock.patch('olympia.versions.tasks.extract_colors_from_image')
@mock.patch('olympia.versions.tasks.pngcrush_image')
@mock.patch('olympia.versions.tasks.resize_image')
@mock.patch('olympia.versions.tasks.write_svg_to_png')
@mock.patch('olympia.versions.tasks.convert_svg_to_png')
@pytest.mark.parametrize(
    'header_url, header_height, preserve_aspect_ratio, mimetype, valid_img',
    (
        ('transparent.gif', 1, 'xMaxYMin meet', 'image/gif', True),
        ('weta.png', 200, 'xMaxYMin meet', 'image/png', True),
        ('wetalong.png', 200, 'xMaxYMin slice', 'image/png', True),
        (
            'weta_theme_firefox.svg',
            92,  # different value for 680 and 760/720
            ('xMaxYMin slice', 'xMaxYMin meet'),
            'image/svg+xml',
            True,
        ),
        ('transparent.svg', 1, 'xMaxYMin meet', 'image/svg+xml', True),
        ('missing_file.png', 0, 'xMaxYMin meet', '', False),
        ('empty-no-ext', 0, 'xMaxYMin meet', '', False),
        (None, 0, 'xMaxYMin meet', '', False),  # i.e. no theme_frame entry
    ),
)
def test_generate_static_theme_preview(
    convert_svg_to_png_mock,
    write_svg_to_png_mock,
    resize_image_mock,
    pngcrush_image_mock,
    extract_colors_from_image_mock,
    index_addons_mock,
    header_url,
    header_height,
    preserve_aspect_ratio,
    mimetype,
    valid_img,
):
    write_svg_to_png_mock.side_effect = write_empty_png
    convert_svg_to_png_mock.return_value = True
    extract_colors_from_image_mock.return_value = [
        {'h': 9, 's': 8, 'l': 7, 'ratio': 0.6}
    ]
    theme_manifest = {
        'images': {},
        'colors': {
            'frame': '#918e43',
            'tab_background_text': '#3deb60',
            'bookmark_text': '#b5ba5b',
            'toolbar_field': '#cc29cc',
            'toolbar_field_text': '#17747d',
            'tab_line': '#00db12',
            'tab_selected': '#40df39',
        },
    }
    if header_url is not None:
        theme_manifest['images']['theme_frame'] = header_url
    addon = addon_factory(
        file_kw={'filename': os.path.join(HEADER_ROOT, 'theme_images.zip')}
    )
    # existing previews should be deleted if they exist
    existing_preview = VersionPreview.objects.create(version=addon.current_version)
    generate_static_theme_preview(theme_manifest, addon.current_version.pk)
    # check that it was deleted
    assert not VersionPreview.objects.filter(id=existing_preview.id).exists()
    assert VersionPreview.objects.filter(version=addon.current_version).count() == 2

    # for svg preview we write the svg twice, 1st with write_svg, later with convert_svg
    assert resize_image_mock.call_count == 2
    assert write_svg_to_png_mock.call_count == 2
    assert convert_svg_to_png_mock.call_count == 1
    assert pngcrush_image_mock.call_count == 1

    # First check the firefox Preview is good
    firefox_preview = VersionPreview.objects.get(
        version=addon.current_version,
        position=amo.THEME_PREVIEW_RENDERINGS['firefox']['position'],
    )
    check_preview(
        firefox_preview,
        amo.THEME_PREVIEW_RENDERINGS['firefox'],
    )
    assert write_svg_to_png_mock.call_args_list[0][0][1] == firefox_preview.image_path
    check_thumbnail(
        firefox_preview,
        amo.THEME_PREVIEW_RENDERINGS['firefox'],
        firefox_preview.image_path,
        resize_image_mock.call_args_list[0],
        pngcrush_image_mock.call_args_list[0][0],
    )

    # And then Preview used on AMO
    amo_preview = VersionPreview.objects.get(
        version=addon.current_version,
        position=amo.THEME_PREVIEW_RENDERINGS['amo']['position'],
    )
    check_preview(
        amo_preview,
        amo.THEME_PREVIEW_RENDERINGS['amo'],
    )
    assert convert_svg_to_png_mock.call_args_list[0][0][0] == amo_preview.image_path
    check_thumbnail(
        amo_preview,
        amo.THEME_PREVIEW_RENDERINGS['amo'],
        convert_svg_to_png_mock.call_args_list[0][0][1],
        resize_image_mock.call_args_list[1],
    )

    # Now check the svg renders
    firefox_svg = write_svg_to_png_mock.call_args_list[0][0][0]
    interim_amo_svg = write_svg_to_png_mock.call_args_list[1][0][0]
    with open(amo_preview.image_path) as svg:
        amo_svg = svg.read()
    preview_colors = {
        **theme_manifest['colors'],
        'tab_selected toolbar': theme_manifest['colors']['tab_selected'],
    }
    colors = [
        'class="%(field)s %(prop)s" %(prop)s="%(color)s"'
        % {
            'field': key,
            'prop': 'stroke' if key == 'tab_line' else 'fill',
            'color': color,
        }
        for (key, color) in preview_colors.items()
        if key != 'tab_selected'
    ]

    preserve_aspect_ratio = (
        (preserve_aspect_ratio,) * 3
        if not isinstance(preserve_aspect_ratio, tuple)
        else preserve_aspect_ratio
    )
    check_render(
        force_str(firefox_svg),
        header_url,
        header_height,
        preserve_aspect_ratio[0],
        mimetype,
        valid_img,
        colors,
        680,
        92,
        680,
    )
    check_render(
        force_str(interim_amo_svg),
        header_url,
        header_height,
        preserve_aspect_ratio[1],
        mimetype,
        valid_img,
        transparent_colors,
        720,
        92,
        720,
    )
    check_render(
        force_str(amo_svg),
        'empty.jpg',
        92,
        'xMaxYMin slice',
        'image/jpeg',
        True,
        colors,
        720,
        92,
        720,
    )

    index_addons_mock.assert_called_with([addon.id])

@pytest.mark.django_db
@mock.patch('olympia.addons.tasks.index_addons.delay')
@mock.patch('olympia.versions.tasks.extract_colors_from_image')
@mock.patch('olympia.versions.tasks.pngcrush_image')
@mock.patch('olympia.versions.tasks.resize_image')
@mock.patch('olympia.versions.tasks.write_svg_to_png')
@mock.patch('olympia.versions.tasks.convert_svg_to_png')
@pytest.mark.parametrize(
    'manifest_images, manifest_colors, svg_colors',
    (
        (  # deprecated properties
            {'headerURL': 'transparent.gif'},
            {
                'accentcolor': '#918e43',  # frame
                'textcolor': '#3deb60',  # tab_background_text
                'toolbar_text': '#b5ba5b',  # bookmark_text
            },
            {
                'frame': '#918e43',
                'tab_background_text': '#3deb60',
                'bookmark_text': '#b5ba5b',
            },
        ),
        (  # defaults and fallbacks
            {'theme_frame': 'transparent.gif'},
            {
                'icons': '#348923',
            },  # icons have class bookmark_text
            {
                'frame': amo.THEME_FRAME_COLOR_DEFAULT,
                'toolbar': 'rgba(255,255,255,0.6)',
                'toolbar_field': 'rgba(255,255,255,1)',
                'tab_selected toolbar': 'rgba(255,255,255,0.6)',
                'tab_line': 'rgba(0,0,0,0.25)',
                'tab_background_text': '',
                'bookmark_text': '#348923',  # icons have class bookmark_text
            },
        ),
        (  # chrome colors
            {'theme_frame': 'transparent.gif'},
            {
                'frame': [123, 45, 67],
                'tab_background_text': [9, 87, 65],
                'bookmark_text': [0, 0, 0],
            },
            {
                'frame': 'rgb(123,45,67)',
                'tab_background_text': 'rgb(9,87,65)',
                'bookmark_text': 'rgb(0,0,0)',
            },
        ),
    ),
)
def test_generate_static_theme_preview_with_alternative_properties(
    convert_svg_to_png_mock,
    write_svg_to_png_mock,
    resize_image_mock,
    pngcrush_image_mock,
    extract_colors_from_image_mock,
    index_addons_mock,
    manifest_images,
    manifest_colors,
    svg_colors,
):
    write_svg_to_png_mock.side_effect = write_empty_png
    convert_svg_to_png_mock.return_value = True
    extract_colors_from_image_mock.return_value = [
        {'h': 9, 's': 8, 'l': 7, 'ratio': 0.6}
    ]
    theme_manifest = {
        'images': manifest_images,
        'colors': manifest_colors,
    }
    addon = addon_factory(
        file_kw={'filename': os.path.join(HEADER_ROOT, 'theme_images.zip')}
    )
    generate_static_theme_preview(theme_manifest, addon.current_version.pk)

    # for svg preview we write the svg twice, 1st with write_svg, later with convert_svg
    assert resize_image_mock.call_count == 2
    assert write_svg_to_png_mock.call_count == 2
    assert convert_svg_to_png_mock.call_count == 1
    assert pngcrush_image_mock.call_count == 1

    # First check the firefox Preview is good
    firefox_preview = VersionPreview.objects.get(
        version=addon.current_version,
        position=amo.THEME_PREVIEW_RENDERINGS['firefox']['position'],
    )
    check_preview(
        firefox_preview,
        amo.THEME_PREVIEW_RENDERINGS['firefox'],
    )
    assert write_svg_to_png_mock.call_args_list[0][0][1] == firefox_preview.image_path
    check_thumbnail(
        firefox_preview,
        amo.THEME_PREVIEW_RENDERINGS['firefox'],
        firefox_preview.image_path,
        resize_image_mock.call_args_list[0],
        pngcrush_image_mock.call_args_list[0][0],
    )

    # And then the Preview used on AMO
    amo_preview = VersionPreview.objects.get(
        version=addon.current_version,
        position=amo.THEME_PREVIEW_RENDERINGS['amo']['position'],
    )
    check_preview(
        amo_preview,
        amo.THEME_PREVIEW_RENDERINGS['amo'],
    )
    assert convert_svg_to_png_mock.call_args_list[0][0][0] == amo_preview.image_path
    check_thumbnail(
        amo_preview,
        amo.THEME_PREVIEW_RENDERINGS['amo'],
        convert_svg_to_png_mock.call_args_list[0][0][1],
        resize_image_mock.call_args_list[1],
    )

    colors = [
        'class="%(field)s %(prop)s" %(prop)s="%(color)s"'
        % {
            'field': key,
            'prop': 'stroke' if key == 'tab_line' else 'fill',
            'color': color,
        }
        for (key, color) in svg_colors.items()
    ]

    firefox_svg = write_svg_to_png_mock.call_args_list[0][0][0]
    interim_amo_svg = write_svg_to_png_mock.call_args_list[1][0][0]
    with open(amo_preview.image_path) as svg:
        amo_svg = svg.read()
    check_render(
        force_str(firefox_svg),
        'transparent.gif',
        1,
        'xMaxYMin meet',
        'image/gif',
        True,
        colors,
        680,
        92,
        680,
    )
    check_render(
        force_str(interim_amo_svg),
        'transparent.gif',
        1,
        'xMaxYMin meet',
        'image/gif',
        True,
        transparent_colors,
        720,
        92,
        720,
    )
    check_render(
        force_str(amo_svg),
        'empty.jpg',
        92,
        'xMaxYMin slice',
        'image/jpeg',
        True,
        colors,
        720,
        92,
        720,
    )

def check_render_additional(svg_content, inner_svg_width, colors):
    # check additional background pattern is correct
    image_width = 270
    image_height = 200
    pattern_x_offset = (inner_svg_width - image_width) // 2
    pattern_tag = (
        '<pattern id="AdditionalBackground1"\n'
        '                   width="%s" height="%s"\n'
        '                   x="%s" y="%s" patternUnits="userSpaceOnUse">'
        % (image_width, image_height, pattern_x_offset, 0)
    )
    assert pattern_tag in svg_content, svg_content
    image_tag = f'<image width="{image_width}" height="{image_height}"'
    assert image_tag in svg_content, svg_content
    rect_tag = (
        '<rect width="100%" height="100%" fill="url(#AdditionalBackground1)"></rect>'
    )
    assert rect_tag in svg_content, svg_content
    # and image content is included and was encoded
    additional = os.path.join(HEADER_ROOT, 'weta_for_tiling.png')
    with root_storage.open(additional, 'rb') as header_file:
        header_blob = header_file.read()
    base_64_uri = 'data:{};base64,{}'.format(
        'image/png',
        force_str(b64encode(header_blob)),
    )
    assert 'xlink:href="%s"></image>' % base_64_uri in svg_content
    # check each of our colors was included
    for color in colors:
        assert color in svg_content

@pytest.mark.django_db
@mock.patch('olympia.addons.tasks.index_addons.delay')
@mock.patch('olympia.versions.tasks.extract_colors_from_image')
@mock.patch('olympia.versions.tasks.pngcrush_image')
@mock.patch('olympia.versions.tasks.resize_image')
@mock.patch('olympia.versions.tasks.write_svg_to_png')
@mock.patch('olympia.versions.tasks.convert_svg_to_png')
def test_generate_preview_with_additional_backgrounds(
    convert_svg_to_png_mock,
    write_svg_to_png_mock,
    resize_image_mock,
    pngcrush_image_mock,
    extract_colors_from_image_mock,
    index_addons_mock,
):
    write_svg_to_png_mock.side_effect = write_empty_png
    convert_svg_to_png_mock.return_value = True
    extract_colors_from_image_mock.return_value = [
        {'h': 9, 's': 8, 'l': 7, 'ratio': 0.6}
    ]

    theme_manifest = {
        'images': {
            'theme_frame': 'empty.png',
            'additional_backgrounds': ['weta_for_tiling.png'],
        },
        'colors': {
            'textcolor': '#123456',
            # Just textcolor, to test the template defaults and fallbacks.
        },
        'properties': {
            'additional_backgrounds_alignment': ['top'],
            'additional_backgrounds_tiling': ['repeat-x'],
        },
    }
    addon = addon_factory(
        file_kw={
            'filename': os.path.join(
                settings.ROOT, 'src/olympia/devhub/tests/addons/static_theme_tiled.zip'
            )
        }
    )
    generate_static_theme_preview(theme_manifest, addon.current_version.pk)

    # for svg preview we write the svg twice, 1st with write_svg, later with convert_svg
    assert resize_image_mock.call_count == 2
    assert write_svg_to_png_mock.call_count == 2
    assert convert_svg_to_png_mock.call_count == 1
    assert pngcrush_image_mock.call_count == 1

    # First check the firefox Preview is good
    firefox_preview = VersionPreview.objects.get(
        version=addon.current_version,
        position=amo.THEME_PREVIEW_RENDERINGS['firefox']['position'],
    )
    check_preview(
        firefox_preview,
        amo.THEME_PREVIEW_RENDERINGS['firefox'],
    )
    assert write_svg_to_png_mock.call_args_list[0][0][1] == firefox_preview.image_path
    check_thumbnail(
        firefox_preview,
        amo.THEME_PREVIEW_RENDERINGS['firefox'],
        firefox_preview.image_path,
        resize_image_mock.call_args_list[0],
        pngcrush_image_mock.call_args_list[0][0],
    )

    # And then the Preview used on AMO
    amo_preview = VersionPreview.objects.get(
        version=addon.current_version,
        position=amo.THEME_PREVIEW_RENDERINGS['amo']['position'],
    )
    check_preview(
        amo_preview,
        amo.THEME_PREVIEW_RENDERINGS['amo'],
    )
    assert convert_svg_to_png_mock.call_args_list[0][0][0] == amo_preview.image_path
    check_thumbnail(
        amo_preview,
        amo.THEME_PREVIEW_RENDERINGS['amo'],
        convert_svg_to_png_mock.call_args_list[0][0][1],
        resize_image_mock.call_args_list[1],
    )

    # These defaults are mostly defined in the xml template
    default_colors = (
        ('frame', 'fill', 'rgba(229,230,232,1)'),  # amo.THEME_FRAME_COLOR_DEFAULT
        ('tab_background_text', 'fill', '#123456'),  # the only one defined in manifest
        ('bookmark_text', 'fill', '#123456'),  # should default to tab_background_text
        ('toolbar_field', 'fill', 'rgba(255,255,255,1)'),
        ('toolbar_field_text', 'fill', ''),
        ('tab_line', 'stroke', 'rgba(0,0,0,0.25)'),
        ('tab_selected toolbar', 'fill', 'rgba(255,255,255,0.6)'),
    )
    colors = [
        f'class="{key} {prop}" {prop}="{color}"'
        for (key, prop, color) in default_colors
    ]

    firefox_svg = write_svg_to_png_mock.call_args_list[0][0][0]
    interim_amo_svg = write_svg_to_png_mock.call_args_list[1][0][0]
    with open(amo_preview.image_path) as svg:
        amo_svg = svg.read()
    check_render_additional(force_str(firefox_svg), 680, colors)
    check_render_additional(force_str(interim_amo_svg), 720, transparent_colors)
    check_render(
        force_str(amo_svg),
        'empty.jpg',
        92,
        'xMaxYMin slice',
        'image/jpeg',
        True,
        colors,
        720,
        92,
        720,
    )

    index_addons_mock.assert_called_with([addon.id])

@pytest.mark.django_db
def test_hard_delete_task():
    addon = addon_factory()
    version1 = addon.current_version
    version2 = version_factory(addon=addon)
    assert Version.unfiltered.count() == 2
    hard_delete_versions.delay([version1.pk, version2.pk])
    assert Version.unfiltered.count() == 0


text:
/****************************************************************************
  History
$Log: sampleplugins.h,v $
Revision 1.2  2006/11/29 00:59:21  cignoni
Cleaned plugins interface; changed useless help class into a plain string

Revision 1.1  2006/09/25 09:24:39  e_cerisoli
add sampleplugins

****************************************************************************/

#ifndef FILTER_MUTUALINFO_H
#define FILTER_MUTUALINFO_H

#include <QObject>

#include <common/interfaces.h>
#include "alignset.h"

class QScriptEngine;

class FilterMutualInfoPlugin : public QObject, public MeshFilterInterface
{
	Q_OBJECT
	Q_INTERFACES(MeshFilterInterface)

public:
	enum { FP_IMAGE_GLOBALIGN} ;

	FilterMutualInfoPlugin();

	virtual QString pluginName(void) const { return "FilterMutualInfoPlugin"; }

	QString filterName(FilterIDType filter) const;
	QString filterInfo(FilterIDType filter) const;
	void initParameterSet(QAction *,MeshDocument & md, RichParameterSet & /*parent*/);
    bool applyFilter(QAction *filter, MeshDocument &md, RichParameterSet & /*parent*/, vcg::CallBackPos * cb) ;
	int postCondition( QAction* ) const {return MeshModel::MM_UNKNOWN;};
    FilterClass getClass(QAction *a);
	QString filterScriptFunctionName(FilterIDType filterID);
	bool preAlignment(MeshDocument &md, RichParameterSet & par, vcg::CallBackPos *cb);
	std::vector<SubGraph> buildGraph(MeshDocument &md, bool globalign=true);
	std::vector<AlignPair> CalcPairs(MeshDocument &md, bool globalign=true);
	std::vector<SubGraph> CreateGraphs(MeshDocument &md, std::vector<AlignPair> arcs);
	bool AlignGlobal(MeshDocument &md, std::vector<SubGraph> graphs);
	int getTheRightNode(SubGraph graph);
	bool AlignNode(MeshDocument &md, Node node);
	bool allActive(SubGraph graph);
	bool UpdateGraph(MeshDocument &md, SubGraph graph, int n);
	float calcShotsDifference(MeshDocument &md, std::vector<vcg::Shotf> oldShots, std::vector<vcg::Point3f> points);

	void initGL();

};

#endif


text:
package org.switchyard.validate.config.model.v1;

import javax.xml.namespace.QName;

import org.switchyard.config.Configuration;
import org.switchyard.config.model.Descriptor;
import org.switchyard.config.model.validate.ValidateModel;
import org.switchyard.config.model.validate.v1.V1BaseValidateModel;
import org.switchyard.validate.config.model.SchemaCatalogsModel;
import org.switchyard.validate.config.model.SchemaFilesModel;
import org.switchyard.validate.config.model.XmlSchemaType;
import org.switchyard.validate.config.model.XmlValidateModel;
import org.switchyard.validate.internal.ValidatorFactoryClass;
import org.switchyard.validate.xml.internal.XmlValidatorFactory;

/**
 * A version 1 XmlValidateModel.
 *
 * @author Tomohisa Igarashi
 */
@ValidatorFactoryClass(XmlValidatorFactory.class)
public class V1XmlValidateModel extends V1BaseValidateModel implements XmlValidateModel {

    private SchemaFilesModel _schemaList;
    private SchemaCatalogsModel _catalogList;

    /**
     * Constructs a new V1XmlValidateModel.
     * @param namespace namespace
     */
    public V1XmlValidateModel(String namespace) {
        super(new QName(namespace, ValidateModel.VALIDATE + '.' + XML));
    }

    /**
     * Constructs a new V1XmlValidateModel with the specified Configuration and Descriptor.
     * @param config the Configuration
     * @param desc the Descriptor
     */
    public V1XmlValidateModel(Configuration config, Descriptor desc) {
        super(config, desc);
        setModelChildrenOrder(SchemaFilesModel.SCHEMA_FILES, SchemaCatalogsModel.SCHEMA_CATALOGS);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean failOnWarning() {
        String fow = getModelAttribute(FAIL_ON_WARNING);
        return Boolean.parseBoolean(fow);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public XmlValidateModel setFailOnWarning(boolean failOnWarning) {
        setModelAttribute(FAIL_ON_WARNING, Boolean.toString(failOnWarning));
        return this;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean namespaceAware() {
        String na = getModelAttribute(NAMESPACE_AWARE);
        return Boolean.parseBoolean(na);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public XmlValidateModel setNamespaceAware(boolean namespaceAware) {
        setModelAttribute(NAMESPACE_AWARE, Boolean.toString(namespaceAware));
        return this;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public SchemaFilesModel getSchemaFiles() {
        if (_schemaList == null) {
            _schemaList = (SchemaFilesModel)getFirstChildModelStartsWith(SchemaFilesModel.SCHEMA_FILES);
        }
        return _schemaList;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public XmlValidateModel setSchemaFiles(SchemaFilesModel schemas) {
        setChildModel(schemas);
        _schemaList = schemas;
        return this;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public SchemaCatalogsModel getSchemaCatalogs() {
        if (_catalogList == null) {
            _catalogList = (SchemaCatalogsModel)getFirstChildModelStartsWith(SchemaCatalogsModel.SCHEMA_CATALOGS);
        }
        return _catalogList;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public XmlValidateModel setSchemaCatalogs(SchemaCatalogsModel catalogs) {
        setChildModel(catalogs);
        _catalogList = catalogs;
        return this;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public XmlSchemaType getSchemaType() {
        String type = getModelAttribute(SCHEMA_TYPE);
        return type != null ? XmlSchemaType.valueOf(type) : null;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public XmlValidateModel setSchemaType(XmlSchemaType type) {
        if (type != null) {
            setModelAttribute(SCHEMA_TYPE, type.toString());
        }
        return this;
    }
}


text:
namespace
{
QString GetScriptPath()
{
  return GetExternalPath("libkomwm.py", "kothic/src", "../tools/kothic/src");
}
}  // namespace

namespace build_style
{
void BuildDrawingRulesImpl(QString const & mapcssFile, QString const & outputDir)
{
  QString const outputTemplate = JoinPathQt({outputDir, "drules_proto_design"});
  QString const outputFile = outputTemplate + ".bin";

  // Caller ensures that output directory is clear
  if (QFile(outputFile).exists())
    throw std::runtime_error("Output directory is not clear");

  // Prepare command line
  QStringList params;
  params << "python" <<
            GetScriptPath() <<
            "-s" << mapcssFile <<
            "-o" << outputTemplate <<
            "-x" << "True";
  QString const cmd = params.join(' ');

  // Add path to the protobuf EGG in the PROTOBUF_EGG_PATH environment variable
  QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
  env.insert("PROTOBUF_EGG_PATH", GetProtobufEggPath());

  // Run the script
  auto const res = ExecProcess(cmd, &env);

  // Script returs nothing and zero exit code if it is executed succesfully,
  if (res.first != 0 || !res.second.isEmpty())
  {
    QString msg = QString("System error ") + std::to_string(res.first).c_str();
    if (!res.second.isEmpty())
      msg = msg + "\n" + res.second;
    throw std::runtime_error(to_string(msg));
  }

  // Ensure generated files has non-zero size
  if (QFile(outputFile).size() == 0)
    throw std::runtime_error("Drawing rules file has zero size");
}

void BuildDrawingRules(QString const & mapcssFile, QString const & outputDir)
{
  CopyFromResources("mapcss-mapping.csv", outputDir);
  CopyFromResources("mapcss-dynamic.txt", outputDir);
  BuildDrawingRulesImpl(mapcssFile, outputDir);
}

void ApplyDrawingRules(QString const & outputDir)
{
  CopyToResources("drules_proto_design.bin", outputDir);
  CopyToResources("classificator.txt", outputDir);
  CopyToResources("types.txt", outputDir);
  CopyToResources("patterns.txt", outputDir, "patterns_design.txt");
  CopyToResources("colors.txt", outputDir, "colors_design.txt");
}
}  // namespace build_style