Example #1
0
  rightmousedrag (x0, y0, x1, y1) {
    let calcRadial = (x, y) => {
      x -= this.width() / 2
      y -= this.height() / 2

      let r = Math.sqrt(x * x + y * y)
      let t = Math.atan(y / x)
      if (x < 0) {
        if (y > 0) {
          t += Math.PI
        } else {
          t -= Math.PI
        }
      }

      return [r, t]
    }

    let r0 = _.take(1, calcRadial(x0, y0))
    let r1 = _.take(1, calcRadial(x1, y1))

    let ratio = 1.0
    if (r1 > 0.0) {
      ratio = r0 / r1
    }

    this.setCameraZoomFromScene(this.zoom * ratio)
  }
Example #2
0
export function initials(string = "", length = 3) {
  if (!string) return null
  const letters = take(string.match(/\b[A-Z]/g, ""), length)
  if (letters.length >= 1) return letters.join("").toUpperCase()
  return take(string.match(/\b\w/g, ""), length)
    .join("")
    .toUpperCase()
}
Example #3
0
const newtonTest = n => {
	const v = range(a, b, n)
	const x = [mean(take(v, 2)), mean(take(v.slice(floor(n / 2)), 2)), mean(takeRight(v, 2))]
	const p = x.map(newton(v))
	const fn = x.map(ary(f, 1))
	const r = subtract(p, x.map(ary(f, 1))).map(abs)
	const Rn = x.map(R2(v))
	print({name: 'Newton', n, x, p, Rn, fn, r})
}
Example #4
0
const chebyshevTest = n => {
	const v = [...Array(n + 1).keys()].map(i => mean(a, b) + mean(b, -a) * cos(PI * (i + 1 / 2) / (n + 1)))
	const x = [mean(take(v, 2)), mean(take(v.slice(floor(n / 2)), 2)), mean(takeRight(v, 2))]
	const p = x.map(lagrange(v))
	const fn = x.map(ary(f, 1))
	const r = subtract(p, x.map(ary(f, 1))).map(abs)
	const Rn = x.map(() => M / factorial(n + 1) * pow(b - a, n) * pow(2, 1 - 2 * n))
	print({name: 'Chebyshev, Lagrange', n, x, p, Rn, fn, r})
}
Example #5
0
const splineTest = n => {
	const v = range(a, b, n)
	const h = (b - a) / n
	const x = [mean(take(v, 2)), mean(take(v.slice(floor(n / 2)), 2)), mean(takeRight(v, 2))]
	const p = x.map(spline(v, h))
	const fn = x.map(ary(f, 1))
	const r = subtract(p, x.map(ary(f, 1))).map(abs)
	const Rn = x.map(R(v))
	print({name: 'Spline', n, x, p, Rn, fn, r})
}
Example #6
0
const ermitTest = n => {
	const v = range(a, b, n)
	const x = [mean(take(v, 2)), mean(take(v.slice(floor(n / 2)), 2)), mean(takeRight(v, 2))]
	const z = [...Array(2 * (n + 1)).keys()].map(i => floor(i / 2))
	const p = x.map(ermit(z, v))
	const fn = x.map(ary(f, 1))
	const r = subtract(p, x.map(ary(f, 1))).map(abs)
	const Rn = x.map(R(v))
	print({name: 'Ermit', n, x, p, Rn, fn, r})
}
Example #7
0
	function render(entities) {
		const props = generateProps(req, res, {
			homepage: true,
			recent: _.take(entities, numRevisionsOnHomepage),
			requireJS: Boolean(res.locals.user)
		});

		/*
		 * Renders react components server side and injects markup into target
		 * file object spread injects the app.locals variables into React as
		 * props
		 */
		const markup = ReactDOMServer.renderToString(
			<Layout {...propHelpers.extractLayoutProps(props)}>
				<Index
					recent={props.recent}
				/>
			</Layout>
		);

		res.send(target({
			dev: process.env.NODE_ENV === 'development',
			markup,
			page: 'Index',
			props: escapeProps(props),
			script: '/js/index.js'
		}));
	}
  this.runFetch = function (key) {
    var self = this;
    console.log("There " + this.fetchStationsChunks[key].length + " that should be fetched in chunk:" + key);
    var stationIds = _.map(this.fetchStationsChunks[key], function (stationInfo) {
      return stationInfo.id;
    });

    console.log("Fetching: "+ _.take(stationIds, 3)+"...");
    songza.station.getBatch(stationIds)
      .then(function (resolvedStations) {
        console.log("Resolved stations: " + resolvedStations.length + "/" + self.fetchStationsChunks[key].length);

        _.each(resolvedStations, function (resolvedStation) {
          var requestedStation = _.find(self.fetchStationsChunks[key], function (reqStation) {
            return reqStation.id == resolvedStation.id;
          });
          requestedStation.cb(resolvedStation);
        });
        delete self.fetchStationsChunks[key]; // clear that chunk

        // send those stations to lurker too so it will start to lookup for them:
        var lurker = new require('./index');
        setTimeout(function () {
          lurker.stationLookup(stationIds);
        }, 5000);
      });
  };
