コード例 #1
0
ファイル: RulesEditor.js プロジェクト: data4society/mpro
    rules.forEach(function(rule, id) {
      let rubrics = rule.rubrics_names.join(' && ')
      if(isEmpty(rubrics)) {
        rubrics = '+ Add rubrics set'
      } else {
        rubrics += ' \r\n + Add other rubrics'
      }
      let entities = rule.entities_names.join(' && ')
      if(isEmpty(entities)) {
        entities = '+ Add entities set'
      } else {
        entities += ' \r\n + Add other entities'
      }

      grid.append(
        $$(Grid.Row).append(
          $$(Grid.Cell, {columns: 5}).addClass('sm-sets').append(rubrics)
            .on('click', this._editRubrics.bind(this, id)),
          $$(Grid.Cell, {columns: 5}).addClass('sm-sets').append(entities)
            .on('click', this._editEntities.bind(this, id)),
          $$(Grid.Cell, {columns: 2}).append(
            $$(Button, {label: 'remove-rule', style: 'default', icon: 'rule-remove'})
              .addClass('se-rule-control')
              .attr({title: this.getLabel('remove-rule-description')})
              .on('click', this._removeRule.bind(this, id)),
            $$(Button, {label: 'reapply-rule', style: 'default', icon: 'rule-reapply'})
              .addClass('se-rule-control')
              .attr({title: this.getLabel('reapply-rule-description')})
              .on('click', this._reapplyRule.bind(this, id))
          )
        ).ref(rule.rule_id)
      )
    }.bind(this))
コード例 #2
0
ファイル: analyseView.js プロジェクト: cwhelan00/lichobile
function renderEvalBox(ctrl) {
  const cevalEnabled = ctrl.ceval.enabled();
  const step = ctrl.vm.step;
  const ceval = ctrl.currentAnyEval() || {};
  let pearl, percent;

  const hash = '' + cevalEnabled + (ceval && renderEval(ceval.cp)) +
    ctrl.nextStepBest() + (ceval && ceval.mate) + defined(step.ceval) +
    ctrl.ceval.percentComplete() + isEmpty(step.dests);

  if (ctrl.vm.evalBoxHash === hash) return {
    subtree: 'retain'
  };
  ctrl.vm.evalBoxHash = hash;

  if (defined(ceval.cp) && ctrl.nextStepBest()) {
    pearl = <pearl>{renderEval(ceval.cp)}</pearl>;
    percent = ctrl.ceval.enabled() ? 100 : 0;
  }
  else if (defined(ceval.cp)) {
    pearl = <pearl>{renderEval(ceval.cp)}</pearl>;
    percent = ctrl.ceval.enabled() ? ctrl.ceval.percentComplete() : 0;
  }
  else if (defined(ceval.mate)) {
    pearl = <pearl>{'#' + ceval.mate}</pearl>;
    percent = ctrl.ceval.enabled() ? 100 : 0;
  }
  else if (ctrl.ceval.enabled() && isEmpty(ctrl.vm.step.dests)) {
    pearl = <pearl>-</pearl>;
    percent = 0;
  }
  else if (ctrl.ceval.enabled()) {
    pearl = <div className="spinner fa fa-hourglass-half"></div>;
    percent = 0;
  }
  else {
    pearl = <pearl>-</pearl>;
    percent = 0;
  }

  return (
    <div className="cevalBox">
      { pearl }
      <div className="cevalBar">
        <span style={{ width: percent + '%' }}></span>
      </div>
      { ctrl.data.analysis ?
        <div className="openSummary" config={helper.ontouch(ctrl.evalSummary.open)}>
          <span className="fa fa-question-circle"/>
        </div> : null
      }
    </div>
  );
}
コード例 #3
0
 return getUserByCredential(user.credential).then((resp) => {
     if (!isEmpty(resp.docs)) {
         let user = resp.docs[0];
         store.dispatch(setMySaved(user.words));
     }   
     return Promise.resolve();
 });
