Service.deletePicture(url).then((data) => {
   var pictures = groupBy(data, function(obj) {
     var picDate = new Date(obj.date);
     return (picDate.getMonth() + 1) + '/' + picDate.getDate() + '/' + picDate.getFullYear();
   });
   this.setState({pictures: pictures});
 });
Example #2
0
Parser.prototype.clean = function() {
  this.symbols = this.symbols.filter(this.filterByProto, this);

  var byLine = groupBy(this.symbols, 'range_line');

  var singleLines = mapValues(byLine, function(symbols) {
    return sortBy(symbols, function(symbol) {
      return symbol.range_column;
    }).shift();
  });

  this.symbols = map(singleLines, function(v, k) {
    return v;
  }).filter(function(symbol) {
    var tag = this.byId.tags[symbol.id];
    var parent = this.byId.tags[symbol.parent];

    if ((/^\</).test(tag.name)) {
      return false;
    }

    return (
      tag.type ||
      (parent && parent.origin['!data'].isPlainObject) ||
      tag.origin['!data'].type
    );
  }, this);
};
const validateNoDuplicateIds = (addComponents: Object[]) => {
  const duplicateIds = {};
  const newGroupedComponents = groupby(addComponents, 'componentId');
  Object.keys(newGroupedComponents).forEach((key) => {
    if (newGroupedComponents[key].length > 1) duplicateIds[key] = newGroupedComponents[key];
  });
  if (!R.isEmpty(duplicateIds) && !R.isNil(duplicateIds)) throw new DuplicateIds(duplicateIds);
};
Example #4
0
File: base.js Project: 4ok/app-data
                            .then((children) => {

                                if (children.length) {
                                    children = groupBy(children, 'parent_id');
                                    item.children = children[item._id]; // @todo
                                }

                                return item;
                            });
Example #5
0
function displayFormation (formation) {
  const groupBy = require('lodash.groupby')
  const map = require('lodash.map')
  const sumBy = require('lodash.sumby')

  formation = groupBy(formation, 'size')
  formation = map(formation, (p, size) => `${bold(sumBy(p, 'quantity'))} | ${size}`)
  cli.log(`  ${label('Dynos:')} ${formation.join(', ')}`)
}
Example #6
0
.then((photos) => {
	photos = photos.map(clean)

	const data = {}
	for (let filter of filters)
		data[filter] = groupBy(photos, (p) => p[filter])

	return data
}, err)
  render () {
    const bySalaryBucket = groupBy(this.state.summaries, 'salaryBucketId')
    const tables = []
    for (let bucket in bySalaryBucket) {
      const byEthnicity = groupBy(bySalaryBucket[bucket], 'ethnicityId')
      const ethnicitySummaries = Object.entries(byEthnicity).map(entry => {
        return {
          name: ETHNICITY_ID_LABELS[entry[0]],
          items: entry[1]
        }
      })
      tables.push(
        <GraphTable summaries={ethnicitySummaries} key={bucket} title={SALARY_BUCKET_LABELS[bucket]} />
      )
    }

    return (
      <div className='SummaryCharts col-xs-12'>
        {tables}
      </div>
    )
  }
  }, function (err, result) {

    // Safe OR results are now in frequencies.ORSets so this should now
    // be edited to read form frequencies.ORSets

    // Should now have the top n (n = offset + pagesize) for every token
    var hits = []
    // TODO: weight results by field

    hits = _map(frequencies.ORSets, function (item) {
      return item.ORSet
    })

    hits = _flatten(hits)
    hits = _groupBy(hits, function (item) {
      return item.id
    })

    hits = _map(hits, function (val, key) {
      var hit = {}
      hit.id = key
      hit.score = 0
      hit.tfidf = []
      // OR
      val.forEach(function (item) {
        hit.tfidf.push(item.tfidf)
        // AND
        item.tfidf.forEach(function (ANDTokens) {
          const tfidf = ANDTokens[2]
          const boost = ANDTokens[5]
          hit.score += +(tfidf + boost)
        })
      })
      return hit
    })

    hits = hits.sort(function (a, b) {
      if (a.score < b.score) return 1
      if (a.score > b.score) return -1
      if (a.id < b.id) return 1
      if (a.id > b.id) return -1
      return 0
    })

    hits = hits.slice((+q.offset), (+q.offset) + (+q.pageSize))

    glueDocs(hits, q, options, function (result) {
      return callbackX(err, result)
    })
  })