function attemptSplit(line, position) {
    /* TEST STRINGS
Field1	INTEGER	description for field 1
Field2	DATE	description for field 2
Field 3 and a bit  DECIMAL	fooobaa for the win
Field 4 and a bit, STRING,	more text	, and more
Field 5 and a bit,STRING,desc
 any, ENUM hfsjkhs jhdjsah jsah d
     */

    const atoms = _.split(line, /[,\W]+/);
    if (atoms.length > 2) {
        const words = _.chain(atoms)
            .map(w => w.trim())
            .filter(w => w.length > 0)
            .value();
        const typePos = _.findIndex(words, w => _.includes(allowedTypes, w));
        const name =_.join(_.take(words, typePos), " ");
        const type = words[typePos];
        const description = _.join(_.drop(words, typePos + 1), " ");
        return {
            name,
            type,
            description,
            position
        };
    }
}
Example #10
0
 .then((ads) => {
   const unpAds = _.take(ads.filter(i => i.images == null), 100)
   // const unpAds = ads.filter(i => i.id === 'i2448859')
   adQ.push(unpAds)
   console.log(unpAds.length, '/', ads.length)
   return null
 })
Example #11
0
Linter.prototype.lint = function (html) {
    var opts = Linter.getOptions(arguments),
        lines = knife.shred(html),
        dom = this.parser.parse(html),
        issues = null,
        maxerr = (!opts.maxerr && opts.maxerr !== 0 ? Infinity : opts.maxerr);

    this.setupSubscriptions();

    this.setupInlineConfigs(dom);

    issues = this.lintByLine(lines, opts);
    issues = issues.concat(this.lintDom(dom, opts));

    issues = issues.concat(this.resetRules(opts));
    this.inlineConfig.clear();

    if (maxerr >= 0) {
        issues = lodash.take(issues, maxerr);
    }

    return Promise.all(issues)
        .then(function (resolved) {
            return lodash.flattenDeep(resolved);
        });
};
Example #12
0
 render: list => {
   return (
     <ul style={{ listStyle: 'none' }}>
       {take(list, 3).map((obj, key) => <li key={key}>{obj.name}</li>)}
     </ul>
   );
 },
Example #13
0
 this.getText(window, (err, text)=> {
   if (err) {
     console.error(err);
     return callback('Error getting text');
   }
   const keywords = this.keywords(text);
   metadata.text = text;
   metadata.keywords = keywords;
   const description = _.take(text.split('. '), 3).join('. ');
   metadata.description = description;
   that.getImages(window, (err, images)=> {
     if (err) {
       console.error(err);
       return callback('Unable to get images');
     }
     metadata.images = _.map(images, function(obj, key){
       if (_.isNumber(key)) {
         return obj;
       }
       return null;
     });
     metadata.images = _.compact(metadata.images);
     callback(null, metadata);
   });
 });
  it("returns valid buildings KML response", function(done) {
    var selectedBuildings = _.take(buildingData, 10);

    var req = expressStub.req({
      params: {
        kml: true
      }
    });
    var res = expressStub.res();

    var findRes = mongooseStub.model(selectedBuildings);
    sandbox.stub(Building, "find").returns(mongooseStub.query(findRes));

    res.send = function(data) {
      expect(data).to.exist;
      expect(res.set).to.be.calledWith("Content-Type", "text/xml");
      expect(data.indexOf("<?xml version='1.0' encoding='UTF-8'?>")).to.not.equal(-1);
      done();
    };

    res.json = function(data) {
      expect.fail();
      done();
    };

    building.getBuildingsBbox(req, res);
  });