コード例 #4
0
  render () {
    const { children, history, wait } = this.props;

    return (
      wait && isEmpty(history) ? <CircularProgress /> : children
    )
  }
コード例 #5
0
ファイル: griddle.jsx.js プロジェクト: Ent-ch/Griddle
  setFilter: function setFilter(filter) {
    if (this.props.useExternal) {
      this.props.externalSetFilter(filter);
      return;
    }

    var that = this,
        updatedState = {
      page: 0,
      filter: filter
    };

    // Obtain the state results.
    updatedState.filteredResults = this.props.useCustomFilterer ? this.props.customFilterer(this.props.results, filter) : this.defaultFilter(this.props.results, filter);

    // Update the max page.
    updatedState.maxPage = that.getMaxPage(updatedState.filteredResults);

    //if filter is null or undefined reset the filter.
    if (isUndefined(filter) || isNull(filter) || isEmpty(filter)) {
      updatedState.filter = filter;
      updatedState.filteredResults = null;
    }

    // Set the state.
    that.setState(updatedState);

    this._resetSelectedRows();
  },
コード例 #6
0
ファイル: index.js プロジェクト: get-focus/focus-tuto-redux
app.use((req, res, next) => {
    console.log(new Date() + ', ' + req.method + ', ' + req.url);
    if (!isEmpty(req.body)) {
        console.log(req.body);
    }
    next();
});
コード例 #7
0
ファイル: pons.js プロジェクト: omeryagmurlu/pons.js
		const pairFieldProcedure = (pair, $obj, field, jqStrHead) => {
			$obj.find('.example').html() && (pair.example = true);

			let wanted = [];
			for (let l = 0; l < $obj.find(jqStrHead + 'a:not(.info a):not(acronym:only-child a)').length; l++) {
				const text = $obj.find(jqStrHead + 'a:not(.info a):not(acronym:only-child a)')[l];
				wanted.push(Utils.ueHTML($(text).html()));
			}
			pair[field] = wanted = wanted.join(' ');

			if (pair[field] === '' && jqStrHead) {
				return pairFieldProcedure(pair, $obj, field, '');
			}

			let propObj = pair[field + '_properties'] = {};
			$obj.find('.sense a') && (propObj.sense = []) && $obj.find('.sense a').each(value => ((propObj.sense.push($($obj.find('.sense a')[value]).html())))) && (propObj.sense && ((propObj.sense.length !== 0) || !(delete propObj.sense)) && (propObj.sense = propObj.sense.join(' '))); // he he :D, lispy, but really, selecting pons' stupid in-translation comments is really hard and I couldn't automate it
			$obj.find('acronym:only-child').each(indis => {
				const $thus = $($obj.find('acronym:only-child')[indis]);
				if (propObj[Utils.ueHTML($thus.parent().attr('class').split(' ')[0])]) {
					if (typeof propObj[Utils.ueHTML($thus.parent().attr('class').split(' ')[0])] === 'string') {
						propObj[Utils.ueHTML($thus.parent().attr('class').split(' ')[0])] = [propObj[Utils.ueHTML($thus.parent().attr('class').split(' ')[0])]];
					}
					propObj[Utils.ueHTML($thus.parent().attr('class').split(' ')[0])].push(Utils.ueHTML($thus.attr('title')));
				} else {
					propObj[Utils.ueHTML($thus.parent().attr('class').split(' ')[0])] = Utils.ueHTML($thus.attr('title'));
				}
			});
			isEmpty(propObj) && delete pair[field + '_properties'];
		};