Example #9
0
    .then((body) => {
      const shapes = groupBy(JSON.parse(body).data.trips, trip => trip.shapeId)
      const shapeIds = Object.keys(shapes)
      const shapePromises = shapeIds.map(shapeId => request(tripRequiest(uri, shapes[shapeId][0].gtfsId)))

      Promise.all(shapePromises).then(geometries => {
        const shapeBundles = zip(shapeIds, shapeIds.map(shapeId => shapes[shapeId][0].route), geometries)
        const geoJSON = {type: "FeatureCollection", features: shapeBundles.map(toFeature)}
        this.tileIndex = geojsonVt(geoJSON, {maxZoom: 20, buffer: 512}); //TODO: this should be configurable
        console.log("all ready")
        callback(null, this)
      }).catch((err) => {
        console.log(err)
        callback(err);
      })
    })
const DepartmentList = ({ positions, toggleSelectPositions, positionsSelectedStatus }) => {
  const departments = groupBy(positions, position => position.department)
  return (
    <ul className="department-list">
      {Object.keys(departments).map((departmentName, index) => (
        <Department
          key={index}
          title={departmentName}
          positions={departments[departmentName]}
          toggleSelectPositions={toggleSelectPositions}
          positionsSelectedStatus={positionsSelectedStatus}
        />
      ))}
    </ul>
  )
}
    const pieCharts = Object.keys(bySalaryBucket).map((bucket, ix) => {
      const byAttribute = groupBy(
        bySalaryBucket[bucket],
        e => e[this.props.attribute]
      )

      const data = constants.ATTRIBUTE_TO_CHOICES[this.props.attribute].map(
        (choice) => [choice, (byAttribute[choice] || []).length]
      )

      const config = {
        chart: {
          plotBackgroundColor: null,
          plotBorderWidth: null,
          plotShadow: true
        },
        exporting: {
          enabled: false
        },
        title: {
          text: constants.SALARY_BUCKET_LABELS[bucket]
        },
        tooltip: {
          pointFormat: '{name}: <b>{point.percentage:.1f}%</b>'
        },
        legend: {
          enabled: true,
          labelFormat: '<b>{name}</b>: <b>{y:.1f}</b>   ({percentage:.1f}%)</b>'
        },
        plotOptions: {
          pie: {
            allowPointSelect: true,
            colors: piechartColors,
            cursor: 'pointer',
            dataLabels: {
              enabled: false
            },
            showInLegend: true
          }
        },
        series: [{data, type: 'pie'}]
      }

      return <ReactHighCharts key={ix} config={config} />
    })
ValidationError.generateErrorMessage = function generateErrorMessage(errors) {
  if (!errors)
    return ''

  let groups = groupBy(errors, 'name')
  let selectedGroup;

  priorities.some((priority) => {
    selectedGroup = groups[priority]
    return selectedGroup
  })
  // if there are no 'important' validation errors, just pick one
  if (!selectedGroup)
    selectedGroup = sample(groups)

  let message = selectedGroup[0].name + ' error: ' + map(selectedGroup, 'stack').join(', ')
  return message
}
Example #13
0
export default function({
  categories,
  availableOptions,
  optionValues,
  onOptionValueChange
}) {
  const options = groupBy(availableOptions, "category");
  return categories.map(
    category =>
      options[category] ? (
        <SidebarCategory key={category} title={category}>
          {options[category].map(option => (
            <Option
              key={option.name}
              option={option}
              value={optionValues[option.name]}
              onChange={onOptionValueChange}
            />
          ))}
        </SidebarCategory>
      ) : null
  );
}
Example #14
0
export function getLocaleFileList(absSrcPath, absPagesPath, singular) {
  const localeFileMath = /^([a-z]{2})-([A-Z]{2})\.(js|ts)$/;
  const localeFolder = singular ? 'locale' : 'locales';
  const localeFiles = globby
    .sync('*.{ts,js}', {
      cwd: join(absSrcPath, localeFolder),
    })
    .map(name => join(absSrcPath, localeFolder, name))
    .concat(
      globby
        .sync(`**/${localeFolder}/*.{ts,js}`, {
          cwd: absPagesPath,
        })
        .map(name => join(absPagesPath, name)),
    )
    .filter(p => localeFileMath.test(basename(p)))
    .map(fullname => {
      const fileName = basename(fullname);
      const fileInfo = localeFileMath.exec(fileName);
      return {
        name: `${fileInfo[1]}-${fileInfo[2]}`,
        path: fullname,
      };
    });
  const groups = groupBy(localeFiles, 'name');
  return Object.keys(groups).map(name => {
    const fileInfo = name.split('-');
    return {
      lang: fileInfo[0],
      name,
      country: fileInfo[1],
      paths: groups[name].map(item => winPath(item.path)),
      momentLocale: getMomentLocale(fileInfo[0], fileInfo[1]),
    };
  });
}
export default function collectErrors(error) {
  if (error !== null) {
    return groupBy(error.details, 'path');
  }
  return {};
}
Example #16
0
		fn: require('./inline-instagram-photos').default,
		hidden: true
	},
	mentionHighlight: {
		id: 'feature-mentions-highlight',
		category: 'timeline',
		label: 'Highlight your mentions in the stream',
		fn: require('./mentions-highlight').default
	},
	renderInlineCode: {
		id: 'feature-inline-code',
		category: 'timeline',
		label: 'Adds Markdown-like styling of text wrapped in backticks',
		fn: require('./inline-code').default
	}
};

