code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
<?php get_header(); ?> <?php the_breadcrumb(); ?> <div class="container"> <div class="row"> <!-- section --> <section role="main" class="col-sm-9"> <?php if (have_posts()): while (have_posts()) : the_post(); ?> <!-- article --> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <!-- post title --> <div class="page-header"> <h1> <?php the_title(); ?> </h1> </div> <!-- /post title --> <!-- post details --> <p class="post-meta"> <span class="date text-muted"> <span class="fa fa-calendar-o"></span> <?php the_time('j. F - Y'); ?> <span class="fa fa-folder-o"></span> <?php the_category(', '); // Separated by commas ?> <span class="fa fa-pencil-square-o"></span> <?php the_author_posts_link(); ?></span> </span> </p> <!-- /post details --> <!-- Featured Image --> <?php // check if the post has a Post Thumbnail assigned to it. if ( has_post_thumbnail() ) { ?> <?php the_post_thumbnail(" img-thumbnail"); ?> <?php } ?> <!-- /Featured Image --> <?php the_content(); // Dynamic Content ?> </article> <?php get_template_part( 'partials/objects/meta-after-post' ); ?> <!-- /article --> <?php // If comments are open or we have at least one comment, load up the comment template if ( comments_open() || '0' != get_comments_number() ) comments_template(); ?> <?php endwhile; ?> <?php else: ?> <!-- article --> <article> <h1><?php _e( 'Sorry, nothing to display.', 'toro' ); ?></h1> </article> <!-- /article --> <?php endif; ?> </section> <!-- /section --> <aside> <?php // get_sidebar(); ?> </aside> </div> </div> <?php get_footer(); ?>
Jursdotme/toro
single.php
PHP
mit
1,748
package org.lua.commons.customapi.javafunctions.handlers; import org.lua.commons.baseapi.LuaThread; import org.lua.commons.baseapi.extensions.LuaExtension; import org.lua.commons.baseapi.types.LuaObject; import org.lua.commons.customapi.javafunctions.handlers.types.Type; public interface TypeCastManager extends LuaExtension { public void addHandler(Class<? extends TypeHandler> handler); public void add(Class<? extends TypeHandler> handler, Class<?>... keys); public void remove(Class<?> key); public Object castFrom(LuaThread thread, LuaObject obj, Type expected); public LuaObject castTo(LuaThread thread, Object obj); }
mrkosterix/lua-commons
lua-commons-3-custom-level/src/main/java/org/lua/commons/customapi/javafunctions/handlers/TypeCastManager.java
Java
mit
653
<?php /* * This file is part of the JobQueue package. * * (c) Jens Schwehn <jens@ldk.net> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ $loader = require __DIR__ . "/../vendor/autoload.php"; $loader->add('JobQueue\\', __DIR__); $loader->add('JobQueue\ConsumerCommand\\', __DIR__ . '/Consumers/');
JSchwehn/JobQueue
tests/bootstrap.php
PHP
mit
390
const mongoose = require('mongoose') let literatureSchema = mongoose.Schema({ category: { type: String, required: true}, name: { type: String, required: true }, description: { type: String }, content: { type: String, required: true }, author: { type: mongoose.Schema.Types.ObjectId, required: true, ref: 'User' }, comments: [{type: mongoose.Schema.Types.ObjectId, ref: 'Comment'}], views: {type: Number}, date: { type: String } }) literatureSchema.method({ prepareDelete: function () { let User = mongoose.model('User') User.findById(this.author).then(user => { "use strict"; if (user) { user.literature.remove(this.id) user.save() } }) let Comment = mongoose.model('Comment') for (let commentId of this.comments) { Comment.findOneAndRemove(commentId).populate('author').then(comment => { "use strict"; if (comment) { let author = comment.author let index = author.comments.indexOf(commentId) let count = 1 author.comments.splice(index, count); author.save() comment.save() } }) } } }) literatureSchema.set('versionKey', false); const Literature = mongoose.model('Literature', literatureSchema) module.exports = Literature
losko/CodeNameSite
server/data/Literature.js
JavaScript
mit
1,477
#!/usr/bin/env python # -*- coding: utf-8 -*- import bottle import datetime import time @bottle.get('/') def index(): return bottle.static_file('index.html', root='.') @bottle.get('/stream') def stream(): bottle.response.content_type = 'text/event-stream' bottle.response.cache_control = 'no-cache' while True: yield 'data: %s\n\n' % str(datetime.datetime.now()) time.sleep(5) if __name__ == '__main__': bottle.run(host='0.0.0.0', port=8080, debug=True)
hustbeta/python-web-recipes
server-sent-events/bottle-sse.py
Python
mit
517
module DocFrac class Format attr_reader :format_text, :ext def initialize(format) formats = { :to_rtf => "--to-rtf", :from_rtf => "--from-rtf", :to_html => "--to-html", :from_html => "--from-html", :to_text => "--to-text", :from_text => "--from-text" } @format_text = formats[format] @ext = format.to_s.split("_").last end end end
Digi-Cazter/doc_frac
lib/doc_frac/format.rb
Ruby
mit
418
/* * * Copyright (C) 2008-2012, OFFIS e.V. and ICSMED AG, Oldenburg, Germany * Copyright (C) 2013-2015, J. Riesmeier, Oldenburg, Germany * All rights reserved. See COPYRIGHT file for details. * * Source file for class DRTBeamLimitingDeviceLeafPairsSequence * * Generated automatically from DICOM PS 3.3-2015c * File created on 2015-12-07 16:29:33 * */ #include "dcmtk/config/osconfig.h" // make sure OS specific configuration is included first #include "dcmtk/dcmrt/seq/drtbldls.h" // --- item class --- DRTBeamLimitingDeviceLeafPairsSequence::Item::Item(const OFBool emptyDefaultItem) : EmptyDefaultItem(emptyDefaultItem), NumberOfLeafJawPairs(DCM_NumberOfLeafJawPairs), RTBeamLimitingDeviceType(DCM_RTBeamLimitingDeviceType) { } DRTBeamLimitingDeviceLeafPairsSequence::Item::Item(const Item &copy) : EmptyDefaultItem(copy.EmptyDefaultItem), NumberOfLeafJawPairs(copy.NumberOfLeafJawPairs), RTBeamLimitingDeviceType(copy.RTBeamLimitingDeviceType) { } DRTBeamLimitingDeviceLeafPairsSequence::Item::~Item() { } DRTBeamLimitingDeviceLeafPairsSequence::Item &DRTBeamLimitingDeviceLeafPairsSequence::Item::operator=(const Item &copy) { if (this != &copy) { EmptyDefaultItem = copy.EmptyDefaultItem; NumberOfLeafJawPairs = copy.NumberOfLeafJawPairs; RTBeamLimitingDeviceType = copy.RTBeamLimitingDeviceType; } return *this; } void DRTBeamLimitingDeviceLeafPairsSequence::Item::clear() { if (!EmptyDefaultItem) { /* clear all DICOM attributes */ RTBeamLimitingDeviceType.clear(); NumberOfLeafJawPairs.clear(); } } OFBool DRTBeamLimitingDeviceLeafPairsSequence::Item::isEmpty() { return RTBeamLimitingDeviceType.isEmpty() && NumberOfLeafJawPairs.isEmpty(); } OFBool DRTBeamLimitingDeviceLeafPairsSequence::Item::isValid() const { return !EmptyDefaultItem; } OFCondition DRTBeamLimitingDeviceLeafPairsSequence::Item::read(DcmItem &item) { OFCondition result = EC_IllegalCall; if (!EmptyDefaultItem) { /* re-initialize object */ clear(); getAndCheckElementFromDataset(item, RTBeamLimitingDeviceType, "1", "1", "BeamLimitingDeviceLeafPairsSequence"); getAndCheckElementFromDataset(item, NumberOfLeafJawPairs, "1", "1", "BeamLimitingDeviceLeafPairsSequence"); result = EC_Normal; } return result; } OFCondition DRTBeamLimitingDeviceLeafPairsSequence::Item::write(DcmItem &item) { OFCondition result = EC_IllegalCall; if (!EmptyDefaultItem) { result = EC_Normal; addElementToDataset(result, item, new DcmCodeString(RTBeamLimitingDeviceType), "1", "1", "BeamLimitingDeviceLeafPairsSequence"); addElementToDataset(result, item, new DcmIntegerString(NumberOfLeafJawPairs), "1", "1", "BeamLimitingDeviceLeafPairsSequence"); } return result; } OFCondition DRTBeamLimitingDeviceLeafPairsSequence::Item::getNumberOfLeafJawPairs(OFString &value, const signed long pos) const { if (EmptyDefaultItem) return EC_IllegalCall; else return getStringValueFromElement(NumberOfLeafJawPairs, value, pos); } OFCondition DRTBeamLimitingDeviceLeafPairsSequence::Item::getNumberOfLeafJawPairs(Sint32 &value, const unsigned long pos) const { if (EmptyDefaultItem) return EC_IllegalCall; else return OFconst_cast(DcmIntegerString &, NumberOfLeafJawPairs).getSint32(value, pos); } OFCondition DRTBeamLimitingDeviceLeafPairsSequence::Item::getRTBeamLimitingDeviceType(OFString &value, const signed long pos) const { if (EmptyDefaultItem) return EC_IllegalCall; else return getStringValueFromElement(RTBeamLimitingDeviceType, value, pos); } OFCondition DRTBeamLimitingDeviceLeafPairsSequence::Item::setNumberOfLeafJawPairs(const OFString &value, const OFBool check) { OFCondition result = EC_IllegalCall; if (!EmptyDefaultItem) { result = (check) ? DcmIntegerString::checkStringValue(value, "1") : EC_Normal; if (result.good()) result = NumberOfLeafJawPairs.putOFStringArray(value); } return result; } OFCondition DRTBeamLimitingDeviceLeafPairsSequence::Item::setRTBeamLimitingDeviceType(const OFString &value, const OFBool check) { OFCondition result = EC_IllegalCall; if (!EmptyDefaultItem) { result = (check) ? DcmCodeString::checkStringValue(value, "1") : EC_Normal; if (result.good()) result = RTBeamLimitingDeviceType.putOFStringArray(value); } return result; } // --- sequence class --- DRTBeamLimitingDeviceLeafPairsSequence::DRTBeamLimitingDeviceLeafPairsSequence(const OFBool emptyDefaultSequence) : EmptyDefaultSequence(emptyDefaultSequence), SequenceOfItems(), CurrentItem(), EmptyItem(OFTrue /*emptyDefaultItem*/) { CurrentItem = SequenceOfItems.end(); } DRTBeamLimitingDeviceLeafPairsSequence::DRTBeamLimitingDeviceLeafPairsSequence(const DRTBeamLimitingDeviceLeafPairsSequence &copy) : EmptyDefaultSequence(copy.EmptyDefaultSequence), SequenceOfItems(), CurrentItem(), EmptyItem(OFTrue /*emptyDefaultItem*/) { /* create a copy of the internal sequence of items */ Item *item = NULL; OFListConstIterator(Item *) current = copy.SequenceOfItems.begin(); const OFListConstIterator(Item *) last = copy.SequenceOfItems.end(); while (current != last) { item = new Item(**current); if (item != NULL) { SequenceOfItems.push_back(item); } else { /* memory exhausted, there is nothing we can do about it */ break; } ++current; } CurrentItem = SequenceOfItems.begin(); } DRTBeamLimitingDeviceLeafPairsSequence &DRTBeamLimitingDeviceLeafPairsSequence::operator=(const DRTBeamLimitingDeviceLeafPairsSequence &copy) { if (this != &copy) { clear(); EmptyDefaultSequence = copy.EmptyDefaultSequence; /* create a copy of the internal sequence of items */ Item *item = NULL; OFListConstIterator(Item *) current = copy.SequenceOfItems.begin(); const OFListConstIterator(Item *) last = copy.SequenceOfItems.end(); while (current != last) { item = new Item(**current); if (item != NULL) { SequenceOfItems.push_back(item); } else { /* memory exhausted, there is nothing we can do about it */ break; } ++current; } CurrentItem = SequenceOfItems.begin(); } return *this; } DRTBeamLimitingDeviceLeafPairsSequence::~DRTBeamLimitingDeviceLeafPairsSequence() { clear(); } void DRTBeamLimitingDeviceLeafPairsSequence::clear() { if (!EmptyDefaultSequence) { CurrentItem = SequenceOfItems.begin(); const OFListConstIterator(Item *) last = SequenceOfItems.end(); /* delete all items and free memory */ while (CurrentItem != last) { delete (*CurrentItem); CurrentItem = SequenceOfItems.erase(CurrentItem); } /* make sure that the list is empty */ SequenceOfItems.clear(); CurrentItem = SequenceOfItems.end(); } } OFBool DRTBeamLimitingDeviceLeafPairsSequence::isEmpty() { return SequenceOfItems.empty(); } OFBool DRTBeamLimitingDeviceLeafPairsSequence::isValid() const { return !EmptyDefaultSequence; } unsigned long DRTBeamLimitingDeviceLeafPairsSequence::getNumberOfItems() const { return SequenceOfItems.size(); } OFCondition DRTBeamLimitingDeviceLeafPairsSequence::gotoFirstItem() { OFCondition result = EC_IllegalCall; if (!SequenceOfItems.empty()) { CurrentItem = SequenceOfItems.begin(); result = EC_Normal; } return result; } OFCondition DRTBeamLimitingDeviceLeafPairsSequence::gotoNextItem() { OFCondition result = EC_IllegalCall; if (CurrentItem != SequenceOfItems.end()) { ++CurrentItem; result = EC_Normal; } return result; } OFCondition DRTBeamLimitingDeviceLeafPairsSequence::gotoItem(const unsigned long num, OFListIterator(Item *) &iterator) { OFCondition result = EC_IllegalCall; if (!SequenceOfItems.empty()) { unsigned long idx = num + 1; iterator = SequenceOfItems.begin(); const OFListConstIterator(Item *) last = SequenceOfItems.end(); while ((--idx > 0) && (iterator != last)) ++iterator; /* specified list item found? */ if ((idx == 0) && (iterator != last)) result = EC_Normal; else result = EC_IllegalParameter; } return result; } OFCondition DRTBeamLimitingDeviceLeafPairsSequence::gotoItem(const unsigned long num, OFListConstIterator(Item *) &iterator) const { OFCondition result = EC_IllegalCall; if (!SequenceOfItems.empty()) { unsigned long idx = num + 1; iterator = SequenceOfItems.begin(); const OFListConstIterator(Item *) last = SequenceOfItems.end(); while ((--idx > 0) && (iterator != last)) ++iterator; /* specified list item found? */ if ((idx == 0) && (iterator != last)) result = EC_Normal; else result = EC_IllegalParameter; } return result; } OFCondition DRTBeamLimitingDeviceLeafPairsSequence::gotoItem(const unsigned long num) { return gotoItem(num, CurrentItem); } OFCondition DRTBeamLimitingDeviceLeafPairsSequence::getCurrentItem(Item *&item) const { OFCondition result = EC_IllegalCall; if (CurrentItem != SequenceOfItems.end()) { item = *CurrentItem; result = EC_Normal; } return result; } DRTBeamLimitingDeviceLeafPairsSequence::Item &DRTBeamLimitingDeviceLeafPairsSequence::getCurrentItem() { if (CurrentItem != SequenceOfItems.end()) return **CurrentItem; else return EmptyItem; } const DRTBeamLimitingDeviceLeafPairsSequence::Item &DRTBeamLimitingDeviceLeafPairsSequence::getCurrentItem() const { if (CurrentItem != SequenceOfItems.end()) return **CurrentItem; else return EmptyItem; } OFCondition DRTBeamLimitingDeviceLeafPairsSequence::getItem(const unsigned long num, Item *&item) { OFListIterator(Item *) iterator; OFCondition result = gotoItem(num, iterator); if (result.good()) item = *iterator; return result; } DRTBeamLimitingDeviceLeafPairsSequence::Item &DRTBeamLimitingDeviceLeafPairsSequence::getItem(const unsigned long num) { OFListIterator(Item *) iterator; if (gotoItem(num, iterator).good()) return **iterator; else return EmptyItem; } const DRTBeamLimitingDeviceLeafPairsSequence::Item &DRTBeamLimitingDeviceLeafPairsSequence::getItem(const unsigned long num) const { OFListConstIterator(Item *) iterator; if (gotoItem(num, iterator).good()) return **iterator; else return EmptyItem; } DRTBeamLimitingDeviceLeafPairsSequence::Item &DRTBeamLimitingDeviceLeafPairsSequence::operator[](const unsigned long num) { return getItem(num); } const DRTBeamLimitingDeviceLeafPairsSequence::Item &DRTBeamLimitingDeviceLeafPairsSequence::operator[](const unsigned long num) const { return getItem(num); } OFCondition DRTBeamLimitingDeviceLeafPairsSequence::addItem(Item *&item) { OFCondition result = EC_IllegalCall; if (!EmptyDefaultSequence) { item = new Item(); if (item != NULL) { SequenceOfItems.push_back(item); result = EC_Normal; } else result = EC_MemoryExhausted; } return result; } OFCondition DRTBeamLimitingDeviceLeafPairsSequence::insertItem(const unsigned long pos, Item *&item) { OFCondition result = EC_IllegalCall; if (!EmptyDefaultSequence) { OFListIterator(Item *) iterator; result = gotoItem(pos, iterator); if (result.good()) { item = new Item(); if (item != NULL) { SequenceOfItems.insert(iterator, 1, item); result = EC_Normal; } else result = EC_MemoryExhausted; } else result = addItem(item); } return result; } OFCondition DRTBeamLimitingDeviceLeafPairsSequence::removeItem(const unsigned long pos) { OFCondition result = EC_IllegalCall; if (!EmptyDefaultSequence) { OFListIterator(Item *) iterator; if (gotoItem(pos, iterator).good()) { delete *iterator; iterator = SequenceOfItems.erase(iterator); result = EC_Normal; } else result = EC_IllegalParameter; } return result; } OFCondition DRTBeamLimitingDeviceLeafPairsSequence::read(DcmItem &dataset, const OFString &card, const OFString &type, const char *moduleName) { OFCondition result = EC_IllegalCall; if (!EmptyDefaultSequence) { /* re-initialize object */ clear(); /* retrieve sequence element from dataset */ DcmSequenceOfItems *sequence; result = dataset.findAndGetSequence(DCM_BeamLimitingDeviceLeafPairsSequence, sequence); if (sequence != NULL) { if (checkElementValue(*sequence, card, type, result, moduleName)) { DcmStack stack; OFBool first = OFTrue; /* iterate over all sequence items */ while (result.good() && sequence->nextObject(stack, first /*intoSub*/).good()) { DcmItem *ditem = OFstatic_cast(DcmItem *, stack.top()); if (ditem != NULL) { Item *item = new Item(); if (item != NULL) { result = item->read(*ditem); if (result.good()) { /* append new item to the end of the list */ SequenceOfItems.push_back(item); first = OFFalse; } } else result = EC_MemoryExhausted; } else result = EC_CorruptedData; } } } else { DcmSequenceOfItems element(DCM_BeamLimitingDeviceLeafPairsSequence); checkElementValue(element, card, type, result, moduleName); } } return result; } OFCondition DRTBeamLimitingDeviceLeafPairsSequence::write(DcmItem &dataset, const OFString &card, const OFString &type, const char *moduleName) { OFCondition result = EC_IllegalCall; if (!EmptyDefaultSequence) { result = EC_MemoryExhausted; DcmSequenceOfItems *sequence = new DcmSequenceOfItems(DCM_BeamLimitingDeviceLeafPairsSequence); if (sequence != NULL) { result = EC_Normal; /* an empty optional sequence is not written */ if ((type == "2") || !SequenceOfItems.empty()) { OFListIterator(Item *) iterator = SequenceOfItems.begin(); const OFListConstIterator(Item *) last = SequenceOfItems.end(); /* iterate over all sequence items */ while (result.good() && (iterator != last)) { DcmItem *item = new DcmItem(); if (item != NULL) { /* append new item to the end of the sequence */ result = sequence->append(item); if (result.good()) { result = (*iterator)->write(*item); ++iterator; } else delete item; } else result = EC_MemoryExhausted; } if (result.good()) { /* insert sequence element into the dataset */ result = dataset.insert(sequence, OFTrue /*replaceOld*/); } if (DCM_dcmrtLogger.isEnabledFor(OFLogger::WARN_LOG_LEVEL)) checkElementValue(*sequence, card, type, result, moduleName); if (result.good()) { /* forget reference to sequence object (avoid deletion below) */ sequence = NULL; } } else if (type == "1") { /* empty type 1 sequence not allowed */ result = RT_EC_InvalidValue; if (DCM_dcmrtLogger.isEnabledFor(OFLogger::WARN_LOG_LEVEL)) checkElementValue(*sequence, card, type, result, moduleName); } /* delete sequence (if not inserted into the dataset) */ delete sequence; } } return result; } // end of source file
cronelab/radroom
conversion/dcmtk/dcmrt/libsrc/drtbldls.cc
C++
mit
17,508
// Saves options to chrome.storage function save_options () { var saveDict = [] var i = 1 $('input').map(function () { var dict = { id: 'scbcc' + i, value: this.value } i++ console.log('save: ', dict) ga('send', 'event', 'setting', 'save', this.value) saveDict.push(dict) }).get() chrome.storage.sync.set({ scbccRegexDict: saveDict }) } // Restores select box and checkbox state using the preferences // stored in chrome.storage. function restore_options () { chrome.storage.sync.get({ scbccRegexDict: [] }, function (items) { $('#field1').attr('value', items.scbccRegexDict[0].value) for (var i = 0; i < items.scbccRegexDict.length; i++) { var value = items.scbccRegexDict[i].value var next = i var addto = '#remove' + next var addRemove = '#field' + (next + 1) next = next + 1 var newIn = '<input autocomplete="off" placeholder="e.g. /this is test/g" id="field' + next + '" name="field' + next + '" type="text" tabindex="1" value=' + value + '>' var newInput = $(newIn) var removeBtn = '<button id="remove' + (next) + '" class="btn btn-danger remove-me" >-</button>' var removeButton = $(removeBtn) $(addto).after(newInput) if (i !== 0) { $(addRemove).after(removeButton) } $('#count').val(next) $('.remove-me').click(function (e) { e.preventDefault() ga('send', 'event', 'setting', 'remove_regex') var fieldNum = this.id.charAt(this.id.length - 1) var fieldID = '#field' + fieldNum $(this).remove() $(fieldID).remove() $('#style').attr('href', 'extra/styles.css') }) } var next = items.scbccRegexDict.length || 1 $('.add-more').click(function (e) { ga('send', 'event', 'setting', 'add_regex') e.preventDefault() var addto = '#remove' + next var addRemove = '#field' + (next + 1) next = next + 1 var newIn = '<input autocomplete="off" placeholder="e.g. /this is test/g" id="field' + next + '" name="field' + next + '" type="text" tabindex="1">' var newInput = $(newIn) var removeBtn = '<button id="remove' + (next) + '" class="btn btn-danger remove-me" >-</button>' var removeButton = $(removeBtn) $(addto).after(newInput) $(addRemove).after(removeButton) $('#count').val(next) $('.remove-me').click(function (e) { e.preventDefault() ga('send', 'event', 'setting', 'remove_regex') var fieldNum = this.id.charAt(this.id.length - 1) var fieldID = '#field' + fieldNum $(this).remove() $(fieldID).remove() $('#style').attr('href', 'extra/styles.css') }) }) }) } document.addEventListener('DOMContentLoaded', restore_options) document.getElementById('save').addEventListener('click', save_options)
samcheuk/boring-copy-cat
options.js
JavaScript
mit
2,881
<?php namespace Service; use Core\Service; use Db\Group\GetInvitations; use Db\Group\Search; use Model\Group as GroupModel; use Db\Group\GetByUserId; use Db\Group\GetById; use Db\Group\Store; class Group extends Service { /** * @param $userId * @return GroupModel[] * @throws \Core\Query\NoResultException */ public static function getByUserId($userId) { $query = new GetByUserId(); $query->setUserId($userId); return self::fillCollection(new GroupModel(), $query->fetchAll()); } /** * @param $id * @return GroupModel * @throws \Core\Query\NoResultException */ public static function getById($id) { $query = new GetById(); $query->setId($id); return self::fillModel(new GroupModel(), $query->fetchRow()); } /** * @param GroupModel $group * @return int */ public static function store(GroupModel $group) { $query = new Store(); $query->setId($group->getId()); $query->setName($group->getName()); $query->setDescription($group->getDescription()); $query->setType($group->getType()); $query->setPortraitFileId($group->getPortraitFileId()); $query->setCreated($group->getCreated()); if ($group->getId()) { $query->query(); return (int)$group->getId(); } else { return (int)$query->insert(); } } /** * @param $search * @return GroupModel[] * @throws \Core\Query\NoResultException */ public static function search($search) { $query = new Search(); $query->setSearch($search); return self::fillCollection(new GroupModel(), $query->fetchAll()); } /** * @param $userId * @return GroupModel[] * @throws \Core\Query\NoResultException */ public static function getInvitations($userId) { $query = new GetInvitations(); $query->setUserId($userId); return self::fillCollection(new GroupModel(), $query->fetchAll()); } }
dnl-jst/ownsocial
library/Service/Group.php
PHP
mit
1,829
class User < ApplicationRecord attr_accessor :remember_token, :activation_token, :reset_token before_save :downcase_email before_create :create_activation_digest VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(?:\.[a-z\d\-]+)*\.[a-z]+\z/i validates :email, presence: true, length: { maximum: 255 }, format: { with: VALID_EMAIL_REGEX }, uniqueness: { case_sensitive: false } has_secure_password validates :password, presence: true, length: { minimum: 8 }, allow_nil: true class << self # Returns the hash digest of a given string def digest(string) cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST : BCrypt::Engine.cost BCrypt::Password.create(string, cost: cost) end # Returns a random token def new_token SecureRandom.urlsafe_base64 end end # Remembers a user in the database for use in persistent sessions def remember self.remember_token = User.new_token update_attribute(:remember_digest, User.digest(remember_token)) end # Returns true if the given token matches the digest. def authenticated?(attribute, token) digest = send("#{attribute}_digest") return false if digest.nil? BCrypt::Password.new(digest).is_password?(token) end # Forgets a user def forget update_attribute(:remember_digest, nil) end # Activates an account def activate update_columns(activated: true, activated_at: Time.zone.now) end # Sends activation email def send_activation_email UserMailer.account_activation(self).deliver_now end # Sets the password reset attributes def create_reset_digest self.reset_token = User.new_token update_columns(reset_digest: User.digest(reset_token), reset_sent_at: Time.zone.now) end # Send password reset email def send_password_reset_email UserMailer.password_reset(self).deliver_now end # Returns true if a password reset has expired def password_reset_expired? reset_sent_at < 2.hours.ago end private # Converts email to all lower-case def downcase_email email.downcase! end # Creates and assigns the activation token and digest def create_activation_digest self.activation_token = User.new_token self.activation_digest = User.digest(activation_token) end end
professorNim/blorg
app/models/user.rb
Ruby
mit
2,289
'use strict'; module.exports = { colors: { black: '#000000', red: '#D54E53', green: '#B9CA4A', yellow: '#E7C547', blue: '#7AA6DA', magenta: '#C397D8', cyan: '#70C0B1', white: '#EAEAEA', lightBlack: '#969896', lightRed: '#D54E53', lightGreen: '#B9CA4A', lightYellow: '#E7C547', lightBlue: '#7AA6DA', lightMagenta: '#C397D8', lightCyan: '#70C0B1', lightWhite: '#EAEAEA', }, // Default backgroundColor: '#000000', foregroundColor: '#EAEAEA', cursorColor: '#EAEAEA', borderColor: '#171717', // Accent color accentColor: '#7AA6DA', // Other tabTitleColor: 'rgba(255, 255, 255, 0.2)', selectedTabTitleColor: '#EAEAEA', };
ooJerryLeeoo/hyper-material-box
scheme/tomorrow-night-bright.js
JavaScript
mit
708
package orestes.bloomfilter.redis.helper; import java.util.ArrayList; import java.util.List; import java.util.Map.Entry; import java.util.Random; import java.util.Set; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; import redis.clients.jedis.Pipeline; import redis.clients.jedis.Response; import redis.clients.jedis.exceptions.JedisConnectionException; import backport.java.util.function.Consumer; import backport.java.util.function.Function; /** * Encapsulates a Connection Pool and offers convenience methods for safe access through Java 8 Lambdas. */ public class RedisPool { private final JedisPool pool; private List<RedisPool> slavePools; private Random random; public RedisPool(JedisPool pool) { this.pool = pool; } public RedisPool(JedisPool pool, int redisConnections, Set<Entry<String, Integer>> readSlaves) { this(pool); if (readSlaves != null && !readSlaves.isEmpty()) { slavePools = new ArrayList<>(); random = new Random(); for (Entry<String, Integer> slave : readSlaves) { slavePools.add(new RedisPool(slave.getKey(), slave.getValue(), redisConnections)); } } } public RedisPool(String host, int port, int redisConnections) { this(createJedisPool(host, port, redisConnections)); } public RedisPool(String host, int port, int redisConnections, Set<Entry<String, Integer>> readSlaves) { this(createJedisPool(host, port, redisConnections), redisConnections, readSlaves); } private static JedisPool createJedisPool(String host, int port, int redisConnections) { JedisPoolConfig config = new JedisPoolConfig(); config.setBlockWhenExhausted(true); config.setMaxTotal(redisConnections); return new JedisPool(config, host, port); } public RedisPool allowingSlaves() { if(slavePools == null) return this; int index = random.nextInt(slavePools.size()); return slavePools.get(index); } public void safelyDo(final Consumer<Jedis> f) { safelyReturn(new Function<Jedis, Object>() { @Override public Object apply(Jedis jedis) { f.accept(jedis); return null; } }); } public <T> T safelyReturn(Function<Jedis, T> f) { T result; Jedis jedis = pool.getResource(); try { result = f.apply(jedis); return result; } catch (JedisConnectionException e) { if (jedis != null) { pool.returnBrokenResource(jedis); jedis = null; } throw e; } finally { if (jedis != null) pool.returnResource(jedis); } } @SuppressWarnings("unchecked") public <T> List<T> transactionallyDo(final Consumer<Pipeline> f, final String... watch) { return (List<T>) safelyReturn(new Function<Jedis, Object>() { @Override public Object apply(Jedis jedis) { Pipeline p = jedis.pipelined(); if (watch.length != 0) p.watch(watch); p.multi(); f.accept(p); Response<List<Object>> exec = p.exec(); p.sync(); return exec.get(); } }); } public <T> List<T> transactionallyRetry(Consumer<Pipeline> f, String... watch) { while(true) { List<T> result = transactionallyDo(f, watch); if(result != null) return result; } } public <T> T transactionallyDoAndReturn(final Function<Pipeline, T> f, final String... watch) { return safelyReturn(new Function<Jedis, T>() { @Override public T apply(Jedis jedis) { Pipeline p = jedis.pipelined(); if (watch.length != 0) p.watch(watch); p.multi(); T responses = f.apply(p); Response<List<Object>> exec = p.exec(); p.sync(); if(exec.get() == null) { return null; // failed } return responses; } }); } public <T> T transactionallyRetryAndReturn(Function<Pipeline, T> f, String... watch) { while(true) { T result = transactionallyDoAndReturn(f, watch); if(result != null) return result; } } public void destroy() { pool.destroy(); } }
Crystark/Orestes-Bloomfilter
src/main/java/orestes/bloomfilter/redis/helper/RedisPool.java
Java
mit
4,691
<?php defined('BASEPATH') OR exit('No direct script access allowed'); /* | ------------------------------------------------------------------- | DATABASE CONNECTIVITY SETTINGS | ------------------------------------------------------------------- | This file will contain the settings needed to access your database. | | For complete instructions please consult the 'Database Connection' | page of the User Guide. | | ------------------------------------------------------------------- | EXPLANATION OF VARIABLES | ------------------------------------------------------------------- | | ['dsn'] The full DSN string describe a connection to the database. | ['hostname'] The hostname of your database server. | ['username'] The username used to connect to the database | ['password'] The password used to connect to the database | ['database'] The name of the database you want to connect to | ['dbdriver'] The database driver. e.g.: mysqli. | Currently supported: | cubrid, ibase, mssql, mysql, mysqli, oci8, | odbc, pdo, postgre, sqlite, sqlite3, sqlsrv | ['dbprefix'] You can add an optional prefix, which will be added | to the table name when using the Query Builder class | ['pconnect'] TRUE/FALSE - Whether to use a persistent connection | ['db_debug'] TRUE/FALSE - Whether database errors should be displayed. | ['cache_on'] TRUE/FALSE - Enables/disables query caching | ['cachedir'] The path to the folder where cache files should be stored | ['char_set'] The character set used in communicating with the database | ['dbcollat'] The character collation used in communicating with the database | NOTE: For MySQL and MySQLi databases, this setting is only used | as a backup if your server is running PHP < 5.2.3 or MySQL < 5.0.7 | (and in table creation queries made with DB Forge). | There is an incompatibility in PHP with mysql_real_escape_string() which | can make your site vulnerable to SQL injection if you are using a | multi-byte character set and are running versions lower than these. | Sites using Latin-1 or UTF-8 database character set and collation are unaffected. | ['swap_pre'] A default table prefix that should be swapped with the dbprefix | ['encrypt'] Whether or not to use an encrypted connection. | | 'mysql' (deprecated), 'sqlsrv' and 'pdo/sqlsrv' drivers accept TRUE/FALSE | 'mysqli' and 'pdo/mysql' drivers accept an array with the following options: | | 'ssl_key' - Path to the private key file | 'ssl_cert' - Path to the public key certificate file | 'ssl_ca' - Path to the certificate authority file | 'ssl_capath' - Path to a directory containing trusted CA certificats in PEM format | 'ssl_cipher' - List of *allowed* ciphers to be used for the encryption, separated by colons (':') | 'ssl_verify' - TRUE/FALSE; Whether verify the server certificate or not ('mysqli' only) | | ['compress'] Whether or not to use client compression (MySQL only) | ['stricton'] TRUE/FALSE - forces 'Strict Mode' connections | - good for ensuring strict SQL while developing | ['ssl_options'] Used to set various SSL options that can be used when making SSL connections. | ['failover'] array - A array with 0 or more data for connections if the main should fail. | ['save_queries'] TRUE/FALSE - Whether to "save" all executed queries. | NOTE: Disabling this will also effectively disable both | $this->db->last_query() and profiling of DB queries. | When you run a query, with this setting set to TRUE (default), | CodeIgniter will store the SQL statement for debugging purposes. | However, this may cause high memory usage, especially if you run | a lot of SQL queries ... disable this to avoid that problem. | | The $active_group variable lets you choose which connection group to | make active. By default there is only one group (the 'default' group). | | The $query_builder variables lets you determine whether or not to load | the query builder class. */ $active_group = 'default'; $query_builder = TRUE; $db['default'] = array( 'dsn' => '', 'hostname' => 'localhost', 'username' => 'root', 'password' => 'root', 'database' => 'my_mvc_db', 'dbdriver' => 'mysqli', 'dbprefix' => '', 'pconnect' => FALSE, 'db_debug' => (ENVIRONMENT !== 'production'), 'cache_on' => FALSE, 'cachedir' => '', 'char_set' => 'utf8', 'dbcollat' => 'utf8_general_ci', 'swap_pre' => '', 'encrypt' => FALSE, 'compress' => FALSE, 'stricton' => FALSE, 'failover' => array(), 'save_queries' => TRUE );
ucantseeme/p2
application/config/database.php
PHP
mit
4,531
/** * @Author: Yingya Zhang <zyy> * @Date: 2016-07-08 11:29:00 * @Email: zyy7259@gmail.com * @Last modified by: zyy * @Last modified time: 2016-07-10 22:18:85 */ import { notexist, isEmpty } from 'type' import { calcHeight, remove, dataset } from 'dom' describe('dom', () => { it('calcHeight', () => { const height = 42 const p = document.createElement('p') p.id = 'calcHeight-' + (+new Date()) p.style.margin = 0 p.style.padding = 0 p.style.lineHeight = height + 'px' p.style.fontSize = '18px' const textNode = document.createTextNode('text') p.appendChild(textNode) const height1 = calcHeight(p) expect(height1).toBe(height) }) it('remove', () => { const domStr = '<div id="divRemove"></div>' document.body.innerHTML += domStr const div = document.getElementById('divRemove') expect(div.parentNode).toEqual(jasmine.anything()) remove(div) expect(notexist(div.parentNode)).toBe(true) }) it('dataset', () => { const domStr = '<div id="divDataset"></div>' document.body.innerHTML += domStr const div = document.getElementById('divDataset') const name = dataset(div, 'name') expect(isEmpty(name)).toBe(true) dataset(div, 'name', 'foo') expect(dataset(div, 'name')).toBe('foo') remove(div) }) // TODO html2node })
zoro-js/zoro-base
test/unit/specs/dom/index_spec.js
JavaScript
mit
1,346
using UnityEngine; using System.Collections; public class EnemyAI : MonoBehaviour { public Transform Target; public float TargetDist; public bool WillChase; public float WalkingSpeed; public Vector3 TopPatrolStart; public Vector3 TopPatrolEnd; public Vector2 SidePatrolStart; public Vector2 SidePatrolEnd; private bool startPatrol = false; // Use this for initialization void Start () { } // Update is called once per frame void Update () { if (GetComponent<Twistable>().State == Mode.TopDown) { if (WillChase && Vector3.Distance(transform.position, Target.transform.position) < TargetDist) { Vector3 direction = Target.transform.position - transform.position; direction.Normalize(); direction *= (WalkingSpeed * Time.deltaTime); transform.position += direction; } else { Vector3 targetPosition = transform.position; if (startPatrol) { targetPosition = TopPatrolEnd; } else { targetPosition = TopPatrolStart; } Vector3 direction = targetPosition - transform.position; if (direction.magnitude <= WalkingSpeed * Time.deltaTime) startPatrol = !startPatrol; direction.Normalize(); direction *= (WalkingSpeed * Time.deltaTime); transform.position += direction; } } else if (GetComponent<Twistable>().State == Mode.SideScroller) { Vector2 selfPos = transform.position; Vector2 targetPos = Target.transform.position; if (WillChase && Vector3.Distance(transform.position, Target.transform.position) < TargetDist) { Vector2 direction = targetPos - selfPos; direction.Normalize(); direction *= (WalkingSpeed * Time.deltaTime); transform.position += new Vector3(direction.x, direction.y, 0); } else { Vector2 targetPosition = transform.position; Vector2 selfPosition = transform.position; if (startPatrol) { targetPosition = SidePatrolEnd; } else { targetPosition = SidePatrolStart; } Vector2 direction = targetPosition - selfPosition; if (direction.magnitude <= WalkingSpeed*Time.deltaTime) startPatrol = !startPatrol; direction.Normalize(); direction *= (WalkingSpeed * Time.deltaTime); transform.position += new Vector3(direction.x, direction.y, 0); } } } public void OnPlayerAttack() { Target.gameObject.GetComponent<PlayerController>().attacked(); } }
NamefulTeam/PortoGameJam2016
PortoGameJam2016/Assets/Scripts/EnemyAI.cs
C#
mit
3,122
package service import ( "math" "math/rand" "time" "github.com/rlister/let-me-in/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws" "github.com/rlister/let-me-in/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/request" ) // DefaultRetryer implements basic retry logic using exponential backoff for // most services. If you want to implement custom retry logic, implement the // request.Retryer interface or create a structure type that composes this // struct and override the specific methods. For example, to override only // the MaxRetries method: // // type retryer struct { // service.DefaultRetryer // } // // // This implementation always has 100 max retries // func (d retryer) MaxRetries() uint { return 100 } type DefaultRetryer struct { *Service } // MaxRetries returns the number of maximum returns the service will use to make // an individual API request. func (d DefaultRetryer) MaxRetries() uint { if aws.IntValue(d.Service.Config.MaxRetries) < 0 { return d.DefaultMaxRetries } return uint(aws.IntValue(d.Service.Config.MaxRetries)) } var seededRand = rand.New(rand.NewSource(time.Now().UnixNano())) // RetryRules returns the delay duration before retrying this request again func (d DefaultRetryer) RetryRules(r *request.Request) time.Duration { delay := int(math.Pow(2, float64(r.RetryCount))) * (seededRand.Intn(30) + 30) return time.Duration(delay) * time.Millisecond } // ShouldRetry returns if the request should be retried. func (d DefaultRetryer) ShouldRetry(r *request.Request) bool { if r.HTTPResponse.StatusCode >= 500 { return true } return r.IsErrorRetryable() }
rlister/let-me-in
Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/service/default_retryer.go
GO
mit
1,638
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace FineBot.WepApi.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try get sample provided for a specific mediaType, controllerName, actionName and parameterNames. // If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames // If still not found, try get the sample provided for a specific type and mediaType if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create one using <see cref="ObjectGenerator"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // Try create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); sampleObject = objectGenerator.GenerateObject(type); } return sampleObject; } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ActionDescriptor.ReturnType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, e.Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
prinzo/Attack-Of-The-Fines-TA15
FineBot/FineBot.WepApi/Areas/HelpPage/SampleGeneration/HelpPageSampleGenerator.cs
C#
mit
17,175
<TS language="es_UY" version="2.1"> <context> <name>AddressBookPage</name> <message> <source>Right-click to edit address or label</source> <translation>Clic derecho para editar dirección o etiqueta</translation> </message> <message> <source>Create a new address</source> <translation>Crear una nueva dirección </translation> </message> <message> <source>&amp;New</source> <translation>Nuevo</translation> </message> <message> <source>Copy the currently selected address to the system clipboard</source> <translation>Copia la dirección seleccionada al portapapeles del sistema</translation> </message> <message> <source>&amp;Copy</source> <translation>Copiar</translation> </message> <message> <source>C&amp;lose</source> <translation>Cerrar</translation> </message> <message> <source>&amp;Export</source> <translation>Exportar</translation> </message> <message> <source>&amp;Delete</source> <translation>&amp;Borrar</translation> </message> </context> <context> <name>AddressTableModel</name> </context> <context> <name>AskPassphraseDialog</name> <message> <source>Enter passphrase</source> <translation>Escriba la contraseña</translation> </message> <message> <source>New passphrase</source> <translation>Nueva contraseña</translation> </message> <message> <source>Repeat new passphrase</source> <translation>Repetir nueva contraseña</translation> </message> </context> <context> <name>BanTableModel</name> </context> <context> <name>BitcoinGUI</name> <message> <source>Synchronizing with network...</source> <translation>Sincronizando con la red...</translation> </message> <message> <source>&amp;Overview</source> <translation>&amp;Vista previa</translation> </message> <message> <source>Show general overview of wallet</source> <translation>Mostrar descripción general del monedero</translation> </message> <message> <source>&amp;Transactions</source> <translation>&amp;transaciones </translation> </message> <message> <source>Browse transaction history</source> <translation>Buscar en el historial de transacciones</translation> </message> <message> <source>E&amp;xit</source> <translation>Salida</translation> </message> <message> <source>Quit application</source> <translation>Salir de la aplicacion </translation> </message> <message> <source>Show information about Qt</source> <translation>Mostrar informacioón sobre</translation> </message> <message> <source>&amp;Options...</source> <translation>&amp;Opciones...</translation> </message> <message> <source>&amp;Backup Wallet...</source> <translation>Respaldar Billetera</translation> </message> <message> <source>&amp;Change Passphrase...</source> <translation>Cambiar contraseña</translation> </message> <message> <source>&amp;Sending addresses...</source> <translation>Enviando direcciones</translation> </message> <message> <source>&amp;Receiving addresses...</source> <translation>Recibiendo direcciones</translation> </message> <message> <source>Send coins to a Chancoin address</source> <translation>Enviar monedas a una dirección Chancoin</translation> </message> <message> <source>Change the passphrase used for wallet encryption</source> <translation>Cambie la clave utilizada para el cifrado del monedero</translation> </message> <message> <source>Chancoin</source> <translation>Chancoin</translation> </message> <message> <source>Wallet</source> <translation>Billetera</translation> </message> <message> <source>&amp;Show / Hide</source> <translation>Mostrar / Ocultar</translation> </message> <message> <source>&amp;File</source> <translation>&amp;Archivo</translation> </message> <message> <source>&amp;Settings</source> <translation>&amp;Configuracion </translation> </message> <message> <source>&amp;Help</source> <translation>&amp;Ayuda</translation> </message> <message> <source>Tabs toolbar</source> <translation>Barra de herramientas</translation> </message> <message> <source>Error</source> <translation>Error</translation> </message> <message> <source>Warning</source> <translation>Alerta</translation> </message> <message> <source>Information</source> <translation>Información</translation> </message> <message> <source>Up to date</source> <translation>A la fecha</translation> </message> <message> <source>Catching up...</source> <translation>Ponerse al dia...</translation> </message> <message> <source>Type: %1 </source> <translation>Tipo: %1 </translation> </message> <message> <source>Address: %1 </source> <translation>Dirección: %1</translation> </message> <message> <source>Sent transaction</source> <translation>Transaccion enviada</translation> </message> <message> <source>Incoming transaction</source> <translation>Transacción entrante</translation> </message> <message> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>El Monedero esta &lt;b&gt;cifrado&lt;/b&gt; y actualmente &lt;b&gt;desbloqueado&lt;/b&gt;</translation> </message> <message> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>El Monedero esta &lt;b&gt;cifrado&lt;/b&gt; y actualmente &lt;b&gt;bloqueado&lt;/b&gt;</translation> </message> </context> <context> <name>CoinControlDialog</name> <message> <source>Quantity:</source> <translation>Cantidad:</translation> </message> <message> <source>Bytes:</source> <translation>Bytes:</translation> </message> <message> <source>Amount:</source> <translation>AMonto:</translation> </message> <message> <source>Change:</source> <translation>Cambio:</translation> </message> <message> <source>Date</source> <translation>Fecha</translation> </message> <message> <source>Confirmed</source> <translation>Confirmado</translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <source>Edit Address</source> <translation>Editar dirección</translation> </message> <message> <source>&amp;Label</source> <translation>&amp;Etiqueta</translation> </message> <message> <source>&amp;Address</source> <translation>&amp;Direccion </translation> </message> </context> <context> <name>FreespaceChecker</name> </context> <context> <name>HelpMessageDialog</name> </context> <context> <name>Intro</name> <message> <source>Error</source> <translation>Error</translation> </message> </context> <context> <name>ModalOverlay</name> <message> <source>Form</source> <translation>Formulario</translation> </message> </context> <context> <name>OpenURIDialog</name> </context> <context> <name>OptionsDialog</name> <message> <source>Options</source> <translation>Opciones</translation> </message> <message> <source>W&amp;allet</source> <translation>Billetera</translation> </message> </context> <context> <name>OverviewPage</name> <message> <source>Form</source> <translation>Formulario</translation> </message> </context> <context> <name>PaymentServer</name> </context> <context> <name>PeerTableModel</name> </context> <context> <name>QObject</name> </context> <context> <name>QObject::QObject</name> </context> <context> <name>QRImageWidget</name> </context> <context> <name>RPCConsole</name> <message> <source>&amp;Information</source> <translation>Información</translation> </message> </context> <context> <name>ReceiveCoinsDialog</name> <message> <source>&amp;Label:</source> <translation>&amp;Etiqueta:</translation> </message> </context> <context> <name>ReceiveRequestDialog</name> <message> <source>Copy &amp;Address</source> <translation>Copiar Dirección</translation> </message> </context> <context> <name>RecentRequestsTableModel</name> </context> <context> <name>SendCoinsDialog</name> <message> <source>Send Coins</source> <translation>Enviar monedas</translation> </message> <message> <source>Quantity:</source> <translation>Cantidad:</translation> </message> <message> <source>Bytes:</source> <translation>Bytes:</translation> </message> <message> <source>Amount:</source> <translation>AMonto:</translation> </message> <message> <source>Change:</source> <translation>Cambio:</translation> </message> <message> <source>Send to multiple recipients at once</source> <translation>Enviar a varios destinatarios a la vez</translation> </message> <message> <source>Balance:</source> <translation>Balance:</translation> </message> <message> <source>Confirm the send action</source> <translation>Confirmar el envío</translation> </message> </context> <context> <name>SendCoinsEntry</name> <message> <source>A&amp;mount:</source> <translation>A&amp;Monto:</translation> </message> <message> <source>Pay &amp;To:</source> <translation>Pagar &amp;A:</translation> </message> <message> <source>&amp;Label:</source> <translation>&amp;Etiqueta:</translation> </message> <message> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <source>Paste address from clipboard</source> <translation>Pegar la dirección desde el portapapeles</translation> </message> <message> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <source>Pay To:</source> <translation>Pagar A:</translation> </message> </context> <context> <name>SendConfirmationDialog</name> </context> <context> <name>ShutdownWindow</name> </context> <context> <name>SignVerifyMessageDialog</name> <message> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <source>Paste address from clipboard</source> <translation>Pegar la dirección desde el portapapeles</translation> </message> <message> <source>Alt+P</source> <translation>Alt+P</translation> </message> </context> <context> <name>SplashScreen</name> <message> <source>[testnet]</source> <translation>[prueba_de_red]</translation> </message> </context> <context> <name>TrafficGraphWidget</name> </context> <context> <name>TransactionDesc</name> </context> <context> <name>TransactionDescDialog</name> </context> <context> <name>TransactionTableModel</name> </context> <context> <name>TransactionView</name> </context> <context> <name>UnitDisplayStatusBarControl</name> </context> <context> <name>WalletFrame</name> </context> <context> <name>WalletModel</name> </context> <context> <name>WalletView</name> </context> <context> <name>bitcoin-core</name> <message> <source>Options:</source> <translation>Opciones:</translation> </message> <message> <source>Information</source> <translation>Información</translation> </message> <message> <source>Warning</source> <translation>Alerta</translation> </message> <message> <source>Error</source> <translation>Error</translation> </message> </context> </TS>
Chancoin-core/CHANCOIN
src/qt/locale/bitcoin_es_UY.ts
TypeScript
mit
12,752
/* http://fiidmi.fi/documentation/customer_order_history */ module.exports = { "bonus": { "type": "object", "properties": { "session_id": { "type": "string", "minLength": 2, "maxLength": 50 }, "restaurant_id": { "type": "string", "minLength": 1, "maxLength": 50 } }, "required": ["session_id", "restaurant_id"] }, "po_credit": { "type": "object", "properties": { "session_id": { "type": "string", "minLength": 2, "maxLength": 50 } }, "required": ["session_id", "order_id"] } };
tidhr/node-fiidmi
lib/api/3.3/customer/information.js
JavaScript
mit
526
export function Fragment(props, ...children) { return collect(children); } const ATTR_PROPS = '_props'; function collect(children) { const ch = []; const push = (c) => { if (c !== null && c !== undefined && c !== '' && c !== false) { ch.push((typeof c === 'function' || typeof c === 'object') ? c : `${c}`); } }; children && children.forEach(c => { if (Array.isArray(c)) { c.forEach(i => push(i)); } else { push(c); } }); return ch; } export function createElement(tag, props, ...children) { const ch = collect(children); if (typeof tag === 'string') return { tag, props, children: ch }; else if (Array.isArray(tag)) return tag; // JSX fragments - babel else if (tag === undefined && children) return ch; // JSX fragments - typescript else if (Object.getPrototypeOf(tag).__isAppRunComponent) return { tag, props, children: ch }; // createComponent(tag, { ...props, children }); else if (typeof tag === 'function') return tag(props, ch); else throw new Error(`Unknown tag in vdom ${tag}`); } ; const keyCache = new WeakMap(); export const updateElement = render; export function render(element, nodes, parent = {}) { // console.log('render', element, node); // tslint:disable-next-line if (nodes == null || nodes === false) return; nodes = createComponent(nodes, parent); const isSvg = (element === null || element === void 0 ? void 0 : element.nodeName) === "SVG"; if (!element) return; if (Array.isArray(nodes)) { updateChildren(element, nodes, isSvg); } else { updateChildren(element, [nodes], isSvg); } } function same(el, node) { // if (!el || !node) return false; const key1 = el.nodeName; const key2 = `${node.tag || ''}`; return key1.toUpperCase() === key2.toUpperCase(); } function update(element, node, isSvg) { if (node['_op'] === 3) return; // console.assert(!!element); isSvg = isSvg || node.tag === "svg"; if (!same(element, node)) { element.parentNode.replaceChild(create(node, isSvg), element); return; } !(node['_op'] & 2) && updateChildren(element, node.children, isSvg); !(node['_op'] & 1) && updateProps(element, node.props, isSvg); } function updateChildren(element, children, isSvg) { var _a; const old_len = ((_a = element.childNodes) === null || _a === void 0 ? void 0 : _a.length) || 0; const new_len = (children === null || children === void 0 ? void 0 : children.length) || 0; const len = Math.min(old_len, new_len); for (let i = 0; i < len; i++) { const child = children[i]; if (child['_op'] === 3) continue; const el = element.childNodes[i]; if (typeof child === 'string') { if (el.textContent !== child) { if (el.nodeType === 3) { el.nodeValue = child; } else { element.replaceChild(createText(child), el); } } } else if (child instanceof HTMLElement || child instanceof SVGElement) { element.insertBefore(child, el); } else { const key = child.props && child.props['key']; if (key) { if (el.key === key) { update(element.childNodes[i], child, isSvg); } else { // console.log(el.key, key); const old = keyCache[key]; if (old) { const temp = old.nextSibling; element.insertBefore(old, el); temp ? element.insertBefore(el, temp) : element.appendChild(el); update(element.childNodes[i], child, isSvg); } else { element.replaceChild(create(child, isSvg), el); } } } else { update(element.childNodes[i], child, isSvg); } } } let n = element.childNodes.length; while (n > len) { element.removeChild(element.lastChild); n--; } if (new_len > len) { const d = document.createDocumentFragment(); for (let i = len; i < children.length; i++) { d.appendChild(create(children[i], isSvg)); } element.appendChild(d); } } function createText(node) { if ((node === null || node === void 0 ? void 0 : node.indexOf('_html:')) === 0) { // ? const div = document.createElement('div'); div.insertAdjacentHTML('afterbegin', node.substring(6)); return div; } else { return document.createTextNode(node !== null && node !== void 0 ? node : ''); } } function create(node, isSvg) { // console.assert(node !== null && node !== undefined); if ((node instanceof HTMLElement) || (node instanceof SVGElement)) return node; if (typeof node === "string") return createText(node); if (!node.tag || (typeof node.tag === 'function')) return createText(JSON.stringify(node)); isSvg = isSvg || node.tag === "svg"; const element = isSvg ? document.createElementNS("http://www.w3.org/2000/svg", node.tag) : document.createElement(node.tag); updateProps(element, node.props, isSvg); if (node.children) node.children.forEach(child => element.appendChild(create(child, isSvg))); return element; } function mergeProps(oldProps, newProps) { newProps['class'] = newProps['class'] || newProps['className']; delete newProps['className']; const props = {}; if (oldProps) Object.keys(oldProps).forEach(p => props[p] = null); if (newProps) Object.keys(newProps).forEach(p => props[p] = newProps[p]); return props; } export function updateProps(element, props, isSvg) { // console.assert(!!element); const cached = element[ATTR_PROPS] || {}; props = mergeProps(cached, props || {}); element[ATTR_PROPS] = props; for (const name in props) { const value = props[name]; // if (cached[name] === value) continue; // console.log('updateProps', name, value); if (name.startsWith('data-')) { const dname = name.substring(5); const cname = dname.replace(/-(\w)/g, (match) => match[1].toUpperCase()); if (element.dataset[cname] !== value) { if (value || value === "") element.dataset[cname] = value; else delete element.dataset[cname]; } } else if (name === 'style') { if (element.style.cssText) element.style.cssText = ''; if (typeof value === 'string') element.style.cssText = value; else { for (const s in value) { if (element.style[s] !== value[s]) element.style[s] = value[s]; } } } else if (name.startsWith('xlink')) { const xname = name.replace('xlink', '').toLowerCase(); if (value == null || value === false) { element.removeAttributeNS('http://www.w3.org/1999/xlink', xname); } else { element.setAttributeNS('http://www.w3.org/1999/xlink', xname, value); } } else if (name.startsWith('on')) { if (!value || typeof value === 'function') { element[name] = value; } else if (typeof value === 'string') { if (value) element.setAttribute(name, value); else element.removeAttribute(name); } } else if (/^id$|^class$|^list$|^readonly$|^contenteditable$|^role|-/g.test(name) || isSvg) { if (element.getAttribute(name) !== value) { if (value) element.setAttribute(name, value); else element.removeAttribute(name); } } else if (element[name] !== value) { element[name] = value; } if (name === 'key' && value) keyCache[value] = element; } if (props && typeof props['ref'] === 'function') { window.requestAnimationFrame(() => props['ref'](element)); } } function render_component(node, parent, idx) { const { tag, props, children } = node; let key = `_${idx}`; let id = props && props['id']; if (!id) id = `_${idx}${Date.now()}`; else key = id; let asTag = 'section'; if (props && props['as']) { asTag = props['as']; delete props['as']; } if (!parent.__componentCache) parent.__componentCache = {}; let component = parent.__componentCache[key]; if (!component || !(component instanceof tag) || !component.element) { const element = document.createElement(asTag); component = parent.__componentCache[key] = new tag(Object.assign(Object.assign({}, props), { children })).start(element); } if (component.mounted) { const new_state = component.mounted(props, children, component.state); (typeof new_state !== 'undefined') && component.setState(new_state); } updateProps(component.element, props, false); return component.element; } function createComponent(node, parent, idx = 0) { var _a; if (typeof node === 'string') return node; if (Array.isArray(node)) return node.map(child => createComponent(child, parent, idx++)); let vdom = node; if (node && typeof node.tag === 'function' && Object.getPrototypeOf(node.tag).__isAppRunComponent) { vdom = render_component(node, parent, idx); } if (vdom && Array.isArray(vdom.children)) { const new_parent = (_a = vdom.props) === null || _a === void 0 ? void 0 : _a._component; if (new_parent) { let i = 0; vdom.children = vdom.children.map(child => createComponent(child, new_parent, i++)); } else { vdom.children = vdom.children.map(child => createComponent(child, parent, idx++)); } } return vdom; } //# sourceMappingURL=vdom-my.js.map
yysun/apprun
esm/vdom-my.js
JavaScript
mit
10,531
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' destination.factory ''' from destination.zeus import ZeusDestination from destination.aws import AwsDestination from exceptions import AutocertError from config import CFG from app import app class DestinationFactoryError(AutocertError): def __init__(self, destination): msg = f'destination factory error with {destination}' super(DestinationFactoryError, self).__init__(msg) def create_destination(destination, ar, cfg, timeout, verbosity): d = None if destination == 'aws': d = AwsDestination(ar, cfg, verbosity) elif destination == 'zeus': d = ZeusDestination(ar, cfg, verbosity) else: raise DestinationFactoryError(destination) dests = list(CFG.destinations.zeus.keys()) if d.has_connectivity(timeout, dests): return d
mozilla-it/autocert
autocert/api/destination/factory.py
Python
mit
854
<?php /** * LitePubl CMS * * @copyright 2010 - 2017 Vladimir Yushko http://litepublisher.com/ http://litepublisher.ru/ * @license https://github.com/litepubl/cms/blob/master/LICENSE.txt MIT * @link https://github.com/litepubl\cms * @version 7.08 */ namespace litepubl\comments; use litepubl\view\Lang; use litepubl\view\Theme; class Json extends \litepubl\core\Events { public function auth($id, $action) { if (!$this->getApp()->options->user) { return false; } $comments = Comments::i(); if (!$comments->itemExists($id)) { return false; } if ($this->getApp()->options->ingroup('moderator')) { return true; } $cm = Manager::i(); switch ($action) { case 'edit': if (!$cm->canedit) { return false; } if ('closed' == $this->getApp()->db->getval('posts', $comments->getvalue($id, 'post'), 'comstatus')) { return false; } return $comments->getvalue($id, 'author') == $this->getApp()->options->user; case 'delete': if (!$cm->candelete) { return false; } if ('closed' == $this->getApp()->db->getval('posts', $comments->getvalue($id, 'post'), 'comstatus')) { return false; } return $comments->getvalue($id, 'author') == $this->getApp()->options->user; } return false; } public function forbidden() { $this->error('Forbidden', 403); } public function comment_delete(array $args) { $id = (int)$args['id']; if (!$this->auth($id, 'delete')) { return $this->forbidden(); } return Comments::i()->delete($id); } public function comment_setstatus($args) { $id = (int)$args['id']; if (!$this->auth($id, 'status')) { return $this->forbidden(); } return Comments::i()->setstatus($id, $args['status']); } public function comment_edit(array $args) { $id = (int)$args['id']; if (!$this->auth($id, 'edit')) { return $this->forbidden(); } $content = trim($args['content']); if (empty($content)) { return false; } $comments = Comments::i(); if ($comments->edit($id, $content)) { return [ 'id' => $id, 'content' => $comments->getvalue($id, 'content') ]; } else { return false; } } public function comment_getraw(array $args) { $id = (int)$args['id']; if (!$this->auth($id, 'edit')) { return $this->forbidden(); } $comments = Comments::i(); $raw = $comments->raw->getvalue($id, 'rawcontent'); return [ 'id' => $id, 'rawcontent' => $raw ]; } public function comments_get_hold(array $args) { if (!$this->getApp()->options->user) { return $this->forbidden(); } $idpost = (int)$args['idpost']; $comments = Comments::i($idpost); if ($this->getApp()->options->ingroup('moderator')) { $where = ''; } else { $where = "and $comments->thistable.author = " . $this->getApp()->options->user; } return [ 'items' => $comments->getcontentwhere('hold', $where) ]; } public function comment_add(array $args) { if ($this->getApp()->options->commentsdisabled) { return [ 'error' => [ 'message' => 'Comments disabled', 'code' => 403 ] ]; } $commentform = Form::i(); $commentform->helper = $this; return $commentform->dorequest($args); } public function comment_confirm(array $args) { return $this->comment_add($args); } //commentform helper public function confirm($confirmid) { return [ 'confirmid' => $confirmid, 'code' => 'confirm', ]; } public function getErrorcontent($s) { return [ 'error' => [ 'message' => $s, 'code' => 'error' ] ]; } public function sendresult($url, $cookies) { return [ 'cookies' => $cookies, 'posturl' => $url, 'code' => 'success' ]; } public function comments_get_logged(array $args) { if (!$this->getApp()->options->user) { return $this->forbidden(); } $theme = Theme::context(); $mesg = $theme->templates['content.post.templatecomments.form.mesg.logged']; $mesg = str_replace('$site.liveuser', $this->getApp()->site->getuserlink(), $mesg); $lang = Lang::i('comment'); return $theme->parse($mesg); } }
litepubl/cms
lib/comments/Json.php
PHP
mit
5,142
var ItineraryWalkStep = require('./itinerary-walk-step') var Backbone = window.Backbone var ItineraryWalkSteps = Backbone.Collection.extend({ model: ItineraryWalkStep }) module.exports = ItineraryWalkSteps
ed-g/otp.js
lib/itinerary-walk-steps.js
JavaScript
mit
211
# frozen_string_literal: true require 'spec_helper' require 'json' describe QueueBus::Worker do it 'proxies to given class' do hash = { 'bus_class_proxy' => 'QueueBus::Driver', 'ok' => true } expect(QueueBus::Driver).to receive(:perform).with(hash) QueueBus::Worker.perform(JSON.generate(hash)) end it 'uses an instance' do hash = { 'bus_class_proxy' => 'QueueBus::Rider', 'ok' => true } expect(QueueBus::Rider).to receive(:perform).with(hash) QueueBus::Worker.new.perform(JSON.generate(hash)) end it 'does not freak out if class not there anymore' do hash = { 'bus_class_proxy' => 'QueueBus::BadClass', 'ok' => true } expect do QueueBus::Worker.perform(JSON.generate(hash)) end.not_to raise_error end it 'raises error if proxy raises error' do hash = { 'bus_class_proxy' => 'QueueBus::Rider', 'ok' => true } expect(QueueBus::Rider).to receive(:perform).with(hash).and_raise('rider crash') expect do QueueBus::Worker.perform(JSON.generate(hash)) end.to raise_error(RuntimeError, 'rider crash') end it 'runs the middleware stack' do hash = { 'bus_class_proxy' => 'QueueBus::Driver', 'ok' => true } expect(QueueBus.worker_middleware_stack).to receive(:run).with(hash).and_yield QueueBus::Worker.perform(JSON.generate(hash)) end end
queue-bus/queue-bus
spec/worker_spec.rb
Ruby
mit
1,332
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CommaExcess.Algae.Graphics { /// <summary> /// Defines a compiled material pass. /// </summary> interface ICompiledMaterialPass { /// <summary> /// Begins rendering the material pass. /// </summary> void Begin(); /// <summary> /// Applies any changes. /// </summary> void Apply(); /// <summary> /// Sets a parameter. /// </summary> /// <param name="parameter">The parameter.</param> /// <param name="value">The value.</param> void SetValue(string parameter, float value); /// <summary> /// Sets a parameter. /// </summary> /// <param name="parameter">The parameter.</param> /// <param name="value">The value.</param> void SetValue(string parameter, int value); /// <summary> /// Sets a parameter. /// </summary> /// <param name="parameter">The parameter.</param> /// <param name="value">The value.</param> void SetValue(string parameter, Vector2 value); /// <summary> /// Sets a parameter. /// </summary> /// <param name="parameter">The parameter.</param> /// <param name="value">The value.</param> void SetValue(string parameter, Vector3 value); /// <summary> /// Sets a parameter. /// </summary> /// <param name="parameter">The parameter.</param> /// <param name="value">The value.</param> void SetValue(string parameter, Vector4 value); /// <summary> /// Sets a parameter. /// </summary> /// <param name="parameter">The parameter.</param> /// <param name="value">The value.</param> void SetValue(string parameter, Matrix value); /// <summary> /// Seta a parameter. /// </summary> /// <param name="parameter">The parameter.</param> /// <param name="texture">The value.</param> void SetValue(string parameter, Texture texture); /// <summary> /// Ends the material pass. /// </summary> void End(); } /// <summary> /// Defines a compiled material. /// </summary> interface ICompiledMaterial : IEnumerable<ICompiledMaterialPass>, IDisposable { /// <summary> /// Gets the pass at the provided index. /// </summary> /// <param name="index">The index.</param> /// <returns>The pass.</returns> ICompiledMaterialPass this[int index] { get; } /// <summary> /// Gets the total amount of passes. /// </summary> int Count { get; } /// <summary> /// Uses the material. Call this before drawing a pass. /// </summary> void Use(); } }
aaronbolyard/Algae.Canvas
Source/Algae/Graphics/ICompiledMaterial.cs
C#
mit
2,495
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from .entity_health import EntityHealth class PartitionHealth(EntityHealth): """Information about the health of a Service Fabric partition. :param aggregated_health_state: Possible values include: 'Invalid', 'Ok', 'Warning', 'Error', 'Unknown' :type aggregated_health_state: str or :class:`enum <azure.servicefabric.models.enum>` :param health_events: The list of health events reported on the entity. :type health_events: list of :class:`HealthEvent <azure.servicefabric.models.HealthEvent>` :param unhealthy_evaluations: :type unhealthy_evaluations: list of :class:`HealthEvaluationWrapper <azure.servicefabric.models.HealthEvaluationWrapper>` :param health_statistics: :type health_statistics: :class:`HealthStatistics <azure.servicefabric.models.HealthStatistics>` :param partition_id: :type partition_id: str :param replica_health_states: The list of replica health states associated with the partition. :type replica_health_states: list of :class:`ReplicaHealthState <azure.servicefabric.models.ReplicaHealthState>` """ _attribute_map = { 'aggregated_health_state': {'key': 'AggregatedHealthState', 'type': 'str'}, 'health_events': {'key': 'HealthEvents', 'type': '[HealthEvent]'}, 'unhealthy_evaluations': {'key': 'UnhealthyEvaluations', 'type': '[HealthEvaluationWrapper]'}, 'health_statistics': {'key': 'HealthStatistics', 'type': 'HealthStatistics'}, 'partition_id': {'key': 'PartitionId', 'type': 'str'}, 'replica_health_states': {'key': 'ReplicaHealthStates', 'type': '[ReplicaHealthState]'}, } def __init__(self, aggregated_health_state=None, health_events=None, unhealthy_evaluations=None, health_statistics=None, partition_id=None, replica_health_states=None): super(PartitionHealth, self).__init__(aggregated_health_state=aggregated_health_state, health_events=health_events, unhealthy_evaluations=unhealthy_evaluations, health_statistics=health_statistics) self.partition_id = partition_id self.replica_health_states = replica_health_states
AutorestCI/azure-sdk-for-python
azure-servicefabric/azure/servicefabric/models/partition_health.py
Python
mit
2,612
#region License /* The MIT License * * Copyright (c) 2011 Red Badger Consulting * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #endregion namespace RedBadger.Xpf.Graphics { public interface IRenderer { void ClearInvalidDrawingContexts(); void Draw(); IDrawingContext GetDrawingContext(IElement element); void PreDraw(); } }
redbadger/XPF
XPF/RedBadger.Xpf/Graphics/IRenderer.cs
C#
mit
1,445
/* * Copyright (c) 2015 by Greg Reimer <gregreimer@gmail.com> * MIT License. See license.txt for more info. */ var stream = require('stream') , util = require('util') , co = require('co') , unresolved = require('./unresolved') // ----------------------------------------------------- function Readable(opts, sender) { stream.Readable.call(this, opts); this._ponySending = unresolved(); var self = this; function output(data, enc) { return self._ponySending.then(function() { if (!self.push(data, enc)) { self._ponySending = unresolved(); } }); } co(sender.bind(this, output)) .then(function() { self.push(null); }) .catch(function(err) { self.emit('error', err); }); } util.inherits(Readable, stream.Readable); Readable.prototype._read = function() { this._ponySending.resolve(); }; // ----------------------------------------------------- module.exports = Readable;
greim/eventual-pony
lib/readable.js
JavaScript
mit
929
<?php namespace JanVince\SmallContactForm\Models; use Str; use Model; use URL; use October\Rain\Router\Helper as RouterHelper; use Cms\Classes\Page as CmsPage; use Cms\Classes\Theme; use JanVince\SmallContactForm\Models\Settings; use Log; use Validator; use Mail; use Request; use Carbon\Carbon; use View; use App; use System\Models\MailTemplate; use System\Classes\MailManager; use Twig; use Input; use System\Models\File; class Message extends Model { use \October\Rain\Database\Traits\Validation; public $table = 'janvince_smallcontactform_messages'; public $implement = ['@RainLab.Translate.Behaviors.TranslatableModel']; public $timestamps = true; public $rules = []; public $translatable = []; protected $guarded = []; protected $jsonable = ['form_data']; public $attachMany = [ 'uploads' => 'System\Models\File', ]; /** * Scope new messages only */ public function scopeIsNew($query) { return $query->where('new_message', '=', 1); } /** * Scope read messages only */ public function scopeIsRead($query) { return $query->where('new_message', '=', 0); } public function storeFormData($data, $formAlias, $formDescription, $formNotes){ if(Settings::getTranslated('privacy_disable_messages_saving')) { return; } $output = []; $name_field_value = NULL; $email_field_value = NULL; $message_field_value = NULL; $formFields = Settings::getTranslated('form_fields'); $uploads = []; foreach($data as $key => $value) { // skip helpers if(substr($key, 0, 1) == '_'){ continue; } // skip reCaptcha if($key == 'g-recaptcha-response'){ continue; } // skip non-defined fields // store uploaded file -- currently only one file is supported $fieldDefined = null; $fieldUpload = null; foreach( $formFields as $field) { if( $field['name'] == $key) { $fieldDefined = true; if($field['type'] == 'file') { $fieldUpload = true; if(!empty(Input::file($key))) { $file = new File; $file->data = (Input::file($key)); $file->is_public = true; $file->save(); $uploads[] = $file; } } } } // skip uploads if($fieldUpload){ continue; } if( !$fieldDefined ) { Log::warning('SMALL CONTACT FORM WARNING: Found a non-defined field in sent data! Field name: ' . e($key) . ' and value: ' . e($value['value']) ); continue; } $output[$key] = e($value['value']); // if email field is assigned in autoreply, save it separatelly if(empty($email_field_value) and $key == Settings::getTranslated('autoreply_email_field')){ $email_field_value = e($value['value']); } // if name field is assigned in autoreply, save it separatelly if(empty($name_field_value) and $key == Settings::getTranslated('autoreply_name_field')){ $name_field_value = e($value['value']); } // if message is assigned in autoreply, save it separatelly if(empty($message_field_value) and $key == Settings::getTranslated('autoreply_message_field')){ $message_field_value = e($value['value']); } } $this->form_data = $output; $this->name = $name_field_value; $this->email = $email_field_value; $this->message = $message_field_value; $this->remote_ip = Request::ip(); $this->form_alias = $formAlias; $this->form_description = $formDescription; $this->url = url()->full(); $this->form_notes = $formNotes; $this->save(); // Add files if($uploads) { foreach($uploads as $upload) { $this->uploads()->add($upload); } } return $this; } /** * Build and send autoreply message */ public function sendAutoreplyEmail($postData, $componentProperties = [], $formAlias, $formDescription, $messageObject, $formNotes){ if(!Settings::getTranslated('allow_autoreply')) { return; } if (!empty($componentProperties['disable_autoreply'])) { return; } if(!Settings::getTranslated('autoreply_email_field')) { Log::error('SMALL CONTACT FORM ERROR: Contact form data have no email to send autoreply message!'); return; } /** * Extract and test email field value */ $sendTo = ''; foreach($postData as $key => $field) { if($key == Settings::getTranslated('autoreply_email_field')){ $sendTo = $field['value']; } } $validator = Validator::make(['email' => $sendTo], ['email' => 'required|email']); if($validator->fails()){ Log::error('SMALL CONTACT FORM ERROR: Email to send autoreply is not valid!' . PHP_EOL . ' Data: '. json_encode($postData) ); return; } if( Settings::getTranslated('allow_email_queue') ){ $method = 'queue'; } else { $method = 'send'; } $output = []; $outputFull = []; $formFields = Settings::getTranslated('form_fields'); foreach($formFields as $field) { if(!empty($field['type'] and $field['type'] == 'file')) { continue; } $fieldValue = null; if( !empty( $postData[ $field['name'] ]['value'] ) ) { $fieldValue = e( html_entity_decode( $postData[ $field['name'] ]['value'] ) ); } else { $fieldValue = null; } if( !empty( $field['name'] ) ) { $outputFull[ $field['name'] ] = array_merge( $field, [ 'value' => $fieldValue ] ); } $output[ $field['name'] ] = $fieldValue; } $output['form_description'] = $formDescription; $output['form_alias'] = $formAlias; $template = Settings::getTranslatedTemplates('en', App::getLocale(), 'autoreply'); if( Settings::getTranslated('email_template') ){ if(View::exists(Settings::getTranslated('email_template')) OR !empty( MailTemplate::listAllTemplates()[Settings::getTranslated('email_template')] ) ) { $template = Settings::getTranslated('email_template'); } else { Log::error('SMALL CONTACT FORM: Missing defined email template: ' . Settings::getTranslated('email_template') . '. Default template will be used!'); } } /** * Override email template by component property * Language specific template has priority (override non language specific) */ if ( !empty($componentProperties['autoreply_template']) and !empty( MailTemplate::listAllTemplates()[ $componentProperties['autoreply_template'] ] ) ) { $template = $componentProperties['autoreply_template']; } elseif ( !empty($componentProperties['autoreply_template']) and empty( MailTemplate::listAllTemplates()[ $componentProperties['autoreply_template'] ] ) ) { Log::error('SMALL CONTACT FORM: Missing defined email template: ' . $componentProperties['autoreply_template'] . '. ' . $template . ' template will be used!'); } if ( !empty($componentProperties[ ('autoreply_template_'.App::getLocale())]) and !empty( MailTemplate::listAllTemplates()[ $componentProperties[ ('autoreply_template_'.App::getLocale())] ] ) ) { $template = $componentProperties[('autoreply_template_'.App::getLocale())]; } elseif ( !empty($componentProperties[ ('autoreply_template_'.App::getLocale())]) and empty( MailTemplate::listAllTemplates()[ $componentProperties[ ('autoreply_template_'.App::getLocale())] ] ) ) { Log::error('SMALL CONTACT FORM: Missing defined email template: ' . $componentProperties[ ('autoreply_template_'.App::getLocale())] . '. ' . $template . ' template will be used!'); } if(!empty($messageObject->uploads)) { $uploads = $messageObject->uploads; } else { $uploads = []; } Mail::{$method}($template, ['messageObject' => $messageObject, 'uploads' => $uploads, 'fields' => $output, 'fieldsDetails' => $outputFull, 'url' => url()->full(), 'form_notes' => $formNotes], function($message) use($sendTo, $componentProperties, $output){ $message->to($sendTo); if (!empty($componentProperties['autoreply_subject'])) { $message->subject(Twig::parse($componentProperties['autoreply_subject'],['fields' => $output])); \App::forgetInstance('parse.twig'); \App::forgetInstance('twig.environment'); } elseif (Settings::getTranslated('email_subject')) { $message->subject(Twig::parse(Settings::getTranslated('email_subject'), ['fields' => $output])); \App::forgetInstance('parse.twig'); \App::forgetInstance('twig.environment'); } /** * From address * Component's property can override this */ $fromAddress = null; $fromAddressName = null; if( Settings::getTranslated('email_address_from') ) { $fromAddress = Settings::getTranslated('email_address_from'); $fromAddressName = Settings::getTranslated('email_address_from_name'); } if( !empty($componentProperties['autoreply_address_from']) ) { $fromAddress = $componentProperties['autoreply_address_from']; } if( !empty($componentProperties['autoreply_address_from_name']) ) { $fromAddressName = $componentProperties['autoreply_address_from_name']; } if( !empty($componentProperties[ ('autoreply_address_from_name_'.App::getLocale()) ]) ) { $fromAddressName = $componentProperties[ ('autoreply_address_from_name_'.App::getLocale()) ]; } $validator = Validator::make(['email' => $fromAddress], ['email' => 'required|email']); if($validator->fails()){ Log::error('SMALL CONTACT FORM ERROR: Autoreply email address is invalid (' .$fromAddress. ')! System email address and name will be used.'); } else { $message->from($fromAddress, $fromAddressName); } /** * Reply To address * Component's property can override this */ $replyToAddress = null; if( Settings::getTranslated('email_address_replyto') ) { $replyToAddress = Settings::getTranslated('email_address_replyto'); } if( !empty($componentProperties['autoreply_address_replyto']) ) { $replyToAddress = $componentProperties['autoreply_address_replyto']; } if( $replyToAddress ) { $validator = Validator::make(['email' => $replyToAddress], ['email' => 'required|email']); if($validator->fails()){ Log::error('SMALL CONTACT FORM ERROR: Autoreply Reply To email address is invalid (' .$replyToAddress. ')! No Reply To header will be added.'); } else { $message->replyTo($replyToAddress); } } }); } /** * Build and send notification message */ public function sendNotificationEmail($postData, $componentProperties, $formAlias, $formDescription, $messageObject, $formNotes){ if(!Settings::getTranslated('allow_notifications')) { return; } if(!empty($componentProperties['disable_notifications'])) { return; } $sendTo = (!empty($componentProperties['notification_address_to']) ? $componentProperties['notification_address_to'] : Settings::getTranslated('notification_address_to') ); $sendToAddresses = explode(',', $sendTo); $sendToAddressesValidated = []; foreach($sendToAddresses as $sendToAddress) { $validator = Validator::make(['email' => trim($sendToAddress)], ['email' => 'required|email']); if($validator->fails()){ Log::error('SMALL CONTACT FORM ERROR: Notification email address (' .trim($sendToAddress). ') is invalid! No notification will be delivered!'); } else { $sendToAddressesValidated[] = trim($sendToAddress); } } if( !count($sendToAddressesValidated) ) { return; } if( Settings::getTranslated('allow_email_queue') ){ $method = 'queue'; } else { $method = 'send'; } $output = []; $outputFull = []; $formFields = Settings::getTranslated('form_fields'); $replyToAddress = null; $replyToName = null; foreach($formFields as $field) { if(!empty($field['type'] and $field['type'] == 'file')) { continue; } $fieldValue = null; if( !empty( $postData[ $field['name'] ]['value'] ) ) { $fieldValue = e( html_entity_decode( $postData[ $field['name'] ]['value'] ) ); } else { $fieldValue = null; } if( !empty( $field['name'] ) ) { $outputFull[ $field['name'] ] = array_merge( $field, [ 'value' => $fieldValue ] ); } // If email field is assigned, prepare for replyTo if(empty($replyToAddress) and $field['name'] == Settings::getTranslated('autoreply_email_field') and isset($postData[$field['name']]['value'])){ $replyToAddress = e( $postData[$field['name']]['value'] ); } // If name field is assigned, prepare for fromAddress if(empty($replyToName) and $field['name'] == Settings::getTranslated('autoreply_name_field') and isset($postData[$field['name']]['value'])){ $replyToName = e( $postData[$field['name']]['value'] ); } $output[ $field['name'] ] = $fieldValue; } $output['form_description'] = $formDescription; $output['form_alias'] = $formAlias; $template = Settings::getTranslatedTemplates('en', App::getLocale(), 'notification'); if( Settings::getTranslated('notification_template') ){ if(View::exists(Settings::getTranslated('notification_template')) OR !empty( MailTemplate::listAllTemplates()[Settings::getTranslated('notification_template')] ) ) { $template = Settings::getTranslated('notification_template'); } else { Log::error('SMALL CONTACT FORM: Missing defined email template: ' . Settings::getTranslated('notification_template') . '. Default template will be used!'); } } /** * Override email template by component property * Language specific template has priority (override non language specific) */ if ( !empty($componentProperties['notification_template']) and !empty( MailTemplate::listAllTemplates()[ $componentProperties['notification_template'] ] ) ) { $template = $componentProperties['notification_template']; } elseif ( !empty($componentProperties['notification_template']) and empty( MailTemplate::listAllTemplates()[ $componentProperties['notification_template'] ] ) ) { Log::error('SMALL CONTACT FORM: Missing defined email template: ' . $componentProperties['notification_template'] . '. ' . $template . ' template will be used!'); } if ( !empty($componentProperties[ ('notification_template_'.App::getLocale())]) and !empty( MailTemplate::listAllTemplates()[ $componentProperties[ ('notification_template_'.App::getLocale())] ] ) ) { $template = $componentProperties[('notification_template_'.App::getLocale())]; } elseif ( !empty($componentProperties[ ('notification_template_'.App::getLocale())]) and empty( MailTemplate::listAllTemplates()[ $componentProperties[ ('notification_template_'.App::getLocale())] ] ) ) { Log::error('SMALL CONTACT FORM: Missing defined email template: ' . $componentProperties[ ('notification_template_'.App::getLocale())] . '. ' . $template . ' template will be used!'); } if(!empty($messageObject->uploads)) { $uploads = $messageObject->uploads; } else { $uploads = []; } Mail::{$method}($template, ['messageObject' => $messageObject, 'uploads' => $uploads, 'fields' => $output, 'fieldsDetails' => $outputFull, 'url' => url()->full(), 'form_notes' => $formNotes], function($message) use($sendToAddressesValidated, $replyToAddress, $replyToName, $componentProperties, $output){ if( count($sendToAddressesValidated)>1 ) { foreach($sendToAddressesValidated as $address) { $message->bcc($address); } } elseif( !empty($sendToAddressesValidated[0]) ) { $message->to($sendToAddressesValidated[0]); } else { return; } if (!empty($componentProperties['notification_subject'])) { $message->subject(Twig::parse($componentProperties['notification_subject'], ['fields' => $output])); \App::forgetInstance('parse.twig'); \App::forgetInstance('twig.environment'); } /** * Set Reply to address and also set From address if requested */ if ( !empty($replyToAddress) ) { $validator = Validator::make(['email' => $replyToAddress], ['email' => 'required|email']); if($validator->fails()){ Log::error('SMALL CONTACT FORM ERROR: Notification replyTo address is not valid (' .$replyToAddress. ')! Reply to address will not be used.'); return; } $message->replyTo($replyToAddress, $replyToName); // Force From field if requested if ( Settings::getTranslated('notification_address_from_form') ) { $message->from($replyToAddress, $replyToName); } } /** * Set From address if defined in component property */ if ( !empty($componentProperties['notification_address_from'])) { if (!empty($componentProperties['notification_address_from_name'])) { $fromAddressName = $componentProperties['notification_address_from_name']; } else { $fromAddressName = null; } $message->from($componentProperties['notification_address_from'], $fromAddressName); } }); } /** * Test how many times was given IP address used this day * @return int */ public function testIPAddress($ip){ $today = Carbon::today(); $count = Message::whereDate('created_at', '=', $today->toDateString()) ->where('remote_ip', '=', $ip) ->count(); return $count; } }
jan-vince/smallcontactform
models/Message.php
PHP
mit
20,183
package com.weixin.util; import java.io.IOException; import java.io.InputStream; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; import com.thoughtworks.xstream.XStream; import com.weixin.vo.TextMessage; /** * @author : Jay */ public class MessageUtil { /** * xml 转为 map * @param request * @return * @throws IOException * @throws DocumentException */ public static Map<String, String> xmlToMap(HttpServletRequest request) throws IOException, DocumentException { Map<String, String> map = new HashMap<String, String>(); SAXReader reader = new SAXReader(); InputStream ins = request.getInputStream(); org.dom4j.Document doc = reader.read(ins); Element root = doc.getRootElement(); List<Element> list = root.elements(); for (Element e : list) { map.put(e.getName(), e.getText()); } ins.close(); return map; } /** * 将文本消息对象转为xml * @return */ public static String textMessageToXml(TextMessage textMessage){ XStream xstream = new XStream(); xstream.alias("xml", textMessage.getClass()); return xstream.toXML(textMessage); } /** * 初始化文本消 * @param toUserName * @param fromUserName * @param content * @return */ public static String initText(String toUserName, String fromUserName,String content){ TextMessage text = new TextMessage(); text.setFromUserName(toUserName); text.setToUserName(fromUserName); text.setMsgType("text"); text.setCreateTime(new Date().getTime()); text.setContent(content); return MessageUtil.textMessageToXml(text); } }
ScorpionJay/wechat
src/main/java/com/weixin/util/MessageUtil.java
Java
mit
1,844
// Copyright (c) 2011-2015 The Gtacoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "sendcoinsentry.h" #include "ui_sendcoinsentry.h" #include "addressbookpage.h" #include "addresstablemodel.h" #include "guiutil.h" #include "optionsmodel.h" #include "platformstyle.h" #include "walletmodel.h" #include <QApplication> #include <QClipboard> SendCoinsEntry::SendCoinsEntry(const PlatformStyle *_platformStyle, QWidget *parent) : QStackedWidget(parent), ui(new Ui::SendCoinsEntry), model(0), platformStyle(_platformStyle) { ui->setupUi(this); // GTACOIN QString theme = GUIUtil::getThemeName(); ui->addressBookButton->setIcon(platformStyle->SingleColorIcon(":/icons/" + theme + "/address-book")); ui->pasteButton->setIcon(platformStyle->SingleColorIcon(":/icons/" + theme + "/editpaste")); ui->deleteButton->setIcon(platformStyle->SingleColorIcon(":/icons/" + theme + "/remove")); ui->deleteButton_is->setIcon(platformStyle->SingleColorIcon(":/icons/" + theme + "/remove")); ui->deleteButton_s->setIcon(platformStyle->SingleColorIcon(":/icons/" + theme + "/remove")); setCurrentWidget(ui->SendCoins); if (platformStyle->getUseExtraSpacing()) ui->payToLayout->setSpacing(4); #if QT_VERSION >= 0x040700 ui->addAsLabel->setPlaceholderText(tr("Enter a label for this address to add it to your address book")); #endif // normal gtacoin address field GUIUtil::setupAddressWidget(ui->payTo, this); // just a label for displaying gtacoin address(es) ui->payTo_is->setFont(GUIUtil::fixedPitchFont()); // Connect signals connect(ui->payAmount, SIGNAL(valueChanged()), this, SIGNAL(payAmountChanged())); connect(ui->checkboxSubtractFeeFromAmount, SIGNAL(toggled(bool)), this, SIGNAL(subtractFeeFromAmountChanged())); connect(ui->deleteButton, SIGNAL(clicked()), this, SLOT(deleteClicked())); connect(ui->deleteButton_is, SIGNAL(clicked()), this, SLOT(deleteClicked())); connect(ui->deleteButton_s, SIGNAL(clicked()), this, SLOT(deleteClicked())); } SendCoinsEntry::~SendCoinsEntry() { delete ui; } void SendCoinsEntry::on_pasteButton_clicked() { // Paste text from clipboard into recipient field ui->payTo->setText(QApplication::clipboard()->text()); } void SendCoinsEntry::on_addressBookButton_clicked() { if(!model) return; AddressBookPage dlg(platformStyle, AddressBookPage::ForSelection, AddressBookPage::SendingTab, this); dlg.setModel(model->getAddressTableModel()); if(dlg.exec()) { ui->payTo->setText(dlg.getReturnValue()); ui->payAmount->setFocus(); } } void SendCoinsEntry::on_payTo_textChanged(const QString &address) { updateLabel(address); } void SendCoinsEntry::setModel(WalletModel *_model) { this->model = _model; if (_model && _model->getOptionsModel()) connect(_model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); clear(); } void SendCoinsEntry::clear() { // clear UI elements for normal payment ui->payTo->clear(); ui->addAsLabel->clear(); ui->payAmount->clear(); ui->checkboxSubtractFeeFromAmount->setCheckState(Qt::Unchecked); ui->messageTextLabel->clear(); ui->messageTextLabel->hide(); ui->messageLabel->hide(); // clear UI elements for unauthenticated payment request ui->payTo_is->clear(); ui->memoTextLabel_is->clear(); ui->payAmount_is->clear(); // clear UI elements for authenticated payment request ui->payTo_s->clear(); ui->memoTextLabel_s->clear(); ui->payAmount_s->clear(); // update the display unit, to not use the default ("GTA") updateDisplayUnit(); } void SendCoinsEntry::deleteClicked() { Q_EMIT removeEntry(this); } bool SendCoinsEntry::validate() { if (!model) return false; // Check input validity bool retval = true; // Skip checks for payment request if (recipient.paymentRequest.IsInitialized()) return retval; if (!model->validateAddress(ui->payTo->text())) { ui->payTo->setValid(false); retval = false; } if (!ui->payAmount->validate()) { retval = false; } // Sending a zero amount is invalid if (ui->payAmount->value(0) <= 0) { ui->payAmount->setValid(false); retval = false; } // Reject dust outputs: if (retval && GUIUtil::isDust(ui->payTo->text(), ui->payAmount->value())) { ui->payAmount->setValid(false); retval = false; } return retval; } SendCoinsRecipient SendCoinsEntry::getValue() { // Payment request if (recipient.paymentRequest.IsInitialized()) return recipient; // Normal payment recipient.address = ui->payTo->text(); recipient.label = ui->addAsLabel->text(); recipient.amount = ui->payAmount->value(); recipient.message = ui->messageTextLabel->text(); recipient.fSubtractFeeFromAmount = (ui->checkboxSubtractFeeFromAmount->checkState() == Qt::Checked); return recipient; } QWidget *SendCoinsEntry::setupTabChain(QWidget *prev) { QWidget::setTabOrder(prev, ui->payTo); QWidget::setTabOrder(ui->payTo, ui->addAsLabel); QWidget *w = ui->payAmount->setupTabChain(ui->addAsLabel); QWidget::setTabOrder(w, ui->checkboxSubtractFeeFromAmount); QWidget::setTabOrder(ui->checkboxSubtractFeeFromAmount, ui->addressBookButton); QWidget::setTabOrder(ui->addressBookButton, ui->pasteButton); QWidget::setTabOrder(ui->pasteButton, ui->deleteButton); return ui->deleteButton; } void SendCoinsEntry::setValue(const SendCoinsRecipient &value) { recipient = value; if (recipient.paymentRequest.IsInitialized()) // payment request { if (recipient.authenticatedMerchant.isEmpty()) // unauthenticated { ui->payTo_is->setText(recipient.address); ui->memoTextLabel_is->setText(recipient.message); ui->payAmount_is->setValue(recipient.amount); ui->payAmount_is->setReadOnly(true); setCurrentWidget(ui->SendCoins_UnauthenticatedPaymentRequest); } else // authenticated { ui->payTo_s->setText(recipient.authenticatedMerchant); ui->memoTextLabel_s->setText(recipient.message); ui->payAmount_s->setValue(recipient.amount); ui->payAmount_s->setReadOnly(true); setCurrentWidget(ui->SendCoins_AuthenticatedPaymentRequest); } } else // normal payment { // message ui->messageTextLabel->setText(recipient.message); ui->messageTextLabel->setVisible(!recipient.message.isEmpty()); ui->messageLabel->setVisible(!recipient.message.isEmpty()); ui->addAsLabel->clear(); ui->payTo->setText(recipient.address); // this may set a label from addressbook if (!recipient.label.isEmpty()) // if a label had been set from the addressbook, don't overwrite with an empty label ui->addAsLabel->setText(recipient.label); ui->payAmount->setValue(recipient.amount); } } void SendCoinsEntry::setAddress(const QString &address) { ui->payTo->setText(address); ui->payAmount->setFocus(); } bool SendCoinsEntry::isClear() { return ui->payTo->text().isEmpty() && ui->payTo_is->text().isEmpty() && ui->payTo_s->text().isEmpty(); } void SendCoinsEntry::setFocus() { ui->payTo->setFocus(); } void SendCoinsEntry::updateDisplayUnit() { if(model && model->getOptionsModel()) { // Update payAmount with the current unit ui->payAmount->setDisplayUnit(model->getOptionsModel()->getDisplayUnit()); ui->payAmount_is->setDisplayUnit(model->getOptionsModel()->getDisplayUnit()); ui->payAmount_s->setDisplayUnit(model->getOptionsModel()->getDisplayUnit()); } } bool SendCoinsEntry::updateLabel(const QString &address) { if(!model) return false; // Fill in label from address book, if address has an associated label QString associatedLabel = model->getAddressTableModel()->labelForAddress(address); if(!associatedLabel.isEmpty()) { ui->addAsLabel->setText(associatedLabel); return true; } return false; }
gtacoin-dev/gtacoin
src/qt/sendcoinsentry.cpp
C++
mit
8,351
using Shouldly; using Specify.Samples.Domain.Atm; using TestStack.BDDfy; namespace Specify.Samples.Specs.ATM { public class CardHasBeenDisabled : ScenarioFor<Atm, AccountHolderWithdrawsCashStory> { private Card _card; public void Given_the_Card_is_disabled() { _card = new Card(false, 100); SUT = new Atm(100); } [When("When the account holder requests $20")] public void When_the_Account_Holder_requests_20_dollars() { SUT.RequestMoney(_card, 20); } public void Then_the_Card_should_be_retained() { SUT.CardIsRetained.ShouldBe(true); } public void AndThen_the_ATM_should_say_the_Card_has_been_retained() { SUT.Message.ShouldBe(DisplayMessage.CardIsRetained); } } }
mwhelan/Specify
src/Samples/Specify.Samples/Specs/ATM/CardHasBeenDisabled.cs
C#
mit
857
import os,sys from trans_rot_coords import * import numpy as np from read_energy_force_new import * from grids_structures_general import DS,Grid_Quarts from orient_struct_2 import OrientDS as OrientDS_2 from orient_struct_3 import OrientDS as OrientDS_3 AU2KCAL = 23.0605*27.2116 R2D = 180.0/3.14159265358979 ## np.pi/4.0: pi4 = 0.78539816339744817 tMass = [15.999, 1.008, 1.008] def get_com(coords): x = [0,0,0] totalM = 0 for i in range(len(coords)): x = [ x[k]+ coords[i][k]*tMass[i] for k in range(3)] totalM += tMass[i] x = [x[k]/totalM for k in range(3)] return x def norm_prob(config,ndx,prob='wtr'): if prob=='wtr': v1 = np.array(config[ndx[1]]) - np.array(config[ndx[0]]) v2 = np.array(config[ndx[2]]) - np.array(config[ndx[0]]) vec = get_normal_unit(v1,v2) return vec class new_atom(): def __init__(self, line, ftype='gjf'): if ftype=='gjf': self.addgjf(line) elif ftype=='gms': self.addinp(line) elif ftype=='pdb': self.addpdb(line) def addgjf(self, line): line = line.split() self.a_nam = line[0] self.x = [float(line[1]), float(line[2]), float(line[3])] def addpdb(self, line): self.line = line self.i_atm = int(line[6:11]) self.a_nam = line[11:16].strip() self.a_res = line[16:20].strip() self.a_chn = line[20:22].strip() self.i_res = int(line[22:26]) self.x = [] self.x.append(float(line[30:38])) self.x.append(float(line[38:46])) self.x.append(float(line[46:54])) def addinp(self, line): line = line.split() self.a_nam = line[0] self.x = [float(line[2]), float(line[3]), float(line[4])] class coordinates(): def __init__(self, n1, n2, FragType, name=''): ## n1,n2 is the number of atoms in mole1 and mole2: self.n1 = n1 self.n2 = n2 ## records of operations of translation and rotation: self.OperateNdx = [] self.Operation = [] ## fragment type: self.FT = FragType ## symmetry faces: self.symface = DS[self.FT].symface self.IsOriented = False self.facendx = {'yx':2, 'xy':2, 'yz':0, 'zy':0, 'zx':1, 'xz':1, 'zarg':5, 'zben':6} self.symm = [1,1,1] self.center = 0 self.natoms = 0 self.original_atoms = [] self.name = name def addatom(self, line, ftype='pdb'): temp = new_atom(line, ftype) self.original_atoms.append(temp) self.natoms += 1 def addpdbatom(self, line): self.original_atoms.append(new_atom(line, 'pdb')) self.natoms += 1 def set_atom(self, i, atom): if i>=len(self.original_atoms): self.original_atoms.append( deepcopy(atom) ) self.natoms += 1 else: self.original_atoms[i] = deepcopy(atom) def MirrorAll(self): """ According to the coords of the 1st atom in mole2. """ self.orignal_com = deepcopy(self.center2) for face in self.symface: fndx = self.facendx[face] if self.center2[fndx] < 0.0: self.symm[ fndx ] = -1 for i in range(self.n1, self.natoms): self.atoms[i].x[fndx] *= -1 self._spherical_x() def MirrorBackProperty(self): for face in self.symface: fndx = self.facendx[face] if self.orignal_com[fndx] < 0.0: self.symm[ fndx ] = -1 self.force[fndx] *= -1 for i in range(3): if not i == fndx: self.torque[i] *= -1 def ReorientToOrigin(self, cut=0.0000001): self.atoms = deepcopy(self.original_atoms) import pdb pdb.set_trace() coord1 = get_com([self.atoms[0].x, self.atoms[1].x, self.atoms[2].x ]) coord2 = get_com([self.atoms[3].x, self.atoms[4].x, self.atoms[5].x ]) self.origin_center_coord = get_unit([coord2[i] - coord1[i] for i in range(3)]) dvec = DS[self.FT].calt_dvec( self.atoms[0].x, self.atoms[1].x, self.atoms[2].x ) for i in range(self.natoms): self.atoms[i].x = translate(self.atoms[i].x, dvec) self.OperateNdx.append(0) self.Operation.append(np.array(dvec)) vec, ax0 = DS[self.FT].calt_vec1( self.atoms[0].x, self.atoms[1].x, self.atoms[2].x ) ang = angle(vec, ax0) ax = get_normal(vec, ax0) if ax[0]==0.0 and ax[1]==0.0 and ax[2]==0.0: pass else: for i in range(self.natoms): self.atoms[i].x = rotate(self.atoms[i].x, ax, ang) self.OperateNdx.append(1) self.Operation.append([ax, ang]) vec, ax0 = DS[self.FT].calt_vec2( self.atoms[0].x, self.atoms[1].x, self.atoms[2].x ) ang = angle(vec, ax0) if abs(ang)<cut: pass else: if abs(ang-np.pi)<cut: ax = [1,0,0] else: ax = get_normal(vec, ax0) for i in range(self.natoms): self.atoms[i].x = rotate(self.atoms[i].x, ax, ang) self.OperateNdx.append(2) self.Operation.append([ax, ang]) self.IsOriented = True self._spherical_x() def ReorientToOldVec(self): ax, ang = self.Operation[self.OperateNdx.index(2)] self.force = rotate(self.force, ax, -1*ang) self.torque = rotate(self.torque, ax, -1*ang) ax, ang = self.Operation[self.OperateNdx.index(1)] self.force = rotate(self.force, ax, -1*ang) self.torque = rotate(self.torque, ax, -1*ang) def _spherical_x(self): """ Calculate the coords in spherical coordination system for molecule 2. """ totalM = 0 x = [0,0,0] for i in range(self.n1,self.natoms): x = [ x[k]+self.atoms[i].x[k]*tMass[i-self.n1] for k in range(3)] totalM += tMass[i-self.n1] x = [x[k]/totalM for k in range(3)] r = np.sqrt(x[0]*x[0]+x[1]*x[1]+x[2]*x[2]) #print "probe vector:", 4.0*x[0]/r, 4.0*x[1]/r, 4.0*x[2]/r ## phi of principal coords: ang1 = np.pi*0.5 - np.arccos(x[2]/r) ## theta of principal coords (from -pi to pi): if abs(x[0])<0.000001: if x[1]>0: ang2 = np.pi*0.5 else: ang2 = np.pi*1.5 else: ang2 = np.arctan(x[1]/x[0]) if x[0]<0: ang2 += np.pi elif x[1]<0: ang2 += np.pi*2 self.r = r self.ang1 = ang1 self.ang2 = ang2 self.center2 = x def _spherical_orient(self): """ calculate the spherical coordinates for the orientational vector """ x = self.orientVec r = length(x) # phi, [-pi/2, pi/2] ang1 = np.pi*0.5 - np.arccos(x[2]/r) # theta, [0, 2*pi] if abs(x[0])<0.000001: if x[1]>0: ang2 = np.pi*0.5 else: ang2 = np.pi*1.5 else: ang2 = np.arctan(x[1]/x[0]) if x[0]<0: ang2 += np.pi elif x[1] <0: ang2 += np.pi*2 self.orient_ang1 = ang1 self.orient_ang2 = ang2 def indexing_orient_auto3(self,ri): """ find the index automatically for each subsection in which the orientational vector resides """ ang1 = self.orient_ang1 ang2 = self.orient_ang2 #print "<<<<<",ang1*R2D,ang2*R2D OrientDS = self.OrientDS[ri] #print "attention!!!" #print OrientDS['wtr'].nGrid if ang1<OrientDS['wtr'].PHI_angles[0] or ang1>OrientDS['wtr'].PHI_angles[-1]: ih = -1 for i in range(1,OrientDS['wtr'].nPhi): if ang1 <= OrientDS['wtr'].PHI_angles[i]: ih = i-1 break ang1_ndx1 = ih ang1_ndx2 = ih + 1 if ang1_ndx1 == OrientDS['wtr'].nPhi-2: # near the up vertex ang1_ndx3 = ih -1 elif ang1_ndx1 == 0: # near the down vertex ang1_ndx3 = ih + 2 else: tmp1 = OrientDS['wtr'].PHI_angles[ih+2] - ang1 tmp2 = ang1 - OrientDS['wtr'].PHI_angles[ih-1] if abs(tmp1) < abs(tmp2): ang1_ndx3 = ih + 2 else: ang1_ndx3 = ih - 1 phiList = [ang1_ndx1,ang1_ndx2,ang1_ndx3] dgrids_sub_ndx = {} dtheta_ndx = {} # determine if use linear interpolation or use quadratic interpolation if len(set(phiList)) == 2: iflinear = 1 elif len(set(phiList)) == 3: iflinear = 0 for kk in set(phiList): dgrids_sub_ndx[kk] = [] dtheta_ndx[kk] = [] ip = -1 for i in range(1, OrientDS['wtr'].NTheta[kk]): if ang2 <= OrientDS['wtr'].THETA_angles[kk][i]: ip = i-1 break if ip == -1: ip = OrientDS['wtr'].NTheta[kk]-1 #print kk, ip ig = 0 for i in range(kk): ig += OrientDS['wtr'].NTheta[i] ig += ip dgrids_sub_ndx[kk].append(ig) dtheta_ndx[kk].append(ip) if ip == OrientDS['wtr'].NTheta[kk]-1: if OrientDS['wtr'].NTheta[kk] == 1: #vertex dgrids_sub_ndx[kk].append(ig) dtheta_ndx[kk].append(0) if iflinear == 0: dgrids_sub_ndx[kk].append(ig) dtheta_ndx[kk].append(0) else: dgrids_sub_ndx[kk].append(ig-OrientDS['wtr'].NTheta[kk]+1) dtheta_ndx[kk].append(0+OrientDS['wtr'].NTheta[kk]) if iflinear == 0: tmp1 = OrientDS['wtr'].THETA_angles[kk][1] - ang2 + 2*np.pi tmp2 = ang2 - OrientDS['wtr'].THETA_angles[kk][ip-1] if tmp1 < tmp2: dgrids_sub_ndx[kk].append(ig-OrientDS['wtr'].NTheta[kk]+1+1) dtheta_ndx[kk].append(0+OrientDS['wtr'].NTheta[kk]+1) else: dgrids_sub_ndx[kk].append(ig-1) dtheta_ndx[kk].append(ip-1) else: dgrids_sub_ndx[kk].append(ig+1) dtheta_ndx[kk].append(ip+1) if iflinear == 0: if ip+2 == OrientDS['wtr'].NTheta[kk]: tmp1 = 2*np.pi - ang2 else: tmp1 = OrientDS['wtr'].THETA_angles[kk][ip+2] - ang2 if ip == 0: tmp2 = ang2 - OrientDS['wtr'].THETA_angles[kk][OrientDS['wtr'].NTheta[kk]-1] + 2*np.pi else: tmp2 = ang2 - OrientDS['wtr'].THETA_angles[kk][ip-1] if tmp1 < tmp2: if ip+2 == OrientDS['wtr'].NTheta[kk]: dgrids_sub_ndx[kk].append(ig+1-OrientDS['wtr'].NTheta[kk]+1) dtheta_ndx[kk].append(0+OrientDS['wtr'].NTheta[kk]) else: dgrids_sub_ndx[kk].append(ig+2) dtheta_ndx[kk].append(ip+2) else: if ip == 0: dgrids_sub_ndx[kk].append(ig+OrientDS['wtr'].NTheta[kk]-1) dtheta_ndx[kk].append(-1) else: dgrids_sub_ndx[kk].append(ig-1) dtheta_ndx[kk].append(ip-1) self.dgrids_sub_ndx[ri] = dgrids_sub_ndx self.dtheta_ndx[ri] = dtheta_ndx def indexing_auto3(self): if not self.IsOriented: raise Exception, "Error: indexing beforce reorientation." r = self.r ang1 = self.ang1 ang2 = self.ang2 #print "probe angles", ang1*R2D, ang2*R2D ## ndx of r: ir = 10001 if r<DS[self.FT].R_NDX[0]: ir = -1 else: for i in range(1,DS[self.FT].nDist): if r<=DS[self.FT].R_NDX[i]: ir = i-1 break #print 'ir',ir if ir>10000: self.r_ndxs = [ir] self.vbis = [0,0,0] self.vnrm = [0,0,0] self.dgrid_ndx_layer = {} self.dtheta_ndx_layer = {} return 10000,0,0 elif ir<0: self.r_ndxs = [ir] self.vbis = [0,0,0] self.vnrm = [0,0,0] self.dgrid_ndx_layer = {} self.dtheta_ndx_layer = {} return -1, 0,0 #print "r=%.1f"%r, ir r_ndxs = [ir,ir+1] # find 3 layers which are close to the query one if ir == 0: r_ndxs.append(ir+2) elif ir == DS[self.FT].nDist -2: r_ndxs.append(ir-1) else: tmp1 = r - DS[self.FT].R_NDX[ir-1] tmp2 = DS[self.FT].R_NDX[ir+2] - r if abs(tmp1) < abs(tmp2): r_ndxs.append(ir-1) else: r_ndxs.append(ir+2) ## ndx of ang1 (Phi): if ang1<DS[self.FT].PHI_angles[0]: ih = -1 for i in range(1, DS[self.FT].nPhi): if ang1<=DS[self.FT].PHI_angles[i]: ih = i-1 break ang1_ndx1 = ih ang1_ndx2 = ih + 1 if ang1_ndx1 == DS[self.FT].nPhi -2: ang1_ndx3 = ih - 1 elif ang1_ndx1 == 0: ang1_ndx3 = ih + 2 else: tmp1 = DS[self.FT].PHI_angles[ih+2] - ang1 tmp2 = ang1 - DS[self.FT].PHI_angles[ih-1] if tmp1 < tmp2: ang1_ndx3 = ih+2 else: ang1_ndx3 = ih-1 phiList = [ang1_ndx1,ang1_ndx2,ang1_ndx3] dgrid_ndx_layer = {} dtheta_ndx_layer = {} # determine if use linear interpolation or use quadratic interpolation if len(set(phiList)) == 2: iflinear = 1 elif len(set(phiList)) == 3: iflinear = 0 for kk in set(phiList): dgrid_ndx_layer[kk] = [] dtheta_ndx_layer[kk] = [] ## ndx_of_ang2 (Theta): ip = -1 for i in range(1,DS[self.FT].NTheta[kk]): if ang2<=DS[self.FT].THETA_angles[kk][i]: ip = i-1 break if ip==-1: ip = DS[self.FT].NTheta[kk]-1 ig = 0 for i in range(kk): ig += DS[self.FT].NTheta[i] ig += ip dgrid_ndx_layer[kk].append(ig) dtheta_ndx_layer[kk].append(ip) #print "check", kk, ip, ig if ip == DS[self.FT].NTheta[kk]-1: if DS[self.FT].NTheta[kk] == 1: #vertex dgrid_ndx_layer[kk].append(ig) dtheta_ndx_layer[kk].append(0) if iflinear == 0: dgrid_ndx_layer[kk].append(ig) dtheta_ndx_layer[kk].append(0) elif self.FT in ['cys','alc','bck','hid','trp','tyr','gln']: dgrid_ndx_layer[kk].append(ig-DS[self.FT].NTheta[kk]+1) dtheta_ndx_layer[kk].append(0+DS[self.FT].NTheta[kk]) if iflinear == 0: tmp1 = DS[self.FT].THETA_angles[kk][1] - ang2 + 2*np.pi tmp2 = ang2 - DS[self.FT].THETA_angles[kk][ip-1] if tmp1 < tmp2: dgrid_ndx_layer[kk].append(ig-DS[self.FT].NTheta[kk]+1+1) dtheta_ndx_layer[kk].append(0+DS[self.FT].NTheta[kk]+1) else: dgrid_ndx_layer[kk].append(ig-1) dtheta_ndx_layer[kk].append(ip-1) else: dgrid_ndx_layer[kk].append(ig-1) dtheta_ndx_layer[kk].append(ip-1) if iflinear == 0: dgrid_ndx_layer[kk].append(ig-2) dtheta_ndx_layer[kk].append(ip-2) else: dgrid_ndx_layer[kk].append(ig+1) dtheta_ndx_layer[kk].append(ip+1) if iflinear == 0: if self.FT in ['cys','alc','bck','hid','trp','tyr','gln']: if ip+2 == DS[self.FT].NTheta[kk]: tmp1 = 2*np.pi -ang2 else: tmp1 = DS[self.FT].THETA_angles[kk][ip+2] - ang2 if ip == 0: tmp2 = ang2 - DS[self.FT].THETA_angles[kk][DS[self.FT].NTheta[kk]-1] + 2*np.pi else: tmp2 = ang2 - DS[self.FT].THETA_angles[kk][ip-1] if tmp1 < tmp2: if ip+2 == DS[self.FT].NTheta[kk]: dgrid_ndx_layer[kk].append(ig+1-DS[self.FT].NTheta[kk]+1) dtheta_ndx_layer[kk].append(0+DS[self.FT].NTheta[kk]) else: dgrid_ndx_layer[kk].append(ig+2) dtheta_ndx_layer[kk].append(ip+2) else: if ip == 0: dgrid_ndx_layer[kk].append(ig+DS[self.FT].NTheta[kk]-1) dtheta_ndx_layer[kk].append(-1) else: dgrid_ndx_layer[kk].append(ig-1) dtheta_ndx_layer[kk].append(ip-1) else: if ip == DS[self.FT].NTheta[kk]-2: dgrid_ndx_layer[kk].append(ig-1) dtheta_ndx_layer[kk].append(ip-1) elif ip == 0: dgrid_ndx_layer[kk].append(ig+2) dtheta_ndx_layer[kk].append(ip+2) else: tmp1 = DS[self.FT].THETA_angles[kk][ip+2] - ang2 tmp2 = ang2 - DS[self.FT].THETA_angles[kk][ip-1] if tmp1 < tmp2: dgrid_ndx_layer[kk].append(ig+2) dtheta_ndx_layer[kk].append(ip+2) else: dgrid_ndx_layer[kk].append(ig-1) dtheta_ndx_layer[kk].append(ip-1) self.dgrid_ndx_layer = dgrid_ndx_layer self.dtheta_ndx_layer = dtheta_ndx_layer ## calculate the vectors of bisector and normal of mole2: a20 = self.atoms[self.n1].x a21 = self.atoms[self.n1+1].x a22 = self.atoms[self.n1+2].x a20 = np.array(a20) a21 = np.array(a21) a22 = np.array(a22) v0 = a21 - a20 v1 = a22 - a20 ## These two vectors must be unit vector: bisect = get_bisect_unit(v0,v1) normal = get_normal_unit(v0,v1) self.r_ndxs = r_ndxs self.vbis = bisect self.vnrm = normal def calt_conf_energy(self, allconfigs, IsForce=False, ehigh=100.0): ri_ndxs = self.r_ndxs self.exit_before = False for ri in ri_ndxs: if ri>100: self.properties = {'E':0.0} return elif ri<0: fuck = [self.origin_center_coord[i] * ehigh for i in range(3)] self.properties = {'E':ehigh, "Fx": fuck[0], "Fy": fuck[1], "Fz": fuck[2], "Tx": 0, "Ty": 0, "Tz": 0} self.exit_before = True return bisv = self.vbis nrmv = self.vnrm dtheta_ndx_layer = self.dtheta_ndx_layer grid_ndx_layer = [] for ih in self.dgrid_ndx_layer: grid_ndx_layer += self.dgrid_ndx_layer[ih] self.orientVec = bisv #print "orient vector:%.5f\t%.5f\t%.5f\n"%(bisv[0]*4.0,bisv[1]*4.0,bisv[2]*4.0) self._spherical_orient() ang1 = self.orient_ang1 ang2 = self.orient_ang2 ang2 = (ang2*R2D+180)%360 #the original orientational vector of water is located at -x axis ang2 = ang2/R2D self.orient_ang2 = ang2 self.OrientDS = {} self.orient_tr = {} self.orient_pr = {} self.dgrids_sub_ndx = {} self.dtheta_ndx = {} grids_sub_ndx = {} dtheta_ndx = {} wghx1 = {} wghx2 = {} wghy = {} label = {} for i in ri_ndxs: dist = DS[self.FT].R_NDX[i] # choose corresponding orientational sampling based on distance #print "which layer:", dist if dist > 5.5000001: cart_ndx, grids_sub_ndx_tmp, wghx_tmp, wghy_tmp = weights_in_subsection( bisv ) grids_sub_ndx[i] = grids_sub_ndx_tmp wghx1[i] = wghx_tmp/pi4 wghx2[i] = wghx_tmp/pi4 wghy[i] = wghy_tmp/pi4 label[i] = 0 else: if dist < 2.5000001: OrientDS = OrientDS_2 elif dist > 2.5000001 and dist < 3.5000001: OrientDS = OrientDS_3 else: OrientDS = OrientDS_2 self.OrientDS[i] = OrientDS self.indexing_orient_auto3(i) dtheta_ndx[i] = self.dtheta_ndx[i] if len(dtheta_ndx[i]) == 2: # not in this script pass #orient_pr =[] #for kk in dtheta_ndx[i]: # ip1=dtheta_ndx[i][kk][0] # ip2=dtheta_ndx[i][kk][1] # if ip1 == 0 and ip2 == 0: # vertex # wtmp = 0 # elif ip1 == OrientDS['wtr'].NTheta[kk]-1: # wtmp = (ang2-OrientDS['wtr'].THETA_angles[kk][ip1])/(2*np.pi+OrientDS['wtr'].THETA_angles[kk][0]-OrientDS['wtr'].THETA_angles[kk][ip1]) # else: # wtmp = (ang2-OrientDS['wtr'].THETA_angles[kk][ip1])/(OrientDS['wtr'].THETA_angles[kk][ip2]-OrientDS['wtr'].THETA_angles[kk][ip1]) # orient_pr.append(wtmp) #wghx1[i] = orient_pr[0] #wghx2[i] = orient_pr[1] #ihs = dtheta_ndx[i].keys() #wghy[i] = (ang1 - OrientDS['wtr'].PHI_angles[ihs[0]])/(OrientDS['wtr'].PHI_angles[ihs[1]]-OrientDS['wtr'].PHI_angles[ihs[0]]) #label[i] = 1 ##print "++++++",wghx1[i],wghx2[i],wghy[i] #grids_sub_ndx[i] = self.dgrids_sub_ndx[i][ihs[0]] + self.dgrids_sub_ndx[i][ihs[1]] if len(dtheta_ndx[i]) == 3: ihs = dtheta_ndx[i].keys() grids_sub_ndx[i] = self.dgrids_sub_ndx[i][ihs[0]] + self.dgrids_sub_ndx[i][ihs[1]] + self.dgrids_sub_ndx[i][ihs[2]] label[i] = 2 #print "grids_sub_ndx:",grids_sub_ndx[i] properties = {'E':[], 'Fx':[], 'Fy':[], 'Fz':[], 'Tx':[], 'Ty':[], 'Tz':[]} propnames = ['E','Fx','Fy','Fz','Tx','Ty','Tz'] tempprop = deepcopy(properties) for i in ri_ndxs: for j in grid_ndx_layer: prop = deepcopy(tempprop) for ni in grids_sub_ndx[i]: inpfiles = [] for k in range(DS[self.FT].nNorm[i]): inpfile = 'r%3.2f/tempconf_d%3.2f_g%03d_c%02d.inp'%(DS[self.FT].R_NDX[i],DS[self.FT].R_NDX[i],j,ni+k*DS[self.FT].nConf[i]) inpfiles.append(inpfile) xvecs = [] for ff in range(len(inpfiles)): xconf = allconfigs.allcfg[i][j][ni][ff].xmole2 xvecs.append( norm_prob(xconf,[0,1,2],'wtr') ) nvec = len(xvecs) if nvec == 2: # linear interpolation for normal vectors w0, w1, ndx0, ndx1 = weights_for_normal_general( nrmv, xvecs) #print 'test',i, j, ni, ndx0, ndx1 for pp in propnames: p0 = allconfigs.get_prop(i,j,ni,ndx0,pp,w0, ehigh=ehigh) p1 = allconfigs.get_prop(i,j,ni,ndx1,pp,w1, ehigh=ehigh) p = p1*abs(w1) + p0*abs(w0) prop[pp].append(p) #print pp, inpfiles[ndx0],p0,w0,inpfiles[ndx1],p1,w1,p elif nvec > 2: # quadratic interpolation for normal vectors angNorm, ndx1, ndx2, ndx3 = get_neighors_for_normal(nrmv, xvecs) angNorm_1 = ndx1*np.pi/nvec angNorm_2 = ndx2*np.pi/nvec angNorm_3 = ndx3*np.pi/nvec #print "lagrange", i, j, ni, ndx1, ndx2, ndx3, angNorm*R2D, angNorm_1*R2D, angNorm_2*R2D, angNorm_3*R2D for pp in propnames: if ndx1 == nvec: ndx1 = 0 if ndx2 == nvec: ndx2 = 0 if ndx3 == nvec: ndx3 = 0 p1 = allconfigs.get_prop(i,j,ni,ndx1,pp,0, ehigh=ehigh) p2 = allconfigs.get_prop(i,j,ni,ndx2,pp,0, ehigh=ehigh) p3 = allconfigs.get_prop(i,j,ni,ndx3,pp,0, ehigh=ehigh) points = [(angNorm_1,p1),(angNorm_2,p2),(angNorm_3,p3)] p = lagrange_interp(points,angNorm) prop[pp].append(p) #print pp, inpfiles[ndx1],p1,inpfiles[ndx2],p2,inpfiles[ndx3],p3,p for pp in propnames: # on the level of orientation, theta and phi if len(prop[pp]) == 4: psub = bilinear_gen(prop[pp][0], prop[pp][1], prop[pp][2], prop[pp][3], wghx1[i], wghx2[i], wghy[i],label[i]) properties[pp].append(psub) #print pp, prop[pp][0], prop[pp][1], prop[pp][2], prop[pp][3], grids_sub_ndx[i], wghx1[i], wghx2[i], wghy[i],psub elif len(prop[pp]) == 9: cn = 0 points_phi = [] for kk in dtheta_ndx[i]: #print "here",kk, self.OrientDS[i]['wtr'].nPhi angPhi = self.OrientDS[i]['wtr'].PHI_angles[kk] #print "for orientation with phi=",angPhi*R2D if len(set(dtheta_ndx[i][kk])) == 1: # vertex p = prop[pp][cn] points_phi.append((angPhi,p)) cn += 3 continue points_theta = [] for ip in dtheta_ndx[i][kk]: if ip >= self.OrientDS[i]['wtr'].NTheta[kk]: angTheta = 2*np.pi + self.OrientDS[i]['wtr'].THETA_angles[kk][ip-self.OrientDS[i]['wtr'].NTheta[kk]] elif ip < 0: angTheta = self.OrientDS[i]['wtr'].THETA_angles[kk][ip] - 2*np.pi else: angTheta = self.OrientDS[i]['wtr'].THETA_angles[kk][ip] points_theta.append((angTheta,prop[pp][cn])) #print pp, angTheta*R2D, prop[pp][cn] cn += 1 p = lagrange_interp(points_theta,ang2) #print 'quadratic interpolation gives',p, 'for property', pp points_phi.append((angPhi,p)) psub = lagrange_interp(points_phi,ang1) #print 'interpolated orientational property of %s:'%pp,psub properties[pp].append(psub) ## on the level of r, theta, phi self.properties = {} if len(dtheta_ndx_layer) == 2: # for grids near vertex of each layers, linear interpolation for grids and quadratic interpolation for layers; NOT IN THIS SCRIPT pass #Wghx = [] #For kk in dtheta_ndx_layer: # ip1 = dtheta_ndx_layer[kk][0] # ip2 = dtheta_ndx_layer[kk][1] # if ip1 == 0 and ip2 == 0: # wtmp = 0 # else: # wtmp = (self.ang2-DS[self.FT].THETA_angles[kk][ip1])/(DS[self.FT].THETA_angles[kk][ip2]-DS[self.FT].THETA_angles[kk][ip1]) # wghx.append(wtmp) #Ihs = dtheta_ndx_layer.keys() #Wghy = (self.ang1-DS[self.FT].PHI_angles[ihs[0]])/(DS[self.FT].PHI_angles[ihs[1]]-DS[self.FT].PHI_angles[ihs[0]]) #For pp in propnames: # psub_r = [] # for m in range(0,len(properties[pp]),4): # for each layer # #print pp, properties[pp][m], properties[pp][m+1],properties[pp][m+2], properties[pp][m+3], wghx[0], wghx[1], wghy # psub = bilinear_gen(properties[pp][m], properties[pp][m+1],properties[pp][m+2], properties[pp][m+3], wghx[0], wghx[1], wghy,1) # psub_r.append(psub) # if not len(psub_r) == 3: # #print 'quadratic interpolation needs 3 layers' # sys.exit() # points = [] # for t in range(len(ri_ndxs)): # dist = DS[self.FT].R_NDX[ri_ndxs[t]] # points.append((dist,psub_r[t])) # p = lagrange_interp(points,self.r) # self.properties[pp] = p elif len(dtheta_ndx_layer) == 3: # quadratic interpolation for layers and grids for pp in propnames: psub_r = [] for m in range(0,len(properties[pp]),9): # for each layer count = 0 points_th = [] for kk in dtheta_ndx_layer: if len(set(dtheta_ndx_layer[kk])) == 1: # vertex p = properties[pp][m+count] points_th.append((DS[self.FT].PHI_angles[kk],p)) count += 3 continue ip1 = dtheta_ndx_layer[kk][0] ip2 = dtheta_ndx_layer[kk][1] ip3 = dtheta_ndx_layer[kk][2] th1 = DS[self.FT].THETA_angles[kk][ip1] th2 = DS[self.FT].THETA_angles[kk][ip2] th3 = DS[self.FT].THETA_angles[kk][ip3] points = [(th1,properties[pp][m+count]),(th2,properties[pp][m+count+1]),(th3,properties[pp][m+count+2])] p = lagrange_interp(points,self.ang2) points_th.append((DS[self.FT].PHI_angles[kk],p)) count += 3 p = lagrange_interp(points_th,self.ang1) psub_r.append(p) if not len(psub_r) == 3: #print 'quadratic interpolation needs 3 layers' sys.exit() points = [] for t in range(len(ri_ndxs)): dist = DS[self.FT].R_NDX[ri_ndxs[t]] points.append((dist,psub_r[t])) p = lagrange_interp(points,self.r) self.properties[pp] = p def reverse_force_toque(self): Fx = self.properties['Fx'] Fy = self.properties['Fy'] Fz = self.properties['Fz'] self.force = [Fx, Fy, Fz] Tx = self.properties['Tx'] Ty = self.properties['Ty'] Tz = self.properties['Tz'] self.torque = [Tx, Ty, Tz] if self.exit_before: return self.MirrorBackProperty() self.ReorientToOldVec() def get_interp_energy(self): return self.properties['E'] def get_interp_force(self): return self.force def get_interp_torque(self): return self.torque
sethbrin/QM
version2/python/calculate_energy_new_coords_general.py
Python
mit
32,462
/** * The MIT License (MIT) * * Copyright (c) 2014-2022 Mickael Jeanroy * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import {isNumber} from './is-number.js'; /** * Check that a given value is a falsy value. * * @param {*} a Value to check. * @return {boolean} `true` if parameter is a falsy value. */ export function isFiniteNumber(a) { return isNumber(a) && isFinite(a); }
mjeanroy/jasmine-utils
src/core/util/is-finite-number.js
JavaScript
mit
1,420
class AchievementsController < ApplicationController before_action :authenticate_admin! before_action :set_achievement, only: [:show, :edit, :update, :destroy] # GET /achievements # GET /achievements.json def index @achievements = Achievement.all end # GET /achievements/1 # GET /achievements/1.json def show end # GET /achievements/new def new @achievement = Achievement.new end # GET /achievements/1/edit def edit end # POST /achievements # POST /achievements.json def create @achievement = Achievement.new(achievement_params) respond_to do |format| if @achievement.save format.html { redirect_to @achievement, notice: 'Achievement was successfully created.' } format.json { render :show, status: :created, location: @achievement } else format.html { render :new } format.json { render json: @achievement.errors, status: :unprocessable_entity } end end end # PATCH/PUT /achievements/1 # PATCH/PUT /achievements/1.json def update respond_to do |format| if @achievement.update(achievement_params) format.html { redirect_to @achievement, notice: 'Achievement was successfully updated.' } format.json { render :show, status: :ok, location: @achievement } else format.html { render :edit } format.json { render json: @achievement.errors, status: :unprocessable_entity } end end end # DELETE /achievements/1 # DELETE /achievements/1.json def destroy @achievement.destroy respond_to do |format| format.html { redirect_to achievements_url, notice: 'Achievement was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_achievement @achievement = Achievement.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def achievement_params params.require(:achievement).permit(:when, :what) end end
jcfausto/jcfausto-rails-website
app/controllers/achievements_controller.rb
Ruby
mit
2,096
# DistantPoints[http://community.topcoder.com/stat?c=problem_statement&pm=11077] class DistantPoints def self.solution (n, k) @max = 2 ** n + 2 points = {} p = [1, 1] (k - 1).times do points[p] = true p = nextPoint(points) end p end def self.nextPoint (points) dMax = 0 nextPoints = [] 1.upto(@max - 1) do |x| 1.upto(@max - 1) do |y| p = [x, y] next if points.has_key? p d = distance(p, points) if d > dMax dMax = d nextPoints = [p] elsif d == dMax nextPoints << p end end end nextPoints.sort! do |a, b| if a[0] < b[0] -1 elsif a[0] > b[0] 1 elsif a[1] < b[1] -1 elsif a[1] > b[1] 1 else 0 end end nextPoints[0] end def self.distance (p1, points) dMin = 1.0/0.0 # infinity points.keys.each do |p2| d = Math.sqrt( ((p1[0] - p2[0]) ** 2) + ((p1[1] - p2[1]) ** 2) ) if d < dMin dMin = d end end dMin end end
erichaase/topcoder
ruby/app/DistantPoints.rb
Ruby
mit
1,107
<?php namespace PlentymarketsAdapter\ServiceBus\QueryHandler\OrderStatus; use PlentyConnector\Connector\ServiceBus\Query\FetchTransferObjectQuery; use PlentyConnector\Connector\ServiceBus\Query\QueryInterface; use PlentyConnector\Connector\ServiceBus\QueryHandler\QueryHandlerInterface; use PlentyConnector\Connector\ServiceBus\QueryType; use PlentyConnector\Connector\TransferObject\OrderStatus\OrderStatus; use PlentymarketsAdapter\Client\ClientInterface; use PlentymarketsAdapter\PlentymarketsAdapter; use PlentymarketsAdapter\ResponseParser\OrderStatus\OrderStatusResponseParserInterface; /** * Class FetchAllOrderStatusesQueryHandler */ class FetchAllOrderStatusesQueryHandler implements QueryHandlerInterface { /** * @var ClientInterface */ private $client; /** * @var OrderStatusResponseParserInterface */ private $responseParser; /** * OrderStatusResponseParserInterface constructor. * * @param ClientInterface $client * @param OrderStatusResponseParserInterface $responseParser */ public function __construct( ClientInterface $client, OrderStatusResponseParserInterface $responseParser ) { $this->client = $client; $this->responseParser = $responseParser; } /** * {@inheritdoc} */ public function supports(QueryInterface $query) { return $query instanceof FetchTransferObjectQuery && $query->getAdapterName() === PlentymarketsAdapter::NAME && $query->getObjectType() === OrderStatus::TYPE && $query->getQueryType() === QueryType::ALL; } /** * {@inheritdoc} */ public function handle(QueryInterface $query) { $elements = $this->client->getIterator('orders/statuses', ['with' => 'names']); foreach ($elements as $element) { $result = $this->responseParser->parse($element); if (null === $result) { continue; } yield $result; } } }
Pfabeck/plentymarkets-shopware-connector
Adapter/PlentymarketsAdapter/ServiceBus/QueryHandler/OrderStatus/FetchAllOrderStatusesQueryHandler.php
PHP
mit
2,062
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html from scrapy.conf import settings import pymongo from datetime import datetime from .models import PQDataModel class ParliamentSearchPipeline(object): def __init__(self): self.connection = None def process_item(self, items, spider): if spider.name == "ls_questions": questions = items['questions'] # self.insert_in_db(questions) else: raise ValueError("Invalid collection:", spider.name) return items def insert_in_db(self, questions): with PQDataModel.batch_write() as batch: records = [] for q in questions: record = PQDataModel() record.question_number = q['question_number'] record.question_origin = q['question_origin'] record.question_type = q['question_type'] record.question_session = q['question_session'] record.question_ministry = q['question_ministry'] record.question_member = q['question_member'] record.question_subject = q['question_subject'] record.question_type = q['question_type'] record.question_annex = q['question_annex'] record.question_url = q['question_url'] record.question_text = q['question_text'] record.question_url = q['question_url'] record.question_date = datetime.strptime(q['question_date'], '%d.%m.%Y') records.append(record) for record in records: batch.save(record)
mthipparthi/parliament-search
parliamentsearch/pipelines.py
Python
mit
1,789
namespace IPCUtilities.IpcPmrep.CommandObjects { public class PmrepAddDeploymentGroup: AbstractRepoObject { private string _deploymentGroupName; private string _versionNumber; private string _folderName; private string _persistentImputFile; private string _dependencyTypes; private string _dbdSeparator; public string DeploymentGroupName { get { return _deploymentGroupName; } set { _deploymentGroupName = " -p " + value; } } public string VersionNumber { get { return _versionNumber; } set { _versionNumber = " -v " + value; } } public string FolderName { get { return _folderName; } set { _folderName = " -f " + value; } } public string PersistentImputFile { get { return _persistentImputFile; } set { _persistentImputFile = " -i " + value; } } public string DependencyTypes { get { return _dependencyTypes; } set { _dependencyTypes = " -d " + value; } } public string DbdSeparator { get { return _dbdSeparator; } set { _dbdSeparator = " -s " + value; } } } }
RainManVays/IPCUtilites
IpcPmrep/CommandObjects/PmrepDeploymentGroup.cs
C#
mit
1,133
/** * Created by TC on 2016/10/10. */ import React, { Component, } from 'react' import { Image, View, ToastAndroid, ActivityIndicator, } from 'react-native' import PixelRatio from "react-native/Libraries/Utilities/PixelRatio"; class GirlComponent extends Component { constructor(props) { super(props); this.state = { imgUrl: '' } } loadImage() { this.setState({imgUrl: ''}); this.getImage(); } componentWillMount() { this.getImage(); } getImage() { fetch('http://gank.io/api/data/福利/100/1')//异步请求图片 .then((response) => { return response.json(); }) .then((responseJson) => { if (responseJson.results) { const index = Math.ceil(Math.random() * 100 - 1);//随机取一张福利图 this.setState({imgUrl: responseJson.results[index].url}); } }).catch((error) => console.error(error)) .done(); } render() { if (this.state.imgUrl.length == 0) { return ( <View style={ {flex: 1, flexDirection: 'row', justifyContent: 'center', alignItems: 'center'}}> <ActivityIndicator size='large' color='#00BCD4'/> </View> ); } else { return ( <View style={{flexDirection: 'column', flex: 1}}> <Image source={{uri: this.state.imgUrl}} style={{width: 200 * PixelRatio.get(), height: 200 * PixelRatio.get()}}/> </View> ); } } } export default GirlComponent;
huxinmin/PracticeMakesPerfect
reactNative/reactnativelearn-master/js/GirlComponent.js
JavaScript
mit
1,751
<?php header('Content-Type: image/png'); header('X-Content-Quality: '.$_GET['quality']); readfile($file);
juijs/store.jui.io
public/v2/plugins/code/preprocessor/png.php
PHP
mit
107
# frozen_string_literal: true # :reek:UtilityFunction module RubyRabbitmqJanus module Janus module Responses # Response for RSpec initializer class RSpec # Constructor to RSpec response. # Create a fake response for testing library. def initialize(type) path = RubyRabbitmqJanus::Tools::Config.instance.rspec_response @json = File.join(Dir.pwd, path, "#{type.gsub('::', '_')}.json") end # Read response json file def read JSON.parse(File.read(@json)) end # Create fake session number def session (rand * 1_000_000).to_i end # Read plugindata field def plugin read['plugindata'] end # Read data to plugindata field def plugin_data read['plugindata']['data'] end # Read data dield def data read['data'] end # Read sdp def sdp read['jsep'] end # Read sessions field def sessions read['sessions'] end # Read info field def info read['info'] end # Read fake keys def keys [546_321_963, 546_321_966] end # Read first Janusinstance in database def instance JanusInstance.first end # Read fake status to instance # # @return [Boolean] Random value def enable [True, False].sample end alias id session alias session_id session alias sender session alias handles sessions alias jsep sdp end end end end
dazzl-tv/ruby-rabbitmq-janus
lib/rrj/janus/responses/rspec.rb
Ruby
mit
1,811
export * from '../common'; export NodeBundle from './NodeBundle'; export CommonJsResolver from './CommonJsResolver';
stephenbunch/palkia
src/node/index.js
JavaScript
mit
117
import arrow import settings from . import misc from . import voting from . import comments from . import exceptions as exc def merge_pr(api, urn, pr, votes, total, threshold): """ merge a pull request, if possible, and use a nice detailed merge commit message """ pr_num = pr["number"] pr_title = pr['title'] pr_description = pr['body'] path = "/repos/{urn}/pulls/{pr}/merge".format(urn=urn, pr=pr_num) record = voting.friendly_voting_record(votes) if record: record = "Vote record:\n" + record votes_summary = formatted_votes_summary(votes, total, threshold) pr_url = "https://github.com/{urn}/pull/{pr}".format(urn=urn, pr=pr_num) title = "merging PR #{num}: {pr_title}".format( num=pr_num, pr_title=pr_title) desc = """ {pr_url}: {pr_title} Description: {pr_description} :ok_woman: PR passed {summary}. {record} """.strip().format( pr_url=pr_url, pr_title=pr_title, pr_description=pr_description, summary=votes_summary, record=record, ) data = { "commit_title": title, "commit_message": desc, "merge_method": "merge", # if some clever person attempts to submit more commits while we're # aggregating votes, this sha check will fail and no merge will occur "sha": pr["head"]["sha"], } try: resp = api("PUT", path, json=data) return resp["sha"] except HTTPError as e: resp = e.response # could not be merged if resp.status_code == 405: raise exc.CouldntMerge # someone trying to be sneaky and change their PR commits during voting elif resp.status_code == 409: raise exc.CouldntMerge else: raise def formatted_votes_summary(votes, total, threshold): vfor = sum(v for v in votes.values() if v > 0) vagainst = abs(sum(v for v in votes.values() if v < 0)) return "with a vote of {vfor} for and {vagainst} against, with a weighted total of {total:.1f} and a threshold of {threshold:.1f}" \ .strip().format(vfor=vfor, vagainst=vagainst, total=total, threshold=threshold) def formatted_votes_short_summary(votes, total, threshold): vfor = sum(v for v in votes.values() if v > 0) vagainst = abs(sum(v for v in votes.values() if v < 0)) return "vote: {vfor}-{vagainst}, weighted total: {total:.1f}, threshold: {threshold:.1f}" \ .strip().format(vfor=vfor, vagainst=vagainst, total=total, threshold=threshold) def label_pr(api, urn, pr_num, labels): """ set a pr's labels (removes old labels) """ if not isinstance(labels, (tuple, list)): labels = [labels] path = "/repos/{urn}/issues/{pr}/labels".format(urn=urn, pr=pr_num) data = labels resp = api("PUT", path, json=data) def close_pr(api, urn, pr): """ https://developer.github.com/v3/pulls/#update-a-pull-request """ path = "/repos/{urn}/pulls/{pr}".format(urn=urn, pr=pr["number"]) data = { "state": "closed", } return api("patch", path, json=data) def get_pr_last_updated(pr_data): """ a helper for finding the utc datetime of the last pr branch modifications """ repo = pr_data["head"]["repo"] if repo: dt = repo["pushed_at"] else: dt = pr_data["created_at"] return arrow.get(dt) def get_pr_comments(api, urn, pr_num): """ yield all comments on a pr, weirdly excluding the initial pr comment itself (the one the owner makes) """ params = { "per_page": settings.DEFAULT_PAGINATION } path = "/repos/{urn}/issues/{pr}/comments".format(urn=urn, pr=pr_num) comments = api("get", path, params=params) for comment in comments: yield comment def get_ready_prs(api, urn, window): """ yield mergeable, non-WIP prs that have had no modifications for longer than the voting window. these are prs that are ready to be considered for merging """ open_prs = get_open_prs(api, urn) for pr in open_prs: pr_num = pr["number"] now = arrow.utcnow() updated = get_pr_last_updated(pr) delta = (now - updated).total_seconds() is_wip = "WIP" in pr["title"] if not is_wip and delta > window: # we check if its mergeable if its outside the voting window, # because there seems to be a race where a freshly-created PR exists # in the paginated list of PRs, but 404s when trying to fetch it # directly mergeable = get_is_mergeable(api, urn, pr_num) if mergeable is True: label_pr(api, urn, pr_num, []) yield pr elif mergeable is False: label_pr(api, urn, pr_num, ["conflicts"]) if delta >= 60 * 60 * settings.PR_STALE_HOURS: comments.leave_stale_comment( api, urn, pr["number"], round(delta / 60 / 60)) close_pr(api, urn, pr) # mergeable can also be None, in which case we just skip it for now def voting_window_remaining_seconds(pr, window): now = arrow.utcnow() updated = get_pr_last_updated(pr) delta = (now - updated).total_seconds() return window - delta def is_pr_in_voting_window(pr, window): return voting_window_remaining_seconds(pr, window) <= 0 def get_pr_reviews(api, urn, pr_num): """ get all pr reviews on a pr https://help.github.com/articles/about-pull-request-reviews/ """ params = { "per_page": settings.DEFAULT_PAGINATION } path = "/repos/{urn}/pulls/{pr}/reviews".format(urn=urn, pr=pr_num) data = api("get", path, params=params) return data def get_is_mergeable(api, urn, pr_num): return get_pr(api, urn, pr_num)["mergeable"] def get_pr(api, urn, pr_num): """ helper for fetching a pr. necessary because the "mergeable" field does not exist on prs that come back from paginated endpoints, so we must fetch the pr directly """ path = "/repos/{urn}/pulls/{pr}".format(urn=urn, pr=pr_num) pr = api("get", path) return pr def get_open_prs(api, urn): params = { "state": "open", "sort": "updated", "direction": "asc", "per_page": settings.DEFAULT_PAGINATION, } path = "/repos/{urn}/pulls".format(urn=urn) data = api("get", path, params=params) return data def get_reactions_for_pr(api, urn, pr): path = "/repos/{urn}/issues/{pr}/reactions".format(urn=urn, pr=pr) params = {"per_page": settings.DEFAULT_PAGINATION} reactions = api("get", path, params=params) for reaction in reactions: yield reaction def post_accepted_status(api, urn, pr, voting_window, votes, total, threshold): sha = pr["head"]["sha"] remaining_seconds = voting_window_remaining_seconds(pr, voting_window) remaining_human = misc.seconds_to_human(remaining_seconds) votes_summary = formatted_votes_short_summary(votes, total, threshold) post_status(api, urn, sha, "success", "remaining: {time}, {summary}".format(time=remaining_human, summary=votes_summary)) def post_rejected_status(api, urn, pr, voting_window, votes, total, threshold): sha = pr["head"]["sha"] remaining_seconds = voting_window_remaining_seconds(pr, voting_window) remaining_human = misc.seconds_to_human(remaining_seconds) votes_summary = formatted_votes_short_summary(votes, total, threshold) post_status(api, urn, sha, "failure", "remaining: {time}, {summary}".format(time=remaining_human, summary=votes_summary)) def post_pending_status(api, urn, pr, voting_window, votes, total, threshold): sha = pr["head"]["sha"] remaining_seconds = voting_window_remaining_seconds(pr, voting_window) remaining_human = misc.seconds_to_human(remaining_seconds) votes_summary = formatted_votes_short_summary(votes, total, threshold) post_status(api, urn, sha, "pending", "remaining: {time}, {summary}".format(time=remaining_human, summary=votes_summary)) def post_status(api, urn, sha, state, description): """ apply an issue label to a pr """ path = "/repos/{urn}/statuses/{sha}".format(urn=urn, sha=sha) data = { "state": state, "description": description, "context": "chaosbot" } api("POST", path, json=data)
eukaryote31/chaos
github_api/prs.py
Python
mit
8,393
#!/usr/bin/env python __copyright__ = "Copyright 2013-2014, http://radical.rutgers.edu" __license__ = "MIT" import sys import radical.pilot as rp # READ: The RADICAL-Pilot documentation: # http://radicalpilot.readthedocs.org/en/latest # # Try running this example with RADICAL_PILOT_VERBOSE=debug set if # you want to see what happens behind the scenes! #------------------------------------------------------------------------------ # def pilot_state_cb (pilot, state): """ this callback is invoked on all pilot state changes """ print "[Callback]: ComputePilot '%s' state: %s." % (pilot.uid, state) if state == rp.FAILED: sys.exit (1) #------------------------------------------------------------------------------ # def unit_state_cb (unit, state): """ this callback is invoked on all unit state changes """ print "[Callback]: ComputeUnit '%s' state: %s." % (unit.uid, state) if state == rp.FAILED: sys.exit (1) # ------------------------------------------------------------------------------ # if __name__ == "__main__": # we can optionally pass session name to RP if len(sys.argv) > 1: session_name = sys.argv[1] else: session_name = None # Create a new session. No need to try/except this: if session creation # fails, there is not much we can do anyways... session = rp.Session(name=session_name) print "session id: %s" % session.uid # all other pilot code is now tried/excepted. If an exception is caught, we # can rely on the session object to exist and be valid, and we can thus tear # the whole RP stack down via a 'session.close()' call in the 'finally' # clause... try: # Add a Pilot Manager. Pilot managers manage one or more ComputePilots. pmgr = rp.PilotManager(session=session) # Register our callback with the PilotManager. This callback will get # called every time any of the pilots managed by the PilotManager # change their state. pmgr.register_callback(pilot_state_cb) # Define a X-core on stamped that runs for N minutes and # uses $HOME/radical.pilot.sandbox as sandbox directoy. pdesc = rp.ComputePilotDescription() pdesc.resource = "xsede.stampede" pdesc.runtime = 15 # N minutes pdesc.cores = 16 # X cores pdesc.project = "TG-MCB090174" # Launch the pilot. pilot = pmgr.submit_pilots(pdesc) cud_list = [] for unit_count in range(0, 4): cu = rp.ComputeUnitDescription() cu.pre_exec = ["module load python intel mvapich2 mpi4py"] cu.executable = "python" cu.arguments = ["helloworld_mpi.py"] cu.input_staging = ["helloworld_mpi.py"] # These two parameters are relevant to MPI execution: # 'cores' sets the number of cores required by the task # 'mpi' identifies the task as an MPI taskg cu.cores = 8 cu.mpi = True cud_list.append(cu) # Combine the ComputePilot, the ComputeUnits and a scheduler via # a UnitManager object. umgr = rp.UnitManager( session=session, scheduler=rp.SCHED_DIRECT_SUBMISSION) # Register our callback with the UnitManager. This callback will get # called every time any of the units managed by the UnitManager # change their state. umgr.register_callback(unit_state_cb) # Add the previously created ComputePilot to the UnitManager. umgr.add_pilots(pilot) # Submit the previously created ComputeUnit descriptions to the # PilotManager. This will trigger the selected scheduler to start # assigning ComputeUnits to the ComputePilots. units = umgr.submit_units(cud_list) # Wait for all compute units to reach a terminal state (DONE or FAILED). umgr.wait_units() if not isinstance(units, list): units = [units] for unit in units: print "* Task %s - state: %s, exit code: %s, started: %s, finished: %s, stdout: %s" \ % (unit.uid, unit.state, unit.exit_code, unit.start_time, unit.stop_time, unit.stdout) except Exception as e: # Something unexpected happened in the pilot code above print "caught Exception: %s" % e raise except (KeyboardInterrupt, SystemExit) as e: # the callback called sys.exit(), and we can here catch the # corresponding KeyboardInterrupt exception for shutdown. We also catch # SystemExit (which gets raised if the main threads exits for some other # reason). print "need to exit now: %s" % e finally: # always clean up the session, no matter if we caught an exception or # not. print "closing session" session.close () # the above is equivalent to # # session.close (cleanup=True, terminate=True) # # it will thus both clean out the session's database record, and kill # all remaining pilots (none in our example). #-------------------------------------------------------------------------------
JensTimmerman/radical.pilot
examples/running_mpi_executables.py
Python
mit
5,342
require "spec_helper" shared_examples "database adapter" do before do test_database.run <<-SQL CREATE SCHEMA foo; CREATE TABLE foo.persons ( id int, first_name varchar(255), last_name varchar(255) ); SQL end after do test_database.run <<-SQL DROP SCHEMA foo CASCADE; SQL end describe "#execute" do it "executes SQL" do adapter.execute <<-SQL INSERT INTO foo.persons VALUES (1, 'hugo', 'warzenkopp'); SQL expect(Sequel.qualify("foo", "persons")).to have_values( [ :id , :first_name , :last_name ], [ 1 , "hugo" , "warzenkopp" ] ) end end describe "#column_names" do it "returns a tables column names" do expect(adapter.column_names("foo", "persons")).to match_array([ :id, :first_name, :last_name ]) end end describe "#column_types" do it "returns a tables column names" do expect(adapter.column_types("foo", "persons")).to match({ id: 'integer', first_name: 'character varying(255)', last_name: 'character varying(255)' }) end end describe "#table_exists?" do it "returns whether a table exists" do expect(adapter.table_exists?("foo", "persons")).to eql(true) expect(adapter.table_exists?("foo", "persons200")).to eql(false) end end end
maiwald/beetle_etl
spec/adapters/shared_examples.rb
Ruby
mit
1,391
from riotwatcher import * from time import sleep import logging log = logging.getLogger('log') def getTeamOfSummoner( summonerId, game ): for p in game['participants']: if p['summonerId'] == summonerId: return p['teamId'] def getSummonerIdsOfOpponentTeam( summonerId, game ): teamId = getTeamOfSummoner(summonerId, game) summoners = [] for p in game['participants']: if p['teamId'] != teamId: summoners.append(p['summonerId']) return summoners def queryPastGameIdSets( w, summonerIds, past10 ): sets = {} rqs = 0 for id in summonerIds: response = w.get_match_list(id); matchlist = [] if 'matches' in response: matchlist = response['matches'] gamelist = [] if past10: gamelist = w.get_recent_games(id)['games'] rqs += 2 if rqs >= 8: sleep(10) rqs = 0 log.debug('matches of summoner '+str(id)+': '+str(len(matchlist))) s = set() for match in matchlist: s.add(match['matchId']) for game in gamelist: s.add(game['gameId']) sets[id] = s return sets def computeFriendship( IdSets ): searchedSets = set() friendships = {} for id in IdSets: friendships[id] = {} for id in IdSets: searchedSets.add(id) for gameId in IdSets[id]: for id2 in IdSets: if not id2 in searchedSets: if gameId in IdSets[id2]: if not id2 in friendships[id]: friendships[id][id2] = 1 if not id in friendships[id2]: friendships[id2][id] = 1 friendships[id][id2] += 1 friendships[id2][id] += 1 return friendships def computePremades( friendshipRelations ): premades = [] for id in friendshipRelations: group = set(friendshipRelations[id].keys()) group.add(id) if group not in premades: premades.append(group) finPremades = [] for group1 in premades: finGroup = group1 for group2 in premades: if group1 != group2 and len(group1 & group2) > 0: finGroup = finGroup | group2 if finGroup not in finPremades: finPremades.append(finGroup) return finPremades def getPremades( summonerName, lolAPIKey, past10 ): w = riotwatcher.RiotWatcher(lolAPIKey, default_region=riotwatcher.EUROPE_WEST) id = w.get_summoner(name=summonerName)['id'] game = w.get_current_game(id) participants = game['participants'] idToParticipantsMap = {} for p in participants: log.info(p['summonerName'].encode('utf8')+' '+str(p['summonerId'])+' '+str(p['teamId'])) idToParticipantsMap[p['summonerId']] = p log.debug(getSummonerIdsOfOpponentTeam(id,game)) gameIdSets = queryPastGameIdSets( w, getSummonerIdsOfOpponentTeam(id,game), past10 ) friendshipRelations = computeFriendship(gameIdSets) log.debug(friendshipRelations) premades = computePremades(friendshipRelations) premadesNames = [] for group in premades: groupNames = [] if len(group) > 1: for summonerId in group: groupNames.append(idToParticipantsMap[summonerId]['summonerName']) premadesNames.append(groupNames) return premadesNames
DenBaum/lolm8guesser
friendship.py
Python
mit
3,046
package org.data2semantics.mustard.rdfvault; import java.util.List; import java.util.Set; import org.data2semantics.mustard.kernels.ComputationTimeTracker; import org.data2semantics.mustard.kernels.FeatureInspector; import org.data2semantics.mustard.kernels.KernelUtils; import org.data2semantics.mustard.kernels.data.RDFData; import org.data2semantics.mustard.kernels.data.SingleDTGraph; import org.data2semantics.mustard.kernels.graphkernels.FeatureVectorKernel; import org.data2semantics.mustard.kernels.graphkernels.GraphKernel; import org.data2semantics.mustard.kernels.graphkernels.singledtgraph.DTGraphGraphListWLSubTreeKernel; import org.data2semantics.mustard.kernels.SparseVector; import org.data2semantics.mustard.rdf.RDFDataSet; import org.data2semantics.mustard.rdf.RDFUtils; import org.openrdf.model.Resource; import org.openrdf.model.Statement; public class RDFGraphListURIPrefixKernel implements GraphKernel<RDFData>, FeatureVectorKernel<RDFData>, ComputationTimeTracker { private int depth; private boolean inference; private DTGraphGraphListURIPrefixKernel kernel; private SingleDTGraph graph; public RDFGraphListURIPrefixKernel(double lambda, int depth, boolean inference, boolean normalize) { super(); this.depth = depth; this.inference = inference; kernel = new DTGraphGraphListURIPrefixKernel(lambda, depth, normalize); } public String getLabel() { return KernelUtils.createLabel(this) + "_" + kernel.getLabel(); } public void setNormalize(boolean normalize) { kernel.setNormalize(normalize); } public SparseVector[] computeFeatureVectors(RDFData data) { init(data.getDataset(), data.getInstances(), data.getBlackList()); return kernel.computeFeatureVectors(graph); } public double[][] compute(RDFData data) { init(data.getDataset(), data.getInstances(), data.getBlackList()); return kernel.compute(graph); } private void init(RDFDataSet dataset, List<Resource> instances, List<Statement> blackList) { Set<Statement> stmts = RDFUtils.getStatements4Depth(dataset, instances, depth, inference); stmts.removeAll(blackList); graph = RDFUtils.statements2Graph(stmts, RDFUtils.REGULAR_LITERALS, instances, true); } public long getComputationTime() { return kernel.getComputationTime(); } }
Data2Semantics/mustard
mustard-experiments/src/main/java/org/data2semantics/mustard/rdfvault/RDFGraphListURIPrefixKernel.java
Java
mit
2,327
<?php // Enable error reporting to help us debug issues error_reporting(E_ALL); // Start PHP sessions session_start(); require_once('./config.php'); $oToken = json_decode(file_get_contents(APP_URL . 'token.php?key=' . $_GET['key'])); define('APP_TOKEN', $oToken->token); function doPost($sMethod, $aPost = array()) { // Build the request string we are going to POST to the API server. We include some of the required params. $sPost = 'token=' . APP_TOKEN . '&method=' . $sMethod; foreach ($aPost as $sKey => $sValue) { $sPost .= '&' . $sKey . '=' . $sValue; } // Start curl request. $hCurl = curl_init(); curl_setopt($hCurl, CURLOPT_URL, APP_URL . 'api.php'); curl_setopt($hCurl, CURLOPT_HEADER, false); curl_setopt($hCurl, CURLOPT_RETURNTRANSFER, true); curl_setopt($hCurl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($hCurl, CURLOPT_POST, true); curl_setopt($hCurl, CURLOPT_POSTFIELDS, $sPost); // Run the exec $sData = curl_exec($hCurl); // Close the curl connection curl_close($hCurl); // print(APP_URL . 'api.php?' . $sPost); // Return the curl request and since we use JSON we decode it. return json_decode(trim($sData)); } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en"> <head> <title>Test Application</title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="<?php echo APP_URL; ?>static/style.php?app_id=<?php echo APP_ID; ?>" /> <script type="text/javascript"> $(document).ready(function(){ $('body').append('<iframe id="crossdomain_frame" src="<?php echo APP_URL; ?>static/crossdomain.php?height=' + document.body.scrollHeight + '&nocache=' + Math.random() + '" height="0" width="0" frameborder="0"></iframe>'); }); </script> </head> <body> <h1>Test Application</h1> <?php echo '<h3>Getting Users Information [user.getUser]</h3>'; $mReturn = doPost('user.getUser'); echo '<pre>' . print_r($mReturn, true) . '</pre>'; echo '<h3>Getting Friends [friend.getFriends]</h3>'; $mReturn = doPost('friend.getFriends'); echo '<pre>' . print_r($mReturn, true) . '</pre>'; if (isset($mReturn->output[0])) { echo '<h3>Checking if Friends with User #' . $mReturn->output[0]->user_id . ' [friend.isFriend]</h3>'; $mReturn = doPost('friend.isFriend', array('friend_user_id' => $mReturn->output[0]->user_id)); echo '<pre>' . print_r($mReturn, true) . '</pre>'; } echo '<h3>Updating Users Status [user.updateStatus]</h3>'; $mReturn = doPost('user.updateStatus', array('user_status' => 'This is a test status update from an application... [' . uniqid() . ']')); echo '<pre>' . print_r($mReturn, true) . '</pre>'; echo '<h3>Getting Photos [photo.getPhotos]</h3>'; $mReturn = doPost('photo.getPhotos'); echo '<pre>' . print_r($mReturn, true) . '</pre>'; echo '<h3>Getting New Notifications Count [notification.getNewCount]</h3>'; $mReturn = doPost('notification.getNewCount'); echo '<pre>' . print_r($mReturn, true) . '</pre>'; echo '<h3>Getting Notifications [notification.get]</h3>'; $mReturn = doPost('notification.get'); echo '<pre>' . print_r($mReturn, true) . '</pre>'; echo '<h3>Getting New Mail Count [mail.getNewCount]</h3>'; $mReturn = doPost('mail.getNewCount'); echo '<pre>' . print_r($mReturn, true) . '</pre>'; ?> </body> </html>
edbiler/BazaarCorner
tools/apps/test/index.php
PHP
mit
3,475
/*! * maptalks.snapto v0.1.11 * LICENSE : MIT * (c) 2016-2018 maptalks.org */ /*! * requires maptalks@^0.33.1 */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('maptalks')) : typeof define === 'function' && define.amd ? define(['exports', 'maptalks'], factory) : (factory((global.maptalks = global.maptalks || {}),global.maptalks)); }(this, (function (exports,maptalks) { 'use strict'; var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; function createCommonjsModule(fn, module) { return module = { exports: {} }, fn(module, module.exports), module.exports; } var quickselect$1 = createCommonjsModule(function (module, exports) { (function (global, factory) { module.exports = factory(); })(commonjsGlobal, function () { 'use strict'; function quickselect(arr, k, left, right, compare) { quickselectStep(arr, k, left || 0, right || arr.length - 1, compare || defaultCompare); } function quickselectStep(arr, k, left, right, compare) { while (right > left) { if (right - left > 600) { var n = right - left + 1; var m = k - left + 1; var z = Math.log(n); var s = 0.5 * Math.exp(2 * z / 3); var sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1); var newLeft = Math.max(left, Math.floor(k - m * s / n + sd)); var newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd)); quickselectStep(arr, k, newLeft, newRight, compare); } var t = arr[k]; var i = left; var j = right; swap(arr, left, k); if (compare(arr[right], t) > 0) swap(arr, left, right); while (i < j) { swap(arr, i, j); i++; j--; while (compare(arr[i], t) < 0) { i++; }while (compare(arr[j], t) > 0) { j--; } } if (compare(arr[left], t) === 0) swap(arr, left, j);else { j++; swap(arr, j, right); } if (j <= k) left = j + 1; if (k <= j) right = j - 1; } } function swap(arr, i, j) { var tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; } function defaultCompare(a, b) { return a < b ? -1 : a > b ? 1 : 0; } return quickselect; }); }); var index$1 = rbush$2; var default_1 = rbush$2; var quickselect = quickselect$1; function rbush$2(maxEntries, format) { if (!(this instanceof rbush$2)) return new rbush$2(maxEntries, format); // max entries in a node is 9 by default; min node fill is 40% for best performance this._maxEntries = Math.max(4, maxEntries || 9); this._minEntries = Math.max(2, Math.ceil(this._maxEntries * 0.4)); if (format) { this._initFormat(format); } this.clear(); } rbush$2.prototype = { all: function all() { return this._all(this.data, []); }, search: function search(bbox) { var node = this.data, result = [], toBBox = this.toBBox; if (!intersects(bbox, node)) return result; var nodesToSearch = [], i, len, child, childBBox; while (node) { for (i = 0, len = node.children.length; i < len; i++) { child = node.children[i]; childBBox = node.leaf ? toBBox(child) : child; if (intersects(bbox, childBBox)) { if (node.leaf) result.push(child);else if (contains(bbox, childBBox)) this._all(child, result);else nodesToSearch.push(child); } } node = nodesToSearch.pop(); } return result; }, collides: function collides(bbox) { var node = this.data, toBBox = this.toBBox; if (!intersects(bbox, node)) return false; var nodesToSearch = [], i, len, child, childBBox; while (node) { for (i = 0, len = node.children.length; i < len; i++) { child = node.children[i]; childBBox = node.leaf ? toBBox(child) : child; if (intersects(bbox, childBBox)) { if (node.leaf || contains(bbox, childBBox)) return true; nodesToSearch.push(child); } } node = nodesToSearch.pop(); } return false; }, load: function load(data) { if (!(data && data.length)) return this; if (data.length < this._minEntries) { for (var i = 0, len = data.length; i < len; i++) { this.insert(data[i]); } return this; } // recursively build the tree with the given data from scratch using OMT algorithm var node = this._build(data.slice(), 0, data.length - 1, 0); if (!this.data.children.length) { // save as is if tree is empty this.data = node; } else if (this.data.height === node.height) { // split root if trees have the same height this._splitRoot(this.data, node); } else { if (this.data.height < node.height) { // swap trees if inserted one is bigger var tmpNode = this.data; this.data = node; node = tmpNode; } // insert the small tree into the large tree at appropriate level this._insert(node, this.data.height - node.height - 1, true); } return this; }, insert: function insert(item) { if (item) this._insert(item, this.data.height - 1); return this; }, clear: function clear() { this.data = createNode([]); return this; }, remove: function remove(item, equalsFn) { if (!item) return this; var node = this.data, bbox = this.toBBox(item), path = [], indexes = [], i, parent, index, goingUp; // depth-first iterative tree traversal while (node || path.length) { if (!node) { // go up node = path.pop(); parent = path[path.length - 1]; i = indexes.pop(); goingUp = true; } if (node.leaf) { // check current node index = findItem(item, node.children, equalsFn); if (index !== -1) { // item found, remove the item and condense tree upwards node.children.splice(index, 1); path.push(node); this._condense(path); return this; } } if (!goingUp && !node.leaf && contains(node, bbox)) { // go down path.push(node); indexes.push(i); i = 0; parent = node; node = node.children[0]; } else if (parent) { // go right i++; node = parent.children[i]; goingUp = false; } else node = null; // nothing found } return this; }, toBBox: function toBBox(item) { return item; }, compareMinX: compareNodeMinX, compareMinY: compareNodeMinY, toJSON: function toJSON() { return this.data; }, fromJSON: function fromJSON(data) { this.data = data; return this; }, _all: function _all(node, result) { var nodesToSearch = []; while (node) { if (node.leaf) result.push.apply(result, node.children);else nodesToSearch.push.apply(nodesToSearch, node.children); node = nodesToSearch.pop(); } return result; }, _build: function _build(items, left, right, height) { var N = right - left + 1, M = this._maxEntries, node; if (N <= M) { // reached leaf level; return leaf node = createNode(items.slice(left, right + 1)); calcBBox(node, this.toBBox); return node; } if (!height) { // target height of the bulk-loaded tree height = Math.ceil(Math.log(N) / Math.log(M)); // target number of root entries to maximize storage utilization M = Math.ceil(N / Math.pow(M, height - 1)); } node = createNode([]); node.leaf = false; node.height = height; // split the items into M mostly square tiles var N2 = Math.ceil(N / M), N1 = N2 * Math.ceil(Math.sqrt(M)), i, j, right2, right3; multiSelect(items, left, right, N1, this.compareMinX); for (i = left; i <= right; i += N1) { right2 = Math.min(i + N1 - 1, right); multiSelect(items, i, right2, N2, this.compareMinY); for (j = i; j <= right2; j += N2) { right3 = Math.min(j + N2 - 1, right2); // pack each entry recursively node.children.push(this._build(items, j, right3, height - 1)); } } calcBBox(node, this.toBBox); return node; }, _chooseSubtree: function _chooseSubtree(bbox, node, level, path) { var i, len, child, targetNode, area, enlargement, minArea, minEnlargement; while (true) { path.push(node); if (node.leaf || path.length - 1 === level) break; minArea = minEnlargement = Infinity; for (i = 0, len = node.children.length; i < len; i++) { child = node.children[i]; area = bboxArea(child); enlargement = enlargedArea(bbox, child) - area; // choose entry with the least area enlargement if (enlargement < minEnlargement) { minEnlargement = enlargement; minArea = area < minArea ? area : minArea; targetNode = child; } else if (enlargement === minEnlargement) { // otherwise choose one with the smallest area if (area < minArea) { minArea = area; targetNode = child; } } } node = targetNode || node.children[0]; } return node; }, _insert: function _insert(item, level, isNode) { var toBBox = this.toBBox, bbox = isNode ? item : toBBox(item), insertPath = []; // find the best node for accommodating the item, saving all nodes along the path too var node = this._chooseSubtree(bbox, this.data, level, insertPath); // put the item into the node node.children.push(item); extend(node, bbox); // split on node overflow; propagate upwards if necessary while (level >= 0) { if (insertPath[level].children.length > this._maxEntries) { this._split(insertPath, level); level--; } else break; } // adjust bboxes along the insertion path this._adjustParentBBoxes(bbox, insertPath, level); }, // split overflowed node into two _split: function _split(insertPath, level) { var node = insertPath[level], M = node.children.length, m = this._minEntries; this._chooseSplitAxis(node, m, M); var splitIndex = this._chooseSplitIndex(node, m, M); var newNode = createNode(node.children.splice(splitIndex, node.children.length - splitIndex)); newNode.height = node.height; newNode.leaf = node.leaf; calcBBox(node, this.toBBox); calcBBox(newNode, this.toBBox); if (level) insertPath[level - 1].children.push(newNode);else this._splitRoot(node, newNode); }, _splitRoot: function _splitRoot(node, newNode) { // split root node this.data = createNode([node, newNode]); this.data.height = node.height + 1; this.data.leaf = false; calcBBox(this.data, this.toBBox); }, _chooseSplitIndex: function _chooseSplitIndex(node, m, M) { var i, bbox1, bbox2, overlap, area, minOverlap, minArea, index; minOverlap = minArea = Infinity; for (i = m; i <= M - m; i++) { bbox1 = distBBox(node, 0, i, this.toBBox); bbox2 = distBBox(node, i, M, this.toBBox); overlap = intersectionArea(bbox1, bbox2); area = bboxArea(bbox1) + bboxArea(bbox2); // choose distribution with minimum overlap if (overlap < minOverlap) { minOverlap = overlap; index = i; minArea = area < minArea ? area : minArea; } else if (overlap === minOverlap) { // otherwise choose distribution with minimum area if (area < minArea) { minArea = area; index = i; } } } return index; }, // sorts node children by the best axis for split _chooseSplitAxis: function _chooseSplitAxis(node, m, M) { var compareMinX = node.leaf ? this.compareMinX : compareNodeMinX, compareMinY = node.leaf ? this.compareMinY : compareNodeMinY, xMargin = this._allDistMargin(node, m, M, compareMinX), yMargin = this._allDistMargin(node, m, M, compareMinY); // if total distributions margin value is minimal for x, sort by minX, // otherwise it's already sorted by minY if (xMargin < yMargin) node.children.sort(compareMinX); }, // total margin of all possible split distributions where each node is at least m full _allDistMargin: function _allDistMargin(node, m, M, compare) { node.children.sort(compare); var toBBox = this.toBBox, leftBBox = distBBox(node, 0, m, toBBox), rightBBox = distBBox(node, M - m, M, toBBox), margin = bboxMargin(leftBBox) + bboxMargin(rightBBox), i, child; for (i = m; i < M - m; i++) { child = node.children[i]; extend(leftBBox, node.leaf ? toBBox(child) : child); margin += bboxMargin(leftBBox); } for (i = M - m - 1; i >= m; i--) { child = node.children[i]; extend(rightBBox, node.leaf ? toBBox(child) : child); margin += bboxMargin(rightBBox); } return margin; }, _adjustParentBBoxes: function _adjustParentBBoxes(bbox, path, level) { // adjust bboxes along the given tree path for (var i = level; i >= 0; i--) { extend(path[i], bbox); } }, _condense: function _condense(path) { // go through the path, removing empty nodes and updating bboxes for (var i = path.length - 1, siblings; i >= 0; i--) { if (path[i].children.length === 0) { if (i > 0) { siblings = path[i - 1].children; siblings.splice(siblings.indexOf(path[i]), 1); } else this.clear(); } else calcBBox(path[i], this.toBBox); } }, _initFormat: function _initFormat(format) { // data format (minX, minY, maxX, maxY accessors) // uses eval-type function compilation instead of just accepting a toBBox function // because the algorithms are very sensitive to sorting functions performance, // so they should be dead simple and without inner calls var compareArr = ['return a', ' - b', ';']; this.compareMinX = new Function('a', 'b', compareArr.join(format[0])); this.compareMinY = new Function('a', 'b', compareArr.join(format[1])); this.toBBox = new Function('a', 'return {minX: a' + format[0] + ', minY: a' + format[1] + ', maxX: a' + format[2] + ', maxY: a' + format[3] + '};'); } }; function findItem(item, items, equalsFn) { if (!equalsFn) return items.indexOf(item); for (var i = 0; i < items.length; i++) { if (equalsFn(item, items[i])) return i; } return -1; } // calculate node's bbox from bboxes of its children function calcBBox(node, toBBox) { distBBox(node, 0, node.children.length, toBBox, node); } // min bounding rectangle of node children from k to p-1 function distBBox(node, k, p, toBBox, destNode) { if (!destNode) destNode = createNode(null); destNode.minX = Infinity; destNode.minY = Infinity; destNode.maxX = -Infinity; destNode.maxY = -Infinity; for (var i = k, child; i < p; i++) { child = node.children[i]; extend(destNode, node.leaf ? toBBox(child) : child); } return destNode; } function extend(a, b) { a.minX = Math.min(a.minX, b.minX); a.minY = Math.min(a.minY, b.minY); a.maxX = Math.max(a.maxX, b.maxX); a.maxY = Math.max(a.maxY, b.maxY); return a; } function compareNodeMinX(a, b) { return a.minX - b.minX; } function compareNodeMinY(a, b) { return a.minY - b.minY; } function bboxArea(a) { return (a.maxX - a.minX) * (a.maxY - a.minY); } function bboxMargin(a) { return a.maxX - a.minX + (a.maxY - a.minY); } function enlargedArea(a, b) { return (Math.max(b.maxX, a.maxX) - Math.min(b.minX, a.minX)) * (Math.max(b.maxY, a.maxY) - Math.min(b.minY, a.minY)); } function intersectionArea(a, b) { var minX = Math.max(a.minX, b.minX), minY = Math.max(a.minY, b.minY), maxX = Math.min(a.maxX, b.maxX), maxY = Math.min(a.maxY, b.maxY); return Math.max(0, maxX - minX) * Math.max(0, maxY - minY); } function contains(a, b) { return a.minX <= b.minX && a.minY <= b.minY && b.maxX <= a.maxX && b.maxY <= a.maxY; } function intersects(a, b) { return b.minX <= a.maxX && b.minY <= a.maxY && b.maxX >= a.minX && b.maxY >= a.minY; } function createNode(children) { return { children: children, height: 1, leaf: true, minX: Infinity, minY: Infinity, maxX: -Infinity, maxY: -Infinity }; } // sort an array so that items come in groups of n unsorted items, with groups sorted between each other; // combines selection algorithm with binary divide & conquer approach function multiSelect(arr, left, right, n, compare) { var stack = [left, right], mid; while (stack.length) { right = stack.pop(); left = stack.pop(); if (right - left <= n) continue; mid = left + Math.ceil((right - left) / n / 2) * n; quickselect(arr, mid, left, right, compare); stack.push(left, mid, mid, right); } } index$1.default = default_1; /** * GeoJSON BBox * * @private * @typedef {[number, number, number, number]} BBox */ /** * GeoJSON Id * * @private * @typedef {(number|string)} Id */ /** * GeoJSON FeatureCollection * * @private * @typedef {Object} FeatureCollection * @property {string} type * @property {?Id} id * @property {?BBox} bbox * @property {Feature[]} features */ /** * GeoJSON Feature * * @private * @typedef {Object} Feature * @property {string} type * @property {?Id} id * @property {?BBox} bbox * @property {*} properties * @property {Geometry} geometry */ /** * GeoJSON Geometry * * @private * @typedef {Object} Geometry * @property {string} type * @property {any[]} coordinates */ /** * Callback for coordEach * * @callback coordEachCallback * @param {Array<number>} currentCoord The current coordinate being processed. * @param {number} coordIndex The current index of the coordinate being processed. * Starts at index 0. * @param {number} featureIndex The current index of the feature being processed. * @param {number} featureSubIndex The current subIndex of the feature being processed. */ /** * Iterate over coordinates in any GeoJSON object, similar to Array.forEach() * * @name coordEach * @param {(FeatureCollection|Feature|Geometry)} geojson any GeoJSON object * @param {Function} callback a method that takes (currentCoord, coordIndex, featureIndex, featureSubIndex) * @param {boolean} [excludeWrapCoord=false] whether or not to include the final coordinate of LinearRings that wraps the ring in its iteration. * @example * var features = turf.featureCollection([ * turf.point([26, 37], {"foo": "bar"}), * turf.point([36, 53], {"hello": "world"}) * ]); * * turf.coordEach(features, function (currentCoord, coordIndex, featureIndex, featureSubIndex) { * //=currentCoord * //=coordIndex * //=featureIndex * //=featureSubIndex * }); */ function coordEach$1(geojson, callback, excludeWrapCoord) { // Handles null Geometry -- Skips this GeoJSON if (geojson === null) return; var featureIndex, geometryIndex, j, k, l, geometry, stopG, coords, geometryMaybeCollection, wrapShrink = 0, coordIndex = 0, isGeometryCollection, type = geojson.type, isFeatureCollection = type === 'FeatureCollection', isFeature = type === 'Feature', stop = isFeatureCollection ? geojson.features.length : 1; // This logic may look a little weird. The reason why it is that way // is because it's trying to be fast. GeoJSON supports multiple kinds // of objects at its root: FeatureCollection, Features, Geometries. // This function has the responsibility of handling all of them, and that // means that some of the `for` loops you see below actually just don't apply // to certain inputs. For instance, if you give this just a // Point geometry, then both loops are short-circuited and all we do // is gradually rename the input until it's called 'geometry'. // // This also aims to allocate as few resources as possible: just a // few numbers and booleans, rather than any temporary arrays as would // be required with the normalization approach. for (featureIndex = 0; featureIndex < stop; featureIndex++) { geometryMaybeCollection = isFeatureCollection ? geojson.features[featureIndex].geometry : isFeature ? geojson.geometry : geojson; isGeometryCollection = geometryMaybeCollection ? geometryMaybeCollection.type === 'GeometryCollection' : false; stopG = isGeometryCollection ? geometryMaybeCollection.geometries.length : 1; for (geometryIndex = 0; geometryIndex < stopG; geometryIndex++) { var featureSubIndex = 0; geometry = isGeometryCollection ? geometryMaybeCollection.geometries[geometryIndex] : geometryMaybeCollection; // Handles null Geometry -- Skips this geometry if (geometry === null) continue; coords = geometry.coordinates; var geomType = geometry.type; wrapShrink = excludeWrapCoord && (geomType === 'Polygon' || geomType === 'MultiPolygon') ? 1 : 0; switch (geomType) { case null: break; case 'Point': callback(coords, coordIndex, featureIndex, featureSubIndex); coordIndex++; featureSubIndex++; break; case 'LineString': case 'MultiPoint': for (j = 0; j < coords.length; j++) { callback(coords[j], coordIndex, featureIndex, featureSubIndex); coordIndex++; if (geomType === 'MultiPoint') featureSubIndex++; } if (geomType === 'LineString') featureSubIndex++; break; case 'Polygon': case 'MultiLineString': for (j = 0; j < coords.length; j++) { for (k = 0; k < coords[j].length - wrapShrink; k++) { callback(coords[j][k], coordIndex, featureIndex, featureSubIndex); coordIndex++; } if (geomType === 'MultiLineString') featureSubIndex++; } if (geomType === 'Polygon') featureSubIndex++; break; case 'MultiPolygon': for (j = 0; j < coords.length; j++) { for (k = 0; k < coords[j].length; k++) { for (l = 0; l < coords[j][k].length - wrapShrink; l++) { callback(coords[j][k][l], coordIndex, featureIndex, featureSubIndex); coordIndex++; } }featureSubIndex++; } break; case 'GeometryCollection': for (j = 0; j < geometry.geometries.length; j++) { coordEach$1(geometry.geometries[j], callback, excludeWrapCoord); }break; default: throw new Error('Unknown Geometry Type'); } } } } /** * Callback for coordReduce * * The first time the callback function is called, the values provided as arguments depend * on whether the reduce method has an initialValue argument. * * If an initialValue is provided to the reduce method: * - The previousValue argument is initialValue. * - The currentValue argument is the value of the first element present in the array. * * If an initialValue is not provided: * - The previousValue argument is the value of the first element present in the array. * - The currentValue argument is the value of the second element present in the array. * * @callback coordReduceCallback * @param {*} previousValue The accumulated value previously returned in the last invocation * of the callback, or initialValue, if supplied. * @param {Array<number>} currentCoord The current coordinate being processed. * @param {number} coordIndex The current index of the coordinate being processed. * Starts at index 0, if an initialValue is provided, and at index 1 otherwise. * @param {number} featureIndex The current index of the feature being processed. * @param {number} featureSubIndex The current subIndex of the feature being processed. */ /** * Reduce coordinates in any GeoJSON object, similar to Array.reduce() * * @name coordReduce * @param {FeatureCollection|Geometry|Feature} geojson any GeoJSON object * @param {Function} callback a method that takes (previousValue, currentCoord, coordIndex) * @param {*} [initialValue] Value to use as the first argument to the first call of the callback. * @param {boolean} [excludeWrapCoord=false] whether or not to include the final coordinate of LinearRings that wraps the ring in its iteration. * @returns {*} The value that results from the reduction. * @example * var features = turf.featureCollection([ * turf.point([26, 37], {"foo": "bar"}), * turf.point([36, 53], {"hello": "world"}) * ]); * * turf.coordReduce(features, function (previousValue, currentCoord, coordIndex, featureIndex, featureSubIndex) { * //=previousValue * //=currentCoord * //=coordIndex * //=featureIndex * //=featureSubIndex * return currentCoord; * }); */ function coordReduce(geojson, callback, initialValue, excludeWrapCoord) { var previousValue = initialValue; coordEach$1(geojson, function (currentCoord, coordIndex, featureIndex, featureSubIndex) { if (coordIndex === 0 && initialValue === undefined) previousValue = currentCoord;else previousValue = callback(previousValue, currentCoord, coordIndex, featureIndex, featureSubIndex); }, excludeWrapCoord); return previousValue; } /** * Callback for propEach * * @callback propEachCallback * @param {Object} currentProperties The current properties being processed. * @param {number} featureIndex The index of the current element being processed in the * array.Starts at index 0, if an initialValue is provided, and at index 1 otherwise. */ /** * Iterate over properties in any GeoJSON object, similar to Array.forEach() * * @name propEach * @param {(FeatureCollection|Feature)} geojson any GeoJSON object * @param {Function} callback a method that takes (currentProperties, featureIndex) * @example * var features = turf.featureCollection([ * turf.point([26, 37], {foo: 'bar'}), * turf.point([36, 53], {hello: 'world'}) * ]); * * turf.propEach(features, function (currentProperties, featureIndex) { * //=currentProperties * //=featureIndex * }); */ function propEach(geojson, callback) { var i; switch (geojson.type) { case 'FeatureCollection': for (i = 0; i < geojson.features.length; i++) { callback(geojson.features[i].properties, i); } break; case 'Feature': callback(geojson.properties, 0); break; } } /** * Callback for propReduce * * The first time the callback function is called, the values provided as arguments depend * on whether the reduce method has an initialValue argument. * * If an initialValue is provided to the reduce method: * - The previousValue argument is initialValue. * - The currentValue argument is the value of the first element present in the array. * * If an initialValue is not provided: * - The previousValue argument is the value of the first element present in the array. * - The currentValue argument is the value of the second element present in the array. * * @callback propReduceCallback * @param {*} previousValue The accumulated value previously returned in the last invocation * of the callback, or initialValue, if supplied. * @param {*} currentProperties The current properties being processed. * @param {number} featureIndex The index of the current element being processed in the * array.Starts at index 0, if an initialValue is provided, and at index 1 otherwise. */ /** * Reduce properties in any GeoJSON object into a single value, * similar to how Array.reduce works. However, in this case we lazily run * the reduction, so an array of all properties is unnecessary. * * @name propReduce * @param {(FeatureCollection|Feature)} geojson any GeoJSON object * @param {Function} callback a method that takes (previousValue, currentProperties, featureIndex) * @param {*} [initialValue] Value to use as the first argument to the first call of the callback. * @returns {*} The value that results from the reduction. * @example * var features = turf.featureCollection([ * turf.point([26, 37], {foo: 'bar'}), * turf.point([36, 53], {hello: 'world'}) * ]); * * turf.propReduce(features, function (previousValue, currentProperties, featureIndex) { * //=previousValue * //=currentProperties * //=featureIndex * return currentProperties * }); */ function propReduce(geojson, callback, initialValue) { var previousValue = initialValue; propEach(geojson, function (currentProperties, featureIndex) { if (featureIndex === 0 && initialValue === undefined) previousValue = currentProperties;else previousValue = callback(previousValue, currentProperties, featureIndex); }); return previousValue; } /** * Callback for featureEach * * @callback featureEachCallback * @param {Feature<any>} currentFeature The current feature being processed. * @param {number} featureIndex The index of the current element being processed in the * array.Starts at index 0, if an initialValue is provided, and at index 1 otherwise. */ /** * Iterate over features in any GeoJSON object, similar to * Array.forEach. * * @name featureEach * @param {(FeatureCollection|Feature|Geometry)} geojson any GeoJSON object * @param {Function} callback a method that takes (currentFeature, featureIndex) * @example * var features = turf.featureCollection([ * turf.point([26, 37], {foo: 'bar'}), * turf.point([36, 53], {hello: 'world'}) * ]); * * turf.featureEach(features, function (currentFeature, featureIndex) { * //=currentFeature * //=featureIndex * }); */ function featureEach$1(geojson, callback) { if (geojson.type === 'Feature') { callback(geojson, 0); } else if (geojson.type === 'FeatureCollection') { for (var i = 0; i < geojson.features.length; i++) { callback(geojson.features[i], i); } } } /** * Callback for featureReduce * * The first time the callback function is called, the values provided as arguments depend * on whether the reduce method has an initialValue argument. * * If an initialValue is provided to the reduce method: * - The previousValue argument is initialValue. * - The currentValue argument is the value of the first element present in the array. * * If an initialValue is not provided: * - The previousValue argument is the value of the first element present in the array. * - The currentValue argument is the value of the second element present in the array. * * @callback featureReduceCallback * @param {*} previousValue The accumulated value previously returned in the last invocation * of the callback, or initialValue, if supplied. * @param {Feature} currentFeature The current Feature being processed. * @param {number} featureIndex The index of the current element being processed in the * array.Starts at index 0, if an initialValue is provided, and at index 1 otherwise. */ /** * Reduce features in any GeoJSON object, similar to Array.reduce(). * * @name featureReduce * @param {(FeatureCollection|Feature|Geometry)} geojson any GeoJSON object * @param {Function} callback a method that takes (previousValue, currentFeature, featureIndex) * @param {*} [initialValue] Value to use as the first argument to the first call of the callback. * @returns {*} The value that results from the reduction. * @example * var features = turf.featureCollection([ * turf.point([26, 37], {"foo": "bar"}), * turf.point([36, 53], {"hello": "world"}) * ]); * * turf.featureReduce(features, function (previousValue, currentFeature, featureIndex) { * //=previousValue * //=currentFeature * //=featureIndex * return currentFeature * }); */ function featureReduce(geojson, callback, initialValue) { var previousValue = initialValue; featureEach$1(geojson, function (currentFeature, featureIndex) { if (featureIndex === 0 && initialValue === undefined) previousValue = currentFeature;else previousValue = callback(previousValue, currentFeature, featureIndex); }); return previousValue; } /** * Get all coordinates from any GeoJSON object. * * @name coordAll * @param {(FeatureCollection|Feature|Geometry)} geojson any GeoJSON object * @returns {Array<Array<number>>} coordinate position array * @example * var features = turf.featureCollection([ * turf.point([26, 37], {foo: 'bar'}), * turf.point([36, 53], {hello: 'world'}) * ]); * * var coords = turf.coordAll(features); * //= [[26, 37], [36, 53]] */ function coordAll(geojson) { var coords = []; coordEach$1(geojson, function (coord) { coords.push(coord); }); return coords; } /** * Callback for geomEach * * @callback geomEachCallback * @param {Geometry} currentGeometry The current geometry being processed. * @param {number} currentIndex The index of the current element being processed in the * array. Starts at index 0, if an initialValue is provided, and at index 1 otherwise. * @param {number} currentProperties The current feature properties being processed. */ /** * Iterate over each geometry in any GeoJSON object, similar to Array.forEach() * * @name geomEach * @param {(FeatureCollection|Feature|Geometry)} geojson any GeoJSON object * @param {Function} callback a method that takes (currentGeometry, featureIndex, currentProperties) * @example * var features = turf.featureCollection([ * turf.point([26, 37], {foo: 'bar'}), * turf.point([36, 53], {hello: 'world'}) * ]); * * turf.geomEach(features, function (currentGeometry, featureIndex, currentProperties) { * //=currentGeometry * //=featureIndex * //=currentProperties * }); */ function geomEach(geojson, callback) { var i, j, g, geometry, stopG, geometryMaybeCollection, isGeometryCollection, geometryProperties, featureIndex = 0, isFeatureCollection = geojson.type === 'FeatureCollection', isFeature = geojson.type === 'Feature', stop = isFeatureCollection ? geojson.features.length : 1; // This logic may look a little weird. The reason why it is that way // is because it's trying to be fast. GeoJSON supports multiple kinds // of objects at its root: FeatureCollection, Features, Geometries. // This function has the responsibility of handling all of them, and that // means that some of the `for` loops you see below actually just don't apply // to certain inputs. For instance, if you give this just a // Point geometry, then both loops are short-circuited and all we do // is gradually rename the input until it's called 'geometry'. // // This also aims to allocate as few resources as possible: just a // few numbers and booleans, rather than any temporary arrays as would // be required with the normalization approach. for (i = 0; i < stop; i++) { geometryMaybeCollection = isFeatureCollection ? geojson.features[i].geometry : isFeature ? geojson.geometry : geojson; geometryProperties = isFeatureCollection ? geojson.features[i].properties : isFeature ? geojson.properties : {}; isGeometryCollection = geometryMaybeCollection ? geometryMaybeCollection.type === 'GeometryCollection' : false; stopG = isGeometryCollection ? geometryMaybeCollection.geometries.length : 1; for (g = 0; g < stopG; g++) { geometry = isGeometryCollection ? geometryMaybeCollection.geometries[g] : geometryMaybeCollection; // Handle null Geometry if (geometry === null) { callback(null, featureIndex, geometryProperties); continue; } switch (geometry.type) { case 'Point': case 'LineString': case 'MultiPoint': case 'Polygon': case 'MultiLineString': case 'MultiPolygon': { callback(geometry, featureIndex, geometryProperties); break; } case 'GeometryCollection': { for (j = 0; j < geometry.geometries.length; j++) { callback(geometry.geometries[j], featureIndex, geometryProperties); } break; } default: throw new Error('Unknown Geometry Type'); } } // Only increase `featureIndex` per each feature featureIndex++; } } /** * Callback for geomReduce * * The first time the callback function is called, the values provided as arguments depend * on whether the reduce method has an initialValue argument. * * If an initialValue is provided to the reduce method: * - The previousValue argument is initialValue. * - The currentValue argument is the value of the first element present in the array. * * If an initialValue is not provided: * - The previousValue argument is the value of the first element present in the array. * - The currentValue argument is the value of the second element present in the array. * * @callback geomReduceCallback * @param {*} previousValue The accumulated value previously returned in the last invocation * of the callback, or initialValue, if supplied. * @param {Geometry} currentGeometry The current Feature being processed. * @param {number} currentIndex The index of the current element being processed in the * array.Starts at index 0, if an initialValue is provided, and at index 1 otherwise. * @param {Object} currentProperties The current feature properties being processed. */ /** * Reduce geometry in any GeoJSON object, similar to Array.reduce(). * * @name geomReduce * @param {(FeatureCollection|Feature|Geometry)} geojson any GeoJSON object * @param {Function} callback a method that takes (previousValue, currentGeometry, featureIndex, currentProperties) * @param {*} [initialValue] Value to use as the first argument to the first call of the callback. * @returns {*} The value that results from the reduction. * @example * var features = turf.featureCollection([ * turf.point([26, 37], {foo: 'bar'}), * turf.point([36, 53], {hello: 'world'}) * ]); * * turf.geomReduce(features, function (previousValue, currentGeometry, featureIndex, currentProperties) { * //=previousValue * //=currentGeometry * //=featureIndex * //=currentProperties * return currentGeometry * }); */ function geomReduce(geojson, callback, initialValue) { var previousValue = initialValue; geomEach(geojson, function (currentGeometry, currentIndex, currentProperties) { if (currentIndex === 0 && initialValue === undefined) previousValue = currentGeometry;else previousValue = callback(previousValue, currentGeometry, currentIndex, currentProperties); }); return previousValue; } /** * Callback for flattenEach * * @callback flattenEachCallback * @param {Feature} currentFeature The current flattened feature being processed. * @param {number} featureIndex The index of the current element being processed in the * array. Starts at index 0, if an initialValue is provided, and at index 1 otherwise. * @param {number} featureSubIndex The subindex of the current element being processed in the * array. Starts at index 0 and increases if the flattened feature was a multi-geometry. */ /** * Iterate over flattened features in any GeoJSON object, similar to * Array.forEach. * * @name flattenEach * @param {(FeatureCollection|Feature|Geometry)} geojson any GeoJSON object * @param {Function} callback a method that takes (currentFeature, featureIndex, featureSubIndex) * @example * var features = turf.featureCollection([ * turf.point([26, 37], {foo: 'bar'}), * turf.multiPoint([[40, 30], [36, 53]], {hello: 'world'}) * ]); * * turf.flattenEach(features, function (currentFeature, featureIndex, featureSubIndex) { * //=currentFeature * //=featureIndex * //=featureSubIndex * }); */ function flattenEach(geojson, callback) { geomEach(geojson, function (geometry, featureIndex, properties) { // Callback for single geometry var type = geometry === null ? null : geometry.type; switch (type) { case null: case 'Point': case 'LineString': case 'Polygon': callback(feature(geometry, properties), featureIndex, 0); return; } var geomType; // Callback for multi-geometry switch (type) { case 'MultiPoint': geomType = 'Point'; break; case 'MultiLineString': geomType = 'LineString'; break; case 'MultiPolygon': geomType = 'Polygon'; break; } geometry.coordinates.forEach(function (coordinate, featureSubIndex) { var geom = { type: geomType, coordinates: coordinate }; callback(feature(geom, properties), featureIndex, featureSubIndex); }); }); } /** * Callback for flattenReduce * * The first time the callback function is called, the values provided as arguments depend * on whether the reduce method has an initialValue argument. * * If an initialValue is provided to the reduce method: * - The previousValue argument is initialValue. * - The currentValue argument is the value of the first element present in the array. * * If an initialValue is not provided: * - The previousValue argument is the value of the first element present in the array. * - The currentValue argument is the value of the second element present in the array. * * @callback flattenReduceCallback * @param {*} previousValue The accumulated value previously returned in the last invocation * of the callback, or initialValue, if supplied. * @param {Feature} currentFeature The current Feature being processed. * @param {number} featureIndex The index of the current element being processed in the * array.Starts at index 0, if an initialValue is provided, and at index 1 otherwise. * @param {number} featureSubIndex The subindex of the current element being processed in the * array. Starts at index 0 and increases if the flattened feature was a multi-geometry. */ /** * Reduce flattened features in any GeoJSON object, similar to Array.reduce(). * * @name flattenReduce * @param {(FeatureCollection|Feature|Geometry)} geojson any GeoJSON object * @param {Function} callback a method that takes (previousValue, currentFeature, featureIndex, featureSubIndex) * @param {*} [initialValue] Value to use as the first argument to the first call of the callback. * @returns {*} The value that results from the reduction. * @example * var features = turf.featureCollection([ * turf.point([26, 37], {foo: 'bar'}), * turf.multiPoint([[40, 30], [36, 53]], {hello: 'world'}) * ]); * * turf.flattenReduce(features, function (previousValue, currentFeature, featureIndex, featureSubIndex) { * //=previousValue * //=currentFeature * //=featureIndex * //=featureSubIndex * return currentFeature * }); */ function flattenReduce(geojson, callback, initialValue) { var previousValue = initialValue; flattenEach(geojson, function (currentFeature, featureIndex, featureSubIndex) { if (featureIndex === 0 && featureSubIndex === 0 && initialValue === undefined) previousValue = currentFeature;else previousValue = callback(previousValue, currentFeature, featureIndex, featureSubIndex); }); return previousValue; } /** * Callback for segmentEach * * @callback segmentEachCallback * @param {Feature<LineString>} currentSegment The current segment being processed. * @param {number} featureIndex The featureIndex currently being processed, starts at index 0. * @param {number} featureSubIndex The featureSubIndex currently being processed, starts at index 0. * @param {number} segmentIndex The segmentIndex currently being processed, starts at index 0. * @returns {void} */ /** * Iterate over 2-vertex line segment in any GeoJSON object, similar to Array.forEach() * (Multi)Point geometries do not contain segments therefore they are ignored during this operation. * * @param {(FeatureCollection|Feature|Geometry)} geojson any GeoJSON * @param {Function} callback a method that takes (currentSegment, featureIndex, featureSubIndex) * @returns {void} * @example * var polygon = turf.polygon([[[-50, 5], [-40, -10], [-50, -10], [-40, 5], [-50, 5]]]); * * // Iterate over GeoJSON by 2-vertex segments * turf.segmentEach(polygon, function (currentSegment, featureIndex, featureSubIndex, segmentIndex) { * //= currentSegment * //= featureIndex * //= featureSubIndex * //= segmentIndex * }); * * // Calculate the total number of segments * var total = 0; * turf.segmentEach(polygon, function () { * total++; * }); */ function segmentEach(geojson, callback) { flattenEach(geojson, function (feature, featureIndex, featureSubIndex) { var segmentIndex = 0; // Exclude null Geometries if (!feature.geometry) return; // (Multi)Point geometries do not contain segments therefore they are ignored during this operation. var type = feature.geometry.type; if (type === 'Point' || type === 'MultiPoint') return; // Generate 2-vertex line segments coordReduce(feature, function (previousCoords, currentCoord) { var currentSegment = lineString([previousCoords, currentCoord], feature.properties); callback(currentSegment, featureIndex, featureSubIndex, segmentIndex); segmentIndex++; return currentCoord; }); }); } /** * Callback for segmentReduce * * The first time the callback function is called, the values provided as arguments depend * on whether the reduce method has an initialValue argument. * * If an initialValue is provided to the reduce method: * - The previousValue argument is initialValue. * - The currentValue argument is the value of the first element present in the array. * * If an initialValue is not provided: * - The previousValue argument is the value of the first element present in the array. * - The currentValue argument is the value of the second element present in the array. * * @callback segmentReduceCallback * @param {*} [previousValue] The accumulated value previously returned in the last invocation * of the callback, or initialValue, if supplied. * @param {Feature<LineString>} [currentSegment] The current segment being processed. * @param {number} featureIndex The featureIndex currently being processed, starts at index 0. * @param {number} featureSubIndex The featureSubIndex currently being processed, starts at index 0. * @param {number} segmentIndex The segmentIndex currently being processed, starts at index 0. */ /** * Reduce 2-vertex line segment in any GeoJSON object, similar to Array.reduce() * (Multi)Point geometries do not contain segments therefore they are ignored during this operation. * * @param {(FeatureCollection|Feature|Geometry)} geojson any GeoJSON * @param {Function} callback a method that takes (previousValue, currentSegment, currentIndex) * @param {*} [initialValue] Value to use as the first argument to the first call of the callback. * @returns {void} * @example * var polygon = turf.polygon([[[-50, 5], [-40, -10], [-50, -10], [-40, 5], [-50, 5]]]); * * // Iterate over GeoJSON by 2-vertex segments * turf.segmentReduce(polygon, function (previousSegment, currentSegment, featureIndex, featureSubIndex, segmentIndex) { * //= previousSegment * //= currentSegment * //= featureIndex * //= featureSubIndex * //= segmentInex * return currentSegment * }); * * // Calculate the total number of segments * var initialValue = 0 * var total = turf.segmentReduce(polygon, function (previousValue) { * previousValue++; * return previousValue; * }, initialValue); */ function segmentReduce(geojson, callback, initialValue) { var previousValue = initialValue; var started = false; segmentEach(geojson, function (currentSegment, featureIndex, featureSubIndex, segmentIndex) { if (started === false && initialValue === undefined) previousValue = currentSegment;else previousValue = callback(previousValue, currentSegment, featureIndex, featureSubIndex, segmentIndex); started = true; }); return previousValue; } /** * Create Feature * * @private * @param {Geometry} geometry GeoJSON Geometry * @param {Object} properties Properties * @returns {Feature} GeoJSON Feature */ function feature(geometry, properties) { if (geometry === undefined) throw new Error('No geometry passed'); return { type: 'Feature', properties: properties || {}, geometry: geometry }; } /** * Create LineString * * @private * @param {Array<Array<number>>} coordinates Line Coordinates * @param {Object} properties Properties * @returns {Feature<LineString>} GeoJSON LineString Feature */ function lineString(coordinates, properties) { if (!coordinates) throw new Error('No coordinates passed'); if (coordinates.length < 2) throw new Error('Coordinates must be an array of two or more positions'); return { type: 'Feature', properties: properties || {}, geometry: { type: 'LineString', coordinates: coordinates } }; } /** * Callback for lineEach * * @callback lineEachCallback * @param {Feature<LineString>} currentLine The current LineString|LinearRing being processed. * @param {number} lineIndex The index of the current element being processed in the array, starts at index 0. * @param {number} lineSubIndex The sub-index of the current line being processed at index 0 */ /** * Iterate over line or ring coordinates in LineString, Polygon, MultiLineString, MultiPolygon Features or Geometries, * similar to Array.forEach. * * @name lineEach * @param {Geometry|Feature<LineString|Polygon|MultiLineString|MultiPolygon>} geojson object * @param {Function} callback a method that takes (currentLine, lineIndex, lineSubIndex) * @example * var mtLn = turf.multiLineString([ * turf.lineString([[26, 37], [35, 45]]), * turf.lineString([[36, 53], [38, 50], [41, 55]]) * ]); * * turf.lineEach(mtLn, function (currentLine, lineIndex) { * //=currentLine * //=lineIndex * }); */ function lineEach(geojson, callback) { // validation if (!geojson) throw new Error('geojson is required'); var type = geojson.geometry ? geojson.geometry.type : geojson.type; if (!type) throw new Error('invalid geojson'); if (type === 'FeatureCollection') throw new Error('FeatureCollection is not supported'); if (type === 'GeometryCollection') throw new Error('GeometryCollection is not supported'); var coordinates = geojson.geometry ? geojson.geometry.coordinates : geojson.coordinates; if (!coordinates) throw new Error('geojson must contain coordinates'); switch (type) { case 'LineString': callback(coordinates, 0, 0); return; case 'Polygon': case 'MultiLineString': var subIndex = 0; for (var line = 0; line < coordinates.length; line++) { if (type === 'MultiLineString') subIndex = line; callback(coordinates[line], line, subIndex); } return; case 'MultiPolygon': for (var multi = 0; multi < coordinates.length; multi++) { for (var ring = 0; ring < coordinates[multi].length; ring++) { callback(coordinates[multi][ring], ring, multi); } } return; default: throw new Error(type + ' geometry not supported'); } } /** * Callback for lineReduce * * The first time the callback function is called, the values provided as arguments depend * on whether the reduce method has an initialValue argument. * * If an initialValue is provided to the reduce method: * - The previousValue argument is initialValue. * - The currentValue argument is the value of the first element present in the array. * * If an initialValue is not provided: * - The previousValue argument is the value of the first element present in the array. * - The currentValue argument is the value of the second element present in the array. * * @callback lineReduceCallback * @param {*} previousValue The accumulated value previously returned in the last invocation * of the callback, or initialValue, if supplied. * @param {Feature<LineString>} currentLine The current LineString|LinearRing being processed. * @param {number} lineIndex The index of the current element being processed in the * array. Starts at index 0, if an initialValue is provided, and at index 1 otherwise. * @param {number} lineSubIndex The sub-index of the current line being processed at index 0 */ /** * Reduce features in any GeoJSON object, similar to Array.reduce(). * * @name lineReduce * @param {Geometry|Feature<LineString|Polygon|MultiLineString|MultiPolygon>} geojson object * @param {Function} callback a method that takes (previousValue, currentFeature, featureIndex) * @param {*} [initialValue] Value to use as the first argument to the first call of the callback. * @returns {*} The value that results from the reduction. * @example * var mtp = turf.multiPolygon([ * turf.polygon([[[12,48],[2,41],[24,38],[12,48]], [[9,44],[13,41],[13,45],[9,44]]]), * turf.polygon([[[5, 5], [0, 0], [2, 2], [4, 4], [5, 5]]]) * ]); * * turf.lineReduce(mtp, function (previousValue, currentLine, lineIndex, lineSubIndex) { * //=previousValue * //=currentLine * //=lineIndex * //=lineSubIndex * return currentLine * }, 2); */ function lineReduce(geojson, callback, initialValue) { var previousValue = initialValue; lineEach(geojson, function (currentLine, lineIndex, lineSubIndex) { if (lineIndex === 0 && initialValue === undefined) previousValue = currentLine;else previousValue = callback(previousValue, currentLine, lineIndex, lineSubIndex); }); return previousValue; } var index$3 = Object.freeze({ coordEach: coordEach$1, coordReduce: coordReduce, propEach: propEach, propReduce: propReduce, featureEach: featureEach$1, featureReduce: featureReduce, coordAll: coordAll, geomEach: geomEach, geomReduce: geomReduce, flattenEach: flattenEach, flattenReduce: flattenReduce, segmentEach: segmentEach, segmentReduce: segmentReduce, feature: feature, lineString: lineString, lineEach: lineEach, lineReduce: lineReduce }); var require$$1 = ( index$3 && undefined ) || index$3; var rbush = index$1; var meta = require$$1; var featureEach = meta.featureEach; var coordEach = meta.coordEach; /** * GeoJSON implementation of [RBush](https://github.com/mourner/rbush#rbush) spatial index. * * @name rbush * @param {number} [maxEntries=9] defines the maximum number of entries in a tree node. 9 (used by default) is a * reasonable choice for most applications. Higher value means faster insertion and slower search, and vice versa. * @returns {RBush} GeoJSON RBush * @example * var rbush = require('geojson-rbush') * var tree = rbush() */ var index = function index(maxEntries) { var tree = rbush(maxEntries); /** * [insert](https://github.com/mourner/rbush#data-format) * * @param {Feature<any>} feature insert single GeoJSON Feature * @returns {RBush} GeoJSON RBush * @example * var polygon = { * "type": "Feature", * "properties": {}, * "geometry": { * "type": "Polygon", * "coordinates": [[[-78, 41], [-67, 41], [-67, 48], [-78, 48], [-78, 41]]] * } * } * tree.insert(polygon) */ tree.insert = function (feature) { if (Array.isArray(feature)) { var bbox = feature; feature = bboxPolygon(bbox); feature.bbox = bbox; } else { feature.bbox = feature.bbox ? feature.bbox : turfBBox(feature); } return rbush.prototype.insert.call(this, feature); }; /** * [load](https://github.com/mourner/rbush#bulk-inserting-data) * * @param {BBox[]|FeatureCollection<any>} features load entire GeoJSON FeatureCollection * @returns {RBush} GeoJSON RBush * @example * var polygons = { * "type": "FeatureCollection", * "features": [ * { * "type": "Feature", * "properties": {}, * "geometry": { * "type": "Polygon", * "coordinates": [[[-78, 41], [-67, 41], [-67, 48], [-78, 48], [-78, 41]]] * } * }, * { * "type": "Feature", * "properties": {}, * "geometry": { * "type": "Polygon", * "coordinates": [[[-93, 32], [-83, 32], [-83, 39], [-93, 39], [-93, 32]]] * } * } * ] * } * tree.load(polygons) */ tree.load = function (features) { var load = []; // Load an Array of BBox if (Array.isArray(features)) { features.forEach(function (bbox) { var feature = bboxPolygon(bbox); feature.bbox = bbox; load.push(feature); }); } else { // Load FeatureCollection featureEach(features, function (feature) { feature.bbox = feature.bbox ? feature.bbox : turfBBox(feature); load.push(feature); }); } return rbush.prototype.load.call(this, load); }; /** * [remove](https://github.com/mourner/rbush#removing-data) * * @param {BBox|Feature<any>} feature remove single GeoJSON Feature * @returns {RBush} GeoJSON RBush * @example * var polygon = { * "type": "Feature", * "properties": {}, * "geometry": { * "type": "Polygon", * "coordinates": [[[-78, 41], [-67, 41], [-67, 48], [-78, 48], [-78, 41]]] * } * } * tree.remove(polygon) */ tree.remove = function (feature) { if (Array.isArray(feature)) { var bbox = feature; feature = bboxPolygon(bbox); feature.bbox = bbox; } return rbush.prototype.remove.call(this, feature); }; /** * [clear](https://github.com/mourner/rbush#removing-data) * * @returns {RBush} GeoJSON Rbush * @example * tree.clear() */ tree.clear = function () { return rbush.prototype.clear.call(this); }; /** * [search](https://github.com/mourner/rbush#search) * * @param {BBox|FeatureCollection|Feature<any>} geojson search with GeoJSON * @returns {FeatureCollection<any>} all features that intersects with the given GeoJSON. * @example * var polygon = { * "type": "Feature", * "properties": {}, * "geometry": { * "type": "Polygon", * "coordinates": [[[-78, 41], [-67, 41], [-67, 48], [-78, 48], [-78, 41]]] * } * } * tree.search(polygon) */ tree.search = function (geojson) { var features = rbush.prototype.search.call(this, this.toBBox(geojson)); return { type: 'FeatureCollection', features: features }; }; /** * [collides](https://github.com/mourner/rbush#collisions) * * @param {BBox|FeatureCollection|Feature<any>} geojson collides with GeoJSON * @returns {boolean} true if there are any items intersecting the given GeoJSON, otherwise false. * @example * var polygon = { * "type": "Feature", * "properties": {}, * "geometry": { * "type": "Polygon", * "coordinates": [[[-78, 41], [-67, 41], [-67, 48], [-78, 48], [-78, 41]]] * } * } * tree.collides(polygon) */ tree.collides = function (geojson) { return rbush.prototype.collides.call(this, this.toBBox(geojson)); }; /** * [all](https://github.com/mourner/rbush#search) * * @returns {FeatureCollection<any>} all the features in RBush * @example * tree.all() * //=FeatureCollection */ tree.all = function () { var features = rbush.prototype.all.call(this); return { type: 'FeatureCollection', features: features }; }; /** * [toJSON](https://github.com/mourner/rbush#export-and-import) * * @returns {any} export data as JSON object * @example * var exported = tree.toJSON() * //=JSON object */ tree.toJSON = function () { return rbush.prototype.toJSON.call(this); }; /** * [fromJSON](https://github.com/mourner/rbush#export-and-import) * * @param {any} json import previously exported data * @returns {RBush} GeoJSON RBush * @example * var exported = { * "children": [ * { * "type": "Feature", * "geometry": { * "type": "Point", * "coordinates": [110, 50] * }, * "properties": {}, * "bbox": [110, 50, 110, 50] * } * ], * "height": 1, * "leaf": true, * "minX": 110, * "minY": 50, * "maxX": 110, * "maxY": 50 * } * tree.fromJSON(exported) */ tree.fromJSON = function (json) { return rbush.prototype.fromJSON.call(this, json); }; /** * Converts GeoJSON to {minX, minY, maxX, maxY} schema * * @private * @param {BBox|FeatureCollectio|Feature<any>} geojson feature(s) to retrieve BBox from * @returns {Object} converted to {minX, minY, maxX, maxY} */ tree.toBBox = function (geojson) { var bbox; if (geojson.bbox) bbox = geojson.bbox;else if (Array.isArray(geojson) && geojson.length === 4) bbox = geojson;else bbox = turfBBox(geojson); return { minX: bbox[0], minY: bbox[1], maxX: bbox[2], maxY: bbox[3] }; }; return tree; }; /** * Takes a bbox and returns an equivalent {@link Polygon|polygon}. * * @private * @name bboxPolygon * @param {Array<number>} bbox extent in [minX, minY, maxX, maxY] order * @returns {Feature<Polygon>} a Polygon representation of the bounding box * @example * var bbox = [0, 0, 10, 10]; * * var poly = turf.bboxPolygon(bbox); * * //addToMap * var addToMap = [poly] */ function bboxPolygon(bbox) { var lowLeft = [bbox[0], bbox[1]]; var topLeft = [bbox[0], bbox[3]]; var topRight = [bbox[2], bbox[3]]; var lowRight = [bbox[2], bbox[1]]; var coordinates = [[lowLeft, lowRight, topRight, topLeft, lowLeft]]; return { type: 'Feature', bbox: bbox, properties: {}, geometry: { type: 'Polygon', coordinates: coordinates } }; } /** * Takes a set of features, calculates the bbox of all input features, and returns a bounding box. * * @private * @name bbox * @param {FeatureCollection|Feature<any>} geojson input features * @returns {Array<number>} bbox extent in [minX, minY, maxX, maxY] order * @example * var line = turf.lineString([[-74, 40], [-78, 42], [-82, 35]]); * var bbox = turf.bbox(line); * var bboxPolygon = turf.bboxPolygon(bbox); * * //addToMap * var addToMap = [line, bboxPolygon] */ function turfBBox(geojson) { var bbox = [Infinity, Infinity, -Infinity, -Infinity]; coordEach(geojson, function (coord) { if (bbox[0] > coord[0]) bbox[0] = coord[0]; if (bbox[1] > coord[1]) bbox[1] = coord[1]; if (bbox[2] < coord[0]) bbox[2] = coord[0]; if (bbox[3] < coord[1]) bbox[3] = coord[1]; }); return bbox; } function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults(subClass, superClass); } var options = { 'mode': 'line', 'tolerance': 10, 'symbol': { 'markerType': 'ellipse', 'markerFill': '#0f89f5', 'markerLineColor': '#fff', 'markerLineWidth': 2, 'markerLineOpacity': 1, 'markerWidth': 15, 'markerHeight': 15 } }; /** * A snap tool used for mouse point to adsorb geometries, it extends maptalks.Class. * * Thanks to rbush's author, this pluging has used the rbush to inspect surrounding geometries within tolerance(https://github.com/mourner/rbush) * * @author liubgithub(https://github.com/liubgithub) * * MIT License */ var SnapTool = function (_maptalks$Class) { _inherits(SnapTool, _maptalks$Class); function SnapTool(options) { _classCallCheck(this, SnapTool); var _this = _possibleConstructorReturn(this, _maptalks$Class.call(this, options)); _this.tree = index(); return _this; } SnapTool.prototype.getMode = function getMode() { this._mode = !this._mode ? this.options['mode'] : this._mode; if (this._checkMode(this._mode)) { return this._mode; } else { throw new Error('snap mode is invalid'); } }; SnapTool.prototype.setMode = function setMode(mode) { if (this._checkMode(this._mode)) { this._mode = mode; if (this.snaplayer) { if (this.snaplayer instanceof Array) { var _ref; this.allLayersGeometries = []; this.snaplayer.forEach(function (tempLayer, index$$1) { var tempGeometries = tempLayer.getGeometries(); this.allLayersGeometries[index$$1] = this._compositGeometries(tempGeometries); }.bind(this)); this.allGeometries = (_ref = []).concat.apply(_ref, this.allLayersGeometries); } else { var geometries = this.snaplayer.getGeometries(); this.allGeometries = this._compositGeometries(geometries); } } } else { throw new Error('snap mode is invalid'); } }; /** * @param {Map} map object * When using the snap tool, you should add it to a map firstly.the enable method excute default */ SnapTool.prototype.addTo = function addTo(map) { var id = maptalks.INTERNAL_LAYER_PREFIX + '_snapto'; this._mousemoveLayer = new maptalks.VectorLayer(id).addTo(map); this._map = map; this.allGeometries = []; this.enable(); }; SnapTool.prototype.remove = function remove() { this.disable(); if (this._mousemoveLayer) { this._mousemoveLayer.remove(); delete this._mousemoveLayer; } }; SnapTool.prototype.getMap = function getMap() { return this._map; }; /** * @param {String} snap mode * mode should be either 'point' or 'line' */ SnapTool.prototype._checkMode = function _checkMode(mode) { if (mode === 'point' || mode === 'line') { return true; } else { return false; } }; /** * Start snap interaction */ SnapTool.prototype.enable = function enable() { var map = this.getMap(); if (this.snaplayer) { if (this.snaplayer instanceof Array) { var _ref2; this.allLayersGeometries = []; this.snaplayer.forEach(function (tempLayer, index$$1) { var tempGeometries = tempLayer.getGeometries(); this.allLayersGeometries[index$$1] = this._compositGeometries(tempGeometries); }.bind(this)); this.allGeometries = (_ref2 = []).concat.apply(_ref2, this.allLayersGeometries); } else { var geometries = this.snaplayer.getGeometries(); this.allGeometries = this._compositGeometries(geometries); } } if (this.allGeometries) { if (!this._mousemove) { this._registerEvents(map); } if (this._mousemoveLayer) { this._mousemoveLayer.show(); } } else { throw new Error('you should set geometries which are snapped to firstly!'); } }; /** * End snap interaction */ SnapTool.prototype.disable = function disable() { var map = this.getMap(); map.off('mousemove touchstart', this._mousemove); map.off('mousedown', this._mousedown, this); map.off('mouseup', this._mouseup, this); if (this._mousemoveLayer) { this._mousemoveLayer.hide(); } delete this._mousemove; this.allGeometries = []; }; /** * @param {Geometry||Array<Geometry>} geometries to snap to * Set geomeries to an array for snapping to */ SnapTool.prototype.setGeometries = function setGeometries(geometries) { geometries = geometries instanceof Array ? geometries : [geometries]; this.allGeometries = this._compositGeometries(geometries); }; /** * @param {Layer||maptalk.VectorLayer||Array.<Layer>||Array.<maptalk.VectorLayer>} layer to snap to * Set layer for snapping to */ SnapTool.prototype.setLayer = function setLayer(layer) { if (layer instanceof Array) { var _ref5; this.snaplayer = []; this.allLayersGeometries = []; layer.forEach(function (tempLayer, index$$1) { if (tempLayer instanceof maptalks.VectorLayer) { this.snaplayer.push(tempLayer); var tempGeometries = tempLayer.getGeometries(); this.allLayersGeometries[index$$1] = this._compositGeometries(tempGeometries); tempLayer.on('addgeo', function () { var _ref3; var tempGeometries = this.snaplayer[index$$1].getGeometries(); this.allLayersGeometries[index$$1] = this._compositGeometries(tempGeometries); this.allGeometries = (_ref3 = []).concat.apply(_ref3, this.allLayersGeometries); }, this); tempLayer.on('clear', function () { var _ref4; this.allLayersGeometries.splice(index$$1, 1); this.allGeometries = (_ref4 = []).concat.apply(_ref4, this.allLayersGeometries); }, this); } }.bind(this)); this.allGeometries = (_ref5 = []).concat.apply(_ref5, this.allLayersGeometries); this._mousemoveLayer.bringToFront(); } else if (layer instanceof maptalks.VectorLayer) { var geometries = layer.getGeometries(); this.snaplayer = layer; this.allGeometries = this._compositGeometries(geometries); layer.on('addgeo', function () { var geometries = this.snaplayer.getGeometries(); this.allGeometries = this._compositGeometries(geometries); }, this); this.snaplayer.on('clear', function () { this._clearGeometries(); }, this); this._mousemoveLayer.bringToFront(); } }; /** * @param {drawTool||maptalks.DrawTool} drawing tool * When interacting with a drawtool, you should bind the drawtool object to this snapto tool */ SnapTool.prototype.bindDrawTool = function bindDrawTool(drawTool) { var _this2 = this; if (drawTool instanceof maptalks.DrawTool) { drawTool.on('drawstart', function (e) { if (_this2.snapPoint) { _this2._resetCoordinates(e.target._geometry, _this2.snapPoint); _this2._resetClickPoint(e.target._clickCoords, _this2.snapPoint); } }, this); drawTool.on('mousemove', function (e) { if (_this2.snapPoint) { var mode = e.target.getMode(); var map = e.target.getMap(); if (mode === 'circle' || mode === 'freeHandCircle') { var radius = map.computeLength(e.target._geometry.getCenter(), _this2.snapPoint); e.target._geometry.setRadius(radius); } else if (mode === 'ellipse' || mode === 'freeHandEllipse') { var center = e.target._geometry.getCenter(); var rx = map.computeLength(center, new maptalks.Coordinate({ x: _this2.snapPoint.x, y: center.y })); var ry = map.computeLength(center, new maptalks.Coordinate({ x: center.x, y: _this2.snapPoint.y })); e.target._geometry.setWidth(rx * 2); e.target._geometry.setHeight(ry * 2); } else if (mode === 'rectangle' || mode === 'freeHandRectangle') { var containerPoint = map.coordToContainerPoint(new maptalks.Coordinate({ x: _this2.snapPoint.x, y: _this2.snapPoint.y })); var firstClick = map.coordToContainerPoint(e.target._geometry.getFirstCoordinate()); var ring = [[firstClick.x, firstClick.y], [containerPoint.x, firstClick.y], [containerPoint.x, containerPoint.y], [firstClick.x, containerPoint.y]]; e.target._geometry.setCoordinates(ring.map(function (c) { return map.containerPointToCoord(new maptalks.Point(c)); })); } else { _this2._resetCoordinates(e.target._geometry, _this2.snapPoint); } } }, this); drawTool.on('drawvertex', function (e) { if (_this2.snapPoint) { _this2._resetCoordinates(e.target._geometry, _this2.snapPoint); _this2._resetClickPoint(e.target._clickCoords, _this2.snapPoint); } }, this); drawTool.on('drawend', function (e) { if (_this2.snapPoint) { var mode = e.target.getMode(); var map = e.target.getMap(); var geometry = e.geometry; if (mode === 'circle' || mode === 'freeHandCircle') { var radius = map.computeLength(e.target._geometry.getCenter(), _this2.snapPoint); geometry.setRadius(radius); } else if (mode === 'ellipse' || mode === 'freeHandEllipse') { var center = geometry.getCenter(); var rx = map.computeLength(center, new maptalks.Coordinate({ x: _this2.snapPoint.x, y: center.y })); var ry = map.computeLength(center, new maptalks.Coordinate({ x: center.x, y: _this2.snapPoint.y })); geometry.setWidth(rx * 2); geometry.setHeight(ry * 2); } else if (mode === 'rectangle' || mode === 'freeHandRectangle') { var containerPoint = map.coordToContainerPoint(new maptalks.Coordinate({ x: _this2.snapPoint.x, y: _this2.snapPoint.y })); var firstClick = map.coordToContainerPoint(geometry.getFirstCoordinate()); var ring = [[firstClick.x, firstClick.y], [containerPoint.x, firstClick.y], [containerPoint.x, containerPoint.y], [firstClick.x, containerPoint.y]]; geometry.setCoordinates(ring.map(function (c) { return map.containerPointToCoord(new maptalks.Point(c)); })); } else { _this2._resetCoordinates(geometry, _this2.snapPoint); } } }, this); } }; SnapTool.prototype._resetCoordinates = function _resetCoordinates(geometry, snapPoint) { if (!geometry) return geometry; var coords = geometry.getCoordinates(); if (geometry instanceof maptalks.Polygon) { if (geometry instanceof maptalks.Circle) { return geometry; } var coordinates = coords[0]; if (coordinates instanceof Array && coordinates.length > 2) { coordinates[coordinates.length - 2].x = snapPoint.x; coordinates[coordinates.length - 2].y = snapPoint.y; } } else if (coords instanceof Array) { coords[coords.length - 1].x = snapPoint.x; coords[coords.length - 1].y = snapPoint.y; } else if (coords instanceof maptalks.Coordinate) { coords.x = snapPoint.x; coords.y = snapPoint.y; } geometry.setCoordinates(coords); return geometry; }; SnapTool.prototype._resetClickPoint = function _resetClickPoint(clickCoords, snapPoint) { if (!clickCoords) return; clickCoords[clickCoords.length - 1].x = snapPoint.x; clickCoords[clickCoords.length - 1].y = snapPoint.y; }; SnapTool.prototype._addGeometries = function _addGeometries(geometries) { geometries = geometries instanceof Array ? geometries : [geometries]; var addGeometries = this._compositGeometries(geometries); this.allGeometries = this.allGeometries.concat(addGeometries); }; SnapTool.prototype._clearGeometries = function _clearGeometries() { this.addGeometries = []; }; /** * @param {Coordinate} mouse's coordinate on map * Using a point to inspect the surrounding geometries */ SnapTool.prototype._prepareGeometries = function _prepareGeometries(coordinate) { if (this.allGeometries) { var allGeoInGeojson = this.allGeometries; this.tree.clear(); this.tree.load({ 'type': 'FeatureCollection', 'features': allGeoInGeojson }); this.inspectExtent = this._createInspectExtent(coordinate); var availGeometries = this.tree.search(this.inspectExtent); return availGeometries; } return null; }; SnapTool.prototype._compositGeometries = function _compositGeometries(geometries) { var geos = []; var mode = this.getMode(); if (mode === 'point') { geos = this._compositToPoints(geometries); } else if (mode === 'line') { geos = this._compositToLines(geometries); } return geos; }; SnapTool.prototype._compositToPoints = function _compositToPoints(geometries) { var geos = []; geometries.forEach(function (geo) { geos = geos.concat(this._parserToPoints(geo)); }.bind(this)); return geos; }; SnapTool.prototype._createMarkers = function _createMarkers(coords) { var markers = []; coords.forEach(function (coord) { if (coord instanceof Array) { coord.forEach(function (_coord) { var _geo = new maptalks.Marker(_coord, { properties: {} }); _geo = _geo.toGeoJSON(); markers.push(_geo); }); } else { var _geo = new maptalks.Marker(coord, { properties: {} }); _geo = _geo.toGeoJSON(); markers.push(_geo); } }); return markers; }; SnapTool.prototype._parserToPoints = function _parserToPoints(geo) { var type = geo.getType(); var coordinates = null; if (type === 'Circle' || type === 'Ellipse') { coordinates = geo.getShell(); } else coordinates = geo.getCoordinates(); var geos = []; //two cases,one is single geometry,and another is multi geometries if (coordinates[0] instanceof Array) { coordinates.forEach(function (coords) { var _markers = this._createMarkers(coords); geos = geos.concat(_markers); }.bind(this)); } else { if (!(coordinates instanceof Array)) { coordinates = [coordinates]; } var _markers = this._createMarkers(coordinates); geos = geos.concat(_markers); } return geos; }; SnapTool.prototype._compositToLines = function _compositToLines(geometries) { var geos = []; geometries.forEach(function (geo) { switch (geo.getType()) { case 'Point': { var _geo = geo.toGeoJSON(); _geo.properties = {}; geos.push(_geo); } break; case 'LineString': case 'Polygon': geos = geos.concat(this._parserGeometries(geo, 1)); break; default: break; } }.bind(this)); return geos; }; SnapTool.prototype._parserGeometries = function _parserGeometries(geo, _len) { var coordinates = geo.getCoordinates(); var geos = []; //two cases,one is single geometry,and another is multi geometries if (coordinates[0] instanceof Array) { coordinates.forEach(function (coords) { var _lines = this._createLine(coords, _len, geo); geos = geos.concat(_lines); }.bind(this)); } else { var _lines = this._createLine(coordinates, _len, geo); geos = geos.concat(_lines); } return geos; }; SnapTool.prototype._createLine = function _createLine(coordinates, _length, geo) { var lines = []; var len = coordinates.length - _length; for (var i = 0; i < len; i++) { var line = new maptalks.LineString([coordinates[i], coordinates[i + 1]], { properties: { obj: geo } }); lines.push(line.toGeoJSON()); } return lines; }; SnapTool.prototype._createInspectExtent = function _createInspectExtent(coordinate) { var tolerance = !this.options['tolerance'] ? 10 : this.options['tolerance']; var map = this.getMap(); var zoom = map.getZoom(); var screenPoint = map.coordinateToPoint(coordinate, zoom); var lefttop = map.pointToCoordinate(new maptalks.Point([screenPoint.x - tolerance, screenPoint.y - tolerance]), zoom); var righttop = map.pointToCoordinate(new maptalks.Point([screenPoint.x + tolerance, screenPoint.y - tolerance]), zoom); var leftbottom = map.pointToCoordinate(new maptalks.Point([screenPoint.x - tolerance, screenPoint.y + tolerance]), zoom); var rightbottom = map.pointToCoordinate(new maptalks.Point([screenPoint.x + tolerance, screenPoint.y + tolerance]), zoom); return { 'type': 'Feature', 'properties': {}, 'geometry': { 'type': 'Polygon', 'coordinates': [[[lefttop.x, lefttop.y], [righttop.x, righttop.y], [rightbottom.x, rightbottom.y], [leftbottom.x, leftbottom.y]]] } }; }; /** * @param {Map} * Register mousemove event */ SnapTool.prototype._registerEvents = function _registerEvents(map) { this._needFindGeometry = true; this._mousemove = function (e) { this.mousePoint = e.coordinate; if (!this._marker) { this._marker = new maptalks.Marker(e.coordinate, { 'symbol': this.options['symbol'] }).addTo(this._mousemoveLayer); } else { this._marker.setCoordinates(e.coordinate); } //indicate find geometry if (!this._needFindGeometry) return; var availGeometries = this._findGeometry(e.coordinate); if (availGeometries.features.length > 0) { this.snapPoint = this._getSnapPoint(availGeometries); if (this.snapPoint) { this._marker.setCoordinates([this.snapPoint.x, this.snapPoint.y]); } } else { this.snapPoint = null; } }; this._mousedown = function () { this._needFindGeometry = false; }; this._mouseup = function () { this._needFindGeometry = true; }; map.on('mousemove touchstart', this._mousemove, this); map.on('mousedown', this._mousedown, this); map.on('mouseup', this._mouseup, this); }; /** * @param {Array<geometry>} available geometries which are surrounded * Calculate the distance from mouse point to every geometry */ SnapTool.prototype._setDistance = function _setDistance(geos) { var geoObjects = []; for (var i = 0; i < geos.length; i++) { var geo = geos[i]; if (geo.geometry.type === 'LineString') { var distance = this._distToPolyline(this.mousePoint, geo); //geo.properties.distance = distance; geoObjects.push({ geoObject: geo, distance: distance }); } else if (geo.geometry.type === 'Point') { var _distance = this._distToPoint(this.mousePoint, geo); //Composite an object including geometry and distance geoObjects.push({ geoObject: geo, distance: _distance }); } } return geoObjects; }; SnapTool.prototype._findNearestGeometries = function _findNearestGeometries(geos) { var geoObjects = this._setDistance(geos); geoObjects = geoObjects.sort(this._compare(geoObjects, 'distance')); return geoObjects[0]; }; SnapTool.prototype._findGeometry = function _findGeometry(coordinate) { var availGeimetries = this._prepareGeometries(coordinate); return availGeimetries; }; SnapTool.prototype._getSnapPoint = function _getSnapPoint(availGeometries) { var _nearestGeometry = this._findNearestGeometries(availGeometries.features); var snapPoint = null; if (!this._validDistance(_nearestGeometry.distance)) { return null; } //when it's point, return itself if (_nearestGeometry.geoObject.geometry.type === 'Point') { snapPoint = { x: _nearestGeometry.geoObject.geometry.coordinates[0], y: _nearestGeometry.geoObject.geometry.coordinates[1] }; } else if (_nearestGeometry.geoObject.geometry.type === 'LineString') { //when it's line,return the vertical insect point var nearestLine = this._setEquation(_nearestGeometry.geoObject); //whether k exists if (nearestLine.A === 0) { snapPoint = { x: this.mousePoint.x, y: _nearestGeometry.geoObject.geometry.coordinates[0][1] }; } else if (nearestLine.A === Infinity) { snapPoint = { x: _nearestGeometry.geoObject.geometry.coordinates[0][0], y: this.mousePoint.y }; } else { var k = nearestLine.B / nearestLine.A; var verticalLine = this._setVertiEquation(k, this.mousePoint); snapPoint = this._solveEquation(nearestLine, verticalLine); } } return snapPoint; }; //Calculate the distance from a point to a line SnapTool.prototype._distToPolyline = function _distToPolyline(point, line) { var equation = this._setEquation(line); var A = equation.A; var B = equation.B; var C = equation.C; var distance = Math.abs((A * point.x + B * point.y + C) / Math.sqrt(Math.pow(A, 2) + Math.pow(B, 2))); return distance; }; SnapTool.prototype._validDistance = function _validDistance(distance) { var map = this.getMap(); var resolution = map.getResolution(); var tolerance = this.options['tolerance']; if (distance / resolution > tolerance) { return false; } else { return true; } }; SnapTool.prototype._distToPoint = function _distToPoint(mousePoint, toPoint) { var from = [mousePoint.x, mousePoint.y]; var to = toPoint.geometry.coordinates; return Math.sqrt(Math.pow(from[0] - to[0], 2) + Math.pow(from[1] - to[1], 2)); }; //create a line's equation SnapTool.prototype._setEquation = function _setEquation(line) { var coords = line.geometry.coordinates; var from = coords[0]; var to = coords[1]; var k = Number((from[1] - to[1]) / (from[0] - to[0]).toString()); var A = k; var B = -1; var C = from[1] - k * from[0]; return { A: A, B: B, C: C }; }; SnapTool.prototype._setVertiEquation = function _setVertiEquation(k, point) { var b = point.y - k * point.x; var A = k; var B = -1; var C = b; return { A: A, B: B, C: C }; }; SnapTool.prototype._solveEquation = function _solveEquation(equationW, equationU) { var A1 = equationW.A, B1 = equationW.B, C1 = equationW.C; var A2 = equationU.A, B2 = equationU.B, C2 = equationU.C; var x = (B1 * C2 - C1 * B2) / (A1 * B2 - A2 * B1); var y = (A1 * C2 - A2 * C1) / (B1 * A2 - B2 * A1); return { x: x, y: y }; }; SnapTool.prototype._compare = function _compare(data, propertyName) { return function (object1, object2) { var value1 = object1[propertyName]; var value2 = object2[propertyName]; if (value2 < value1) { return 1; } else if (value2 > value1) { return -1; } else { return 0; } }; }; return SnapTool; }(maptalks.Class); SnapTool.mergeOptions(options); exports.SnapTool = SnapTool; Object.defineProperty(exports, '__esModule', { value: true }); typeof console !== 'undefined' && console.log('maptalks.snapto v0.1.11, requires maptalks@^0.33.1.'); })));
liubgithub/maptalks.snapto
dist/maptalks.snapto.js
JavaScript
mit
96,163
// // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2014-2015 Marius Avram, The appleseedhq Organization // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // Interface header. #include "minimizebutton.h" // Qt headers. #include <QAction> #include <QDockWidget> #include <QMouseEvent> #include <QStyle> namespace appleseed { namespace studio { // // MinimizeButton class implementation. // MinimizeButton::MinimizeButton(QDockWidget* dock_widget, QWidget* parent) : QPushButton(dock_widget->windowTitle(), parent) , m_dock_widget(dock_widget) , m_on(true) , m_minimized(false) { setObjectName("toggle_button_on"); connect( m_dock_widget->toggleViewAction(), SIGNAL(toggled(bool)), SLOT(slot_minimize())); } bool MinimizeButton::is_on() const { return m_on; } void MinimizeButton::set_fullscreen(const bool on) { if (on) { // Setting fullscreen on. m_minimized = m_on; if (!m_on) m_dock_widget->toggleViewAction()->activate(QAction::Trigger); } else { // Deactivating fullscreen. Keep state before fullscreen. if (!m_minimized) m_dock_widget->toggleViewAction()->activate(QAction::Trigger); } } void MinimizeButton::mousePressEvent(QMouseEvent* event) { if (event->buttons() & Qt::LeftButton) m_dock_widget->toggleViewAction()->activate(QAction::Trigger); } void MinimizeButton::slot_minimize() { m_on = !m_on; setObjectName(m_on ? "toggle_button_on" : "toggle_button_off"); // Force stylesheet reloading for this widget. style()->unpolish(this); style()->polish(this); } } // namespace studio } // namespace appleseed
Vertexwahn/appleseed
src/appleseed.studio/mainwindow/minimizebutton.cpp
C++
mit
2,861
window.onload=function() { var start = document.getElementById('start'); start.onclick = function () { var name = document.getElementById('Name').value; var id = document.getElementById('Id').value; var tel = document.getElementById("Tel").value; if (name == "") { alert("请输入名字"); return false; } if (!isName(name)) { alert("请输入正确的姓名") return false; } if (id =="") { alert("请输入学号"); return false; } if (!isId(id)) { alert("请输入正确学号"); return false; } if (tel == "") { alert("请输入电话号码"); return false; } if (!isTelephone(tel)) { alert("请输入正确的手机号码"); return false; } else { start.submit(); // document.getElementById("myform").submit(); // window.open("answer.html","_self"); } } function isName(obj) { var nameReg = /[\u4E00-\u9FA5]+$/; return nameReg.test(obj); } function isId(obj) { var emailReg = /^2017\d{8}$/; return emailReg.test(obj); } function isTelephone(obj) { reg = /^1[34578]\d{9}$/; return reg.test(obj); } }
StaticWalk/exam
src/main/resources/static/js/login.js
JavaScript
mit
1,412
(function (){ "use strict"; (function() { var $bordered = $('.bordered'); window.setInterval(function() { var top = window.pageYOffset || document.documentElement.scrollTop; if(top > 0) { $bordered.fadeOut('fast'); } else if(top == 0 && !$bordered.is(':visible')) { $bordered.fadeIn("fast"); } }, 200); })(); $(function() { $('.scroll').click(function(e) { e.preventDefault(); if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) { var target = $(this.hash); target = target.length ? target : $('[name=' + this.hash.slice(1) +']'); if (target.length) { $('html,body').animate({ scrollTop: target.offset().top }, 1000); return false; } } }); }); (function () { var $hash = $(location.hash); if ($hash.hasClass('modal')) { $hash.modal('show'); } })(); // // carousels intervals and disabled the keyboard support // $(document).ready(function(){ $('#backgroundCarousel').carousel({ interval: 10000000, // TODO just one slide for now keyboard : false }); $('#partnersCarousel').carousel({ interval: 4000, keyboard : false }); }); })(); (function(){ "use strict"; // // toggle popups from pricing dialog to the partners dialog // var cennik = $("#cennik"); var ponuka = $("#ponuka"); function toggle(){ cennik.modal("toggle"); ponuka.modal("toggle"); } $("#cennik button").on("click", toggle); })(); (function(){ "use strict"; // // deep linking for tracking google analytics // requested by michael, should not be also standard deep linking // function setDeeplinking(event){ window.location.hash = $(event.target).data("target"); } function clearDeeplinking(event){ window.location.hash = ""; } $("nav .menu").on("click", setDeeplinking); $("#try").on("click", setDeeplinking); $('#cennik').on('hidden.bs.modal', clearDeeplinking); $('#ponuka').on('hidden.bs.modal', clearDeeplinking); $('#kontakt').on('hidden.bs.modal', clearDeeplinking); })(); (function(){ "use strict"; // // sending emails via the rest api // $("#form1").on("click", function(e){ e.preventDefault(); sendContent( $("#formName1")[0].value, $("#formEmail1")[0].value, $("#formNote1")[0].value, $($("#events1")[0]).prop('checked'), function(){ $("#formName1").css("display", "none"); $("#form1").css("display", "none"); $("#formEmail1").css("display", "none"); $("#formNote1").css("display", "none"); $("#events1").css("display", "none"); $(".events-align label").css("display", "none"); $("#mobilethanks").css("display", "block"); } ); }); $("#form2").on("click", function(e){ e.preventDefault(); sendContent( $("#formName2")[0].value, $("#formEmail2")[0].value, $("#formNote2")[0].value, $($("#events2")[0]).prop('checked'), function emptyCallback(){} ); }); function sendContent(name, email, note, newsletter, callback){ var EMAIL_RECIPIENT = "pridajsa@halmispace.sk"; var NAME_RECIPIENT = "HalmiSpace"; var SND_EMAIL_RECIPIENT = "x+25519533291603@mail.asana.com"; var SND_NAME_RECIPIENT = "Lolovia"; if (!email){ email = ":( Uchádzač nespokytol žiadny email."; } if (!note){ note = ":( Uchádzač neposlal žiadnu poznámku."; } if (!name){ name = "Uchádzač"; } console.log("newsletter", newsletter); var wantsReceiveEmail = newsletter ? "Áno, mám záujem o newsletter." : "Nemám záujem o newsletter."; var toParam = { "email": EMAIL_RECIPIENT, "name": NAME_RECIPIENT, "type": "to" }; var message = ""; message += "Uchádzač: " + name + "<br/>"; message += "Email: " + email + "<br/>"; message += "Poznámka: " + note + "<br/>"; message += "Newsletter: " + wantsReceiveEmail + "<br/>"; var messageParam = { "from_email": "pridajsa@halmispace.sk", "to": [toParam, { "email": SND_EMAIL_RECIPIENT, "name": SND_NAME_RECIPIENT, "type": "to" }], "headers": { "Reply-To": email }, "autotext": "true", "subject": "Uchádzač o coworking: " + name, "html": message }; var opts = { url: "https://mandrillapp.com/api/1.0/messages/send.json", data: { "key": "9WZGkQuvFHBbuy-p8ZOPjQ", "message": messageParam }, type: "POST", crossDomain: true, success: function(msg){ console.info("success email message", msg[0]); }, error : function(){ alert("Vyskytla sa chyba, kontaktuj nas na pridajsa@halmispace.sk!") } }; $.ajax(opts).done(function(){ $("#formName1")[0].value = ""; $("#formEmail1")[0].value = ""; $("#formNote1")[0].value = ""; $("#formName2")[0].value = ""; $("#formEmail2")[0].value = ""; $("#formNote2")[0].value = ""; $("#thanks").addClass("active"); callback(); }); } })();
martinmaricak/HalmiCaffe
assets/javascript.js
JavaScript
mit
5,224
<!-- /. NAV SIDE --> <div id="page-wrapper" > <div id="page-inner"> <div class="row"> <div classe="col-md-12"> <h2>Admin home</h2> <h5>Welcome Admin </h5> </div> </div> <!-- /. ROW --> <hr /> <div class="row"> <div class="col-md-3 col-sm-6 col-xs-6"> <div class="panel panel-back noti-box"> <span class="icon-box bg-color-red set-icon"> <i class="fa fa-envelope-o"></i> </span> <div class="text-box" > <p class="main-text"><a href="../admin/additem"><h3></br></br></br></br></br>ADD NEW ITEM</h3> </a></p> <p class="text-muted">menu</p> </div> </div> </div> <div class="col-md-3 col-sm-6 col-xs-6"> <div class="panel panel-back noti-box"> <span class="icon-box bg-color-green set-icon"> <i class="fa fa-bars"></i> </span> <div class="text-box" > <p class="main-text"><a href="../admin/feedback"><h3></br></br></br></br></br>recent feedbacks</h3> </a></p> <p class="text-muted">Remaining</p> </div> </div> </div> <div class="col-md-3 col-sm-6 col-xs-6"> <div class="panel panel-back noti-box"> <span class="icon-box bg-color-blue set-icon"> <i class="fa fa-bell-o"></i> </span> <div class="text-box" > <p class="main-text"><a href="../admin/menu"><h3></br></br></br></br></br>view menu</h3> </a></p> <p class="text-muted">items</p> </div> </div> </div> <div class="col-md-3 col-sm-6 col-xs-6"> <div class="panel panel-back noti-box"> <span class="icon-box bg-color-brown set-icon"> <i class="fa fa-rocket"></i> </span> <div class="text-box" > <p class="main-text"><a href="../admin/custdetl"><h3></br></br></br></br></br>registered customers</h3> </a></p> <p class="text-muted">points</p> </div> </div> </div> </div> <!-- /. ROW --> <hr /> <!-- /. ROW --> <!-- /. ROW --> <!-- /. ROW --> <!-- /. ROW --> <div id="div_orders"></div> </div> <!-- /. PAGE INNER --> </div> <!-- /. PAGE WRAPPER --> </div> <!-- /. WRAPPER --> <!-- SCRIPTS -AT THE BOTOM TO REDUCE THE LOAD TIME--> <!-- JQUERY SCRIPTS --> <script src="assets/js/jquery-1.10.2.js"></script> <!-- BOOTSTRAP SCRIPTS --> <script src="assets/js/bootstrap.min.js"></script> <!-- METISMENU SCRIPTS --> <script src="assets/js/jquery.metisMenu.js"></script> <!-- MORRIS CHART SCRIPTS --> <script src="assets/js/morris/raphael-2.1.0.min.js"></script> <script src="assets/js/morris/morris.js"></script> <!-- CUSTOM SCRIPTS --> <script src="assets/js/custom.js"></script> <script> function show_orders() { var http=new XMLHttpRequest(); /*http.onreadystatechange=function() { if(http.readyState==4) { document.getElementById("div_orders").innerHTML=http.responseText; } } http.open("GET","ajax_orders.php",true); http.send();*/ } function call_orders() { setInterval(show_orders,1000); } call_orders(); </script> <body> </body>
amalkanth/waiterless_restaurant
application/views/admin/adminhome.php
PHP
mit
4,067
describe('$materialPopup service', function() { beforeEach(module('material.services.popup', 'ngAnimateMock')); function setup(options) { var popup; inject(function($materialPopup, $rootScope) { $materialPopup(options).then(function(p) { popup = p; }); $rootScope.$apply(); }); return popup; } describe('enter()', function() { it('should append to options.appendTo', inject(function($animate, $rootScope) { var parent = angular.element('<div id="parent">'); var popup = setup({ appendTo: parent, template: '<div id="element"></div>' }); popup.enter(); $rootScope.$digest(); expect($animate.queue.shift().event).toBe('enter'); expect(popup.element.parent()[0]).toBe(parent[0]); //fails })); it('should append to $rootElement by default', inject(function($rootScope, $document, $rootElement) { var popup = setup({ template: '<div id="element"></div>' }); popup.enter(); $rootScope.$digest(); expect(popup.element.parent()[0]).toBe($rootElement[0]); })); }); describe('destroy()', function() { it('should leave and then destroy scope', inject(function($rootScope, $animate) { var popup = setup({ template: '<div>' }); popup.enter(); $rootScope.$apply(); var scope = popup.element.scope(); spyOn($animate, 'leave').andCallFake(function(element, cb) { cb(); }); spyOn(scope, '$destroy'); popup.destroy(); expect($animate.leave).toHaveBeenCalled(); expect(scope.$destroy).toHaveBeenCalled(); })); }); });
stackmates/common.client.build
src/common/style/sass/material/services/popup/popup.spec.js
JavaScript
mit
1,657
/** * Created by Samuel Schmid on 23.03.14. * * Class for Database Handling * * Containing * - App Config * - Database Information * * @type {Database} */ module.exports = Database; Array.prototype.contains = function(obj) { var i = this.length; while (i--) { if (this[i] === obj) { return true; } } return false; } String.prototype.replaceAll = function(target, replacement) { return this.split(target).join(replacement); }; function Database(grunt) { this.grunt = grunt; this.appconfig = grunt.config().appconfig; this.db = this.appconfig.db; } /** * delete Database Schemes of Docs * * @param docs */ Database.prototype.deleteSchemes = function(docs) { var grunt = this.grunt; grunt.log.debug("start "); if(docs.docs.length > 0) { var firstDoc = docs.docs[0]; var rootfolder = firstDoc.schemefolder.split("/")[0]; grunt.log.debug("Database: delete files in folder:" + rootfolder); grunt.file.delete(rootfolder); } else { grunt.log.debug("Empty"); return; } } /** * create Database Schemes for Docs * * @param docs */ Database.prototype.createSchemes = function(docs) { var grunt = this.grunt; if(this.db.name === "mongodb") { if(this.db.provider === "mongoose") { grunt.log.write("start writing schemes for database " + this.db.name + " and provider "+this.db.provider + "."); var Provider = require('./providers/mongoose/mongoose-provider.js'); var provider = new Provider(grunt); for(var i=0;i<docs.docs.length;i++) { var doc = docs.docs[i]; if(doc.json.type.endsWith('.abstract')) { provider.writeAbstractScheme(doc); } } for(var i=0;i<docs.docs.length;i++) { var doc = docs.docs[i]; if(!doc.json.type.endsWith('.apidescription') && !doc.json.type.endsWith('.abstract')) { provider.writeScheme(doc); } } provider.writeLib(); } else { grunt.log.write("cannot create schemes for database " + this.db.name + ", because there we can't use the provider "+this.db.provider+" for it."); } } else { grunt.log.write("cannot create schemes for database " + this.db.name + ", because there is no provider for it."); } }
veith/restapiexpress
grunt/database/database.js
JavaScript
mit
2,478
import { getEmailTransport, initializeAdminApp } from './_internal'; import * as functions from 'firebase-functions'; import { District, GroupCreateInput, RepresentativeCreateInput } from '@civ/city-council'; import { createRandomString } from './utils'; const app = initializeAdminApp(); const db = app.database(); const auth = app.auth(); const cors = require('cors')({ origin: true }); export const createGroup = functions.https.onRequest((request, response) => { cors(request, response, () => { console.info(`Creating group for input:`); console.info(request.body); doCreateGroup(request.body as GroupCreateInput).then(groupId => { console.info(`Successfully created group ${groupId}`); response.status(201).send({ success: true, groupId }); }).catch(error => { console.error(`Error creating group: ${JSON.stringify(error)}`); console.error(error); response.status(500).send({ success: false, error }); }) }); }); export async function doCreateGroup(groupInput: GroupCreateInput) { const groupId = await pushBasicInfo(groupInput.name, groupInput.icon, groupInput.adminId); console.info(`pushed basic info - new group id: ${groupId}`); const repDataMap = groupInput.representatives.reduce((result, repData) => ({ ...result, [repData.id]: repData }), {}); console.info(`creating rep user accounts`); //create user accounts for each representative, const repPushes: Promise<{ inputId: string, outputId: string }[]> = Promise.all( groupInput.representatives.map(repData => new Promise((resolve, reject) => { return createUserAccountForRepresentative(repData, { id: groupId, name: groupInput.name }) .then(outputId => resolve({ inputId: repData.id, outputId })) .catch(err => reject(err)) }) ) ); const repIdMap: { [inputId: string]: string } = (await repPushes).reduce( (result, entry: any) => ({ ...result, [entry.inputId]: entry.outputId }), {}); console.info(`adding rep info to group`); //push representative objects (keyed by user id) to group await Promise.all(Object.keys(repIdMap) .map(inputId => addRepresentativeInfoToGroup(repIdMap[ inputId ], repDataMap[ inputId ], groupId)) ); console.info(`creating districts`); //create districts, linking to representatives by correct userId const districts = await Promise.all(groupInput.districts.map(data => new Promise((resolve, reject) => createDistrict(groupId, data.name, repIdMap[ data.representative ]) .then(id => resolve({ ...data, id })) ))); //finally, update rep user objects to attach them to their respective districts console.info('updating rep user groups'); await Promise.all(districts.map((district: District) => { let repId = repIdMap[ district.representative ]; return updateRepresentativeGroups(repId, { id: groupId, name: groupInput.name }, { id: district.id, name: district.name }) })); return groupId; } async function createDistrict(groupId: string, name: string, representative: string) { const result = await db.ref(`/group/${groupId}/districts`).push({ name, representative }); return result.key; } async function addRepresentativeInfoToGroup(repId: string, repData: RepresentativeCreateInput, groupId: string) { return await db.ref(`/group/${groupId}/representatives`).update({ [repId]: { firstName: repData.firstName, lastName: repData.lastName, icon: repData.icon, email: repData.email, title: repData.title } }) } async function pushBasicInfo(name: string, icon: string, owner: string): Promise<string> { console.info(`pushing basic info: {name: ${name}, icon: ${icon}, owner: ${owner}`); const result = await db.ref(`/group`).push({ name, icon, owner }); return result.key; } async function createUserAccountForRepresentative(input: RepresentativeCreateInput, group: { id: string, name: string }, district?: { id: string, name: string }): Promise<string> { let password = createRandomString(), userId: string; try { userId = await createAuthAccount(input.email, password); console.info('DONE creating auth account'); } catch (err) { console.error('ERROR creating auth account'); console.error(err); throw new Error(`Error creating auth account: ${JSON.stringify(err)}`); } try { await createUserPrivateEntry(userId, input.email); } catch (err) { console.error('ERROR creating user private entry'); throw new Error(`Error creating userPrivate entry: ${JSON.stringify(err)}`); } console.info('DONE creating user private entry'); try { await createUserPublicEntry(userId, input.firstName, input.lastName, input.icon); console.info('DONE creating user public entry'); } catch (err) { console.error('ERROR creating user public entry'); console.error(err); throw new Error(`Error creating userPublic entry: ${JSON.stringify(err)}`); } try { await sendRepresentativeEmail('drew@civinomics.com', password, input.firstName, group.name); console.info(`DONE sending email to ${input.email}`); } catch (err) { console.error(`ERROR sending email to ${input.email}`); console.error(err); /* if (err){ throw new Error(`Error sending representative email: ${JSON.stringify(err)}`); }*/ } console.info(`DONE creating rep account for ${input.firstName} ${input.lastName}`); return userId; async function createAuthAccount(email: string, password: string): Promise<string> { const result = await auth.createUser({ email, password, emailVerified: true }); return result.uid; } async function createUserPrivateEntry(id: string, email: string) { return await db.ref(`/user_private/${id}`).set({ email, isVerified: true }); } async function createUserPublicEntry(id: string, firstName: string, lastName: string, icon: string) { return await db.ref(`/user/${id}`).set({ firstName, lastName, icon }) } function sendRepresentativeEmail(email: string, password: string, name: string, groupName: string) { const msg = { to: email, subject: `Your new Civinomics Account`, html: ` <div> <p>Greetings, ${name}</p> <p>${groupName} has recently begun using Civinomics, and you were listed as a representative. </p> <p>A new account has been created for you - you can sign in <a href="https://civinomics.com/log-in">here</a> using the following credentials: </p> </div>g <strong>email:</strong> ${email} <strong>temporary password: </strong> ${password} </div> <div> <p> If you have any questions, don't hesitate to contact us at <a href="mailto:info@civinomics.com">info@civinomics.com</a> </p> <p>Look forward to seeing you online! </p> <p>-Team Civinomics</p> </div> ` }; return new Promise((resolve, reject) => { const transport = getEmailTransport(); transport.sendMail(msg, (err, info) => { if (err) { reject(err); return; } resolve(info); console.log(`sent: ${JSON.stringify(info)}`); }); }); } } async function updateRepresentativeGroups(repId: string, group: { id: string, name: string }, district?: { id: string, name: string }) { let obj: any = { [group.id]: { name: group.name, role: 'representative', district } }; if (district) { obj.district = { id: district.id, name: district.name } } return await db.ref(`/user/${repId}/groups`).update(obj); }
civinomics/city-council
cloud/functions/src/create-group.ts
TypeScript
mit
7,829
from django.dispatch import Signal pre_save = Signal(providing_args=['instance', 'action', ]) post_save = Signal(providing_args=['instance', 'action', ]) pre_delete = Signal(providing_args=['instance', 'action', ]) post_delete = Signal(providing_args=['instance', 'action', ])
thoas/django-sequere
sequere/contrib/timeline/signals.py
Python
mit
279
package me.coley.bmf.insn.impl; import me.coley.bmf.insn.Instruction; import me.coley.bmf.insn.OpType; public class CALOAD extends Instruction { public CALOAD() { super(OpType.ARRAY, Instruction.CALOAD, 1); } }
Col-E/Bytecode-Modification-Framework
src/main/java/me/coley/bmf/insn/impl/CALOAD.java
Java
mit
229
class MeetupEvent < ActiveRecord::Base self.primary_key = "meetup_event_id" belongs_to :meetup_group, foreign_key: "meetup_group_id" class << self def enabled where(enable_sync: true) end def from_api_response(response) start_time = LocalTime.convert(response['time'].to_i) end_time = if response['duration'].blank? start_time + 2.hours else LocalTime.convert(response['time'].to_i + response['duration'].to_i) end self.new( meetup_event_id: response['id'], meetup_group_id: response['group']['id'], meetup_last_update: response['updated'], name: response['name'], start_time: start_time, end_time: end_time, details: response, requires_sync: true ) end end def update_from(another_event) self.update_attributes( meetup_last_update: another_event.meetup_last_update, name: another_event.name, start_time: another_event.start_time, end_time: another_event.end_time, details: another_event.details, requires_sync: true ) end end
swifthand/meetup-calendar-sync
app/models/meetup_event.rb
Ruby
mit
1,271
<?php namespace Site\Bundle\PlatformBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; class SitePlatformBundle extends Bundle { }
starsea/cmp
src/Site/Bundle/PlatformBundle/SitePlatformBundle.php
PHP
mit
139
package epsi.md4.com.epsicalendar.activities; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.Toast; import java.util.List; import epsi.md4.com.epsicalendar.Common; import epsi.md4.com.epsicalendar.R; import epsi.md4.com.epsicalendar.adapters.EventItemAdapter; import epsi.md4.com.epsicalendar.beans.Event; import epsi.md4.com.epsicalendar.ws.ApiClient; import retrofit.Callback; import retrofit.Response; import retrofit.Retrofit; public class EventListActivity extends AppCompatActivity implements AdapterView.OnItemClickListener { public static final int EVENT_FORM_ACTIVITY_REQUEST_CODE = 1; public static final String TAG = EventListActivity.class.getName(); public static final String EXTRA_EVENT_ID = "EXTRA_EVENT_ID"; private ListView mList; private ApiClient mApiClient; private SharedPreferences mSharedPrefs; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Init view setContentView(R.layout.activity_event_list); // Init fields this.mList = (ListView) findViewById(R.id.event_list_view); this.mSharedPrefs = getSharedPreferences(Common.PREFS_SCOPE, Context.MODE_PRIVATE); mApiClient = new ApiClient(this); } /** * Refresh data */ private void refreshData() { mApiClient.listEvents().enqueue(new Callback<List<Event>>() { @Override public void onResponse(Response<List<Event>> response, Retrofit retrofit) { Log.v(TAG, String.format("listEvents.response: %d", response.code())); if (response.isSuccess()) { EventItemAdapter eventItemAdapter = new EventItemAdapter(EventListActivity.this, response.body()); mList.setOnItemClickListener(EventListActivity.this); mList.setAdapter(eventItemAdapter); } else { Log.e(TAG, "can't get events from api "); } } @Override public void onFailure(Throwable t) { Log.e(TAG, String.format("Error: %s", t.getMessage())); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == EventFormActivity.REQUEST_CODE) { if (resultCode == EventFormActivity.RESULT_OK) { Log.d(TAG, "new event, refreshing list"); refreshData(); } else if (resultCode == EventFormActivity.RESULT_CANCELED) { Log.d(TAG, "operation cancelled"); } } } public void onClickAddEvent(View view) { Intent intent = new Intent(EventListActivity.this, EventFormActivity.class); this.startActivityForResult(intent, EVENT_FORM_ACTIVITY_REQUEST_CODE); } @Override protected void onResume() { super.onResume(); Log.v(TAG, String.format("prefs.USER_EMAIL_KEY = %s", mSharedPrefs.getString(Common.USER_EMAIL_KEY, ""))); if (mSharedPrefs.getString(Common.USER_EMAIL_KEY, "").equals("")) { Intent intent = new Intent(this, UserFormActivity.class); startActivity(intent); } else { refreshData(); } } public void onClickDisconnect(View view) { mApiClient.logout().enqueue(new Callback<Void>() { @Override public void onResponse(Response<Void> response, Retrofit retrofit) { localDisconnect(); onResume(); } @Override public void onFailure(Throwable t) { Toast.makeText(EventListActivity.this, "Can not logout", Toast.LENGTH_SHORT).show(); Log.e(TAG, String.format("Error while logging out: %s", t.getLocalizedMessage())); } }); } private void localDisconnect() { Log.v(TAG, String.format("Clearing %s prefs", Common.PREFS_SCOPE)); SharedPreferences.Editor edit = this.mSharedPrefs.edit(); edit.clear(); edit.apply(); } /** * Listener for list item click * * @param parent * @param view * @param position * @param id */ @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Event clickedItem = (Event) parent.getItemAtPosition(position); Log.v(TAG, clickedItem.toString()); Intent intent = new Intent(this, EventItemActivity.class); intent.putExtra(EXTRA_EVENT_ID, clickedItem.getId().toString()); startActivity(intent); } }
MD4/EPSICalendar
app/src/main/java/epsi/md4/com/epsicalendar/activities/EventListActivity.java
Java
mit
5,006
package com.blamejared.compat.tcomplement.highoven; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import com.blamejared.ModTweaker; import com.blamejared.compat.mantle.RecipeMatchIIngredient; import com.blamejared.compat.tcomplement.highoven.recipes.HeatRecipeTweaker; import com.blamejared.compat.tcomplement.highoven.recipes.HighOvenFuelTweaker; import com.blamejared.compat.tcomplement.highoven.recipes.MixRecipeTweaker; import com.blamejared.compat.tconstruct.recipes.MeltingRecipeTweaker; import com.blamejared.mtlib.helpers.InputHelper; import com.blamejared.mtlib.helpers.LogHelper; import com.blamejared.mtlib.utils.BaseAction; import crafttweaker.CraftTweakerAPI; import crafttweaker.annotations.ModOnly; import crafttweaker.annotations.ZenRegister; import crafttweaker.api.item.IIngredient; import crafttweaker.api.item.IItemStack; import crafttweaker.api.liquid.ILiquidStack; import crafttweaker.mc1120.item.MCItemStack; import knightminer.tcomplement.library.TCompRegistry; import knightminer.tcomplement.library.events.TCompRegisterEvent; import net.minecraft.item.ItemStack; import net.minecraft.util.NonNullList; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import stanhebben.zenscript.annotations.Optional; import stanhebben.zenscript.annotations.ZenClass; import stanhebben.zenscript.annotations.ZenMethod; import stanhebben.zenscript.util.Pair; @ZenClass("mods.tcomplement.highoven.HighOven") @ZenRegister @ModOnly("tcomplement") public class HighOven { public static final List<IIngredient> REMOVED_FUELS = new LinkedList<>(); public static final Map<ILiquidStack, IItemStack> REMOVED_OVERRIDES = new LinkedHashMap<>(); public static final List<Pair<FluidStack, FluidStack>> REMOVED_HEAT_RECIPES = new LinkedList<>(); public static final List<Pair<FluidStack, FluidStack>> REMOVED_MIX_RECIPES = new LinkedList<>(); private static boolean init = false; private static void init() { if (!init) { MinecraftForge.EVENT_BUS.register(new HighOven()); init = true; } } /*-------------------------------------------------------------------------*\ | High Oven Fuels | \*-------------------------------------------------------------------------*/ @ZenMethod public static void removeFuel(IIngredient stack) { init(); CraftTweakerAPI.apply(new HighOven.RemoveFuel(stack)); } @ZenMethod public static void addFuel(IIngredient fuel, int burnTime, int tempRate) { init(); ModTweaker.LATE_ADDITIONS.add(new HighOven.AddFuel(fuel, burnTime, tempRate)); } private static class AddFuel extends BaseAction { private IIngredient fuel; private int time; private int rate; public AddFuel(IIngredient fuel, int time, int rate) { super("High Oven fuel"); this.fuel = fuel; this.time = time; this.rate = rate; } @Override public void apply() { TCompRegistry.registerFuel(new HighOvenFuelTweaker(new RecipeMatchIIngredient(fuel), time, rate)); } @Override public String describe() { return String.format("Adding %s as %s", this.getRecipeInfo(), this.name); } @Override public String getRecipeInfo() { return LogHelper.getStackDescription(fuel); } } private static class RemoveFuel extends BaseAction { private IIngredient fuel; public RemoveFuel(IIngredient fuel) { super("High Oven fuel"); this.fuel = fuel; }; @Override public void apply() { REMOVED_FUELS.add(fuel); } @Override public String describe() { return String.format("Removing %s as %s", this.getRecipeInfo(), this.name); } @Override public String getRecipeInfo() { return LogHelper.getStackDescription(fuel); } } /*-------------------------------------------------------------------------*\ | High Oven Melting | \*-------------------------------------------------------------------------*/ @ZenMethod public static void addMeltingOverride(ILiquidStack output, IIngredient input, @Optional int temp) { init(); ModTweaker.LATE_ADDITIONS .add(new HighOven.AddMelting(InputHelper.toFluid(output), input, (temp == 0 ? -1 : temp))); } @ZenMethod public static void removeMeltingOverride(ILiquidStack output, @Optional IItemStack input) { init(); CraftTweakerAPI.apply(new HighOven.RemoveMelting(output, input)); } private static class AddMelting extends BaseAction { private IIngredient input; private FluidStack output; private int temp; public AddMelting(FluidStack output, IIngredient input, int temp) { super("High Oven melting override"); this.input = input; this.output = output; this.temp = temp; } @Override public void apply() { if (temp > 0) { TCompRegistry.registerHighOvenOverride( new MeltingRecipeTweaker(new RecipeMatchIIngredient(input, output.amount), output, temp)); } else { TCompRegistry.registerHighOvenOverride( new MeltingRecipeTweaker(new RecipeMatchIIngredient(input, output.amount), output)); } } @Override public String describe() { return String.format("Adding %s for %s", this.name, this.getRecipeInfo()); } @Override protected String getRecipeInfo() { return LogHelper.getStackDescription(input) + ", now yields " + LogHelper.getStackDescription(output); } } private static class RemoveMelting extends BaseAction { private ILiquidStack output; private IItemStack input; public RemoveMelting(ILiquidStack output, IItemStack input) { super("High Oven melting override"); this.input = input; this.output = output; } @Override public void apply() { REMOVED_OVERRIDES.put(output, input); } @Override public String describe() { return String.format("Removing %s Recipe(s) for %s", this.name, this.getRecipeInfo()); } @Override protected String getRecipeInfo() { return LogHelper.getStackDescription(output); } } /*-------------------------------------------------------------------------*\ | High Oven Heat | \*-------------------------------------------------------------------------*/ @ZenMethod public static void removeHeatRecipe(ILiquidStack output, @Optional ILiquidStack input) { init(); CraftTweakerAPI.apply(new RemoveHeat(input, output)); } @ZenMethod public static void addHeatRecipe(ILiquidStack output, ILiquidStack input, int temp) { init(); ModTweaker.LATE_ADDITIONS .add(new HighOven.AddHeat(InputHelper.toFluid(output), InputHelper.toFluid(input), temp)); } private static class AddHeat extends BaseAction { private FluidStack output, input; private int temp; public AddHeat(FluidStack output, FluidStack input, int temp) { super("High Oven Heat"); this.output = output; this.input = input; this.temp = temp; } @Override public void apply() { TCompRegistry.registerHeatRecipe(new HeatRecipeTweaker(input, output, temp)); } @Override public String describe() { return String.format("Adding %s Recipe for %s", this.name, this.getRecipeInfo()); } @Override protected String getRecipeInfo() { return LogHelper.getStackDescription(output); } } private static class RemoveHeat extends BaseAction { private ILiquidStack input; private ILiquidStack output; public RemoveHeat(ILiquidStack input, ILiquidStack output) { super("High Oven Heat"); this.input = input; this.output = output; } @Override public void apply() { REMOVED_HEAT_RECIPES.add(new Pair<>(InputHelper.toFluid(input), InputHelper.toFluid(output))); } @Override public String describe() { return String.format("Removing %s Recipe(s) for %s", this.name, this.getRecipeInfo()); } @Override public String getRecipeInfo() { return LogHelper.getStackDescription(output) + ((input == null) ? "" : (" from " + LogHelper.getStackDescription(input))); } } /*-------------------------------------------------------------------------*\ | High Oven Mix | \*-------------------------------------------------------------------------*/ @ZenMethod public static void removeMixRecipe(ILiquidStack output, @Optional ILiquidStack input) { init(); CraftTweakerAPI.apply(new RemoveMix(output, input)); } @ZenMethod public static MixRecipeBuilder newMixRecipe(ILiquidStack output, ILiquidStack input, int temp) { init(); return new MixRecipeBuilder(output, input, temp); } @ZenMethod public static MixRecipeManager manageMixRecipe(ILiquidStack output, ILiquidStack input) { init(); return new MixRecipeManager(output, input); } private static class RemoveMix extends BaseAction { private ILiquidStack output; private ILiquidStack input; public RemoveMix(ILiquidStack output, ILiquidStack input) { super("High Oven Mix"); this.output = output; this.input = input; } @Override public void apply() { REMOVED_MIX_RECIPES.add(new Pair<>(InputHelper.toFluid(input), InputHelper.toFluid(output))); } @Override public String describe() { return String.format("Removing %s Recipe(s) for %s", this.name, this.getRecipeInfo()); } @Override protected String getRecipeInfo() { return LogHelper.getStackDescription(output) + ((input == null) ? "" : (" from " + LogHelper.getStackDescription(input))); } } /*-------------------------------------------------------------------------*\ | Event handlers | \*-------------------------------------------------------------------------*/ @SubscribeEvent public void onHighOvenFuelRegister(TCompRegisterEvent.HighOvenFuelRegisterEvent event) { if (event.getRecipe() instanceof HighOvenFuelTweaker) { return; } for (IIngredient entry : REMOVED_FUELS) { for (ItemStack fuel : event.getRecipe().getFuels()) { if (entry.matches(new MCItemStack(fuel))) { event.setCanceled(true); return; } } } } @SubscribeEvent public void onHighOvenHeatRegister(TCompRegisterEvent.HighOvenHeatRegisterEvent event) { if (event.getRecipe() instanceof HeatRecipeTweaker) { return; } else { for (Pair<FluidStack, FluidStack> entry : REMOVED_HEAT_RECIPES) { if (event.getRecipe().matches(entry.getKey(), entry.getValue())) { event.setCanceled(true); return; } } } } @SubscribeEvent public void onHighOvenMixRegister(TCompRegisterEvent.HighOvenMixRegisterEvent event) { if (event.getRecipe() instanceof MixRecipeTweaker) { return; } else { for (Pair<FluidStack, FluidStack> entry : REMOVED_MIX_RECIPES) { if (event.getRecipe().matches(entry.getKey(), entry.getValue())) { event.setCanceled(true); return; } } } } @SubscribeEvent public void onHighOvenOverrideRegister(TCompRegisterEvent.HighOvenOverrideRegisterEvent event) { if (event.getRecipe() instanceof MeltingRecipeTweaker) { return; } for (Map.Entry<ILiquidStack, IItemStack> entry : REMOVED_OVERRIDES.entrySet()) { if (event.getRecipe().getResult().isFluidEqual(((FluidStack) entry.getKey().getInternal()))) { if (entry.getValue() != null) { if (event.getRecipe().input .matches(NonNullList.withSize(1, (ItemStack) entry.getValue().getInternal())).isPresent()) { event.setCanceled(true); } } else event.setCanceled(true); } } } }
jaredlll08/ModTweaker
src/main/java/com/blamejared/compat/tcomplement/highoven/HighOven.java
Java
mit
11,580
/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.io; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; /** * InputStream that returns content in small portions. * * @since 0.12 */ public final class SlowInputStream extends InputStream { /** * Original stream. */ private final InputStream origin; /** * Ctor. * @param size The size of the array to encapsulate */ public SlowInputStream(final int size) { this(new ByteArrayInputStream(new byte[size])); } /** * Ctor. * @param stream Original stream to encapsulate and make slower */ SlowInputStream(final InputStream stream) { super(); this.origin = stream; } @Override public int read() throws IOException { final byte[] buf = new byte[1]; final int result; if (this.read(buf) < 0) { result = -1; } else { result = Byte.toUnsignedInt(buf[0]); } return result; } @Override public int read(final byte[] buf, final int offset, final int len) throws IOException { final int result; if (len > 1) { result = this.origin.read(buf, offset, len - 1); } else { result = this.origin.read(buf, offset, len); } return result; } @Override public int read(final byte[] buf) throws IOException { return this.read(buf, 0, buf.length); } }
yegor256/cactoos
src/test/java/org/cactoos/io/SlowInputStream.java
Java
mit
2,637
'use strict'; import { gl } from './Context'; import { mat4 } from 'gl-matrix'; import Camera from './Camera'; class OrthographicCamera extends Camera { constructor( { path, uniforms, background, translucence, right, top, name = 'orthographic.camera', left = -1, bottom = -1, near = 0.1, far = 1 } = {}) { super({ name, path, uniforms, background, translucence }); this.left = left; this.right = right; this.bottom = bottom; this.top = top; this.near = near; this.far = far; this.inheritance = ['Entity', 'Structure', 'Camera', 'OrthographicCamera']; this.configure(); } get left() { return this._left; } set left(left) { this._left = left; } get right() { return this._right; } set right(right) { this._right = right; } get bottom() { return this._bottom; } set bottom(bottom) { this._bottom = bottom; } get top() { return this._top; } set top(top) { this._top = top; } get near() { return this._near; } set near(near) { this._near = near; } get far() { return this._far; } set far(far) { this._far = far; } configure() { super.configure(); mat4.ortho(this.projectionMatrix, this.left, this.right, this.bottom, this.top, this.near, this.far); mat4.identity(this.modelViewMatrix); } bind(program) { super.bind(program); gl.disable(gl.DEPTH_TEST); gl.viewport(0, 0, this.right, this.top); } } export default OrthographicCamera;
allotrop3/four
src/OrthographicCamera.js
JavaScript
mit
1,846
<?php return [ /* |-------------------------------------------------------------------------- | Default Database Connection Name |-------------------------------------------------------------------------- | | Here you may specify which of the database connections below you wish | to use as your default connection for all database work. Of course | you may use many connections at once using the Database library. | */ 'default' => env('DB_CONNECTION', 'mysql'), /* |-------------------------------------------------------------------------- | Database Connections |-------------------------------------------------------------------------- | | Here are each of the database connections setup for your application. | Of course, examples of configuring each database platform that is | supported by Laravel is shown below to make development simple. | | | All database work in Laravel is done through the PHP PDO facilities | so make sure you have the driver for your particular database of | choice installed on your machine before you begin development. | */ 'connections' => [ 'sqlite' => [ 'driver' => 'sqlite', 'database' => env('DB_DATABASE', database_path('database.sqlite')), 'prefix' => '', ], 'mysql' => [ 'driver' => 'mysql', 'host' => env('DB_HOST', '127.0.0.1'), 'port' => env('DB_PORT', '3306'), 'database' => env('DB_DATABASE', 'forge'), 'username' => env('DB_USERNAME', 'forge'), 'password' => env('DB_PASSWORD', ''), 'unix_socket' => env('DB_SOCKET', ''), 'charset' => 'utf8mb4', 'collation' => 'utf8mb4_unicode_ci', 'prefix' => '', 'strict' => true, 'engine' => null, ], 'testing' => [ 'driver' => 'mysql', 'host' => env('DB_TEST_HOST', 'localhost'), 'database' => env('DB_TEST_DATABASE', 'homestead_test'), 'username' => env('DB_TEST_USERNAME', 'homestead'), 'password' => env('DB_TEST_PASSWORD', 'secret'), 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', 'prefix' => '', 'strict' => false, ], 'pgsql' => [ 'driver' => 'pgsql', 'port' => env('DB_PORT', '5432'), 'host' => parse_url(getenv("DATABASE_URL"))["host"], 'database' => substr(parse_url(getenv("DATABASE_URL"))["path"], 1), 'username' => parse_url(getenv("DATABASE_URL"))["user"], 'password' => parse_url(getenv("DATABASE_URL"))["pass"], 'charset' => 'utf8', 'prefix' => '', 'schema' => 'public', 'sslmode' => 'prefer', ], 'sqlsrv' => [ 'driver' => 'sqlsrv', 'host' => env('DB_HOST', 'localhost'), 'port' => env('DB_PORT', '1433'), 'database' => env('DB_DATABASE', 'forge'), 'username' => env('DB_USERNAME', 'forge'), 'password' => env('DB_PASSWORD', ''), 'charset' => 'utf8', 'prefix' => '', ], ], /* |-------------------------------------------------------------------------- | Migration Repository Table |-------------------------------------------------------------------------- | | This table keeps track of all the migrations that have already run for | your application. Using this information, we can determine which of | the migrations on disk haven't actually been run in the database. | */ 'migrations' => 'migrations', /* |-------------------------------------------------------------------------- | Redis Databases |-------------------------------------------------------------------------- | | Redis is an open source, fast, and advanced key-value store that also | provides a richer set of commands than a typical key-value systems | such as APC or Memcached. Laravel makes it easy to dig right in. | */ 'redis' => [ 'client' => 'predis', 'default' => [ 'host' => env('REDIS_HOST', '127.0.0.1'), 'password' => env('REDIS_PASSWORD', null), 'port' => env('REDIS_PORT', 6379), 'database' => 0, ], ], ];
TanerTombas/stories
config/database.php
PHP
mit
4,498
<?php /** * @package Abricos * @subpackage Notify * @copyright 2008-2015 Alexander Kuzmin * @license http://opensource.org/licenses/mit-license.php MIT License * @author Alexander Kuzmin <roosit@abricos.org> */ require_once 'phpmailer/class.phpmailer.php'; /** * Class NotifyManager * * @property NotifyModule $module */ class old_NotifyManager extends Ab_ModuleManager { private $emlcounter = 1; public function SendMail($email, $subject, $message, $from = '', $fromName = ''){ /* // настройки конфига $config['module']['notify']['type'] = "abricos"; /**/ $cfg = Abricos::$config['module']['notify']; if ($cfg['totestfile']){ $filepath = CWD."/cache/eml"; @mkdir($filepath); $filename = $filepath."/".date("YmdHis", time())."-".($this->emlcounter++).".htm"; $fh = @fopen($filename, 'a'); if (!$fh){ return false; } $str = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ru" lang="ru" dir="ltr"> <head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /></head> <body class="yui-skin-sam"> <div style="width: 600px; margin: 0 auto;">'; $str .= "<p>E-mail: <b>".$email."</b><br />"; $str .= "From: ".$from."<br />"; $str .= "FromName: ".$fromName."<br />"; $str .= "Subject: <b>".$subject."</b><br />"; $str .= "Message (html code):</p>"; $str .= '<textarea style="width: 100%; height: 300px;">'; $str .= htmlspecialchars($message); $str .= '</textarea>'; $str .= "<p>Message (preview):</p>"; $str .= "<div style='background-color: #F0F0F0;'>".$message."</div>"; $str .= '</div></body></html>'; fwrite($fh, $str); fflush($fh); fclose($fh); return true; } else { return $this->SendByMailer($email, $subject, $message, $from, $fromName); } } /** * Отправка почты через PHPMailer * * Настройка SMTP в файле config.php * $config["module"]["notify"] = array( * "SMTP" => true, // Использовать SMTP * "SMTPHost" => "mail.yourdomain.com", // SMTP сервер * "SMTPPort" => 26, // SMTP порт * "SMTPAuth" => true, // использовать авторизацию SMTP * "SMTPSecure" => true, // использовать SMTP Secure * "SMTPUsername" => "yourname@youdomain", // имя пользователя SMTP * "SMTPPassword" => "yourpassword", // пароль пользователя SMTP * * // Если необходима предварительная POP3 авторизация * "POPBefore" => false, // Использовать POP3 * "POPHost" => "mail.youdomain.com", // POP3 сервер * "POPPort" => 110, // POP3 порт * "POPUsername" => "yourname@youdomain", // имя пользователя POP3 * "POPPassword" => "yourpassword" // пароль пользователя POP3 * ); * * @param string $email * @param string $subject * @param string $message * @param string $from * @param string $fromName */ public function SendByMailer($email, $subject, $message, $from = '', $fromName = ''){ $cfg = &Abricos::$config['module']['notify']; $mailer = new NotifyMailer(); if (!$mailer->ValidateAddress($email)){ return false; } if ($cfg['POPBefore']){ // авторизация POP перед SMTP require_once 'phpmailer/class.pop3.php'; $pop = new POP3(); $res = $pop->Authorise($cfg['POPHost'], $cfg['POPPort'], 30, $cfg['POPUsername'], $cfg['POPPassword']); } if ($cfg['SMTP']){ // использовать SMTP $mailer->IsSMTP(); $mailer->Host = $cfg['SMTPHost']; if (intval($cfg['SMTPPort']) > 0){ $mailer->Port = intval($cfg['SMTPPort']); } if ($cfg['SMTPAuth']){ $mailer->SMTPAuth = true; $mailer->Username = $cfg['SMTPUsername']; $mailer->Password = $cfg['SMTPPassword']; $mailer->SMTPSecure = $cfg['SMTPSecure']; } } $mailer->Subject = $subject; $mailer->MsgHTML($message); $mailer->AddAddress($email); if (!empty($from)){ $mailer->From = $from; } if (!empty($fromName)){ $mailer->FromName = $fromName; } $result = $mailer->Send(); if (!$result && $cfg['errorlog']){ $filepath = CWD."/cache/eml"; @mkdir($filepath); $filename = $filepath."/error.log"; $fh = fopen($filename, 'a'); if (!$fh){ return false; } $str = date("YmdHis", time())." "; $str .= $mailer->ErrorInfo."\n"; fwrite($fh, $str); fflush($fh); fclose($fh); } return $result; } public function SendByAbricos($email, $subject, $message, $from = '', $fromName = ''){ $mailer = new NotifyAbricos(); $mailer->email = $email; $mailer->subject = $subject; $mailer->message = $message; if (!empty($from)){ $mailer->from = $from; } if (!empty($fromName)){ $mailer->fromName = $fromName; } $mailer->Send(); } } class NotifyAbricos { public $fromName = ""; public $from = ""; public $email = ""; public $subject = ""; public $message = ""; private $host = ""; private $password = ""; public function __construct(){ $this->from = SystemModule::$instance->GetPhrases()->Get('admin_mail'); $this->fromName = SystemModule::$instance->GetPhrases()->Get('site_name'); $cfg = &Abricos::$config['module']['notify']; $this->host = $cfg['host']; $this->password = $cfg['password']; } private function EncodeParam($arr){ $data = array(); foreach ($arr as $name => $value){ array_push($data, $name."=".urlencode($value)); } return implode("&", $data); } public function Send(){ $data = $this->EncodeParam(array( "from" => $this->from, "fromname" => $this->fromName, "body" => $this->message, "subject" => $this->subject, "to" => $this->email, "password" => $this->password )); $fp = fsockopen($this->host, 80, $errno, $errstr, 10); if ($fp){ $out = "POST /mailer/send/ HTTP/1.1\r\n"; $out .= "Host: ".$this->host."\r\n"; $out .= "User-Agent: Opera/8.50 (Windows NT 5.1; U; ru)\r\n"; $out .= "Content-Type: application/x-www-form-urlencoded\r\n"; $out .= "Content-Length: ".strlen($data)."\r\n\r\n"; $out .= $data."\r\n\r\n"; fputs($fp, $out); // отправляем данные /* while($gets=fgets($fp,2048)){ // print $gets; } /**/ fclose($fp); } return true; } } class NotifyMailer extends PHPMailer { public function __construct(){ $this->FromName = SystemModule::$instance->GetPhrases()->Get('site_name'); $this->From = SystemModule::$instance->GetPhrases()->Get('admin_mail'); $this->AltBody = "To view the message, please use an HTML compatible email viewer!"; $this->Priority = 3; $this->CharSet = "utf-8"; } public function MsgHTML($message, $basedir = ''){ $message = "<html><body>".$message."</body></html>"; parent::MsgHTML($message, $basedir); } public function Send(){ if (Abricos::$db->readonly){ return true; } return parent::Send(); } }
abricos/abricos-mod-notify
src/includes/old_manager.php
PHP
mit
8,474
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("04. Opinion Poll")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("04. Opinion Poll")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("1d3df66e-ff82-4862-8ff9-c630b9093fe5")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
VaskoViktorov/SoftUni-Homework
06. OOP Basics C# - 27.06.2017/02. Defining Classes - Exercise/04. Opinion Poll/04. Opinion Poll/Properties/AssemblyInfo.cs
C#
mit
1,403
#!/usr/bin/env python ''' Import this module to have access to a global redis cache named GLOBAL_CACHE. USAGE: from caching import GLOBAL_CACHE GLOBAL_CACHE.store('foo', 'bar') GLOBAL_CACHE.get('foo') >> bar ''' from redis_cache import SimpleCache try: GLOBAL_CACHE except NameError: GLOBAL_CACHE = SimpleCache(limit=1000, expire=60*60*24, namespace="GLOBAL_CACHE") else: # Already defined... pass
miketwo/pylacuna
pylacuna/caching.py
Python
mit
434
using System; namespace East.Tool.UseCaseTranslator.WebAPI.Areas.HelpPage { /// <summary> /// This represents an image sample on the help page. There's a display template named ImageSample associated with this class. /// </summary> public class ImageSample { /// <summary> /// Initializes a new instance of the <see cref="ImageSample"/> class. /// </summary> /// <param name="src">The URL of an image.</param> public ImageSample(string src) { if (src == null) { throw new ArgumentNullException("src"); } Src = src; } public string Src { get; private set; } public override bool Equals(object obj) { ImageSample other = obj as ImageSample; return other != null && Src == other.Src; } public override int GetHashCode() { return Src.GetHashCode(); } public override string ToString() { return Src; } } }
east-pmo/UseCaseTranslator
UseCaseTranslator.WebAPI/Areas/HelpPage/SampleGeneration/ImageSample.cs
C#
mit
1,077
'use strict' // create a net-peer compatible object based on a UDP datagram socket module.exports = function udpAdapter(udpSocket, udpDestinationHost, udpDestinationPort) { const _listeners = [] udpSocket.on('message', (msg, rinfo) => { //console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`) for(let i=0; i < _listeners.length; i++) { _listeners[i](msg) } }) let on = function(event, fn) { if (event === 'data') { _listeners.push(fn) } } let send = function(message) { udpSocket.send(Buffer.from(message.buffer), udpDestinationPort, udpDestinationHost, (err) => { }) } return Object.freeze({ on, send }) }
mreinstein/net-peer
examples/udp/udp-adapter.js
JavaScript
mit
680
package ru.otus.java_2017_04.golovnin.hw09; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; @Entity(name = "user") @Table(name = "users") public class User extends DataSet{ @Column(name = "name") private String name; @Column(name = "age", nullable = false, length = 3) private int age; User(){ super(); name = ""; age = 0; } User(long id, String name, int age){ super(id); this.name = name; this.age = age; } String getName(){ return name; } int getAge() { return age; } }
vladimir-golovnin/otus-java-2017-04-golovnin
hw09/src/main/java/ru/otus/java_2017_04/golovnin/hw09/User.java
Java
mit
642
var Filter = require('broccoli-filter') module.exports = WrapFilter; WrapFilter.prototype = Object.create(Filter.prototype); WrapFilter.prototype.constructor = WrapFilter; function WrapFilter (inputTree, options) { if (!(this instanceof WrapFilter)) return new WrapFilter(inputTree, options) Filter.call(this, inputTree, options) this.options = options || {}; this.options.extensions = this.options.extensions || ['js']; this.extensions = this.options.extensions; } WrapFilter.prototype.processString = function (string) { var wrapper = this.options.wrapper; if ( !(wrapper instanceof Array) ) { return string; } var startWith = wrapper[0] || ''; var endWith = wrapper[1] || ''; return [startWith, string, endWith].join('') }
H1D/broccoli-wrap
index.js
JavaScript
mit
757
package com.purvotara.airbnbmapexample.model; import android.content.Context; import com.android.volley.Request; import com.google.gson.Gson; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import com.google.gson.reflect.TypeToken; import com.purvotara.airbnbmapexample.constants.NetworkConstants; import com.purvotara.airbnbmapexample.controller.BaseInterface; import com.purvotara.airbnbmapexample.network.BaseNetwork; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; import java.util.List; /** * Created by skytreasure on 15/4/16. */ public class AddressModel extends BaseModel { @SerializedName("address_id") @Expose private Integer addressId; @SerializedName("mPincode") @Expose private String mPincode; @SerializedName("city") @Expose private String city; @SerializedName("line_1") @Expose private String line1; @SerializedName("line_2") @Expose private String line2; @SerializedName("longitude") @Expose private String longitude; @SerializedName("latitude") @Expose private String latitude; @SerializedName("address_type") @Expose private String addressType; @SerializedName("default") @Expose private Boolean _default; @SerializedName("image") @Expose private String image; @SerializedName("rating") @Expose private String rating; @SerializedName("distance") @Expose private String distance; /** * Constructor for the base model * * @param context the application mContext * @param baseInterface it is the instance of baseinterface, */ public AddressModel(Context context, BaseInterface baseInterface) { super(context, baseInterface); } public void fetchAddressFromServer() { BaseNetwork baseNetwork = new BaseNetwork(mContext, this); baseNetwork.getJSONObjectForRequest(Request.Method.GET, NetworkConstants.ADDRESS_URL, null, NetworkConstants.ADDRESS_REQUEST); } @Override public void parseAndNotifyResponse(JSONObject response, int requestType) throws JSONException { try { // boolean error = response.getBoolean(NetworkConstants.ERROR); Gson gson = new Gson(); switch (requestType) { case NetworkConstants.ADDRESS_REQUEST: JSONArray addressArray = response.getJSONArray(NetworkConstants.ADDRESS); List<AddressModel> addressList = gson.fromJson(addressArray.toString(), new TypeToken<List<AddressModel>>() { }.getType()); mBaseInterface.handleNetworkCall(addressList, requestType); break; } } catch (Exception e) { mBaseInterface.handleNetworkCall(e.getMessage(), requestType); } } @Override public HashMap<String, Object> getRequestBodyObject(int requestType) { return null; } @Override public HashMap<String, String> getRequestBodyString(int requestType) { return null; } public Integer getAddressId() { return addressId; } public void setAddressId(Integer addressId) { this.addressId = addressId; } public String getmPincode() { return mPincode; } public void setmPincode(String mPincode) { this.mPincode = mPincode; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getLine1() { return line1; } public void setLine1(String line1) { this.line1 = line1; } public String getLine2() { return line2; } public void setLine2(String line2) { this.line2 = line2; } public String getLongitude() { return longitude; } public void setLongitude(String longitude) { this.longitude = longitude; } public String getLatitude() { return latitude; } public void setLatitude(String latitude) { this.latitude = latitude; } public String getAddressType() { return addressType; } public void setAddressType(String addressType) { this.addressType = addressType; } public Boolean get_default() { return _default; } public void set_default(Boolean _default) { this._default = _default; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } public String getRating() { return rating; } public void setRating(String rating) { this.rating = rating; } public String getDistance() { return distance; } public void setDistance(String distance) { this.distance = distance; } }
SkyTreasure/Airbnb-Android-Google-Map-View
app/src/main/java/com/purvotara/airbnbmapexample/model/AddressModel.java
Java
mit
5,013
namespace _8.ArraySymmetry { using System; using System.Linq; public class ArraySymmetry { public static void Main() { var words = Console.ReadLine().Split(' ').ToArray(); var isSymmetric = true; for (int i = 0; i < words.Length / 2; i++) { var firstPart = words[i]; var secondPart = words[words.Length - 1 - i]; if (firstPart != secondPart) { isSymmetric = false; } } if (isSymmetric) Console.WriteLine("Yes"); else Console.WriteLine("No"); } } }
toteva94/SoftUni
[01]ProgrammingFundamentals/07.ExercisesArraysSimpleArrayProcessing/08.ArraySymmetry/ArraySymmetry.cs
C#
mit
717
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Books extends MY_Controller { public function __construct() { parent::__construct(); $this->loadModel('Book', 'books_model'); $this->setTitle('Bookshelf'); } public function index() { $this->setOutputData('books', $this->books_model->getAll()); $this->view('books/index'); } public function show($id) { $book = $this->books_model->get($id); $this->setOutputData('book', $book); if ($book == null) { $this->not_found(); } else { $this->setTitle($book->title); $this->load->helper('html'); $this->view('books/show'); } } public function create() { if($this->is_logged_in()) { $this->load->helper('form'); $this->loadModel('Author', 'authors_model'); $this->setOutputData('authors', $this->authors_model->getAll()); $this->setOutputData('author_id', $this->input->get('author_id')); $this->setTitle('New book'); $this->view('books/new'); } else { $this->forbidden(); } } public function edit($id) { if($this->is_logged_in()) { $this->load->helper('form'); $this->loadModel('Author', 'authors_model'); $this->setOutputData('authors', $this->authors_model->getAll()); $this->setOutputData('book', $this->books_model->get($id)); $this->setTitle('Edit book'); $this->view('books/edit'); } else { $this->forbidden(); } } public function delete($id) { if($this->is_logged_in()) { $this->setOutputData('book', $this->books_model->get($id)); $this->view('books/delete'); } else { $this->forbidden(); } } }
sixpounder/CI-WORKSHOP
application/controllers/Books.php
PHP
mit
1,752
Template.formeditprofile.events({ 'submit #editform': function(event){ event.preventDefault(); var firstNameVar = event.target.firstname.value; var lastNameVar = event.target.lastname.value; var classVar = event.target.classvar.value; Profiles.insert({ uid:Meteor.userId(), firstname: firstNameVar, lastname: lastNameVar, classvar: classVar }); alert("Done!"); } }); Template.addprofile.rendered = function(){ this.$('.ui.dropdown').dropdown(); }
zhjch05/MemoryChess
semantic-ui/client/pages/addprofile.js
JavaScript
mit
477
# https://graphics.stanford.edu/~seander/bithacks.html#NextBitPermutation def selector(values, setBits): maxBits = len(values) def select(v): out = [] for i in range(maxBits): if (v & (1 << i)): out.append(values[i]) return out v = (2 ** setBits) - 1 endState = v << (maxBits - setBits) yield select(v) while v != endState: t = (v | (v - 1)) + 1 v = t | ((((t & (-t % (1 << maxBits))) // (v & (-v % (1 << maxBits)))) >> 1) - 1) yield select(v) def normalize(perm): ref = sorted(perm) return [ref.index(x) for x in perm] def contains_pattern(perm, patt): if len(patt) > len(perm): return False for p in selector(perm, len(patt)): if normalize(p) == patt: return True return False if __name__ == '__main__': print(contains_pattern( [14, 12, 6, 10, 0, 9, 1, 11, 13, 16, 17, 3, 7, 5, 15, 2, 4, 8], [3, 0, 1, 2])) print(True)
asgeir/old-school-projects
python/verkefni2/cpattern.py
Python
mit
1,006
// FoalTS import { ValidateFunction } from 'ajv'; import { ApiParameter, ApiResponse, Context, Hook, HookDecorator, HttpResponseBadRequest, IApiHeaderParameter, OpenApi, ServiceManager } from '../../core'; import { getAjvInstance } from '../utils'; import { isFunction } from './is-function.util'; /** * Hook - Validate a specific header against an AJV schema. * * @export * @param {string} name - Header name. * @param {(object | ((controller: any) => object))} [schema={ type: 'string' }] - Schema used to * validate the header. * @param {{ openapi?: boolean, required?: boolean }} [options={}] - Options. * @param {boolean} [options.openapi] - Add OpenApi metadata. * @param {boolean} [options.required] - Specify is the header is optional. * @returns {HookDecorator} The hook. */ export function ValidateHeader( name: string, schema: object | ((controller: any) => object) = { type: 'string' }, options: { openapi?: boolean, required?: boolean } = {} ): HookDecorator { // tslint:disable-next-line const required = options.required ?? true; name = name.toLowerCase(); let validateSchema: ValidateFunction|undefined; function validate(this: any, ctx: Context, services: ServiceManager) { if (!validateSchema) { const ajvSchema = isFunction(schema) ? schema(this) : schema; const components = services.get(OpenApi).getComponents(this); validateSchema = getAjvInstance().compile({ components, properties: { [name]: ajvSchema }, required: required ? [ name ] : [], type: 'object', }); } if (!validateSchema(ctx.request.headers)) { return new HttpResponseBadRequest({ headers: validateSchema.errors }); } } const param: IApiHeaderParameter = { in: 'header', name }; if (required) { param.required = required; } const openapi = [ ApiParameter((c: any) => ({ ...param, schema: isFunction(schema) ? schema(c) : schema })), ApiResponse(400, { description: 'Bad request.' }) ]; return Hook(validate, openapi, options); }
FoalTS/foal
packages/core/src/common/hooks/validate-header.hook.ts
TypeScript
mit
2,105
using System; using System.Collections.Generic; using Baseline; using Marten.Storage; namespace Marten.Schema.Identity.Sequences { public class IdentityKeyGeneration : IIdGeneration { private readonly HiloSettings _hiloSettings; private readonly DocumentMapping _mapping; public IdentityKeyGeneration(DocumentMapping mapping, HiloSettings hiloSettings) { _mapping = mapping; _hiloSettings = hiloSettings ?? new HiloSettings(); } public int MaxLo => _hiloSettings.MaxLo; public IEnumerable<Type> KeyTypes { get; } = new[] {typeof(string)}; public IIdGenerator<T> Build<T>() { return (IIdGenerator<T>) new IdentityKeyGenerator(_mapping.DocumentType, _mapping.Alias); } public bool RequiresSequences { get; } = true; public Type[] DependentFeatures() { return new Type[] { typeof(SequenceFactory) }; } } public class IdentityKeyGenerator : IIdGenerator<string> { private readonly Type _documentType; public IdentityKeyGenerator(Type documentType, string alias) { _documentType = documentType; Alias = alias; } public string Alias { get; set; } public string Assign(ITenant tenant, string existing, out bool assigned) { if (existing.IsEmpty()) { var next = tenant.Sequences.SequenceFor(_documentType).NextLong(); assigned = true; return $"{Alias}/{next}"; } assigned = false; return existing; } } }
jokokko/marten
src/Marten/Schema/Identity/Sequences/IdentityKeyGeneration.cs
C#
mit
1,691
var expect = require('expect.js'); var EventEmitter = require('events').EventEmitter; var fixtures = require('../fixtures'); var Detector = require('../../lib/detector.js'); describe('Detector', function() { // Used to test emitted events var found; var listener = function(magicNumber) { found.push(magicNumber); }; beforeEach(function() { found = []; }); describe('constructor', function() { it('inherits from EventEmitter', function() { expect(new Detector()).to.be.an(EventEmitter); }); it('accepts an array of file paths', function() { var filePaths = ['path1.js', 'path2.js']; var detector = new Detector(filePaths); expect(detector._filePaths).to.be(filePaths); }); it('accepts a boolean to enforce the use of const', function() { var detector = new Detector([], { enforceConst: true }); expect(detector._enforceConst).to.be(true); }); it('accepts an array of numbers to ignore', function() { var ignore = [1, 2, 3.4]; var detector = new Detector([], { ignore: ignore }); expect(detector._ignore).to.be(ignore); }); }); describe('run', function() { it('is compatible with callbacks', function(done) { var detector = new Detector([fixtures.emptyFile]); detector.run(function(err) { done(err); }); }); it('is compatible with promises', function(done) { var detector = new Detector([fixtures.emptyFile]); detector.run().then(function() { done(); }).catch(done); }); it('returns an Error if not given an array of file paths', function(done) { var detector = new Detector(); detector.run().catch(function(err) { expect(err).to.be.an(Error); expect(err.message).to.be('filePaths must be a non-empty array of paths'); done(); }); }); }); it('emits end on completion, passing the number of files parsed', function(done) { var detector = new Detector([fixtures.emptyFile, fixtures.singleVariable]); detector.on('end', function(numFiles) { expect(numFiles).to.be(2); done(); }); detector.run().catch(done); }); it('emits no events when parsing an empty file', function(done) { var detector = new Detector([fixtures.emptyFile]); detector.on('found', listener); detector.run().then(function() { expect(found).to.be.empty(); done(); }).catch(done); }); it('emits no events when the file contains only named constants', function(done) { var detector = new Detector([fixtures.singleVariable]); detector.on('found', listener); detector.run().then(function() { expect(found).to.be.empty(); done(); }).catch(done); }); it('emits no events for literals assigned to object properties', function(done) { var detector = new Detector([fixtures.objectProperties]); detector.on('found', listener); detector.run().then(function() { expect(found).to.have.length(2); expect(found[0].value).to.be('4'); expect(found[1].value).to.be('5'); done(); }).catch(done); }); it('emits no events for literals used in AssignmentExpressions', function(done) { var detector = new Detector([fixtures.assignmentExpressions]); detector.on('found', listener); detector.run().then(function() { expect(found).to.have.length(0); done(); }).catch(done); }); it('emits no events for numbers marked by ignore:line', function(done) { var detector = new Detector([fixtures.lineIgnore]); detector.on('found', listener); detector.run().then(function() { expect(found).to.be.empty(); done(); }).catch(done); }); it('emits no events between ignore:start / ignore:end', function(done) { var detector = new Detector([fixtures.blockIgnore]); detector.on('found', listener); detector.run().then(function() { expect(found).to.be.empty(); done(); }).catch(done); }); it('emits a "found" event containing a magic number, when found', function(done) { var detector = new Detector([fixtures.secondsInMinute]); detector.on('found', listener); detector.run().then(function() { expect(found).to.have.length(1); expect(found[0].value).to.be('60'); expect(found[0].file.substr(-18)).to.be('secondsInMinute.js'); expect(found[0].startColumn).to.be(9); expect(found[0].endColumn).to.be(11); expect(found[0].fileLength).to.be(4); expect(found[0].lineNumber).to.be(2); expect(found[0].lineSource).to.be(' return 60;'); expect(found[0].contextLines).to.eql([ 'function getSecondsInMinute() {', ' return 60;', '}' ]); expect(found[0].contextIndex).to.eql(1); done(); }).catch(done); }); it('correctly emits hex and octal values', function(done) { var detector = new Detector([fixtures.hexOctal]); detector.on('found', listener); detector.run().then(function() { expect(found).to.have.length(3); expect(found[0].value).to.be('0x1A'); expect(found[1].value).to.be('0x02'); expect(found[2].value).to.be('071'); done(); }).catch(done); }); it('skips unnamed constants within the ignore list', function(done) { var detector = new Detector([fixtures.ignore], { ignore: [0] }); detector.on('found', listener); detector.run().then(function() { expect(found).to.have.length(1); expect(found[0].value).to.be('1'); done(); }).catch(done); }); it('ignores the shebang at the start of a file', function(done) { var detector = new Detector([fixtures.shebang]); detector.on('found', listener); detector.run().then(function() { expect(found).to.have.length(1); expect(found[0].lineNumber).to.be(4); expect(found[0].value).to.be('100'); done(); }).catch(done); }); describe('with detectObjects set to true', function() { it('emits a "found" event for object literals', function(done) { var detector = new Detector([fixtures.objectLiterals], { detectObjects: true }); detector.on('found', listener); detector.run().then(function() { expect(found).to.have.length(1); expect(found[0].value).to.be('42'); done(); }).catch(done); }); it('emits a "found" event for property assignments', function(done) { var detector = new Detector([fixtures.objectProperties], { detectObjects: true }); detector.on('found', listener); detector.run().then(function() { expect(found).to.have.length(4); expect(found[0].value).to.be('2'); expect(found[1].value).to.be('3'); expect(found[2].value).to.be('4'); expect(found[3].value).to.be('5'); done(); }).catch(done); }); }); describe('with enforceConst set to true', function() { it('emits a "found" event for variable declarations', function(done) { var detector = new Detector([fixtures.constVariable], { enforceConst: true }); detector.on('found', listener); detector.run().then(function() { expect(found).to.have.length(1); expect(found[0].value).to.be('10'); done(); }).catch(done); }); it('emits a "found" event for object expressions', function(done) { var detector = new Detector([fixtures.constObject], { enforceConst: true }); detector.on('found', listener); detector.run().then(function() { expect(found).to.have.length(1); expect(found[0].value).to.be('10'); done(); }).catch(done); }); }); });
dushmis/buddy.js
spec/unit/detectorSpec.js
JavaScript
mit
7,750
require "pubs/clients/db/models/concerns/dynamic_attributes" require "pubs/clients/db/models/concerns/hooks" require "pubs/clients/db/models/concerns/json_keys_symbolizer" require "pubs/clients/db/models/concerns/validations" require 'pubs/clients/db/models/model' require 'pubs/clients/db/models/unit'
lemmycaution/pubs
lib/pubs/clients/db/all.rb
Ruby
mit
303
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Xml; using Microsoft.Build.Collections; using Microsoft.Build.Evaluation; using Microsoft.Build.Execution; using Microsoft.Build.Framework; using Microsoft.Build.Internal; using Microsoft.Build.Shared; using Microsoft.Build.Utilities; using Microsoft.Win32; using ProjectHelpers = Microsoft.Build.UnitTests.BackEnd.ProjectHelpers; using TaskItem = Microsoft.Build.Execution.ProjectItemInstance.TaskItem; using InvalidProjectFileException = Microsoft.Build.Exceptions.InvalidProjectFileException; using ProjectItemInstanceFactory = Microsoft.Build.Execution.ProjectItemInstance.TaskItem.ProjectItemInstanceFactory; using Xunit; using Microsoft.Build.BackEnd; using Microsoft.Build.Shared.FileSystem; using Shouldly; namespace Microsoft.Build.UnitTests.Evaluation { public class Expander_Tests { private string _dateToParse = new DateTime(2010, 12, 25).ToString(CultureInfo.CurrentCulture); private static readonly string s_rootPathPrefix = NativeMethodsShared.IsWindows ? "C:\\" : Path.VolumeSeparatorChar.ToString(); [Fact] public void ExpandAllIntoTaskItems0() { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); IList<TaskItem> itemsOut = expander.ExpandIntoTaskItemsLeaveEscaped("", ExpanderOptions.ExpandProperties, null); ObjectModelHelpers.AssertItemsMatch("", GetTaskArrayFromItemList(itemsOut)); } [Fact] public void ExpandAllIntoTaskItems1() { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); IList<TaskItem> itemsOut = expander.ExpandIntoTaskItemsLeaveEscaped("foo", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); ObjectModelHelpers.AssertItemsMatch(@"foo", GetTaskArrayFromItemList(itemsOut)); } [Fact] public void ExpandAllIntoTaskItems2() { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); IList<TaskItem> itemsOut = expander.ExpandIntoTaskItemsLeaveEscaped("foo;bar", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); ObjectModelHelpers.AssertItemsMatch(@" foo bar ", GetTaskArrayFromItemList(itemsOut)); } [Fact] public void ExpandAllIntoTaskItems3() { ProjectInstance project = ProjectHelpers.CreateEmptyProjectInstance(); PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); List<ProjectItemInstance> ig = new List<ProjectItemInstance>(); ig.Add(new ProjectItemInstance(project, "Compile", "foo.cs", project.FullPath)); ig.Add(new ProjectItemInstance(project, "Compile", "bar.cs", project.FullPath)); List<ProjectItemInstance> ig2 = new List<ProjectItemInstance>(); ig2.Add(new ProjectItemInstance(project, "Resource", "bing.resx", project.FullPath)); ItemDictionary<ProjectItemInstance> itemsByType = new ItemDictionary<ProjectItemInstance>(); itemsByType.ImportItems(ig); itemsByType.ImportItems(ig2); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, itemsByType, FileSystems.Default); IList<TaskItem> itemsOut = expander.ExpandIntoTaskItemsLeaveEscaped("foo;bar;@(compile);@(resource)", ExpanderOptions.ExpandPropertiesAndItems, MockElementLocation.Instance); ObjectModelHelpers.AssertItemsMatch(@" foo bar foo.cs bar.cs bing.resx ", GetTaskArrayFromItemList(itemsOut)); } [Fact] public void ExpandAllIntoTaskItems4() { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); pg.Set(ProjectPropertyInstance.Create("a", "aaa")); pg.Set(ProjectPropertyInstance.Create("b", "bbb")); pg.Set(ProjectPropertyInstance.Create("c", "cc;dd")); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); IList<TaskItem> itemsOut = expander.ExpandIntoTaskItemsLeaveEscaped("foo$(a);$(b);$(c)", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); ObjectModelHelpers.AssertItemsMatch(@" fooaaa bbb cc dd ", GetTaskArrayFromItemList(itemsOut)); } /// <summary> /// Expand property expressions into ProjectPropertyInstance items /// </summary> [Fact] public void ExpandPropertiesIntoProjectPropertyInstances() { ProjectInstance project = ProjectHelpers.CreateEmptyProjectInstance(); PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); pg.Set(ProjectPropertyInstance.Create("a", "aaa")); pg.Set(ProjectPropertyInstance.Create("b", "bbb")); pg.Set(ProjectPropertyInstance.Create("c", "cc;dd")); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); ProjectItemInstanceFactory itemFactory = new ProjectItemInstanceFactory(project, "i"); IList<ProjectItemInstance> itemsOut = expander.ExpandIntoItemsLeaveEscaped("foo$(a);$(b);$(c);$(d", itemFactory, ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal(5, itemsOut.Count); } /// <summary> /// Expand property expressions into ProjectPropertyInstance items /// </summary> [Fact] public void ExpandEmptyPropertyExpressionToEmpty() { ProjectHelpers.CreateEmptyProjectInstance(); PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); string result = expander.ExpandIntoStringLeaveEscaped("$()", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal(String.Empty, result); } /// <summary> /// Expand an item vector into items of the specified type /// </summary> [Fact] public void ExpandItemVectorsIntoProjectItemInstancesSpecifyingItemType() { ProjectInstance project = ProjectHelpers.CreateEmptyProjectInstance(); var expander = CreateExpander(); ProjectItemInstanceFactory itemFactory = new ProjectItemInstanceFactory(project, "j"); IList<ProjectItemInstance> items = expander.ExpandIntoItemsLeaveEscaped("@(i)", itemFactory, ExpanderOptions.ExpandItems, MockElementLocation.Instance); Assert.Equal(2, items.Count); Assert.Equal("j", items[0].ItemType); Assert.Equal("j", items[1].ItemType); Assert.Equal("i0", items[0].EvaluatedInclude); Assert.Equal("i1", items[1].EvaluatedInclude); } /// <summary> /// Expand an item vector into items of the type of the item vector /// </summary> [Fact] public void ExpandItemVectorsIntoProjectItemInstancesWithoutSpecifyingItemType() { ProjectInstance project = ProjectHelpers.CreateEmptyProjectInstance(); var expander = CreateExpander(); ProjectItemInstanceFactory itemFactory = new ProjectItemInstanceFactory(project); IList<ProjectItemInstance> items = expander.ExpandIntoItemsLeaveEscaped("@(i)", itemFactory, ExpanderOptions.ExpandItems, MockElementLocation.Instance); Assert.Equal(2, items.Count); Assert.Equal("i", items[0].ItemType); Assert.Equal("i", items[1].ItemType); Assert.Equal("i0", items[0].EvaluatedInclude); Assert.Equal("i1", items[1].EvaluatedInclude); } /// <summary> /// Expand an item vector function AnyHaveMetadataValue /// </summary> [Fact] public void ExpandItemVectorFunctionsAnyHaveMetadataValue() { ProjectInstance project = ProjectHelpers.CreateEmptyProjectInstance(); var expander = CreateItemFunctionExpander(); ProjectItemInstanceFactory itemFactory = new ProjectItemInstanceFactory(project, "i"); IList<ProjectItemInstance> itemsTrue = expander.ExpandIntoItemsLeaveEscaped("@(i->AnyHaveMetadataValue('Even', 'true'))", itemFactory, ExpanderOptions.ExpandItems, MockElementLocation.Instance); Assert.Single(itemsTrue); Assert.Equal("i", itemsTrue[0].ItemType); Assert.Equal("true", itemsTrue[0].EvaluatedInclude); IList<ProjectItemInstance> itemsFalse = expander.ExpandIntoItemsLeaveEscaped("@(i->AnyHaveMetadataValue('Even', 'goop'))", itemFactory, ExpanderOptions.ExpandItems, MockElementLocation.Instance); Assert.Single(itemsFalse); Assert.Equal("i", itemsFalse[0].ItemType); Assert.Equal("false", itemsFalse[0].EvaluatedInclude); } /// <summary> /// Expand an item vector function Metadata()->DirectoryName()->Distinct() /// </summary> [Fact] [Trait("Category", "netcore-osx-failing")] [Trait("Category", "netcore-linux-failing")] public void ExpandItemVectorFunctionsGetDirectoryNameOfMetadataValueDistinct() { ProjectInstance project = ProjectHelpers.CreateEmptyProjectInstance(); var expander = CreateItemFunctionExpander(); ProjectItemInstanceFactory itemFactory = new ProjectItemInstanceFactory(project, "i"); IList<ProjectItemInstance> itemsTrue = expander.ExpandIntoItemsLeaveEscaped("@(i->Metadata('Meta0')->DirectoryName()->Distinct())", itemFactory, ExpanderOptions.ExpandItems, MockElementLocation.Instance); Assert.Single(itemsTrue); Assert.Equal("i", itemsTrue[0].ItemType); Assert.Equal(Path.Combine(s_rootPathPrefix, "firstdirectory", "seconddirectory"), itemsTrue[0].EvaluatedInclude); IList<ProjectItemInstance> itemsDir = expander.ExpandIntoItemsLeaveEscaped("@(i->Metadata('Meta9')->DirectoryName()->Distinct())", itemFactory, ExpanderOptions.ExpandItems, MockElementLocation.Instance); Assert.Single(itemsDir); Assert.Equal("i", itemsDir[0].ItemType); Assert.Equal(Path.Combine(Directory.GetCurrentDirectory(), @"seconddirectory"), itemsDir[0].EvaluatedInclude); } /// <summary> /// /// Expand an item vector function that is an itemspec modifier /// </summary> [Fact] [Trait("Category", "netcore-osx-failing")] [Trait("Category", "netcore-linux-failing")] [Trait("Category", "mono-osx-failing")] public void ExpandItemVectorFunctionsItemSpecModifier() { ProjectInstance project = ProjectHelpers.CreateEmptyProjectInstance(); var expander = CreateItemFunctionExpander(); ProjectItemInstanceFactory itemFactory = new ProjectItemInstanceFactory(project, "i"); IList<ProjectItemInstance> itemsTrue = expander.ExpandIntoItemsLeaveEscaped("@(i->Metadata('Meta0')->Directory())", itemFactory, ExpanderOptions.ExpandItems, MockElementLocation.Instance); Assert.Equal(10, itemsTrue.Count); Assert.Equal("i", itemsTrue[5].ItemType); Assert.Equal(Path.Combine("firstdirectory", "seconddirectory") + Path.DirectorySeparatorChar, itemsTrue[5].EvaluatedInclude); itemsTrue = expander.ExpandIntoItemsLeaveEscaped("@(i->Metadata('Meta0')->Filename())", itemFactory, ExpanderOptions.ExpandItems, MockElementLocation.Instance); Assert.Equal(10, itemsTrue.Count); Assert.Equal("i", itemsTrue[5].ItemType); Assert.Equal(@"file0", itemsTrue[5].EvaluatedInclude); itemsTrue = expander.ExpandIntoItemsLeaveEscaped("@(i->Metadata('Meta0')->Extension())", itemFactory, ExpanderOptions.ExpandItems, MockElementLocation.Instance); Assert.Equal(10, itemsTrue.Count); Assert.Equal("i", itemsTrue[5].ItemType); Assert.Equal(@".ext", itemsTrue[5].EvaluatedInclude); } /// <summary> /// Expand an item expression (that isn't a real expression) but includes a property reference nested within a metadata reference /// </summary> [Fact] public void ExpandItemVectorFunctionsInvalid1() { ProjectHelpers.CreateEmptyProjectInstance(); var expander = CreateItemFunctionExpander(); string result = expander.ExpandIntoStringLeaveEscaped("[@(type-&gt;'%($(a)), '%'')]", ExpanderOptions.ExpandAll, MockElementLocation.Instance); Assert.Equal(@"[@(type-&gt;'%(filename), '%'')]", result); } /// <summary> /// Expand an item expression (that isn't a real expression) but includes a metadata reference that till needs to be expanded /// </summary> [Fact] public void ExpandItemVectorFunctionsInvalid2() { ProjectHelpers.CreateEmptyProjectInstance(); var expander = CreateItemFunctionExpander(); string result = expander.ExpandIntoStringLeaveEscaped("[@(i->'%(Meta9))']", ExpanderOptions.ExpandAll, MockElementLocation.Instance); Assert.Equal(@"[@(i->')']", result); } /// <summary> /// Expand an item vector function that is chained into a string /// </summary> [Fact] [Trait("Category", "netcore-osx-failing")] [Trait("Category", "netcore-linux-failing")] [Trait("Category", "mono-osx-failing")] public void ExpandItemVectorFunctionsChained1() { ProjectHelpers.CreateEmptyProjectInstance(); var expander = CreateItemFunctionExpander(); string result = expander.ExpandIntoStringLeaveEscaped("@(i->'%(Meta0)'->'%(Directory)'->Distinct())", ExpanderOptions.ExpandItems, MockElementLocation.Instance); Assert.Equal(Path.Combine("firstdirectory", "seconddirectory") + Path.DirectorySeparatorChar, result); } /// <summary> /// Expand an item vector function that is chained and has constants into a string /// </summary> [Fact] [Trait("Category", "netcore-osx-failing")] [Trait("Category", "netcore-linux-failing")] [Trait("Category", "mono-osx-failing")] public void ExpandItemVectorFunctionsChained2() { ProjectHelpers.CreateEmptyProjectInstance(); var expander = CreateItemFunctionExpander(); string result = expander.ExpandIntoStringLeaveEscaped("[@(i->'%(Meta0)'->'%(Directory)'->Distinct())]", ExpanderOptions.ExpandItems, MockElementLocation.Instance); Assert.Equal(@"[firstdirectory\seconddirectory\]", result); } /// <summary> /// Expand an item vector function that is chained and has constants into a string /// </summary> [Fact] public void ExpandItemVectorFunctionsChained3() { ProjectHelpers.CreateEmptyProjectInstance(); var expander = CreateItemFunctionExpander(); string result = expander.ExpandIntoStringLeaveEscaped("@(i->'%(MetaBlank)'->'%(Directory)'->Distinct())", ExpanderOptions.ExpandItems, MockElementLocation.Instance); Assert.Equal(@"", result); } [Fact] [Trait("Category", "netcore-osx-failing")] [Trait("Category", "netcore-linux-failing")] [Trait("Category", "mono-osx-failing")] public void ExpandItemVectorFunctionsChainedProject1() { MockLogger logger = Helpers.BuildProjectWithNewOMExpectSuccess(@" <Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <ItemGroup> <Compile Include=`a.cpp`> <SomeMeta>C:\Value1\file1.txt</SomeMeta> <A>||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||</A> <B>##</B> </Compile> <Compile Include=`b.cpp`> <SomeMeta>C:\Value2\file2.txt</SomeMeta> <A>||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||</A> <B>##</B> </Compile> <Compile Include=`c.cpp`> <SomeMeta>C:\Value2\file3.txt</SomeMeta> <A>||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||</A> <B>##</B> </Compile> <Compile Include=`c.cpp`> <SomeMeta>C:\Value2\file3.txt</SomeMeta> <A>||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||</A> <B>##</B> </Compile> </ItemGroup> <Target Name=`Build`> <Message Text=`DirChain0: @(Compile->'%(SomeMeta)'->'%(Directory)'->Distinct())`/> <Message Text=`DirChain1: @(Compile->'%(SomeMeta)'->'%(Directory)'->Distinct(), '%(A)')`/> <Message Text=`DirChain2: @(Compile->'%(SomeMeta)'->'%(Directory)'->Distinct(), '%(A)%(B)')`/> <Message Text=`DirChain3: @(Compile->'%(SomeMeta)'->'%(Directory)'->Distinct(), '%(A)$%(B)')`/> <Message Text=`DirChain4: @(Compile->'%(SomeMeta)'->'%(Directory)'->Distinct(), '$%(A)$%(B)')`/> <Message Text=`DirChain5: @(Compile->'%(SomeMeta)'->'%(Directory)'->Distinct(), '$%(A)$%(B)$')`/> </Target> </Project> "); logger.AssertLogContains(@"DirChain0: Value1\;Value2\"); logger.AssertLogContains(@"DirChain1: Value1\||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||Value2\"); logger.AssertLogContains(@"DirChain2: Value1\||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||##Value2\"); logger.AssertLogContains(@"DirChain3: Value1\||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||$##Value2\"); logger.AssertLogContains(@"DirChain4: Value1\$||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||$##Value2\"); logger.AssertLogContains(@"DirChain5: Value1\$||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||$##$Value2\"); } [Fact] public void ExpandItemVectorFunctionsCount1() { string content = @" <Project DefaultTargets=`t` xmlns=`http://schemas.microsoft.com/developer/msbuild/2003`> <Target Name=`t`> <ItemGroup> <I Include=`foo;bar`/> <J Include=`;`/> </ItemGroup> <Message Text=`[@(I->Count())][@(J->Count())]` /> </Target> </Project> "; MockLogger log = Helpers.BuildProjectWithNewOMExpectSuccess(content); log.AssertLogContains("[2][0]"); } [Fact] public void ExpandItemVectorFunctionsCount2() { string content = @" <Project DefaultTargets=`t` xmlns=`http://schemas.microsoft.com/developer/msbuild/2003`> <Target Name=`t`> <ItemGroup> <I Include=`foo;bar`/> <J Include=`;`/> <K Include=`@(I->Count());@(J->Count())`/> </ItemGroup> <Message Text=`@(K)` /> </Target> </Project> "; MockLogger log = Helpers.BuildProjectWithNewOMExpectSuccess(content); log.AssertLogContains("2;0"); } [Fact] public void ExpandItemVectorFunctionsCountOperatingOnEmptyResult1() { string content = @" <Project DefaultTargets=`t` xmlns=`http://schemas.microsoft.com/developer/msbuild/2003`> <Target Name=`t`> <ItemGroup> <I Include=`foo;bar`/> <J Include=`;`/> </ItemGroup> <Message Text=`[@(I->Metadata('foo')->Count())][@(J->Metadata('foo')->Count())]` /> </Target> </Project> "; MockLogger log = Helpers.BuildProjectWithNewOMExpectSuccess(content); log.AssertLogContains("[0][0]"); } [Fact] public void ExpandItemVectorFunctionsCountOperatingOnEmptyResult2() { string content = @" <Project DefaultTargets=`t` xmlns=`http://schemas.microsoft.com/developer/msbuild/2003`> <Target Name=`t`> <ItemGroup> <I Include=`foo;bar`/> <J Include=`;`/> <K Include=`@(I->Metadata('foo')->Count());@(J->Metadata('foo')->Count())`/> </ItemGroup> <Message Text=`@(K)` /> </Target> </Project> "; MockLogger log = Helpers.BuildProjectWithNewOMExpectSuccess(content); log.AssertLogContains("0;0"); } [Fact] public void ExpandItemVectorFunctionsBuiltIn1() { string content = @" <Project DefaultTargets=`t` xmlns=`http://schemas.microsoft.com/developer/msbuild/2003`> <Target Name=`t`> <ItemGroup> <I Include=`foo;bar`/> </ItemGroup> <Message Text=`[@(I->FullPath())]` /> </Target> </Project> "; MockLogger log = Helpers.BuildProjectWithNewOMExpectSuccess(content); var current = Directory.GetCurrentDirectory(); log.AssertLogContains(String.Format(@"[{0}foo;{0}bar]", current + Path.DirectorySeparatorChar)); } [Fact] public void ExpandItemVectorFunctionsBuiltIn2() { string content = @" <Project DefaultTargets=`t` xmlns=`http://schemas.microsoft.com/developer/msbuild/2003`> <Target Name=`t`> <ItemGroup> <I Include=`foo;bar`/> </ItemGroup> <Message Text=`[@(I->FullPath()->Distinct())]` /> </Target> </Project> "; MockLogger log = Helpers.BuildProjectWithNewOMExpectSuccess(content); var current = Directory.GetCurrentDirectory(); log.AssertLogContains(String.Format(@"[{0}foo;{0}bar]", current + Path.DirectorySeparatorChar)); } [Fact] public void ExpandItemVectorFunctionsBuiltIn3() { string content = @" <Project DefaultTargets=`t` xmlns=`http://schemas.microsoft.com/developer/msbuild/2003`> <Target Name=`t`> <ItemGroup> <I Include=`foo;bar;foo;bar;foo`/> </ItemGroup> <Message Text=`[@(I->FullPath()->Distinct())]` /> </Target> </Project> "; MockLogger log = Helpers.BuildProjectWithNewOMExpectSuccess(content); var current = Directory.GetCurrentDirectory(); log.AssertLogContains(String.Format(@"[{0}foo;{0}bar]", current + Path.DirectorySeparatorChar)); } [Fact] public void ExpandItemVectorFunctionsBuiltIn4() { string content = @" <Project DefaultTargets=`t` xmlns=`http://schemas.microsoft.com/developer/msbuild/2003`> <Target Name=`t`> <ItemGroup> <I Include=`foo;bar;foo;bar;foo`/> </ItemGroup> <Message Text=`[@(I->Identity()->Distinct())]` /> </Target> </Project> "; MockLogger log = Helpers.BuildProjectWithNewOMExpectSuccess(content); log.AssertLogContains("[foo;bar]"); } [ConditionalFact(typeof(NativeMethodsShared), nameof(NativeMethodsShared.IsMaxPathLegacyWindows))] [PlatformSpecific(TestPlatforms.Windows)] [SkipOnTargetFramework(TargetFrameworkMonikers.Netcoreapp, "https://github.com/microsoft/msbuild/issues/4363")] public void ExpandItemVectorFunctionsBuiltIn_PathTooLongError() { string content = @" <Project DefaultTargets=`t` xmlns=`http://schemas.microsoft.com/developer/msbuild/2003`> <Target Name=`t`> <ItemGroup> <I Include=`fooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo`/> </ItemGroup> <Message Text=`[@(I->FullPath())]` /> </Target> </Project> "; MockLogger log = Helpers.BuildProjectWithNewOMExpectFailure(content, false /* no crashes */); log.AssertLogContains("MSB4198"); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.Netcoreapp, ".NET Core 2.1+ no longer validates paths: https://github.com/dotnet/corefx/issues/27779#issuecomment-371253486")] public void ExpandItemVectorFunctionsBuiltIn_InvalidCharsError() { if (!NativeMethodsShared.IsWindows) { return; // "Cannot have invalid characters in file name on Unix" } string content = @" <Project DefaultTargets=`t` xmlns=`http://schemas.microsoft.com/developer/msbuild/2003`> <Target Name=`t`> <ItemGroup> <I Include=`aaa|||bbb\ccc.txt`/> </ItemGroup> <Message Text=`[@(I->Directory())]` /> </Target> </Project> "; MockLogger log = Helpers.BuildProjectWithNewOMExpectFailure(content, false /* no crashes */); log.AssertLogContains("MSB4198"); } /// <summary> /// /// Expand an item vector function that is an itemspec modifier /// </summary> [Fact] [Trait("Category", "netcore-osx-failing")] [Trait("Category", "netcore-linux-failing")] [Trait("Category", "mono-osx-failing")] public void ExpandItemVectorFunctionsItemSpecModifier2() { ProjectInstance project = ProjectHelpers.CreateEmptyProjectInstance(); var expander = CreateItemFunctionExpander(); ProjectItemInstanceFactory itemFactory = new ProjectItemInstanceFactory(project, "i"); IList<ProjectItemInstance> itemsTrue = expander.ExpandIntoItemsLeaveEscaped("@(i->'%(Meta0)'->'%(Directory)')", itemFactory, ExpanderOptions.ExpandItems, MockElementLocation.Instance); Assert.Equal(10, itemsTrue.Count); Assert.Equal("i", itemsTrue[5].ItemType); Assert.Equal(Path.Combine("firstdirectory", "seconddirectory") + Path.DirectorySeparatorChar, itemsTrue[5].EvaluatedInclude); itemsTrue = expander.ExpandIntoItemsLeaveEscaped("@(i->'%(Meta0)'->'%(Filename)')", itemFactory, ExpanderOptions.ExpandItems, MockElementLocation.Instance); Assert.Equal(10, itemsTrue.Count); Assert.Equal("i", itemsTrue[5].ItemType); Assert.Equal(@"file0", itemsTrue[5].EvaluatedInclude); itemsTrue = expander.ExpandIntoItemsLeaveEscaped("@(i->'%(Meta0)'->'%(Extension)'->Distinct())", itemFactory, ExpanderOptions.ExpandItems, MockElementLocation.Instance); Assert.Single(itemsTrue); Assert.Equal("i", itemsTrue[0].ItemType); Assert.Equal(@".ext", itemsTrue[0].EvaluatedInclude); itemsTrue = expander.ExpandIntoItemsLeaveEscaped("@(i->'%(Meta0)'->'%(Filename)'->Substring($(Val)))", itemFactory, ExpanderOptions.ExpandItems, MockElementLocation.Instance); Assert.Equal(10, itemsTrue.Count); Assert.Equal("i", itemsTrue[5].ItemType); Assert.Equal(@"le0", itemsTrue[5].EvaluatedInclude); } /// <summary> /// Expand an item vector function Metadata()->DirectoryName() /// </summary> [Fact] [Trait("Category", "netcore-osx-failing")] [Trait("Category", "netcore-linux-failing")] public void ExpandItemVectorFunctionsGetDirectoryNameOfMetadataValue() { ProjectInstance project = ProjectHelpers.CreateEmptyProjectInstance(); var expander = CreateItemFunctionExpander(); ProjectItemInstanceFactory itemFactory = new ProjectItemInstanceFactory(project, "i"); IList<ProjectItemInstance> itemsTrue = expander.ExpandIntoItemsLeaveEscaped("@(i->Metadata('Meta0')->DirectoryName())", itemFactory, ExpanderOptions.ExpandItems, MockElementLocation.Instance); Assert.Equal(10, itemsTrue.Count); Assert.Equal("i", itemsTrue[5].ItemType); Assert.Equal(Path.Combine(s_rootPathPrefix, "firstdirectory", "seconddirectory"), itemsTrue[5].EvaluatedInclude); } /// <summary> /// Expand an item vector function Metadata() that contains semi-colon delimited sub-items /// </summary> [Fact] [Trait("Category", "netcore-osx-failing")] [Trait("Category", "netcore-linux-failing")] public void ExpandItemVectorFunctionsMetadataValueMultiItem() { ProjectInstance project = ProjectHelpers.CreateEmptyProjectInstance(); var expander = CreateItemFunctionExpander(); ProjectItemInstanceFactory itemFactory = new ProjectItemInstanceFactory(project, "i"); IList<ProjectItemInstance> items = expander.ExpandIntoItemsLeaveEscaped("@(i->Metadata('Meta10')->DirectoryName())", itemFactory, ExpanderOptions.ExpandItems, MockElementLocation.Instance); Assert.Equal(20, items.Count); Assert.Equal("i", items[5].ItemType); Assert.Equal("i", items[6].ItemType); Assert.Equal(Path.Combine(Directory.GetCurrentDirectory(), @"secondd;rectory"), items[5].EvaluatedInclude); Assert.Equal(Path.Combine(Directory.GetCurrentDirectory(), @"someo;herplace"), items[6].EvaluatedInclude); } /// <summary> /// Expand an item vector function Items->ClearMetadata() /// </summary> [Fact] public void ExpandItemVectorFunctionsClearMetadata() { ProjectInstance project = ProjectHelpers.CreateEmptyProjectInstance(); var expander = CreateItemFunctionExpander(); ProjectItemInstanceFactory itemFactory = new ProjectItemInstanceFactory(project, "i"); IList<ProjectItemInstance> items = expander.ExpandIntoItemsLeaveEscaped("@(i->ClearMetadata())", itemFactory, ExpanderOptions.ExpandItems, MockElementLocation.Instance); Assert.Equal(10, items.Count); Assert.Equal("i", items[5].ItemType); Assert.Empty(items[5].Metadata); } /// <summary> /// Creates an expander populated with some ProjectPropertyInstances and ProjectPropertyItems. /// </summary> /// <returns></returns> private Expander<ProjectPropertyInstance, ProjectItemInstance> CreateItemFunctionExpander() { ProjectInstance project = ProjectHelpers.CreateEmptyProjectInstance(); PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); pg.Set(ProjectPropertyInstance.Create("p", "v0")); pg.Set(ProjectPropertyInstance.Create("p", "v1")); pg.Set(ProjectPropertyInstance.Create("Val", "2")); pg.Set(ProjectPropertyInstance.Create("a", "filename")); ItemDictionary<ProjectItemInstance> ig = new ItemDictionary<ProjectItemInstance>(); for (int n = 0; n < 10; n++) { ProjectItemInstance pi = new ProjectItemInstance(project, "i", "i" + n.ToString(), project.FullPath); for (int m = 0; m < 5; m++) { pi.SetMetadata("Meta" + m.ToString(), Path.Combine(s_rootPathPrefix, "firstdirectory", "seconddirectory", "file") + m.ToString() + ".ext"); } pi.SetMetadata("Meta9", Path.Combine("seconddirectory", "file.ext")); pi.SetMetadata("Meta10", String.Format(";{0};{1};", Path.Combine("someo%3bherplace", "foo.txt"), Path.Combine("secondd%3brectory", "file.ext"))); pi.SetMetadata("MetaBlank", @""); if (n % 2 > 0) { pi.SetMetadata("Even", "true"); pi.SetMetadata("Odd", "false"); } else { pi.SetMetadata("Even", "false"); pi.SetMetadata("Odd", "true"); } ig.Add(pi); } Dictionary<string, string> itemMetadataTable = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); itemMetadataTable["Culture"] = "abc%253bdef;$(Gee_Aych_Ayee)"; itemMetadataTable["Language"] = "english"; IMetadataTable itemMetadata = new StringMetadataTable(itemMetadataTable); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, ig, itemMetadata, FileSystems.Default); return expander; } /// <summary> /// Creates an expander populated with some ProjectPropertyInstances and ProjectPropertyItems. /// </summary> /// <returns></returns> private Expander<ProjectPropertyInstance, ProjectItemInstance> CreateExpander() { ProjectInstance project = ProjectHelpers.CreateEmptyProjectInstance(); PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); pg.Set(ProjectPropertyInstance.Create("p", "v0")); pg.Set(ProjectPropertyInstance.Create("p", "v1")); ItemDictionary<ProjectItemInstance> ig = new ItemDictionary<ProjectItemInstance>(); ProjectItemInstance i0 = new ProjectItemInstance(project, "i", "i0", project.FullPath); ProjectItemInstance i1 = new ProjectItemInstance(project, "i", "i1", project.FullPath); ig.Add(i0); ig.Add(i1); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, ig, FileSystems.Default); return expander; } /// <summary> /// Regression test for bug when there are literally zero items declared /// in the project, we should continue to expand item list references to empty-string /// rather than not expand them at all. /// </summary> [Fact] public void ZeroItemsInProjectExpandsToEmpty() { MockLogger logger = Helpers.BuildProjectWithNewOMExpectSuccess(@" <Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <Target Name=`Build` Condition=`'@(foo)'!=''` > <Message Text=`This target should NOT run.`/> </Target> </Project> "); logger.AssertLogDoesntContain("This target should NOT run."); logger = Helpers.BuildProjectWithNewOMExpectSuccess(@" <Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <ItemGroup> <foo Include=`abc` Condition=` '@(foo)' == '' ` /> </ItemGroup> <Target Name=`Build`> <Message Text=`Item list foo contains @(foo)`/> </Target> </Project> "); logger.AssertLogContains("Item list foo contains abc"); } [Fact] public void ItemIncludeContainsMultipleItemReferences() { MockLogger logger = Helpers.BuildProjectWithNewOMExpectSuccess(@" <Project DefaultTarget=`ShowProps` ToolsVersion=`msbuilddefaulttoolsversion` xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"" > <PropertyGroup> <OutputType>Library</OutputType> </PropertyGroup> <ItemGroup> <CFiles Include=`foo.c;bar.c`/> <ObjFiles Include=`@(CFiles->'%(filename).obj')`/> <ObjFiles Include=`@(CPPFiles->'%(filename).obj')`/> <CleanFiles Condition=`'$(OutputType)'=='Library'` Include=`@(ObjFiles);@(TargetLib)`/> </ItemGroup> <Target Name=`ShowProps`> <Message Text=`Property OutputType=$(OutputType)`/> <Message Text=`Item ObjFiles=@(ObjFiles)`/> <Message Text=`Item CleanFiles=@(CleanFiles)`/> </Target> </Project> "); logger.AssertLogContains("Property OutputType=Library"); logger.AssertLogContains("Item ObjFiles=foo.obj;bar.obj"); logger.AssertLogContains("Item CleanFiles=foo.obj;bar.obj"); } #if FEATURE_LEGACY_GETFULLPATH /// <summary> /// Bad path when getting metadata through ->Metadata function /// </summary> [ConditionalFact(typeof(NativeMethodsShared), nameof(NativeMethodsShared.IsMaxPathLegacyWindows))] [PlatformSpecific(TestPlatforms.Windows)] public void InvalidPathAndMetadataItemFunctionPathTooLong() { MockLogger logger = Helpers.BuildProjectWithNewOMExpectFailure(@" <Project DefaultTargets='Build' xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <ItemGroup> <x Include='" + new string('x', 250) + @"'/> </ItemGroup> <Target Name='Build'> <Message Text=""@(x->Metadata('FullPath'))"" /> </Target> </Project>", false); logger.AssertLogContains("MSB4023"); } #endif /// <summary> /// Bad path with illegal windows chars when getting metadata through ->Metadata function /// </summary> [Fact] [PlatformSpecific(TestPlatforms.Windows)] [SkipOnTargetFramework(TargetFrameworkMonikers.Netcoreapp, ".NET Core 2.1+ no longer validates paths: https://github.com/dotnet/corefx/issues/27779#issuecomment-371253486")] public void InvalidPathAndMetadataItemFunctionInvalidWindowsPathChars() { MockLogger logger = Helpers.BuildProjectWithNewOMExpectFailure(@" <Project DefaultTargets='Build' xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <ItemGroup> <x Include='" + ":|?*" + @"'/> </ItemGroup> <Target Name='Build'> <Message Text=""@(x->Metadata('FullPath'))"" /> </Target> </Project>", false); logger.AssertLogContains("MSB4023"); } /// <summary> /// Asking for blank metadata /// </summary> [Fact] public void InvalidMetadataName() { MockLogger logger = Helpers.BuildProjectWithNewOMExpectFailure(@" <Project DefaultTargets='Build' xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <ItemGroup> <x Include='x'/> </ItemGroup> <Target Name='Build'> <Message Text=""@(x->Metadata(''))"" /> </Target> </Project>", false); logger.AssertLogContains("MSB4023"); } #if FEATURE_LEGACY_GETFULLPATH /// <summary> /// Bad path when getting metadata through ->WithMetadataValue function /// </summary> [ConditionalFact(typeof(NativeMethodsShared), nameof(NativeMethodsShared.IsMaxPathLegacyWindows))] [PlatformSpecific(TestPlatforms.Windows)] public void InvalidPathAndMetadataItemFunctionPathTooLong2() { MockLogger logger = Helpers.BuildProjectWithNewOMExpectFailure(@" <Project DefaultTargets='Build' xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <ItemGroup> <x Include='" + new string('x', 250) + @"'/> </ItemGroup> <Target Name='Build'> <Message Text=""@(x->WithMetadataValue('FullPath', 'x'))"" /> </Target> </Project>", false); logger.AssertLogContains("MSB4023"); } #endif /// <summary> /// Bad path with illegal windows chars when getting metadata through ->WithMetadataValue function /// </summary> [Fact] [PlatformSpecific(TestPlatforms.Windows)] [SkipOnTargetFramework(TargetFrameworkMonikers.Netcoreapp, ".NET Core 2.1+ no longer validates paths: https://github.com/dotnet/corefx/issues/27779#issuecomment-371253486")] public void InvalidPathAndMetadataItemFunctionInvalidWindowsPathChars2() { MockLogger logger = Helpers.BuildProjectWithNewOMExpectFailure(@" <Project DefaultTargets='Build' xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <ItemGroup> <x Include='" + ":|?*" + @"'/> </ItemGroup> <Target Name='Build'> <Message Text=""@(x->WithMetadataValue('FullPath', 'x'))"" /> </Target> </Project>", false); logger.AssertLogContains("MSB4023"); } /// <summary> /// Asking for blank metadata with ->WithMetadataValue /// </summary> [Fact] public void InvalidMetadataName2() { MockLogger logger = Helpers.BuildProjectWithNewOMExpectFailure(@" <Project DefaultTargets='Build' xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <ItemGroup> <x Include='x'/> </ItemGroup> <Target Name='Build'> <Message Text=""@(x->WithMetadataValue('', 'x'))"" /> </Target> </Project>", false); logger.AssertLogContains("MSB4023"); } #if FEATURE_LEGACY_GETFULLPATH /// <summary> /// Bad path when getting metadata through ->AnyHaveMetadataValue function /// </summary> [ConditionalFact(typeof(NativeMethodsShared), nameof(NativeMethodsShared.IsMaxPathLegacyWindows))] [PlatformSpecific(TestPlatforms.Windows)] public void InvalidPathAndMetadataItemFunctionPathTooLong3() { MockLogger logger = Helpers.BuildProjectWithNewOMExpectFailure(@" <Project DefaultTargets='Build' xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <ItemGroup> <x Include='" + new string('x', 250) + @"'/> </ItemGroup> <Target Name='Build'> <Message Text=""@(x->AnyHaveMetadataValue('FullPath', 'x'))"" /> </Target> </Project>", false); logger.AssertLogContains("MSB4023"); } #endif /// <summary> /// Bad path with illegal windows chars when getting metadata through ->AnyHaveMetadataValue function /// </summary> [Fact] [PlatformSpecific(TestPlatforms.Windows)] [SkipOnTargetFramework(TargetFrameworkMonikers.Netcoreapp, ".NET Core 2.1+ no longer validates paths: https://github.com/dotnet/corefx/issues/27779#issuecomment-371253486")] public void InvalidPathAndMetadataItemInvalidWindowsPathChars3() { MockLogger logger = Helpers.BuildProjectWithNewOMExpectFailure(@" <Project DefaultTargets='Build' xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <ItemGroup> <x Include='" + ":|?*" + @"'/> </ItemGroup> <Target Name='Build'> <Message Text=""@(x->AnyHaveMetadataValue('FullPath', 'x'))"" /> </Target> </Project>", false); logger.AssertLogContains("MSB4023"); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] [SkipOnTargetFramework(TargetFrameworkMonikers.Netcoreapp, ".NET Core 2.1+ no longer validates paths: https://github.com/dotnet/corefx/issues/27779#issuecomment-371253486")] public void InvalidPathInDirectMetadata() { var logger = Helpers.BuildProjectContentUsingBuildManagerExpectResult( @"<Project DefaultTargets='Build' xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <ItemGroup> <x Include=':|?*'> <m>%(FullPath)</m> </x> </ItemGroup> </Project>", BuildResultCode.Failure); logger.AssertLogContains("MSB4248"); } [ConditionalFact(typeof(NativeMethodsShared), nameof(NativeMethodsShared.IsMaxPathLegacyWindows))] [PlatformSpecific(TestPlatforms.Windows)] [SkipOnTargetFramework(TargetFrameworkMonikers.Netcoreapp, "new enough dotnet.exe transparently opts into long paths")] public void PathTooLongInDirectMetadata() { var logger = Helpers.BuildProjectContentUsingBuildManagerExpectResult( @"<Project DefaultTargets='Build' xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <ItemGroup> <x Include='" + new string('x', 250) + @"'> <m>%(FullPath)</m> </x> </ItemGroup> </Project>", BuildResultCode.Failure); logger.AssertLogContains("MSB4248"); } /// <summary> /// Asking for blank metadata with ->AnyHaveMetadataValue /// </summary> [Fact] public void InvalidMetadataName3() { MockLogger logger = Helpers.BuildProjectWithNewOMExpectFailure(@" <Project DefaultTargets='Build' xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <ItemGroup> <x Include='x'/> </ItemGroup> <Target Name='Build'> <Message Text=""@(x->AnyHaveMetadataValue('', 'x'))"" /> </Target> </Project>", false); logger.AssertLogContains("MSB4023"); } /// <summary> /// Filter by metadata presence /// </summary> [Fact] public void HasMetadata() { MockLogger logger = Helpers.BuildProjectWithNewOMExpectSuccess(@" <Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <ItemGroup> <_Item Include=""One""> <A>aa</A> <B>bb</B> <C>cc</C> </_Item> <_Item Include=""Two""> <B>bb</B> <C>cc</C> </_Item> <_Item Include=""Three""> <A>aa</A> <C>cc</C> </_Item> <_Item Include=""Four""> <A>aa</A> <B>bb</B> <C>cc</C> </_Item> <_Item Include=""Five""> <A></A> </_Item> </ItemGroup> <Target Name=""AfterBuild""> <Message Text=""[@(_Item->HasMetadata('a'), '|')]""/> </Target> </Project>"); logger.AssertLogContains("[One|Three|Four]"); } [Fact] public void DirectItemMetadataReferenceShouldBeCaseInsensitive() { MockLogger logger = Helpers.BuildProjectWithNewOMExpectSuccess(@" <Project> <ItemGroup> <Foo Include=`Foo`> <SENSITIVE>X</SENSITIVE> </Foo> </ItemGroup> <Target Name=`Build`> <Message Importance=`high` Text=`QualifiedNotMatchCase %(Foo.FileName)=%(Foo.sensitive)`/> <Message Importance=`high` Text=`QualifiedMatchCase %(Foo.FileName)=%(Foo.SENSITIVE)`/> <Message Importance=`high` Text=`UnqualifiedNotMatchCase %(Foo.FileName)=%(sensitive)`/> <Message Importance=`high` Text=`UnqualifiedMatchCase %(Foo.FileName)=%(SENSITIVE)`/> </Target> </Project> "); logger.AssertLogContains("QualifiedNotMatchCase Foo=X"); logger.AssertLogContains("QualifiedMatchCase Foo=X"); logger.AssertLogContains("UnqualifiedNotMatchCase Foo=X"); logger.AssertLogContains("UnqualifiedMatchCase Foo=X"); } [Fact] public void ItemDefinitionGroupMetadataReferenceShouldBeCaseInsensitive() { MockLogger logger = Helpers.BuildProjectWithNewOMExpectSuccess(@" <Project> <ItemDefinitionGroup> <Foo> <SENSITIVE>X</SENSITIVE> </Foo> </ItemDefinitionGroup> <ItemGroup> <Foo Include=`Foo`/> </ItemGroup> <Target Name=`Build`> <Message Importance=`high` Text=`QualifiedNotMatchCase %(Foo.FileName)=%(Foo.sensitive)`/> <Message Importance=`high` Text=`QualifiedMatchCase %(Foo.FileName)=%(Foo.SENSITIVE)`/> <Message Importance=`high` Text=`UnqualifiedNotMatchCase %(Foo.FileName)=%(sensitive)`/> <Message Importance=`high` Text=`UnqualifiedMatchCase %(Foo.FileName)=%(SENSITIVE)`/> </Target> </Project> "); logger.AssertLogContains("QualifiedNotMatchCase Foo=X"); logger.AssertLogContains("QualifiedMatchCase Foo=X"); logger.AssertLogContains("UnqualifiedNotMatchCase Foo=X"); logger.AssertLogContains("UnqualifiedMatchCase Foo=X"); } [Fact] public void WellKnownMetadataReferenceShouldBeCaseInsensitive() { MockLogger logger = Helpers.BuildProjectWithNewOMExpectSuccess(@" <Project> <ItemGroup> <Foo Include=`Foo`/> </ItemGroup> <Target Name=`Build`> <Message Importance=`high` Text=`QualifiedNotMatchCase %(Foo.Identity)=%(Foo.FILENAME)`/> <Message Importance=`high` Text=`QualifiedMatchCase %(Foo.Identity)=%(Foo.FileName)`/> <Message Importance=`high` Text=`UnqualifiedNotMatchCase %(Foo.Identity)=%(FILENAME)`/> <Message Importance=`high` Text=`UnqualifiedMatchCase %(Foo.Identity)=%(FileName)`/> </Target> </Project> "); logger.AssertLogContains("QualifiedNotMatchCase Foo=Foo"); logger.AssertLogContains("QualifiedMatchCase Foo=Foo"); logger.AssertLogContains("UnqualifiedNotMatchCase Foo=Foo"); logger.AssertLogContains("UnqualifiedMatchCase Foo=Foo"); } /// <summary> /// Verify when there is an error due to an attempt to use a static method that we report the method name /// </summary> [Fact] public void StaticMethodErrorMessageHaveMethodName() { try { Helpers.BuildProjectWithNewOMExpectFailure(@" <Project DefaultTargets='Build' xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <PropertyGroup> <Function>$([System.IO.Path]::Combine(null,''))</Function> </PropertyGroup> <Target Name='Build'> <Message Text='[ $(Function) ]' /> </Target> </Project>", false); } catch (Microsoft.Build.Exceptions.InvalidProjectFileException e) { Assert.NotEqual(-1, e.Message.IndexOf("[System.IO.Path]::Combine(null, '')", StringComparison.OrdinalIgnoreCase)); return; } Assert.True(false); } /// <summary> /// Verify when there is an error due to an attempt to use a static method that we report the method name /// </summary> [Fact] public void StaticMethodErrorMessageHaveMethodName1() { try { Helpers.BuildProjectWithNewOMExpectFailure(@" <Project DefaultTargets='Build' xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <PropertyGroup> <Function>$(System.IO.Path::Combine('a','b'))</Function> </PropertyGroup> <Target Name='Build'> <Message Text='[ $(Function) ]' /> </Target> </Project>", false); } catch (Microsoft.Build.Exceptions.InvalidProjectFileException e) { Assert.NotEqual(-1, e.Message.IndexOf("System.IO.Path::Combine('a','b')", StringComparison.OrdinalIgnoreCase)); return; } Assert.True(false); } /// <summary> /// Creates a set of complicated item metadata and properties, and items to exercise /// the Expander class. The data here contains escaped characters, metadata that /// references properties, properties that reference items, and other complex scenarios. /// </summary> /// <param name="pg"></param> /// <param name="primaryItemsByName"></param> /// <param name="secondaryItemsByName"></param> /// <param name="itemMetadata"></param> private void CreateComplexPropertiesItemsMetadata ( out Lookup readOnlyLookup, out StringMetadataTable itemMetadata ) { ProjectInstance project = ProjectHelpers.CreateEmptyProjectInstance(); Dictionary<string, string> itemMetadataTable = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); itemMetadataTable["Culture"] = "abc%253bdef;$(Gee_Aych_Ayee)"; itemMetadataTable["Language"] = "english"; itemMetadata = new StringMetadataTable(itemMetadataTable); PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); pg.Set(ProjectPropertyInstance.Create("Gee_Aych_Ayee", "ghi")); pg.Set(ProjectPropertyInstance.Create("OutputPath", @"\jk ; l\mno%253bpqr\stu")); pg.Set(ProjectPropertyInstance.Create("TargetPath", "@(IntermediateAssembly->'%(RelativeDir)')")); List<ProjectItemInstance> intermediateAssemblyItemGroup = new List<ProjectItemInstance>(); ProjectItemInstance i1 = new ProjectItemInstance(project, "IntermediateAssembly", NativeMethodsShared.IsWindows ? @"subdir1\engine.dll" : "subdir1/engine.dll", project.FullPath); intermediateAssemblyItemGroup.Add(i1); i1.SetMetadata("aaa", "111"); ProjectItemInstance i2 = new ProjectItemInstance(project, "IntermediateAssembly", NativeMethodsShared.IsWindows ? @"subdir2\tasks.dll" : "subdir2/tasks.dll", project.FullPath); intermediateAssemblyItemGroup.Add(i2); i2.SetMetadata("bbb", "222"); List<ProjectItemInstance> contentItemGroup = new List<ProjectItemInstance>(); ProjectItemInstance i3 = new ProjectItemInstance(project, "Content", "splash.bmp", project.FullPath); contentItemGroup.Add(i3); i3.SetMetadata("ccc", "333"); List<ProjectItemInstance> resourceItemGroup = new List<ProjectItemInstance>(); ProjectItemInstance i4 = new ProjectItemInstance(project, "Resource", "string$(p).resx", project.FullPath); resourceItemGroup.Add(i4); i4.SetMetadata("ddd", "444"); ProjectItemInstance i5 = new ProjectItemInstance(project, "Resource", "dialogs%253b.resx", project.FullPath); resourceItemGroup.Add(i5); i5.SetMetadata("eee", "555"); List<ProjectItemInstance> contentItemGroup2 = new List<ProjectItemInstance>(); ProjectItemInstance i6 = new ProjectItemInstance(project, "Content", "about.bmp", project.FullPath); contentItemGroup2.Add(i6); i6.SetMetadata("fff", "666"); ItemDictionary<ProjectItemInstance> secondaryItemsByName = new ItemDictionary<ProjectItemInstance>(); secondaryItemsByName.ImportItems(resourceItemGroup); secondaryItemsByName.ImportItems(contentItemGroup2); Lookup lookup = new Lookup(secondaryItemsByName, pg); // Add primary items lookup.EnterScope("x"); lookup.PopulateWithItems("IntermediateAssembly", intermediateAssemblyItemGroup); lookup.PopulateWithItems("Content", contentItemGroup); readOnlyLookup = lookup; } /// <summary> /// Exercises ExpandAllIntoTaskItems with a complex set of data. /// </summary> [Fact] public void ExpandAllIntoTaskItemsComplex() { Lookup lookup; StringMetadataTable itemMetadata; CreateComplexPropertiesItemsMetadata(out lookup, out itemMetadata); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(lookup, lookup, itemMetadata, FileSystems.Default); IList<TaskItem> taskItems = expander.ExpandIntoTaskItemsLeaveEscaped( "@(Resource->'%(Filename)') ; @(Content) ; @(NonExistent) ; $(NonExistent) ; %(NonExistent) ; " + "$(OutputPath) ; $(TargetPath) ; %(Language)_%(Culture)", ExpanderOptions.ExpandAll, MockElementLocation.Instance); // the following items are passed to the TaskItem constructor, and thus their ItemSpecs should be // in escaped form. ObjectModelHelpers.AssertItemsMatch(@" string$(p): ddd=444 dialogs%253b: eee=555 splash.bmp: ccc=333 \jk l\mno%253bpqr\stu subdir1" + Path.DirectorySeparatorChar + @": aaa=111 subdir2" + Path.DirectorySeparatorChar + @": bbb=222 english_abc%253bdef ghi ", GetTaskArrayFromItemList(taskItems)); } /// <summary> /// Exercises ExpandAllIntoString with a complex set of data but in a piecemeal fashion /// </summary> [Fact] public void ExpandAllIntoStringComplexPiecemeal() { Lookup lookup; StringMetadataTable itemMetadata; CreateComplexPropertiesItemsMetadata(out lookup, out itemMetadata); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(lookup, lookup, itemMetadata, FileSystems.Default); string stringToExpand = "@(Resource->'%(Filename)') ;"; Assert.Equal( @"string$(p);dialogs%3b ;", expander.ExpandIntoStringAndUnescape(stringToExpand, ExpanderOptions.ExpandAll, MockElementLocation.Instance)); stringToExpand = "@(Content)"; Assert.Equal( @"splash.bmp", expander.ExpandIntoStringAndUnescape(stringToExpand, ExpanderOptions.ExpandAll, MockElementLocation.Instance)); stringToExpand = "@(NonExistent)"; Assert.Equal( @"", expander.ExpandIntoStringAndUnescape(stringToExpand, ExpanderOptions.ExpandAll, MockElementLocation.Instance)); stringToExpand = "$(NonExistent)"; Assert.Equal( @"", expander.ExpandIntoStringAndUnescape(stringToExpand, ExpanderOptions.ExpandAll, MockElementLocation.Instance)); stringToExpand = "%(NonExistent)"; Assert.Equal( @"", expander.ExpandIntoStringAndUnescape(stringToExpand, ExpanderOptions.ExpandAll, MockElementLocation.Instance)); stringToExpand = "$(OutputPath)"; Assert.Equal( @"\jk ; l\mno%3bpqr\stu", expander.ExpandIntoStringAndUnescape(stringToExpand, ExpanderOptions.ExpandAll, MockElementLocation.Instance)); stringToExpand = "$(TargetPath)"; Assert.Equal( "subdir1" + Path.DirectorySeparatorChar + ";subdir2" + Path.DirectorySeparatorChar, expander.ExpandIntoStringAndUnescape(stringToExpand, ExpanderOptions.ExpandAll, MockElementLocation.Instance)); stringToExpand = "%(Language)_%(Culture)"; Assert.Equal( @"english_abc%3bdef;ghi", expander.ExpandIntoStringAndUnescape(stringToExpand, ExpanderOptions.ExpandAll, MockElementLocation.Instance)); } /// <summary> /// Exercises ExpandAllIntoString with an item list using a transform that is empty /// </summary> [Fact] public void ExpandAllIntoStringEmpty() { Lookup lookup; StringMetadataTable itemMetadata; CreateComplexPropertiesItemsMetadata(out lookup, out itemMetadata); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(lookup, lookup, itemMetadata, FileSystems.Default); XmlAttribute xmlattribute = (new XmlDocument()).CreateAttribute("dummy"); xmlattribute.Value = "@(IntermediateAssembly->'')"; Assert.Equal( @";", expander.ExpandIntoStringAndUnescape(xmlattribute.Value, ExpanderOptions.ExpandAll, MockElementLocation.Instance)); xmlattribute.Value = "@(IntermediateAssembly->'%(goop)')"; Assert.Equal( @";", expander.ExpandIntoStringAndUnescape(xmlattribute.Value, ExpanderOptions.ExpandAll, MockElementLocation.Instance)); } /// <summary> /// Exercises ExpandAllIntoString with a complex set of data. /// </summary> [Fact] public void ExpandAllIntoStringComplex() { Lookup lookup; StringMetadataTable itemMetadata; CreateComplexPropertiesItemsMetadata(out lookup, out itemMetadata); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(lookup, lookup, itemMetadata, FileSystems.Default); XmlAttribute xmlattribute = (new XmlDocument()).CreateAttribute("dummy"); xmlattribute.Value = "@(Resource->'%(Filename)') ; @(Content) ; @(NonExistent) ; $(NonExistent) ; %(NonExistent) ; " + "$(OutputPath) ; $(TargetPath) ; %(Language)_%(Culture)"; Assert.Equal( @"string$(p);dialogs%3b ; splash.bmp ; ; ; ; \jk ; l\mno%3bpqr\stu ; subdir1" + Path.DirectorySeparatorChar + ";subdir2" + Path.DirectorySeparatorChar + " ; english_abc%3bdef;ghi", expander.ExpandIntoStringAndUnescape(xmlattribute.Value, ExpanderOptions.ExpandAll, MockElementLocation.Instance)); } /// <summary> /// Exercises ExpandAllIntoString with a complex set of data. /// </summary> [Fact] public void ExpandAllIntoStringLeaveEscapedComplex() { Lookup lookup; StringMetadataTable itemMetadata; CreateComplexPropertiesItemsMetadata(out lookup, out itemMetadata); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(lookup, lookup, itemMetadata, FileSystems.Default); XmlAttribute xmlattribute = (new XmlDocument()).CreateAttribute("dummy"); xmlattribute.Value = "@(Resource->'%(Filename)') ; @(Content) ; @(NonExistent) ; $(NonExistent) ; %(NonExistent) ; " + "$(OutputPath) ; $(TargetPath) ; %(Language)_%(Culture)"; Assert.Equal( @"string$(p);dialogs%253b ; splash.bmp ; ; ; ; \jk ; l\mno%253bpqr\stu ; subdir1" + Path.DirectorySeparatorChar + ";subdir2" + Path.DirectorySeparatorChar + " ; english_abc%253bdef;ghi", expander.ExpandIntoStringLeaveEscaped(xmlattribute.Value, ExpanderOptions.ExpandAll, MockElementLocation.Instance)); } /// <summary> /// Exercises ExpandAllIntoString with a string that does not need expanding. /// In this case the expanded string should be reference identical to the passed in string. /// </summary> [Fact] public void ExpandAllIntoStringExpectIdenticalReference() { Lookup lookup; StringMetadataTable itemMetadata; CreateComplexPropertiesItemsMetadata(out lookup, out itemMetadata); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(lookup, lookup, itemMetadata, FileSystems.Default); XmlAttribute xmlattribute = (new XmlDocument()).CreateAttribute("dummy"); // Create a *non-literal* string. If we used a literal string, the CLR might (would) intern // it, which would mean that Expander would inevitably return a reference to the same string. // In real builds, the strings will never be literals, and we want to test the behavior in // that situation. xmlattribute.Value = "abc123" + new Random().Next(); string expandedString = expander.ExpandIntoStringLeaveEscaped(xmlattribute.Value, ExpanderOptions.ExpandAll, MockElementLocation.Instance); #if FEATURE_STRING_INTERN // Verify neither string got interned, so that this test is meaningful Assert.Null(string.IsInterned(xmlattribute.Value)); Assert.Null(string.IsInterned(expandedString)); #endif // Finally verify Expander indeed didn't create a new string. Assert.True(Object.ReferenceEquals(xmlattribute.Value, expandedString)); } /// <summary> /// Exercises ExpandAllIntoString with a complex set of data and various expander options /// </summary> [Fact] public void ExpandAllIntoStringExpanderOptions() { Lookup lookup; StringMetadataTable itemMetadata; CreateComplexPropertiesItemsMetadata(out lookup, out itemMetadata); string value = @"@(Resource->'%(Filename)') ; @(Content) ; @(NonExistent) ; $(NonExistent) ; %(NonExistent) ; $(OutputPath) ; $(TargetPath) ; %(Language)_%(Culture)"; Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(lookup, lookup, itemMetadata, FileSystems.Default); Assert.Equal(@"@(Resource->'%(Filename)') ; @(Content) ; @(NonExistent) ; ; %(NonExistent) ; \jk ; l\mno%3bpqr\stu ; @(IntermediateAssembly->'%(RelativeDir)') ; %(Language)_%(Culture)", expander.ExpandIntoStringAndUnescape(value, ExpanderOptions.ExpandProperties, MockElementLocation.Instance)); Assert.Equal(@"@(Resource->'%(Filename)') ; @(Content) ; @(NonExistent) ; ; ; \jk ; l\mno%3bpqr\stu ; @(IntermediateAssembly->'%(RelativeDir)') ; english_abc%3bdef;ghi", expander.ExpandIntoStringAndUnescape(value, ExpanderOptions.ExpandPropertiesAndMetadata, MockElementLocation.Instance)); Assert.Equal(@"string$(p);dialogs%3b ; splash.bmp ; ; ; ; \jk ; l\mno%3bpqr\stu ; subdir1" + Path.DirectorySeparatorChar + ";subdir2" + Path.DirectorySeparatorChar + " ; english_abc%3bdef;ghi", expander.ExpandIntoStringAndUnescape(value, ExpanderOptions.ExpandAll, MockElementLocation.Instance)); Assert.Equal(@"string$(p);dialogs%3b ; splash.bmp ; ; $(NonExistent) ; %(NonExistent) ; $(OutputPath) ; $(TargetPath) ; %(Language)_%(Culture)", expander.ExpandIntoStringAndUnescape(value, ExpanderOptions.ExpandItems, MockElementLocation.Instance)); } /// <summary> /// Exercises ExpandAllIntoStringListLeaveEscaped with a complex set of data. /// </summary> [Fact] public void ExpandAllIntoStringListLeaveEscapedComplex() { Lookup lookup; StringMetadataTable itemMetadata; CreateComplexPropertiesItemsMetadata(out lookup, out itemMetadata); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(lookup, lookup, itemMetadata, FileSystems.Default); string value = "@(Resource->'%(Filename)') ; @(Content) ; @(NonExistent) ; $(NonExistent) ; %(NonExistent) ; " + "$(OutputPath) ; $(TargetPath) ; %(Language)_%(Culture)"; IList<string> expanded = expander.ExpandIntoStringListLeaveEscaped(value, ExpanderOptions.ExpandAll, MockElementLocation.Instance).ToList(); Assert.Equal(9, expanded.Count); Assert.Equal(@"string$(p)", expanded[0]); Assert.Equal(@"dialogs%253b", expanded[1]); Assert.Equal(@"splash.bmp", expanded[2]); Assert.Equal(@"\jk", expanded[3]); Assert.Equal(@"l\mno%253bpqr\stu", expanded[4]); Assert.Equal("subdir1" + Path.DirectorySeparatorChar, expanded[5]); Assert.Equal("subdir2" + Path.DirectorySeparatorChar, expanded[6]); Assert.Equal(@"english_abc%253bdef", expanded[7]); Assert.Equal(@"ghi", expanded[8]); } internal ITaskItem[] GetTaskArrayFromItemList(IList<TaskItem> list) { ITaskItem[] items = new ITaskItem[list.Count]; for (int i = 0; i < list.Count; ++i) { items[i] = list[i]; } return items; } /// <summary> /// v10.0\TeamData\Microsoft.Data.Schema.Common.targets shipped with bad syntax: /// $(HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\9.0\VSTSDB@VSTSDBDirectory) /// this was evaluating to blank before, now it errors; we have to special case it to /// evaluate to blank. /// Note that this still works whether or not the key exists and has a value. /// </summary> [Fact] public void RegistryPropertyInvalidPrefixSpecialCase() { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); string result = expander.ExpandIntoStringLeaveEscaped(@"$(HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\9.0\VSTSDB@VSTSDBDirectory)", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal(String.Empty, result); } // Compat hack: WebProjects may have an import with a condition like: // Condition=" '$(Solutions.VSVersion)' == '8.0'" // These would have been '' in prior versions of msbuild but would be treated as a possible string function in current versions. // Be compatible by returning an empty string here. [Fact] public void Regress692569() { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); string result = expander.ExpandIntoStringLeaveEscaped(@"$(Solutions.VSVersion)", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal(String.Empty, result); } /// <summary> /// In the general case, we should still error for properties that incorrectly miss the Registry: prefix. /// Note that this still fails whether or not the key exists. /// </summary> [Fact] public void RegistryPropertyInvalidPrefixError() { Assert.Throws<InvalidProjectFileException>(() => { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); expander.ExpandIntoStringLeaveEscaped(@"$(HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\9.0\VSTSDB@XXXXDBDirectory)", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); } ); } /// <summary> /// In the general case, we should still error for properties that incorrectly miss the Registry: prefix, like /// the special case, but with extra char on the end. /// Note that this still fails whether or not the key exists. /// </summary> [Fact] public void RegistryPropertyInvalidPrefixError2() { Assert.Throws<InvalidProjectFileException>(() => { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); expander.ExpandIntoStringLeaveEscaped(@"$(HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\9.0\VSTSDB@VSTSDBDirectoryX)", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); } ); } #if FEATURE_WIN32_REGISTRY [Fact] public void RegistryPropertyString() { try { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); RegistryKey key = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\MSBuild_test"); key.SetValue("Value", "String", RegistryValueKind.String); string result = expander.ExpandIntoStringLeaveEscaped(@"$(Registry:HKEY_CURRENT_USER\Software\Microsoft\MSBuild_test@Value)", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal("String", result); } finally { Registry.CurrentUser.DeleteSubKey(@"Software\Microsoft\MSBuild_test"); } } [Fact] public void RegistryPropertyBinary() { try { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); RegistryKey key = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\MSBuild_test"); UTF8Encoding enc = new UTF8Encoding(); byte[] utfText = enc.GetBytes("String".ToCharArray()); key.SetValue("Value", utfText, RegistryValueKind.Binary); string result = expander.ExpandIntoStringLeaveEscaped(@"$(Registry:HKEY_CURRENT_USER\Software\Microsoft\MSBuild_test@Value)", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal("83;116;114;105;110;103", result); } finally { Registry.CurrentUser.DeleteSubKey(@"Software\Microsoft\MSBuild_test"); } } [Fact] public void RegistryPropertyDWord() { try { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); RegistryKey key = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\MSBuild_test"); key.SetValue("Value", 123456, RegistryValueKind.DWord); string result = expander.ExpandIntoStringLeaveEscaped(@"$(Registry:HKEY_CURRENT_USER\Software\Microsoft\MSBuild_test@Value)", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal("123456", result); } finally { Registry.CurrentUser.DeleteSubKey(@"Software\Microsoft\MSBuild_test"); } } [Fact] public void RegistryPropertyExpandString() { try { string envVar = NativeMethodsShared.IsWindows ? "TEMP" : "USER"; PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); RegistryKey key = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\MSBuild_test"); key.SetValue("Value", "%" + envVar + "%", RegistryValueKind.ExpandString); string result = expander.ExpandIntoStringLeaveEscaped(@"$(Registry:HKEY_CURRENT_USER\Software\Microsoft\MSBuild_test@Value)", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal(Environment.GetEnvironmentVariable(envVar), result); } finally { Registry.CurrentUser.DeleteSubKey(@"Software\Microsoft\MSBuild_test"); } } [Fact] public void RegistryPropertyQWord() { try { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); RegistryKey key = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\MSBuild_test"); key.SetValue("Value", (long)123456789123456789, RegistryValueKind.QWord); string result = expander.ExpandIntoStringLeaveEscaped(@"$(Registry:HKEY_CURRENT_USER\Software\Microsoft\MSBuild_test@Value)", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal("123456789123456789", result); } finally { Registry.CurrentUser.DeleteSubKey(@"Software\Microsoft\MSBuild_test"); } } [Fact] public void RegistryPropertyMultiString() { try { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); RegistryKey key = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\MSBuild_test"); key.SetValue("Value", new string[] { "A", "B", "C", "D" }, RegistryValueKind.MultiString); string result = expander.ExpandIntoStringLeaveEscaped(@"$(Registry:HKEY_CURRENT_USER\Software\Microsoft\MSBuild_test@Value)", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal("A;B;C;D", result); } finally { Registry.CurrentUser.DeleteSubKey(@"Software\Microsoft\MSBuild_test"); } } #endif [Fact] public void TestItemSpecModiferEscaping() { string content = @" <Project DefaultTargets=""Build"" xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <Target Name=""Build""> <WriteLinesToFile Overwrite=""true"" File=""unittest.%28msbuild%29.file"" Lines=""Nothing much here""/> <ItemGroup> <TestFile Include=""unittest.%28msbuild%29.file"" /> </ItemGroup> <Message Text=""@(TestFile->FullPath())"" /> <Message Text=""@(TestFile->'%(FullPath)'->Distinct())"" /> <Delete Files=""unittest.%28msbuild%29.file"" /> </Target> </Project> "; MockLogger log = Helpers.BuildProjectWithNewOMExpectSuccess(content); log.AssertLogDoesntContain("%28"); log.AssertLogDoesntContain("%29"); } [Fact] [Trait("Category", "mono-osx-failing")] public void TestGetPathToReferenceAssembliesAsFunction() { if (ToolLocationHelper.GetPathToDotNetFrameworkReferenceAssemblies(TargetDotNetFrameworkVersion.Version45) == null) { // if there aren't any reference assemblies installed on the machine in the first place, of course // we're not going to find them. :) return; } string content = @" <Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <PropertyGroup> <TargetFrameworkIdentifier>.NETFramework</TargetFrameworkIdentifier> <TargetFrameworkVersion>v4.5</TargetFrameworkVersion> <TargetFrameworkProfile></TargetFrameworkProfile> <TargetFrameworkMoniker>$(TargetFrameworkIdentifier),Version=$(TargetFrameworkVersion)</TargetFrameworkMoniker> </PropertyGroup> <Target Name=""Build""> <GetReferenceAssemblyPaths Condition="" '$(TargetFrameworkDirectory)' == '' and '$(TargetFrameworkMoniker)' !=''"" TargetFrameworkMoniker=""$(TargetFrameworkMoniker)"" RootPath=""$(TargetFrameworkRootPath)"" > <Output TaskParameter=""ReferenceAssemblyPaths"" PropertyName=""ReferenceAssemblyPathsFromTask""/> </GetReferenceAssemblyPaths> <PropertyGroup> <ReferenceAssemblyPathsFromFunction>$([Microsoft.Build.Utilities.ToolLocationHelper]::GetPathToStandardLibraries($(TargetFrameworkIdentifier), $(TargetFrameworkVersion), $(TargetFrameworkProfile)))\</ReferenceAssemblyPathsFromFunction> </PropertyGroup> <Message Text=""Task: $(ReferenceAssemblyPathsFromTask)"" Importance=""High"" /> <Message Text=""Function: $(ReferenceAssemblyPathsFromFunction)"" Importance=""High"" /> <Warning Text=""Reference assembly paths do not match!"" Condition=""'$(ReferenceAssemblyPathsFromFunction)' != '$(ReferenceAssemblyPathsFromTask)'"" /> </Target> </Project> "; MockLogger log = Helpers.BuildProjectWithNewOMExpectSuccess(content); log.AssertLogDoesntContain("Reference assembly paths do not match"); } /// <summary> /// Expand property function that takes a null argument /// </summary> [Fact] public void PropertyFunctionNullArgument() { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); string result = expander.ExpandIntoStringLeaveEscaped("$([System.Convert]::ChangeType('null',$(SomeStuff.GetType())))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal("null", result); } /// <summary> /// Expand property function that returns a null /// </summary> [Fact] public void PropertyFunctionNullReturn() { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); pg.Set(ProjectPropertyInstance.Create("SomeStuff", "This IS SOME STUff")); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); string result = expander.ExpandIntoStringLeaveEscaped("$([System.Convert]::ChangeType(,$(SomeStuff.GetType())))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal("", result); } /// <summary> /// Expand property function that takes no arguments and returns a string /// </summary> [Fact] public void PropertyFunctionNoArguments() { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); pg.Set(ProjectPropertyInstance.Create("SomeStuff", "This IS SOME STUff")); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); string result = expander.ExpandIntoStringLeaveEscaped("$(SomeStuff.ToUpperInvariant())", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal("THIS IS SOME STUFF", result); } /// <summary> /// Expand property function that takes no arguments and returns a string (trimmed) /// </summary> [Fact] public void PropertyFunctionNoArgumentsTrim() { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); pg.Set(ProjectPropertyInstance.Create("FileName", " foo.ext ")); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); string result = expander.ExpandIntoStringLeaveEscaped("$(FileName.Trim())", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal("foo.ext", result); } /// <summary> /// Expand property function that is a get property accessor /// </summary> [Fact] public void PropertyFunctionPropertyGet() { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); pg.Set(ProjectPropertyInstance.Create("SomeStuff", "This IS SOME STUff")); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); string result = expander.ExpandIntoStringLeaveEscaped("$(SomeStuff.Length)", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal("18", result); } /// <summary> /// Expand property function which is a manual get property accessor /// </summary> [Fact] public void PropertyFunctionPropertyManualGet() { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); pg.Set(ProjectPropertyInstance.Create("SomeStuff", "This IS SOME STUff")); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); string result = expander.ExpandIntoStringLeaveEscaped("$(SomeStuff.get_Length())", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal("18", result); } /// <summary> /// Expand property function which is a manual get property accessor and a concatenation of a constant /// </summary> [Fact] public void PropertyFunctionPropertyNoArgumentsConcat() { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); pg.Set(ProjectPropertyInstance.Create("SomeStuff", "This IS SOME STUff")); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); string result = expander.ExpandIntoStringLeaveEscaped("$(SomeStuff.ToLowerInvariant())_goop", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal("this is some stuff_goop", result); } /// <summary> /// Expand property function with a constant argument /// </summary> [Fact] public void PropertyFunctionPropertyWithArgument() { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); pg.Set(ProjectPropertyInstance.Create("SomeStuff", "This IS SOME STUff")); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); string result = expander.ExpandIntoStringLeaveEscaped("$(SomeStuff.SubString(13))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal("STUff", result); } /// <summary> /// Expand property function with a constant argument that contains spaces /// </summary> [Fact] public void PropertyFunctionPropertyWithArgumentWithSpaces() { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); pg.Set(ProjectPropertyInstance.Create("SomeStuff", "This IS SOME STUff")); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); string result = expander.ExpandIntoStringLeaveEscaped("$(SomeStuff.SubString(8))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal("SOME STUff", result); } /// <summary> /// Expand property function with a constant argument /// </summary> [Fact] public void PropertyFunctionPropertyPathRootSubtraction() { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); pg.Set(ProjectPropertyInstance.Create("RootPath", Path.Combine(s_rootPathPrefix, "this", "is", "the", "root"))); pg.Set(ProjectPropertyInstance.Create("MyPath", Path.Combine(s_rootPathPrefix, "this", "is", "the", "root", "my", "project", "is", "here.proj"))); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); string result = expander.ExpandIntoStringLeaveEscaped("$(MyPath.SubString($(RootPath.Length)))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal(Path.Combine(Path.DirectorySeparatorChar.ToString(), "my", "project", "is", "here.proj"), result); } /// <summary> /// Expand property function with an argument that is a property /// </summary> [Fact] public void PropertyFunctionPropertyWithArgumentExpandedProperty() { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); pg.Set(ProjectPropertyInstance.Create("Value", "3")); pg.Set(ProjectPropertyInstance.Create("SomeStuff", "This IS SOME STUff")); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); string result = expander.ExpandIntoStringLeaveEscaped("$(SomeStuff.SubString(1$(Value)))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal("STUff", result); } /// <summary> /// Expand property function that has a boolean return value /// </summary> [Fact] public void PropertyFunctionPropertyWithArgumentBooleanReturn() { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); pg.Set(ProjectPropertyInstance.Create("PathRoot", Path.Combine(s_rootPathPrefix, "goo"))); pg.Set(ProjectPropertyInstance.Create("PathRoot2", Path.Combine(s_rootPathPrefix, "goop") + Path.DirectorySeparatorChar)); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); string result = expander.ExpandIntoStringLeaveEscaped(@"$(PathRoot2.Endswith(" + Path.DirectorySeparatorChar + "))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal("True", result); result = expander.ExpandIntoStringLeaveEscaped(@"$(PathRoot.Endswith(" + Path.DirectorySeparatorChar + "))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal("False", result); } /// <summary> /// Expand property function with an argument that is expanded, and a chaining of other functions. /// </summary> [Fact] public void PropertyFunctionPropertyWithArgumentNestedAndChainedFunction() { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); pg.Set(ProjectPropertyInstance.Create("Value", "3")); pg.Set(ProjectPropertyInstance.Create("SomeStuff", "This IS SOME STUff")); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); string result = expander.ExpandIntoStringLeaveEscaped("$(SomeStuff.SubString(1$(Value)).ToLowerInvariant().SubString($(Value)))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal("ff", result); } /// <summary> /// Expand property function with chained functions on its results /// </summary> [Fact] public void PropertyFunctionPropertyWithArgumentChained() { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); pg.Set(ProjectPropertyInstance.Create("Value", "3")); pg.Set(ProjectPropertyInstance.Create("SomeStuff", "This IS SOME STUff")); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); string result = expander.ExpandIntoStringLeaveEscaped("$(SomeStuff.ToUpperInvariant().ToLowerInvariant())", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal("this is some stuff", result); } /// <summary> /// Expand property function with an argument that is a function /// </summary> [Fact] public void PropertyFunctionPropertyWithArgumentNested() { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); pg.Set(ProjectPropertyInstance.Create("Value", "12345")); pg.Set(ProjectPropertyInstance.Create("SomeStuff", "1234567890")); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); string result = expander.ExpandIntoStringLeaveEscaped("$(SomeStuff.SubString($(Value.get_Length())))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal("67890", result); } /// <summary> /// Expand property function that returns an generic list /// </summary> [Fact] public void PropertyFunctionGenericListReturn() { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); string result = expander.ExpandIntoStringLeaveEscaped("$([MSBuild]::__GetListTest())", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal("A;B;C;D", result); } /// <summary> /// Expand property function that returns an array /// </summary> [Fact] public void PropertyFunctionArrayReturn() { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); pg.Set(ProjectPropertyInstance.Create("List", "A-B-C-D")); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); string result = expander.ExpandIntoStringLeaveEscaped("$(List.Split(-))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal("A;B;C;D", result); } /// <summary> /// Expand property function that returns a Dictionary /// </summary> [Fact] [Trait("Category", "netcore-osx-failing")] [Trait("Category", "netcore-linux-failing")] [Trait("Category", "mono-osx-failing")] public void PropertyFunctionDictionaryReturn() { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); string result = expander.ExpandIntoStringLeaveEscaped("$([System.Environment]::GetEnvironmentVariables())", ExpanderOptions.ExpandProperties, MockElementLocation.Instance).ToUpperInvariant(); string expected = ("OS=" + Environment.GetEnvironmentVariable("OS")).ToUpperInvariant(); Assert.Contains(expected, result); } /// <summary> /// Expand property function that returns an array /// </summary> [Fact] public void PropertyFunctionArrayReturnManualSplitter() { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); pg.Set(ProjectPropertyInstance.Create("List", "A-B-C-D")); pg.Set(ProjectPropertyInstance.Create("Splitter", "-")); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); string result = expander.ExpandIntoStringLeaveEscaped("$(List.Split($(Splitter.ToCharArray())))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal("A;B;C;D", result); } /// <summary> /// Expand property function that returns an array /// </summary> [Fact] public void PropertyFunctionInCondition() { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); pg.Set(ProjectPropertyInstance.Create("PathRoot", Path.Combine(s_rootPathPrefix, "goo"))); pg.Set(ProjectPropertyInstance.Create("PathRoot2", Path.Combine(s_rootPathPrefix, "goop") + Path.DirectorySeparatorChar)); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); Assert.True( ConditionEvaluator.EvaluateCondition( @"'$(PathRoot2.Endswith(`" + Path.DirectorySeparatorChar + "`))' == 'true'", ParserOptions.AllowAll, expander, ExpanderOptions.ExpandProperties, Directory.GetCurrentDirectory(), MockElementLocation.Instance, null, new BuildEventContext(1, 2, 3, 4), FileSystems.Default)); Assert.True( ConditionEvaluator.EvaluateCondition( @"'$(PathRoot.EndsWith(" + Path.DirectorySeparatorChar + "))' == 'false'", ParserOptions.AllowAll, expander, ExpanderOptions.ExpandProperties, Directory.GetCurrentDirectory(), MockElementLocation.Instance, null, new BuildEventContext(1, 2, 3, 4), FileSystems.Default)); } /// <summary> /// Expand property function that is invalid - properties don't take arguments /// </summary> [Fact] public void PropertyFunctionInvalid1() { Assert.Throws<InvalidProjectFileException>(() => { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); pg.Set(ProjectPropertyInstance.Create("Value", "3")); pg.Set(ProjectPropertyInstance.Create("SomeStuff", "This IS SOME STUff")); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); expander.ExpandIntoStringLeaveEscaped("[$(SomeStuff($(Value)))]", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); } ); } /// <summary> /// Expand property function - invalid since properties don't have properties /// </summary> [Fact] public void PropertyFunctionInvalid2() { Assert.Throws<InvalidProjectFileException>(() => { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); pg.Set(ProjectPropertyInstance.Create("Value", "3")); pg.Set(ProjectPropertyInstance.Create("SomeStuff", "This IS SOME STUff")); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); expander.ExpandIntoStringLeaveEscaped("[$(SomeStuff.Lgg)]", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); } ); } /// <summary> /// Expand property function - invalid since properties don't have properties and don't support '.' in them /// </summary> [Fact] public void PropertyFunctionInvalid3() { Assert.Throws<InvalidProjectFileException>(() => { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); pg.Set(ProjectPropertyInstance.Create("Value", "3")); pg.Set(ProjectPropertyInstance.Create("SomeStuff", "This IS SOME STUff")); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); expander.ExpandIntoStringLeaveEscaped("$(SomeStuff.ToUpperInvariant().Foo)", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); } ); } /// <summary> /// Expand property function - properties don't take arguments /// </summary> [Fact] public void PropertyFunctionInvalid4() { Assert.Throws<InvalidProjectFileException>(() => { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); pg.Set(ProjectPropertyInstance.Create("Value", "3")); pg.Set(ProjectPropertyInstance.Create("SomeStuff", "This IS SOME STUff")); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); expander.ExpandIntoStringLeaveEscaped("[$(SomeStuff($(System.DateTime.Now)))]", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); } ); } /// <summary> /// Expand property function - invalid expression /// </summary> [Fact] public void PropertyFunctionInvalid5() { Assert.Throws<InvalidProjectFileException>(() => { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); pg.Set(ProjectPropertyInstance.Create("SomeStuff", "This IS SOME STUff")); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); expander.ExpandIntoStringLeaveEscaped("$(SomeStuff.ToLowerInvariant()_goop)", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); } ); } /// <summary> /// Expand property function - functions with invalid arguments /// </summary> [Fact] public void PropertyFunctionInvalid6() { Assert.Throws<InvalidProjectFileException>(() => { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); pg.Set(ProjectPropertyInstance.Create("SomeStuff", "This IS SOME STUff")); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); expander.ExpandIntoStringLeaveEscaped("[$(SomeStuff.Substring(HELLO!))]", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); } ); } /// <summary> /// Expand property function - functions with invalid arguments /// </summary> [Fact] public void PropertyFunctionInvalid7() { Assert.Throws<InvalidProjectFileException>(() => { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); pg.Set(ProjectPropertyInstance.Create("SomeStuff", "This IS SOME STUff")); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); expander.ExpandIntoStringLeaveEscaped("[$(SomeStuff.Substring(-10))]", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); } ); } /// <summary> /// Expand property function that calls a static method with quoted arguments /// </summary> [Fact] public void PropertyFunctionInvalid8() { Assert.Throws<InvalidProjectFileException>(() => { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); expander.ExpandIntoStringLeaveEscaped("$(([System.DateTime]::Now).ToString(\"MM.dd.yyyy\"))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); } ); } /// <summary> /// Expand property function - we don't handle metadata functions /// </summary> [Fact] public void PropertyFunctionInvalidNoMetadataFunctions() { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); string result = expander.ExpandIntoStringLeaveEscaped("[%(LowerLetterList.Identity.ToUpper())]", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal("[%(LowerLetterList.Identity.ToUpper())]", result); } /// <summary> /// Expand property function - properties won't get confused with a type or namespace /// </summary> [Fact] public void PropertyFunctionNoCollisionsOnType() { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); pg.Set(ProjectPropertyInstance.Create("System", "The System Namespace")); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); string result = expander.ExpandIntoStringLeaveEscaped("$(System)", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal("The System Namespace", result); } /// <summary> /// Expand property function that calls a static method /// </summary> [Fact] [Trait("Category", "netcore-osx-failing")] [Trait("Category", "netcore-linux-failing")] public void PropertyFunctionStaticMethodMakeRelative() { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); pg.Set(ProjectPropertyInstance.Create("ParentPath", Path.Combine(s_rootPathPrefix, "abc", "def"))); pg.Set(ProjectPropertyInstance.Create("FilePath", Path.Combine(s_rootPathPrefix, "abc", "def", "foo.cpp"))); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); string result = expander.ExpandIntoStringLeaveEscaped(@"$([MSBuild]::MakeRelative($(ParentPath), `$(FilePath)`))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal(@"foo.cpp", result); } /// <summary> /// Expand property function that calls a static method /// </summary> [Fact] public void PropertyFunctionStaticMethod1() { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); pg.Set(ProjectPropertyInstance.Create("Drive", s_rootPathPrefix)); pg.Set(ProjectPropertyInstance.Create("File", Path.Combine("foo", "file.txt"))); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); string result = expander.ExpandIntoStringLeaveEscaped(@"$([System.IO.Path]::Combine($(Drive), `$(File)`))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal(Path.Combine(s_rootPathPrefix, "foo", "file.txt"), result); } /// <summary> /// Expand property function that creates an instance of a type /// </summary> [Fact] public void PropertyFunctionConstructor1() { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); pg.Set(ProjectPropertyInstance.Create("ver1", @"1.2.3.4")); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); object result = expander.ExpandPropertiesLeaveTypedAndEscaped(@"$([System.Version]::new($(ver1)))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.IsType<Version>(result); Version v = (Version)result; Assert.Equal(1, v.Major); Assert.Equal(2, v.Minor); Assert.Equal(3, v.Build); Assert.Equal(4, v.Revision); } /// <summary> /// Expand property function that creates an instance of a type /// </summary> [Fact] public void PropertyFunctionConstructor2() { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); pg.Set(ProjectPropertyInstance.Create("ver1", @"1.2.3.4")); pg.Set(ProjectPropertyInstance.Create("ver2", @"2.2.3.4")); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); string result = expander.ExpandIntoStringLeaveEscaped(@"$([System.Version]::new($(ver1)).CompareTo($([System.Version]::new($(ver2)))))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal(@"-1", result); } /// <summary> /// Expand property function that is only available when MSBUILDENABLEALLPROPERTYFUNCTIONS=1 /// </summary> [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.Netcoreapp, "https://github.com/dotnet/coreclr/issues/15662")] public void PropertyStaticFunctionAllEnabled() { using (var env = TestEnvironment.Create()) { env.SetEnvironmentVariable("MSBUILDENABLEALLPROPERTYFUNCTIONS", "1"); PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); try { string result = expander.ExpandIntoStringLeaveEscaped("$([System.Type]::GetType(`System.Type`))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal("System.Type", result); } finally { AvailableStaticMethods.Reset_ForUnitTestsOnly(); } } } /// <summary> /// Expand property function that is defined (on CoreFX) in an assembly named after its full namespace. /// </summary> [Fact] public void PropertyStaticFunctioLocatedFromAssemblyWithNamespaceName() { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); string env = Environment.GetEnvironmentVariable("MSBUILDENABLEALLPROPERTYFUNCTIONS"); try { Environment.SetEnvironmentVariable("MSBUILDENABLEALLPROPERTYFUNCTIONS", "1"); string result = expander.ExpandIntoStringLeaveEscaped("$([System.Diagnostics.Process]::GetCurrentProcess().Id)", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); int pid; Assert.True(int.TryParse(result, out pid)); Assert.Equal(System.Diagnostics.Process.GetCurrentProcess().Id, pid); } finally { Environment.SetEnvironmentVariable("MSBUILDENABLEALLPROPERTYFUNCTIONS", env); AvailableStaticMethods.Reset_ForUnitTestsOnly(); } } /// <summary> /// Expand property function that is only available when MSBUILDENABLEALLPROPERTYFUNCTIONS=1, but cannot be found /// </summary> [Fact] public void PropertyStaticFunctionUsingNamespaceNotFound() { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); string env = Environment.GetEnvironmentVariable("MSBUILDENABLEALLPROPERTYFUNCTIONS"); try { Environment.SetEnvironmentVariable("MSBUILDENABLEALLPROPERTYFUNCTIONS", "1"); Assert.Throws<InvalidProjectFileException>(() => expander.ExpandIntoStringLeaveEscaped("$([Microsoft.FOO.FileIO.FileSystem]::CurrentDirectory)", ExpanderOptions.ExpandProperties, MockElementLocation.Instance)); Assert.Throws<InvalidProjectFileException>(() => expander.ExpandIntoStringLeaveEscaped("$([Foo.Baz]::new())", ExpanderOptions.ExpandProperties, MockElementLocation.Instance)); Assert.Throws<InvalidProjectFileException>(() => expander.ExpandIntoStringLeaveEscaped("$([Foo]::new())", ExpanderOptions.ExpandProperties, MockElementLocation.Instance)); Assert.Throws<InvalidProjectFileException>(() => expander.ExpandIntoStringLeaveEscaped("$([Foo.]::new())", ExpanderOptions.ExpandProperties, MockElementLocation.Instance)); Assert.Throws<InvalidProjectFileException>(() => expander.ExpandIntoStringLeaveEscaped("$([.Foo]::new())", ExpanderOptions.ExpandProperties, MockElementLocation.Instance)); Assert.Throws<InvalidProjectFileException>(() => expander.ExpandIntoStringLeaveEscaped("$([.]::new())", ExpanderOptions.ExpandProperties, MockElementLocation.Instance)); Assert.Throws<InvalidProjectFileException>(() => expander.ExpandIntoStringLeaveEscaped("$([]::new())", ExpanderOptions.ExpandProperties, MockElementLocation.Instance)); } finally { Environment.SetEnvironmentVariable("MSBUILDENABLEALLPROPERTYFUNCTIONS", env); AvailableStaticMethods.Reset_ForUnitTestsOnly(); } } /// <summary> /// Expand property function that calls a static method /// </summary> [Fact] [Trait("Category", "netcore-osx-failing")] [Trait("Category", "netcore-linux-failing")] public void PropertyFunctionStaticMethodQuoted1() { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); pg.Set(ProjectPropertyInstance.Create("File", Path.Combine("foo", "file.txt"))); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); string result = expander.ExpandIntoStringLeaveEscaped(@"$([System.IO.Path]::Combine(`" + s_rootPathPrefix + "`, `$(File)`))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal(Path.Combine(s_rootPathPrefix, "foo", "file.txt"), result); } /// <summary> /// Expand property function that calls a static method /// </summary> [Fact] public void PropertyFunctionStaticMethodQuoted1Spaces() { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); pg.Set(ProjectPropertyInstance.Create("File", "foo goo" + Path.DirectorySeparatorChar + "file.txt")); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); string result = expander.ExpandIntoStringLeaveEscaped(@"$([System.IO.Path]::Combine(`" + Path.Combine(s_rootPathPrefix, "foo goo") + "`, `$(File)`))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal(Path.Combine(s_rootPathPrefix, "foo goo", "foo goo", "file.txt"), result); } /// <summary> /// Expand property function that calls a static method /// </summary> [Fact] public void PropertyFunctionStaticMethodQuoted1Spaces2() { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); pg.Set(ProjectPropertyInstance.Create("File", Path.Combine("foo bar", "baz.txt"))); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); string result = expander.ExpandIntoStringLeaveEscaped(@"$([System.IO.Path]::Combine(`" + Path.Combine(s_rootPathPrefix, "foo baz") + @"`, `$(File)`))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal(Path.Combine(s_rootPathPrefix, "foo baz", "foo bar", "baz.txt"), result); } /// <summary> /// Expand property function that calls a static method /// </summary> [Fact] public void PropertyFunctionStaticMethodQuoted1Spaces3() { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); pg.Set(ProjectPropertyInstance.Create("File", Path.Combine("foo bar", "baz.txt"))); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); string result = expander.ExpandIntoStringLeaveEscaped(@"$([System.IO.Path]::Combine(`" + Path.Combine(s_rootPathPrefix, "foo baz") + @" `, `$(File)`))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal(Path.Combine(s_rootPathPrefix, "foo baz ", "foo bar", "baz.txt"), result); } /// <summary> /// Expand property function that calls a static method with quoted arguments /// </summary> [Fact] public void PropertyFunctionStaticMethodQuoted2() { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); string dateTime = "'" + _dateToParse + "'"; string result = expander.ExpandIntoStringLeaveEscaped("$([System.DateTime]::Parse(" + dateTime + ").ToString(\"yyyy/MM/dd HH:mm:ss\"))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal(System.DateTime.Parse(_dateToParse).ToString("yyyy/MM/dd HH:mm:ss"), result); } /// <summary> /// Expand property function that calls a static method with quoted arguments /// </summary> [Fact] public void PropertyFunctionStaticMethodQuoted3() { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); string dateTime = "'" + _dateToParse + "'"; string result = expander.ExpandIntoStringLeaveEscaped("$([System.DateTime]::Parse(" + dateTime + ").ToString(\"MM.dd.yyyy\"))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal(System.DateTime.Parse(_dateToParse).ToString("MM.dd.yyyy"), result); } /// <summary> /// Expand property function that calls a static method with quoted arguments /// </summary> [Fact] public void PropertyFunctionStaticMethodQuoted4() { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); string result = expander.ExpandIntoStringLeaveEscaped("$([System.DateTime]::Now.ToString(\"MM.dd.yyyy\"))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal(DateTime.Now.ToString("MM.dd.yyyy"), result); } /// <summary> /// Expand property function that calls a static method /// </summary> [Fact] public void PropertyFunctionStaticMethodNested() { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); pg.Set(ProjectPropertyInstance.Create("File", "foo" + Path.DirectorySeparatorChar + "file.txt")); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); string result = expander.ExpandIntoStringLeaveEscaped(@"$([System.IO.Path]::Combine(`" + s_rootPathPrefix + @"`, $([System.IO.Path]::Combine(`foo`,`file.txt`))))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal(Path.Combine(s_rootPathPrefix, "foo", "file.txt"), result); } /// <summary> /// Expand property function that calls a static method regex /// </summary> [Fact] public void PropertyFunctionStaticMethodRegex1() { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); pg.Set(ProjectPropertyInstance.Create("File", "foo" + Path.DirectorySeparatorChar + "file.txt")); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); // Support enum combines as Enum.Parse expects them string result = expander.ExpandIntoStringLeaveEscaped(@"$([System.Text.RegularExpressions.Regex]::IsMatch(`-42`, `^-?\d+(\.\d{2})?$`, `RegexOptions.IgnoreCase,RegexOptions.Singleline`))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal(@"True", result); // We support the C# style enum combining syntax too result = expander.ExpandIntoStringLeaveEscaped(@"$([System.Text.RegularExpressions.Regex]::IsMatch(`-42`, `^-?\d+(\.\d{2})?$`, System.Text.RegularExpressions.RegexOptions.IgnoreCase|RegexOptions.Singleline))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal(@"True", result); result = expander.ExpandIntoStringLeaveEscaped(@"$([System.Text.RegularExpressions.Regex]::IsMatch(`100 GBP`, `^-?\d+(\.\d{2})?$`))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal(@"False", result); } /// <summary> /// Expand property function that calls a static method with an instance method chained /// </summary> [Fact] public void PropertyFunctionStaticMethodChained() { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); string dateTime = "'" + _dateToParse + "'"; string result = expander.ExpandIntoStringLeaveEscaped(@"$([System.DateTime]::Parse(" + dateTime + ").ToString(`yyyy/MM/dd HH:mm:ss`))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal(DateTime.Parse(_dateToParse).ToString("yyyy/MM/dd HH:mm:ss"), result); } /// <summary> /// Expand property function that calls a static method available only on net46 (Environment.GetFolderPath) /// </summary> [Fact] public void PropertyFunctionGetFolderPath() { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); string result = expander.ExpandIntoStringLeaveEscaped(@"$([System.Environment]::GetFolderPath(SpecialFolder.System))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal(System.Environment.GetFolderPath(Environment.SpecialFolder.System), result); } /// <summary> /// The test exercises: RuntimeInformation / OSPlatform usage, static method invocation, static property invocation, method invocation expression as argument, call chain expression as argument /// </summary> [Theory] [InlineData( "$([System.Runtime.InteropServices.RuntimeInformation]::IsOSPlatform($([System.Runtime.InteropServices.OSPlatform]::Create($([System.Runtime.InteropServices.OSPlatform]::$$platform$$.ToString())))))", "True" )] [InlineData( @"$([System.Runtime.InteropServices.RuntimeInformation]::IsOSPlatform($([System.Runtime.InteropServices.OSPlatform]::$$platform$$)))", "True" )] [InlineData( "$([System.Runtime.InteropServices.RuntimeInformation]::OSArchitecture)", "$$architecture$$" )] [InlineData( "$([MSBuild]::IsOSPlatform($$platform$$))", "True" )] public void PropertyFunctionRuntimeInformation(string propertyFunction, string expectedExpansion) { Func<string, string, string, string> formatString = (aString, platform, architecture) => aString .Replace("$$platform$$", platform) .Replace("$$architecture$$", architecture); var pg = new PropertyDictionary<ProjectPropertyInstance>(); var expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); string currentPlatformString = Helpers.GetOSPlatformAsString(); var currentArchitectureString = RuntimeInformation.OSArchitecture.ToString(); propertyFunction = formatString(propertyFunction, currentPlatformString, currentArchitectureString); expectedExpansion = formatString(expectedExpansion, currentPlatformString, currentArchitectureString); var result = expander.ExpandIntoStringLeaveEscaped(propertyFunction, ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal(expectedExpansion, result); } [Fact] public void IsOsPlatformShouldBeCaseInsensitiveToParameter() { var pg = new PropertyDictionary<ProjectPropertyInstance>(); var expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); var osPlatformLowerCase = Helpers.GetOSPlatformAsString().ToLower(); var result = expander.ExpandIntoStringLeaveEscaped($"$([MSBuild]::IsOsPlatform({osPlatformLowerCase}))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal("True", result); } /// <summary> /// Expand property function that calls a method with an enum parameter /// </summary> [Fact] public void PropertyFunctionStaticMethodEnumArgument() { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); string result = expander.ExpandIntoStringLeaveEscaped("$([System.String]::Equals(`a`, `A`, StringComparison.OrdinalIgnoreCase))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal(true.ToString(), result); } /// <summary> /// Expand intrinsic property function to locate the directory of a file above /// </summary> [Fact] public void PropertyFunctionStaticMethodDirectoryNameOfFileAbove() { string tempPath = Path.GetTempPath(); string tempFile = Path.GetFileName(FileUtilities.GetTemporaryFile()); try { string directoryStart = Path.Combine(tempPath, "one\\two\\three\\four\\five"); PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); pg.Set(ProjectPropertyInstance.Create("StartingDirectory", directoryStart)); pg.Set(ProjectPropertyInstance.Create("FileToFind", tempFile)); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); string result = expander.ExpandIntoStringAndUnescape(@"$([MSBuild]::GetDirectoryNameOfFileAbove($(StartingDirectory), $(FileToFind)))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal(Microsoft.Build.Shared.FileUtilities.EnsureTrailingSlash(tempPath), Microsoft.Build.Shared.FileUtilities.EnsureTrailingSlash(result)); result = expander.ExpandIntoStringAndUnescape(@"$([MSBuild]::GetDirectoryNameOfFileAbove($(StartingDirectory), Hobbits))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal(String.Empty, result); } finally { File.Delete(tempFile); } } /// <summary> /// Verifies that <see cref="IntrinsicFunctions.GetPathOfFileAbove"/> returns the correct path if a file exists /// or an empty string if it doesn't. /// </summary> [Fact] public void PropertyFunctionStaticMethodGetPathOfFileAbove() { // Set element location to a file deep in the directory structure. This is where the function should start looking // MockElementLocation mockElementLocation = new MockElementLocation(Path.Combine(ObjectModelHelpers.TempProjectDir, "one", "two", "three", "four", "five", Path.GetRandomFileName())); string fileToFind = FileUtilities.GetTemporaryFile(ObjectModelHelpers.TempProjectDir, ".tmp"); try { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); pg.Set(ProjectPropertyInstance.Create("FileToFind", Path.GetFileName(fileToFind))); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); string result = expander.ExpandIntoStringAndUnescape(@"$([MSBuild]::GetPathOfFileAbove($(FileToFind)))", ExpanderOptions.ExpandProperties, mockElementLocation); Assert.Equal(fileToFind, result); result = expander.ExpandIntoStringAndUnescape(@"$([MSBuild]::GetPathOfFileAbove('Hobbits'))", ExpanderOptions.ExpandProperties, mockElementLocation); Assert.Equal(String.Empty, result); } finally { ObjectModelHelpers.DeleteTempProjectDirectory(); } } /// <summary> /// Verifies that the usage of GetPathOfFileAbove() within an in-memory project throws an exception. /// </summary> [Fact] public void PropertyFunctionStaticMethodGetPathOfFileAboveInMemoryProject() { InvalidProjectFileException exception = Assert.Throws<InvalidProjectFileException>(() => { ObjectModelHelpers.CreateInMemoryProject("<Project><PropertyGroup><foo>$([MSBuild]::GetPathOfFileAbove('foo'))</foo></PropertyGroup></Project>"); }); Assert.StartsWith("The expression \"[MSBuild]::GetPathOfFileAbove(foo, \'\')\" cannot be evaluated.", exception.Message); } /// <summary> /// Verifies that <see cref="IntrinsicFunctions.GetPathOfFileAbove"/> only accepts a file name. /// </summary> [Fact] public void PropertyFunctionStaticMethodGetPathOfFileAboveFileNameOnly() { string fileWithPath = Path.Combine("foo", "bar", "file.txt"); InvalidProjectFileException exception = Assert.Throws<InvalidProjectFileException>(() => { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); pg.Set(ProjectPropertyInstance.Create("FileWithPath", fileWithPath)); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); expander.ExpandIntoStringLeaveEscaped(@"$([MSBuild]::GetPathOfFileAbove($(FileWithPath)))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); }); Assert.Contains(ResourceUtilities.FormatResourceStringStripCodeAndKeyword("InvalidGetPathOfFileAboveParameter", fileWithPath), exception.Message); } /// <summary> /// Expand property function that calls GetCultureInfo /// </summary> [Fact] public void PropertyFunctionStaticMethodGetCultureInfo() { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); #if FEATURE_CULTUREINFO_GETCULTURES string result = expander.ExpandIntoStringLeaveEscaped(@"$([System.Globalization.CultureInfo]::GetCultureInfo(`en-US`).ToString())", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); #else string result = expander.ExpandIntoStringLeaveEscaped(@"$([System.Globalization.CultureInfo]::new(`en-US`).ToString())", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); #endif Assert.Equal(new CultureInfo("en-US").ToString(), result); } /// <summary> /// Expand property function that calls a static arithmetic method /// </summary> [Fact] public void PropertyFunctionStaticMethodArithmeticAddInt32() { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); string result = expander.ExpandIntoStringLeaveEscaped(@"$([MSBuild]::Add(40, 2))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal((40 + 2).ToString(), result); } /// <summary> /// Expand property function that calls a static arithmetic method /// </summary> [Fact] public void PropertyFunctionStaticMethodArithmeticAddDouble() { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); string result = expander.ExpandIntoStringLeaveEscaped(@"$([MSBuild]::Add(39.9, 2.1))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal((39.9 + 2.1).ToString(), result); } /// <summary> /// Expand property function choosing either the value (if not empty) or the default specified /// </summary> [Fact] public void PropertyFunctionValueOrDefault() { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); string result = expander.ExpandIntoStringLeaveEscaped(@"$([MSBuild]::ValueOrDefault('', '42'))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal("42", result); result = expander.ExpandIntoStringLeaveEscaped(@"$([MSBuild]::ValueOrDefault('42', '43'))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal("42", result); } /// <summary> /// Expand property function choosing either the value (from the environment) or the default specified /// </summary> [Fact] public void PropertyFunctionValueOrDefaultFromEnvironment() { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); pg["BonkersTargetsPath"] = ProjectPropertyInstance.Create("BonkersTargetsPath", "Bonkers"); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); string result = expander.ExpandIntoStringLeaveEscaped(@"$([MSBuild]::ValueOrDefault('$(BonkersTargetsPath)', '42'))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal("Bonkers", result); pg["BonkersTargetsPath"] = ProjectPropertyInstance.Create("BonkersTargetsPath", String.Empty); result = expander.ExpandIntoStringLeaveEscaped(@"$([MSBuild]::ValueOrDefault('$(BonkersTargetsPath)', '43'))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal("43", result); } #if FEATURE_APPDOMAIN /// <summary> /// Expand property function that tests for existence of the task host /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void PropertyFunctionDoesTaskHostExist() { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); string result = expander.ExpandIntoStringLeaveEscaped(@"$([MSBuild]::DoesTaskHostExist('CurrentRuntime', 'CurrentArchitecture'))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); // This is the current, so it had better be true! Assert.Equal("true", result, true); } /// <summary> /// Expand property function that tests for existence of the task host /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void PropertyFunctionDoesTaskHostExist_Whitespace() { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); string result = expander.ExpandIntoStringLeaveEscaped(@"$([MSBuild]::DoesTaskHostExist(' CurrentRuntime ', 'CurrentArchitecture'))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); // This is the current, so it had better be true! Assert.Equal("true", result, true); } #endif [Fact] public void PropertyFunctionNormalizeDirectory() { Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(new PropertyDictionary<ProjectPropertyInstance>(new[] { ProjectPropertyInstance.Create("MyPath", "one"), ProjectPropertyInstance.Create("MySecondPath", "two"), }), FileSystems.Default); Assert.Equal( $"{Path.GetFullPath("one")}{Path.DirectorySeparatorChar}", expander.ExpandIntoStringAndUnescape(@"$([MSBuild]::NormalizeDirectory($(MyPath)))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance)); Assert.Equal( $"{Path.GetFullPath(Path.Combine("one", "two"))}{Path.DirectorySeparatorChar}", expander.ExpandIntoStringAndUnescape(@"$([MSBuild]::NormalizeDirectory($(MyPath), $(MySecondPath)))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance)); } /// <summary> /// Expand property function that tests for existence of the task host /// </summary> [Fact] public void PropertyFunctionDoesTaskHostExist_Error() { Assert.Throws<InvalidProjectFileException>(() => { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); expander.ExpandIntoStringLeaveEscaped(@"$([MSBuild]::DoesTaskHostExist('ASDF', 'CurrentArchitecture'))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); // We should have failed before now Assert.True(false); } ); } #if FEATURE_APPDOMAIN /// <summary> /// Expand property function that tests for existence of the task host /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void PropertyFunctionDoesTaskHostExist_Evaluated() { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); pg["Runtime"] = ProjectPropertyInstance.Create("Runtime", "CurrentRuntime"); pg["Architecture"] = ProjectPropertyInstance.Create("Architecture", "CurrentArchitecture"); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); string result = expander.ExpandIntoStringLeaveEscaped(@"$([MSBuild]::DoesTaskHostExist('$(Runtime)', '$(Architecture)'))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); // This is the current, so it had better be true! Assert.Equal("true", result, true); } #endif #if FEATURE_APPDOMAIN /// <summary> /// Expand property function that tests for existence of the task host /// </summary> [Fact] public void PropertyFunctionDoesTaskHostExist_NonexistentTaskHost() { string taskHostName = Environment.GetEnvironmentVariable("MSBUILDTASKHOST_EXE_NAME"); try { Environment.SetEnvironmentVariable("MSBUILDTASKHOST_EXE_NAME", "asdfghjkl.exe"); NodeProviderOutOfProcTaskHost.ClearCachedTaskHostPaths(); PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); string result = expander.ExpandIntoStringLeaveEscaped(@"$([MSBuild]::DoesTaskHostExist('CLR2', 'CurrentArchitecture'))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); // CLR has been forced to pretend not to exist, whether it actually does or not Assert.Equal("false", result, true); } finally { Environment.SetEnvironmentVariable("MSBUILDTASKHOST_EXE_NAME", taskHostName); NodeProviderOutOfProcTaskHost.ClearCachedTaskHostPaths(); } } #endif /// <summary> /// Expand property function that calls a static bitwise method to retrieve file attribute /// </summary> [Fact] [Trait("Category", "netcore-osx-failing")] [Trait("Category", "netcore-linux-failing")] [Trait("Category", "mono-osx-failing")] public void PropertyFunctionStaticMethodFileAttributes() { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); string tempFile = FileUtilities.GetTemporaryFile(); try { File.SetAttributes(tempFile, FileAttributes.ReadOnly | FileAttributes.Archive); string result = expander.ExpandIntoStringLeaveEscaped(@"$([MSBuild]::BitwiseAnd(32,$([System.IO.File]::GetAttributes(" + tempFile + "))))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal("32", result); } finally { File.SetAttributes(tempFile, FileAttributes.Normal); File.Delete(tempFile); } } /// <summary> /// Expand intrinsic property function calls a static arithmetic method /// </summary> [Fact] public void PropertyFunctionStaticMethodIntrinsicMaths() { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); string result = expander.ExpandIntoStringLeaveEscaped(@"$([MSBuild]::Add(39.9, 2.1))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal((39.9 + 2.1).ToString(), result); result = expander.ExpandIntoStringLeaveEscaped(@"$([MSBuild]::Add(40, 2))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal((40 + 2).ToString(), result); result = expander.ExpandIntoStringLeaveEscaped(@"$([MSBuild]::Subtract(44, 2))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal((44 - 2).ToString(), result); result = expander.ExpandIntoStringLeaveEscaped(@"$([MSBuild]::Subtract(42.9, 0.9))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal((42.9 - 0.9).ToString(), result); result = expander.ExpandIntoStringLeaveEscaped(@"$([MSBuild]::Multiply(21, 2))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal((21 * 2).ToString(), result); result = expander.ExpandIntoStringLeaveEscaped(@"$([MSBuild]::Multiply(84.0, 0.5))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal((84.0 * 0.5).ToString(), result); result = expander.ExpandIntoStringLeaveEscaped(@"$([MSBuild]::Divide(84, 2))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal((84 / 2).ToString(), result); result = expander.ExpandIntoStringLeaveEscaped(@"$([MSBuild]::Divide(84.4, 2.0))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal((84.4 / 2.0).ToString(), result); result = expander.ExpandIntoStringLeaveEscaped(@"$([MSBuild]::Modulo(85, 2))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal((85 % 2).ToString(), result); result = expander.ExpandIntoStringLeaveEscaped(@"$([MSBuild]::Modulo(2345.5, 43))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal((2345.5 % 43).ToString(), result); // test for overflow wrapping result = expander.ExpandIntoStringLeaveEscaped(@"$([MSBuild]::Add(9223372036854775807, 20))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); double expectedResult = 9223372036854775807D + 20D; Assert.Equal(expectedResult.ToString(), result); result = expander.ExpandIntoStringLeaveEscaped(@"$([MSBuild]::BitwiseOr(40, 2))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal((40 | 2).ToString(), result); result = expander.ExpandIntoStringLeaveEscaped(@"$([MSBuild]::BitwiseAnd(42, 2))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal((42 & 2).ToString(), result); result = expander.ExpandIntoStringLeaveEscaped(@"$([MSBuild]::BitwiseXor(213, 255))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal((213 ^ 255).ToString(), result); result = expander.ExpandIntoStringLeaveEscaped(@"$([MSBuild]::BitwiseNot(-43))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal((~-43).ToString(), result); } /// <summary> /// Expand a property reference that has whitespace around the property name (should result in empty) /// </summary> [Fact] public void PropertySimpleSpaced() { PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); pg.Set(ProjectPropertyInstance.Create("SomeStuff", "This IS SOME STUff")); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); string result = expander.ExpandIntoStringLeaveEscaped(@"$( SomeStuff )", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal(String.Empty, result); } #if FEATURE_WIN32_REGISTRY [Fact] public void PropertyFunctionGetRegitryValue() { try { string envVar = NativeMethodsShared.IsWindows ? "TEMP" : "USER"; PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); pg.Set(ProjectPropertyInstance.Create("SomeProperty", "Value")); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); RegistryKey key = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\MSBuild_test"); key.SetValue("Value", "%" + envVar + "%", RegistryValueKind.ExpandString); string result = expander.ExpandIntoStringLeaveEscaped(@"$([MSBuild]::GetRegistryValue('HKEY_CURRENT_USER\Software\Microsoft\MSBuild_test', '$(SomeProperty)'))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal(Environment.GetEnvironmentVariable(envVar), result); } finally { Registry.CurrentUser.DeleteSubKey(@"Software\Microsoft\MSBuild_test"); } } [Fact] public void PropertyFunctionGetRegitryValueDefault() { try { string envVar = NativeMethodsShared.IsWindows ? "TEMP" : "USER"; PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); pg.Set(ProjectPropertyInstance.Create("SomeProperty", "Value")); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); RegistryKey key = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\MSBuild_test"); key.SetValue(String.Empty, "%" + envVar + "%", RegistryValueKind.ExpandString); string result = expander.ExpandIntoStringLeaveEscaped(@"$([MSBuild]::GetRegistryValue('HKEY_CURRENT_USER\Software\Microsoft\MSBuild_test', null))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal(Environment.GetEnvironmentVariable(envVar), result); } finally { Registry.CurrentUser.DeleteSubKey(@"Software\Microsoft\MSBuild_test"); } } [Fact] public void PropertyFunctionGetRegistryValueFromView1() { try { string envVar = NativeMethodsShared.IsWindows ? "TEMP" : "USER"; PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); pg.Set(ProjectPropertyInstance.Create("SomeProperty", "Value")); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); RegistryKey key = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\MSBuild_test"); key.SetValue(String.Empty, "%" + envVar + "%", RegistryValueKind.ExpandString); string result = expander.ExpandIntoStringLeaveEscaped(@"$([MSBuild]::GetRegistryValueFromView('HKEY_CURRENT_USER\Software\Microsoft\MSBuild_test', null, null, RegistryView.Default, RegistryView.Default))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal(Environment.GetEnvironmentVariable(envVar), result); } finally { Registry.CurrentUser.DeleteSubKey(@"Software\Microsoft\MSBuild_test"); } } [Fact] public void PropertyFunctionGetRegistryValueFromView2() { try { string envVar = NativeMethodsShared.IsWindows ? "TEMP" : "USER"; PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); pg.Set(ProjectPropertyInstance.Create("SomeProperty", "Value")); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); RegistryKey key = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\MSBuild_test"); key.SetValue(String.Empty, "%" + envVar + "%", RegistryValueKind.ExpandString); string result = expander.ExpandIntoStringLeaveEscaped(@"$([MSBuild]::GetRegistryValueFromView('HKEY_CURRENT_USER\Software\Microsoft\MSBuild_test', null, null, Microsoft.Win32.RegistryView.Default))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal(Environment.GetEnvironmentVariable(envVar), result); } finally { Registry.CurrentUser.DeleteSubKey(@"Software\Microsoft\MSBuild_test"); } } #endif /// <summary> /// Expand a property function that references item metadata /// </summary> [Fact] public void PropertyFunctionConsumingItemMetadata() { ProjectInstance project = ProjectHelpers.CreateEmptyProjectInstance(); PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); Dictionary<string, string> itemMetadataTable = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); itemMetadataTable["Compile.Identity"] = "fOo.Cs"; StringMetadataTable itemMetadata = new StringMetadataTable(itemMetadataTable); List<ProjectItemInstance> ig = new List<ProjectItemInstance>(); pg.Set(ProjectPropertyInstance.Create("SomePath", Path.Combine(s_rootPathPrefix, "some", "path"))); ig.Add(new ProjectItemInstance(project, "Compile", "fOo.Cs", project.FullPath)); ItemDictionary<ProjectItemInstance> itemsByType = new ItemDictionary<ProjectItemInstance>(); itemsByType.ImportItems(ig); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, itemsByType, itemMetadata, FileSystems.Default); string result = expander.ExpandIntoStringLeaveEscaped(@"$([System.IO.Path]::Combine($(SomePath),%(Compile.Identity)))", ExpanderOptions.ExpandAll, MockElementLocation.Instance); Assert.Equal(Path.Combine(s_rootPathPrefix, "some", "path", "fOo.Cs"), result); } /// <summary> /// A whole bunch error check tests /// </summary> [Fact] public void Medley() { // Make absolutely sure that the static method cache hasn't been polluted by the other tests. AvailableStaticMethods.Reset_ForUnitTestsOnly(); PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); pg.Set(ProjectPropertyInstance.Create("File", @"foo\file.txt")); pg.Set(ProjectPropertyInstance.Create("a", "no")); pg.Set(ProjectPropertyInstance.Create("b", "true")); pg.Set(ProjectPropertyInstance.Create("c", "1")); pg.Set(ProjectPropertyInstance.Create("position", "4")); pg.Set(ProjectPropertyInstance.Create("d", "xxx")); pg.Set(ProjectPropertyInstance.Create("e", "xxx")); pg.Set(ProjectPropertyInstance.Create("and", "and")); pg.Set(ProjectPropertyInstance.Create("a_semi_b", "a;b")); pg.Set(ProjectPropertyInstance.Create("a_apos_b", "a'b")); pg.Set(ProjectPropertyInstance.Create("foo_apos_foo", "foo'foo")); pg.Set(ProjectPropertyInstance.Create("a_escapedsemi_b", "a%3bb")); pg.Set(ProjectPropertyInstance.Create("a_escapedapos_b", "a%27b")); pg.Set(ProjectPropertyInstance.Create("has_trailing_slash", @"foo\")); pg.Set(ProjectPropertyInstance.Create("emptystring", @"")); pg.Set(ProjectPropertyInstance.Create("space", @" ")); pg.Set(ProjectPropertyInstance.Create("listofthings", @"a;b;c;d;e;f;g;h;i;j;k;l")); pg.Set(ProjectPropertyInstance.Create("input", @"EXPORT a")); pg.Set(ProjectPropertyInstance.Create("propertycontainingnullasastring", @"null")); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); var validTests = new List<string[]> { new string[] {"$(input.ToString()[1])", "X"}, new string[] {"$(input[1])", "X"}, new string[] {"$(listofthings.Split(';')[$(position)])","e"}, new string[] {@"$([System.Text.RegularExpressions.Regex]::Match($(Input), `EXPORT\s+(.+)`).Groups[1].Value)","a"}, new string[] {"$([MSBuild]::Add(1,2).CompareTo(3))", "0"}, new string[] {"$([MSBuild]::Add(1,2).CompareTo(3))", "0"}, new string[] {"$([MSBuild]::Add(1,2).CompareTo(3.0))", "0"}, new string[] {"$([MSBuild]::Add(1,2).CompareTo('3'))", "0"}, new string[] {"$([MSBuild]::Add(1,2).CompareTo(3.1))", "-1"}, new string[] {"$([MSBuild]::Add(1,2).CompareTo(2))", "1"}, new string[] {"$([MSBuild]::Add(1,2).Equals(3))", "True"}, new string[] {"$([MSBuild]::Add(1,2).Equals(3.0))", "True"}, new string[] {"$([MSBuild]::Add(1,2).Equals('3'))", "True"}, new string[] {"$([MSBuild]::Add(1,2).Equals(3.1))", "False"}, new string[] {"$(a.Insert(0,'%28'))", "%28no"}, new string[] {"$(a.Insert(0,'\"'))", "\"no"}, new string[] {"$(a.Insert(0,'(('))", "%28%28no"}, new string[] {"$(a.Insert(0,'))'))", "%29%29no"}, new string[] {"A$(Reg:A)A", "AA"}, new string[] {"A$(Reg:AA)", "A"}, new string[] {"$(Reg:AA)", ""}, new string[] {"$(Reg:AAAA)", ""}, new string[] {"$(Reg:AAA)", ""}, new string[] {"$([MSBuild]::Add(2,$([System.Convert]::ToInt64('28', 16))))", "42"}, new string[] {"$([MSBuild]::Add(2,$([System.Convert]::ToInt64('28', $([System.Convert]::ToInt32(16))))))", "42"}, new string[] {"$(e.Length.ToString())", "3"}, new string[] {"$(e.get_Length().ToString())", "3"}, new string[] {"$(emptystring.Length)", "0" }, new string[] {"$(space.Length)", "1" }, new string[] {"$([System.TimeSpan]::Equals(null, null))", "True"}, // constant, unquoted null is a special value new string[] {"$([MSBuild]::Add(40,null))", "40"}, new string[] {"$([MSBuild]::Add( 40 , null ))", "40"}, new string[] {"$([MSBuild]::Add(null,40))", "40"}, new string[] {"$([MSBuild]::Escape(';'))", "%3b"}, new string[] {"$([MSBuild]::UnEscape('%3b'))", ";"}, new string[] {"$(e.Substring($(e.Length)))", ""}, new string[] {"$([System.Int32]::MaxValue)", System.Int32.MaxValue.ToString()}, new string[] {"x$()", "x"}, new string[] {"A$(Reg:A)A", "AA"}, new string[] {"A$(Reg:AA)", "A"}, new string[] {"$(Reg:AA)", ""}, new string[] {"$(Reg:AAAA)", ""}, new string[] {"$(Reg:AAA)", ""} }; var errorTests = new List<string>{ "$(input[)", "$(input.ToString()])", "$(input.ToString()[)", "$(input.ToString()[12])", "$(input[])", "$(input[-1])", "$(listofthings.Split(';')[)", "$(listofthings.Split(';')['goo'])", "$(listofthings.Split(';')[])", "$(listofthings.Split(';')[-1])", "$([]::())", @" $( $( [System.IO]::Path.GetDirectory('c:\foo\bar\baz.txt') ).Substring( '$([System.IO]::Path.GetPathRoot( '$([System.IO]::Path.GetDirectory('c:\foo\bar\baz.txt'))' ).Length)' ) ", "$([Microsoft.VisualBasic.FileIO.FileSystem]::CurrentDirectory)", // not allowed "$(e.Length..ToString())", "$(SomeStuff.get_Length(null))", "$(SomeStuff.Substring((1)))", "$(b.Substring(-10, $(c)))", "$(b.Substring(-10, $(emptystring)))", "$(b.Substring(-10, $(space)))", "$([MSBuild]::Add.Sub(null,40))", "$([MSBuild]::Add( ,40))", // empty parameter is empty string "$([MSBuild]::Add('',40))", // empty quoted parameter is empty string "$([MSBuild]::Add(40,,,))", "$([MSBuild]::Add(40, ,,))", "$([MSBuild]::Add(40,)", "$([MSBuild]::Add(40,X)", "$([MSBuild]::Add(40,", "$([MSBuild]::Add(40", "$([MSBuild]::Add(,))", // gives "Late bound operations cannot be performed on types or methods for which ContainsGenericParameters is true." "$([System.TimeSpan]::Equals(,))", // empty parameter is interpreted as empty string "$([System.TimeSpan]::Equals($(space),$(emptystring)))", // empty parameter is interpreted as empty string "$([System.TimeSpan]::Equals($(emptystring),$(emptystring)))", // empty parameter is interpreted as empty string "$([MSBuild]::Add($(PropertyContainingNullAsAString),40))", // a property containing the word null is a string "null" "$([MSBuild]::Add('null',40))", // the word null is a string "null" "$(SomeStuff.Substring(-10))", "$(.Length)", "$(.Substring(1))", "$(.get_Length())", "$(e.)", "$(e..)", "$(e..Length)", "$(e$(d).Length)", "$($(d).Length)", "$(e`.Length)", "$([System.IO.Path]Combine::Combine(`a`,`b`))", "$([System.IO.Path]::Combine((`a`,`b`))", "$([System.IO.Path]Combine(::Combine(`a`,`b`))", "$([System.IO.Path]Combine(`::Combine(`a`,`b`)`, `b`)`)", "$([System.IO.Path]::`Combine(`a`, `b`)`)", "$([System.IO.Path]::(`Combine(`a`, `b`)`))", "$([System.DateTime]foofoo::Now)", "$([System.DateTime].Now)", "$([].Now)", "$([ ].Now)", "$([ .Now)", "$([])", "$([ )", "$([ ])", "$([System.Diagnostics.Process]::Start(`NOTEPAD.EXE`))", "$([[]]::Start(`NOTEPAD.EXE`))", "$([(::Start(`NOTEPAD.EXE`))", "$([Goop]::Start(`NOTEPAD.EXE`))", "$([System.Threading.Thread]::CurrentThread)", "$", "$(", "$((", "@", "@(", "@()", "%", "%(", "%()", "exists", "exists(", "exists()", "exists( )", "exists(,)", "@(x->'", "@(x->''", "@(x-", "@(x->'x','", "@(x->'x',''", "@(x->'x','')", "-1>x", "\n", "\t", "+-1", "$(SomeStuff.)", "$(SomeStuff.!)", "$(SomeStuff.`)", "$(SomeStuff.GetType)", "$(goop.baz`)", "$(SomeStuff.Substring(HELLO!))", "$(SomeStuff.ToLowerInvariant()_goop)", "$(SomeStuff($(System.DateTime.Now)))", "$(System.Foo.Bar.Lgg)", "$(SomeStuff.Lgg)", "$(SomeStuff($(Value)))", "$(e.$(e.Length))", "$(e.Substring($(e.Substring(,)))", "$(e.Substring($(e.Substring(a)))", "$(e.Substring($([System.IO.Path]::Combine(`a`, `b`))))", "$([]::())", "$((((", "$($())", "$", "()" }; #if !RUNTIME_TYPE_NETCORE if (NativeMethodsShared.IsWindows) { // '|' is only an invalid character in Windows filesystems errorTests.Add("$([System.IO.Path]::Combine(`|`,`b`))"); } #endif #if FEATURE_WIN32_REGISTRY if (NativeMethodsShared.IsWindows) { errorTests.Add("$(Registry:X)"); } #endif if (!NativeMethodsShared.IsWindows) { // If no registry or not running on windows, this gets expanded to the empty string // example: xplat build running on OSX validTests.Add(new string[]{"$(Registry:X)", ""}); } string result; for (int i = 0; i < validTests.Count; i++) { result = expander.ExpandIntoStringLeaveEscaped(validTests[i][0], ExpanderOptions.ExpandProperties, MockElementLocation.Instance); if (!String.Equals(result, validTests[i][1])) { string message = "FAILURE: " + validTests[i][0] + " expanded to '" + result + "' instead of '" + validTests[i][1] + "'"; Console.WriteLine(message); Assert.True(false, message); } else { Console.WriteLine(validTests[i][0] + " expanded to '" + result + "'"); } } for (int i = 0; i < errorTests.Count; i++) { // If an expression is invalid, // - Expansion may throw InvalidProjectFileException, or // - return the original unexpanded expression bool success = true; bool caughtException = false; result = String.Empty; try { result = expander.ExpandIntoStringLeaveEscaped(errorTests[i], ExpanderOptions.ExpandProperties, MockElementLocation.Instance); if (String.Compare(result, errorTests[i]) == 0) { Console.WriteLine(errorTests[i] + " did not expand."); success = false; } } catch (InvalidProjectFileException ex) { Console.WriteLine(errorTests[i] + " caused '" + ex.Message + "'"); caughtException = true; } Assert.True( (success == false || caughtException == true), "FAILURE: Expected '" + errorTests[i] + "' to not parse or not be evaluated but it evaluated to '" + result + "'" ); } } [Fact] public void PropertyFunctionEnsureTrailingSlash() { string path = Path.Combine("foo", "bar"); PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); pg.Set(ProjectPropertyInstance.Create("SomeProperty", path)); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); // Verify a constant expands properly string result = expander.ExpandIntoStringLeaveEscaped($"$([MSBuild]::EnsureTrailingSlash('{path}'))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal(path + Path.DirectorySeparatorChar, result); // Verify that a property expands properly result = expander.ExpandIntoStringLeaveEscaped("$([MSBuild]::EnsureTrailingSlash($(SomeProperty)))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.Equal(path + Path.DirectorySeparatorChar, result); } [Fact] public void PropertyFunctionWithNewLines() { const string propertyFunction = @"$(SomeProperty .Substring(0, 10) .ToString() .Substring(0, 5) .ToString())"; PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); pg.Set(ProjectPropertyInstance.Create("SomeProperty", "6C8546D5297C424F962201B0E0E9F142")); Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, FileSystems.Default); string result = expander.ExpandIntoStringLeaveEscaped(propertyFunction, ExpanderOptions.ExpandProperties, MockElementLocation.Instance); result.ShouldBe("6C854"); } [Fact] public void PropertyFunctionStringIndexOfAny() { TestPropertyFunction("$(prop.IndexOfAny('y'))", "prop", "x-y-z", "2"); } [Fact] public void PropertyFunctionStringLastIndexOf() { TestPropertyFunction("$(prop.LastIndexOf('y'))", "prop", "x-x-y-y-y-z", "8"); TestPropertyFunction("$(prop.LastIndexOf('y', 7))", "prop", "x-x-y-y-y-z", "6"); } [Fact] public void PropertyFunctionStringCopy() { string propertyFunction = @"$([System.String]::Copy($(X)).LastIndexOf( '.designer.cs', System.StringComparison.OrdinalIgnoreCase))"; TestPropertyFunction(propertyFunction, "X", "test.designer.cs", "4"); } [Fact] public void PropertyFunctionVersionParse() { TestPropertyFunction(@"$([System.Version]::Parse('$(X)').ToString(1))", "X", "4.0", "4"); } [Fact] public void PropertyFunctionGuidNewGuid() { var expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(new PropertyDictionary<ProjectPropertyInstance>(), FileSystems.Default); string result = expander.ExpandIntoStringLeaveEscaped("$([System.Guid]::NewGuid())", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); Assert.True(Guid.TryParse(result, out Guid guid)); } [Fact] public void PropertyFunctionIntrinsicFunctionGetCurrentToolsDirectory() { TestPropertyFunction("$([Microsoft.Build.Evaluation.IntrinsicFunctions]::GetCurrentToolsDirectory())", "X", "_", EscapingUtilities.Escape(IntrinsicFunctions.GetCurrentToolsDirectory())); } [Fact] public void PropertyFunctionIntrinsicFunctionGetToolsDirectory32() { TestPropertyFunction("$([Microsoft.Build.Evaluation.IntrinsicFunctions]::GetToolsDirectory32())", "X", "_", EscapingUtilities.Escape(IntrinsicFunctions.GetToolsDirectory32())); } [Fact] public void PropertyFunctionIntrinsicFunctionGetToolsDirectory64() { TestPropertyFunction("$([Microsoft.Build.Evaluation.IntrinsicFunctions]::GetToolsDirectory64())", "X", "_", EscapingUtilities.Escape(IntrinsicFunctions.GetToolsDirectory64())); } [Fact] public void PropertyFunctionIntrinsicFunctionGetMSBuildSDKsPath() { TestPropertyFunction("$([Microsoft.Build.Evaluation.IntrinsicFunctions]::GetMSBuildSDKsPath())", "X", "_", EscapingUtilities.Escape(IntrinsicFunctions.GetMSBuildSDKsPath())); } [Fact] public void PropertyFunctionIntrinsicFunctionGetVsInstallRoot() { string vsInstallRoot = EscapingUtilities.Escape(IntrinsicFunctions.GetVsInstallRoot()); vsInstallRoot = (vsInstallRoot == null) ? "" : vsInstallRoot; TestPropertyFunction("$([Microsoft.Build.Evaluation.IntrinsicFunctions]::GetVsInstallRoot())", "X", "_", vsInstallRoot); } [Fact] public void PropertyFunctionIntrinsicFunctionGetMSBuildExtensionsPath() { TestPropertyFunction("$([Microsoft.Build.Evaluation.IntrinsicFunctions]::GetMSBuildExtensionsPath())", "X", "_", EscapingUtilities.Escape(IntrinsicFunctions.GetMSBuildExtensionsPath())); } [Fact] public void PropertyFunctionIntrinsicFunctionGetProgramFiles32() { TestPropertyFunction("$([Microsoft.Build.Evaluation.IntrinsicFunctions]::GetProgramFiles32())", "X", "_", EscapingUtilities.Escape(IntrinsicFunctions.GetProgramFiles32())); } [Fact] public void PropertyFunctionStringArrayIndexerGetter() { TestPropertyFunction("$(prop.Split('-')[0])", "prop", "x-y-z", "x"); } [Fact] public void PropertyFunctionSubstring1() { TestPropertyFunction("$(prop.Substring(2))", "prop", "abcdef", "cdef"); } [Fact] public void PropertyFunctionSubstring2() { TestPropertyFunction("$(prop.Substring(2, 3))", "prop", "abcdef", "cde"); } [Fact] public void PropertyFunctionStringGetChars() { TestPropertyFunction("$(prop[0])", "prop", "461", "4"); } [Fact] public void PropertyFunctionStringGetCharsError() { Assert.Throws<InvalidProjectFileException>(() => { TestPropertyFunction("$(prop[5])", "prop", "461", "4"); }); } [Fact] public void PropertyFunctionStringPadLeft1() { TestPropertyFunction("$(prop.PadLeft(2))", "prop", "x", " x"); } [Fact] public void PropertyFunctionStringPadLeft2() { TestPropertyFunction("$(prop.PadLeft(2, '0'))", "prop", "x", "0x"); } [Fact] public void PropertyFunctionStringPadRight1() { TestPropertyFunction("$(prop.PadRight(2))", "prop", "x", "x "); } [Fact] public void PropertyFunctionStringPadRight2() { TestPropertyFunction("$(prop.PadRight(2, '0'))", "prop", "x", "x0"); } [Fact] public void PropertyFunctionStringTrimEndCharArray() { TestPropertyFunction("$(prop.TrimEnd('.0123456789'))", "prop", "net461", "net"); } [Fact] public void PropertyFunctionStringTrimStart() { TestPropertyFunction("$(X.TrimStart('vV'))", "X", "v40", "40"); } [Fact] public void PropertyFunctionStringTrimStartNoQuotes() { TestPropertyFunction("$(X.TrimStart(vV))", "X", "v40", "40"); } [Fact] public void PropertyFunctionStringTrimEnd1() { TestPropertyFunction("$(prop.TrimEnd('a'))", "prop", "netaa", "net"); } // https://github.com/Microsoft/msbuild/issues/2882 [Fact] public void PropertyFunctionMathMaxOverflow() { TestPropertyFunction("$([System.Math]::Max($(X), 0))", "X", "-2010", "0"); } [Fact] public void PropertyFunctionStringTrimEnd2() { Assert.Throws<InvalidProjectFileException>(() => { TestPropertyFunction("$(prop.TrimEnd('a', 'b'))", "prop", "stringab", "string"); }); } [Fact] public void PropertyFunctionMathMin() { TestPropertyFunction("$([System.Math]::Min($(X), 20))", "X", "30", "20"); } [Fact] public void PropertyFunctionMSBuildAdd() { TestPropertyFunction("$([MSBuild]::Add($(X), 5))", "X", "7", "12"); } [Fact] public void PropertyFunctionMSBuildSubtract() { TestPropertyFunction("$([MSBuild]::Subtract($(X), 20100000))", "X", "20100042", "42"); } [Fact] public void PropertyFunctionMSBuildMultiply() { TestPropertyFunction("$([MSBuild]::Multiply($(X), 8800))", "X", "2", "17600"); } [Fact] public void PropertyFunctionMSBuildDivide() { TestPropertyFunction("$([MSBuild]::Divide($(X), 10000))", "X", "65536", "6.5536"); } [Fact] public void PropertyFunctionConvertToString() { TestPropertyFunction("$([System.Convert]::ToString(`.`))", "_", "_", "."); } [Fact] public void PropertyFunctionConvertToInt32() { TestPropertyFunction("$([System.Convert]::ToInt32(42))", "_", "_", "42"); } [Fact] public void PropertyFunctionToCharArray() { TestPropertyFunction("$([System.Convert]::ToString(`.`).ToCharArray())", "_", "_", "."); } [Fact] public void PropertyFunctionStringArrayGetValue() { TestPropertyFunction("$(X.Split($([System.Convert]::ToString(`.`).ToCharArray())).GetValue($([System.Convert]::ToInt32(0))))", "X", "ab.cd", "ab"); } private void TestPropertyFunction(string expression, string propertyName, string propertyValue, string expected) { var properties = new PropertyDictionary<ProjectPropertyInstance>(); properties.Set(ProjectPropertyInstance.Create(propertyName, propertyValue)); var expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(properties, FileSystems.Default); string result = expander.ExpandIntoStringLeaveEscaped(expression, ExpanderOptions.ExpandProperties, MockElementLocation.Instance); result.ShouldBe(expected); } [Fact] public void ExpandItemVectorFunctions_GetPathsOfAllDirectoriesAbove() { // Directory structure: // <temp>\ // alpha\ // .proj // One.cs // beta\ // Two.cs // Three.cs // gamma\ using (var env = TestEnvironment.Create()) { var root = env.CreateFolder(); var alpha = root.CreateDirectory("alpha"); var projectFile = env.CreateFile(alpha, ".proj", @"<Project> <ItemGroup> <Compile Include=""One.cs"" /> <Compile Include=""beta\Two.cs"" /> <Compile Include=""beta\Three.cs"" /> </ItemGroup> <ItemGroup> <MyDirectories Include=""@(Compile->GetPathsOfAllDirectoriesAbove())"" /> </ItemGroup> </Project>"); var beta = alpha.CreateDirectory("beta"); var gamma = alpha.CreateDirectory("gamma"); ProjectInstance projectInstance = new ProjectInstance(projectFile.Path); ICollection<ProjectItemInstance> myDirectories = projectInstance.GetItems("MyDirectories"); var includes = myDirectories.Select(i => i.EvaluatedInclude); includes.ShouldBeUnique(); includes.ShouldContain(root.Path); includes.ShouldContain(alpha.Path); includes.ShouldContain(beta.Path); includes.ShouldNotContain(gamma.Path); } } [Fact] public void ExpandItemVectorFunctions_GetPathsOfAllDirectoriesAbove_ReturnCanonicalPaths() { // Directory structure: // <temp>\ // alpha\ // .proj // One.cs // beta\ // Two.cs // gamma\ // Three.cs using (var env = TestEnvironment.Create()) { var root = env.CreateFolder(); var alpha = root.CreateDirectory("alpha"); var projectFile = env.CreateFile(alpha, ".proj", @"<Project> <ItemGroup> <Compile Include=""One.cs"" /> <Compile Include=""beta\Two.cs"" /> <Compile Include=""..\gamma\Three.cs"" /> </ItemGroup> <ItemGroup> <MyDirectories Include=""@(Compile->GetPathsOfAllDirectoriesAbove())"" /> </ItemGroup> </Project>"); var beta = alpha.CreateDirectory("beta"); var gamma = root.CreateDirectory("gamma"); ProjectInstance projectInstance = new ProjectInstance(projectFile.Path); ICollection<ProjectItemInstance> myDirectories = projectInstance.GetItems("MyDirectories"); var includes = myDirectories.Select(i => i.EvaluatedInclude); includes.ShouldBeUnique(); includes.ShouldContain(root.Path); includes.ShouldContain(alpha.Path); includes.ShouldContain(beta.Path); includes.ShouldContain(gamma.Path); } } [Fact] public void ExpandItemVectorFunctions_Combine() { using (var env = TestEnvironment.Create()) { var root = env.CreateFolder(); var projectFile = env.CreateFile(root, ".proj", @"<Project> <ItemGroup> <MyDirectory Include=""Alpha;Beta;Alpha\Gamma"" /> </ItemGroup> <ItemGroup> <Squiggle Include=""@(MyDirectory->Combine('.squiggle'))"" /> </ItemGroup> </Project>"); ProjectInstance projectInstance = new ProjectInstance(projectFile.Path); ICollection<ProjectItemInstance> squiggles = projectInstance.GetItems("Squiggle"); var expectedAlphaSquigglePath = Path.Combine("Alpha", ".squiggle"); var expectedBetaSquigglePath = Path.Combine("Beta", ".squiggle"); var expectedAlphaGammaSquigglePath = Path.Combine("Alpha", "Gamma", ".squiggle"); squiggles.Select(i => i.EvaluatedInclude).ShouldBe(new[] { expectedAlphaSquigglePath, expectedBetaSquigglePath, expectedAlphaGammaSquigglePath }, Case.Insensitive); } } [Fact] public void ExpandItemVectorFunctions_Exists_Files() { // Directory structure: // <temp>\ // .proj // alpha\ // One.cs // exists // Two.cs // does not exist // Three.cs // exists // Four.cs // does not exist using (var env = TestEnvironment.Create()) { var root = env.CreateFolder(); var projectFile = env.CreateFile(root, ".proj", @"<Project> <ItemGroup> <PotentialCompile Include=""alpha\One.cs"" /> <PotentialCompile Include=""alpha\Two.cs"" /> <PotentialCompile Include=""alpha\Three.cs"" /> <PotentialCompile Include=""alpha\Four.cs"" /> </ItemGroup> <ItemGroup> <Compile Include=""@(PotentialCompile->Exists())"" /> </ItemGroup> </Project>"); var alpha = root.CreateDirectory("alpha"); var one = alpha.CreateFile("One.cs"); var three = alpha.CreateFile("Three.cs"); ProjectInstance projectInstance = new ProjectInstance(projectFile.Path); ICollection<ProjectItemInstance> squiggleItems = projectInstance.GetItems("Compile"); var alphaOnePath = Path.Combine("alpha", "One.cs"); var alphaThreePath = Path.Combine("alpha", "Three.cs"); squiggleItems.Select(i => i.EvaluatedInclude).ShouldBe(new[] { alphaOnePath, alphaThreePath }, Case.Insensitive); } } [Fact] public void ExpandItemVectorFunctions_Exists_Directories() { // Directory structure: // <temp>\ // .proj // alpha\ // beta\ // exists // gamma\ // does not exist // delta\ // exists // epsilon\ // does not exist using (var env = TestEnvironment.Create()) { var root = env.CreateFolder(); var projectFile = env.CreateFile(root, ".proj", @"<Project> <ItemGroup> <PotentialDirectory Include=""alpha\beta"" /> <PotentialDirectory Include=""alpha\gamma"" /> <PotentialDirectory Include=""alpha\delta"" /> <PotentialDirectory Include=""alpha\epsilon"" /> </ItemGroup> <ItemGroup> <MyDirectory Include=""@(PotentialDirectory->Exists())"" /> </ItemGroup> </Project>"); var alpha = root.CreateDirectory("alpha"); var beta = alpha.CreateDirectory("beta"); var delta = alpha.CreateDirectory("delta"); ProjectInstance projectInstance = new ProjectInstance(projectFile.Path); ICollection<ProjectItemInstance> squiggleItems = projectInstance.GetItems("MyDirectory"); var alphaBetaPath = Path.Combine("alpha", "beta"); var alphaDeltaPath = Path.Combine("alpha", "delta"); squiggleItems.Select(i => i.EvaluatedInclude).ShouldBe(new[] { alphaBetaPath, alphaDeltaPath }, Case.Insensitive); } } } }
jeffkl/msbuild
src/Build.UnitTests/Evaluation/Expander_Tests.cs
C#
mit
195,337
# testStr = "Hello {name}, How long have you bean?. I'm {myName}" # # testStr = testStr.format(name="Leo", myName="Serim") # # print(testStr) limit = None hello = str(limit, "") print(hello) # print( "4" in "3.5")
SELO77/seloPython
3.X/ex/strFormat.py
Python
mit
217
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'App.created_at' db.add_column('mobile_apps_app', 'created_at', self.gf('django.db.models.fields.DateTimeField')(null=True, blank=True), keep_default=False) def backwards(self, orm): # Deleting field 'App.created_at' db.delete_column('mobile_apps_app', 'created_at') models = { 'core.level': { 'Meta': {'ordering': "['order']", 'object_name': 'Level'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'level': ('django.db.models.fields.CharField', [], {'max_length': '45'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '25'}), 'order': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}) }, 'mobile_apps.app': { 'Meta': {'object_name': 'App'}, 'content_areas': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'related_name': "'content_areas'", 'null': 'True', 'symmetrical': 'False', 'to': "orm['core.Level']"}), 'cost': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '8', 'decimal_places': '2', 'blank': 'True'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'levels': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'related_name': "'levels'", 'null': 'True', 'symmetrical': 'False', 'to': "orm['core.Level']"}), 'link': ('django.db.models.fields.URLField', [], {'max_length': '200'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['mobile_apps.Type']"}) }, 'mobile_apps.type': { 'Meta': {'object_name': 'Type'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}) } } complete_apps = ['mobile_apps']
katemsu/kate_website
kate3/mobile_apps/migrations/0002_auto__add_field_app_created_at.py
Python
mit
2,545
<?php /* * Copyright (c) 2011 Sergei Lissovski, http://sergei.lissovski.org * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ if (!defined('VOBLA_TESTING')) { set_include_path(implode(PATH_SEPARATOR, array( realpath(__DIR__.'/../lib/'), realpath(__DIR__.'/../lib/vendor/Doctrine/lib/'), realpath(__DIR__.'/../lib/vendor/Moko/lib/'), realpath(__DIR__.'/../lib/vendor/Logade/lib/'), get_include_path() ))); require_once 'Vobla/Tools/ClassLoader.php'; \Vobla\Tools\ClassLoader::register(); define('VOBLA_TESTING', true); }
sergeil/Vobla
tests/bootstrap.php
PHP
mit
1,654
import React, { PropTypes } from 'react'; import { connect } from 'react-redux'; import './PostListView.scss'; import { toastr } from 'react-redux-toastr'; import { bindActionCreators } from 'redux'; import { fetchPostsFromApi, selectPostCategory, clearPostsErrors, clearPostsMessages } from '../../../actions/actionCreators'; import CategoryFilterContainer from '../../CategoryFilterContainer/CategoryFilterContainer'; import { PostList, LoadingIndicator, Divider, MessagesSection } from '../../../components'; import NoPostsFound from '../Misc/NoPostsFound'; // containsCategory :: Object -> Object -> Bool const containsCategory = (post, category) => { const categories = post.categories.filter( (cat) => cat._id == category.id ); return categories.length > 0; }; // getFilteredPosts :: Object -> [Object] -> [Object] const getFilteredPosts = ( category, posts ) => { if (category === null || category.name === 'All') { return posts; } return posts.filter((post) => { if (containsCategory(post, category)) { return post; } return undefined; }); }; /* Only used internally and it's so small so not worth creating a new component */ const SectionSubTitle = ({ title }) => ( <h4 className="section-sub-title"> {title} </h4> ); SectionSubTitle.propTypes = { title: PropTypes.string.isRequired }; class PostListView extends React.Component { constructor(props) { super(props); this.handleSelectCategory = this.handleSelectCategory.bind(this); this.handleChangePage = this.handleChangePage.bind(this); this.handleClose = this.handleClose.bind(this); } componentDidMount() { const { posts, fetchPosts } = this.props; if (!posts.items || posts.items.length === 0) { fetchPosts(); } } handleChangePage() { //TODO: Implement me!! } handleSelectCategory(category) { const { selectPostCat } = this.props; selectPostCat(category); } showMessage(message) { toastr.info(message); } handleClose(sender) { const { clearErrors, clearMessages } = this.props; const theElement = sender.target.id; if (theElement === 'button-close-error-panel') { clearErrors(); } else if (theElement === 'button-close-messages-panel') { clearMessages(); } } render() { const { posts, isFetching, postCategories, selectedCategory, errors, messages } = this.props; const items = posts.items; const visiblePosts = getFilteredPosts(selectedCategory, items); return ( <LoadingIndicator isLoading={isFetching}> <div className="post-list-view__wrapper"> <MessagesSection messages={messages} errors={errors} onClose={this.handleClose} /> <h1 className="section-header">From the Blog</h1> <SectionSubTitle title={selectedCategory.name == 'All' ? // eslint-disable-line 'All Posts' : `Selected Category: ${selectedCategory.name}` } /> <Divider /> <CategoryFilterContainer categories={postCategories} onSelectCategory={this.handleSelectCategory} selectedCategory={selectedCategory} /> {visiblePosts !== undefined && visiblePosts.length > 0 ? <PostList posts={visiblePosts} onChangePage={this.handleChangePage} /> : <NoPostsFound selectedCategory={selectedCategory} /> } </div> </LoadingIndicator> ); } } PostListView.propTypes = { dispatch: PropTypes.func.isRequired, errors: PropTypes.array.isRequired, messages: PropTypes.array.isRequired, posts: PropTypes.object.isRequired, isFetching: PropTypes.bool.isRequired, fetchPosts: PropTypes.func.isRequired, selectPostCat: PropTypes.func.isRequired, postCategories: PropTypes.array.isRequired, selectedCategory: PropTypes.object.isRequired, clearMessages: PropTypes.func.isRequired, clearErrors: PropTypes.func.isRequired }; // mapStateToProps :: {State} -> {Props} const mapStateToProps = (state) => ({ posts: state.posts, postCategories: state.posts.categories, selectedCategory: state.posts.selectedCategory, messages: state.messages.posts, errors: state.errors.posts, isFetching: state.posts.isFetching }); // mapDispatchToProps :: {Dispatch} -> {Props} const mapDispatchToProps = (dispatch) => bindActionCreators({ fetchPosts: () => fetchPostsFromApi(), selectPostCat: (category) => selectPostCategory(category), clearMessages: () => clearPostsMessages(), clearErrors: () => clearPostsErrors() }, dispatch); export default connect( mapStateToProps, mapDispatchToProps )(PostListView);
RyanCCollins/ryancollins.io
app/src/containers/Blog/PostListView/PostListView.js
JavaScript
mit
4,864
package models.factories; import models.squares.PropertySquare; import java.util.Set; /** * @author Ani Kristo */ interface PropertyFactory { Set<? extends PropertySquare> makeSquares(); }
CS319-G12/uMonopoly
src/models/factories/PropertyFactory.java
Java
mit
198
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Problem 4 – Dancing Bits")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Problem 4 – Dancing Bits")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("39a40e90-f004-484f-8abe-b9fe00d2ce98")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
Horwits/Telerik-Academy-2016-2017
C#/C#-Part-One/Exam-Preparation/Variant 2 2012/Problem 4 – Dancing Bits/Properties/AssemblyInfo.cs
C#
mit
1,428
version https://git-lfs.github.com/spec/v1 oid sha256:4a4e80129485fe848fa53149568184f09fa2da8648b6476b750ef97344bd4c5b size 10959
yogeshsaroya/new-cdnjs
ajax/libs/jsSHA/1.6.0/sha512.js
JavaScript
mit
130
using System; using System.Collections.Generic; using System.Data.Entity; using System.Data.Entity.ModelConfiguration.Conventions; using System.Linq; using System.Text; using System.Threading.Tasks; using TableTop.Repository.DatabaseModels; namespace TableTop.Data.Context { public class TableTopContext : DbContext { public TableTopContext():base("TableTopContext") { } public DbSet<Inventory_Item> Employees { get; set; } public DbSet<Person> People { get; set; } public DbSet<Location> Locations { get; set; } public DbSet<Quest> Quests { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Conventions.Remove<PluralizingTableNameConvention>(); } } }
heilc/TableTop
TableTop.Data/Context/TableTopContext.cs
C#
mit
810
using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Drawing.Design; using System.Collections; using System.Diagnostics; using System.Drawing; using System.Linq; using System.Collections.Generic; using SharpGL; using SharpGL.SceneGraph.Quadrics; using SharpGL.SceneGraph.Cameras; using SharpGL.SceneGraph.Evaluators; using SharpGL.SceneGraph.Collections; using SharpGL.SceneGraph.Core; using SharpGL.SceneGraph.Lighting; using SharpGL.SceneGraph.Effects; using SharpGL.SceneGraph.Assets; using System.Collections.ObjectModel; using System.Xml.Serialization; namespace SharpGL.SceneGraph { [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] [XmlInclude(typeof(PerspectiveCamera))] [XmlInclude(typeof(OrthographicCamera))] [XmlInclude(typeof(FrustumCamera))] [XmlInclude(typeof(LookAtCamera))] [XmlInclude(typeof(ArcBallCamera))] public class Scene : IHasOpenGLContext { /// <summary> /// Initializes a new instance of the <see cref="Scene"/> class. /// </summary> public Scene() { RenderBoundingVolumes = true; // The SceneContainer must have it's parent scene set. sceneContainer.ParentScene = this; } /// <summary> /// Performs a hit test on the scene. All elements that implement IVolumeBound will /// be hit tested. /// </summary> /// <param name="x">The x.</param> /// <param name="y">The y.</param> /// <returns>The elements hit.</returns> public virtual IEnumerable<SceneElement> DoHitTest(int x, int y) { // Create a result set. List<SceneElement> resultSet = new List<SceneElement>(); // Create a hitmap. Dictionary<uint, SceneElement> hitMap = new Dictionary<uint, SceneElement>(); // If we don't have a current camera, we cannot hit test. if (currentCamera == null) return resultSet; // Create an array that will be the viewport. int[] viewport = new int[4]; // Get the viewport, then convert the mouse point to an opengl point. gl.GetInteger(OpenGL.GL_VIEWPORT, viewport); y = viewport[3] - y; // Create a select buffer. uint[] selectBuffer = new uint[512]; gl.SelectBuffer(512, selectBuffer); // Enter select mode. gl.RenderMode(OpenGL.GL_SELECT); // Initialise the names, and add the first name. gl.InitNames(); gl.PushName(0); // Push matrix, set up projection, then load matrix. gl.MatrixMode(OpenGL.GL_PROJECTION); gl.PushMatrix(); gl.LoadIdentity(); gl.PickMatrix(x, y, 4, 4, viewport); currentCamera.TransformProjectionMatrix(gl); gl.MatrixMode(OpenGL.GL_MODELVIEW); gl.LoadIdentity(); // Create the name. uint currentName = 1; // Render the root for hit testing. RenderElementForHitTest(SceneContainer, hitMap, ref currentName); // Pop matrix and flush commands. gl.MatrixMode(OpenGL.GL_PROJECTION); gl.PopMatrix(); gl.MatrixMode(OpenGL.GL_MODELVIEW); gl.Flush(); // End selection. int hits = gl.RenderMode(OpenGL.GL_RENDER); uint posinarray = 0; // Go through each name. for (int hit = 0; hit < hits; hit++) { uint nameCount = selectBuffer[posinarray++]; uint z1 = selectBuffer[posinarray++]; uint z2 = selectBuffer[posinarray++]; if (nameCount == 0) continue; // Add each hit element to the result set to the array. for (int name = 0; name < nameCount; name++) { uint hitName = selectBuffer[posinarray++]; resultSet.Add(hitMap[hitName]); } } // Return the result set. return resultSet; } /// <summary> /// This function draws all of the objects in the scene (i.e. every quadric /// in the quadrics arraylist etc). /// </summary> public virtual void Draw(Camera camera = null) { // TODO: we must decide what to do about drawing - are // cameras completely outside of the responsibility of the scene? // If no camera has been provided, use the current one. if (camera == null) camera = currentCamera; // Set the clear color. float[] clear = clearColour; gl.ClearColor(clear[0], clear[1], clear[2], clear[3]); // Reproject. if (camera != null) camera.Project(gl); // Clear. gl.Clear(OpenGL.GL_COLOR_BUFFER_BIT | OpenGL.GL_DEPTH_BUFFER_BIT | OpenGL.GL_STENCIL_BUFFER_BIT); //gl.BindTexture(OpenGL.GL_TEXTURE_2D, 0); // Render the root element, this will then render the whole // of the scene tree. RenderElement(sceneContainer, RenderMode.Design); // TODO: Adding this code here re-enables textures- it should work without it but it // doesn't, look into this. //gl.BindTexture(OpenGL.GL_TEXTURE_2D, 0); //gl.Enable(OpenGL.GL_TEXTURE_2D); gl.Flush(); } /// <summary> /// Renders the element. /// </summary> /// <param name="gl">The gl.</param> /// <param name="renderMode">The render mode.</param> public void RenderElement(SceneElement sceneElement, RenderMode renderMode) { // If the element is disabled, we're done. if (sceneElement.IsEnabled == false) return; // Push each effect. foreach (var effect in sceneElement.Effects) if(effect.IsEnabled) effect.Push(gl, sceneElement); // If the element can be bound, bind it. if (sceneElement is IBindable) ((IBindable)sceneElement).Bind(gl); // If the element has an object space, transform into it. if (sceneElement is IHasObjectSpace) ((IHasObjectSpace)sceneElement).PushObjectSpace(gl); // If the element has a material, push it. if (sceneElement is IHasMaterial && ((IHasMaterial)sceneElement).Material != null) ((IHasMaterial)sceneElement).Material.Push(gl); // If the element can be rendered, render it. if (sceneElement is IRenderable) ((IRenderable)sceneElement).Render(gl, renderMode); // If the element has a material, pop it. if (sceneElement is IHasMaterial && ((IHasMaterial)sceneElement).Material != null) ((IHasMaterial)sceneElement).Material.Pop(gl); // IF the element is volume bound and we are rendering volumes, render the volume. if (RenderBoundingVolumes && sceneElement is IVolumeBound) ((IVolumeBound)sceneElement).BoundingVolume.Render(gl, renderMode); // Recurse through the children. foreach (var childElement in sceneElement.Children) RenderElement(childElement, renderMode); // If the element has an object space, transform out of it. if (sceneElement is IHasObjectSpace) ((IHasObjectSpace)sceneElement).PopObjectSpace(gl); // Pop each effect. for (int i = sceneElement.Effects.Count - 1; i >= 0; i--) if(sceneElement.Effects[i].IsEnabled) sceneElement.Effects[i].Pop(gl, sceneElement); } /// <summary> /// Renders the element for hit test. /// </summary> /// <param name="sceneElement">The scene element.</param> /// <param name="hitMap">The hit map.</param> /// <param name="currentName">Current hit name.</param> private void RenderElementForHitTest(SceneElement sceneElement, Dictionary<uint, SceneElement> hitMap, ref uint currentName) { // If the element is disabled, we're done. // Also, never hit test the current camera. if (sceneElement.IsEnabled == false || sceneElement == currentCamera) return; // Push each effect. foreach (var effect in sceneElement.Effects) if (effect.IsEnabled) effect.Push(gl, sceneElement); // If the element has an object space, transform into it. if (sceneElement is IHasObjectSpace) ((IHasObjectSpace)sceneElement).PushObjectSpace(gl); // If the element is volume bound, render the volume. if (sceneElement is IVolumeBound) { // Load and map the name. gl.LoadName(currentName); hitMap[currentName] = sceneElement; // Render the bounding volume. ((IVolumeBound)sceneElement).BoundingVolume.Render(gl, RenderMode.HitTest); // Increment the name. currentName++; } // Recurse through the children. foreach (var childElement in sceneElement.Children) RenderElementForHitTest(childElement, hitMap, ref currentName); // If the element has an object space, transform out of it. if (sceneElement is IHasObjectSpace) ((IHasObjectSpace)sceneElement).PopObjectSpace(gl); // Pop each effect. for (int i = sceneElement.Effects.Count - 1; i >= 0; i--) if (sceneElement.Effects[i].IsEnabled) sceneElement.Effects[i].Pop(gl, sceneElement); } /// <summary> /// Use this function to resize the scene window, and also to look through /// the current camera. /// </summary> /// <param name="width">Width of the screen.</param> /// <param name="height">Height of the screen.</param> public virtual void Resize(int width, int height) { if(width != -1 && height != -1) { // Resize. gl.Viewport(0, 0, width, height); if (currentCamera != null) { // Set aspect ratio. currentCamera.AspectRatio = (float)width / (float)height; // Then project. currentCamera.Project(gl); } } } /// <summary> /// Create in the context of the supplied OpenGL instance. /// </summary> /// <param name="gl">The OpenGL instance.</param> public void CreateInContext(OpenGL gl) { // Create every scene element. var openGLContextElements = SceneContainer.Traverse<SceneElement>( se => se is IHasOpenGLContext); foreach (var openGLContextElement in openGLContextElements) ((IHasOpenGLContext)openGLContextElement).CreateInContext(gl); this.gl = gl; } /// <summary> /// Destroy in the context of the supplied OpenGL instance. /// </summary> /// <param name="gl">The OpenGL instance.</param> public void DestroyInContext(OpenGL gl) { } /// <summary> /// This is the OpenGL class, use it to call OpenGL functions. /// </summary> private OpenGL gl = new OpenGL(); /// <summary> /// The main scene container - this is the top level element of the Scene Tree. /// </summary> private SceneContainer sceneContainer = new SceneContainer(); /// <summary> /// The set of scene assets. /// </summary> private ObservableCollection<Asset> assets = new ObservableCollection<Asset>(); /// <summary> /// This is the camera that is currently being used to view the scene. /// </summary> private Camera currentCamera; /// <summary> /// This is the colour of the background of the scene. /// </summary> private GLColor clearColour = new GLColor(0, 0, 0, 0); /// <summary> /// Gets or sets the open GL. /// </summary> /// <value> /// The open GL. /// </value> [XmlIgnore] [Description("OpenGL API Wrapper Class"), Category("OpenGL/External")] public OpenGL OpenGL { get {return gl;} set {gl = value;} } /// <summary> /// Gets or sets the scene container. /// </summary> /// <value> /// The scene container. /// </value> [Description("The top-level object in the Scene Tree"), Category("Scene")] public SceneContainer SceneContainer { get { return sceneContainer; } set { sceneContainer = value; } } /// <summary> /// Gets the assets. /// </summary> [Description("The scene assets."), Category("Scene")] public ObservableCollection<Asset> Assets { get { return assets; } } /// <summary> /// Gets or sets the current camera. /// </summary> /// <value> /// The current camera. /// </value> [Description("The current camera being used to view the scene."), Category("Scene")] public Camera CurrentCamera { get {return currentCamera;} set {currentCamera = value;} } /// <summary> /// Gets or sets the color of the clear. /// </summary> /// <value> /// The color of the clear. /// </value> [Description("The background colour."), Category("Scene")] public Color ClearColor { get {return clearColour;} set {clearColour = value;} } /// <summary> /// Gets or sets a value indicating whether [render bounding volumes]. /// </summary> /// <value> /// <c>true</c> if [render bounding volumes]; otherwise, <c>false</c>. /// </value> //todo tidy up (into render options?) public bool RenderBoundingVolumes { get; set; } /// <summary> /// Gets the current OpenGL that the object exists in context. /// </summary> [XmlIgnore] [Browsable(false)] public OpenGL CurrentOpenGLContext { get { return gl; } } } }
DanFTRX/sharpgl
source/SharpGL/Core/SharpGL.SceneGraph/Scene.cs
C#
mit
15,697
/** * Created by yangge on 1/29/2016. */ public class EggPlant extends Veggies { }
eroicaleo/DesignPatterns
HeadFirst/ch04/PizzaStoreAbstractFactory/EggPlant.java
Java
mit
85
/** * Module dependencies. */ var util = require('sails-util'), uuid = require('node-uuid'), path = require('path'), generateSecret = require('./generateSecret'), cookie = require('express/node_modules/cookie'), parseSignedCookie = require('cookie-parser').signedCookie, ConnectSession = require('express/node_modules/connect').middleware.session.Session; module.exports = function(sails) { ////////////////////////////////////////////////////////////////////////////// // TODO: // // All of this craziness can be replaced by making the socket.io interpreter // 100% connect-compatible (it's close!). Then, the connect cookie parser // can be used directly with Sails' simulated req and res objects. // ////////////////////////////////////////////////////////////////////////////// /** * Prototype for the connect session store wrapper used by the sockets hook. * Includes a save() method to persist the session data. */ function SocketIOSession(options) { var sid = options.sid, data = options.data; this.save = function(cb) { if (!sid) { sails.log.error('Trying to save session, but could not determine session ID.'); sails.log.error('This probably means a requesting socket did not send a cookie.'); sails.log.error('Usually, this happens when a socket from an old browser tab ' + ' tries to reconnect.'); sails.log.error('(this can also occur when trying to connect a cross-origin socket.)'); if (cb) cb('Could not save session.'); return; } // Merge data directly into instance to allow easy access on `req.session` later util.defaults(this, data); // Persist session Session.set(sid, sails.util.cloneDeep(this), function(err) { if (err) { sails.log.error('Could not save session:'); sails.log.error(err); } if (cb) cb(err); }); }; // Set the data on this object, since it will be used as req.session util.extend(this, options.data); } // Session hook var Session = { defaults: { session: { adapter: 'memory', key: "sails.sid" } }, /** * Normalize and validate configuration for this hook. * Then fold any modifications back into `sails.config` */ configure: function() { // Validate config // Ensure that secret is specified if a custom session store is used if (sails.config.session) { if (!util.isObject(sails.config.session)) { throw new Error('Invalid custom session store configuration!\n' + '\n' + 'Basic usage ::\n' + '{ session: { adapter: "memory", secret: "someVerySecureString", /* ...if applicable: host, port, etc... */ } }' + '\n\nCustom usage ::\n' + '{ session: { store: { /* some custom connect session store instance */ }, secret: "someVerySecureString", /* ...custom settings.... */ } }' ); } } // If session config is set, but secret is undefined, set a secure, one-time use secret if (!sails.config.session || !sails.config.session.secret) { sails.log.verbose('Session secret not defined-- automatically generating one for now...'); if (sails.config.environment === 'production') { sails.log.warn('Session secret must be identified!'); sails.log.warn('Automatically generating one for now...'); sails.log.error('This generated session secret is NOT OK for production!'); sails.log.error('It will change each time the server starts and break multi-instance deployments.'); sails.log.blank(); sails.log.error('To set up a session secret, add or update it in `config/session.js`:'); sails.log.error('module.exports.session = { secret: "keyboardcat" }'); sails.log.blank(); } sails.config.session.secret = generateSecret(); } // Backwards-compatibility / shorthand notation // (allow mongo or redis session stores to be specified directly) if (sails.config.session.adapter === 'redis') { sails.config.session.adapter = 'connect-redis'; } else if (sails.config.session.adapter === 'mongo') { sails.config.session.adapter = 'connect-mongo'; } }, /** * Create a connection to the configured session store * and keep it around * * @api private */ initialize: function(cb) { var sessionConfig = sails.config.session; // Intepret session adapter config and "new up" a session store if (util.isObject(sessionConfig) && !util.isObject(sessionConfig.store)) { // Unless the session is explicitly disabled, require the appropriate adapter if (sessionConfig.adapter) { // 'memory' is a special case if (sessionConfig.adapter === 'memory') { var MemoryStore = require('express').session.MemoryStore; sessionConfig.store = new MemoryStore(); } // Try and load the specified adapter from the local sails project, // or catch and return error: else { var COULD_NOT_REQUIRE_CONNECT_ADAPTER_ERR = function (adapter, packagejson, e) { var errMsg; if (e && typeof e === 'object' && e instanceof Error) { errMsg = e.stack; } else { errMsg = util.inspect(e); } var output = 'Could not load Connect session adapter :: ' + adapter + '\n'; if (packagejson && !packagejson.main) { output+='(If this is your module, make sure that the module has a "main" configuration in its package.json file)'; } output+='\nError from adapter:\n'+ errMsg+'\n\n'; // Recommend installation of the session adapter: output += 'Do you have the Connect session adapter installed in this project?\n'; output += 'Try running the following command in your project\'s root directory:\n'; var installRecommendation = 'npm install '; if (adapter === 'connect-redis') { installRecommendation += 'connect-redis@1.4.5'; installRecommendation += '\n(Note that `connect-redis@1.5.0` introduced breaking changes- make sure you have v1.4.5 installed!)'; } else { installRecommendation += adapter; installRecommendation +='\n(Note: Make sure the version of the Connect adapter you install is compatible with Express 3/Sails v0.10)'; } installRecommendation += '\n'; output += installRecommendation; return output; }; try { // Determine the path to the adapter by using the "main" described in its package.json file: var pathToAdapterDependency; var pathToAdapterPackage = path.resolve(sails.config.appPath, 'node_modules', sessionConfig.adapter ,'package.json'); var adapterPackage; try { adapterPackage = require(pathToAdapterPackage); pathToAdapterDependency = path.resolve(sails.config.appPath, 'node_modules', sessionConfig.adapter, adapterPackage.main); } catch (e) { return cb(COULD_NOT_REQUIRE_CONNECT_ADAPTER_ERR(sessionConfig.adapter, adapterPackage, e)); } var SessionAdapter = require(pathToAdapterDependency); var CustomStore = SessionAdapter(require('express')); sessionConfig.store = new CustomStore(sessionConfig); } catch (e) { // TODO: negotiate error return cb(COULD_NOT_REQUIRE_CONNECT_ADAPTER_ERR(sessionConfig.adapter, adapterPackage, e)); } } } } // Save reference in `sails.session` sails.session = Session; return cb(); }, /** * Create a new sid and build an empty session for it. * * @param {Object} handshake - a socket "handshake" -- basically, this is like `req` * @param {Function} cb * @returns live session, with `id` property === new sid */ generate: function(handshake, cb) { // Generate a session object w/ sid // This is important since we need this sort of object as the basis for the data // we'll save directly into the session store. // (handshake is a pretend `req` object, and 2nd argument is cookie config) var session = new ConnectSession(handshake, { cookie: { // Prevent access from client-side javascript httpOnly: true, // Restrict to path path: '/' } }); // Next, persist the new session Session.set(session.id, session, function(err) { if (err) return cb(err); sails.log.verbose('Generated new session (', session.id, ') for socket....'); // Pass back final session object return cb(null, session); }); }, /** * @param {String} sessionId * @param {Function} cb * * @api private */ get: function(sessionId, cb) { if (!util.isFunction(cb)) { throw new Error('Invalid usage :: `Session.get(sessionId, cb)`'); } return sails.config.session.store.get(sessionId, cb); }, /** * @param {String} sessionId * @param {} data * @param {Function} [cb] - optional * * @api private */ set: function(sessionId, data, cb) { cb = util.optional(cb); return sails.config.session.store.set(sessionId, data, cb); }, /** * Create a session transaction * * Load the Connect session data using the sessionID in the socket.io handshake object * Mix-in the session.save() method for persisting the data back to the session store. * * Functionally equivalent to connect's sessionStore middleware. */ fromSocket: function(socket, cb) { // If a socket makes it here, even though its associated session is not specified, // it's authorized as far as the app is concerned, so no need to do that again. // Instead, use the cookie to look up the sid, and then the sid to look up the session data // If sid doesn't exit in socket, we have to do a little work first to get it // (or generate a new one-- and therefore a new empty session as well) if (!socket.handshake.sessionID && !socket.handshake.headers.cookie) { // If no cookie exists, generate a random one (this will create a new session!) var generatedCookie = sails.config.session.key + '=' + uuid.v1(); socket.handshake.headers.cookie = generatedCookie; sails.log.verbose('Could not fetch session, since connecting socket (', socket.id, ') has no cookie.'); sails.log.verbose('Is this a cross-origin socket..?)'); sails.log.verbose('Generated a one-time-use cookie:', generatedCookie); sails.log.verbose('This will result in an empty session, i.e. (req.session === {})'); // Convert cookie into `sid` using session secret // Maintain sid in socket so that the session can be queried before processing each incoming message socket.handshake.cookie = cookie.parse(generatedCookie); // Parse and decrypt cookie and save it in the socket.handshake socket.handshake.sessionID = parseSignedCookie(socket.handshake.cookie[sails.config.session.key], sails.config.session.secret); // Generate and persist a new session in the store Session.generate(socket.handshake, function(err, sessionData) { if (err) return cb(err); sails.log.silly('socket.handshake.sessionID is now :: ', socket.handshake.sessionID); // Provide access to adapter-agnostic `.save()` return cb(null, new SocketIOSession({ sid: sessionData.id, data: sessionData })); }); return; } try { // Convert cookie into `sid` using session secret // Maintain sid in socket so that the session can be queried before processing each incoming message socket.handshake.cookie = cookie.parse(socket.handshake.headers.cookie); // Parse and decrypt cookie and save it in the socket.handshake socket.handshake.sessionID = parseSignedCookie(socket.handshake.cookie[sails.config.session.key], sails.config.session.secret); } catch (e) { sails.log.error('Could not load session for socket #' + socket.id); sails.log.error('The socket\'s cookie could not be parsed into a sessionID.'); sails.log.error('Unless you\'re overriding the `authorization` function, make sure ' + 'you pass in a valid `' + sails.config.session.key + '` cookie'); sails.log.error('(or omit the cookie altogether to have a new session created and an ' + 'encrypted cookie sent in the response header to your socket.io upgrade request)'); return cb(e); } // If sid DOES exist, it's easy to look up in the socket var sid = socket.handshake.sessionID; // Cache the handshake in case it gets wiped out during the call to Session.get var handshake = socket.handshake; // Retrieve session data from store Session.get(sid, function(err, sessionData) { if (err) { sails.log.error('Error retrieving session from socket.'); return cb(err); } // sid is not known-- the session secret probably changed // Or maybe server restarted and it was: // (a) using an auto-generated secret, or // (b) using the session memory store // and so it doesn't recognize the socket's session ID. else if (!sessionData) { sails.log.verbose('A socket (' + socket.id + ') is trying to connect with an invalid or expired session ID (' + sid + ').'); sails.log.verbose('Regnerating empty session...'); Session.generate(handshake, function(err, sessionData) { if (err) return cb(err); // Provide access to adapter-agnostic `.save()` return cb(null, new SocketIOSession({ sid: sessionData.id, data: sessionData })); }); } // Otherwise session exists and everything is ok. // Instantiate SocketIOSession (provides .save() method) // And extend it with session data else return cb(null, new SocketIOSession({ data: sessionData, sid: sid })); }); } }; return Session; };
mnaughto/sails
lib/hooks/session/index.js
JavaScript
mit
14,850
// // StoreLocation.cs - System.Security.Cryptography.X509Certificates.StoreLocation // // Author: // Sebastien Pouliot <sebastien@ximian.com> // // (C) 2003 Motus Technologies Inc. (http://www.motus.com) // Copyright (C) 2004 Novell Inc. (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // #if NET_2_0 using System; namespace System.Security.Cryptography.X509Certificates { [Serializable] public enum StoreLocation { CurrentUser = 1, LocalMachine = 2 } } #endif
jjenki11/blaze-chem-rendering
qca_designer/lib/ml-pnet-0.8.1/mcs-sources/class/System.Security/System.Security.Cryptography.X509Certificates/StoreLocation.cs
C#
mit
1,531
function showErrorMessage(errorMessage) { $("#authorize-prompt") .addClass("error-prompt") .removeClass("success-prompt") .html(errorMessage); } function showSuccessMessage(message) { $("#authorize-prompt") .removeClass("error-prompt") .addClass("success-prompt") .html(message); } function shake() { var l = 10; var original = -150; for( var i = 0; i < 8; i++ ) { var computed; if (i % 2 > 0.51) { computed = original - l; } else { computed = original + l; } $("#login-box").animate({ "left": computed + "px" }, 100); } $("#login-box").animate({ "left": "-150px" }, 50); } function handleAuthSuccess(data) { showSuccessMessage(data.message); $("#login-button").prop("disabled", true); setTimeout(function() { location.href = data.redirectUri; }, 1000); } function handleAuthFailure(data) { showErrorMessage(data.responseJSON.message); shake(); } $(function () { $('[data-toggle="tooltip"]').tooltip() }) function handleGrantAuthorization() { var csrf_token = $("#csrf_token").val(); var client_id = $("#client_id").val(); $.ajax("/oauth/authorize", { "method": "POST", "data": { client_id, csrf_token }, "success": handleAuthSuccess, "error": handleAuthFailure }); }
AndrewMontagne/alliance-auth
static/js/authorize.js
JavaScript
mit
1,462
import math import urwid from mitmproxy.tools.console import common from mitmproxy.tools.console import signals from mitmproxy.tools.console import grideditor class SimpleOverlay(urwid.Overlay): def __init__(self, master, widget, parent, width, valign="middle"): self.widget = widget self.master = master super().__init__( widget, parent, align="center", width=width, valign=valign, height="pack" ) def keypress(self, size, key): key = super().keypress(size, key) if key == "esc": signals.pop_view_state.send(self) if key == "?": self.master.view_help(self.widget.make_help()) else: return key class Choice(urwid.WidgetWrap): def __init__(self, txt, focus, current): if current: s = "option_active_selected" if focus else "option_active" else: s = "option_selected" if focus else "text" return super().__init__( urwid.AttrWrap( urwid.Padding(urwid.Text(txt)), s, ) ) def selectable(self): return True def keypress(self, size, key): return key class ChooserListWalker(urwid.ListWalker): def __init__(self, choices, current): self.index = 0 self.choices = choices self.current = current def _get(self, idx, focus): c = self.choices[idx] return Choice(c, focus, c == self.current) def set_focus(self, index): self.index = index def get_focus(self): return self._get(self.index, True), self.index def get_next(self, pos): if pos >= len(self.choices) - 1: return None, None pos = pos + 1 return self._get(pos, False), pos def get_prev(self, pos): pos = pos - 1 if pos < 0: return None, None return self._get(pos, False), pos class Chooser(urwid.WidgetWrap): def __init__(self, title, choices, current, callback): self.choices = choices self.callback = callback choicewidth = max([len(i) for i in choices]) self.width = max(choicewidth, len(title) + 5) self.walker = ChooserListWalker(choices, current) super().__init__( urwid.AttrWrap( urwid.LineBox( urwid.BoxAdapter( urwid.ListBox(self.walker), len(choices) ), title= title ), "background" ) ) def selectable(self): return True def keypress(self, size, key): key = common.shortcuts(key) if key == "enter": self.callback(self.choices[self.walker.index]) signals.pop_view_state.send(self) return super().keypress(size, key) def make_help(self): text = [] keys = [ ("enter", "choose option"), ("esc", "exit chooser"), ] text.extend(common.format_keyvals(keys, key="key", val="text", indent=4)) return text class OptionsOverlay(urwid.WidgetWrap): def __init__(self, master, name, vals, vspace): """ vspace: how much vertical space to keep clear """ cols, rows = master.ui.get_cols_rows() self.ge = grideditor.OptionsEditor(master, name, vals) super().__init__( urwid.AttrWrap( urwid.LineBox( urwid.BoxAdapter(self.ge, rows - vspace), title=name ), "background" ) ) self.width = math.ceil(cols * 0.8) def make_help(self): return self.ge.make_help()
xaxa89/mitmproxy
mitmproxy/tools/console/overlay.py
Python
mit
3,855
/* * This file is part of the Turtle project * * (c) 2011 Julien Brochet <julien.brochet@etu.univ-lyon1.fr> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ package turtle.gui.panel; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.border.Border; import turtle.behavior.team.TeamBehaviorInterface; import turtle.controller.Kernel; import turtle.entity.Team; import turtle.util.Log; /** * Représentation du panel permettant le changement du * comportement d'une équipe * * @author Julien Brochet <julien.brochet@etu.univ-lyon1.fr> * @since 1.0 */ public class TeamBehaviorPanel extends JPanel implements ActionListener { /** * L'équipe concernée */ protected Team mTeam; /** * Le contrôlleur */ protected Kernel mKernel; public TeamBehaviorPanel(Kernel kernel, Team team) { mTeam = team; mKernel = kernel; initialize(); } /** * Création de la fenêtre et de ses composants */ private void initialize() { Border paddingBorder = BorderFactory.createEmptyBorder(0,10,10,0); JLabel label = new JLabel("Comportement de l'équipe " + mTeam.getName()); label.setBorder(paddingBorder); JComboBox comboBox = new JComboBox(mTeam.getAvailableBehaviors().toArray()); comboBox.addActionListener(this); comboBox.setSelectedIndex(-1); setLayout(new BorderLayout()); add(label, BorderLayout.NORTH); add(comboBox, BorderLayout.SOUTH); } @Override public void actionPerformed(ActionEvent e) { JComboBox cb = (JComboBox) e.getSource(); TeamBehaviorInterface behavior = (TeamBehaviorInterface) cb.getSelectedItem(); TeamBehaviorInterface oldBehavior = mTeam.getBehavior(); if (behavior != oldBehavior) { Log.i(String.format("Behavior change for Team %s (old=%s, new=%s)", mTeam.getName(), mTeam.getBehavior(), behavior)); mKernel.changeTeamBehavior(mTeam, behavior); } } }
aerialls/Turtle
src/turtle/gui/panel/TeamBehaviorPanel.java
Java
mit
2,309
module.exports = [ 'M6 2 L26 2 L26 30', 'L16 24 L6 30 Z' ].join(' ');
zaccolley/songkick.pink
src/components/Icon/svg/bookmark.js
JavaScript
mit
75
class PluginSerializer < ActiveModel::Serializer attributes :name attribute :plugin_attributes, key: :attributes end
degica/barcelona
app/serializers/plugin_serializer.rb
Ruby
mit
121