コード例 #8
0
ファイル: controller.js プロジェクト: octet-stream/twi
const route = (path, method, ...middleware) => function(target, k, descriptor) {
  if (!isString(path)) {
    throw new TypeError("Path should be a string.")
  }

  if (!target.router) {
    target.router = new Router()
  }

  if (isEmpty(method)) {
    throw new Error("HTTP method name cannot be empty.")
  }

  if (!isString(method)) {
    throw new TypeError("HTTP method name should be a string.")
  }

  method = toLowerCase(method)

  if (!(method in methods)) {
    throw new Error(`Unknown HTTP method name: ${method}`)
  }

  // Add handler to given method
  // TODO: Add support for static class methods though initializer
  target.router[method](path, ...middleware, descriptor.value)
}
コード例 #9
0
ファイル: progress-store.js プロジェクト: BMOTech/wp-calypso
SignupProgressStore.dispatchToken = Dispatcher.register( function( payload ) {
	var action = payload.action,
		step = addTimestamp( action.data );

	Dispatcher.waitFor( [ SignupDependencyStore.dispatchToken ] );

	if ( ! isEmpty( action.errors ) ) {
		return setStepInvalid( step, action.errors );
	}

	switch ( action.type ) {
		case 'FETCH_CACHED_SIGNUP':
			loadProgressFromCache();
			break;
		case 'SAVE_SIGNUP_STEP':
			saveStep( step );
			break;
		case 'SUBMIT_SIGNUP_STEP':
			debug( 'submit step' );
			submitStep( step );
			break;
		case 'PROCESS_SIGNUP_STEP':
			processStep( step );
			break;
		case 'PROCESSED_SIGNUP_STEP':
			debug( 'complete step' );
			completeStep( step );
			break;
	}
} );
コード例 #10
0
    $delegate.setScopeExperience = ($scope) => {
        if (!iVXjs) return;

        const { experience = {} } = iVXjs;
        let entity = {};

        const { data: experienceData = {}, organization = {}, childEntityKey = "" } = experience;
        let { data: organizationData = {}, childEntityType, name, key, logo = {} } = organization;

        if (!isEmpty(childEntityKey)) {
            const { entities } = organization;
            const foundEntity = entities.find((currentEntity) => currentEntity.key === childEntityKey) || {};

            entity = Object.assign({},
                foundEntity,
                {
                    type: childEntityType
                });
        }

        return Object.assign($scope, {
            experience: {
                data: experienceData
            },
            organization: {
                data: organizationData,
                entity,
                name,
                key,
                logo
            }
        })
    }
コード例 #11
0
ファイル: selectors.js プロジェクト: Vizzuality/gfw
 (data, colors) => {
   if (isEmpty(data)) return null;
   const { totalArea, totalExtent, extent } = data;
   const secondaryExtent = totalExtent - extent < 0 ? 0 : totalExtent - extent;
   const parsedData = [
     {
       label: 'Primary Forest',
       value: extent,
       color: colors.primaryForest,
       percentage: extent / totalArea * 100
     },
     {
       label: 'Other Tree Cover',
       value: secondaryExtent,
       color: colors.otherCover,
       percentage: secondaryExtent / totalArea * 100
     },
     {
       label: 'Non-Forest',
       value: totalArea - totalExtent,
       color: colors.nonForest,
       percentage: (totalArea - totalExtent) / totalArea * 100
     }
   ];
   return parsedData;
 }
コード例 #12
0
    getData: function(){
        if(_isEmpty(_data) && !this.readFromStorage()){
            console.info('data store is empty');
        }

        return _data;
    },
コード例 #13
0
ファイル: GithubAccount.js プロジェクト: s594475/peter
  render(){
    let GitHubInfo;
    let x = <CircularProgress size={2} style={{marginLeft:'50%'}}/>;
    if(!isEmpty(this.state.user)) {
      GitHubInfo = (
        <div>
          <UserInfo userInfo={this.state.user} />
          <Repos repos={this.state.repos} />
        </div>
      );
    }
    return(
      <div>
        {this.state.wait ? x :
          <div className='account'>
            <Card className="content">
              { GitHubInfo }
            </Card>
            <Card className="content">
                <Echarts />
            </Card>

          </div>
        }
    </div>
    )
  }