export const featuresArr = sortBy(Object.values(features), ['category', 'label']);

export const groupedFeatures = groupBy(featuresArr, 'category');

export const autoInitFeatures = featuresArr.filter(feature => feature.runOnInit);

const _featuresDefaultValues = {};
for (const feature of featuresArr) {
	_featuresDefaultValues[feature.id] =
		typeof feature.enabledByDefault === 'boolean' ? feature.enabledByDefault : true;
}

export const featuresDefaultValues = _featuresDefaultValues;
Example #17
0
  // Gets *all* attachments and add-ons and filters locally because the API
  // returns *owned* items not associated items.
  function * addonGetter (api, app) {
    let attachments, addons

    if (app) { // don't disploy attachments globally
      addons = api.get(`/apps/${app}/addons`, {headers: {'Accept-Expansion': 'addon_service,plan'}})

      let sudoHeaders = JSON.parse(process.env.HEROKU_HEADERS || '{}')
      if (sudoHeaders['X-Heroku-Sudo'] && !sudoHeaders['X-Heroku-Sudo-User']) {
        // because the root /addon-attachments endpoint won't include relevant
        // attachments when sudo-ing for another app, we will use the more
        // specific API call and sacrifice listing foreign attachments.
        attachments = api.request({
          method: 'GET',
          path: `/apps/${app}/addon-attachments`
        })
      } else {
        // In order to display all foreign attachments, we'll get out entire
        // attachment list
        attachments = api.get('/addon-attachments')
      }
    } else {
      addons = api.request({
        method: 'GET',
        path: '/addons',
        headers: {'Accept-Expansion': 'addon_service,plan'}
      })
    }

    // Get addons and attachments in parallel
    let items = yield [addons, attachments]

    function isRelevantToApp (addon) {
      return !app ||
      addon.app.name === app ||
      some(addon.attachments, (att) => att.app.name === app)
    }

    attachments = groupBy(items[1], 'addon.id')

    addons = []
    items[0].forEach(function (addon) {
      addon.attachments = attachments[addon.id] || []

      delete attachments[addon.id]

      if (isRelevantToApp(addon)) {
        addons.push(addon)
      }
    })

    // Any attachments left didn't have a corresponding add-on record in API.
    // This is probably normal (because we are asking API for all attachments)
    // but it could also be due to certain types of permissions issues, so check
    // if the attachment looks relevant to the app, and then render whatever
    // information we can.
    values(attachments).forEach(function (atts) {
      let inaccessibleAddon = {
        app: atts[0].addon.app,
        name: atts[0].addon.name,
        addon_service: {},
        plan: {},
        attachments: atts
      }

      if (isRelevantToApp(inaccessibleAddon)) {
        addons.push(inaccessibleAddon)
      }
    })

    return addons
  }