Example #15
0
	async aggregate(criteria, skip, limit){

		if (!criteria)
			criteria = {};
	
		let aggregationResult = await this.dbModel.aggregate(criteria).exec();
		if (aggregationResult.length == 0){
			return {
				data: aggregationResult,
				count: 0,
				skip:  skip,
				limit:  limit
			};
		}

		//per prima cosa ordino l'array
		// console.log('before sort', aggregationResult);
		aggregationResult = _.sortBy(aggregationResult, 'name');
		//poi pagino
		// console.log('before paginate', aggregationResult);
		var res = _.take( _.drop(aggregationResult, skip), limit);
		// console.log('post paginate', res);

		return {
			data: res,
				count: aggregationResult.length,
				skip:  skip,
				limit:  limit
		}
	}
  .forEach((weekIndex) => {
    const currentWeekTeams = [];
    _.forEach(weekOfFirstLossPerTeam, (weekLossCounts, teamName) => {
      runningTeamCounts[teamName] = runningTeamCounts[teamName] || 0;
      runningTeamCounts[teamName] += weekLossCounts[weekIndex];
      currentWeekTeams.push({
        teamName,
        lossCount: runningTeamCounts[teamName],
        lossCountPercentage: Number(
          ((runningTeamCounts[teamName] * 100) / seasonCountsPerTeam[teamName]).toFixed(2)
        ),
      });
    });

    const currentWeekTeamsSortedByLossCount = _.sortBy(
      currentWeekTeams,
      ({lossCount}) => -lossCount
    );
    const currentWeekTeamsSortedByLossCountPercentage = _.sortBy(
      currentWeekTeams,
      ({lossCountPercentage}) => -lossCountPercentage
    );

    console.log(
      `WEEK ${weekIndex + 1} LEADERS BY LOSS COUNT:`,
      _.take(currentWeekTeamsSortedByLossCount, 5).map(
        ({teamName, lossCount}) => `${teamName}-${lossCount}`
      )
    );

    // console.log(
    //   `WEEK ${weekIndex + 1} LEADERS BY LOSS COUNT PERCENTAGE:`,
    //   _.take(currentWeekTeamsSortedByLossCountPercentage, 5)
    // );
  });
Example #17
0
 usage.forEach(({line, matches, meanDuration, pattern, uri}) => {
   let col1 = [pattern.toString()]
   let col2 = []
   if (matches.length > 0) {
     if (isFinite(meanDuration)) {
       col2.push(`${parseFloat(meanDuration.toFixed(2))}ms`)
     } else {
       col2.push('-')
     }
   } else {
     col2.push('UNUSED')
   }
   let col3 = [formatLocation(this.cwd, {line, uri})]
   _.take(matches, 5).forEach((match) => {
     col1.push(`  ${match.text}`)
     if (isFinite(match.duration)) {
       col2.push(`${match.duration}ms`)
     }
     else {
       col2.push('-')
     }
     col3.push(formatLocation(this.cwd, match))
   })
   if (matches.length > 5) {
     col1.push(`  ${matches.length - 5} more`)
   }
   table.push([col1.join('\n'), col2.join('\n'), col3.join('\n')])
 })