コード例 #14
0
		wpcom.undocumented().sitesNew( data, function( errors, response ) {
			let providedDependencies, siteSlug;

			if ( response && response.blog_details ) {
				siteSlug = response.blog_details.blogname + '.wordpress.com';
				providedDependencies = { siteSlug };
			}

			if ( user.get() && isEmpty( errors ) ) {
				fetchSitesAndUser( siteSlug, () => {
					callback( undefined, providedDependencies );
				} );
			} else {
				callback( isEmpty( errors ) ? undefined : [ errors ], providedDependencies );
			}
		} );
コード例 #15
0
 /**
  * 保存当前对话的属性至服务器
  * @return {Promise.<Conversation>} self
  */
 save() {
   this._debug('save');
   const attr = internal(this).pendingAttributes;
   if (isEmpty(attr)) {
     this._debug('nothing touched, resolve with self');
     return Promise.resolve(this);
   }
   this._debug('attr: %O', attr);
   const convMessage = new ConvCommand({
     attr: new JsonObjectMessage({
       data: JSON.stringify(attr),
     }),
   });
   return this
     ._send(new GenericCommand({
       op: 'update',
       convMessage,
     }))
     .then((resCommand) => {
       this.updatedAt = resCommand.convMessage.udate;
       this._attributes = internal(this).currentAttributes;
       internal(this).pendingAttributes = {};
       return this;
     });
 }
コード例 #16
0
ファイル: selectors.js プロジェクト: Vizzuality/gfw
  (data, location, sentences, locationsDict, settings) => {
    if (!sentences || isEmpty(data)) return null;

    if (location === 'global') {
      const sorted = sortByKey(data, [settings.variable]).reverse();

      let biomTop5 = 0;
      let densTop5 = 0;
      const biomTotal = sorted.reduce((acc, next, i) => {
        if (i < 5) {
          biomTop5 += next.totalbiomass;
          densTop5 += next.biomassdensity;
        }
        return acc + next.totalbiomass;
      }, 0);

      const percent = biomTop5 / biomTotal * 100;
      const avgBiomDensity = densTop5 / 5;

      const value =
        settings.variable === 'totalbiomass'
          ? formatNumber({ num: percent, unit: '%' })
          : formatNumber({ num: avgBiomDensity, unit: 't/ha' });

      const labels = {
        biomassdensity: 'biomass density',
        totalbiomass: 'total biomass'
      };

      return {
        sentence: sentences[settings.variable],
        params: {
          label: labels[settings.variable],
          value
        }
      };
    }
    const iso =
      locationsDict &&
      Object.keys(locationsDict).find(key => locationsDict[key] === location);
    const region =
      data &&
      data.find(item => {
        if (item.admin_2) return String(item.admin_2) === iso;
        else if (item.admin_1) return String(item.admin_1) === iso;
        return item.iso === iso;
      });
    if (!region) return null;

    const { biomassdensity, totalbiomass } = region;
    return {
      sentence: sentences.initial,
      params: {
        location,
        biomassDensity: formatNumber({ num: biomassdensity, unit: 't/ha' }),
        totalBiomass: formatNumber({ num: totalbiomass, unit: 't' })
      }
    };
  }
コード例 #17
0
ファイル: progress-store.js プロジェクト: BMOTech/wp-calypso
function loadProgressFromCache() {
	const cachedSignupProgress = store.get( STORAGE_KEY );

	if ( ! isEmpty( cachedSignupProgress ) ) {
		signupProgress = cachedSignupProgress;
	}

	handleChange();
}
コード例 #18
0
    toggle: function(id, hide){
        if(_isEmpty(_data)){
            console.info('data store is empty');
            return;
        }

        _data.items[id].hide = !!hide;
        this.saveToStorage();
    },
