<commit_before>import DocPage from '../DocPage';
import Paper from '../../src/Paper';
import React from 'react';
import TextField from '../../src/TextField';

class PaperDocs extends React.Component {

  constructor(props) {
    super(props);
    this.onControlPanel = this.onControlPanel.bind(this);
    this.state = {
      children: 'Hello World',
      elevation: '10',
      style: '{"padding": "20px"}'
    };
  }

  onControlPanel(key, value) {
    this.setState({[key]: value});
  }

  render() {
    let elevation;
    let style;
    try {
      elevation = Number(this.state.elevation);
      style = JSON.parse(this.state.style);
    } catch (e) {
      style = {};
    }
    return (
      <DocPage
        componentName="Paper"
        buildYourOwn={
          <Paper elevation={elevation} style={style}>
            {this.state.children}
          </Paper>
        }
        buildYourOwnControlPanel={

              <TextField
                type="number"
                onChange={e => (this.onControlPanel('elevation', e.target.value))}
                label="Elevation"
                value={this.state.elevation}
                helperText="Pick a value between 1 and 25"
              />

              <TextField
                onChange={e => (this.onControlPanel('children', e.target.value))}
                label="Children"
                value={this.state.children}
                helperText="For demonstration purposes, limited to plaintext"
              />

              <TextField
                onChange={e => (this.onControlPanel('style', e.target.value))}
                label="Style"
                value={this.state.style}
                helperText="JSON will be converted to a style object"
              />

        }
        examples={

              <Paper elevation={2} style={{height: '100px', width: '80%', padding: '10px', background: 'white'}}>
                Paper with elevation of 2.
              </Paper>

              <Paper elevation={12} style={{height: '100px', width: '80%', padding: '10px', background: 'white'}}>
                Paper with elevation of 12.
              </Paper>

              <Paper elevation={25} style={{height: '100px', width: '80%', padding: '10px', background: 'white'}}>
                Paper with elevation of 25.
              </Paper>

        }
      />
    );
  }
}

export default PaperDocs;
<commit_msg>[docs] [Paper] center example<commit_after>import DocPage from '../DocPage';
import Paper from '../../src/Paper';
import React from 'react';
import TextField from '../../src/TextField';

class PaperDocs extends React.Component {

  constructor(props) {
    super(props);
    this.onControlPanel = this.onControlPanel.bind(this);
    this.state = {
      children: 'Hello World',
      elevation: '10',
      style: '{"padding": "20px", "width": "300px"}'
    };
  }

  onControlPanel(key, value) {
    this.setState({[key]: value});
  }

  render() {
    let elevation;
    let style;
    try {
      elevation = Number(this.state.elevation);
      style = JSON.parse(this.state.style);
    } catch (e) {
      style = {};
    }
    return (
      <DocPage
        componentName="Paper"
        buildYourOwn={

            <Paper elevation={elevation} style={style}>
              {this.state.children}
            </Paper>

        }
        buildYourOwnControlPanel={

              <TextField
                type="number"
                onChange={e => (this.onControlPanel('elevation', e.target.value))}
                label="Elevation"
                value={this.state.elevation}
                helperText="Pick a value between 1 and 25"
              />

              <TextField
                onChange={e => (this.onControlPanel('children', e.target.value))}
                label="Children"
                value={this.state.children}
                helperText="For demonstration purposes, limited to plaintext"
              />

              <TextField
                onChange={e => (this.onControlPanel('style', e.target.value))}
                label="Style"
                value={this.state.style}
                helperText="JSON will be converted to a style object"
              />

        }
        examples={

              <Paper elevation={2} style={{height: '100px', width: '80%', padding: '10px', background: 'white'}}>
                Paper with elevation of 2.
              </Paper>

              <Paper elevation={12} style={{height: '100px', width: '80%', padding: '10px', background: 'white'}}>
                Paper with elevation of 12.
              </Paper>

              <Paper elevation={25} style={{height: '100px', width: '80%', padding: '10px', background: 'white'}}>
                Paper with elevation of 25.
              </Paper>

        }
      />
    );
  }
}

export default PaperDocs;
<|endoftext|>


<commit_before>/* Project specific Javascript goes here. */
var data, geojson;
var map = L.map('map').setView([-12.9696, -38.4676], 13);
var mapTiles = L.tileLayer('http://a.tile.thunderforest.com/transport/{z}/{x}/{y}.png', {
  attribution: 'Maps © Thunderforest, \
               Data © OpenStreetMap contributors'
});
mapTiles.addTo(map);

var markerIcon = L.icon({
  iconUrl: 'static/js/images/marker-48.png',
  iconRetinaUrl: 'static/js/images/marker-48@2x.png',
  iconSize: [48, 48],
  iconAnchor: [24, 42],
  popupAnchor: [0, -30],
});

var grayIcon = L.icon({
  iconUrl: 'static/js/images/gray-24.png',
  iconRetinaUrl: 'static/js/images/gray-24@2x.png',
  iconSize: [15, 15],
  popupAnchor: [0, -8],
});

var redIcon = L.icon({
  iconUrl: 'static/js/images/red-24.png',
  iconRetinaUrl: 'static/js/images/red-24@2x.png',
  iconSize: [15, 15],
  popupAnchor: [0, -8],
});

var yellowIcon = L.icon({
  iconUrl: 'static/js/images/yellow-24.png',
  iconRetinaUrl: 'static/js/images/yellow-24@2x.png',
  iconSize: [15, 15],
  popupAnchor: [0, -8],
});

var greenIcon = L.icon({
  iconUrl: 'static/js/images/green-24.png',
  iconRetinaUrl: 'static/js/images/green-24@2x.png',
  iconSize: [15, 15],
  popupAnchor: [0, -8],
});

function popupContent(id) {
  return 'Ponto ' + id + ''
}

$.getJSON("core/pontos.geojson/?format=json", function (data) {
  var geojson = L.geoJson(data, {
    pointToLayer: function (feature, latlng) {
      return L.marker(latlng, {icon: grayIcon}).bindPopup(popupContent(feature.id));
    },
  });

  var nao_avaliado = L.geoJson(data, {
    filter: function(feature, layer) {
        if (feature.properties.avaliacao == null) {
          return true;
        }
    },
    pointToLayer: function (feature, latlng) {
      return L.marker(latlng, {icon: grayIcon}).bindPopup(popupContent(feature.id));
    },
  });

  var critica = L.geoJson(data, {
    filter: function(feature, layer) {
        if (feature.properties.avaliacao != null && feature.properties.avaliacao.final == 'critica') {
          return true;
        }
    },
    pointToLayer: function (feature, latlng) {
      return L.marker(latlng, {icon: redIcon}).bindPopup(popupContent(feature.id));
    },
  });

  var aceitavel = L.geoJson(data, {
    filter: function(feature, layer) {
        if (feature.properties.avaliacao != null && feature.properties.avaliacao.final == 'aceitavel') {
          return true;
        }
    },
    pointToLayer: function (feature, latlng) {
      return L.marker(latlng, {icon: yellowIcon}).bindPopup(popupContent(feature.id));
    },
  });

  var favoravel = L.geoJson(data, {
    filter: function(feature, layer) {
        if (feature.properties.avaliacao != null && feature.properties.avaliacao.final == 'favoravel') {
          return true;
        }
    },
    pointToLayer: function (feature, latlng) {
      return L.marker(latlng, {icon: greenIcon}).bindPopup(popupContent(feature.id));
    },
  });
  nao_avaliado.addTo(map);
  critica.addTo(map);
  aceitavel.addTo(map);
  favoravel.addTo(map);
});
<commit_msg>adiciona control layers para exibir cada categoria de pontos<commit_after>/* Project specific Javascript goes here. */
var data, geojson;

var map = L.map('map').setView([-12.9696, -38.4676], 13);
var mapTiles = L.tileLayer('http://a.tile.thunderforest.com/transport/{z}/{x}/{y}.png', {
  attribution: 'Maps © Thunderforest, \
               Data © OpenStreetMap contributors'
});
mapTiles.addTo(map);

var markerIcon = L.icon({
  iconUrl: 'static/js/images/marker-48.png',
  iconRetinaUrl: 'static/js/images/marker-48@2x.png',
  iconSize: [48, 48],
  iconAnchor: [24, 42],
  popupAnchor: [0, -30],
});

var grayIcon = L.icon({
  iconUrl: 'static/js/images/gray-24.png',
  iconRetinaUrl: 'static/js/images/gray-24@2x.png',
  iconSize: [15, 15],
  popupAnchor: [0, -8],
});

var redIcon = L.icon({
  iconUrl: 'static/js/images/red-24.png',
  iconRetinaUrl: 'static/js/images/red-24@2x.png',
  iconSize: [15, 15],
  popupAnchor: [0, -8],
});

var yellowIcon = L.icon({
  iconUrl: 'static/js/images/yellow-24.png',
  iconRetinaUrl: 'static/js/images/yellow-24@2x.png',
  iconSize: [15, 15],
  popupAnchor: [0, -8],
});

var greenIcon = L.icon({
  iconUrl: 'static/js/images/green-24.png',
  iconRetinaUrl: 'static/js/images/green-24@2x.png',
  iconSize: [15, 15],
  popupAnchor: [0, -8],
});

var layerNaoAvaliado = L.layerGroup([]);
var layerCritica = L.layerGroup([]);
var layerAceitavel = L.layerGroup([]);
var layerFavoravel = L.layerGroup([]);

function popupContent(id) {
  return 'Ponto ' + id + ''
}

$.getJSON("core/pontos.geojson/?format=json", function (data) {
  var geojson = L.geoJson(data, {
    pointToLayer: function (feature, latlng) {
      return L.marker(latlng, {icon: grayIcon}).bindPopup(popupContent(feature.id));
    },
  });

  var nao_avaliado = L.geoJson(data, {
    filter: function(feature, layer) {
        if (feature.properties.avaliacao == null) {
          return true;
        }
    },
    pointToLayer: function (feature, latlng) {
      return L.marker(latlng, {icon: grayIcon}).bindPopup(popupContent(feature.id));
    },
  });

  var critica = L.geoJson(data, {
    filter: function(feature, layer) {
        if (feature.properties.avaliacao != null && feature.properties.avaliacao.final == 'critica') {
          return true;
        }
    },
    pointToLayer: function (feature, latlng) {
      return L.marker(latlng, {icon: redIcon}).bindPopup(popupContent(feature.id));
    },
  });

  var aceitavel = L.geoJson(data, {
    filter: function(feature, layer) {
        if (feature.properties.avaliacao != null && feature.properties.avaliacao.final == 'aceitavel') {
          return true;
        }
    },
    pointToLayer: function (feature, latlng) {
      return L.marker(latlng, {icon: yellowIcon}).bindPopup(popupContent(feature.id));
    },
  });

  var favoravel = L.geoJson(data, {
    filter: function(feature, layer) {
        if (feature.properties.avaliacao != null && feature.properties.avaliacao.final == 'favoravel') {
          return true;
        }
    },
    pointToLayer: function (feature, latlng) {
      return L.marker(latlng, {icon: greenIcon}).bindPopup(popupContent(feature.id));
    },
  });
  nao_avaliado.addTo(layerNaoAvaliado);
  critica.addTo(layerCritica);
  aceitavel.addTo(layerAceitavel);
  favoravel.addTo(layerFavoravel);
});