Example #18
0
Reference.search = function(str) {
  str = str.toUpperCase();
  if (str === '') {
    return [];
  }
  var arr = Reference.dictionaryToArray();
  var isExplicit = str.match(/!/);
  if (!isExplicit) {
    arr = arr.filter(function(x) {
      return x.hidden !== true;
    });
  }
  sort(
    arr,
    sort.descending(function(x) {
      var label = x.label.toUpperCase();
      return stringSimilarity.compareTwoStrings(label, str);
    })
  );
  arr = _.uniqBy(arr, function(x) {
    // return x.href
    return URI(x.href)
      .fragment('')
      .toString();
  });
  arr = _.take(arr, 5);
  // sort(arr, sort.descending(function (x) {
  //   var title = x.title || x.label
  //   title = title.toUpperCase()
  //   return stringSimilarity.compareTwoStrings(title, str)
  // }))
  return arr;
};
    const rows = indexPatternIds.map((indexPatternId, key) => {
      const objects = this.state.objects[indexPatternId].list;
      const sample = take(objects, 5).map((obj, key) => <span key={key}>{obj.name}<br/></span>);

      return (
        <KuiTableRow key={key}>
          <KuiTableRowCell>
            {indexPatternId}
          </KuiTableRowCell>
          <KuiTableRowCell>
            {objects.length}
          </KuiTableRowCell>
          <KuiTableRowCell>
            {sample}
          </KuiTableRowCell>
          <KuiTableRowCell>
            <select
              className="kuiSelect kuiSelect--medium"
              data-test-subj="managementChangeIndexSelection"
              value={this.state.objects[indexPatternId].newIndexPatternId}
              onChange={this.onIndexChange.bind(this, indexPatternId)}
            >
              <option value={indexPatternId}>Skip import</option>
              {this.props.indices.map((index, i) => {
                return (
                  <option key={i} value={index.id}>
                    {index.get('title')}
                  </option>
                );
              })}
            </select>
          </KuiTableRowCell>
        </KuiTableRow>
      );
    });
Example #20
0
// Estimates spent working hours based on commit dates
function estimateHours(dates) {
    if (dates.length < 2) {
        return 0;
    }

    // Oldest commit first, newest last
    var sortedDates = dates.sort(function(a, b) {
        return a - b;
    });
    var allButLast = _.take(sortedDates, sortedDates.length - 1);

    var hours = _.reduce(allButLast, function(hours, date, index) {
        var nextDate = sortedDates[index + 1];
        var diffInMinutes = (nextDate - date) / 1000 / 60;

        // Check if commits are counted to be in same coding session
        if (diffInMinutes < config.maxCommitDiffInMinutes) {
            return hours + (diffInMinutes / 60);
        }

        // The date difference is too big to be inside single coding session
        // The work of first commit of a session cannot be seen in git history,
        // so we make a blunt estimate of it
        return hours + (config.firstCommitAdditionInMinutes / 60);

    }, 0);

    return Math.round(hours);
}
Example #21
0
  function* search(query, res) {
    const query_trim = query.trim();
    if (query_trim.length === 0)
      return;

    const query_enc = encodeURIComponent(query_trim);

    res.add({
      id: `http://bower.io/search/?q=${query_enc}`,
      payload: 'open',
      title: 'Search: ' + query,
      desc: DESC
    });

    let results = yield* queryBower(query_trim);
    results = _.reject(results, (x) => x === query_trim);
    results = _.take(results, 10).map((x) => {
      return {
        id: x['url'],  
        payload: 'open',
        title: x['name'],
        desc: x['url'],
      };
    });
    res.add(results);
  }
  // Parse the route into
  function _parseRoute (pathComponents, urlComponents) {
    // Extract resource name from path
    var resourceName = _.first(pathComponents);

    // Extract parameters from resource (we must parse the url our selves because expresses router overrides parameters with the same name)
    var paramNames = _.take(pathComponents.slice(1), isParam);
    var paramIndexes = _.map(paramNames, _.partial(_.indexOf, pathComponents));
    var paramValues = _.map(paramIndexes, function (index) { return urlComponents[index]; });
    paramNames = _.map(paramNames, function (paramName) { return paramName.slice(1); });

    // Remove the parsed part from the url and path
    pathComponents = _.drop(pathComponents, paramNames.length + 1);
    urlComponents = _.drop(urlComponents, paramNames.length + 1);

    var resource = {
      name: resourceName,
      conditions: _.zipObject(paramNames, paramValues)
    };

    // Recursively parse the rest of the path
    if (pathComponents.length > 0) {
      return [resource].concat(_parseRoute(pathComponents, urlComponents));
    }

    return [resource];
  }