コード例 #19
0
ファイル: step-actions.js プロジェクト: noxee/wp-calypso
		wpcom.undocumented().sitesNew( data, function( errors, response ) {
			let providedDependencies, siteSlug;

			if ( response && response.blog_details ) {
				const parsedBlogURL = parseURL( response.blog_details.url );
				siteSlug = parsedBlogURL.hostname;

				providedDependencies = { siteSlug };
			}

			if ( user.get() && isEmpty( errors ) ) {
				fetchSitesAndUser( siteSlug, () => {
					callback( undefined, providedDependencies );
				} );
			} else {
				callback( isEmpty( errors ) ? undefined : [ errors ], providedDependencies );
			}
		} );
コード例 #20
0
    highlight: function(id, highlight){
        if(_isEmpty(_data)){
            console.info('data store is empty');
            return;
        }

        _data.items[id].highlight = !!highlight;
        this.saveToStorage();
    },
コード例 #21
0
function parseChildren (child, parent) {
  if (isString(child)) {
    parent.name = child || ''
    return
  }

  if (isArray(child)) {
    forEach(child, x => parseChildren(x, parent))
    return
  }

  if (!isObject(child)) return

  const {props} = child
  const type = camelCase(child.type)
  const node = omit(props, 'children')

  if (isEmpty(node) && !isObject(props.children) && !isArray(props.children)) {
    if (type === 'title') {
      parent.title = {
        text: props.children
      }
    } else {
      parent[type] = props.children === undefined
        ? true
        : props.children
    }

    return
  }

  forEach(node, (value, name) => {
    if (looksLikeAnEventHandler(name)) {
      node.events = node.events || {}
      node.events[lowerCase(name.slice(2))] = value
    }
  })

  if (parent.isRoot && includes(seriesTypes, type)) {
    node.type = type
    node.isSeries = true
    parent.series = parent.series || []
    parent.series.push(node)
  } else if (parent.isSeries && type === 'point') {
    parent.data = parent.data || []
    parent.data.push(node)
  } else {
    parent[type] = node
  }

  if (isArray(props.children)) {
    forEach(props.children, children =>
      parseChildren(children, node))
  } else {
    parseChildren(props.children, node)
  }
}
コード例 #22
0
 reset: function(){
     if(_isEmpty(_data)){
         console.info('data store is empty');
         return;
     }else{
         _data = {};
         this.saveToStorage();
         console.info('data reseted');
     }
 },
コード例 #23
0
ファイル: search.js プロジェクト: ndobariya219/conductor
function* doFetchSearchResults() {
  const {query, entirely, types, states, cutoff, start} = yield select(state => state.search);

  const queryParts = [];

  if (!isEmpty(types)) {
    queryParts.push(`workflowType IN (${encodeURIComponent(toString(types))})`);
  }

  if (!isEmpty(states)) {
    queryParts.push(`status IN (${toString(states)})`);
  }

  const fullQuery = join(queryParts, ' AND ');
  const freeText = (!isEmpty(query) && entirely) ? `"${query}"` : query;

  const searchUrl = `/api/wfe/?q=${fullQuery}&h=${cutoff}&freeText=${freeText}&start=${start}`;

  try {
    // this is possible a task ID
    if (query.match(UUID_RE)) {
      const taskSearchUrl = `/api/wfe/search-by-task/${query}?q=${fullQuery}&h=${cutoff}&start=${start}`;

      const [allResult, byTaskResult] = yield all([
        call(http.get, searchUrl),
        call(http.get, taskSearchUrl)
      ]);

      /// only use the task search results if we don't get any results searching everywhere
      if (getTotalHits(allResult) === 0) {
        yield put(receiveSearchResults(getHits(byTaskResult), getTotalHits(byTaskResult)));
      } else {
        yield put(receiveSearchResults(getHits(allResult), getTotalHits(allResult)));
      }
    } else {
      const result = yield call(http.get, searchUrl);

      yield put(receiveSearchResults(getHits(result), getTotalHits(result)));
    }
  } catch ({message}) {
    yield put(failSearchResults(message));
  }
}
コード例 #24
0
  componentDidMount () {
    let { action, dispatch, interval, history, poll } = this.props;

    if (isEmpty(history)) {
      dispatch(action)
    }

    this.interval = poll &&
      dispatch(timing.setInterval(action, interval));
  }