layerNaoAvaliado.addTo(map);
layerCritica.addTo(map);
layerAceitavel.addTo(map);
layerFavoravel.addTo(map);

var baseMaps = {
  "Transporte Público": mapTiles,
};

var overlayMaps = {
  "Avaliação Favorável": layerFavoravel,
  "Avaliação Aceitável": layerAceitavel,
  "Avaliação Crítica": layerCritica,
  "Pontos ainda não avaliados": layerNaoAvaliado,
};

L.control.layers(baseMaps, overlayMaps, {collapsed: true}).addTo(map);
<|endoftext|>


<commit_before>import React from 'react';
import {
  compose,
  withPropsOnChange,
  branch,
  renderComponent,
  withProps,
  withState,
  lifecycle,
} from 'recompose';
import md5 from 'blueimp-md5';
import urlJoin from 'url-join';
import _ from 'lodash';

import ClinicalVariableCard from './ClinicalVariableCard.js';
import consoleDebug from '@ncigdc/utils/consoleDebug';
import { redirectToLogin } from '@ncigdc/utils/auth';
import { withLoader } from '@ncigdc/uikit/Loaders/Loader';
import Loader from '@ncigdc/uikit/Loaders/Loader';

import { API, IS_AUTH_PORTAL } from '@ncigdc/utils/constants';

const simpleAggCache = {};
const pendingAggCache = {};
const DEFAULT_CONTINUOUS_BUCKETS = 4;

const getContinuousAggs = ({ fieldName, stats, filters }) => {
  // prevent query failing if interval will equal 0
  if (_.isNull(stats.min) || _.isNull(stats.max)) {
    return null;
  }
  const interval = (stats.max - stats.min) / DEFAULT_CONTINUOUS_BUCKETS;
  const queryFieldName = fieldName.replace('.', '__');

  const variables = {
    filters,
  };
  const componentName = 'ContinuousAggregationQuery';
  const body = JSON.stringify({
    query: `query ${componentName}(\n  $filters: FiltersArgument\n) {\n  viewer {\n    explore {\n      cases {\n        aggregations(filters: $filters) {\n          ${queryFieldName} {\n            histogram(interval: ${interval}) {\n              buckets {\n                key\n                doc_count\n              }\n            }\n          }\n        }\n      }\n    }\n  }\n}\n`,
    variables,
  });

  const hash = md5(body);

  if (pendingAggCache[hash]) {
    return new Promise((res, rej) => {
      const id = setInterval(() => {
        let timer = 0;
        if (simpleAggCache[hash]) {
          clearInterval(id);
          res(simpleAggCache[hash]);
        }

        if (timer > 10000) {
          clearInterval(id);
          delete pendingAggCache[hash];
          rej(`Error: ${componentName} was pending for too long.`);
        }
        timer += 100;
      }, 100);
    });
  }

  if (simpleAggCache[hash]) {
    return Promise.resolve(simpleAggCache[hash]);
  }
  pendingAggCache[hash] = true;
  return fetch(
    urlJoin(API, `graphql/ContinuousAggregationQuery?hash=${hash}`),
    {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body,
    }
  ).then(response =>
    response
      .json()
      .then(json => {
        if (!response.ok) {
          consoleDebug('throwing error in Environment');
          throw response;
        }

        if (response.status === 200) {
          simpleAggCache[hash] = json;
          delete pendingAggCache[hash];
        }

        return json;
      })
      .catch(err => {
        if (err.status) {
          switch (err.status) {
            case 401:
            case 403:
              consoleDebug(err.statusText);
              if (IS_AUTH_PORTAL) {
                return redirectToLogin('timeout');
              }
              break;
            case 400:
            case 404:
              consoleDebug(err.statusText);
              break;
            default:
              return consoleDebug(`Default error case: ${err.statusText}`);
          }
        } else {
          consoleDebug(
            `Something went wrong in environment, but no error status: ${err}`
          );
        }
      })
  );
};

export default compose(
  withState('aggData', 'setAggData', null),
  withState('isLoading', 'setIsLoading', true),
  withProps({
    updateData: async ({
      fieldName,
      stats,
      filters,
      setAggData,
      setIsLoading,
    }) => {
      const res = await getContinuousAggs({
        fieldName,
        stats,
        filters,
      });
      setAggData(res && res.data.viewer, () => setIsLoading(false));
    },
  }),
  withPropsOnChange(['filters'], ({ updateData, ...props }) =>
    updateData(props)
  )
)(({ aggData, isLoading, setId, stats, hits, ...props }) => {
  if (isLoading) {
    return <Loader />;
  }
  return (
    <ClinicalVariableCard
      setId={setId}
      stats={stats}
      data={{ ...aggData, hits }}
      {...props}
    />
  );
});
<commit_msg>PRTL-2544 fetch data for box plot + table<commit_after>import React from 'react';
import {
  compose,
  withPropsOnChange,
  branch,
  renderComponent,
  withProps,
  withState,
  lifecycle,
} from 'recompose';
import md5 from 'blueimp-md5';
import urlJoin from 'url-join';
import _ from 'lodash';

import consoleDebug from '@ncigdc/utils/consoleDebug';
import { redirectToLogin } from '@ncigdc/utils/auth';
import Loader, { withLoader } from '@ncigdc/uikit/Loaders/Loader';

import { API, IS_AUTH_PORTAL } from '@ncigdc/utils/constants';
import ClinicalVariableCard from './ClinicalVariableCard';

const simpleAggCache = {};
const pendingAggCache = {};
const DEFAULT_CONTINUOUS_BUCKETS = 4;

const getContinuousAggs = ({ fieldName, stats, filters }) => {
  // prevent query failing if interval will equal 0
  if (_.isNull(stats.min) || _.isNull(stats.max)) {
    return null;
  }
  const interval = (stats.max - stats.min) / DEFAULT_CONTINUOUS_BUCKETS;
  const queryFieldName = fieldName.replace('.', '__');

  const variables = {
    filters,
  };
  const componentName = 'ContinuousAggregationQuery';
  const body = JSON.stringify({
    query: `query ${componentName}($filters: FiltersArgument) {
      viewer {
        explore {
          cases {
            aggregations(filters: $filters) {
              ${queryFieldName} {
                stats {
                  Min : min
                  Max: max
                  Mean: avg
                  SD: std_deviation
                }
                percentiles {
                  Median: median
                  IQR: iqr
                  q1: quartile_1
                  q3: quartile_3
                }
                histogram(interval: ${interval}) {
                  buckets {
                    key
                    doc_count
                  }
                }
              }
            }
          }
        }
      }
    }`,
    variables,
  });

  const hash = md5(body);

  if (pendingAggCache[hash]) {
    return new Promise((res, rej) => {
      const id = setInterval(() => {
        let timer = 0;
        if (simpleAggCache[hash]) {
          clearInterval(id);
          res(simpleAggCache[hash]);
        }

        if (timer > 10000) {
          clearInterval(id);
          delete pendingAggCache[hash];
          rej(`Error: ${componentName} was pending for too long.`);
        }
        timer += 100;
      }, 100);
    });
  }

  if (simpleAggCache[hash]) {
    return Promise.resolve(simpleAggCache[hash]);
  }
  pendingAggCache[hash] = true;
  return fetch(
    urlJoin(API, `graphql/ContinuousAggregationQuery?hash=${hash}`),
    {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body,
    }
  ).then(response => response
    .json()
    .then(json => {
      if (!response.ok) {
        consoleDebug('throwing error in Environment');
        throw response;
      }

      if (response.status === 200) {
        simpleAggCache[hash] = json;
        delete pendingAggCache[hash];
      }

      return json;
    })
    .catch(err => {
      if (err.status) {
        switch (err.status) {
          case 401:
          case 403:
            consoleDebug(err.statusText);
            if (IS_AUTH_PORTAL) {
              return redirectToLogin('timeout');
            }
            break;
          case 400:
          case 404:
            consoleDebug(err.statusText);
            break;
          default:
            return consoleDebug(`Default error case: ${err.statusText}`);
        }
      } else {
        consoleDebug(
            `Something went wrong in environment, but no error status: ${err}`
        );
      }
    }));
};

export default compose(
  withState('aggData', 'setAggData', null),
  withState('isLoading', 'setIsLoading', true),
  withProps({
    updateData: async ({
      fieldName,
      stats,
      filters,
      setAggData,
      setIsLoading,
    }) => {
      const res = await getContinuousAggs({
        fieldName,
        stats,
        filters,
      });
      setAggData(res && res.data.viewer, () => setIsLoading(false));
    },
  }),
  withPropsOnChange(['filters'], ({ updateData, ...props }) => updateData(props))
)(({
  aggData, isLoading, setId, stats, hits, ...props
}) => {
  if (isLoading) {
    return <Loader />;
  }
  return (
    <ClinicalVariableCard
      data={{
        ...aggData,
        hits,
      }}
      setId={setId}
      stats={stats}
      {...props}
      />
  );
});
<|endoftext|>


<commit_before>'use strict';
const _ = require('lodash');
const rp = require('request-promise');
const LocalRunner = require('./LocalRunner.js');
const DockerRunner = require('./DockerRunner.js');
const endpointToUrl = require('./common.js').endpointToUrl;

class InstanceManager {
  constructor (name) {
    this.instances = [];

    if (process.env.RESILIENCE_ARANGO_BASEPATH) {
      this.runner = new LocalRunner(process.env.RESILIENCE_ARANGO_BASEPATH);
    } else if (process.env.RESILIENCE_DOCKER_IMAGE) {
      this.runner = new DockerRunner(process.env.RESILIENCE_DOCKER_IMAGE);
    }

    if (!this.runner) {
      throw new Error('Must specify RESILIENCE_ARANGO_BASEPATH (source root dir including a "build" folder containing compiled binaries or RESILIENCE_DOCKER_IMAGE to test a docker container');
    }
    this.currentLog = '';
  }