Example #23
0
  _renderApps = () => {
    if (!this.props.data.user) {
      return;
    }

    let { apps, appCount } = this.props.data.user;

    if (!apps || !apps.length) {
      return <EmptyProfileProjectsNotice isOwnProfile={this.props.isOwnProfile} />;
    } else {
      // let appsToDisplay = take(apps, MAX_APPS_TO_DISPLAY);
      let otherApps = takeRight(apps, Math.max(0, apps.length - MAX_APPS_TO_DISPLAY));

      return (
        <View>
          <View style={[SharedStyles.sectionLabelContainer, { marginTop: 10 }]}>
            <Text style={SharedStyles.sectionLabelText}>PROJECTS</Text>
          </View>

          {take(apps, 3).map(this._renderApp)}
          <SeeAllProjectsButton
            apps={otherApps}
            appCount={appCount - 3}
            label="See all projects"
            onPress={this._handlePressProjectList}
          />
        </View>
      );
    }
  };
Example #24
0
 Post.find({}, function(err, posts){
   if(err){
     res.status(500).json({
       msg: err
     });
   } else {
     var numberOfPostsToGet = req.params.number; //grabbing the number from the url
     //The following variables uses lodash to order the posts array by the
     // create tag in ascending order. Remember the posts variables would be
     // an array that has objects in it that looks like the following:
     // {
     //  title: 'Awesome Post',
     //  body: "I have done some amazing things!",
     //  created: 2016-08-01T14:00:00Z
     //  author: 74iify4i82edujfk,
     //  updated: 2016-08-04T18:00:00Z
     // }
     var postsOrderedByDate = _.orderBy(posts, ['created'], ['asc']);
     // The following function takes the previous array of values and
     // grabs the first :number (for example 10) of posts of the ordered posts
     var firstNumberOfOrderedPosts = _.take(postsOrderedByDate, numberOfPostsToGet);
     //Return the first :number of date ordered posts
     res.status(200).json({
       posts: firstNumberOfOrderedPosts
     });
   }
 });
Example #25
0
	getMatchingSuggestions(
		searchValue = this.state.incompleteTokenValue,
		suggestions = this.props.suggestions,
		value = this.props.value,
		maxSuggestions = this.props.maxSuggestions,
		saveTransform = this.props.saveTransform,
	) {
		let match = saveTransform( searchValue );
		const startsWithMatch = [];
		const containsMatch = [];

		if ( match.length === 0 ) {
			suggestions = difference( suggestions, value );
		} else {
			match = match.toLocaleLowerCase();

			each( suggestions, ( suggestion ) => {
				const index = suggestion.toLocaleLowerCase().indexOf( match );
				if ( value.indexOf( suggestion ) === -1 ) {
					if ( index === 0 ) {
						startsWithMatch.push( suggestion );
					} else if ( index > 0 ) {
						containsMatch.push( suggestion );
					}
				}
			} );

			suggestions = startsWithMatch.concat( containsMatch );
		}

		return take( suggestions, maxSuggestions );
	}
 context.api.getSuggestedSymptoms(context.data).then((suggestedSymptoms) => {
   if (!suggestedSymptoms.length) {
     resolve('<p><i class="fa fa-circle-o-notch fa-spin fa-fw"></i> I am thinking...</p>');
     document.getElementById('next-step').click();
   }
   resolve(html`
       <h5 class="card-title">Do you have any of the following symptoms?</h5>
       <div class="card-text">
         <form>
           ${_.take(suggestedSymptoms, 5).map(symptom => {
             return html`
               <div class="form-group">
                 <label class="custom-control custom-checkbox mb-2 mr-sm-2 mb-sm-0">
                   <input id="${symptom.id}" type="checkbox" class="input-symptom custom-control-input">
                   <span class="custom-control-indicator"></span>
                   <span class="custom-control-description">${symptom.name}</span>
                 </label>
               </div>
             `;
           })}
         </form>
         <p class="text-muted small"><i class="fa fa-info-circle"></i> This is a list of symptoms suggested by our AI, based on the information gathered so far during the interview.</p>
       </div>
     `);
 });