コード例 #25
0
ファイル: formioWizard.js プロジェクト: marguslaak/ngFormio
          $timeout(function() {
            // If the page is past the components length, try to clear first.
            if ($scope.currentPage >= $scope.pages.length) {
              $scope.clear();
            }

            // Handle Local Storage Definition
            if ($scope.storage && !$scope.readOnly) {
              // If there is no localStorage object - make a new object schema
              if (!localStorage.getItem($scope.storage)) {
                localStorage.setItem($scope.storage, angular.toJson({
                  page: $scope.currentPage,
                  data: $scope.submission.data
                }));
              }

              // if there is a localStorage object && submission.data is blank then bind localStorage to $scope
              if(localStorage.getItem($scope.storage) && isEmpty($scope.submission.data) == true){
                var storageToScope = JSON.parse(localStorage.getItem($scope.storage));
                $scope.submission.data = storageToScope.data
              }

              // if there is a localStorage object | && it is data | merge the two
              if(localStorage.getItem($scope.storage) && isEmpty($scope.submission.data) == false){
                localStorage.setItem($scope.storage, angular.toJson({
                  page: $scope.currentPage,
                  data: $scope.submission.data
                }));
              }
            }


            $scope.page.components = $scope.pages[$scope.currentPage].components;
            $scope.activePage = $scope.pages[$scope.currentPage];
            $scope.formioAlerts = [];
            if (scroll) {
              window.scrollTo(0, $scope.wizardTop);
            }
            $scope.wizardLoaded = true;
            $scope.$emit('wizardPage', $scope.currentPage);
            $timeout($scope.$apply.bind($scope));
          });
コード例 #26
0
ファイル: reducer.js プロジェクト: alexballera/wp-calypso
export function jetpackConnectAuthorize( state = {}, action ) {
	switch ( action.type ) {
		case JETPACK_CONNECT_AUTHORIZE:
			return Object.assign( {}, state, { isAuthorizing: true, authorizeSuccess: false, authorizeError: false, isRedirectingToWpAdmin: false } );
		case JETPACK_CONNECT_AUTHORIZE_RECEIVE:
			if ( isEmpty( action.error ) && action.data ) {
				const { plans_url, activate_manage } = action.data;
				return Object.assign( {}, state, { authorizeError: false, authorizeSuccess: true, autoAuthorize: false, plansUrl: plans_url, siteReceived: false, activateManageSecret: activate_manage } );
			}
			return Object.assign( {}, state, { isAuthorizing: false, authorizeError: action.error, authorizeSuccess: false, autoAuthorize: false } );
		case JETPACK_CONNECT_AUTHORIZE_RECEIVE_SITE_LIST:
			const updateQueryObject = omit( state.queryObject, '_wp_nonce', 'secret', 'scope' );
			return Object.assign( {}, omit( state, 'queryObject' ), { siteReceived: true, isAuthorizing: false, queryObject: updateQueryObject } );
		case JETPACK_CONNECT_ACTIVATE_MANAGE:
			return Object.assign( {}, state, { isActivating: true } );
		case JETPACK_CONNECT_ACTIVATE_MANAGE_RECEIVE:
			const error = action.error;
			return Object.assign( {}, state, { isActivating: false, manageActivated: true, manageActivatedError: error, activateManageSecret: false } );
		case JETPACK_CONNECT_QUERY_SET:
			const queryObject = Object.assign( {}, action.queryObject );
			return Object.assign( {}, defaultAuthorizeState, { queryObject: queryObject } );
		case JETPACK_CONNECT_QUERY_UPDATE:
			return Object.assign( {}, state, { queryObject: Object.assign( {}, state.queryObject, { [ action.property ]: action.value } ) } );
		case JETPACK_CONNECT_CREATE_ACCOUNT:
			return Object.assign( {}, state, { isAuthorizing: true, authorizeSuccess: false, authorizeError: false, autoAuthorize: true } );
		case JETPACK_CONNECT_CREATE_ACCOUNT_RECEIVE:
			if ( ! isEmpty( action.error ) ) {
				return Object.assign( {}, state, { isAuthorizing: false, authorizeSuccess: false, authorizeError: true, autoAuthorize: false } );
			}
			return Object.assign( {}, state, { isAuthorizing: true, authorizeSuccess: false, authorizeError: false, autoAuthorize: true, userData: action.userData, bearerToken: action.data.bearer_token } );
		case JETPACK_CONNECT_REDIRECT_WP_ADMIN:
			return Object.assign( {}, state, { isRedirectingToWpAdmin: true } );
		case DESERIALIZE:
			if ( isValidStateWithSchema( state, jetpackConnectAuthorizeSchema ) ) {
				return state;
			}
			return {};
		case SERIALIZE:
			return state;
	}
	return state;
}
コード例 #27
0
	_canGoForward: Function = (fields: Fields, page: string): boolean => {
		for (const field in fields) {
			const item = fields[field];

			if (this._getPageForField(field) === page && (item.error || this._isFieldRequired(field) && isEmpty(item.value))) {
				return false;
			}
		}

		return true;
	};