  startArango (name, endpoint, role, args) {
    args.push('--server.authentication=false');

    let instance = {
      name,
      role,
      process: null,
      status: 'NEW',
      exitcode: null,
      endpoint,
      args,
      logFn: line => {
        if (line.trim().length > 0) {
          let logLine = instance.name + '(' + process.pid + '): \t' + line;
          if (process.env.LOG_IMMEDIATE) {
            console.log(line);
          } else {
            this.currentLog += logLine + '\n';
          }
        }
      }
    };
    return this.runner.firstStart(instance);
  }

  startDbServer (name) {
    return this.runner.createEndpoint()
    .then(endpoint => {
      let args = [
        '--cluster.agency-endpoint=' + this.getAgencyEndpoint(),
        '--cluster.my-role=PRIMARY',
        '--cluster.my-local-info=' + name,
        '--cluster.my-address=' + endpoint
      ];
      return this.startArango(name, endpoint, 'primary', args);
    });
  }

  getAgencyEndpoint () {
    return this.instances.filter(instance => {
      return instance.role === 'agent';
    })[0].endpoint;
  }

  startCoordinator (name) {
    return this.runner.createEndpoint()
    .then(endpoint => {
      let args = [
        '--cluster.agency-endpoint=' + this.getAgencyEndpoint(),
        '--cluster.my-role=COORDINATOR',
        '--cluster.my-local-info=' + name,
        '--cluster.my-address=' + endpoint
      ];
      return this.startArango(name, endpoint, 'coordinator', args);
    });
  }

  replace (instance) {
    const i = this.instances.indexOf(instance);
    let promise;
    if (instance.status === 'EXITED') {
      promise = Promise.resolve();
    } else {
      promise = this.kill(instance);
    }
    return promise
    .then(() => {
      let args = [
        '--cluster.agency-endpoint=' + this.getAgencyEndpoint(),
        '--cluster.my-role=' + instance.role.toUpperCase(),
        '--cluster.my-local-info=' + instance.name,
        '--cluster.my-address=' + instance.endpoint
      ];
      return this.startArango(instance.name, instance.endpoint, instance.role, args);
    })
    .then((instance) => this.waitForInstance(instance))
    .then((instance) => {
      this.instances = [
        ...this.instances.slice(0, i),
        instance,
        ...this.instances.slice(i + 1)
      ];
      return instance;
    });
  }

  startAgency (options = {}) {
    let size = options.agencySize || 1;
    if (options.agencyWaitForSync === undefined) {
      options.agencyWaitForSync = false;
    }
    const wfs = options.agencyWaitForSync;
    let promise = Promise.resolve([]);
    for (var i = 0; i < size; i++) {
      promise = promise.then(instances => {
        return this.runner.createEndpoint()
        .then(endpoint => {
          let index = instances.length;
          let args = [
            '--agency.activate=true',
            '--agency.size=' + size,
            '--agency.pool-size=' + size,
            '--agency.wait-for-sync=' + wfs,
            '--agency.supervision=true',
            '--agency.my-address=' + endpoint
          ];
          if (index === 0) {
            args.push('--agency.endpoint=' + endpoint);
          } else {
            args.push('--agency.endpoint=' + instances[0].endpoint);
          }
          return this.startArango('agency-' + (index + 1), endpoint, 'agent', args);
        })
        .then(instance => {
          return [...instances, instance];
        });
      });
    }
    return promise
    .then(agents => {
      this.instances = agents;
      return agents;
    });
  }

  startCluster (numAgents, numCoordinators, numDbServers, options = {}) {
    let agencyOptions = options.agents || {};
    _.extend(agencyOptions, {agencySize: numAgents});

    return this.startAgency(agencyOptions)
    .then(agents => {
      let promises = [Promise.resolve(agents)];

      let coordinatorOptions = options.coordinators || {};
      let coordinators = Array.from(Array(numDbServers).keys()).reduce((servers, index) => {
        return servers.then(instances => {
          return this.startCoordinator('coordinator-' + (index + 1), coordinatorOptions)
          .then(instance => {
            return [...instances, instance];
          });
        });
      }, Promise.resolve([]));
      promises.push(coordinators);

      let dbServerOptions = options.dbservers || {};
      let dbServers = Array.from(Array(numDbServers).keys()).reduce((dbServers, index) => {
        return dbServers.then(instances => {
          return this.startDbServer('dbServer-' + (index + 1), dbServerOptions)
          .then(instance => {
            return [...instances, instance];
          });
        });
      }, Promise.resolve([]));
      promises.push(dbServers);
      return Promise.all(promises);
    })
    .then(serverGroups => {
      let servers = [];
      serverGroups.forEach(serverGroup => {
        servers = servers.concat(serverGroup);
      });
      return servers;
    })
    .then(servers => {
      this.instances = servers;
      return this.waitForAllInstances();
    })
    .then(() => {
      return this.getEndpoint();
    });
  }

  waitForInstance (instance) {
    if (instance.status !== 'RUNNING') {
      return Promise.reject(new Error('Instance ' + instance.name + ' is down!'));
    }
    return rp(endpointToUrl(instance.endpoint) + '/_api/version')
    .then(() => {
      return instance;
    }, () => {
      return new Promise((resolve, reject) => {
        setTimeout(resolve, 100);
      })
      .then(() => {
        return this.waitForInstance(instance);
      });
    });
  }

  waitForAllInstances () {
    return Promise.all(this.instances.map(instance => {
      return this.waitForInstance(instance);
    }));
  }

  getEndpoint (instance) {
    return (instance || this.coordinators()[0]).endpoint;
  }

  getEndpointUrl (instance) {
    return endpointToUrl(this.getEndpoint());
  }

  check () {
    return this.instances.every(instance => {
      return instance.status === 'RUNNING';
    });
  }

  shutdownCluster () {
    let shutdownPromise;
    if (this.coordinators().length === 0) {
      shutdownPromise = Promise.all(this.agents().map(agent => {
        return agent.process.kill();
      }));
    } else {
      shutdownPromise = rp({
        method: 'DELETE',
        uri: endpointToUrl(this.getEndpoint()) + '/_admin/shutdown?shutdown_cluster=1'
      });
    }
    return shutdownPromise
    .then(() => {
      let checkDown = () => {
        let allDown = this.instances.every(instance => {
          return instance.status === 'EXITED';
        });

        if (allDown) {
          return Promise.resolve(true);
        } else {
          return new Promise((resolve, reject) => {
            setTimeout(() => {
              checkDown.bind(this)().then(resolve, reject);
            }, 100);
          });
        }
      };
      return checkDown();
    });
  }

  cleanup () {
    return this.shutdownCluster()
    .then(() => {
      this.instances = [];
      return this.runner.cleanup();
    })
    .then(() => {
      let log = this.currentLog;
      this.currentLog = '';
      return log;
    });
  }

  dbServers () {
    return this.instances.filter(instance => {
      return instance.role === 'primary';
    });
  }

  coordinators () {
    return this.instances.filter(instance => {
      return instance.role === 'coordinator';
    });
  }

  agents () {
    return this.instances.filter(instance => {
      return instance.role === 'agent';
    });
  }

  kill (instance, signal = 'SIGTERM') {
    let index = this.instances.indexOf(instance);
    if (index === -1) {
      throw new Error('Couldn\'t find instance ' + instance.name);
    }

    instance.process.kill(signal);
    instance.status = 'KILLED';
    return new Promise((resolve, reject) => {
      let check = function () {
        if (instance.status !== 'EXITED') {
          setTimeout(check, 50);
        } else {
          resolve();
        }
      };
      check();
    });
  }

  destroy (instance) {
    let promise;
    if (this.instances.includes(instance)) {
      promise = this.kill(instance);
    } else {
      promise = Promise.resolve();
    }
    return promise
    .then(() => this.runner.destroy(instance))
    .then(() => {
      const i = this.instances.indexOf(instance);
      if (i !== -1) {
        this.instances = [
          ...this.instances.slice(0, i),
          ...this.instances.slice(i + 1)
        ];
      }
    });
  }

  restart (instance) {
    let index = this.instances.indexOf(instance);
    if (index === -1) {
      throw new Error('Couldn\'t find instance ' + instance.name);
    }

    return this.runner.restart(instance)
    .then(() => {
      return this.waitForInstance(instance);
    });
  }
}

module.exports = InstanceManager;
<commit_msg>Fix log output<commit_after>'use strict';
const _ = require('lodash');
const rp = require('request-promise');
const LocalRunner = require('./LocalRunner.js');
const DockerRunner = require('./DockerRunner.js');
const endpointToUrl = require('./common.js').endpointToUrl;

class InstanceManager {
  constructor (name) {
    this.instances = [];

    if (process.env.RESILIENCE_ARANGO_BASEPATH) {
      this.runner = new LocalRunner(process.env.RESILIENCE_ARANGO_BASEPATH);
    } else if (process.env.RESILIENCE_DOCKER_IMAGE) {
      this.runner = new DockerRunner(process.env.RESILIENCE_DOCKER_IMAGE);
    }

    if (!this.runner) {
      throw new Error('Must specify RESILIENCE_ARANGO_BASEPATH (source root dir including a "build" folder containing compiled binaries or RESILIENCE_DOCKER_IMAGE to test a docker container');
    }
    this.currentLog = '';
  }

  startArango (name, endpoint, role, args) {
    args.push('--server.authentication=false');

    let instance = {
      name,
      role,
      process: null,
      status: 'NEW',
      exitcode: null,
      endpoint,
      args,
      logFn: line => {
        if (line.trim().length > 0) {
          let logLine = instance.name + '(' + process.pid + '): \t' + line;
          if (process.env.LOG_IMMEDIATE) {
            console.log(logLine);
          } else {
            this.currentLog += logLine + '\n';
          }
        }
      }
    };
    return this.runner.firstStart(instance);
  }

  startDbServer (name) {
    return this.runner.createEndpoint()
    .then(endpoint => {
      let args = [
        '--cluster.agency-endpoint=' + this.getAgencyEndpoint(),
        '--cluster.my-role=PRIMARY',
        '--cluster.my-local-info=' + name,
        '--cluster.my-address=' + endpoint
      ];
      return this.startArango(name, endpoint, 'primary', args);
    });
  }

  getAgencyEndpoint () {
    return this.instances.filter(instance => {
      return instance.role === 'agent';
    })[0].endpoint;
  }

  startCoordinator (name) {
    return this.runner.createEndpoint()
    .then(endpoint => {
      let args = [
        '--cluster.agency-endpoint=' + this.getAgencyEndpoint(),
        '--cluster.my-role=COORDINATOR',
        '--cluster.my-local-info=' + name,
        '--cluster.my-address=' + endpoint
      ];
      return this.startArango(name, endpoint, 'coordinator', args);
    });
  }