Example #18
0
  /**
   * given the component paths, prepare the id, mainFile and files to be added later on to bitmap
   * the id of the component is either entered by the user or, if not entered, concluded by the path.
   * e.g. bar/foo.js, the id would be bar/foo.
   * in case bitmap has already the same id, the complete id is taken from bitmap (see _getIdAccordingToExistingComponent)
   */
  async addOneComponent(componentPathsStats: PathsStats): Promise<AddedComponent> {
    let finalBitId: BitId; // final id to use for bitmap file
    if (this.id) {
      finalBitId = this._getIdAccordingToExistingComponent(this.id);
    }

    const componentsWithFilesP = Object.keys(componentPathsStats).map(async (componentPath) => {
      if (componentPathsStats[componentPath].isDir) {
        const relativeComponentPath = this.consumer.getPathRelativeToConsumer(componentPath);

        const matches = await glob(path.join(relativeComponentPath, '**'), {
          cwd: this.consumer.getPath(),
          nodir: true
        });

        const filteredMatches = this.gitIgnore.filter(matches);

        if (!filteredMatches.length) throw new EmptyDirectory();

        let filteredMatchedFiles = filteredMatches.map((match: PathOsBased) => {
          return { relativePath: pathNormalizeToLinux(match), test: false, name: path.basename(match) };
        });

        // merge test files with files
        filteredMatchedFiles = await this._mergeTestFilesWithFiles(filteredMatchedFiles);
        const resolvedMainFile = this._addMainFileToFiles(filteredMatchedFiles);

        if (!finalBitId) {
          const absoluteComponentPath = path.resolve(componentPath);
          const splitPath = absoluteComponentPath.split(path.sep);
          const lastDir = splitPath[splitPath.length - 1];
          const nameSpaceOrDir = this.namespace || splitPath[splitPath.length - 2];
          const idFromPath = BitId.getValidBitId(nameSpaceOrDir, lastDir);
          finalBitId = this._getIdAccordingToExistingComponent(idFromPath.toString());
        }

        const trackDir =
          Object.keys(componentPathsStats).length === 1 &&
          !this.exclude.length &&
          this.origin === COMPONENT_ORIGINS.AUTHORED
            ? relativeComponentPath
            : undefined;

        return { componentId: finalBitId, files: filteredMatchedFiles, mainFile: resolvedMainFile, trackDir };
      }
      // is file
      const absolutePath = path.resolve(componentPath);
      const pathParsed = path.parse(absolutePath);
      const relativeFilePath = this.consumer.getPathRelativeToConsumer(componentPath);
      if (!finalBitId) {
        let dirName = pathParsed.dir;
        if (!dirName) {
          dirName = path.dirname(absolutePath);
        }
        const nameSpaceOrLastDir = this.namespace || R.last(dirName.split(path.sep));
        const idFromPath = BitId.getValidBitId(nameSpaceOrLastDir, pathParsed.name);
        finalBitId = this._getIdAccordingToExistingComponent(idFromPath.toString());
      }

      let files = [
        { relativePath: pathNormalizeToLinux(relativeFilePath), test: false, name: path.basename(relativeFilePath) }
      ];

      files = await this._mergeTestFilesWithFiles(files);
      const resolvedMainFile = this._addMainFileToFiles(files);
      return { componentId: finalBitId, files, mainFile: resolvedMainFile };
    });

    let componentsWithFiles: AddedComponent[] = await Promise.all(componentsWithFilesP);

    // remove files that are excluded
    if (!R.isEmpty(this.exclude)) await this.removeExcludedFiles(componentsWithFiles);

    const componentId = finalBitId;
    componentsWithFiles = componentsWithFiles.filter(componentWithFiles => componentWithFiles.files.length);

    if (componentsWithFiles.length === 0) return { componentId, files: [] };
    if (componentsWithFiles.length === 1) return componentsWithFiles[0];

    const files = componentsWithFiles.reduce((a, b) => {
      return a.concat(b.files);
    }, []);
    const groupedComponents = groupby(files, 'relativePath');
    const uniqComponents = Object.keys(groupedComponents).map(key =>
      assignwith({}, ...groupedComponents[key], (val1, val2) => val1 || val2)
    );
    return {
      componentId,
      files: uniqComponents,
      mainFile: R.head(componentsWithFiles).mainFile,
      trackDir: R.head(componentsWithFiles).trackDir
    };
  }
  render () {
    if (!this.props.attribute) {
      return null
    }

    let employees = this.props.employees
    if (this.props.departmentId) {
      employees = this.props.employees.filter(
        e => e.departmentId === this.props.departmentId
      )
    }

    const bySalaryBucket = groupBy(employees, e => e.salaryBucketId)

    // Get totals for each attribute group w/in each income group
    const pieCharts = Object.keys(bySalaryBucket).map((bucket, ix) => {
      const byAttribute = groupBy(
        bySalaryBucket[bucket],
        e => e[this.props.attribute]
      )

      const data = constants.ATTRIBUTE_TO_CHOICES[this.props.attribute].map(
        (choice) => [choice, (byAttribute[choice] || []).length]
      )

      const config = {
        chart: {
          plotBackgroundColor: null,
          plotBorderWidth: null,
          plotShadow: true
        },
        exporting: {
          enabled: false
        },
        title: {
          text: constants.SALARY_BUCKET_LABELS[bucket]
        },
        tooltip: {
          pointFormat: '{name}: <b>{point.percentage:.1f}%</b>'
        },
        legend: {
          enabled: true,
          labelFormat: '<b>{name}</b>: <b>{y:.1f}</b>   ({percentage:.1f}%)</b>'
        },
        plotOptions: {
          pie: {
            allowPointSelect: true,
            colors: piechartColors,
            cursor: 'pointer',
            dataLabels: {
              enabled: false
            },
            showInLegend: true
          }
        },
        series: [{data, type: 'pie'}]
      }

      return <ReactHighCharts key={ix} config={config} />
    })

    return (
      <div className='IncomeLevelPieCharts'>
        {pieCharts}
      </div>
    )
  }