コード例 #28
0
ファイル: SelectFilter.js プロジェクト: data4society/mpro
    each(options, function(option) {
      if(!isNull(option) && !isEmpty(option)) {
        let optionEl = $$('option')
          .attr({value: option.toString()})
          .append(option.toString())

        if(value === option) optionEl.attr({selected: 'selected'})

        select.append(optionEl)
      }
    })
コード例 #29
0
ファイル: selectors.js プロジェクト: Vizzuality/gfw
  (data, latest) => {
    if (!data || isEmpty(data)) return null;
    const groupedByYear = groupBy(data, 'year');

    const hasAlertsByYears = Object.values(groupedByYear).reduce(
      (acc, next) => {
        const { year } = next[0];
        return {
          ...acc,
          [year]: next.some(item => item.alerts > 0)
        };
      },
      {}
    );
    const dataYears = Object.keys(hasAlertsByYears).filter(
      key => hasAlertsByYears[key] === true
    );
    const minYear = Math.min(...dataYears.map(el => parseInt(el, 10)));
    const startYear =
      minYear === moment().year() ? moment().year() - 1 : minYear;

    const years = [];
    const latestFullWeek = moment(latest).subtract(1, 'weeks');
    const lastWeek = {
      isoWeek: latestFullWeek.isoWeek(),
      year: latestFullWeek.year()
    };

    for (let i = startYear; i <= lastWeek.year; i += 1) {
      years.push(i);
    }
    const yearLengths = {};
    years.forEach(y => {
      if (lastWeek.year === parseInt(y, 10)) {
        yearLengths[y] = lastWeek.isoWeek;
      } else if (moment(`${y}-12-31`).weekday() === 1) {
        yearLengths[y] = moment(`${y}-12-30`).isoWeek();
      } else {
        yearLengths[y] = moment(`${y}-12-31`).isoWeek();
      }
    });
    const zeroFilledData = [];
    years.forEach(d => {
      const yearDataByWeek = groupBy(groupedByYear[d], 'week');
      for (let i = 1; i <= yearLengths[d]; i += 1) {
        zeroFilledData.push(
          yearDataByWeek[i]
            ? yearDataByWeek[i][0]
            : { count: 0, week: i, year: parseInt(d, 10) }
        );
      }
    });
    return zeroFilledData;
  }
コード例 #30
0
function setThemeOnSite( callback, { siteSlug }, { themeSlug } ) {
	if ( isEmpty( themeSlug ) ) {
		defer( callback );

		return;
	}

	wpcom.undocumented().changeTheme( siteSlug, { theme: themeSlug }, function( errors ) {
		callback( isEmpty( errors ) ? undefined : [ errors ] );
	} );
}