  replace (instance) {
    const i = this.instances.indexOf(instance);
    let promise;
    if (instance.status === 'EXITED') {
      promise = Promise.resolve();
    } else {
      promise = this.kill(instance);
    }
    return promise
    .then(() => {
      let args = [
        '--cluster.agency-endpoint=' + this.getAgencyEndpoint(),
        '--cluster.my-role=' + instance.role.toUpperCase(),
        '--cluster.my-local-info=' + instance.name,
        '--cluster.my-address=' + instance.endpoint
      ];
      return this.startArango(instance.name, instance.endpoint, instance.role, args);
    })
    .then((instance) => this.waitForInstance(instance))
    .then((instance) => {
      this.instances = [
        ...this.instances.slice(0, i),
        instance,
        ...this.instances.slice(i + 1)
      ];
      return instance;
    });
  }

  startAgency (options = {}) {
    let size = options.agencySize || 1;
    if (options.agencyWaitForSync === undefined) {
      options.agencyWaitForSync = false;
    }
    const wfs = options.agencyWaitForSync;
    let promise = Promise.resolve([]);
    for (var i = 0; i < size; i++) {
      promise = promise.then(instances => {
        return this.runner.createEndpoint()
        .then(endpoint => {
          let index = instances.length;
          let args = [
            '--agency.activate=true',
            '--agency.size=' + size,
            '--agency.pool-size=' + size,
            '--agency.wait-for-sync=' + wfs,
            '--agency.supervision=true',
            '--agency.my-address=' + endpoint
          ];
          if (index === 0) {
            args.push('--agency.endpoint=' + endpoint);
          } else {
            args.push('--agency.endpoint=' + instances[0].endpoint);
          }
          return this.startArango('agency-' + (index + 1), endpoint, 'agent', args);
        })
        .then(instance => {
          return [...instances, instance];
        });
      });
    }
    return promise
    .then(agents => {
      this.instances = agents;
      return agents;
    });
  }

  startCluster (numAgents, numCoordinators, numDbServers, options = {}) {
    let agencyOptions = options.agents || {};
    _.extend(agencyOptions, {agencySize: numAgents});

    return this.startAgency(agencyOptions)
    .then(agents => {
      let promises = [Promise.resolve(agents)];

      let coordinatorOptions = options.coordinators || {};
      let coordinators = Array.from(Array(numDbServers).keys()).reduce((servers, index) => {
        return servers.then(instances => {
          return this.startCoordinator('coordinator-' + (index + 1), coordinatorOptions)
          .then(instance => {
            return [...instances, instance];
          });
        });
      }, Promise.resolve([]));
      promises.push(coordinators);

      let dbServerOptions = options.dbservers || {};
      let dbServers = Array.from(Array(numDbServers).keys()).reduce((dbServers, index) => {
        return dbServers.then(instances => {
          return this.startDbServer('dbServer-' + (index + 1), dbServerOptions)
          .then(instance => {
            return [...instances, instance];
          });
        });
      }, Promise.resolve([]));
      promises.push(dbServers);
      return Promise.all(promises);
    })
    .then(serverGroups => {
      let servers = [];
      serverGroups.forEach(serverGroup => {
        servers = servers.concat(serverGroup);
      });
      return servers;
    })
    .then(servers => {
      this.instances = servers;
      return this.waitForAllInstances();
    })
    .then(() => {
      return this.getEndpoint();
    });
  }

  waitForInstance (instance) {
    if (instance.status !== 'RUNNING') {
      return Promise.reject(new Error('Instance ' + instance.name + ' is down!'));
    }
    return rp(endpointToUrl(instance.endpoint) + '/_api/version')
    .then(() => {
      return instance;
    }, () => {
      return new Promise((resolve, reject) => {
        setTimeout(resolve, 100);
      })
      .then(() => {
        return this.waitForInstance(instance);
      });
    });
  }

  waitForAllInstances () {
    return Promise.all(this.instances.map(instance => {
      return this.waitForInstance(instance);
    }));
  }

  getEndpoint (instance) {
    return (instance || this.coordinators()[0]).endpoint;
  }

  getEndpointUrl (instance) {
    return endpointToUrl(this.getEndpoint());
  }

  check () {
    return this.instances.every(instance => {
      return instance.status === 'RUNNING';
    });
  }

  shutdownCluster () {
    let shutdownPromise;
    if (this.coordinators().length === 0) {
      shutdownPromise = Promise.all(this.agents().map(agent => {
        return agent.process.kill();
      }));
    } else {
      shutdownPromise = rp({
        method: 'DELETE',
        uri: endpointToUrl(this.getEndpoint()) + '/_admin/shutdown?shutdown_cluster=1'
      });
    }
    return shutdownPromise
    .then(() => {
      let checkDown = () => {
        let allDown = this.instances.every(instance => {
          return instance.status === 'EXITED';
        });

        if (allDown) {
          return Promise.resolve(true);
        } else {
          return new Promise((resolve, reject) => {
            setTimeout(() => {
              checkDown.bind(this)().then(resolve, reject);
            }, 100);
          });
        }
      };
      return checkDown();
    });
  }

  cleanup () {
    return this.shutdownCluster()
    .then(() => {
      this.instances = [];
      return this.runner.cleanup();
    })
    .then(() => {
      let log = this.currentLog;
      this.currentLog = '';
      return log;
    });
  }

  dbServers () {
    return this.instances.filter(instance => {
      return instance.role === 'primary';
    });
  }

  coordinators () {
    return this.instances.filter(instance => {
      return instance.role === 'coordinator';
    });
  }

  agents () {
    return this.instances.filter(instance => {
      return instance.role === 'agent';
    });
  }

  kill (instance, signal = 'SIGTERM') {
    let index = this.instances.indexOf(instance);
    if (index === -1) {
      throw new Error('Couldn\'t find instance ' + instance.name);
    }

    instance.process.kill(signal);
    instance.status = 'KILLED';
    return new Promise((resolve, reject) => {
      let check = function () {
        if (instance.status !== 'EXITED') {
          setTimeout(check, 50);
        } else {
          resolve();
        }
      };
      check();
    });
  }

  destroy (instance) {
    let promise;
    if (this.instances.includes(instance)) {
      promise = this.kill(instance);
    } else {
      promise = Promise.resolve();
    }
    return promise
    .then(() => this.runner.destroy(instance))
    .then(() => {
      const i = this.instances.indexOf(instance);
      if (i !== -1) {
        this.instances = [
          ...this.instances.slice(0, i),
          ...this.instances.slice(i + 1)
        ];
      }
    });
  }

  restart (instance) {
    let index = this.instances.indexOf(instance);
    if (index === -1) {
      throw new Error('Couldn\'t find instance ' + instance.name);
    }

    return this.runner.restart(instance)
    .then(() => {
      return this.waitForInstance(instance);
    });
  }
}

module.exports = InstanceManager;
<|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

export default ['$timeout', '$parse', ($timeout, $parse) => {
    return ($scope, $element, $attrs) => {
        const handlerCheckFocusOut = (FocusClick) => {
            if ($element.find(FocusClick.target).length)
                return;

            $parse($attrs.igniteOnFocusOut)($scope);

            $timeout();
        };

        window.addEventListener('click', handlerCheckFocusOut, true);
        window.addEventListener('focusin', handlerCheckFocusOut, true);

        $scope.$on('$destroy', () => {
            window.removeEventListener('click', handlerCheckFocusOut, true);
            window.removeEventListener('focusin', handlerCheckFocusOut, true);
        });
    };
}];
<commit_msg>IGNITE-7958 Optimize on-focus-out directive.     1. Don't parse expression every callback call.     2. Use $evalAsync instead of $timeout.<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

export default ['$parse', ($parse) => {
    return ($scope, $element, $attrs) => {
        const parsedExpr = $parse($attrs.igniteOnFocusOut);

        const handlerCheckFocusOut = (FocusClick) => {
            if ($element.find(FocusClick.target).length)
                return;

            $scope.$evalAsync(() => parsedExpr($scope));
        };

        window.addEventListener('click', handlerCheckFocusOut, true);
        window.addEventListener('focusin', handlerCheckFocusOut, true);

        $scope.$on('$destroy', () => {
            window.removeEventListener('click', handlerCheckFocusOut, true);
            window.removeEventListener('focusin', handlerCheckFocusOut, true);
        });
    };
}];
<|endoftext|>


<commit_before>class KeyRecorder {
  constructor(){
    this.keyPresses = [];
    this.firstRecordingAt = 0;
    this.latestRecordingAt = 0;
    this.isRecording = false;
  }

  getEvent(index){
    if (index < 0 || index > (this.keyPresses.length - 1)){
      return null;
    }
    return this.keyPresses[index];
  }

  startRecording(){
    console.log('recoder startRecording');
    this.isRecording = true;
  }

  stopRecording(){
    console.log('recoder stopRecording');
    this.isRecording = false;
  }

  recordKeyPress(keycode){
    let currentMillis = millis(); //-timeOffset;
    console.log("Recording key["+keycode+"] at time["+currentMillis+"]");
    if (this.firstRecordingAt == 0){
      this.firstRecordingAt = currentMillis;
    }
    this.latestRecordingAt = max(this.latestRecordingAt, currentMillis);
    this.keyPresses.push( new KeyEvent(keycode, currentMillis) );
  }

  getFirstRecordingTime(){
    return this.firstRecordingAt;
  }

  getLatestRecordingTime(){
    return this.latestRecordingAt;
  }
}
<commit_msg>p5js/keyviz - Remove debugging statements<commit_after>class KeyRecorder {
  constructor(){
    this.keyPresses = [];
    this.firstRecordingAt = 0;
    this.latestRecordingAt = 0;
    this.isRecording = false;
  }

  getEvent(index){
    if (index < 0 || index > (this.keyPresses.length - 1)){
      return null;
    }
    return this.keyPresses[index];
  }

  startRecording(){
    this.isRecording = true;
  }

  stopRecording(){
    this.isRecording = false;
  }

  recordKeyPress(keycode){
    let currentMillis = millis(); //-timeOffset;
    // console.log("Recording key["+keycode+"] at time["+currentMillis+"]");
    if (this.firstRecordingAt == 0){
      this.firstRecordingAt = currentMillis;
    }
    this.latestRecordingAt = max(this.latestRecordingAt, currentMillis);
    this.keyPresses.push( new KeyEvent(keycode, currentMillis) );
  }

  getFirstRecordingTime(){
    return this.firstRecordingAt;
  }

  getLatestRecordingTime(){
    return this.latestRecordingAt;
  }
}
<|endoftext|>


<commit_before>const Vue = require('vue')
const Vuetify = require('vuetify')
const fs = require('fs')
const map = require('./map')
const deepmerge = require('deepmerge')