Example #27
0
 return _.map(_.sample(this.props.hotel.result, 6), hotel => {
   let splitUri = hotel.business_uri.split('?');
   let noRootUri = splitUri[0].split('tiket.com/');
   let validUri = noRootUri[1].replace(/\//g, "_");
   return (
     <div className="col-md-4 col-sm-6 col-xs-12" key={hotel.id}>
       <div className="popular_hotel_box ">
         <div className="img">
           <Link
             to={`/${validUri}/${moment().format('YYYY-MM-DD')}/1/1/2`}>
             <img src={`${hotel.photo_primary}`} alt="place" className="img-responsive" />
           </Link>
         </div>
         <div className="hotel_detail">
           <div className="hotel-name">
             <h4>{_.take(_.words(hotel.name), 4).join(" ")}</h4>
             <p><i className="fa fa-map-marker"></i> {hotel.regional}</p>
             <div className="pull-left">Price per night from:</div>
             <div className="pull-right">IDR {numeral(hotel.price).format('IDR 0,0')}</div>
             <div className="book-now">
               <Link
                 to={`/${validUri}/${moment().format('YYYY-MM-DD')}/1/1/2`}
                 className="btn btn_book_now"
               >
                 View Room
               </Link>
             </div>
           </div>
         </div>
       </div>
     </div>
   );
 });
Example #28
0
function isFourValidCandidate( processed, toProcess ) {
	const ratio = sum( take( toProcess, 4 ) );
	return (
		( fourIsNotRecent( processed ) && ( ratio < 3.5 && toProcess.length > 5 ) ) ||
		( ratio < 7 && toProcess.length === 4 )
	);
}
Example #29
0
 .then(results => {
   if (results.length != 1) {
     throw undefined;
   }
   const user = results[0];
   let oldPasswords = [];
   if (user._password_history)
     oldPasswords = _.take(user._password_history, this.config.passwordPolicy.maxPasswordHistory - 1);
   oldPasswords.push(user.password);
   const newPassword = this.data.password;
   // compare the new password hash with all old password hashes
   let promises = oldPasswords.map(function (hash) {
     return passwordCrypto.compare(newPassword, hash).then((result) => {
       if (result) // reject if there is a match
         return Promise.reject("REPEAT_PASSWORD");
       return Promise.resolve();
     })
   });
   // wait for all comparisons to complete
   return Promise.all(promises).then(() => {
     return Promise.resolve();
   }).catch(err => {
     if (err === "REPEAT_PASSWORD") // a match was found
       return Promise.reject(new Parse.Error(Parse.Error.VALIDATION_ERROR, `New password should not be the same as last ${this.config.passwordPolicy.maxPasswordHistory} passwords.`));
     throw err;
   });
 });
Example #30
0
function renderChange(change) {
  let before = [], after = [];

  const descriptor = [{highlighted: `In line ${change.line}:\n`}];

  if (change.before) {
    // at least one line of context, if possible
    const beforeLines = _.takeRight(change.before.value.split("\n"), 2);
    before = beforeLines.map((line, index) => {
      return (index != beforeLines.length - 1) ? line + "\n" : line;
    });
  }

  const changed = change.parts.map(part => {
    if (part.removed)
      return {removed: part.value};
    if (part.added)
      return {added: part.value};
  });

  if (change.after) {
    // at least one line of context, if possible
    const afterLines = _.take(change.after.value.split("\n"), 2);
    after = afterLines.map((line, index) => {
      return (index != afterLines.length - 1) ? line + "\n" : line;
    });
  }

  return [].concat(descriptor, before, changed, after);
}