<commit_before>// @flow
const props = {
  // react props
  // https://github.com/facebook/react/blob/5495a7f24aef85ba6937truetrue1ce962673ca9f5fde6/src/renderers/dom/shared/hooks/ReactDOMUnknownPropertyHook.js
  children: true,
  dangerouslySetInnerHTML: true,
  key: true,
  ref: true,
  autoFocus: true,
  defaultValue: true,
  defaultChecked: true,
  innerHTML: true,
  suppressContentEditableWarning: true,
  suppressHydrationWarning: true,
  // deprecated react prop
  valueLink: true,

  // https://github.com/facebook/react/blob/d7157651f7b72d9888ctrue123e191f9b88cd8f41e9/src/renderers/dom/shared/HTMLDOMPropertyConfig.js
  /**
   * Standard Properties
   */

  accept: true,
  acceptCharset: true,
  accessKey: true,
  action: true,
  allow: true,
  allowUserMedia: true,
  allowPaymentRequest: true,
  allowFullScreen: true,
  allowTransparency: true,
  alt: true,
  // specifies target context for links with `preload` type
  // as: true,
  async: true,
  autoComplete: true,
  // autoFocus is polyfilled/normalized by AutoFocusUtils
  // autoFocus: true,
  autoPlay: true,
  capture: true,
  cellPadding: true,
  cellSpacing: true,
  // keygen prop
  challenge: true,
  charSet: true,
  checked: true,
  cite: true,
  classID: true,
  className: true,
  cols: true,
  colSpan: true,
  content: true,
  contentEditable: true,
  contextMenu: true,
  controls: true,
  controlsList: true,
  coords: true,
  crossOrigin: true,
  data: true, // For `<object />` acts as `src`.
  dateTime: true,
  decoding: true,
  default: true,
  defer: true,
  dir: true,
  disabled: true,
  disablePictureInPicture: true,
  download: true,
  draggable: true,
  encType: true,
  form: true,
  formAction: true,
  formEncType: true,
  formMethod: true,
  formNoValidate: true,
  formTarget: true,
  frameBorder: true,
  headers: true,
  height: true,
  hidden: true,
  high: true,
  href: true,
  hrefLang: true,
  htmlFor: true,
  httpEquiv: true,
  id: true,
  inputMode: true,
  integrity: true,
  is: true,
  keyParams: true,
  keyType: true,
  kind: true,
  label: true,
  lang: true,
  list: true,
  loading: true,
  loop: true,
  low: true,
  // manifest: true,
  marginHeight: true,
  marginWidth: true,
  max: true,
  maxLength: true,
  media: true,
  mediaGroup: true,
  method: true,
  min: true,
  minLength: true,
  // Caution; `option.selected` is not updated if `select.multiple` is
  // disabled with `removeAttribute`.
  multiple: true,
  muted: true,
  name: true,
  nonce: true,
  noValidate: true,
  open: true,
  optimum: true,
  pattern: true,
  placeholder: true,
  playsInline: true,
  poster: true,
  preload: true,
  profile: true,
  radioGroup: true,
  readOnly: true,
  referrerPolicy: true,
  rel: true,
  required: true,
  reversed: true,
  role: true,
  rows: true,
  rowSpan: true,
  sandbox: true,
  scope: true,
  scoped: true,
  scrolling: true,
  seamless: true,
  selected: true,
  shape: true,
  size: true,
  sizes: true,
  // support for projecting regular DOM Elements via V1 named slots ( shadow dom )
  slot: true,
  span: true,
  spellCheck: true,
  src: true,
  srcDoc: true,
  srcLang: true,
  srcSet: true,
  start: true,
  step: true,
  style: true,
  summary: true,
  tabIndex: true,
  target: true,
  title: true,
  translate: true,
  // Setting .type throws on non-<input> tags
  type: true,
  useMap: true,
  value: true,
  width: true,
  wmode: true,
  wrap: true,

  /**
   * RDFa Properties
   */
  about: true,
  datatype: true,
  inlist: true,
  prefix: true,
  // property is also supported for OpenGraph in meta tags.
  property: true,
  resource: true,
  typeof: true,
  vocab: true,

  /**
   * Non-standard Properties
   */
  // autoCapitalize and autoCorrect are supported in Mobile Safari for
  // keyboard hints.
  autoCapitalize: true,
  autoCorrect: true,
  // autoSave allows WebKit/Blink to persist values of input fields on page reloads
  autoSave: true,
  // color is for Safari mask-icon link
  color: true,
  // used in amp html for indicating the fallback behavior
  // https://amp.dev/documentation/guides-and-tutorials/develop/style_and_layout/placeholders/
  fallback: true,
  // https://html.spec.whatwg.org/multipage/interaction.html#inert
  inert: true,
  // itemProp, itemScope, itemType are for
  // Microdata support. See http://schema.org/docs/gs.html
  itemProp: true,
  itemScope: true,
  itemType: true,
  // itemID and itemRef are for Microdata support as well but
  // only specified in the WHATWG spec document. See
  // https://html.spec.whatwg.org/multipage/microdata.html#microdata-dom-api
  itemID: true,
  itemRef: true,
  // used in amp html for eventing purposes
  // https://amp.dev/documentation/guides-and-tutorials/learn/common_attributes/
  on: true,
  // used in amp html for indicating that the option is selectable
  // https://amp.dev/documentation/components/amp-selector/
  option: true,
  // results show looking glass icon and recent searches on input
  // search fields in WebKit/Blink
  results: true,
  // IE-only attribute that specifies security restrictions on an iframe
  // as an alternative to the sandbox attribute on IE<1true
  security: true,
  // IE-only attribute that controls focus behavior
  unselectable: true,
  //
  // SVG properties: https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute
  // The following "onX" events have been omitted:
  //
  //  onabort
  //  onactivate
  //  onbegin
  //  onclick
  //  onend
  //  onerror
  //  onfocusin
  //  onfocusout
  //  onload
  //  onmousedown
  //  onmousemove
  //  onmouseout
  //  onmouseover
  //  onmouseup
  //  onrepeat
  //  onresize
  //  onscroll
  //  onunload
  accentHeight: true,
  accumulate: true,
  additive: true,
  alignmentBaseline: true,
  allowReorder: true,
  alphabetic: true,
  amplitude: true,
  arabicForm: true,
  ascent: true,
  attributeName: true,
  attributeType: true,
  autoReverse: true,
  azimuth: true,
  baseFrequency: true,
  baselineShift: true,
  baseProfile: true,
  bbox: true,
  begin: true,
  bias: true,
  by: true,
  calcMode: true,
  capHeight: true,
  clip: true,
  clipPathUnits: true,
  clipPath: true,
  clipRule: true,
  colorInterpolation: true,
  colorInterpolationFilters: true,
  colorProfile: true,
  colorRendering: true,
  contentScriptType: true,
  contentStyleType: true,
  cursor: true,
  cx: true,
  cy: true,
  d: true,
  decelerate: true,
  descent: true,
  diffuseConstant: true,
  direction: true,
  display: true,
  divisor: true,
  dominantBaseline: true,
  dur: true,
  dx: true,
  dy: true,
  edgeMode: true,
  elevation: true,
  enableBackground: true,
  end: true,
  exponent: true,
  externalResourcesRequired: true,
  fill: true,
  fillOpacity: true,
  fillRule: true,
  filter: true,
  filterRes: true,
  filterUnits: true,
  floodColor: true,
  floodOpacity: true,
  focusable: true,
  fontFamily: true,
  fontSize: true,
  fontSizeAdjust: true,
  fontStretch: true,
  fontStyle: true,
  fontVariant: true,
  fontWeight: true,
  format: true,
  from: true,
  fr: true, // valid SVG element but React will ask for removal
  fx: true,
  fy: true,
  g1: true,
  g2: true,
  glyphName: true,
  glyphOrientationHorizontal: true,
  glyphOrientationVertical: true,
  glyphRef: true,
  gradientTransform: true,
  gradientUnits: true,
  hanging: true,
  horizAdvX: true,
  horizOriginX: true,
  ideographic: true,
  imageRendering: true,
  in: true,
  in2: true,
  intercept: true,
  k: true,
  k1: true,
  k2: true,
  k3: true,
  k4: true,
  kernelMatrix: true,
  kernelUnitLength: true,
  kerning: true,
  keyPoints: true,
  keySplines: true,
  keyTimes: true,
  lengthAdjust: true,
  letterSpacing: true,
  lightingColor: true,
  limitingConeAngle: true,
  local: true,
  markerEnd: true,
  markerMid: true,
  markerStart: true,
  markerHeight: true,
  markerUnits: true,
  markerWidth: true,
  mask: true,
  maskContentUnits: true,
  maskUnits: true,
  mathematical: true,
  mode: true,
  numOctaves: true,
  offset: true,
  opacity: true,
  operator: true,
  order: true,
  orient: true,
  orientation: true,
  origin: true,
  overflow: true,
  overlinePosition: true,
  overlineThickness: true,
  panose1: true,
  paintOrder: true,
  pathLength: true,
  patternContentUnits: true,
  patternTransform: true,
  patternUnits: true,
  pointerEvents: true,
  points: true,
  pointsAtX: true,
  pointsAtY: true,
  pointsAtZ: true,
  preserveAlpha: true,
  preserveAspectRatio: true,
  primitiveUnits: true,
  r: true,
  radius: true,
  refX: true,
  refY: true,
  renderingIntent: true,
  repeatCount: true,
  repeatDur: true,
  requiredExtensions: true,
  requiredFeatures: true,
  restart: true,
  result: true,
  rotate: true,
  rx: true,
  ry: true,
  scale: true,
  seed: true,
  shapeRendering: true,
  slope: true,
  spacing: true,
  specularConstant: true,
  specularExponent: true,
  speed: true,
  spreadMethod: true,
  startOffset: true,
  stdDeviation: true,
  stemh: true,
  stemv: true,
  stitchTiles: true,
  stopColor: true,
  stopOpacity: true,
  strikethroughPosition: true,
  strikethroughThickness: true,
  string: true,
  stroke: true,
  strokeDasharray: true,
  strokeDashoffset: true,
  strokeLinecap: true,
  strokeLinejoin: true,
  strokeMiterlimit: true,
  strokeOpacity: true,
  strokeWidth: true,
  surfaceScale: true,
  systemLanguage: true,
  tableValues: true,
  targetX: true,
  targetY: true,
  textAnchor: true,
  textDecoration: true,
  textRendering: true,
  textLength: true,
  to: true,
  transform: true,
  u1: true,
  u2: true,
  underlinePosition: true,
  underlineThickness: true,
  unicode: true,
  unicodeBidi: true,
  unicodeRange: true,
  unitsPerEm: true,
  vAlphabetic: true,
  vHanging: true,
  vIdeographic: true,
  vMathematical: true,
  values: true,
  vectorEffect: true,
  version: true,
  vertAdvY: true,
  vertOriginX: true,
  vertOriginY: true,
  viewBox: true,
  viewTarget: true,
  visibility: true,
  widths: true,
  wordSpacing: true,
  writingMode: true,
  x: true,
  xHeight: true,
  x1: true,
  x2: true,
  xChannelSelector: true,
  xlinkActuate: true,
  xlinkArcrole: true,
  xlinkHref: true,
  xlinkRole: true,
  xlinkShow: true,
  xlinkTitle: true,
  xlinkType: true,
  xmlBase: true,
  xmlns: true,
  xmlnsXlink: true,
  xmlLang: true,
  xmlSpace: true,
  y: true,
  y1: true,
  y2: true,
  yChannelSelector: true,
  z: true,
  zoomAndPan: true,
  // preact
  for: true,
  class: true,
  autofocus: true
}
// eslint-disable-next-line import/no-commonjs
module.exports = `/^((${Object.keys(props).join(
  '|'
)})|(([Dd][Aa][Tt][Aa]|[Aa][Rr][Ii][Aa]|x)-.*))$/`
<commit_msg>add incremental prop (#2191)<commit_after>// @flow
const props = {
  // react props
  // https://github.com/facebook/react/blob/5495a7f24aef85ba6937truetrue1ce962673ca9f5fde6/src/renderers/dom/shared/hooks/ReactDOMUnknownPropertyHook.js
  children: true,
  dangerouslySetInnerHTML: true,
  key: true,
  ref: true,
  autoFocus: true,
  defaultValue: true,
  defaultChecked: true,
  innerHTML: true,
  suppressContentEditableWarning: true,
  suppressHydrationWarning: true,
  // deprecated react prop
  valueLink: true,

  // https://github.com/facebook/react/blob/d7157651f7b72d9888ctrue123e191f9b88cd8f41e9/src/renderers/dom/shared/HTMLDOMPropertyConfig.js
  /**
   * Standard Properties
   */

  accept: true,
  acceptCharset: true,
  accessKey: true,
  action: true,
  allow: true,
  allowUserMedia: true,
  allowPaymentRequest: true,
  allowFullScreen: true,
  allowTransparency: true,
  alt: true,
  // specifies target context for links with `preload` type
  // as: true,
  async: true,
  autoComplete: true,
  // autoFocus is polyfilled/normalized by AutoFocusUtils
  // autoFocus: true,
  autoPlay: true,
  capture: true,
  cellPadding: true,
  cellSpacing: true,
  // keygen prop
  challenge: true,
  charSet: true,
  checked: true,
  cite: true,
  classID: true,
  className: true,
  cols: true,
  colSpan: true,
  content: true,
  contentEditable: true,
  contextMenu: true,
  controls: true,
  controlsList: true,
  coords: true,
  crossOrigin: true,
  data: true, // For `<object />` acts as `src`.
  dateTime: true,
  decoding: true,
  default: true,
  defer: true,
  dir: true,
  disabled: true,
  disablePictureInPicture: true,
  download: true,
  draggable: true,
  encType: true,
  form: true,
  formAction: true,
  formEncType: true,
  formMethod: true,
  formNoValidate: true,
  formTarget: true,
  frameBorder: true,
  headers: true,
  height: true,
  hidden: true,
  high: true,
  href: true,
  hrefLang: true,
  htmlFor: true,
  httpEquiv: true,
  id: true,
  inputMode: true,
  integrity: true,
  is: true,
  keyParams: true,
  keyType: true,
  kind: true,
  label: true,
  lang: true,
  list: true,
  loading: true,
  loop: true,
  low: true,
  // manifest: true,
  marginHeight: true,
  marginWidth: true,
  max: true,
  maxLength: true,
  media: true,
  mediaGroup: true,
  method: true,
  min: true,
  minLength: true,
  // Caution; `option.selected` is not updated if `select.multiple` is
  // disabled with `removeAttribute`.
  multiple: true,
  muted: true,
  name: true,
  nonce: true,
  noValidate: true,
  open: true,
  optimum: true,
  pattern: true,
  placeholder: true,
  playsInline: true,
  poster: true,
  preload: true,
  profile: true,
  radioGroup: true,
  readOnly: true,
  referrerPolicy: true,
  rel: true,
  required: true,
  reversed: true,
  role: true,
  rows: true,
  rowSpan: true,
  sandbox: true,
  scope: true,
  scoped: true,
  scrolling: true,
  seamless: true,
  selected: true,
  shape: true,
  size: true,
  sizes: true,
  // support for projecting regular DOM Elements via V1 named slots ( shadow dom )
  slot: true,
  span: true,
  spellCheck: true,
  src: true,
  srcDoc: true,
  srcLang: true,
  srcSet: true,
  start: true,
  step: true,
  style: true,
  summary: true,
  tabIndex: true,
  target: true,
  title: true,
  translate: true,
  // Setting .type throws on non-<input> tags
  type: true,
  useMap: true,
  value: true,
  width: true,
  wmode: true,
  wrap: true,

  /**
   * RDFa Properties
   */
  about: true,
  datatype: true,
  inlist: true,
  prefix: true,
  // property is also supported for OpenGraph in meta tags.
  property: true,
  resource: true,
  typeof: true,
  vocab: true,

  /**
   * Non-standard Properties
   */
  // autoCapitalize and autoCorrect are supported in Mobile Safari for
  // keyboard hints.
  autoCapitalize: true,
  autoCorrect: true,
  // autoSave allows WebKit/Blink to persist values of input fields on page reloads
  autoSave: true,
  // color is for Safari mask-icon link
  color: true,
  // https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/search#incremental_This_API_has_not_been_standardized
  incremental: true,
  // used in amp html for indicating the fallback behavior
  // https://amp.dev/documentation/guides-and-tutorials/develop/style_and_layout/placeholders/
  fallback: true,
  // https://html.spec.whatwg.org/multipage/interaction.html#inert
  inert: true,
  // itemProp, itemScope, itemType are for
  // Microdata support. See http://schema.org/docs/gs.html
  itemProp: true,
  itemScope: true,
  itemType: true,
  // itemID and itemRef are for Microdata support as well but
  // only specified in the WHATWG spec document. See
  // https://html.spec.whatwg.org/multipage/microdata.html#microdata-dom-api
  itemID: true,
  itemRef: true,
  // used in amp html for eventing purposes
  // https://amp.dev/documentation/guides-and-tutorials/learn/common_attributes/
  on: true,
  // used in amp html for indicating that the option is selectable
  // https://amp.dev/documentation/components/amp-selector/
  option: true,
  // results show looking glass icon and recent searches on input
  // search fields in WebKit/Blink
  results: true,
  // IE-only attribute that specifies security restrictions on an iframe
  // as an alternative to the sandbox attribute on IE<1true
  security: true,
  // IE-only attribute that controls focus behavior
  unselectable: true,
  //
  // SVG properties: https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute
  // The following "onX" events have been omitted:
  //
  //  onabort
  //  onactivate
  //  onbegin
  //  onclick
  //  onend
  //  onerror
  //  onfocusin
  //  onfocusout
  //  onload
  //  onmousedown
  //  onmousemove
  //  onmouseout
  //  onmouseover
  //  onmouseup
  //  onrepeat
  //  onresize
  //  onscroll
  //  onunload
  accentHeight: true,
  accumulate: true,
  additive: true,
  alignmentBaseline: true,
  allowReorder: true,
  alphabetic: true,
  amplitude: true,
  arabicForm: true,
  ascent: true,
  attributeName: true,
  attributeType: true,
  autoReverse: true,
  azimuth: true,
  baseFrequency: true,
  baselineShift: true,
  baseProfile: true,
  bbox: true,
  begin: true,
  bias: true,
  by: true,
  calcMode: true,
  capHeight: true,
  clip: true,
  clipPathUnits: true,
  clipPath: true,
  clipRule: true,
  colorInterpolation: true,
  colorInterpolationFilters: true,
  colorProfile: true,
  colorRendering: true,
  contentScriptType: true,
  contentStyleType: true,
  cursor: true,
  cx: true,
  cy: true,
  d: true,
  decelerate: true,
  descent: true,
  diffuseConstant: true,
  direction: true,
  display: true,
  divisor: true,
  dominantBaseline: true,
  dur: true,
  dx: true,
  dy: true,
  edgeMode: true,
  elevation: true,
  enableBackground: true,
  end: true,
  exponent: true,
  externalResourcesRequired: true,
  fill: true,
  fillOpacity: true,
  fillRule: true,
  filter: true,
  filterRes: true,
  filterUnits: true,
  floodColor: true,
  floodOpacity: true,
  focusable: true,
  fontFamily: true,
  fontSize: true,
  fontSizeAdjust: true,
  fontStretch: true,
  fontStyle: true,
  fontVariant: true,
  fontWeight: true,
  format: true,
  from: true,
  fr: true, // valid SVG element but React will ask for removal
  fx: true,
  fy: true,
  g1: true,
  g2: true,
  glyphName: true,
  glyphOrientationHorizontal: true,
  glyphOrientationVertical: true,
  glyphRef: true,
  gradientTransform: true,
  gradientUnits: true,
  hanging: true,
  horizAdvX: true,
  horizOriginX: true,
  ideographic: true,
  imageRendering: true,
  in: true,
  in2: true,
  intercept: true,
  k: true,
  k1: true,
  k2: true,
  k3: true,
  k4: true,
  kernelMatrix: true,
  kernelUnitLength: true,
  kerning: true,
  keyPoints: true,
  keySplines: true,
  keyTimes: true,
  lengthAdjust: true,
  letterSpacing: true,
  lightingColor: true,
  limitingConeAngle: true,
  local: true,
  markerEnd: true,
  markerMid: true,
  markerStart: true,
  markerHeight: true,
  markerUnits: true,
  markerWidth: true,
  mask: true,
  maskContentUnits: true,
  maskUnits: true,
  mathematical: true,
  mode: true,
  numOctaves: true,
  offset: true,
  opacity: true,
  operator: true,
  order: true,
  orient: true,
  orientation: true,
  origin: true,
  overflow: true,
  overlinePosition: true,
  overlineThickness: true,
  panose1: true,
  paintOrder: true,
  pathLength: true,
  patternContentUnits: true,
  patternTransform: true,
  patternUnits: true,
  pointerEvents: true,
  points: true,
  pointsAtX: true,
  pointsAtY: true,
  pointsAtZ: true,
  preserveAlpha: true,
  preserveAspectRatio: true,
  primitiveUnits: true,
  r: true,
  radius: true,
  refX: true,
  refY: true,
  renderingIntent: true,
  repeatCount: true,
  repeatDur: true,
  requiredExtensions: true,
  requiredFeatures: true,
  restart: true,
  result: true,
  rotate: true,
  rx: true,
  ry: true,
  scale: true,
  seed: true,
  shapeRendering: true,
  slope: true,
  spacing: true,
  specularConstant: true,
  specularExponent: true,
  speed: true,
  spreadMethod: true,
  startOffset: true,
  stdDeviation: true,
  stemh: true,
  stemv: true,
  stitchTiles: true,
  stopColor: true,
  stopOpacity: true,
  strikethroughPosition: true,
  strikethroughThickness: true,
  string: true,
  stroke: true,
  strokeDasharray: true,
  strokeDashoffset: true,
  strokeLinecap: true,
  strokeLinejoin: true,
  strokeMiterlimit: true,
  strokeOpacity: true,
  strokeWidth: true,
  surfaceScale: true,
  systemLanguage: true,
  tableValues: true,
  targetX: true,
  targetY: true,
  textAnchor: true,
  textDecoration: true,
  textRendering: true,
  textLength: true,
  to: true,
  transform: true,
  u1: true,
  u2: true,
  underlinePosition: true,
  underlineThickness: true,
  unicode: true,
  unicodeBidi: true,
  unicodeRange: true,
  unitsPerEm: true,
  vAlphabetic: true,
  vHanging: true,
  vIdeographic: true,
  vMathematical: true,
  values: true,
  vectorEffect: true,
  version: true,
  vertAdvY: true,
  vertOriginX: true,
  vertOriginY: true,
  viewBox: true,
  viewTarget: true,
  visibility: true,
  widths: true,
  wordSpacing: true,
  writingMode: true,
  x: true,
  xHeight: true,
  x1: true,
  x2: true,
  xChannelSelector: true,
  xlinkActuate: true,
  xlinkArcrole: true,
  xlinkHref: true,
  xlinkRole: true,
  xlinkShow: true,
  xlinkTitle: true,
  xlinkType: true,
  xmlBase: true,
  xmlns: true,
  xmlnsXlink: true,
  xmlLang: true,
  xmlSpace: true,
  y: true,
  y1: true,
  y2: true,
  yChannelSelector: true,
  z: true,
  zoomAndPan: true,
  // preact
  for: true,
  class: true,
  autofocus: true
}
// eslint-disable-next-line import/no-commonjs
module.exports = `/^((${Object.keys(props).join(
  '|'
)})|(([Dd][Aa][Tt][Aa]|[Aa][Rr][Ii][Aa]|x)-.*))$/`
<|endoftext|>


<commit_before>/* ***********************************************************************************************

    Unify Project

    Homepage: unify-project.org
    License: MIT + Apache (V2)
    Copyright: 2011, Sebastian Fastner, Mainz, Germany, http://unify-training.com

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

/**
 * EXPERIMENTAL
 *
 * Overlay container widget
 */
qx.Class.define("unify.ui.container.Overlay", {
  extend : unify.ui.container.Composite,

  include : [unify.ui.core.MChildControl, qx.ui.core.MRemoteChildrenHandling],

  events : {
    /** Event thrown if overlay visibility is changed to hidden */
    "hidden" : "qx.event.type.Event",

    /** Event thrown if overlay visibility is changed to shown */
    "shown" : "qx.event.type.Event"
  },

  properties : {
    // overridden
    appearance : {
      refine: true,
      init: "overlay"
    },

    /** Paint arrow */
    hasArrow : {
      check: "Boolean",
      init: true,
      apply: "__applyHasArrow"
    },

    /** relative position of the arrow on its axis
     *
     * may be "left,right,center,top,bottom, a percentage of the axis size or a pixel value (relative to axis start)
     */
    relativeArrowPosition : {
      init: "left",
      nullable: true
    },

    /** optional reference to widget that triggers show/hide of this overlay */
    trigger : {
      check: "unify.ui.core.Widget",
      init: null,
      nullable: true
    },

     /** optional strategy to ponsition overlay relative to trigger
      * must be a map containing a value for x and y axis
      * the value can be "left,right,center,top,bottom, a percentage of the axis size or a pixel value (relative to axis start)
      */
    relativeTriggerPosition : {
      init: {x:"bottom",y:"center"},
      nullable: true
    }

  },

  /**
   * @param noArrow {Boolean?} set to true if overlay should not have an arrow element
   */
  construct : function(noArrow) {
    this.base(arguments, new unify.ui.layout.special.OverlayLayout());

    this._showChildControl("container");
    this.setHasArrow(!noArrow);//applyHasArrow creates the arrow if required
  },

  members : {

    /**
     * Gets inner content container
     *
     * @return {unify.ui.core.Widget} Content widget
     */
    getChildrenContainer : function() {
      return this.getChildControl("container");
    },

    /**
     * Returns child control widget identified by id
     *
     * @param id {String} ID of child widget
     * @return {unify.ui.core.Widget} Content widget
     */
    _createChildControlImpl : function(id) {
      var control;

      if (id == "arrow") {
        control = new unify.ui.other.Arrow();
        this._addAt(control, 1, {
          type: "arrow"
        });
      } else if (id == "container") {
        control = new unify.ui.container.Composite(new unify.ui.layout.Canvas());
        this._addAt(control, 0);
      }

      return control || this.base(arguments, id);
    },

    /**
     * shows/hides the arrow element depending on value
     * @param value {Boolean} new hasArrow value
     */
    __applyHasArrow : function(value) {
      if (value) {
        this._showChildControl("arrow");
      } else {
        this._excludeChildControl("arrow");
      }
    },
    //overridden, calculate overlaysize as content size + arrow size depending on arrow direction
    _computeSizeHint: function(){
      var hint=this.getChildrenContainer().getSizeHint();
      if(this.getHasArrow()){
        var arrow=this.getChildControl("arrow");
        var arrowHint=arrow.getSizeHint();
        var direction=arrow.getDirection();
        if(direction=="left"||direction=="right"){
          hint.width+=arrowHint.width;
        } else if(direction=="top"||direction=="bottom"){
          hint.height+=arrowHint.height;
        }
      }
      return hint;
    },

    /**
     * Calculates a position hint to align overlay to trigger widget
     *
     * if the overlay has an arrow, the arrows pointing edge is used as reference
     */
    __getPositionHint : function() {
      qx.ui.core.queue.Manager.flush();//make sure appearance is applied
      var left = 0;
      var top = 0;
      var trigger=this.getTrigger();
      var relativeTriggerPosition=this.getRelativeTriggerPosition();

      if(trigger && relativeTriggerPosition){
        var triggerPoint=this.__resolveRelative(trigger.getPositionInfo(),relativeTriggerPosition);
        left = triggerPoint.left;
        top=triggerPoint.top;
      }
      var arrow=this.getChildControl("arrow");
      if(arrow){
        var thisSize=this.getSizeHint();
        var arrowPosition=this.calculateArrowPosition(thisSize.height,thisSize.width);

        left-=arrowPosition.left;
        top-=arrowPosition.top;
        var arrowDirection=arrow.getDirection();

        //now account for arrow pointing edge offset
        //TODO at the moment we assume the pointing edge is in the middle, refactor into arrow class to allow arbitraty points
        var arrowSize=arrow.getSizeHint();
        if(arrowDirection=="left"||arrowDirection=="right"){
          top-=Math.round(arrowSize.height/2);
        } else if (arrowDirection=="bottom"||arrowDirection=="top"){
          left-=Math.round(arrowSize.width/2);
        }
      }

      return {
        left: left,
        top: top
      };
    },

    /**
     * calculate the left/top position of the arrow element on the overlay .
     *
     * this function is used by the layout and by __getPositionHint
     * @param height {Number} height of the overlay content
     * @param width {Number} width of the overlay content
     */
    calculateArrowPosition : function(height,width){
      var GAP = 6;//TODO use border width +1?
      var arrow = this.getChildControl("arrow");
      var arrowLeft=0;
      var arrowTop=0;

      if(arrow){
        var arrowWidth=arrow.getWidth();
        var arrowHeight=arrow.getHeight();
        var arrowDirection=arrow.getDirection();
        var arrowPosition=this.getRelativeArrowPosition();

        if(arrowDirection=="left" || arrowDirection=="right"){
          var relativeOffset=this.__toPixelValue(height,arrowPosition);
          if(arrowPosition=="top"){
            arrowTop=GAP;
          } else if(arrowPosition=="bottom"){
            arrowTop = height - arrowHeight - GAP;
          } else if(arrowPosition=="center"){
            arrowTop = Math.round(height / 2 - arrowHeight/2);
          } else {
            arrowTop = relativeOffset - Math.round(arrowHeight/2);
          }
        } else if (arrowDirection=="top" || arrowDirection=="bottom"){
          var relativeOffset=this.__toPixelValue(width,arrowPosition);
          if(arrowPosition=="left"){
            arrowLeft=GAP;
          } else if(arrowPosition=="right"){
            arrowLeft = width - arrowWidth - GAP;
          } else if(arrowPosition=="center"){
            arrowLeft = Math.round(width / 2 - arrowWidth/2);
          } else {
            arrowLeft = relativeOffset - Math.round(arrowWidth/2);
          }
        }
      }

      return {
        left: arrowLeft,
        top: arrowTop
      }
    },

    /**
     * helper function that calculates the absolute position values of a relativePos in elemPos
     * @param elemPos {Object}  a map containing the elements current position and dimensions (top,left,width,height)
     * @param relativePos {Object} a map containing relative position values as keys x and y e.g. {x:"center",y:"bottom"}
     */
    __resolveRelative: function(elemPos,relativePos){
      return {
        top: (elemPos.top||0)+this.__toPixelValue(elemPos.height,relativePos.x),
        left:(elemPos.left||0)+this.__toPixelValue(elemPos.width,relativePos.y)
      }
    },

    /**
     * calculates the pixel value of relativePosition in relation to baseSize
     *
     * @param baseSize {Number} size value to
     * @param relativePosition {String|Number} left,right,top,bottom,center, a percentage string, a px string or a Number
     * @return {Number} calculated value
     */
    __toPixelValue : function(baseSize,relativePosition){
      if(relativePosition=="left" || relativePosition == "top"){
        return 0;
      } else if (relativePosition == "center"){
        return Math.round(baseSize/2);
      } else if (relativePosition=="right" || relativePosition == "bottom"){
        return baseSize;
      } else if(typeof relativePosition == "string"){
        if(relativePosition.substring(relativePosition.length-1)=="%"){
          return Math.round(baseSize*(parseInt(relativePosition,10)/100));
        } else if(relativePosition.substring(relativePosition.length-2)=="px"){
          return parseInt(relativePosition,10);
        } else {
          //value is a string but cannot be parsed
          this.error("invalid relative value: "+relativePosition);
          return 0;
        }
      } else if(typeof relativePosition == "number") {
        return relativePosition;
      }
    },

    /**
     * Shows overlay
     */
    show : function() {
      this.base(arguments);
      var posHint = this.__getPositionHint();
      this.getLayoutParent().add(this, posHint);
      this.fireEvent("shown");
    },

    /**
     * Hides overlay
     */
    hide : function() {
      this.base(arguments);
      this.fireEvent("hidden");
    }
  }
});<commit_msg>logic fix: reverse usage of x and y axis in relativeTriggerPosition<commit_after>/* ***********************************************************************************************

    Unify Project

    Homepage: unify-project.org
    License: MIT + Apache (V2)
    Copyright: 2011, Sebastian Fastner, Mainz, Germany, http://unify-training.com

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

/**
 * EXPERIMENTAL
 *
 * Overlay container widget
 */
qx.Class.define("unify.ui.container.Overlay", {
  extend : unify.ui.container.Composite,

  include : [unify.ui.core.MChildControl, qx.ui.core.MRemoteChildrenHandling],

  events : {
    /** Event thrown if overlay visibility is changed to hidden */
    "hidden" : "qx.event.type.Event",

    /** Event thrown if overlay visibility is changed to shown */
    "shown" : "qx.event.type.Event"
  },

  properties : {
    // overridden
    appearance : {
      refine: true,
      init: "overlay"
    },

    /** Paint arrow */
    hasArrow : {
      check: "Boolean",
      init: true,
      apply: "__applyHasArrow"
    },

    /** relative position of the arrow on its axis
     *
     * may be "left,right,center,top,bottom, a percentage of the axis size or a pixel value (relative to axis start)
     */
    relativeArrowPosition : {
      init: "left",
      nullable: true
    },

    /** optional reference to widget that triggers show/hide of this overlay */
    trigger : {
      check: "unify.ui.core.Widget",
      init: null,
      nullable: true
    },

     /** optional strategy to ponsition overlay relative to trigger
      * must be a map containing a value for x and y axis
      * the value can be "left,right,center,top,bottom, a percentage of the axis size or a pixel value (relative to axis start)
      */
    relativeTriggerPosition : {
      init: {y:"bottom",x:"center"},
      nullable: true
    }

  },

  /**
   * @param noArrow {Boolean?} set to true if overlay should not have an arrow element
   */
  construct : function(noArrow) {
    this.base(arguments, new unify.ui.layout.special.OverlayLayout());

    this._showChildControl("container");
    this.setHasArrow(!noArrow);//applyHasArrow creates the arrow if required
  },

  members : {

    /**
     * Gets inner content container
     *
     * @return {unify.ui.core.Widget} Content widget
     */
    getChildrenContainer : function() {
      return this.getChildControl("container");
    },

    /**
     * Returns child control widget identified by id
     *
     * @param id {String} ID of child widget
     * @return {unify.ui.core.Widget} Content widget
     */
    _createChildControlImpl : function(id) {
      var control;

      if (id == "arrow") {
        control = new unify.ui.other.Arrow();
        this._addAt(control, 1, {
          type: "arrow"
        });
      } else if (id == "container") {
        control = new unify.ui.container.Composite(new unify.ui.layout.Canvas());
        this._addAt(control, 0);
      }

      return control || this.base(arguments, id);
    },

    /**
     * shows/hides the arrow element depending on value
     * @param value {Boolean} new hasArrow value
     */
    __applyHasArrow : function(value) {
      if (value) {
        this._showChildControl("arrow");
      } else {
        this._excludeChildControl("arrow");
      }
    },
    //overridden, calculate overlaysize as content size + arrow size depending on arrow direction
    _computeSizeHint: function(){
      var hint=this.getChildrenContainer().getSizeHint();
      if(this.getHasArrow()){
        var arrow=this.getChildControl("arrow");
        var arrowHint=arrow.getSizeHint();
        var direction=arrow.getDirection();
        if(direction=="left"||direction=="right"){
          hint.width+=arrowHint.width;
        } else if(direction=="top"||direction=="bottom"){
          hint.height+=arrowHint.height;
        }
      }
      return hint;
    },

    /**
     * Calculates a position hint to align overlay to trigger widget
     *
     * if the overlay has an arrow, the arrows pointing edge is used as reference
     */
    __getPositionHint : function() {
      qx.ui.core.queue.Manager.flush();//make sure appearance is applied
      var left = 0;
      var top = 0;
      var trigger=this.getTrigger();
      var relativeTriggerPosition=this.getRelativeTriggerPosition();

      if(trigger && relativeTriggerPosition){
        var triggerPoint=this.__resolveRelative(trigger.getPositionInfo(),relativeTriggerPosition);
        left = triggerPoint.left;
        top=triggerPoint.top;
      }
      var arrow=this.getChildControl("arrow");
      if(arrow){
        var thisSize=this.getSizeHint();
        var arrowPosition=this.calculateArrowPosition(thisSize.height,thisSize.width);

        left-=arrowPosition.left;
        top-=arrowPosition.top;
        var arrowDirection=arrow.getDirection();

        //now account for arrow pointing edge offset
        //TODO at the moment we assume the pointing edge is in the middle, refactor into arrow class to allow arbitraty points
        var arrowSize=arrow.getSizeHint();
        if(arrowDirection=="left"||arrowDirection=="right"){
          top-=Math.round(arrowSize.height/2);
        } else if (arrowDirection=="bottom"||arrowDirection=="top"){
          left-=Math.round(arrowSize.width/2);
        }
      }

      return {
        left: left,
        top: top
      };
    },

    /**
     * calculate the left/top position of the arrow element on the overlay .
     *
     * this function is used by the layout and by __getPositionHint
     * @param height {Number} height of the overlay content
     * @param width {Number} width of the overlay content
     */
    calculateArrowPosition : function(height,width){
      var GAP = 6;//TODO use border width +1?
      var arrow = this.getChildControl("arrow");
      var arrowLeft=0;
      var arrowTop=0;

      if(arrow){
        var arrowWidth=arrow.getWidth();
        var arrowHeight=arrow.getHeight();
        var arrowDirection=arrow.getDirection();
        var arrowPosition=this.getRelativeArrowPosition();

        if(arrowDirection=="left" || arrowDirection=="right"){
          var relativeOffset=this.__toPixelValue(height,arrowPosition);
          if(arrowPosition=="top"){
            arrowTop=GAP;
          } else if(arrowPosition=="bottom"){
            arrowTop = height - arrowHeight - GAP;
          } else if(arrowPosition=="center"){
            arrowTop = Math.round(height / 2 - arrowHeight/2);
          } else {
            arrowTop = relativeOffset - Math.round(arrowHeight/2);
          }
        } else if (arrowDirection=="top" || arrowDirection=="bottom"){
          var relativeOffset=this.__toPixelValue(width,arrowPosition);
          if(arrowPosition=="left"){
            arrowLeft=GAP;
          } else if(arrowPosition=="right"){
            arrowLeft = width - arrowWidth - GAP;
          } else if(arrowPosition=="center"){
            arrowLeft = Math.round(width / 2 - arrowWidth/2);
          } else {
            arrowLeft = relativeOffset - Math.round(arrowWidth/2);
          }
        }
      }

      return {
        left: arrowLeft,
        top: arrowTop
      }
    },

    /**
     * helper function that calculates the absolute position values of a relativePos in elemPos
     * @param elemPos {Object}  a map containing the elements current position and dimensions (top,left,width,height)
     * @param relativePos {Object} a map containing relative position values as keys x and y e.g. {x:"center",y:"bottom"}
     */
    __resolveRelative: function(elemPos,relativePos){
      return {
        top: (elemPos.top||0)+this.__toPixelValue(elemPos.height,relativePos.y),
        left:(elemPos.left||0)+this.__toPixelValue(elemPos.width,relativePos.x)
      }
    },

    /**
     * calculates the pixel value of relativePosition in relation to baseSize
     *
     * @param baseSize {Number} size value to
     * @param relativePosition {String|Number} left,right,top,bottom,center, a percentage string, a px string or a Number
     * @return {Number} calculated value
     */
    __toPixelValue : function(baseSize,relativePosition){
      if(relativePosition=="left" || relativePosition == "top"){
        return 0;
      } else if (relativePosition == "center"){
        return Math.round(baseSize/2);
      } else if (relativePosition=="right" || relativePosition == "bottom"){
        return baseSize;
      } else if(typeof relativePosition == "string"){
        if(relativePosition.substring(relativePosition.length-1)=="%"){
          return Math.round(baseSize*(parseInt(relativePosition,10)/100));
        } else if(relativePosition.substring(relativePosition.length-2)=="px"){
          return parseInt(relativePosition,10);
        } else {
          //value is a string but cannot be parsed
          this.error("invalid relative value: "+relativePosition);
          return 0;
        }
      } else if(typeof relativePosition == "number") {
        return relativePosition;
      }
    },

    /**
     * Shows overlay
     */
    show : function() {
      this.base(arguments);
      var posHint = this.__getPositionHint();
      this.getLayoutParent().add(this, posHint);
      this.fireEvent("shown");
    },

    /**
     * Hides overlay
     */
    hide : function() {
      this.base(arguments);
      this.fireEvent("hidden");
    }
  }
});<|endoftext|>


<commit_before>'use strict'

const Joi = require('joi')

const mapResult = result => {
  return {
    name: result.contract.name,
    consumer: result.contract.consumer,
    status: result.err ? 'Fail' : 'Pass',
    error: result.err ? result.err.toString() : null
  }
}

module.exports = mapResult
<commit_msg>Removed unused import<commit_after>'use strict'

const mapResult = result => {
  return {
    name: result.contract.name,
    consumer: result.contract.consumer,
    status: result.err ? 'Fail' : 'Pass',
    error: result.err ? result.err.toString() : null
  }
}

module.exports = mapResult
<|endoftext|>


<commit_before>import React, { PureComponent, createRef } from 'react';
import classnames from 'classnames';
import PropTypes from 'prop-types';
import ReactMapGL, { FlyToInterpolator, TRANSITION_EVENTS } from 'react-map-gl';
import WebMercatorViewport from 'viewport-mercator-project';
import isEqual from 'react-fast-compare';
import isEmpty from 'lodash/isEmpty';

// constants
import { DEFAULT_VIEWPORT } from './constants';

// styles
import './styles.scss';

class Map extends PureComponent {
  static propTypes = {
    /** A function that returns the map instance */
    children: PropTypes.func,

    /** Custom CSS class for styling */
    className: PropTypes.string,

    /** An object that defines the viewport
     * @see https://uber.github.io/react-map-gl/#/Documentation/api-reference/interactive-map?section=initialization
    */
    viewport: PropTypes.shape({}),

    /** An object that defines the bounds */
    bounds: PropTypes.shape({
      bbox: PropTypes.array,
      options: PropTypes.shape({})
    }),

    /** An object that defines how fitting bounds behaves */
    fitBoundsOptions: PropTypes.object,

    /** A string that defines the basemap to display */
    basemap: PropTypes.string.isRequired,

    /** A string that defines the type of label to display */
    labels: PropTypes.string,

    /** A string that defines if boundaries should be displayed */
    boundaries: PropTypes.bool,

    /** A boolean that allows panning */
    dragPan: PropTypes.bool,

    /** A boolean that allows rotating */
    dragRotate: PropTypes.bool,

    /** A boolean that allows zooming */
    scrollZoom: PropTypes.bool,

    /** A boolean that allows zooming */
    touchZoom: PropTypes.bool,

    /** A boolean that allows touch rotating */
    touchRotate: PropTypes.bool,

    /** A boolean that allows double click zooming */
    doubleClickZoom: PropTypes.bool,

    /** A function that exposes when the map is loaded.
     * It returns and object with the `this.map` and `this.mapContainer`
     * reference. */
    onLoad: PropTypes.func,

    /** function invoked if something is wrong */
    onError: PropTypes.func,

    /** A function that exposes the viewport */
    onViewportChange: PropTypes.func,

    /** A function that exposes the viewport */
    getCursor: PropTypes.func
  }

  static defaultProps = {
    children: null,
    className: null,
    viewport: DEFAULT_VIEWPORT,
    bounds: {},
    labels: null,
    boundaries: false,
    dragPan: true,
    dragRotate: true,
    scrollZoom: true,
    touchZoom: true,
    touchRotate: true,
    doubleClickZoom: true,
    fitBoundsOptions: { transitionDuration: 1500 },

    onViewportChange: () => {},
    onLoad: () => {},
    onError: null,
    getCursor: ({ isHovering, isDragging }) => {
      if (isHovering) return 'pointer';
      if (isDragging) return 'grabbing';
      return 'grab';
    }
  }

  state = {
    viewport: {
      ...DEFAULT_VIEWPORT,
      ...this.props.viewport
    },
    flying: false,
    loaded: false
  }

  componentDidUpdate(prevProps) {
    const {
      viewport: prevViewport,
      bounds: prevBounds,
      basemap: prevBasemap,
      labels: prevLabels,
      boundaries: prevBoundaries
    } = prevProps;
    const {
      viewport,
      bounds,
      labels,
      basemap,
      boundaries
    } = this.props;
    const { viewport: stateViewport } = this.state;
    const basemapChanged = prevBasemap !== basemap;
    const labelsChanged = prevLabels !== labels;
    const boundariesChanged = prevBoundaries !== boundaries;
    const boundsChanged = !isEqual(bounds, prevBounds);

    if (!isEqual(viewport, prevViewport)) {
      this.setState({ // eslint-disable-line
        viewport: {
          ...stateViewport,
          ...viewport
        }
      });
    }

    if (basemapChanged) this.setBasemap();
    if (labelsChanged) this.setLabels();
    if (boundariesChanged) this.setBoundaries();
    if (!isEmpty(bounds) && boundsChanged) this.fitBounds();
  }

  onLoad = () => {
    const { onLoad, bounds } = this.props;
    this.setState({ loaded: true });

    this.setBasemap();
    this.setLabels();
    this.setBoundaries();

    if (!isEmpty(bounds) && !!bounds.bbox) {
      this.fitBounds(0);
    }

    onLoad({
      map: this.map.current.getMap(),
      mapContainer: this.mapContainer.current
    });
  }

  onViewportChange = (_viewport) => {
    const { onViewportChange } = this.props;

    this.setState({ viewport: _viewport },
      () => { onViewportChange(_viewport); });
  }

  onResize = (_viewport) => {
    const { onViewportChange } = this.props;
    const { viewport } = this.state;
    const newViewport = {
      ...viewport,
      ..._viewport
    };

    this.setState({ viewport: newViewport });
    onViewportChange(newViewport);
  }

  setBasemap = () => {
    const { basemap } = this.props;
    const BASEMAP_GROUPS = ['basemap'];
    const { layers, metadata } = this.map.current.getMap().getStyle();

    const basemapGroups = Object.keys(metadata['mapbox:groups']).filter((k) => {
      const { name } = metadata['mapbox:groups'][k];

      const matchedGroups = BASEMAP_GROUPS.map(rgr => name.toLowerCase().includes(rgr));

      return matchedGroups.some(bool => bool);
    });

    const basemapsWithMeta = basemapGroups.map(_groupId => ({
      ...metadata['mapbox:groups'][_groupId],
      id: _groupId
    }));
    const basemapToDisplay = basemapsWithMeta.find(_basemap => _basemap.name.includes(basemap));

    const basemapLayers = layers.filter((l) => {
      const { metadata: layerMetadata } = l;
      if (!layerMetadata) return false;

      const gr = layerMetadata['mapbox:group'];
      return basemapGroups.includes(gr);
    });

    if (!basemapToDisplay) return false;

    basemapLayers.forEach((_layer) => {
      const match = _layer.metadata['mapbox:group'] === basemapToDisplay.id;
      if (!match) {
        this.map.current.getMap().setLayoutProperty(_layer.id, 'visibility', 'none');
      } else {
        this.map.current.getMap().setLayoutProperty(_layer.id, 'visibility', 'visible');
      }
    });

    return true;
  }

  setLabels = () => {
    const { labels } = this.props;

    const LABELS_GROUP = ['labels'];
    const { layers, metadata } = this.map.current.getMap().getStyle();

    const labelGroups = Object.keys(metadata['mapbox:groups']).filter((k) => {
      const { name } = metadata['mapbox:groups'][k];

      const matchedGroups = LABELS_GROUP.filter(rgr => name.toLowerCase().includes(rgr));

      return matchedGroups.some(bool => bool);
    });

    const labelsWithMeta = labelGroups.map(_groupId => ({
      ...metadata['mapbox:groups'][_groupId],
      id: _groupId
    }));
    const labelsToDisplay = labelsWithMeta.find(_basemap => _basemap.name.includes(labels)) || {};

    const labelLayers = layers.filter((l) => {
      const { metadata: layerMetadata } = l;
      if (!layerMetadata) return false;

      const gr = layerMetadata['mapbox:group'];
      return labelGroups.includes(gr);
    });

    labelLayers.forEach((_layer) => {
      const match = _layer.metadata['mapbox:group'] === labelsToDisplay.id;
      this.map.current.getMap().setLayoutProperty(_layer.id, 'visibility', match ? 'visible' : 'none');
    });

    return true;
  }

  setBoundaries = () => {
    const { boundaries } = this.props;
    const LABELS_GROUP = ['boundaries'];
    const { layers, metadata } = this.map.current.getMap().getStyle();

    const boundariesGroups = Object.keys(metadata['mapbox:groups']).filter((k) => {
      const { name } = metadata['mapbox:groups'][k];

      const labelsGroup = LABELS_GROUP.map(rgr => name.toLowerCase().includes(rgr));

      return labelsGroup.some(bool => bool);
    });

    const boundariesLayers = layers.filter((l) => {
      const { metadata: layerMetadata } = l;
      if (!layerMetadata) return false;

      const gr = layerMetadata['mapbox:group'];
      return boundariesGroups.includes(gr);
    });

    boundariesLayers.forEach((l) => {
      this.map.current.getMap().setLayoutProperty(l.id, 'visibility', boundaries ? 'visible' : 'none');
    });
  }

  map = createRef();

  mapContainer = createRef();

  fitBounds = () => {
    const { viewport: currentViewport } = this.state;
    const {
      bounds,
      onViewportChange,
      fitBoundsOptions,
      onError,
    } = this.props;
    const { bbox, options } = bounds;

    const viewport = {
      width: this.mapContainer.current.offsetWidth,
      height: this.mapContainer.current.offsetHeight,
      ...currentViewport,
    };

    try {
      const { longitude, latitude, zoom } = new WebMercatorViewport(viewport).fitBounds(
        [[bbox[0], bbox[1]], [bbox[2], bbox[3]]],
        options,
      );

      const newViewport = {
        ...currentViewport,
        longitude,
        latitude,
        zoom,
        ...fitBoundsOptions,
        transitionInterruption: TRANSITION_EVENTS.UPDATE,
      };

      this.setState({
        flying: true,
        viewport: newViewport,
      });
      onViewportChange(newViewport);
    } catch (e) {
      if (onError) onError('There was an error fitting bounds. Please, check your bbox values.');
    }

    setTimeout(() => {
      this.setState({ flying: false });
    }, 1500);
  };

  render() {
    const {
      className,
      children,
      getCursor,
      dragPan,
      dragRotate,
      scrollZoom,
      touchZoom,
      touchRotate,
      doubleClickZoom,
      disableEventsOnFly,
      ...mapboxProps
    } = this.props;
    const { viewport, flying, loaded } = this.state;

    return (
      <div
        ref={this.mapContainer}
        className={classnames({
          'c-map': true,
          [className]: !!className
        })}
      >
        <ReactMapGL
          ref={this.map}

          // CUSTOM PROPS FROM REACT MAPBOX API
          {...mapboxProps}

          // VIEWPORT
          {...viewport}
          width="100%"
          height="100%"

          // INTERACTIVE
          dragPan={!flying && dragPan}
          dragRotate={!flying && dragRotate}
          scrollZoom={!flying && scrollZoom}
          touchZoom={!flying && touchZoom}
          touchRotate={!flying && touchRotate}
          doubleClickZoom={!flying && doubleClickZoom}
          getCursor={getCursor}

          // DEFAULT FUC IMPLEMENTATIONS
          onViewportChange={this.onViewportChange}
          onResize={this.onResize}
          onLoad={this.onLoad}

          transitionInterpolator={new FlyToInterpolator()}
        >
          {loaded && !!this.map && typeof children === 'function' && children(this.map.current.getMap())}
        </ReactMapGL>
      </div>
    );
  }
}

export default Map;
<commit_msg>avoids passing onError function to MapGL map<commit_after>import React, { PureComponent, createRef } from 'react';
import classnames from 'classnames';
import PropTypes from 'prop-types';
import ReactMapGL, { FlyToInterpolator, TRANSITION_EVENTS } from 'react-map-gl';
import WebMercatorViewport from 'viewport-mercator-project';
import isEqual from 'react-fast-compare';
import isEmpty from 'lodash/isEmpty';

// constants
import { DEFAULT_VIEWPORT } from './constants';

// styles
import './styles.scss';

class Map extends PureComponent {
  static propTypes = {
    /** A function that returns the map instance */
    children: PropTypes.func,

    /** Custom CSS class for styling */
    className: PropTypes.string,

    /** An object that defines the viewport
     * @see https://uber.github.io/react-map-gl/#/Documentation/api-reference/interactive-map?section=initialization
    */
    viewport: PropTypes.shape({}),

    /** An object that defines the bounds */
    bounds: PropTypes.shape({
      bbox: PropTypes.array,
      options: PropTypes.shape({})
    }),

    /** An object that defines how fitting bounds behaves */
    fitBoundsOptions: PropTypes.object,

    /** A string that defines the basemap to display */
    basemap: PropTypes.string.isRequired,

    /** A string that defines the type of label to display */
    labels: PropTypes.string,

    /** A string that defines if boundaries should be displayed */
    boundaries: PropTypes.bool,

    /** A boolean that allows panning */
    dragPan: PropTypes.bool,

    /** A boolean that allows rotating */
    dragRotate: PropTypes.bool,

    /** A boolean that allows zooming */
    scrollZoom: PropTypes.bool,

    /** A boolean that allows zooming */
    touchZoom: PropTypes.bool,

    /** A boolean that allows touch rotating */
    touchRotate: PropTypes.bool,

    /** A boolean that allows double click zooming */
    doubleClickZoom: PropTypes.bool,

    /** A function that exposes when the map is loaded.
     * It returns and object with the `this.map` and `this.mapContainer`
     * reference. */
    onLoad: PropTypes.func,

    /** function invoked if something is wrong */
    onError: PropTypes.func,

    /** A function that exposes the viewport */
    onViewportChange: PropTypes.func,

    /** A function that exposes the viewport */
    getCursor: PropTypes.func
  }

  static defaultProps = {
    children: null,
    className: null,
    viewport: DEFAULT_VIEWPORT,
    bounds: {},
    labels: null,
    boundaries: false,
    dragPan: true,
    dragRotate: true,
    scrollZoom: true,
    touchZoom: true,
    touchRotate: true,
    doubleClickZoom: true,
    fitBoundsOptions: { transitionDuration: 1500 },

    onViewportChange: () => {},
    onLoad: () => {},
    onError: null,
    getCursor: ({ isHovering, isDragging }) => {
      if (isHovering) return 'pointer';
      if (isDragging) return 'grabbing';
      return 'grab';
    }
  }

  state = {
    viewport: {
      ...DEFAULT_VIEWPORT,
      ...this.props.viewport
    },
    flying: false,
    loaded: false
  }

  componentDidUpdate(prevProps) {
    const {
      viewport: prevViewport,
      bounds: prevBounds,
      basemap: prevBasemap,
      labels: prevLabels,
      boundaries: prevBoundaries
    } = prevProps;
    const {
      viewport,
      bounds,
      labels,
      basemap,
      boundaries
    } = this.props;
    const { viewport: stateViewport } = this.state;
    const basemapChanged = prevBasemap !== basemap;
    const labelsChanged = prevLabels !== labels;
    const boundariesChanged = prevBoundaries !== boundaries;
    const boundsChanged = !isEqual(bounds, prevBounds);

    if (!isEqual(viewport, prevViewport)) {
      this.setState({ // eslint-disable-line
        viewport: {
          ...stateViewport,
          ...viewport
        }
      });
    }

    if (basemapChanged) this.setBasemap();
    if (labelsChanged) this.setLabels();
    if (boundariesChanged) this.setBoundaries();
    if (!isEmpty(bounds) && boundsChanged) this.fitBounds();
  }

  onLoad = () => {
    const { onLoad, bounds } = this.props;
    this.setState({ loaded: true });

    this.setBasemap();
    this.setLabels();
    this.setBoundaries();

    if (!isEmpty(bounds) && !!bounds.bbox) {
      this.fitBounds(0);
    }

    onLoad({
      map: this.map.current.getMap(),
      mapContainer: this.mapContainer.current
    });
  }

  onViewportChange = (_viewport) => {
    const { onViewportChange } = this.props;

    this.setState({ viewport: _viewport },
      () => { onViewportChange(_viewport); });
  }

  onResize = (_viewport) => {
    const { onViewportChange } = this.props;
    const { viewport } = this.state;
    const newViewport = {
      ...viewport,
      ..._viewport
    };

    this.setState({ viewport: newViewport });
    onViewportChange(newViewport);
  }

  setBasemap = () => {
    const { basemap } = this.props;
    const BASEMAP_GROUPS = ['basemap'];
    const { layers, metadata } = this.map.current.getMap().getStyle();

    const basemapGroups = Object.keys(metadata['mapbox:groups']).filter((k) => {
      const { name } = metadata['mapbox:groups'][k];

      const matchedGroups = BASEMAP_GROUPS.map(rgr => name.toLowerCase().includes(rgr));

      return matchedGroups.some(bool => bool);
    });

    const basemapsWithMeta = basemapGroups.map(_groupId => ({
      ...metadata['mapbox:groups'][_groupId],
      id: _groupId
    }));
    const basemapToDisplay = basemapsWithMeta.find(_basemap => _basemap.name.includes(basemap));

    const basemapLayers = layers.filter((l) => {
      const { metadata: layerMetadata } = l;
      if (!layerMetadata) return false;

      const gr = layerMetadata['mapbox:group'];
      return basemapGroups.includes(gr);
    });

    if (!basemapToDisplay) return false;

    basemapLayers.forEach((_layer) => {
      const match = _layer.metadata['mapbox:group'] === basemapToDisplay.id;
      if (!match) {
        this.map.current.getMap().setLayoutProperty(_layer.id, 'visibility', 'none');
      } else {
        this.map.current.getMap().setLayoutProperty(_layer.id, 'visibility', 'visible');
      }
    });

    return true;
  }

  setLabels = () => {
    const { labels } = this.props;

    const LABELS_GROUP = ['labels'];
    const { layers, metadata } = this.map.current.getMap().getStyle();

    const labelGroups = Object.keys(metadata['mapbox:groups']).filter((k) => {
      const { name } = metadata['mapbox:groups'][k];

      const matchedGroups = LABELS_GROUP.filter(rgr => name.toLowerCase().includes(rgr));

      return matchedGroups.some(bool => bool);
    });

    const labelsWithMeta = labelGroups.map(_groupId => ({
      ...metadata['mapbox:groups'][_groupId],
      id: _groupId
    }));
    const labelsToDisplay = labelsWithMeta.find(_basemap => _basemap.name.includes(labels)) || {};

    const labelLayers = layers.filter((l) => {
      const { metadata: layerMetadata } = l;
      if (!layerMetadata) return false;

      const gr = layerMetadata['mapbox:group'];
      return labelGroups.includes(gr);
    });

    labelLayers.forEach((_layer) => {
      const match = _layer.metadata['mapbox:group'] === labelsToDisplay.id;
      this.map.current.getMap().setLayoutProperty(_layer.id, 'visibility', match ? 'visible' : 'none');
    });

    return true;
  }

  setBoundaries = () => {
    const { boundaries } = this.props;
    const LABELS_GROUP = ['boundaries'];
    const { layers, metadata } = this.map.current.getMap().getStyle();

    const boundariesGroups = Object.keys(metadata['mapbox:groups']).filter((k) => {
      const { name } = metadata['mapbox:groups'][k];

      const labelsGroup = LABELS_GROUP.map(rgr => name.toLowerCase().includes(rgr));

      return labelsGroup.some(bool => bool);
    });

    const boundariesLayers = layers.filter((l) => {
      const { metadata: layerMetadata } = l;
      if (!layerMetadata) return false;

      const gr = layerMetadata['mapbox:group'];
      return boundariesGroups.includes(gr);
    });

    boundariesLayers.forEach((l) => {
      this.map.current.getMap().setLayoutProperty(l.id, 'visibility', boundaries ? 'visible' : 'none');
    });
  }

  map = createRef();

  mapContainer = createRef();

  fitBounds = () => {
    const { viewport: currentViewport } = this.state;
    const {
      bounds,
      onViewportChange,
      fitBoundsOptions,
      onError,
    } = this.props;
    const { bbox, options } = bounds;

    const viewport = {
      width: this.mapContainer.current.offsetWidth,
      height: this.mapContainer.current.offsetHeight,
      ...currentViewport,
    };

    try {
      const { longitude, latitude, zoom } = new WebMercatorViewport(viewport).fitBounds(
        [[bbox[0], bbox[1]], [bbox[2], bbox[3]]],
        options,
      );

      const newViewport = {
        ...currentViewport,
        longitude,
        latitude,
        zoom,
        ...fitBoundsOptions,
        transitionInterruption: TRANSITION_EVENTS.UPDATE,
      };

      this.setState({
        flying: true,
        viewport: newViewport,
      });
      onViewportChange(newViewport);
    } catch (e) {
      if (onError) onError('There was an error fitting bounds. Please, check your bbox values.');
    }

    setTimeout(() => {
      this.setState({ flying: false });
    }, 1500);
  };

  render() {
    const {
      className,
      children,
      getCursor,
      dragPan,
      dragRotate,
      scrollZoom,
      touchZoom,
      touchRotate,
      doubleClickZoom,
      disableEventsOnFly,
      onError,
      ...mapboxProps
    } = this.props;
    const { viewport, flying, loaded } = this.state;

    return (
      <div
        ref={this.mapContainer}
        className={classnames({
          'c-map': true,
          [className]: !!className
        })}
      >
        <ReactMapGL
          ref={this.map}

          // CUSTOM PROPS FROM REACT MAPBOX API
          {...mapboxProps}

          // VIEWPORT
          {...viewport}
          width="100%"
          height="100%"

          // INTERACTIVE
          dragPan={!flying && dragPan}
          dragRotate={!flying && dragRotate}
          scrollZoom={!flying && scrollZoom}
          touchZoom={!flying && touchZoom}
          touchRotate={!flying && touchRotate}
          doubleClickZoom={!flying && doubleClickZoom}
          getCursor={getCursor}

          // DEFAULT FUC IMPLEMENTATIONS
          onViewportChange={this.onViewportChange}
          onResize={this.onResize}
          onLoad={this.onLoad}

          transitionInterpolator={new FlyToInterpolator()}
        >
          {loaded && !!this.map && typeof children === 'function' && children(this.map.current.getMap())}
        </ReactMapGL>
      </div>
    );
  }
}

export default Map;
<|endoftext|>


<commit_before>// Imports
import express from 'express';
import graphqlHTTP from 'express-graphql';
// Relative imports
import Schema from '../graphql/schema';

// Setting up environment
const router = express.Router();

router.use('/graphql', graphqlHTTP({
  schema: Schema,
  graphiql: true,
}));
<commit_msg>Updating graphql route<commit_after>// Imports
import express from 'express';
import graphqlHTTP from 'express-graphql';
// Relative imports
import Schema from '../graphql/schema';

// Setting up environment
const router = express.Router();

router.use('/', graphqlHTTP({
  schema: Schema,
  graphiql: true,
}));
<|endoftext|>


<commit_before>var APIKEY = require('./config.js').key;
var _ = require('underscore.deferred');
var I = require('inflection');
var request = require('request');
var article = require('./lib/indefinite');
var Wordnik = require('wordnik-bb').init(APIKEY);

var express = require('express'),
  app = express();
app.use(express.logger());
app.listen(3000);
console.log('Express server started on port 3000');

function getCoupletPromise() {

  var coupletDeferred = _.Deferred();
  var coupletPromise = coupletDeferred.promise();

  var url = "http://api.wordnik.com//v4/words.json/randomWord?includePartOfSpeech=noun&excludePartOfSpeech=proper-noun,proper-noun-plural,proper-noun-posessive,suffix,family-name,idiom,affix&minCorpusCount=5000&api_key=" + APIKEY;
  var rwDeferred = _.Deferred();
  var randomWordPromise = rwDeferred.promise();
  request({
    url: url
  }, function (error, response, body) {
    if (!error && response.statusCode === 200) {
      //console.log(JSON.parse(body).word);
      //console.log(I.singularize(JSON.parse(body).word));
      var word = new Wordnik.Word({
        word: I.singularize(JSON.parse(body).word),
        params: {
          relationshipTypes: 'rhyme',
          limitPerRelationshipType: 100,
          hasDictionaryDef: true
        }
      });
      rwDeferred.resolve(word);

    }
    else {
      rwDeferred.reject(error);
    }
  });

  randomWordPromise.done(function (word) {
    //console.log("The model for our random word: ", word);
    // We could also get more info about the random word, in this case, relatedWords that rhyme:
    _.when(word.getRelatedWords())
      .then(function () {
      if (word.get("relatedWords").length > 0) {
//        var wordPos = word.get("definitions")[0].partOfSpeech;
        var first = getLine(word.id, 'noun');
        if (first === "") {
          coupletDeferred.resolve(result);
        }
        else {
          var word2 = word.get("relatedWords")[0].words[Math.floor(Math.random() * word.get("relatedWords")[0].words.length)];
          var posPromise = getPartOfSpeech(word2);
          (function (first, word2) {

            posPromise.done(function (pos) {
              var result = "oops!";
              result = getLine(word2, pos);
              if (result === "") {
                coupletDeferred.resolve(result);
              }
              else {
                coupletDeferred.resolve(first + "\n
" + result + "\n
");
              }
            });
          })(first, word2);
        }
      }
      else {
        //coupletDeferred.resolve("Sorry. We couldn't find anything that rhymes with " + word.id + "!");
        coupletDeferred.resolve("");
      }
    });
  });
  return coupletDeferred.promise();
}

app.get('/', function (req, res) {

  var cypher = "";

  var stuffToDo = [];
  for (var i = 0; i < 12; i++) {
    var cp = getCoupletPromise();
    cp.done(function (couplet) {
      if (couplet !== "") {
        cypher += (couplet);
      }
    });
    stuffToDo.push(cp);
  }

  _.when(stuffToDo).done(function () {
    //console.log(cypher);
    //console.log('*drops the mic*');
    cypher += "
*drops the mic*";
    res.send('<!doctype html><title>Freestyle 80s Battle Rap Generator</title>
Freestyle 80s Battle Rap Generator

' + cypher + '
');

  });

});

function getPartOfSpeech(wordId) {
  // accepts a word string
  var word = new Wordnik.Word({
    word: wordId,
    params: {
      includeSuggestions: true
    }
  });
  var deferred = _.Deferred();
  word.getDefinitions()
    .then(function (word) {
    deferred.resolve(word.get("definitions")[0].partOfSpeech);
  });
  return deferred.promise();
}

function ladiesFellas() {
  return (Math.random() < 0.5) ? "ladies" : "fellas";
}

function womanMan() {
  return (Math.random() < 0.5) ? "woman" : "man";
}

function sistasHomies() {
  return (Math.random() < 0.5) ? "sistas" : "homies";
}

function w(word) {
  return "" + word + "";
}

function getLine(word, pos) {

  var result = "Oops, we didn't account for something.";

  if (pos === 'adjective') {
    var pre = [
      "You can try and battle me, but you're too ",
      "I make the MCs in the place wish that they were ",
      "My rhymes blow your mind and you think it's ",
      "My sweet-ass rhymes make your " + womanMan() + " feel ",
      "Now I'm gonna tell you why you ain't ", ];
    result = pre[Math.floor(Math.random() * pre.length)] + w(word);
  }
  else if (pos === 'noun' || pos === 'proper-noun') {
    var a = article(word) + " ";
    var pre = [
      "I'm the illest MC to ever rock the ",
      "When I'm on the mic you realize you're " + a,
      "My rhymes bring the power like a raging ",
      "If you can't handle this then you're nothing but " + a,
      "When I come to a battle I'm strapped with " + a,
      "When you battle me it's like you battle " + a,
      "Every other MC is a sucker ",
      "There's nobody like me 'cause I'm the greatest ",
      "You hear my freestyle and you drop your ",
      "My flow and my style both blow away the ",
      "My posse's got my back and my " + sistasHomies() + " got my ",
      "Sweeter than molasses, and stronger than " + a,
      "Try to step to me and I'mma wreck your ",
      "Wherever I go, people give me some "];
    result = pre[Math.floor(Math.random() * pre.length)] + w(I.singularize(word));
  }
  else if (pos === 'verb-transitive') {
    result = "My rhyme profile makes the " + ladiesFellas() + " " + w(word);
  }
  else if (pos === 'interjection') {
    result = "*skratch solo* ... (" + word[0] + "-" + word[0] + "-" + w(word) + "!)";
  }
  else {
    //result = pos;
    //coupletDeferred.resolve(result);
    //coupletDeferred.resolve("");
    result = "";
  }

  return result;

}
<commit_msg>Put definition call back in<commit_after>var APIKEY = require('./config.js').key;
var _ = require('underscore.deferred');
var I = require('inflection');
var request = require('request');
var article = require('./lib/indefinite');
var Wordnik = require('wordnik-bb').init(APIKEY);

var express = require('express'),
  app = express();
app.use(express.logger());
app.listen(3000);
console.log('Express server started on port 3000');

function getCoupletPromise() {

  var coupletDeferred = _.Deferred();
  var coupletPromise = coupletDeferred.promise();

  var url = "http://api.wordnik.com//v4/words.json/randomWord?includePartOfSpeech=noun&excludePartOfSpeech=proper-noun,proper-noun-plural,proper-noun-posessive,suffix,family-name,idiom,affix&minCorpusCount=5000&api_key=" + APIKEY;
  var rwDeferred = _.Deferred();
  var randomWordPromise = rwDeferred.promise();
  request({
    url: url
  }, function (error, response, body) {
    if (!error && response.statusCode === 200) {
      //console.log(JSON.parse(body).word);
      //console.log(I.singularize(JSON.parse(body).word));
      var word = new Wordnik.Word({
        word: I.singularize(JSON.parse(body).word),
        params: {
          relationshipTypes: 'rhyme',
          limitPerRelationshipType: 100,
          hasDictionaryDef: true
        }
      });
      rwDeferred.resolve(word);

    }
    else {
      rwDeferred.reject(error);
    }
  });

  randomWordPromise.done(function (word) {
    //console.log("The model for our random word: ", word);
    // We could also get more info about the random word, in this case, relatedWords that rhyme:
    _.when(word.getRelatedWords())
      .then(function () {
      if (word.get("relatedWords").length > 0) {
        var wordPos = word.get("definitions")[0].partOfSpeech;
        var first = getLine(word.id, wordPos);
        if (first === "") {
          coupletDeferred.resolve(result);
        }
        else {
          var word2 = word.get("relatedWords")[0].words[Math.floor(Math.random() * word.get("relatedWords")[0].words.length)];
          var posPromise = getPartOfSpeech(word2);
          (function (first, word2) {

            posPromise.done(function (pos) {
              var result = "oops!";
              result = getLine(word2, pos);
              if (result === "") {
                coupletDeferred.resolve(result);
              }
              else {
                coupletDeferred.resolve(first + "\n
" + result + "\n
");
              }
            });
          })(first, word2);
        }
      }
      else {
        //coupletDeferred.resolve("Sorry. We couldn't find anything that rhymes with " + word.id + "!");
        coupletDeferred.resolve("");
      }
    });
  });
  return coupletDeferred.promise();
}

app.get('/', function (req, res) {

  var cypher = "";

  var stuffToDo = [];
  for (var i = 0; i < 12; i++) {
    var cp = getCoupletPromise();
    cp.done(function (couplet) {
      if (couplet !== "") {
        cypher += (couplet);
      }
    });
    stuffToDo.push(cp);
  }

  _.when(stuffToDo).done(function () {
    //console.log(cypher);
    //console.log('*drops the mic*');
    cypher += "
*drops the mic*";
    res.send('<!doctype html><title>Freestyle 80s Battle Rap Generator</title>
Freestyle 80s Battle Rap Generator

' + cypher + '
');

  });

});

function getPartOfSpeech(wordId) {
  // accepts a word string
  var word = new Wordnik.Word({
    word: wordId,
    params: {
      includeSuggestions: true
    }
  });
  var deferred = _.Deferred();
  word.getDefinitions()
    .then(function (word) {
    deferred.resolve(word.get("definitions")[0].partOfSpeech);
  });
  return deferred.promise();
}

function ladiesFellas() {
  return (Math.random() < 0.5) ? "ladies" : "fellas";
}

function womanMan() {
  return (Math.random() < 0.5) ? "woman" : "man";
}

function sistasHomies() {
  return (Math.random() < 0.5) ? "sistas" : "homies";
}

function w(word) {
  return "" + word + "";
}

function getLine(word, pos) {

  var result = "Oops, we didn't account for something.";

  if (pos === 'adjective') {
    var pre = [
      "You can try and battle me, but you're too ",
      "I make the MCs in the place wish that they were ",
      "My rhymes blow your mind and you think it's ",
      "My sweet-ass rhymes make your " + womanMan() + " feel ",
      "Now I'm gonna tell you why you ain't ", ];
    result = pre[Math.floor(Math.random() * pre.length)] + w(word);
  }
  else if (pos === 'noun' || pos === 'proper-noun') {
    var a = article(word) + " ";
    var pre = [
      "I'm the illest MC to ever rock the ",
      "When I'm on the mic you realize you're " + a,
      "My rhymes bring the power like a raging ",
      "If you can't handle this then you're nothing but " + a,
      "When I come to a battle I'm strapped with " + a,
      "When you battle me it's like you battle " + a,
      "Every other MC is a sucker ",
      "There's nobody like me 'cause I'm the greatest ",
      "You hear my freestyle and you drop your ",
      "My flow and my style both blow away the ",
      "My posse's got my back and my " + sistasHomies() + " got my ",
      "Sweeter than molasses, and stronger than " + a,
      "Try to step to me and I'mma wreck your ",
      "Wherever I go, people give me some "];
    result = pre[Math.floor(Math.random() * pre.length)] + w(I.singularize(word));
  }
  else if (pos === 'verb-transitive') {
    result = "My rhyme profile makes the " + ladiesFellas() + " " + w(word);
  }
  else if (pos === 'interjection') {
    result = "*skratch solo* ... (" + word[0] + "-" + word[0] + "-" + w(word) + "!)";
  }
  else {
    //result = pos;
    //coupletDeferred.resolve(result);
    //coupletDeferred.resolve("");
    result = "";
  }

  return result;

}
<|endoftext|>


<commit_before>/**
 * grunt/pipeline.js
 *
 * The order in which your css, javascript, and template files should be
 * compiled and linked from your views and static HTML files.
 *
 * (Note that you can take advantage of Grunt-style wildcard/glob/splat expressions
 * for matching multiple files.)
 */

// CSS files to inject in order
//
// (if you're using LESS with the built-in default config, you'll want
//  to change `assets/styles/importer.less` instead.)
var cssFilesToInject = [
  'vendor/**/*.css',
  'shared/**/*.css',
  'components/**/*.css'
];

// Client-side javascript files to inject in order
// (uses Grunt-style wildcard/glob/splat expressions)
var jsFilesToInject = [
  // 'vendor/js/angular.min.js',
  // 'vendor/js/angular-route.min.js',
  // 'vendor/js/jquery.min.js',
  'vendor/js/*.js',
  '*.js',
  'shared/**/*.js',
  'components/**/*.js'
];

// Client-side HTML templates are injected using the sources below
// The ordering of these templates shouldn't matter.
// (uses Grunt-style wildcard/glob/splat expressions)
//
// By default, Sails uses JST templates and precompiles them into
// functions for you.  If you want to use jade, handlebars, dust, etc.,
// with the linker, no problem-- you'll just want to make sure the precompiled
// templates get spit out to the same file.  Be sure and check out `tasks/README.md`
// for information on customizing and installing new tasks.
var templateFilesToInject = [
  'templates/**/*.html'
];

// Prefix relative paths to source files so they point to the proper locations
// (i.e. where the other Grunt tasks spit them out, or in some cases, where
// they reside in the first place)
module.exports.cssFilesToInject = cssFilesToInject.map(function(path) {
  return '.tmp/public/' + path;
});
module.exports.jsFilesToInject = jsFilesToInject.map(function(path) {
  return '.tmp/public/' + path;
});
module.exports.templateFilesToInject = templateFilesToInject.map(function(path) {
  return 'assets/' + path;
});
<commit_msg>working in prod<commit_after>/**
 * grunt/pipeline.js
 *
 * The order in which your css, javascript, and template files should be
 * compiled and linked from your views and static HTML files.
 *
 * (Note that you can take advantage of Grunt-style wildcard/glob/splat expressions
 * for matching multiple files.)
 */

// CSS files to inject in order
//
// (if you're using LESS with the built-in default config, you'll want
//  to change `assets/styles/importer.less` instead.)
var cssFilesToInject = [
  'components/**/*.css',
  'shared/**/*.css',
  'vendor/**/*.css'
];

// Client-side javascript files to inject in order
// (uses Grunt-style wildcard/glob/splat expressions)
var jsFilesToInject = [
  // 'vendor/js/angular.min.js',
  // 'vendor/js/angular-route.min.js',
  // 'vendor/js/jquery.min.js',
  'vendor/js/*.js',
  '*.js',
  'shared/**/*.js',
  'components/**/*.js'
];

// Client-side HTML templates are injected using the sources below
// The ordering of these templates shouldn't matter.
// (uses Grunt-style wildcard/glob/splat expressions)
//
// By default, Sails uses JST templates and precompiles them into
// functions for you.  If you want to use jade, handlebars, dust, etc.,
// with the linker, no problem-- you'll just want to make sure the precompiled
// templates get spit out to the same file.  Be sure and check out `tasks/README.md`
// for information on customizing and installing new tasks.
var templateFilesToInject = [
  'templates/**/*.html'
];

// Prefix relative paths to source files so they point to the proper locations
// (i.e. where the other Grunt tasks spit them out, or in some cases, where
// they reside in the first place)
module.exports.cssFilesToInject = cssFilesToInject.map(function(path) {
  return '.tmp/public/' + path;
});
module.exports.jsFilesToInject = jsFilesToInject.map(function(path) {
  return '.tmp/public/' + path;
});
module.exports.templateFilesToInject = templateFilesToInject.map(function(path) {
  return 'assets/' + path;
});
<|endoftext|>


<commit_before>import React, {Component} from 'react';
import PropTypes from 'prop-types';
import {connect} from 'react-redux';
import {t} from '../../util.js';

import * as Control from '../../controls.js';
import {Row, Form, Col} from 'react-bootstrap';
import {saveClient} from '../../../actions/appActions.js';
import {getNewClient, requiredClientProperties} from '../../client/EditClientViewModel.js';

class ClientModalComponent extends Component {
  static propTypes = {
    config: PropTypes.object.isRequired,
    saveClient: PropTypes.func.isRequired,
    client: PropTypes.object,
    show: PropTypes.bool.isRequired,
    onClose: PropTypes.func.isRequired,
    onConfirm: PropTypes.func,
  }

  constructor(props) {
    super(props);
    this.state = this.copyClient(props);
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.client !== this.props.client) {
      this.setState({...this.copyClient(nextProps)});
    }
  }

  copyClient(props) {
    if (props.client) {
      return JSON.parse(JSON.stringify(props.client));
    }
    return getNewClient(props.config);
  }

  onSave() {
    const updatedClient = this.state;
    this.props.saveClient(updatedClient, true, clientWithServerValues => this.props.onConfirm(clientWithServerValues));
  }

  render() {
    const client = this.state;
    if (!client) {
      return null;
    }

    return (
      <Control.Modal
        show={this.props.show}
        onClose={this.props.onClose}
        title={client._id ? client.name : t('client.createNew')}
        onConfirm={this.onSave.bind(this)}
      >
        <Row>
          <Form>
            <Control.InputArray
              config={requiredClientProperties}
              model={client}
              onChange={value => this.setState({...client, ...value})}
              tPrefix="config.company."
            />

            <Col sm={12}>
              <Control.TextareaInput
                label={t('notes')}
                placeholder={t('notes')}
                value={client.notes}
                onChange={value => this.setState({...client, notes: value})}
                style={{height: 120}}
              />
            </Col>
          </Form>
        </Row>
      </Control.Modal>
    );
  }
}

export const ClientModal = connect(state => ({config: state.config}), {saveClient})(ClientModalComponent);
<commit_msg>ClientModal: onConfirm is not required bugfix<commit_after>import React, {Component} from 'react';
import PropTypes from 'prop-types';
import {connect} from 'react-redux';
import {t} from '../../util.js';

import * as Control from '../../controls.js';
import {Row, Form, Col} from 'react-bootstrap';
import {saveClient} from '../../../actions/appActions.js';
import {getNewClient, requiredClientProperties} from '../../client/EditClientViewModel.js';

class ClientModalComponent extends Component {
  static propTypes = {
    config: PropTypes.object.isRequired,
    saveClient: PropTypes.func.isRequired,
    client: PropTypes.object,
    show: PropTypes.bool.isRequired,
    onClose: PropTypes.func.isRequired,
    onConfirm: PropTypes.func,
  }

  constructor(props) {
    super(props);
    this.state = this.copyClient(props);
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.client !== this.props.client) {
      this.setState({...this.copyClient(nextProps)});
    }
  }

  copyClient(props) {
    if (props.client) {
      return JSON.parse(JSON.stringify(props.client));
    }
    return getNewClient(props.config);
  }

  onSave() {
    const updatedClient = this.state;
    const onSuccess = this.props.onConfirm ? clientWithServerValues => this.props.onConfirm(clientWithServerValues) : null;
    this.props.saveClient(updatedClient, true, onSuccess);
  }

  render() {
    const client = this.state;
    if (!client) {
      return null;
    }

    return (
      <Control.Modal
        show={this.props.show}
        onClose={this.props.onClose}
        title={client._id ? client.name : t('client.createNew')}
        onConfirm={this.onSave.bind(this)}
      >
        <Row>
          <Form>
            <Control.InputArray
              config={requiredClientProperties}
              model={client}
              onChange={value => this.setState({...client, ...value})}
              tPrefix="config.company."
            />

            <Col sm={12}>
              <Control.TextareaInput
                label={t('notes')}
                placeholder={t('notes')}
                value={client.notes}
                onChange={value => this.setState({...client, notes: value})}
                style={{height: 120}}
              />
            </Col>
          </Form>
        </Row>
      </Control.Modal>
    );
  }
}

export const ClientModal = connect(state => ({config: state.config}), {saveClient})(ClientModalComponent);
<|endoftext|>


<commit_before>// @flow
import React, { Component } from 'react'
import { Alert, View } from 'react-native'
import { NavigationActions, StackNavigator } from 'react-navigation'
import { withMappedNavigationProps, withMappedNavigationAndConfigProps } from 'react-navigation-props-mapper'
import { connect } from 'react-redux'
import expect from 'expect'

import SRStudyList, { studyListTitle } from './SRStudyList'
import SRStudyTaskEditor from './SRStudyTaskEditor'
import SRSpacedRepetition from './SRSpacedRepetition'
import { SRDarkColor, SRYellowColor, SRBrightColor, SRRedColor } from './utilities/SRColors'
import { mapDispatchToProps, mapStateToProps } from './dataModel/SRDataManipulator'

export const StudyTaskDetailsScreenName = 'StudyTaskDetails'

class SRHome extends Component {

  static navigationOptions = (props) => {
    const { studyTasks } = props
    return {
      headerTintColor: SRDarkColor,
      headerStyle: { backgroundColor: SRBrightColor},
      title: (studyTasks == null || studyTasks.length == 0) ? ' ' : studyListTitle,
    }
  }

  render() {
    return (
      <View style={{flex:1}}>

        <SRStudyList
          navigationAction ={item => this.navigateToItem(item)}
          rateAction = {(item, grade) => this.rateTask(item, grade)}
        />

       </View>
    )
  }

  updateTask = (
    newTask: {id: string, taskName: string, notes: string, date: string},
    oldTask: {id: string, taskName: string, notes: string, date: string}) => {
    const { replaceItem, studyTasks } = this.props
    const mergedItem = this.dataWithID(oldTask.id, studyTasks)
    mergedItem.taskName = newTask.taskName
    mergedItem.notes = newTask.notes
    replaceItem(mergedItem)
  }

  rateTask = (id: string, grade: number) => {
    const { replaceItem, studyTasks } = this.props
    expect(id).toExist('rateItem(): undefined id')
    const item = this.dataWithID(id, studyTasks)

    // update SRS, rating history, date rated,
    item.ratingHistory.push(grade)

    const dateRated = new Date().toString()
    item.dates.push(dateRated)

    const { easinessFactor, interval, repetition } = item.srs
    const updatedSRS = new SRSpacedRepetition(easinessFactor, interval, repetition).grade(grade)
    item.srs = updatedSRS

    replaceItem(item)
  }

  dataWithID = (id: string, studyTasks: Array<Object>) => {
    expect(id).toExist('dataWithID(): Undefined id')
    const filteredArray = studyTasks.filter((item) => item.id == id)
    expect(filteredArray.length).toBe(1, `Looking for data with id: ${id}. Item: ${JSON.stringify(studyTasks)}`)
    const item = filteredArray[0]
    return item
  }

  // SRStudyListCell

  navigateToItem = (item: {id: string, taskName: string, notes: string, date: string}) => {
    const displayProps = {
      readonly: true,
      item: item,
      saveAction: (newItem, oldItem) => this.updateTask(newItem, oldItem),
      deleteAction: () => this.deleteTask(item),
    }
    this.props.navigation.navigate(StudyTaskDetailsScreenName, displayProps)
  }

  deleteTask = (task: {id: string, taskName: string, notes: string, date: string}) => {
    const { navigation, removeItem } = this.props
    Alert.alert(
      'Delete Study Task',
      'Are you sure you want to delete the study task? This cannot be undone.',
      [
        {text: 'Cancel', onPress: () => {}, style: 'cancel'},
        {text: 'Delete', onPress: () => {
          removeItem(task)
          navigation.dispatch(NavigationActions.back())
        }},
      ],
      { cancelable: true }
    )
  }

}

export default connect(mapStateToProps, mapDispatchToProps)(SRHome)
<commit_msg>Remove unused imports.<commit_after>// @flow
import React, { Component } from 'react'
import { Alert, View } from 'react-native'
import { NavigationActions } from 'react-navigation'
import { connect } from 'react-redux'
import expect from 'expect'

import SRStudyList, { studyListTitle } from './SRStudyList'
import SRSpacedRepetition from './SRSpacedRepetition'
import { SRDarkColor, SRYellowColor, SRBrightColor, SRRedColor } from './utilities/SRColors'
import { mapDispatchToProps, mapStateToProps } from './dataModel/SRDataManipulator'

export const StudyTaskDetailsScreenName = 'StudyTaskDetails'

class SRHome extends Component {

  static navigationOptions = (props) => {
    const { studyTasks } = props
    return {
      headerTintColor: SRDarkColor,
      headerStyle: { backgroundColor: SRBrightColor},
      title: (studyTasks == null || studyTasks.length == 0) ? ' ' : studyListTitle,
    }
  }

  render() {
    return (
      <View style={{flex:1}}>

        <SRStudyList
          navigationAction ={item => this.navigateToItem(item)}
          rateAction = {(item, grade) => this.rateTask(item, grade)}
        />

       </View>
    )
  }

  updateTask = (
    newTask: {id: string, taskName: string, notes: string, date: string},
    oldTask: {id: string, taskName: string, notes: string, date: string}) => {
    const { replaceItem, studyTasks } = this.props
    const mergedItem = this.dataWithID(oldTask.id, studyTasks)
    mergedItem.taskName = newTask.taskName
    mergedItem.notes = newTask.notes
    replaceItem(mergedItem)
  }

  rateTask = (id: string, grade: number) => {
    const { replaceItem, studyTasks } = this.props
    expect(id).toExist('rateItem(): undefined id')
    const item = this.dataWithID(id, studyTasks)

    // update SRS, rating history, date rated,
    item.ratingHistory.push(grade)

    const dateRated = new Date().toString()
    item.dates.push(dateRated)

    const { easinessFactor, interval, repetition } = item.srs
    const updatedSRS = new SRSpacedRepetition(easinessFactor, interval, repetition).grade(grade)
    item.srs = updatedSRS

    replaceItem(item)
  }

  dataWithID = (id: string, studyTasks: Array<Object>) => {
    expect(id).toExist('dataWithID(): Undefined id')
    const filteredArray = studyTasks.filter((item) => item.id == id)
    expect(filteredArray.length).toBe(1, `Looking for data with id: ${id}. Item: ${JSON.stringify(studyTasks)}`)
    const item = filteredArray[0]
    return item
  }

  // SRStudyListCell

  navigateToItem = (item: {id: string, taskName: string, notes: string, date: string}) => {
    const displayProps = {
      readonly: true,
      item: item,
      saveAction: (newItem, oldItem) => this.updateTask(newItem, oldItem),
      deleteAction: () => this.deleteTask(item),
    }
    this.props.navigation.navigate(StudyTaskDetailsScreenName, displayProps)
  }

  deleteTask = (task: {id: string, taskName: string, notes: string, date: string}) => {
    const { navigation, removeItem } = this.props
    Alert.alert(
      'Delete Study Task',
      'Are you sure you want to delete the study task? This cannot be undone.',
      [
        {text: 'Cancel', onPress: () => {}, style: 'cancel'},
        {text: 'Delete', onPress: () => {
          removeItem(task)
          navigation.dispatch(NavigationActions.back())
        }},
      ],
      { cancelable: true }
    )
  }

}

export default connect(mapStateToProps, mapDispatchToProps)(SRHome)
<|endoftext|>


<commit_before>import { runQuery, newMutation } from 'meteor/vulcan:core';
import Users from 'meteor/vulcan:users';
import { Posts, Comments } from 'meteor/example-forum'
import { Random } from 'meteor/random';

export const createDummyUser = async (username) => {
  const queryUsername = username || Random.id()
  const query = `
    mutation  {
      usersNew(document:{
        username:"${queryUsername}",
        email:"${queryUsername + "@test.lesswrong.com"}",
      }) {
        _id
        username
        email
      }
    }
  `;
  return (await runQuery(query)).data.usersNew;
}

export const dummyPostTitle = "Test Title";
export const dummyPostBody = "Test Body";

export const createDummyPost = async (userId, title=dummyPostTitle, body=dummyPostBody) => {
  const query = `
    mutation  {
      PostsNew(document:{
        title:"${title}",
        body:"${body}"
      }) {
        _id
        userId
        title
        htmlBody
      }
    }
  `;
  return (await runQuery(query,{},{currentUser:{_id:userId}})).data.PostsNew;
}

export const createDummyPostServer = async (user, data) => {
  const defaultData = {
    userId: user._id,
    title: dummyPostTitle,
    baseScore: 3,
    score: 0,
  }
  const postData = {...defaultData, ...data};
  console.log("CreateDummyPostServer postData: ", postData);
  return await newMutation({
    collection: Posts,
    document: postData,
    currentUser: user,
    validate: false,
    context: {},
  });
}

export const clearDatabase = async () => {
  Users.find().fetch().forEach((i)=>{
    Users.remove(i._id)
  })
  Posts.find().fetch().forEach((i)=>{
    Posts.remove(i._id)
  })
  Comments.find().fetch().forEach((i)=>{
    Posts.remove(i._id)
  })
}
<commit_msg>Fixed default post values<commit_after>import { runQuery, newMutation } from 'meteor/vulcan:core';
import Users from 'meteor/vulcan:users';
import { Posts, Comments } from 'meteor/example-forum'
import { Random } from 'meteor/random';

export const createDummyUser = async (username) => {
  const queryUsername = username || Random.id()
  const query = `
    mutation  {
      usersNew(document:{
        username:"${queryUsername}",
        email:"${queryUsername + "@test.lesswrong.com"}",
      }) {
        _id
        username
        email
      }
    }
  `;
  return (await runQuery(query)).data.usersNew;
}

export const dummyPostTitle = "Test Title";
export const dummyPostBody = "Test Body";

export const createDummyPost = async (userId, title=dummyPostTitle, body=dummyPostBody) => {
  const query = `
    mutation  {
      PostsNew(document:{
        title:"${title}",
        body:"${body}"
      }) {
        _id
        userId
        title
        htmlBody
      }
    }
  `;
  return (await runQuery(query,{},{currentUser:{_id:userId}})).data.PostsNew;
}

export const createDummyPostServer = async (user, data) => {
  const defaultData = {
    userId: user._id,
    title: dummyPostTitle,
  }
  const postData = {...defaultData, ...data};
  console.log("CreateDummyPostServer postData: ", postData);
  return await newMutation({
    collection: Posts,
    document: postData,
    currentUser: user,
    validate: false,
    context: {},
  });
}

export const clearDatabase = async () => {
  Users.find().fetch().forEach((i)=>{
    Users.remove(i._id)
  })
  Posts.find().fetch().forEach((i)=>{
    Posts.remove(i._id)
  })
  Comments.find().fetch().forEach((i)=>{
    Posts.remove(i._id)
  })
}
<|endoftext|>