function arrayMerge (a, b) {
  const arr = a.slice()
  for (let i = 0; i < b.length; i++) {
    const found = a.findIndex(item => item.name == b[i].name)
    if (found >= 0) {
      arr[found] = deepmerge(a[found], b[i])
    } else {
      arr.push(b[i])
    }
  }
  return arr
}

Vue.use(Vuetify)

function parseFunctionParams (func) {
  const groups = /function\s_.*\((.*)\)\s\{.*/i.exec(func)
  if (groups && groups.length > 1) return `(${groups[1]}) => {}`
  else return 'null'
}

function getPropType (type) {
  if (Array.isArray(type)) {
    return type.map(t => getPropType(t))
  }

  if (!type) return 'any'

  return type.name.toLowerCase()
}

function getPropDefault (def, type) {
  if (def === '' ||
    (def == null && type !== 'boolean' && type !== 'function')
  ) {
    return 'undefined'
  } else if (typeof(def) === 'function' && type !== 'function') {
    def = def()
  }

  if (type === 'boolean') {
    return def ? 'true' : 'false'
  }

  if (type === 'string') {
    return def ? `'${def}'` : def
  }

  if (type === 'function') {
    return parseFunctionParams(def)
  }

  return def
}

function getPropSource (name, mixins) {
  let source = null
  for (let i = 0; i < mixins.length; i++) {
    let mixin = mixins[i]
    if (mixin.name === 'VueComponent') mixin = mixin.options

    if (mixin.name) {
      const source = Object.keys(mixin.props || {}).find(p => p === name) && mixin.name
      let found = getPropSource(name, [mixin.extends].concat(mixin.mixins).filter(m => !!m)) || source
      if (found) return found
    }
  }

  return source
}

function genProp (name, props, mixins) {
  const prop = props[name]
  const type = getPropType(prop.type)
  const source = getPropSource(name, mixins)

  return {
    name,
    type,
    default: getPropDefault(prop.default, type),
    source
  }
}

function parseComponent (component) {
  return {
    props: parseProps(component),
    mixins: parseMixins(component)
  }
}

function parseProps (component, array = [], mixin = false) {
  const mixins = [component.extends].concat(component.mixins).filter(m => !!m)
  const props = component.props || {}

  Object.keys(props).forEach(prop => {
    let generated = genProp(prop, props, mixins)
    array.push(generated)
  })

  return array.sort((a, b) => a.name > b.name)
}

function parseMixins (component) {
  if (!component.mixins) return []

  let mixins = []
  for (let i = 0; i < component.mixins.length; i++) {
    let mixin = component.mixins[i]

    if (mixin.name === 'VueComponent') mixin = mixin.options

    if (mixin.name) {
      mixins.push(mixin.name)

      if (mixin.mixins) {
        mixins = mixins.concat(parseMixins(mixin))
      }
    }
  }

  return mixins.sort((a, b) => a > b)
}

const components = {}
const directives = {}

const installedComponents = Vue.options._base.options.components
const installedDirectives = Vue.options._base.options.directives

const hyphenateRE = /\B([A-Z])/g
const hyphenate = str => {
  return str.replace(hyphenateRE, '-$1').toLowerCase()
}

const componentNameRegex = /^(?:V[A-Z]|v-[a-z])/
for (const name in installedComponents) {
  if (!componentNameRegex.test(name)) continue

  let component = installedComponents[name]
  if (component.options.$_wrapperFor) {
    component = Vue.extend(component.options.$_wrapperFor)
  }

  const kebabName = hyphenate(name)
  let options = parseComponent(component.options || component)

  if (map[kebabName]) {
    options = deepmerge(options, map[kebabName], { arrayMerge })
  }

  components[kebabName] = options
}

for (const key of ['ripple', 'resize', 'scroll', 'touch']) {
  if (!installedDirectives[key]) continue

  const vKey = `v-${key}`
  const directive = map[vKey]
  directive.type = getPropDefault(directive.default, directive.type)
  directives[vKey] = directive
}

function writeApiFile (obj, file) {
  const stream = fs.createWriteStream(file)

  const comment = `/*
 * THIS FILE HAS BEEN AUTOMATICALLY GENERATED USING THE API-GENERATOR TOOL.
 *
 * CHANGES MADE TO THIS FILE WILL BE LOST!
 */

`

  stream.once('open', () => {
    stream.write(comment)
    stream.write('module.exports = ')
    stream.write(JSON.stringify(obj, null, 2))
    stream.end()
  })
}

function writeJsonFile (obj, file) {
  const stream = fs.createWriteStream(file)

  stream.once('open', () => {
    stream.write(JSON.stringify(obj, null, 2))
    stream.end()
  })
}

function writePlainFile (content, file) {
  const stream = fs.createWriteStream(file)

  stream.once('open', () => {
    stream.write(content)
    stream.end()
  })
}

const tags = Object.keys(components).reduce((t, k) => {
  t[k] = {
    attributes: components[k].props.map(p => p.name.replace(/([A-Z])/g, (g) => `-${g[0].toLowerCase()}`)).sort(),
    description: ''
  }

  return t
}, {})

const attributes = Object.keys(components).reduce((attrs, k) => {
  const tmp = components[k].props.reduce((a, prop) => {
    let type = prop.type

    if (!type) type = ''
    else if (Array.isArray(type)) type = type.map(t => t.toLowerCase()).join('|')
    else type = type.toLowerCase()

    const name = prop.name.replace(/([A-Z])/g, (g) => `-${g[0].toLowerCase()}`)

    a[`${k}/${name}`] = {
      type,
      description: ''
    }

    return a
  }, {})

  return Object.assign(attrs, tmp)
}, {})

const fakeComponents = `import Vue from 'vue'\n\n` + Object.keys(components).map(component => {
  const propType = type => {
    if (type === 'any') return 'null'
    if (Array.isArray(type)) return `[${type.map(s => s.charAt(0).toUpperCase() + s.slice(1)).join(',')}]`
    return type.charAt(0).toUpperCase() + type.slice(1)
  }
  const quoteProp = name => name.match(/-/) ? `'${name}'` : name
  let props = components[component].props.map(prop => `    ${quoteProp(prop.name)}: ${propType(prop.type)}`).join(',\n')
  if (props) props = `\n  props: {\n${props}\n  }\n`
  return `// noinspection JSUnresolvedFunction\nVue.component('${component}', {${props}})`
}).join('\n')

writeJsonFile(tags, 'dist/tags.json')
writeJsonFile(attributes, 'dist/attributes.json')
writePlainFile(fakeComponents, 'dist/fakeComponents.js')

components['$vuetify'] = map['$vuetify']

writeApiFile({ ...components, ...directives }, 'dist/api.js')
<commit_msg>enh: sort props<commit_after>const Vue = require('vue')
const Vuetify = require('vuetify')
const fs = require('fs')
const map = require('./map')
const deepmerge = require('deepmerge')

function arrayMerge (a, b) {
  const arr = a.slice()
  for (let i = 0; i < b.length; i++) {
    const found = a.findIndex(item => item.name == b[i].name)
    if (found >= 0) {
      arr[found] = deepmerge(a[found], b[i])
    } else {
      arr.push(b[i])
    }
  }
  return arr
}

Vue.use(Vuetify)

function parseFunctionParams (func) {
  const groups = /function\s_.*\((.*)\)\s\{.*/i.exec(func)
  if (groups && groups.length > 1) return `(${groups[1]}) => {}`
  else return 'null'
}

function getPropType (type) {
  if (Array.isArray(type)) {
    return type.map(t => getPropType(t))
  }

  if (!type) return 'any'

  return type.name.toLowerCase()
}

function getPropDefault (def, type) {
  if (def === '' ||
    (def == null && type !== 'boolean' && type !== 'function')
  ) {
    return 'undefined'
  } else if (typeof(def) === 'function' && type !== 'function') {
    def = def()
  }

  if (type === 'boolean') {
    return def ? 'true' : 'false'
  }

  if (type === 'string') {
    return def ? `'${def}'` : def
  }

  if (type === 'function') {
    return parseFunctionParams(def)
  }

  return def
}

function getPropSource (name, mixins) {
  let source = null
  for (let i = 0; i < mixins.length; i++) {
    let mixin = mixins[i]
    if (mixin.name === 'VueComponent') mixin = mixin.options

    if (mixin.name) {
      const source = Object.keys(mixin.props || {}).find(p => p === name) && mixin.name
      let found = getPropSource(name, [mixin.extends].concat(mixin.mixins).filter(m => !!m)) || source
      if (found) return found
    }
  }

  return source
}

function genProp (name, props, mixins) {
  const prop = props[name]
  const type = getPropType(prop.type)
  const source = getPropSource(name, mixins)

  return {
    name,
    type,
    default: getPropDefault(prop.default, type),
    source
  }
}

function parseComponent (component) {
  return {
    props: parseProps(component),
    mixins: parseMixins(component)
  }
}

function parseProps (component, array = [], mixin = false) {
  const mixins = [component.extends].concat(component.mixins).filter(m => !!m)
  const props = component.props || {}

  Object.keys(props).forEach(prop => {
    let generated = genProp(prop, props, mixins)
    array.push(generated)
  })

  return array.sort((a, b) => a.name > b.name)
}

function parseMixins (component) {
  if (!component.mixins) return []

  let mixins = []
  for (let i = 0; i < component.mixins.length; i++) {
    let mixin = component.mixins[i]

    if (mixin.name === 'VueComponent') mixin = mixin.options

    if (mixin.name) {
      mixins.push(mixin.name)

      if (mixin.mixins) {
        mixins = mixins.concat(parseMixins(mixin))
      }
    }
  }

  return mixins.sort((a, b) => a > b)
}

const components = {}
const directives = {}

const installedComponents = Vue.options._base.options.components
const installedDirectives = Vue.options._base.options.directives

const hyphenateRE = /\B([A-Z])/g
const hyphenate = str => {
  return str.replace(hyphenateRE, '-$1').toLowerCase()
}

const componentNameRegex = /^(?:V[A-Z]|v-[a-z])/
for (const name in installedComponents) {
  if (!componentNameRegex.test(name)) continue

  let component = installedComponents[name]
  if (component.options.$_wrapperFor) {
    component = Vue.extend(component.options.$_wrapperFor)
  }

  const kebabName = hyphenate(name)
  let options = parseComponent(component.options || component)

  if (map[kebabName]) {
    options = deepmerge(options, map[kebabName], { arrayMerge })
  }

  components[kebabName] = options
}

for (const key of ['ripple', 'resize', 'scroll', 'touch']) {
  if (!installedDirectives[key]) continue

  const vKey = `v-${key}`
  const directive = map[vKey]
  directive.type = getPropDefault(directive.default, directive.type)
  directives[vKey] = directive
}

function writeApiFile (obj, file) {
  const stream = fs.createWriteStream(file)

  const comment = `/*
 * THIS FILE HAS BEEN AUTOMATICALLY GENERATED USING THE API-GENERATOR TOOL.
 *
 * CHANGES MADE TO THIS FILE WILL BE LOST!
 */

`

  stream.once('open', () => {
    stream.write(comment)
    stream.write('module.exports = ')
    stream.write(JSON.stringify(obj, null, 2))
    stream.end()
  })
}

function writeJsonFile (obj, file) {
  const stream = fs.createWriteStream(file)

  stream.once('open', () => {
    stream.write(JSON.stringify(obj, null, 2))
    stream.end()
  })
}

function writePlainFile (content, file) {
  const stream = fs.createWriteStream(file)

  stream.once('open', () => {
    stream.write(content)
    stream.end()
  })
}

const tags = Object.keys(components).reduce((t, k) => {
  t[k] = {
    attributes: components[k].props.map(p => p.name.replace(/([A-Z])/g, (g) => `-${g[0].toLowerCase()}`)).sort(),
    description: ''
  }

  return t
}, {})

const attributes = Object.keys(components).reduce((attrs, k) => {
  const tmp = components[k].props.reduce((a, prop) => {
    let type = prop.type

    if (!type) type = ''
    else if (Array.isArray(type)) type = type.map(t => t.toLowerCase()).join('|')
    else type = type.toLowerCase()

    const name = prop.name.replace(/([A-Z])/g, (g) => `-${g[0].toLowerCase()}`)

    a[`${k}/${name}`] = {
      type,
      description: ''
    }

    return a
  }, {})

  return Object.assign(attrs, tmp)
}, {})

const fakeComponents = `import Vue from 'vue'\n\n` + Object.keys(components).map(component => {
  const propType = type => {
    if (type === 'any' || typeof type === 'undefined') return 'null'
    if (Array.isArray(type)) return `[${type.map(s => s.charAt(0).toUpperCase() + s.slice(1)).join(',')}]`
    return type.charAt(0).toUpperCase() + type.slice(1)
  }
  const quoteProp = name => name.match(/-/) ? `'${name}'` : name
  const componentProps = components[component].props
  componentProps.sort((a, b) => {
    if (a.name < b.name) return -1;
    return a.name === b.name ? 0 : 1;
  })
  let props = componentProps.map(prop => `    ${quoteProp(prop.name)}: ${propType(prop.type)}`).join(',\n')
  if (props) props = `\n  props: {\n${props}\n  }\n`
  return `// noinspection JSUnresolvedFunction\nVue.component('${component}', {${props}})`
}).join('\n')

writeJsonFile(tags, 'dist/tags.json')
writeJsonFile(attributes, 'dist/attributes.json')
writePlainFile(fakeComponents, 'dist/fakeComponents.js')

components['$vuetify'] = map['$vuetify']

writeApiFile({ ...components, ...directives }, 'dist/api.js')
<|endoftext|>


<commit_before>// ==UserScript==
// @name         Ads DOM Remover
// @namespace    sagiegurari
// @version      1.24
// @author       Sagie Gur-Ari
// @description  Removes Ad Containers from DOM (doesn't replace adblocker extension, but blocks dynamic content which the adblocker fails to block by removing whole sections from the HTML DOM.)
// @homepage     https://github.com/sagiegurari/userscripts-ads-dom-remover
// @supportURL   https://github.com/sagiegurari/userscripts-ads-dom-remover/issues
// @match        http://www.ynet.co.il/home/*
// @match        https://www.ynet.co.il/home/*
// @match        http://www.ynet.co.il/articles/*
// @match        https://www.ynet.co.il/articles/*
// @match        http://www.mynet.co.il/articles/*
// @match        https://www.mynet.co.il/articles/*
// @match        http://www.calcalist.co.il/*
// @match        https://www.calcalist.co.il/*
// @match        http://www.globes.co.il/*
// @match        https://www.globes.co.il/*
// @match        https://sourceforge.net/projects/*/download*
// @match        https://sourceforge.net/projects/*/postdownload*
// @match        http://subscenter.cinemast.com/*
// @match        https://subscenter.cinemast.com/*
// @match        http://www.subscenter.co/*
// @match        https://www.subscenter.co/*
// @match        http://www.subscenter.org/*
// @match        https://www.subscenter.org/*
// @match        https://*.wikipedia.org/*
// @match        http://*.techonthenet.com/*
// @match        https://*.techonthenet.com/*
// @match        http://www.opensubtitles.org/*
// @match        https://www.opensubtitles.org/*
// @match        http://*.wikia.com/wiki/*
// @match        https://*.wikia.com/wiki/*
// @match        http://*.reddit.com/*
// @match        https://*.reddit.com/*
// @match        http://*.youtube.com/*
// @match        https://*.youtube.com/*
// @match        http://*.bostonglobe.com/*
// @match        https://*.bostonglobe.com/*
// @require      https://code.jquery.com/jquery-2.2.2.min.js
// @require      https://greasyfork.org/scripts/18490-ads-dom-remover-runner/code/Ads%20DOM%20Remover%20Runner.js?version=684030
// @grant        none
// @license      MIT License
// ==/UserScript==

(function run($, runner) {
    'use strict';

    var selectorDefinitions = {
        ynet: {
            hostNames: [
                'ynet',
                'calcalist'
            ],
            selectors: [
                '#colorbox',
                '#cboxOverlay',
                '#ads.premium',
                '#articleLayoutrightsidtable',
                '#google_image_div',
                'img[src*="dynamicyield"]',
                'div.MSCmainContent',
                '[id*="arketingCarouse"]',
                '[id*="arketingRecommended"]',
                '.mainVerticalArticleSharingLinks',
                '.OUTBRAIN',
                '.topBannerWrap',
                '.block.B3 .B3.ghcite.dyother.dyMonitor div',
                '.bigdealhomepage',
                '#ww6s_Main',
                '.buyandsavedy',
                '.area.footer.ghcite',
                '.hdr_set_homepage',
                '#c1_Hor',
                '#c2_Hor',
                '#c3_Hor',
                '#c4_Hor',
                '#c5_Hor',
                '#c6_Hor',
                '.homepagevideo-x6',
                '.buyandsave',
                '.general-image',
                '.PhotoArticlesTalkbacks',
                '[name="ExternalWebpageIframe"]',
                '#PROCOIL_SearchForm',
                '#magazines1024',
                '[id^="promo_"]',
                '[id^="ads."]',
                '[class*="facebook"]',
                '[class*="WinWin"]',
                '.main_search_radio',
                'tr td [id^="ads."]',
                '.art-action-wrp',
                '.header-user-profile',
                '.left-art-content',
                '[class*="GeneralBanner"]',
                '#vilon',
                '#prime.shook',
                '#articlebottomsharinglinks',
                '.floatingPlayerimReallyDummy_container',
                {
                    selector: '.homepagelitevideo',
                    fineTuneSelector: function ($element) {
                        return $element.parent().parent();
                    }
                },
                {
                    selector: 'iframe',
                    fineTuneSelector: function ($element) {
                        return $element.filter(function () {
                            return !$(this).parent().hasClass('news_ticker_iframe');
                        });
                    }
                },
                {
                    selector: 'div.B2b.block div',
                    pre: function ($element) {
                        $element.parent().css({
                            height: '1px'
                        });
                    }
                }
            ]
        },
        globes: {
            hostNames: 'globes',
            selectors: [
                '#chromeWindow',
                {
                    selector: 'iframe',
                    filter: function ($element) {
                        var id = $element.attr('id');
                        var src = $element.attr('src') || '';

                        return (id !== 'GlobalFinanceData_home') && (src.indexOf('/news/') !== -1);
                    }
                }
            ]
        },
        techonthenet: {
            hostNames: 'techonthenet.com',
            selectors: ['.adsblocked']
        },
        sourceforge: {
            hostNames: 'sourceforge.net',
            selectors: [
                '#content-for-adblock',
                '#newsletter-floating',
                '#page-body'
            ]
        },
        subscenter: {
            hostNames: 'subscenter',
            selectors: [
                '.weekBottom',
                '.reviewsWindow',
                '#banner_cinemast',
                '.bottomMenu',
                'footer',
                '#paypal',
                '#aboveSite',
                {
                    selector: '#subtitles_list a[href="/he/contactus/"]',
                    fineTuneSelector: function ($element) {
                        return $element.parent();
                    }
                }
            ]
        },
        wikipedia: {
            hostNames: 'wikipedia.org',
            selectors: [
                '#frbanner',
                '#frb-inline',
                '#wlm-banner',
                '#centralNotice',
                '.frb-main',
                '.frbanner',
                '.frm',
                '.frb'
            ]
        },
        opensubtitles: {
            hostNames: 'opensubtitles',
            selectors: ['.rec_container_right']
        },
        wikia: {
            hostNames: 'wikia.com',
            selectors: [
                '.WikiaFooter',
                '.WikiaRail',
                '.wds-global-footer'
            ]
        },
        reddit: {
            hostNames: 'reddit.com',
            selectors: ['#onboarding-splash']
        },
        youtube: {
            hostNames: 'youtube.com',
            selectors: [
                '.ytp-ce-element',
                'ytd-companion-slot-renderer',
                '#masthead-ad',
                '.video-ads ytp-ad-module',
                '.ytp-ad-overlay-ad-info-dialog-container',
                '.ytp-ad-overlay-slot'
            ],
            options: {
                loops: 200,
                interval: 2500
            }
        },
        bostonglobe: {
            hostNames: 'bostonglobe.com',
            selectors: [
                '.meter-social-connect',
                '.meter-social-connect__container'
            ]
        }
    };

    [
        '#dcPremiumRightImg',
        '.boulevard',
        '#multiarticles-9',
        '#multiarticles-12',
        '#multiarticles-13',
        '#multiarticles-14',
        '#multiarticles-15',
        '#multiarticles-16',
        '.CdaMostViews',
        '.CdaCalcalistToday',
        '.CdaRecomendedMovies',
        '#SpecialBuilder1280',
        '.cdaFooter1280'
    ].forEach(function addSelector(selector) {
        selectorDefinitions.ynet.selectors.push({
            selector: selector,
            fineTuneSelector: function ($element) {
                return $element.parent();
            }
        });
    });

    runner($, {
        getSelectorDefinitions: function () {
            return selectorDefinitions;
        }
    });
}(window.jQuery.noConflict(true), window.adrRunner));
<commit_msg>reddit<commit_after>// ==UserScript==
// @name         Ads DOM Remover
// @namespace    sagiegurari
// @version      1.25
// @author       Sagie Gur-Ari
// @description  Removes Ad Containers from DOM (doesn't replace adblocker extension, but blocks dynamic content which the adblocker fails to block by removing whole sections from the HTML DOM.)
// @homepage     https://github.com/sagiegurari/userscripts-ads-dom-remover
// @supportURL   https://github.com/sagiegurari/userscripts-ads-dom-remover/issues
// @match        http://www.ynet.co.il/home/*
// @match        https://www.ynet.co.il/home/*
// @match        http://www.ynet.co.il/articles/*
// @match        https://www.ynet.co.il/articles/*
// @match        http://www.mynet.co.il/articles/*
// @match        https://www.mynet.co.il/articles/*
// @match        http://www.calcalist.co.il/*
// @match        https://www.calcalist.co.il/*
// @match        http://www.globes.co.il/*
// @match        https://www.globes.co.il/*
// @match        https://sourceforge.net/projects/*/download*
// @match        https://sourceforge.net/projects/*/postdownload*
// @match        http://subscenter.cinemast.com/*
// @match        https://subscenter.cinemast.com/*
// @match        http://www.subscenter.co/*
// @match        https://www.subscenter.co/*
// @match        http://www.subscenter.org/*
// @match        https://www.subscenter.org/*
// @match        https://*.wikipedia.org/*
// @match        http://*.techonthenet.com/*
// @match        https://*.techonthenet.com/*
// @match        http://www.opensubtitles.org/*
// @match        https://www.opensubtitles.org/*
// @match        http://*.wikia.com/wiki/*
// @match        https://*.wikia.com/wiki/*
// @match        http://*.reddit.com/*
// @match        https://*.reddit.com/*
// @match        http://*.youtube.com/*
// @match        https://*.youtube.com/*
// @match        http://*.bostonglobe.com/*
// @match        https://*.bostonglobe.com/*
// @require      https://code.jquery.com/jquery-2.2.2.min.js
// @require      https://greasyfork.org/scripts/18490-ads-dom-remover-runner/code/Ads%20DOM%20Remover%20Runner.js?version=684030
// @grant        none
// @license      MIT License
// ==/UserScript==

(function run($, runner) {
    'use strict';

    var selectorDefinitions = {
        ynet: {
            hostNames: [
                'ynet',
                'calcalist'
            ],
            selectors: [
                '#colorbox',
                '#cboxOverlay',
                '#ads.premium',
                '#articleLayoutrightsidtable',
                '#google_image_div',
                'img[src*="dynamicyield"]',
                'div.MSCmainContent',
                '[id*="arketingCarouse"]',
                '[id*="arketingRecommended"]',
                '.mainVerticalArticleSharingLinks',
                '.OUTBRAIN',
                '.topBannerWrap',
                '.block.B3 .B3.ghcite.dyother.dyMonitor div',
                '.bigdealhomepage',
                '#ww6s_Main',
                '.buyandsavedy',
                '.area.footer.ghcite',
                '.hdr_set_homepage',
                '#c1_Hor',
                '#c2_Hor',
                '#c3_Hor',
                '#c4_Hor',
                '#c5_Hor',
                '#c6_Hor',
                '.homepagevideo-x6',
                '.buyandsave',
                '.general-image',
                '.PhotoArticlesTalkbacks',
                '[name="ExternalWebpageIframe"]',
                '#PROCOIL_SearchForm',
                '#magazines1024',
                '[id^="promo_"]',
                '[id^="ads."]',
                '[class*="facebook"]',
                '[class*="WinWin"]',
                '.main_search_radio',
                'tr td [id^="ads."]',
                '.art-action-wrp',
                '.header-user-profile',
                '.left-art-content',
                '[class*="GeneralBanner"]',
                '#vilon',
                '#prime.shook',
                '#articlebottomsharinglinks',
                '.floatingPlayerimReallyDummy_container',
                {
                    selector: '.homepagelitevideo',
                    fineTuneSelector: function ($element) {
                        return $element.parent().parent();
                    }
                },
                {
                    selector: 'iframe',
                    fineTuneSelector: function ($element) {
                        return $element.filter(function () {
                            return !$(this).parent().hasClass('news_ticker_iframe');
                        });
                    }
                },
                {
                    selector: 'div.B2b.block div',
                    pre: function ($element) {
                        $element.parent().css({
                            height: '1px'
                        });
                    }
                }
            ]
        },
        globes: {
            hostNames: 'globes',
            selectors: [
                '#chromeWindow',
                {
                    selector: 'iframe',
                    filter: function ($element) {
                        var id = $element.attr('id');
                        var src = $element.attr('src') || '';

                        return (id !== 'GlobalFinanceData_home') && (src.indexOf('/news/') !== -1);
                    }
                }
            ]
        },
        techonthenet: {
            hostNames: 'techonthenet.com',
            selectors: ['.adsblocked']
        },
        sourceforge: {
            hostNames: 'sourceforge.net',
            selectors: [
                '#content-for-adblock',
                '#newsletter-floating',
                '#page-body'
            ]
        },
        subscenter: {
            hostNames: 'subscenter',
            selectors: [
                '.weekBottom',
                '.reviewsWindow',
                '#banner_cinemast',
                '.bottomMenu',
                'footer',
                '#paypal',
                '#aboveSite',
                {
                    selector: '#subtitles_list a[href="/he/contactus/"]',
                    fineTuneSelector: function ($element) {
                        return $element.parent();
                    }
                }
            ]
        },
        wikipedia: {
            hostNames: 'wikipedia.org',
            selectors: [
                '#frbanner',
                '#frb-inline',
                '#wlm-banner',
                '#centralNotice',
                '.frb-main',
                '.frbanner',
                '.frm',
                '.frb'
            ]
        },
        opensubtitles: {
            hostNames: 'opensubtitles',
            selectors: ['.rec_container_right']
        },
        wikia: {
            hostNames: 'wikia.com',
            selectors: [
                '.WikiaFooter',
                '.WikiaRail',
                '.wds-global-footer'
            ]
        },
        reddit: {
            hostNames: 'reddit.com',
            selectors: [
                '#onboarding-splash',
                '[id^="google_ads"]'
            ]
        },
        youtube: {
            hostNames: 'youtube.com',
            selectors: [
                '.ytp-ce-element',
                'ytd-companion-slot-renderer',
                '#masthead-ad',
                '.video-ads ytp-ad-module',
                '.ytp-ad-overlay-ad-info-dialog-container',
                '.ytp-ad-overlay-slot'
            ],
            options: {
                loops: 200,
                interval: 2500
            }
        },
        bostonglobe: {
            hostNames: 'bostonglobe.com',
            selectors: [
                '.meter-social-connect',
                '.meter-social-connect__container'
            ]
        }
    };

    [
        '#dcPremiumRightImg',
        '.boulevard',
        '#multiarticles-9',
        '#multiarticles-12',
        '#multiarticles-13',
        '#multiarticles-14',
        '#multiarticles-15',
        '#multiarticles-16',
        '.CdaMostViews',
        '.CdaCalcalistToday',
        '.CdaRecomendedMovies',
        '#SpecialBuilder1280',
        '.cdaFooter1280'
    ].forEach(function addSelector(selector) {
        selectorDefinitions.ynet.selectors.push({
            selector: selector,
            fineTuneSelector: function ($element) {
                return $element.parent();
            }
        });
    });

    runner($, {
        getSelectorDefinitions: function () {
            return selectorDefinitions;
        }
    });
}(window.jQuery.noConflict(true), window.adrRunner));
<|endoftext|>


<commit_before>// ==UserScript==
// @name         Ads DOM Remover
// @namespace    sagiegurari
// @version      1.18
// @author       Sagie Gur-Ari
// @description  Removes Ad Containers from DOM (doesn't replace adblocker extension, but blocks dynamic content which the adblocker fails to block by removing whole sections from the HTML DOM.)
// @homepage     https://github.com/sagiegurari/userscripts-ads-dom-remover
// @supportURL   https://github.com/sagiegurari/userscripts-ads-dom-remover/issues
// @match        http://www.ynet.co.il/home/*
// @match        https://www.ynet.co.il/home/*
// @match        http://www.ynet.co.il/articles/*
// @match        https://www.ynet.co.il/articles/*
// @match        http://www.mynet.co.il/articles/*
// @match        https://www.mynet.co.il/articles/*
// @match        http://www.calcalist.co.il/*
// @match        https://www.calcalist.co.il/*
// @match        http://www.globes.co.il/*
// @match        https://www.globes.co.il/*
// @match        https://sourceforge.net/projects/*/download*
// @match        https://sourceforge.net/projects/*/postdownload*
// @match        http://subscenter.cinemast.com/*
// @match        https://subscenter.cinemast.com/*
// @match        http://www.subscenter.co/*
// @match        https://www.subscenter.co/*
// @match        http://www.subscenter.org/*
// @match        https://www.subscenter.org/*
// @match        https://*.wikipedia.org/*
// @match        http://*.techonthenet.com/*
// @match        https://*.techonthenet.com/*
// @match        http://www.opensubtitles.org/*
// @match        https://www.opensubtitles.org/*
// @match        http://*.wikia.com/wiki/*
// @match        https://*.wikia.com/wiki/*
// @match        http://*.reddit.com/*
// @match        https://*.reddit.com/*
// @match        http://*.bostonglobe.com/*
// @match        https://*.bostonglobe.com/*
// @require      https://code.jquery.com/jquery-2.2.2.min.js
// @require      https://greasyfork.org/scripts/18490-ads-dom-remover-runner/code/Ads%20DOM%20Remover%20Runner.js?version=189663
// @grant        none
// @license      MIT License
// ==/UserScript==

(function run($, runner) {
    'use strict';

    var selectorDefinitions = {
        ynet: {
            hostNames: [
                'ynet',
                'calcalist'
            ],
            selectors: [
                '#colorbox',
                '#cboxOverlay',
                '#ads.premium',
                '#articleLayoutrightsidtable',
                '#google_image_div',
                'img[src*="dynamicyield"]',
                'div.MSCmainContent',
                '[id*="arketingCarouse"]',
                '[id*="arketingRecommended"]',
                '.mainVerticalArticleSharingLinks',
                '.OUTBRAIN',
                '.topBannerWrap',
                '.block.B3 .B3.ghcite.dyother.dyMonitor div',
                '.bigdealhomepage',
                '#ww6s_Main',
                '.buyandsavedy',
                '.area.footer.ghcite',
                '.hdr_set_homepage',
                '#c1_Hor',
                '#c2_Hor',
                '#c3_Hor',
                '#c4_Hor',
                '#c5_Hor',
                '#c6_Hor',
                '.homepagevideo-x6',
                '.buyandsave',
                '.general-image',
                '.PhotoArticlesTalkbacks',
                '[name="ExternalWebpageIframe"]',
                '#PROCOIL_SearchForm',
                '#magazines1024',
                '[id^="promo_"]',
                '[id^="ads."]',
                '[class*="facebook"]',
                '[class*="WinWin"]',
                '.main_search_radio',
                'tr td [id^="ads."]',
                '.art-action-wrp',
                '.header-user-profile',
                '.left-art-content',
                '[class*="GeneralBanner"]',
                '#vilon',
                '#prime.shook',
                '#articlebottomsharinglinks',
                {
                    selector: '.homepagelitevideo',
                    fineTuneSelector: function ($element) {
                        return $element.parent().parent();
                    }
                },
                {
                    selector: 'iframe',
                    fineTuneSelector: function ($element) {
                        return $element.filter(function () {
                            return !$(this).parent().hasClass('news_ticker_iframe');
                        });
                    }
                },
                {
                    selector: 'div.B2b.block div',
                    pre: function ($element) {
                        $element.parent().css({
                            height: '1px'
                        });
                    }
                }
            ]
        },
        globes: {
            hostNames: 'globes',
            selectors: [
                '#chromeWindow',
                {
                    selector: 'iframe',
                    filter: function ($element) {
                        var id = $element.attr('id');
                        var src = $element.attr('src') || '';

                        return (id !== 'GlobalFinanceData_home') && (src.indexOf('/news/') !== -1);
                    }
                }
            ]
        },
        techonthenet: {
            hostNames: 'techonthenet.com',
            selectors: ['.adsblocked']
        },
        sourceforge: {
            hostNames: 'sourceforge.net',
            selectors: [
                '#content-for-adblock',
                '#newsletter-floating',
                '#page-body'
            ]
        },
        subscenter: {
            hostNames: 'subscenter',
            selectors: [
                '.weekBottom',
                '.reviewsWindow',
                '#banner_cinemast',
                '.bottomMenu',
                'footer',
                '#paypal',
                '#aboveSite',
                {
                    selector: '#subtitles_list a[href="/he/contactus/"]',
                    fineTuneSelector: function ($element) {
                        return $element.parent();
                    }
                }
            ]
        },
        wikipedia: {
            hostNames: 'wikipedia.org',
            selectors: [
                '#frbanner',
                '#frb-inline',
                '#wlm-banner',
                '#centralNotice',
                '.frb-main',
                '.frbanner',
                '.frm',
                '.frb'
            ]
        },
        opensubtitles: {
            hostNames: 'opensubtitles',
            selectors: ['.rec_container_right']
        },
        wikia: {
            hostNames: 'wikia.com',
            selectors: [
                '.WikiaFooter',
                '.WikiaRail',
                '.wds-global-footer'
            ]
        },
        reddit: {
            hostNames: 'reddit.com',
            selectors: ['#onboarding-splash']
        },
        bostonglobe: {
            hostNames: 'bostonglobe.com',
            selectors: [
                '.meter-social-connect',
                '.meter-social-connect__container'
            ]
        }
    };

    [
        '#dcPremiumRightImg',
        '.boulevard',
        '#multiarticles-9',
        '#multiarticles-12',
        '#multiarticles-13',
        '#multiarticles-14',
        '#multiarticles-15',
        '#multiarticles-16',
        '.CdaMostViews',
        '.CdaCalcalistToday',
        '.CdaRecomendedMovies',
        '#SpecialBuilder1280',
        '.cdaFooter1280'
    ].forEach(function addSelector(selector) {
        selectorDefinitions.ynet.selectors.push({
            selector: selector,
            fineTuneSelector: function ($element) {
                return $element.parent();
            }
        });
    });

    runner($, {
        getSelectorDefinitions: function () {
            return selectorDefinitions;
        }
    });
}(window.jQuery.noConflict(true), window.adrRunner));
<commit_msg>update selectors<commit_after>// ==UserScript==
// @name         Ads DOM Remover
// @namespace    sagiegurari
// @version      1.19
// @author       Sagie Gur-Ari
// @description  Removes Ad Containers from DOM (doesn't replace adblocker extension, but blocks dynamic content which the adblocker fails to block by removing whole sections from the HTML DOM.)
// @homepage     https://github.com/sagiegurari/userscripts-ads-dom-remover
// @supportURL   https://github.com/sagiegurari/userscripts-ads-dom-remover/issues
// @match        http://www.ynet.co.il/home/*
// @match        https://www.ynet.co.il/home/*
// @match        http://www.ynet.co.il/articles/*
// @match        https://www.ynet.co.il/articles/*
// @match        http://www.mynet.co.il/articles/*
// @match        https://www.mynet.co.il/articles/*
// @match        http://www.calcalist.co.il/*
// @match        https://www.calcalist.co.il/*
// @match        http://www.globes.co.il/*
// @match        https://www.globes.co.il/*
// @match        https://sourceforge.net/projects/*/download*
// @match        https://sourceforge.net/projects/*/postdownload*
// @match        http://subscenter.cinemast.com/*
// @match        https://subscenter.cinemast.com/*
// @match        http://www.subscenter.co/*
// @match        https://www.subscenter.co/*
// @match        http://www.subscenter.org/*
// @match        https://www.subscenter.org/*
// @match        https://*.wikipedia.org/*
// @match        http://*.techonthenet.com/*
// @match        https://*.techonthenet.com/*
// @match        http://www.opensubtitles.org/*
// @match        https://www.opensubtitles.org/*
// @match        http://*.wikia.com/wiki/*
// @match        https://*.wikia.com/wiki/*
// @match        http://*.reddit.com/*
// @match        https://*.reddit.com/*
// @match        http://*.bostonglobe.com/*
// @match        https://*.bostonglobe.com/*
// @require      https://code.jquery.com/jquery-2.2.2.min.js
// @require      https://greasyfork.org/scripts/18490-ads-dom-remover-runner/code/Ads%20DOM%20Remover%20Runner.js?version=189663
// @grant        none
// @license      MIT License
// ==/UserScript==

(function run($, runner) {
    'use strict';

    var selectorDefinitions = {
        ynet: {
            hostNames: [
                'ynet',
                'calcalist'
            ],
            selectors: [
                '#colorbox',
                '#cboxOverlay',
                '#ads.premium',
                '#articleLayoutrightsidtable',
                '#google_image_div',
                'img[src*="dynamicyield"]',
                'div.MSCmainContent',
                '[id*="arketingCarouse"]',
                '[id*="arketingRecommended"]',
                '.mainVerticalArticleSharingLinks',
                '.OUTBRAIN',
                '.topBannerWrap',
                '.block.B3 .B3.ghcite.dyother.dyMonitor div',
                '.bigdealhomepage',
                '#ww6s_Main',
                '.buyandsavedy',
                '.area.footer.ghcite',
                '.hdr_set_homepage',
                '#c1_Hor',
                '#c2_Hor',
                '#c3_Hor',
                '#c4_Hor',
                '#c5_Hor',
                '#c6_Hor',
                '.homepagevideo-x6',
                '.buyandsave',
                '.general-image',
                '.PhotoArticlesTalkbacks',
                '[name="ExternalWebpageIframe"]',
                '#PROCOIL_SearchForm',
                '#magazines1024',
                '[id^="promo_"]',
                '[id^="ads."]',
                '[class*="facebook"]',
                '[class*="WinWin"]',
                '.main_search_radio',
                'tr td [id^="ads."]',
                '.art-action-wrp',
                '.header-user-profile',
                '.left-art-content',
                '[class*="GeneralBanner"]',
                '#vilon',
                '#prime.shook',
                '#articlebottomsharinglinks',
                '.floatingPlayerimReallyDummy_container',
                {
                    selector: '.homepagelitevideo',
                    fineTuneSelector: function ($element) {
                        return $element.parent().parent();
                    }
                },
                {
                    selector: 'iframe',
                    fineTuneSelector: function ($element) {
                        return $element.filter(function () {
                            return !$(this).parent().hasClass('news_ticker_iframe');
                        });
                    }
                },
                {
                    selector: 'div.B2b.block div',
                    pre: function ($element) {
                        $element.parent().css({
                            height: '1px'
                        });
                    }
                }
            ]
        },
        globes: {
            hostNames: 'globes',
            selectors: [
                '#chromeWindow',
                {
                    selector: 'iframe',
                    filter: function ($element) {
                        var id = $element.attr('id');
                        var src = $element.attr('src') || '';

                        return (id !== 'GlobalFinanceData_home') && (src.indexOf('/news/') !== -1);
                    }
                }
            ]
        },
        techonthenet: {
            hostNames: 'techonthenet.com',
            selectors: ['.adsblocked']
        },
        sourceforge: {
            hostNames: 'sourceforge.net',
            selectors: [
                '#content-for-adblock',
                '#newsletter-floating',
                '#page-body'
            ]
        },
        subscenter: {
            hostNames: 'subscenter',
            selectors: [
                '.weekBottom',
                '.reviewsWindow',
                '#banner_cinemast',
                '.bottomMenu',
                'footer',
                '#paypal',
                '#aboveSite',
                {
                    selector: '#subtitles_list a[href="/he/contactus/"]',
                    fineTuneSelector: function ($element) {
                        return $element.parent();
                    }
                }
            ]
        },
        wikipedia: {
            hostNames: 'wikipedia.org',
            selectors: [
                '#frbanner',
                '#frb-inline',
                '#wlm-banner',
                '#centralNotice',
                '.frb-main',
                '.frbanner',
                '.frm',
                '.frb'
            ]
        },
        opensubtitles: {
            hostNames: 'opensubtitles',
            selectors: ['.rec_container_right']
        },
        wikia: {
            hostNames: 'wikia.com',
            selectors: [
                '.WikiaFooter',
                '.WikiaRail',
                '.wds-global-footer'
            ]
        },
        reddit: {
            hostNames: 'reddit.com',
            selectors: ['#onboarding-splash']
        },
        bostonglobe: {
            hostNames: 'bostonglobe.com',
            selectors: [
                '.meter-social-connect',
                '.meter-social-connect__container'
            ]
        }
    };

    [
        '#dcPremiumRightImg',
        '.boulevard',
        '#multiarticles-9',
        '#multiarticles-12',
        '#multiarticles-13',
        '#multiarticles-14',
        '#multiarticles-15',
        '#multiarticles-16',
        '.CdaMostViews',
        '.CdaCalcalistToday',
        '.CdaRecomendedMovies',
        '#SpecialBuilder1280',
        '.cdaFooter1280'
    ].forEach(function addSelector(selector) {
        selectorDefinitions.ynet.selectors.push({
            selector: selector,
            fineTuneSelector: function ($element) {
                return $element.parent();
            }
        });
    });

    runner($, {
        getSelectorDefinitions: function () {
            return selectorDefinitions;
        }
    });
}(window.jQuery.noConflict(true), window.adrRunner));
<|endoftext|>