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
package DoordashPrep; public class _0121BestTimeToBuyAndSellStock { public static void main(String[] args) { System.out.println(maxProfit(new int[] { 7, 1, 5, 3, 6, 4 })); System.out.println(maxProfit(new int[] { 7, 6, 4, 3, 1 })); System.out.println(maxProfit(new int[] { 3, 2, 6, 5, 0, 3 })); System.out.println(maxProfit(new int[] { 1, 2 })); } public static int maxProfit(int[] prices) { if (prices == null || prices.length < 2) return 0; int minSoFar = prices[0]; int maxProfit = 0; for (int i = 1; i < prices.length; i++) { if (prices[i] < minSoFar) { minSoFar = prices[i]; } maxProfit = Math.max(maxProfit, prices[i] - minSoFar); } return maxProfit; } }
darshanhs90/Java-InterviewPrep
src/DoordashPrep/_0121BestTimeToBuyAndSellStock.java
Java
mit
703
import json import requests import key API_key = key.getAPIkey() #load all champion pictures def load_champion_pictures(champion_json): print len(champion_json['data']) version = champion_json['version'] print "version: " + version for champion in champion_json['data']: print champion r = requests.get('http://ddragon.leagueoflegends.com/cdn/' + version + '/img/champion/' + champion + '.png') if r.status_code == 200: img = r.content with open('static/images/champions/' + champion_json['data'][champion]['name'] + '.png', 'w') as f: f.write(img) print "img created" else: print "pictures: something went wrong" #load champion json #converts to python dict using json() and json.dump() for error checking def load_champion_json(): try: r = requests.get('https://global.api.pvp.net/api/lol/static-data/na/v1.2/champion?&api_key=' + API_key) champion_json = r.json() if 'status' in champion_json: print champion_json['status']['message'] return load_champion_pictures(champion_json) # quick fix to change MonkeyKing to Wukong so that sort_keys sorts it properly champion_json['data']['Wukong'] = champion_json['data']['MonkeyKing'] del champion_json['data']['MonkeyKing'] except ValueError as e: print e.message return with open('static/json/champion.json', 'w') as f: json.dump(champion_json, f, sort_keys=True) load_champion_json()
dzhang55/riftwatch
static_images.py
Python
mit
1,397
require 'acts_as_rateable' ActiveRecord::Base.send(:include, ActiveRecord::Acts::Rateable)
mreinsch/acts_as_rateable
rails/init.rb
Ruby
mit
91
using System; namespace Nop.Core.Caching { /// <summary> /// Extensions /// </summary> public static class CacheExtensions { /// <summary> /// Get a cached item. If it's not in the cache yet, then load and cache it /// </summary> /// <typeparam name="T">Type</typeparam> /// <param name="cacheManager">Cache manager</param> /// <param name="key">Cache key</param> /// <param name="acquire">Function to load item if it's not in the cache yet</param> /// <returns>Cached item</returns> public static T Get<T>(this ICacheManager cacheManager, string key, Func<T> acquire) { return Get(cacheManager, key, 60, acquire); } /// <summary> /// Get a cached item. If it's not in the cache yet, then load and cache it /// </summary> /// <typeparam name="T">Type</typeparam> /// <param name="cacheManager">Cache manager</param> /// <param name="key">Cache key</param> /// <param name="cacheTime">Cache time in minutes (0 - do not cache)</param> /// <param name="acquire">Function to load item if it's not in the cache yet</param> /// <returns>Cached item</returns> public static T Get<T>(this ICacheManager cacheManager, string key, int cacheTime, Func<T> acquire) { if (cacheManager.IsSet(key)) { return cacheManager.Get<T>(key); } var result = acquire(); if (cacheTime > 0) cacheManager.Set(key, result, cacheTime); return result; } } }
andri0331/cetaku
Libraries/Nop.Core/Caching/Extensions.cs
C#
mit
1,654
webpackJsonp([0],{ /***/ 109: /***/ (function(module, exports) { function webpackEmptyAsyncContext(req) { // Here Promise.resolve().then() is used instead of new Promise() to prevent // uncatched exception popping up in devtools return Promise.resolve().then(function() { throw new Error("Cannot find module '" + req + "'."); }); } webpackEmptyAsyncContext.keys = function() { return []; }; webpackEmptyAsyncContext.resolve = webpackEmptyAsyncContext; module.exports = webpackEmptyAsyncContext; webpackEmptyAsyncContext.id = 109; /***/ }), /***/ 150: /***/ (function(module, exports) { function webpackEmptyAsyncContext(req) { // Here Promise.resolve().then() is used instead of new Promise() to prevent // uncatched exception popping up in devtools return Promise.resolve().then(function() { throw new Error("Cannot find module '" + req + "'."); }); } webpackEmptyAsyncContext.keys = function() { return []; }; webpackEmptyAsyncContext.resolve = webpackEmptyAsyncContext; module.exports = webpackEmptyAsyncContext; webpackEmptyAsyncContext.id = 150; /***/ }), /***/ 193: /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return TabsPage; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__angular_core__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__home_home__ = __webpack_require__(194); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__about_about__ = __webpack_require__(196); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__contact_contact__ = __webpack_require__(197); var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var TabsPage = /** @class */ (function () { function TabsPage() { // this tells the tabs component which Pages // should be each tab's root Page this.tab1Root = __WEBPACK_IMPORTED_MODULE_1__home_home__["a" /* HomePage */]; this.tab2Root = __WEBPACK_IMPORTED_MODULE_2__about_about__["a" /* AboutPage */]; this.tab3Root = __WEBPACK_IMPORTED_MODULE_3__contact_contact__["a" /* ContactPage */]; } TabsPage = __decorate([ Object(__WEBPACK_IMPORTED_MODULE_0__angular_core__["m" /* Component */])({template:/*ion-inline-start:"/home/marcus/ionic2-camera-demo/src/pages/tabs/tabs.html"*/'<ion-tabs>\n <ion-tab [root]="tab1Root" tabTitle="Home" tabIcon="home"></ion-tab>\n <ion-tab [root]="tab2Root" tabTitle="About" tabIcon="information-circle"></ion-tab>\n <ion-tab [root]="tab3Root" tabTitle="Contact" tabIcon="contacts"></ion-tab>\n</ion-tabs>\n'/*ion-inline-end:"/home/marcus/ionic2-camera-demo/src/pages/tabs/tabs.html"*/ }), __metadata("design:paramtypes", []) ], TabsPage); return TabsPage; }()); //# sourceMappingURL=tabs.js.map /***/ }), /***/ 194: /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return HomePage; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__angular_core__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_ionic_angular__ = __webpack_require__(33); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__ionic_native_camera__ = __webpack_require__(195); var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var HomePage = /** @class */ (function () { function HomePage(navCtrl, camera) { this.navCtrl = navCtrl; this.camera = camera; this.images = []; } HomePage.prototype.takePhoto = function () { var _this = this; var options = { quality: 80, destinationType: this.camera.DestinationType.DATA_URL, sourceType: this.camera.PictureSourceType.CAMERA, allowEdit: false, encodingType: this.camera.EncodingType.JPEG, saveToPhotoAlbum: false }; this.camera.getPicture(options).then(function (imageData) { // imageData is either a base64 encoded string or a file URI // If it's base64: var base64Image = 'data:image/jpeg;base64,' + imageData; _this.images.unshift({ src: base64Image }); }, function (err) { // Handle error }); }; HomePage = __decorate([ Object(__WEBPACK_IMPORTED_MODULE_0__angular_core__["m" /* Component */])({ selector: 'page-home',template:/*ion-inline-start:"/home/marcus/ionic2-camera-demo/src/pages/home/home.html"*/'<ion-header>\n <ion-navbar>\n <ion-title>Home</ion-title>\n </ion-navbar>\n</ion-header>\n<ion-content>\n <ion-slides style="height: 50vh">\n <ion-slide *ngFor="let image of images">\n <ion-card>\n <img [src]="image.src"/>\n </ion-card>\n </ion-slide>\n </ion-slides>\n <p>\n <button ion-button round icon-only block (click)="takePhoto()">\n <ion-icon name="camera"></ion-icon>\n </button>\n </p>\n</ion-content>\n'/*ion-inline-end:"/home/marcus/ionic2-camera-demo/src/pages/home/home.html"*/ }), __metadata("design:paramtypes", [__WEBPACK_IMPORTED_MODULE_1_ionic_angular__["d" /* NavController */], __WEBPACK_IMPORTED_MODULE_2__ionic_native_camera__["a" /* Camera */]]) ], HomePage); return HomePage; }()); //# sourceMappingURL=home.js.map /***/ }), /***/ 196: /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return AboutPage; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__angular_core__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_ionic_angular__ = __webpack_require__(33); var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var AboutPage = /** @class */ (function () { function AboutPage(navCtrl) { this.navCtrl = navCtrl; } AboutPage = __decorate([ Object(__WEBPACK_IMPORTED_MODULE_0__angular_core__["m" /* Component */])({ selector: 'page-about',template:/*ion-inline-start:"/home/marcus/ionic2-camera-demo/src/pages/about/about.html"*/'<ion-header>\n <ion-navbar>\n <ion-title>\n About\n </ion-title>\n </ion-navbar>\n</ion-header>\n\n<ion-content padding>\n\n</ion-content>\n'/*ion-inline-end:"/home/marcus/ionic2-camera-demo/src/pages/about/about.html"*/ }), __metadata("design:paramtypes", [__WEBPACK_IMPORTED_MODULE_1_ionic_angular__["d" /* NavController */]]) ], AboutPage); return AboutPage; }()); //# sourceMappingURL=about.js.map /***/ }), /***/ 197: /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return ContactPage; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__angular_core__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_ionic_angular__ = __webpack_require__(33); var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var ContactPage = /** @class */ (function () { function ContactPage(navCtrl) { this.navCtrl = navCtrl; } ContactPage = __decorate([ Object(__WEBPACK_IMPORTED_MODULE_0__angular_core__["m" /* Component */])({ selector: 'page-contact',template:/*ion-inline-start:"/home/marcus/ionic2-camera-demo/src/pages/contact/contact.html"*/'<ion-header>\n <ion-navbar>\n <ion-title>\n Contact\n </ion-title>\n </ion-navbar>\n</ion-header>\n\n<ion-content>\n <ion-list>\n <ion-list-header>Follow us on Twitter</ion-list-header>\n <ion-item>\n <ion-icon name="ionic" item-left></ion-icon>\n @ionicframework\n </ion-item>\n </ion-list>\n</ion-content>\n'/*ion-inline-end:"/home/marcus/ionic2-camera-demo/src/pages/contact/contact.html"*/ }), __metadata("design:paramtypes", [__WEBPACK_IMPORTED_MODULE_1_ionic_angular__["d" /* NavController */]]) ], ContactPage); return ContactPage; }()); //# sourceMappingURL=contact.js.map /***/ }), /***/ 198: /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__angular_platform_browser_dynamic__ = __webpack_require__(199); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__app_module__ = __webpack_require__(221); Object(__WEBPACK_IMPORTED_MODULE_0__angular_platform_browser_dynamic__["a" /* platformBrowserDynamic */])().bootstrapModule(__WEBPACK_IMPORTED_MODULE_1__app_module__["a" /* AppModule */]); //# sourceMappingURL=main.js.map /***/ }), /***/ 221: /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return AppModule; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__angular_core__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_ionic_angular__ = __webpack_require__(33); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__app_component__ = __webpack_require__(264); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__pages_about_about__ = __webpack_require__(196); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__pages_contact_contact__ = __webpack_require__(197); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__pages_home_home__ = __webpack_require__(194); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__pages_tabs_tabs__ = __webpack_require__(193); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__angular_platform_browser__ = __webpack_require__(29); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__ionic_native_status_bar__ = __webpack_require__(190); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_9__ionic_native_splash_screen__ = __webpack_require__(192); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_10__ionic_native_camera__ = __webpack_require__(195); var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var AppModule = /** @class */ (function () { function AppModule() { } AppModule = __decorate([ Object(__WEBPACK_IMPORTED_MODULE_0__angular_core__["I" /* NgModule */])({ declarations: [ __WEBPACK_IMPORTED_MODULE_2__app_component__["a" /* MyApp */], __WEBPACK_IMPORTED_MODULE_3__pages_about_about__["a" /* AboutPage */], __WEBPACK_IMPORTED_MODULE_4__pages_contact_contact__["a" /* ContactPage */], __WEBPACK_IMPORTED_MODULE_5__pages_home_home__["a" /* HomePage */], __WEBPACK_IMPORTED_MODULE_6__pages_tabs_tabs__["a" /* TabsPage */] ], imports: [ __WEBPACK_IMPORTED_MODULE_1_ionic_angular__["c" /* IonicModule */].forRoot(__WEBPACK_IMPORTED_MODULE_2__app_component__["a" /* MyApp */], {}, { links: [] }), __WEBPACK_IMPORTED_MODULE_7__angular_platform_browser__["a" /* BrowserModule */] ], bootstrap: [__WEBPACK_IMPORTED_MODULE_1_ionic_angular__["a" /* IonicApp */]], entryComponents: [ __WEBPACK_IMPORTED_MODULE_2__app_component__["a" /* MyApp */], __WEBPACK_IMPORTED_MODULE_3__pages_about_about__["a" /* AboutPage */], __WEBPACK_IMPORTED_MODULE_4__pages_contact_contact__["a" /* ContactPage */], __WEBPACK_IMPORTED_MODULE_5__pages_home_home__["a" /* HomePage */], __WEBPACK_IMPORTED_MODULE_6__pages_tabs_tabs__["a" /* TabsPage */] ], providers: [ __WEBPACK_IMPORTED_MODULE_8__ionic_native_status_bar__["a" /* StatusBar */], __WEBPACK_IMPORTED_MODULE_9__ionic_native_splash_screen__["a" /* SplashScreen */], __WEBPACK_IMPORTED_MODULE_10__ionic_native_camera__["a" /* Camera */], { provide: __WEBPACK_IMPORTED_MODULE_0__angular_core__["u" /* ErrorHandler */], useClass: __WEBPACK_IMPORTED_MODULE_1_ionic_angular__["b" /* IonicErrorHandler */] } ] }) ], AppModule); return AppModule; }()); //# sourceMappingURL=app.module.js.map /***/ }), /***/ 264: /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return MyApp; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__angular_core__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_ionic_angular__ = __webpack_require__(33); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__ionic_native_status_bar__ = __webpack_require__(190); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__ionic_native_splash_screen__ = __webpack_require__(192); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__pages_tabs_tabs__ = __webpack_require__(193); var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var MyApp = /** @class */ (function () { function MyApp(platform, statusBar, splashScreen) { this.rootPage = __WEBPACK_IMPORTED_MODULE_4__pages_tabs_tabs__["a" /* TabsPage */]; platform.ready().then(function () { // Okay, so the platform is ready and our plugins are available. // Here you can do any higher level native things you might need. statusBar.styleDefault(); splashScreen.hide(); }); } MyApp = __decorate([ Object(__WEBPACK_IMPORTED_MODULE_0__angular_core__["m" /* Component */])({template:/*ion-inline-start:"/home/marcus/ionic2-camera-demo/src/app/app.html"*/'<ion-nav [root]="rootPage"></ion-nav>\n'/*ion-inline-end:"/home/marcus/ionic2-camera-demo/src/app/app.html"*/ }), __metadata("design:paramtypes", [__WEBPACK_IMPORTED_MODULE_1_ionic_angular__["e" /* Platform */], __WEBPACK_IMPORTED_MODULE_2__ionic_native_status_bar__["a" /* StatusBar */], __WEBPACK_IMPORTED_MODULE_3__ionic_native_splash_screen__["a" /* SplashScreen */]]) ], MyApp); return MyApp; }()); //# sourceMappingURL=app.component.js.map /***/ }) },[198]); //# sourceMappingURL=main.js.map
marcusasplund/ionic2-camera-demo
www/build/main.js
JavaScript
mit
18,319
using GalaSoft.MvvmLight.Messaging; using System; using System.Diagnostics; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using WordPressUWP.ViewModels; namespace WordPressUWP.Views { public sealed partial class ShellPage : Page { private ShellViewModel ViewModel { get { return DataContext as ShellViewModel; } } public ShellPage() { InitializeComponent(); DataContext = ViewModel; ViewModel.Initialize(shellFrame); } private void Page_Loaded(object sender, Windows.UI.Xaml.RoutedEventArgs e) { Messenger.Default.Register<NotificationMessage>(this, (message) => GlobalInAppNotification.Show(message.Notification, 3000)); Window.Current.SizeChanged += Current_SizeChanged; InitLoginPopup(); } private void Current_SizeChanged(object sender, Windows.UI.Core.WindowSizeChangedEventArgs e) { InitLoginPopup(); } private void InitLoginPopup() { var windowWidth = Window.Current.Bounds.Width; var windowHeight = Window.Current.Bounds.Height; double popupWidth; double popupHeight; popupHeight = windowHeight; popupWidth = windowWidth; if (windowWidth <= 700) { LoginPopupGrid.Width = windowWidth; LoginPopupGrid.Height = windowHeight; } else { // set to Auto LoginPopupGrid.Width = double.NaN; LoginPopupGrid.Height = double.NaN; } LoginPopupWrapper.Width = popupWidth; LoginPopupWrapper.Height = popupHeight; LoginPopupGrid.VerticalAlignment = VerticalAlignment.Center; LoginPopupGrid.HorizontalAlignment = HorizontalAlignment.Center; } private void LoginBtn_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e) { Login(); } private void Login() { ViewModel.Login(UsernameTbx.Text, PasswordTbx.Password); PasswordTbx.Password = String.Empty; } private void PasswordTbx_KeyDown(object sender, Windows.UI.Xaml.Input.KeyRoutedEventArgs e) { if(e.Key == Windows.System.VirtualKey.Enter) Login(); } } }
wp-net/WordPressUWP
WordPressUWP/Views/ShellPage.xaml.cs
C#
mit
2,457
mf.include("chat_commands.js"); mf.include("assert.js"); mf.include("arrays.js"); /** * Example: * var id; * var count = 0; * task_manager.doLater(new task_manager.Task(function start() { * id = mf.setInterval(function() { * mf.debug("hello"); * if (++count === 10) { * task_manager.done(); * } * }, 1000); * }, function stop() { * mf.clearInterval(id); * }, "saying hello 10 times"); */ var task_manager = {}; (function() { /** * Constructor. * @param start_func() called when the job starts or resumes * @param stop_func() called when the job should pause or abort * @param string either a toString function or a string used to display the task in a list */ task_manager.Task = function(start_func, stop_func, string, resume_func) { assert.isFunction(start_func); this.start = start_func; assert.isFunction(stop_func); this.stop = stop_func; if (typeof string === "string") { var old_string = string; string = function() { return old_string; }; } assert.isFunction(string); this.toString = string; if (resume_func !== undefined) { assert.isFunction(resume_func); this.resume = resume_func; } this.started = false; }; var tasks = []; function runNextCommand() { if (tasks.length === 0) { return; } if (tasks[0].started && tasks[0].resume !== undefined) { tasks[0].resume(); } else { tasks[0].started = true; tasks[0].begin_time = new Date().getTime(); tasks[0].start(); } }; task_manager.doLater = function(task) { tasks.push(task); task.started = false; if (tasks.length === 1) { runNextCommand(); } }; task_manager.doNow = function(task) { if (tasks.length !== 0) { tasks[0].stop(); } tasks.remove(task); tasks.unshift(task); runNextCommand(); }; task_manager.done = function() { assert.isTrue(tasks.length !== 0); var length = tasks.length; tasks[0].started = false; tasks.shift(); assert.isTrue(length !== tasks.length); runNextCommand(); }; task_manager.postpone = function(min_timeout) { var task = tasks[0]; tasks.remove(task); if (min_timeout > 0) { task.postponed = mf.setTimeout(function resume() { task.postponed = undefined; tasks.push(task); if (tasks.length === 1) { runNextCommand(); } }, min_timeout); } else { tasks.push(task); } runNextCommand(); }; task_manager.remove = function(task) { if (task === tasks[0]) { task.stop(); tasks.remove(task); runNextCommand(); } else { tasks.remove(task); if (task.postponed !== undefined) { mf.clearTimeout(task.postponed); task.postponed = undefined; task.stop(); } } } chat_commands.registerCommand("stop", function() { if (tasks.length === 0) { return; } tasks[0].stop(); tasks = []; }); chat_commands.registerCommand("tasks",function(speaker,args,responder_fun) { responder_fun("Tasks: " + tasks.join(", ")); }); chat_commands.registerCommand("reboot", function(speaker, args, responder_fun) { if (tasks.length === 0) { responder_fun("no tasks"); return; } tasks[0].stop(); tasks[0].start(); }), })();
crazy2be/mineflayer
mineflayer-script/lib/task_manager.js
JavaScript
mit
3,848
#!/usr/bin/env python from util import nodeenv_delegate from setup import setup if __name__ == "__main__": setup(skip_dependencies=True) nodeenv_delegate("npx")
outoftime/learnpad
tools/npx.py
Python
mit
171
package org.knowm.xchange.dsx.dto.account; import org.knowm.xchange.dsx.dto.DSXReturn; import com.fasterxml.jackson.annotation.JsonProperty; /** * @author Mikhail Wall */ public class DSXFiatWithdrawReturn extends DSXReturn<DSXFiatWithdraw> { public DSXFiatWithdrawReturn(@JsonProperty("success") boolean success, @JsonProperty("return") DSXFiatWithdraw value, @JsonProperty("error") String error) { super(success, value, error); } }
gaborkolozsy/XChange
xchange-dsx/src/main/java/org/knowm/xchange/dsx/dto/account/DSXFiatWithdrawReturn.java
Java
mit
455
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\ErrorHandler; use Doctrine\Common\Persistence\Proxy as LegacyProxy; use Doctrine\Persistence\Proxy; use PHPUnit\Framework\MockObject\Matcher\StatelessInvocation; use PHPUnit\Framework\MockObject\MockObject; use Prophecy\Prophecy\ProphecySubjectInterface; use ProxyManager\Proxy\ProxyInterface; /** * Autoloader checking if the class is really defined in the file found. * * The ClassLoader will wrap all registered autoloaders * and will throw an exception if a file is found but does * not declare the class. * * It can also patch classes to turn docblocks into actual return types. * This behavior is controlled by the SYMFONY_PATCH_TYPE_DECLARATIONS env var, * which is a url-encoded array with the follow parameters: * - "force": any value enables deprecation notices - can be any of: * - "docblock" to patch only docblock annotations * - "object" to turn union types to the "object" type when possible (not recommended) * - "1" to add all possible return types including magic methods * - "0" to add possible return types excluding magic methods * - "php": the target version of PHP - e.g. "7.1" doesn't generate "object" types * - "deprecations": "1" to trigger a deprecation notice when a child class misses a * return type while the parent declares an "@return" annotation * * Note that patching doesn't care about any coding style so you'd better to run * php-cs-fixer after, with rules "phpdoc_trim_consecutive_blank_line_separation" * and "no_superfluous_phpdoc_tags" enabled typically. * * @author Fabien Potencier <fabien@symfony.com> * @author Christophe Coevoet <stof@notk.org> * @author Nicolas Grekas <p@tchwork.com> * @author Guilhem Niot <guilhem.niot@gmail.com> */ class DebugClassLoader { private const SPECIAL_RETURN_TYPES = [ 'mixed' => 'mixed', 'void' => 'void', 'null' => 'null', 'resource' => 'resource', 'static' => 'object', '$this' => 'object', 'boolean' => 'bool', 'true' => 'bool', 'false' => 'bool', 'integer' => 'int', 'array' => 'array', 'bool' => 'bool', 'callable' => 'callable', 'float' => 'float', 'int' => 'int', 'iterable' => 'iterable', 'object' => 'object', 'string' => 'string', 'self' => 'self', 'parent' => 'parent', ]; private const BUILTIN_RETURN_TYPES = [ 'void' => true, 'array' => true, 'bool' => true, 'callable' => true, 'float' => true, 'int' => true, 'iterable' => true, 'object' => true, 'string' => true, 'self' => true, 'parent' => true, ]; private const MAGIC_METHODS = [ '__set' => 'void', '__isset' => 'bool', '__unset' => 'void', '__sleep' => 'array', '__wakeup' => 'void', '__toString' => 'string', '__clone' => 'void', '__debugInfo' => 'array', '__serialize' => 'array', '__unserialize' => 'void', ]; private const INTERNAL_TYPES = [ 'ArrayAccess' => [ 'offsetExists' => 'bool', 'offsetSet' => 'void', 'offsetUnset' => 'void', ], 'Countable' => [ 'count' => 'int', ], 'Iterator' => [ 'next' => 'void', 'valid' => 'bool', 'rewind' => 'void', ], 'IteratorAggregate' => [ 'getIterator' => '\Traversable', ], 'OuterIterator' => [ 'getInnerIterator' => '\Iterator', ], 'RecursiveIterator' => [ 'hasChildren' => 'bool', ], 'SeekableIterator' => [ 'seek' => 'void', ], 'Serializable' => [ 'serialize' => 'string', 'unserialize' => 'void', ], 'SessionHandlerInterface' => [ 'open' => 'bool', 'close' => 'bool', 'read' => 'string', 'write' => 'bool', 'destroy' => 'bool', 'gc' => 'bool', ], 'SessionIdInterface' => [ 'create_sid' => 'string', ], 'SessionUpdateTimestampHandlerInterface' => [ 'validateId' => 'bool', 'updateTimestamp' => 'bool', ], 'Throwable' => [ 'getMessage' => 'string', 'getCode' => 'int', 'getFile' => 'string', 'getLine' => 'int', 'getTrace' => 'array', 'getPrevious' => '?\Throwable', 'getTraceAsString' => 'string', ], ]; private $classLoader; private $isFinder; private $loaded = []; private $patchTypes; private static $caseCheck; private static $checkedClasses = []; private static $final = []; private static $finalMethods = []; private static $deprecated = []; private static $internal = []; private static $internalMethods = []; private static $annotatedParameters = []; private static $darwinCache = ['/' => ['/', []]]; private static $method = []; private static $returnTypes = []; private static $methodTraits = []; private static $fileOffsets = []; public function __construct(callable $classLoader) { $this->classLoader = $classLoader; $this->isFinder = \is_array($classLoader) && method_exists($classLoader[0], 'findFile'); parse_str(getenv('SYMFONY_PATCH_TYPE_DECLARATIONS') ?: '', $this->patchTypes); $this->patchTypes += [ 'force' => null, 'php' => null, 'deprecations' => false, ]; if (!isset(self::$caseCheck)) { $file = file_exists(__FILE__) ? __FILE__ : rtrim(realpath('.'), \DIRECTORY_SEPARATOR); $i = strrpos($file, \DIRECTORY_SEPARATOR); $dir = substr($file, 0, 1 + $i); $file = substr($file, 1 + $i); $test = strtoupper($file) === $file ? strtolower($file) : strtoupper($file); $test = realpath($dir.$test); if (false === $test || false === $i) { // filesystem is case sensitive self::$caseCheck = 0; } elseif (substr($test, -\strlen($file)) === $file) { // filesystem is case insensitive and realpath() normalizes the case of characters self::$caseCheck = 1; } elseif (false !== stripos(PHP_OS, 'darwin')) { // on MacOSX, HFS+ is case insensitive but realpath() doesn't normalize the case of characters self::$caseCheck = 2; } else { // filesystem case checks failed, fallback to disabling them self::$caseCheck = 0; } } } /** * Gets the wrapped class loader. * * @return callable The wrapped class loader */ public function getClassLoader(): callable { return $this->classLoader; } /** * Wraps all autoloaders. */ public static function enable(): void { // Ensures we don't hit https://bugs.php.net/42098 class_exists('Symfony\Component\ErrorHandler\ErrorHandler'); class_exists('Psr\Log\LogLevel'); if (!\is_array($functions = spl_autoload_functions())) { return; } foreach ($functions as $function) { spl_autoload_unregister($function); } foreach ($functions as $function) { if (!\is_array($function) || !$function[0] instanceof self) { $function = [new static($function), 'loadClass']; } spl_autoload_register($function); } } /** * Disables the wrapping. */ public static function disable(): void { if (!\is_array($functions = spl_autoload_functions())) { return; } foreach ($functions as $function) { spl_autoload_unregister($function); } foreach ($functions as $function) { if (\is_array($function) && $function[0] instanceof self) { $function = $function[0]->getClassLoader(); } spl_autoload_register($function); } } public static function checkClasses(): bool { if (!\is_array($functions = spl_autoload_functions())) { return false; } $loader = null; foreach ($functions as $function) { if (\is_array($function) && $function[0] instanceof self) { $loader = $function[0]; break; } } if (null === $loader) { return false; } static $offsets = [ 'get_declared_interfaces' => 0, 'get_declared_traits' => 0, 'get_declared_classes' => 0, ]; foreach ($offsets as $getSymbols => $i) { $symbols = $getSymbols(); for (; $i < \count($symbols); ++$i) { if (!is_subclass_of($symbols[$i], MockObject::class) && !is_subclass_of($symbols[$i], ProphecySubjectInterface::class) && !is_subclass_of($symbols[$i], Proxy::class) && !is_subclass_of($symbols[$i], ProxyInterface::class) && !is_subclass_of($symbols[$i], LegacyProxy::class) ) { $loader->checkClass($symbols[$i]); } } $offsets[$getSymbols] = $i; } return true; } public function findFile(string $class): ?string { return $this->isFinder ? ($this->classLoader[0]->findFile($class) ?: null) : null; } /** * Loads the given class or interface. * * @throws \RuntimeException */ public function loadClass(string $class): void { $e = error_reporting(error_reporting() | E_PARSE | E_ERROR | E_CORE_ERROR | E_COMPILE_ERROR); try { if ($this->isFinder && !isset($this->loaded[$class])) { $this->loaded[$class] = true; if (!$file = $this->classLoader[0]->findFile($class) ?: '') { // no-op } elseif (\function_exists('opcache_is_script_cached') && @opcache_is_script_cached($file)) { include $file; return; } elseif (false === include $file) { return; } } else { ($this->classLoader)($class); $file = ''; } } finally { error_reporting($e); } $this->checkClass($class, $file); } private function checkClass(string $class, string $file = null): void { $exists = null === $file || class_exists($class, false) || interface_exists($class, false) || trait_exists($class, false); if (null !== $file && $class && '\\' === $class[0]) { $class = substr($class, 1); } if ($exists) { if (isset(self::$checkedClasses[$class])) { return; } self::$checkedClasses[$class] = true; $refl = new \ReflectionClass($class); if (null === $file && $refl->isInternal()) { return; } $name = $refl->getName(); if ($name !== $class && 0 === strcasecmp($name, $class)) { throw new \RuntimeException(sprintf('Case mismatch between loaded and declared class names: "%s" vs "%s".', $class, $name)); } $deprecations = $this->checkAnnotations($refl, $name); foreach ($deprecations as $message) { @trigger_error($message, E_USER_DEPRECATED); } } if (!$file) { return; } if (!$exists) { if (false !== strpos($class, '/')) { throw new \RuntimeException(sprintf('Trying to autoload a class with an invalid name "%s". Be careful that the namespace separator is "\" in PHP, not "/".', $class)); } throw new \RuntimeException(sprintf('The autoloader expected class "%s" to be defined in file "%s". The file was found but the class was not in it, the class name or namespace probably has a typo.', $class, $file)); } if (self::$caseCheck && $message = $this->checkCase($refl, $file, $class)) { throw new \RuntimeException(sprintf('Case mismatch between class and real file names: "%s" vs "%s" in "%s".', $message[0], $message[1], $message[2])); } } public function checkAnnotations(\ReflectionClass $refl, string $class): array { if ( 'Symfony\Bridge\PhpUnit\Legacy\SymfonyTestsListenerForV7' === $class || 'Symfony\Bridge\PhpUnit\Legacy\SymfonyTestsListenerForV6' === $class ) { return []; } $deprecations = []; $className = isset($class[15]) && "\0" === $class[15] && 0 === strpos($class, "class@anonymous\x00") ? (get_parent_class($class) ?: key(class_implements($class))).'@anonymous' : $class; // Don't trigger deprecations for classes in the same vendor if ($class !== $className) { $vendor = preg_match('/^namespace ([^;\\\\\s]++)[;\\\\]/m', @file_get_contents($refl->getFileName()), $vendor) ? $vendor[1].'\\' : ''; $vendorLen = \strlen($vendor); } elseif (2 > $vendorLen = 1 + (strpos($class, '\\') ?: strpos($class, '_'))) { $vendorLen = 0; $vendor = ''; } else { $vendor = str_replace('_', '\\', substr($class, 0, $vendorLen)); } // Detect annotations on the class if (false !== $doc = $refl->getDocComment()) { foreach (['final', 'deprecated', 'internal'] as $annotation) { if (false !== strpos($doc, $annotation) && preg_match('#\n\s+\* @'.$annotation.'(?:( .+?)\.?)?\r?\n\s+\*(?: @|/$|\r?\n)#s', $doc, $notice)) { self::${$annotation}[$class] = isset($notice[1]) ? preg_replace('#\.?\r?\n( \*)? *(?= |\r?\n|$)#', '', $notice[1]) : ''; } } if ($refl->isInterface() && false !== strpos($doc, 'method') && preg_match_all('#\n \* @method\s+(static\s+)?+(?:[\w\|&\[\]\\\]+\s+)?(\w+(?:\s*\([^\)]*\))?)+(.+?([[:punct:]]\s*)?)?(?=\r?\n \*(?: @|/$|\r?\n))#', $doc, $notice, PREG_SET_ORDER)) { foreach ($notice as $method) { $static = '' !== $method[1]; $name = $method[2]; $description = $method[3] ?? null; if (false === strpos($name, '(')) { $name .= '()'; } if (null !== $description) { $description = trim($description); if (!isset($method[4])) { $description .= '.'; } } self::$method[$class][] = [$class, $name, $static, $description]; } } } $parent = get_parent_class($class) ?: null; $parentAndOwnInterfaces = $this->getOwnInterfaces($class, $parent); if ($parent) { $parentAndOwnInterfaces[$parent] = $parent; if (!isset(self::$checkedClasses[$parent])) { $this->checkClass($parent); } if (isset(self::$final[$parent])) { $deprecations[] = sprintf('The "%s" class is considered final%s. It may change without further notice as of its next major version. You should not extend it from "%s".', $parent, self::$final[$parent], $className); } } // Detect if the parent is annotated foreach ($parentAndOwnInterfaces + class_uses($class, false) as $use) { if (!isset(self::$checkedClasses[$use])) { $this->checkClass($use); } if (isset(self::$deprecated[$use]) && strncmp($vendor, str_replace('_', '\\', $use), $vendorLen) && !isset(self::$deprecated[$class])) { $type = class_exists($class, false) ? 'class' : (interface_exists($class, false) ? 'interface' : 'trait'); $verb = class_exists($use, false) || interface_exists($class, false) ? 'extends' : (interface_exists($use, false) ? 'implements' : 'uses'); $deprecations[] = sprintf('The "%s" %s %s "%s" that is deprecated%s.', $className, $type, $verb, $use, self::$deprecated[$use]); } if (isset(self::$internal[$use]) && strncmp($vendor, str_replace('_', '\\', $use), $vendorLen)) { $deprecations[] = sprintf('The "%s" %s is considered internal%s. It may change without further notice. You should not use it from "%s".', $use, class_exists($use, false) ? 'class' : (interface_exists($use, false) ? 'interface' : 'trait'), self::$internal[$use], $className); } if (isset(self::$method[$use])) { if ($refl->isAbstract()) { if (isset(self::$method[$class])) { self::$method[$class] = array_merge(self::$method[$class], self::$method[$use]); } else { self::$method[$class] = self::$method[$use]; } } elseif (!$refl->isInterface()) { $hasCall = $refl->hasMethod('__call'); $hasStaticCall = $refl->hasMethod('__callStatic'); foreach (self::$method[$use] as $method) { list($interface, $name, $static, $description) = $method; if ($static ? $hasStaticCall : $hasCall) { continue; } $realName = substr($name, 0, strpos($name, '(')); if (!$refl->hasMethod($realName) || !($methodRefl = $refl->getMethod($realName))->isPublic() || ($static && !$methodRefl->isStatic()) || (!$static && $methodRefl->isStatic())) { $deprecations[] = sprintf('Class "%s" should implement method "%s::%s"%s', $className, ($static ? 'static ' : '').$interface, $name, null == $description ? '.' : ': '.$description); } } } } } if (trait_exists($class)) { $file = $refl->getFileName(); foreach ($refl->getMethods() as $method) { if ($method->getFileName() === $file) { self::$methodTraits[$file][$method->getStartLine()] = $class; } } return $deprecations; } // Inherit @final, @internal, @param and @return annotations for methods self::$finalMethods[$class] = []; self::$internalMethods[$class] = []; self::$annotatedParameters[$class] = []; self::$returnTypes[$class] = []; foreach ($parentAndOwnInterfaces as $use) { foreach (['finalMethods', 'internalMethods', 'annotatedParameters', 'returnTypes'] as $property) { if (isset(self::${$property}[$use])) { self::${$property}[$class] = self::${$property}[$class] ? self::${$property}[$use] + self::${$property}[$class] : self::${$property}[$use]; } } if (null !== (self::INTERNAL_TYPES[$use] ?? null)) { foreach (self::INTERNAL_TYPES[$use] as $method => $returnType) { if ('void' !== $returnType) { self::$returnTypes[$class] += [$method => [$returnType, $returnType, $class, '']]; } } } } foreach ($refl->getMethods() as $method) { if ($method->class !== $class) { continue; } if (null === $ns = self::$methodTraits[$method->getFileName()][$method->getStartLine()] ?? null) { $ns = $vendor; $len = $vendorLen; } elseif (2 > $len = 1 + (strpos($ns, '\\') ?: strpos($ns, '_'))) { $len = 0; $ns = ''; } else { $ns = str_replace('_', '\\', substr($ns, 0, $len)); } if ($parent && isset(self::$finalMethods[$parent][$method->name])) { list($declaringClass, $message) = self::$finalMethods[$parent][$method->name]; $deprecations[] = sprintf('The "%s::%s()" method is considered final%s. It may change without further notice as of its next major version. You should not extend it from "%s".', $declaringClass, $method->name, $message, $className); } if (isset(self::$internalMethods[$class][$method->name])) { list($declaringClass, $message) = self::$internalMethods[$class][$method->name]; if (strncmp($ns, $declaringClass, $len)) { $deprecations[] = sprintf('The "%s::%s()" method is considered internal%s. It may change without further notice. You should not extend it from "%s".', $declaringClass, $method->name, $message, $className); } } // To read method annotations $doc = $method->getDocComment(); if (isset(self::$annotatedParameters[$class][$method->name])) { $definedParameters = []; foreach ($method->getParameters() as $parameter) { $definedParameters[$parameter->name] = true; } foreach (self::$annotatedParameters[$class][$method->name] as $parameterName => $deprecation) { if (!isset($definedParameters[$parameterName]) && !($doc && preg_match("/\\n\\s+\\* @param +((?(?!callable *\().*?|callable *\(.*\).*?))(?<= )\\\${$parameterName}\\b/", $doc))) { $deprecations[] = sprintf($deprecation, $className); } } } $forcePatchTypes = $this->patchTypes['force']; if ($canAddReturnType = null !== $forcePatchTypes && false === strpos($method->getFileName(), \DIRECTORY_SEPARATOR.'vendor'.\DIRECTORY_SEPARATOR)) { if ('void' !== (self::MAGIC_METHODS[$method->name] ?? 'void')) { $this->patchTypes['force'] = $forcePatchTypes ?: 'docblock'; } $canAddReturnType = false !== strpos($refl->getFileName(), \DIRECTORY_SEPARATOR.'Tests'.\DIRECTORY_SEPARATOR) || $refl->isFinal() || $method->isFinal() || $method->isPrivate() || ('' === (self::$internal[$class] ?? null) && !$refl->isAbstract()) || '' === (self::$final[$class] ?? null) || preg_match('/@(final|internal)$/m', $doc) ; } if (null !== ($returnType = self::$returnTypes[$class][$method->name] ?? self::MAGIC_METHODS[$method->name] ?? null) && !$method->hasReturnType() && !($doc && preg_match('/\n\s+\* @return +(\S+)/', $doc))) { list($normalizedType, $returnType, $declaringClass, $declaringFile) = \is_string($returnType) ? [$returnType, $returnType, '', ''] : $returnType; if ('void' === $normalizedType) { $canAddReturnType = false; } if ($canAddReturnType && 'docblock' !== $this->patchTypes['force']) { $this->patchMethod($method, $returnType, $declaringFile, $normalizedType); } if (strncmp($ns, $declaringClass, $len)) { if ($canAddReturnType && 'docblock' === $this->patchTypes['force'] && false === strpos($method->getFileName(), \DIRECTORY_SEPARATOR.'vendor'.\DIRECTORY_SEPARATOR)) { $this->patchMethod($method, $returnType, $declaringFile, $normalizedType); } elseif ('' !== $declaringClass && $this->patchTypes['deprecations']) { $deprecations[] = sprintf('Method "%s::%s()" will return "%s" as of its next major version. Doing the same in child class "%s" will be required when upgrading.', $declaringClass, $method->name, $normalizedType, $className); } } } if (!$doc) { $this->patchTypes['force'] = $forcePatchTypes; continue; } $matches = []; if (!$method->hasReturnType() && ((false !== strpos($doc, '@return') && preg_match('/\n\s+\* @return +(\S+)/', $doc, $matches)) || 'void' !== (self::MAGIC_METHODS[$method->name] ?? 'void'))) { $matches = $matches ?: [1 => self::MAGIC_METHODS[$method->name]]; $this->setReturnType($matches[1], $method, $parent); if (isset(self::$returnTypes[$class][$method->name][0]) && $canAddReturnType) { $this->fixReturnStatements($method, self::$returnTypes[$class][$method->name][0]); } if ($method->isPrivate()) { unset(self::$returnTypes[$class][$method->name]); } } $this->patchTypes['force'] = $forcePatchTypes; if ($method->isPrivate()) { continue; } $finalOrInternal = false; foreach (['final', 'internal'] as $annotation) { if (false !== strpos($doc, $annotation) && preg_match('#\n\s+\* @'.$annotation.'(?:( .+?)\.?)?\r?\n\s+\*(?: @|/$|\r?\n)#s', $doc, $notice)) { $message = isset($notice[1]) ? preg_replace('#\.?\r?\n( \*)? *(?= |\r?\n|$)#', '', $notice[1]) : ''; self::${$annotation.'Methods'}[$class][$method->name] = [$class, $message]; $finalOrInternal = true; } } if ($finalOrInternal || $method->isConstructor() || false === strpos($doc, '@param') || StatelessInvocation::class === $class) { continue; } if (!preg_match_all('#\n\s+\* @param +((?(?!callable *\().*?|callable *\(.*\).*?))(?<= )\$([a-zA-Z0-9_\x7f-\xff]++)#', $doc, $matches, PREG_SET_ORDER)) { continue; } if (!isset(self::$annotatedParameters[$class][$method->name])) { $definedParameters = []; foreach ($method->getParameters() as $parameter) { $definedParameters[$parameter->name] = true; } } foreach ($matches as list(, $parameterType, $parameterName)) { if (!isset($definedParameters[$parameterName])) { $parameterType = trim($parameterType); self::$annotatedParameters[$class][$method->name][$parameterName] = sprintf('The "%%s::%s()" method will require a new "%s$%s" argument in the next major version of its parent class "%s", not defining it is deprecated.', $method->name, $parameterType ? $parameterType.' ' : '', $parameterName, $className); } } } return $deprecations; } public function checkCase(\ReflectionClass $refl, string $file, string $class): ?array { $real = explode('\\', $class.strrchr($file, '.')); $tail = explode(\DIRECTORY_SEPARATOR, str_replace('/', \DIRECTORY_SEPARATOR, $file)); $i = \count($tail) - 1; $j = \count($real) - 1; while (isset($tail[$i], $real[$j]) && $tail[$i] === $real[$j]) { --$i; --$j; } array_splice($tail, 0, $i + 1); if (!$tail) { return null; } $tail = \DIRECTORY_SEPARATOR.implode(\DIRECTORY_SEPARATOR, $tail); $tailLen = \strlen($tail); $real = $refl->getFileName(); if (2 === self::$caseCheck) { $real = $this->darwinRealpath($real); } if (0 === substr_compare($real, $tail, -$tailLen, $tailLen, true) && 0 !== substr_compare($real, $tail, -$tailLen, $tailLen, false) ) { return [substr($tail, -$tailLen + 1), substr($real, -$tailLen + 1), substr($real, 0, -$tailLen + 1)]; } return null; } /** * `realpath` on MacOSX doesn't normalize the case of characters. */ private function darwinRealpath(string $real): string { $i = 1 + strrpos($real, '/'); $file = substr($real, $i); $real = substr($real, 0, $i); if (isset(self::$darwinCache[$real])) { $kDir = $real; } else { $kDir = strtolower($real); if (isset(self::$darwinCache[$kDir])) { $real = self::$darwinCache[$kDir][0]; } else { $dir = getcwd(); if (!@chdir($real)) { return $real.$file; } $real = getcwd().'/'; chdir($dir); $dir = $real; $k = $kDir; $i = \strlen($dir) - 1; while (!isset(self::$darwinCache[$k])) { self::$darwinCache[$k] = [$dir, []]; self::$darwinCache[$dir] = &self::$darwinCache[$k]; while ('/' !== $dir[--$i]) { } $k = substr($k, 0, ++$i); $dir = substr($dir, 0, $i--); } } } $dirFiles = self::$darwinCache[$kDir][1]; if (!isset($dirFiles[$file]) && ') : eval()\'d code' === substr($file, -17)) { // Get the file name from "file_name.php(123) : eval()'d code" $file = substr($file, 0, strrpos($file, '(', -17)); } if (isset($dirFiles[$file])) { return $real.$dirFiles[$file]; } $kFile = strtolower($file); if (!isset($dirFiles[$kFile])) { foreach (scandir($real, 2) as $f) { if ('.' !== $f[0]) { $dirFiles[$f] = $f; if ($f === $file) { $kFile = $k = $file; } elseif ($f !== $k = strtolower($f)) { $dirFiles[$k] = $f; } } } self::$darwinCache[$kDir][1] = $dirFiles; } return $real.$dirFiles[$kFile]; } /** * `class_implements` includes interfaces from the parents so we have to manually exclude them. * * @return string[] */ private function getOwnInterfaces(string $class, ?string $parent): array { $ownInterfaces = class_implements($class, false); if ($parent) { foreach (class_implements($parent, false) as $interface) { unset($ownInterfaces[$interface]); } } foreach ($ownInterfaces as $interface) { foreach (class_implements($interface) as $interface) { unset($ownInterfaces[$interface]); } } return $ownInterfaces; } private function setReturnType(string $types, \ReflectionMethod $method, ?string $parent): void { $nullable = false; $typesMap = []; foreach (explode('|', $types) as $t) { $typesMap[$this->normalizeType($t, $method->class, $parent)] = $t; } if (isset($typesMap['array'])) { if (isset($typesMap['Traversable']) || isset($typesMap['\Traversable'])) { $typesMap['iterable'] = 'array' !== $typesMap['array'] ? $typesMap['array'] : 'iterable'; unset($typesMap['array'], $typesMap['Traversable'], $typesMap['\Traversable']); } elseif ('array' !== $typesMap['array'] && isset(self::$returnTypes[$method->class][$method->name])) { return; } } if (isset($typesMap['array']) && isset($typesMap['iterable'])) { if ('[]' === substr($typesMap['array'], -2)) { $typesMap['iterable'] = $typesMap['array']; } unset($typesMap['array']); } $iterable = $object = true; foreach ($typesMap as $n => $t) { if ('null' !== $n) { $iterable = $iterable && (\in_array($n, ['array', 'iterable']) || false !== strpos($n, 'Iterator')); $object = $object && (\in_array($n, ['callable', 'object', '$this', 'static']) || !isset(self::SPECIAL_RETURN_TYPES[$n])); } } $normalizedType = key($typesMap); $returnType = current($typesMap); foreach ($typesMap as $n => $t) { if ('null' === $n) { $nullable = true; } elseif ('null' === $normalizedType) { $normalizedType = $t; $returnType = $t; } elseif ($n !== $normalizedType || !preg_match('/^\\\\?[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*+(?:\\\\[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*+)*+$/', $n)) { if ($iterable) { $normalizedType = $returnType = 'iterable'; } elseif ($object && 'object' === $this->patchTypes['force']) { $normalizedType = $returnType = 'object'; } else { // ignore multi-types return declarations return; } } } if ('void' === $normalizedType) { $nullable = false; } elseif (!isset(self::BUILTIN_RETURN_TYPES[$normalizedType]) && isset(self::SPECIAL_RETURN_TYPES[$normalizedType])) { // ignore other special return types return; } if ($nullable) { $normalizedType = '?'.$normalizedType; $returnType .= '|null'; } self::$returnTypes[$method->class][$method->name] = [$normalizedType, $returnType, $method->class, $method->getFileName()]; } private function normalizeType(string $type, string $class, ?string $parent): string { if (isset(self::SPECIAL_RETURN_TYPES[$lcType = strtolower($type)])) { if ('parent' === $lcType = self::SPECIAL_RETURN_TYPES[$lcType]) { $lcType = null !== $parent ? '\\'.$parent : 'parent'; } elseif ('self' === $lcType) { $lcType = '\\'.$class; } return $lcType; } if ('[]' === substr($type, -2)) { return 'array'; } if (preg_match('/^(array|iterable|callable) *[<(]/', $lcType, $m)) { return $m[1]; } // We could resolve "use" statements to return the FQDN // but this would be too expensive for a runtime checker return $type; } /** * Utility method to add @return annotations to the Symfony code-base where it triggers a self-deprecations. */ private function patchMethod(\ReflectionMethod $method, string $returnType, string $declaringFile, string $normalizedType) { static $patchedMethods = []; static $useStatements = []; if (!file_exists($file = $method->getFileName()) || isset($patchedMethods[$file][$startLine = $method->getStartLine()])) { return; } $patchedMethods[$file][$startLine] = true; $fileOffset = self::$fileOffsets[$file] ?? 0; $startLine += $fileOffset - 2; $nullable = '?' === $normalizedType[0] ? '?' : ''; $normalizedType = ltrim($normalizedType, '?'); $returnType = explode('|', $returnType); $code = file($file); foreach ($returnType as $i => $type) { if (preg_match('/((?:\[\])+)$/', $type, $m)) { $type = substr($type, 0, -\strlen($m[1])); $format = '%s'.$m[1]; } elseif (preg_match('/^(array|iterable)<([^,>]++)>$/', $type, $m)) { $type = $m[2]; $format = $m[1].'<%s>'; } else { $format = null; } if (isset(self::SPECIAL_RETURN_TYPES[$type]) || ('\\' === $type[0] && !$p = strrpos($type, '\\', 1))) { continue; } list($namespace, $useOffset, $useMap) = $useStatements[$file] ?? $useStatements[$file] = self::getUseStatements($file); if ('\\' !== $type[0]) { list($declaringNamespace, , $declaringUseMap) = $useStatements[$declaringFile] ?? $useStatements[$declaringFile] = self::getUseStatements($declaringFile); $p = strpos($type, '\\', 1); $alias = $p ? substr($type, 0, $p) : $type; if (isset($declaringUseMap[$alias])) { $type = '\\'.$declaringUseMap[$alias].($p ? substr($type, $p) : ''); } else { $type = '\\'.$declaringNamespace.$type; } $p = strrpos($type, '\\', 1); } $alias = substr($type, 1 + $p); $type = substr($type, 1); if (!isset($useMap[$alias]) && (class_exists($c = $namespace.$alias) || interface_exists($c) || trait_exists($c))) { $useMap[$alias] = $c; } if (!isset($useMap[$alias])) { $useStatements[$file][2][$alias] = $type; $code[$useOffset] = "use $type;\n".$code[$useOffset]; ++$fileOffset; } elseif ($useMap[$alias] !== $type) { $alias .= 'FIXME'; $useStatements[$file][2][$alias] = $type; $code[$useOffset] = "use $type as $alias;\n".$code[$useOffset]; ++$fileOffset; } $returnType[$i] = null !== $format ? sprintf($format, $alias) : $alias; if (!isset(self::SPECIAL_RETURN_TYPES[$normalizedType]) && !isset(self::SPECIAL_RETURN_TYPES[$returnType[$i]])) { $normalizedType = $returnType[$i]; } } if ('docblock' === $this->patchTypes['force'] || ('object' === $normalizedType && '7.1' === $this->patchTypes['php'])) { $returnType = implode('|', $returnType); if ($method->getDocComment()) { $code[$startLine] = " * @return $returnType\n".$code[$startLine]; } else { $code[$startLine] .= <<<EOTXT /** * @return $returnType */ EOTXT; } $fileOffset += substr_count($code[$startLine], "\n") - 1; } self::$fileOffsets[$file] = $fileOffset; file_put_contents($file, $code); $this->fixReturnStatements($method, $nullable.$normalizedType); } private static function getUseStatements(string $file): array { $namespace = ''; $useMap = []; $useOffset = 0; if (!file_exists($file)) { return [$namespace, $useOffset, $useMap]; } $file = file($file); for ($i = 0; $i < \count($file); ++$i) { if (preg_match('/^(class|interface|trait|abstract) /', $file[$i])) { break; } if (0 === strpos($file[$i], 'namespace ')) { $namespace = substr($file[$i], \strlen('namespace '), -2).'\\'; $useOffset = $i + 2; } if (0 === strpos($file[$i], 'use ')) { $useOffset = $i; for (; 0 === strpos($file[$i], 'use '); ++$i) { $u = explode(' as ', substr($file[$i], 4, -2), 2); if (1 === \count($u)) { $p = strrpos($u[0], '\\'); $useMap[substr($u[0], false !== $p ? 1 + $p : 0)] = $u[0]; } else { $useMap[$u[1]] = $u[0]; } } break; } } return [$namespace, $useOffset, $useMap]; } private function fixReturnStatements(\ReflectionMethod $method, string $returnType) { if ('7.1' === $this->patchTypes['php'] && 'object' === ltrim($returnType, '?') && 'docblock' !== $this->patchTypes['force']) { return; } if (!file_exists($file = $method->getFileName())) { return; } $fixedCode = $code = file($file); $i = (self::$fileOffsets[$file] ?? 0) + $method->getStartLine(); if ('?' !== $returnType && 'docblock' !== $this->patchTypes['force']) { $fixedCode[$i - 1] = preg_replace('/\)(;?\n)/', "): $returnType\\1", $code[$i - 1]); } $end = $method->isGenerator() ? $i : $method->getEndLine(); for (; $i < $end; ++$i) { if ('void' === $returnType) { $fixedCode[$i] = str_replace(' return null;', ' return;', $code[$i]); } elseif ('mixed' === $returnType || '?' === $returnType[0]) { $fixedCode[$i] = str_replace(' return;', ' return null;', $code[$i]); } else { $fixedCode[$i] = str_replace(' return;', " return $returnType!?;", $code[$i]); } } if ($fixedCode !== $code) { file_put_contents($file, $fixedCode); } } }
zorn-v/symfony
src/Symfony/Component/ErrorHandler/DebugClassLoader.php
PHP
mit
41,716
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="IEnumerableExtensions.cs" company="Freiwillige Feuerwehr Krems/Donau"> // Freiwillige Feuerwehr Krems/Donau // Austraße 33 // A-3500 Krems/Donau // Austria // // Tel.: +43 (0)2732 85522 // Fax.: +43 (0)2732 85522 40 // E-mail: office@feuerwehr-krems.at // // This software is furnished under a license and may be // used and copied only in accordance with the terms of // such license and with the inclusion of the above // copyright notice. This software or any other copies // thereof may not be provided or otherwise made // available to any other person. No title to and // ownership of the software is hereby transferred. // // The information in this software is subject to change // without notice and should not be construed as a // commitment by Freiwillige Feuerwehr Krems/Donau. // // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace At.FF.Krems.Utils.Extensions { using System.Collections; using System.Collections.Generic; using System.Linq; // ReSharper disable once InconsistentNaming /// <summary>The IEnumerable extensions.</summary> public static class IEnumerableExtensions { /// <summary>Determines whether the specified IEnumerable has items.</summary> /// <param name="target">The target.</param> /// <returns><see cref="bool">False</see> if null or empty.</returns> public static bool HasItems(this IEnumerable target) { return target != null && target.OfType<object>().Any(); } /// <summary>Determines whether the specified generic IEnumerable has items.</summary> /// <typeparam name="T">The element type.</typeparam> /// <param name="target">The target.</param> /// <returns><see cref="bool">False</see> if null or empty.</returns> public static bool HasItems<T>(this IEnumerable<T> target) { return target != null && target.Any(); } } }
Grisu-NOE/Infoscreen
src/Shared/Utils/Extensions/IEnumerableExtensions.cs
C#
mit
2,269
/** * Adds a new plugin to plugin.json, based on user prompts */ (function(){ var fs = require("fs"), inquirer = require("inquirer"), chalk = require("chalk"), plugins = require("../plugins.json"), banner = require("./banner.js"), tags = require("./tags.js")(), tagChoices = tags.getTags().map(function(tag){ return { name: tag }; }), questions = [ { type: "input", name: "name", message: "What is the name of your postcss plugin?", validate: function( providedName ){ if( providedName.length < 1 ){ return "Please provide an actual name for your plugin." } var exists = plugins.filter(function( plugin ){ return plugin.name === providedName; }).length; if( exists ) { return "This plugin has already been added to the list."; } if( providedName.indexOf("postcss-") === -1 ){ console.log( chalk.red("\nFYI: Plugin names usually start with 'postcss-' so they can easily be found on NPM.") ); } return true; } },{ type: "input", name: "description", message: "Describe your plugin by finishing this sentence:\nPostCSS plugin...", default: "eg: \"...that transforms your CSS.\"" },{ type: "input", name: "url", message: "What is the GitHub URL for your plugin?", validate: function( providedName ){ if( providedName.indexOf("https://github.com/") > -1 ) return true; else return "Please provide a valid GitHub URL"; } },{ type: "checkbox", name: "tags", message: "Choose at least one tag that describes your plugin.\nFor descriptions of the tags, please see the list in full:\nhttps://github.com/himynameisdave/postcss-plugins/blob/master/docs/tags.md", choices: tagChoices, validate: function( answer ) { if ( answer.length < 1 ) { return "You must choose at least one tag."; } return true; } } ]; // START DA SCRIPT // 1. Hello console.log( banner ); // 2. Da Questions inquirer.prompt( questions, function(answers){ console.log( chalk.yellow("Adding a postcss plugin with the following properties:") ); console.log( chalk.cyan("name:\n ")+chalk.green(answers.name) ); console.log( chalk.cyan("description:\n ")+chalk.green(answers.description) ); console.log( chalk.cyan("url:\n ")+chalk.green(answers.url) ); console.log( chalk.cyan("tags:") ); answers.tags.forEach(function( tag ){ console.log( chalk.green(" - "+tag) ); }); // sets the author here var newPlug = answers; newPlug.author = newPlug.url.split("/")[3]; // push the new plugin right on there because it's formatted 👌👌👌 plugins.push( newPlug ) // write the plugins.json fs.writeFile( "plugins.json", JSON.stringify( plugins, null, 2 ), function(err){ if(err) throw err; console.log("Added the new plugin to plugins.json!"); require("./versionBump.js")(answers); }); }); })();
admdh/postcss-plugins
scripts/addNewPlugin.js
JavaScript
mit
3,398
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using Azure.Core.TestFramework; using NUnit.Framework; using Azure.Data.Tables.Tests; using System.Net; namespace Azure.Data.Tables.Samples { public partial class TablesSamples : TablesTestEnvironment { [Test] public void CreateTableConflict() { string tableName = "OfficeSupplies"; string connectionString = $"DefaultEndpointsProtocol=https;AccountName={StorageAccountName};AccountKey={PrimaryStorageAccountKey};EndpointSuffix={StorageEndpointSuffix ?? DefaultStorageSuffix}"; #region Snippet:CreateDuplicateTable // Construct a new TableClient using a connection string. var client = new TableClient( connectionString, tableName); // Create the table if it doesn't already exist. client.CreateIfNotExists(); // Now attempt to create the same table unconditionally. try { client.Create(); } catch (RequestFailedException ex) when (ex.Status == (int)HttpStatusCode.Conflict) { Console.WriteLine(ex.ToString()); } #endregion } } }
Azure/azure-sdk-for-net
sdk/tables/Azure.Data.Tables/tests/samples/Sample7_Troubleshooting.cs
C#
mit
1,336
import java.util.List; class BuilderSingularNoAuto { private List<String> things; private List<String> widgets; private List<String> items; @java.beans.ConstructorProperties({"things", "widgets", "items"}) @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularNoAuto(final List<String> things, final List<String> widgets, final List<String> items) { this.things = things; this.widgets = widgets; this.items = items; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public static class BuilderSingularNoAutoBuilder { @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private java.util.ArrayList<String> things; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private java.util.ArrayList<String> widgets; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") private java.util.ArrayList<String> items; @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") BuilderSingularNoAutoBuilder() { } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularNoAutoBuilder things(final String things) { if (this.things == null) this.things = new java.util.ArrayList<String>(); this.things.add(things); return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularNoAutoBuilder things(final java.util.Collection<? extends String> things) { if (this.things == null) this.things = new java.util.ArrayList<String>(); this.things.addAll(things); return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularNoAutoBuilder clearThings() { if (this.things != null) this.things.clear(); return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularNoAutoBuilder widget(final String widget) { if (this.widgets == null) this.widgets = new java.util.ArrayList<String>(); this.widgets.add(widget); return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularNoAutoBuilder widgets(final java.util.Collection<? extends String> widgets) { if (this.widgets == null) this.widgets = new java.util.ArrayList<String>(); this.widgets.addAll(widgets); return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularNoAutoBuilder clearWidgets() { if (this.widgets != null) this.widgets.clear(); return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularNoAutoBuilder items(final String items) { if (this.items == null) this.items = new java.util.ArrayList<String>(); this.items.add(items); return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularNoAutoBuilder items(final java.util.Collection<? extends String> items) { if (this.items == null) this.items = new java.util.ArrayList<String>(); this.items.addAll(items); return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularNoAutoBuilder clearItems() { if (this.items != null) this.items.clear(); return this; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public BuilderSingularNoAuto build() { java.util.List<String> things; switch (this.things == null ? 0 : this.things.size()) { case 0: things = java.util.Collections.emptyList(); break; case 1: things = java.util.Collections.singletonList(this.things.get(0)); break; default: things = java.util.Collections.unmodifiableList(new java.util.ArrayList<String>(this.things)); } java.util.List<String> widgets; switch (this.widgets == null ? 0 : this.widgets.size()) { case 0: widgets = java.util.Collections.emptyList(); break; case 1: widgets = java.util.Collections.singletonList(this.widgets.get(0)); break; default: widgets = java.util.Collections.unmodifiableList(new java.util.ArrayList<String>(this.widgets)); } java.util.List<String> items; switch (this.items == null ? 0 : this.items.size()) { case 0: items = java.util.Collections.emptyList(); break; case 1: items = java.util.Collections.singletonList(this.items.get(0)); break; default: items = java.util.Collections.unmodifiableList(new java.util.ArrayList<String>(this.items)); } return new BuilderSingularNoAuto(things, widgets, items); } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public java.lang.String toString() { return "BuilderSingularNoAuto.BuilderSingularNoAutoBuilder(things=" + this.things + ", widgets=" + this.widgets + ", items=" + this.items + ")"; } } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public static BuilderSingularNoAutoBuilder builder() { return new BuilderSingularNoAutoBuilder(); } }
openlegacy/lombok
test/transform/resource/after-delombok/BuilderSingularNoAuto.java
Java
mit
5,179
$(function() { /* We're going to use these elements a lot, so let's save references to them * here. All of these elements are already created by the HTML code produced * by the items page. */ var $orderPanel = $('#order-panel'); var $orderPanelCloseButton = $('#order-panel-close-button'); var $itemName = $('#item-name'); var $itemDescription = $('#item-description'); var $itemQuantity = $('#item-quantity-input'); var $itemId = $('#item-id-input'); /* Show or hide the side panel. We do this by animating its `left` CSS * property, causing it to slide off screen with a negative value when * we want to hide it. */ var togglePanel = function(show) { $orderPanel.animate({ right: show ? 0 : -$orderPanel.outerWidth()}); }; /* A function to show an alert box at the top of the page. */ var showAlert = function(message, type) { /* This stuctured mess of code creates a Bootstrap-style alert box. * Note the use of chainable jQuery methods. */ var $alert = ( $('<div>') // create a <div> element .text(message) // set its text .addClass('alert') // add some CSS classes and attributes .addClass('alert-' + type) .addClass('alert-dismissible') .attr('role', 'alert') .prepend( // prepend a close button to the inner HTML $('<button>') // create a <button> element .attr('type', 'button') // and so on... .addClass('close') .attr('data-dismiss', 'alert') .html('&times;') // &times; is code for the x-symbol ) .hide() // initially hide the alert so it will slide into view ); /* Add the alert to the alert container. */ $('#alerts').append($alert); /* Slide the alert into view with an animation. */ $alert.slideDown(); }; /* Close the panel when the close button is clicked. */ $('#order-panel-close-button').click(function() { togglePanel(false); }); /* Whenever an element with class `item-link` is clicked, copy over the item * information to the side panel, then show the side panel. */ $('.item-link').click(function(event) { // Prevent default link navigation event.preventDefault(); var $this = $(this); $itemName.text($this.find('.item-name').text()); $itemDescription.text($this.find('.item-description').text()); $itemId.val($this.attr('data-id')); togglePanel(true); }); /* A boring detail but an important one. When the size of the window changes, * update the `left` property of the side menu so that it remains fully * hidden. */ $(window).resize(function() { if($orderPanel.offset().right < 0) { $orderPanel.offset({ right: -$orderPanel.outerWidth() }); } }); /* When the form is submitted (button is pressed or enter key is pressed), * make the Ajax call to add the item to the current order. */ $('#item-add-form').submit(function(event) { // Prevent default form submission event.preventDefault(); /* No input validation... yet. */ var quantity = $itemQuantity.val(); //get orderid var orderID; $.ajax({ type: 'PUT', url: '/orders/', contentType: 'application/json', data:JSON.stringify({ userID: 1 }), async: false, dataType: 'json' }).done(function(data) { orderID = data.orderID //showAlert('Order created successfully', 'success'); }).fail(function() { showAlert('Fail to get orderID', 'danger'); }); /* Send the data to `PUT /orders/:orderid/items/:itemid`. */ $.ajax({ /* The HTTP method. */ type: 'PUT', /* The URL. Use a dummy order ID for now. */ url: '/orders/'+orderID+'/items/' + $itemId.val(), /* The `Content-Type` header. This tells the server what format the body * of our request is in. This sets the header as * `Content-Type: application/json`. */ contentType: 'application/json', /* The request body. `JSON.stringify` formats it as JSON. */ data: JSON.stringify({ quantity: quantity }), /* The `Accept` header. This tells the server that we want to receive * JSON. This sets the header as something like * `Accept: application/json`. */ dataType: 'json' }).done(function() { /* This is called if and when the server responds with a 2XX (success) * status code. */ /* Show a success message. */ showAlert('Posted the order with id ' + orderID, 'success'); /* Close the side panel while we're at it. */ togglePanel(false); }).fail(function() { showAlert('Something went wrong.', 'danger'); }); }); });
zyz29/yzhou9-webapps
hw4/api/js/items.js
JavaScript
mit
4,719
class CreateRubygems < ActiveRecord::Migration def self.up create_table :rubygems do |t| t.string :name t.timestamps end end def self.down drop_table :rubygems end end
jodosha/minegems
db/migrate/20110125112540_create_rubygems.rb
Ruby
mit
202
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateSaranasTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('saranas', function (Blueprint $table) { $table->increments('id'); $table->integer('timeline_id')->unsigned(); $table->integer('latar_belakang_id')->unsigned(); $table->integer('evaluasi_id')->unsigned(); $table->text('tempat'); $table->text('kerjasama'); $table->string('doc_kerjasama'); $table->string('doc_anggaran'); $table->string('doc_resiko'); $table->string('doc_tor'); $table->string('doc_laporan'); $table->string('doc_evaluasi'); $table->string('doc_absensi'); $table->timestamps(); $table->foreign('timeline_id')->references('id')->on('timelines') ->onUpdate('cascade') ->onDelete('restrict'); $table->foreign('latar_belakang_id')->references('id')->on('latar_belakangs') ->onUpdate('cascade') ->onDelete('restrict'); $table->foreign('evaluasi_id')->references('id')->on('evaluasis') ->onUpdate('cascade') ->onDelete('restrict'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('saranas'); } }
danangistu/webcsr
database/migrations/2017_05_03_001059_create_saranas_table.php
PHP
mit
1,621
// @flow /* eslint-disable react/no-danger */ // $FlowMeteor import { find, propEq } from "ramda"; import { Link } from "react-router"; import Split, { Left, Right, } from "../../../components/@primitives/layout/split"; import Meta from "../../../components/shared/meta"; import AddToCart from "../../../components/giving/add-to-cart"; type ILayout = { account: Object, }; const Layout = ({ account }: ILayout) => ( <div> <Split nav classes={["background--light-primary"]}> <Meta title={account.name} description={account.summary} image={ account.images ? find(propEq("fileLabel", "2:1"), account.images).cloudfront : account.image } meta={[{ property: "og:type", content: "article" }]} /> <Right background={ account.images ? find(propEq("fileLabel", "2:1"), account.images).cloudfront : account.image } mobile /> <Right background={ account.images ? find(propEq("fileLabel", "2:1"), account.images).cloudfront : account.image } mobile={false} /> </Split> <Left scroll classes={["background--light-primary"]}> <Link to="/give/now" className={ "locked-top locked-left soft-double@lap-and-up soft " + "h7 text-dark-secondary plain visuallyhidden@handheld" } > <i className="icon-arrow-back soft-half-right display-inline-block" style={{ verticalAlign: "middle" }} /> <span className="display-inline-block" style={{ verticalAlign: "middle", marginTop: "5px" }} > Back </span> </Link> <div className="soft@lap-and-up soft-double-top@lap-and-up"> <div className="soft soft-double-bottom soft-double-top@lap-and-up"> <h2>{account.name}</h2> <div dangerouslySetInnerHTML={{ __html: account.description }} /> </div> </div> <div className="background--light-secondary"> <div className="constrain-copy soft-double@lap-and-up"> <div className="soft soft-double-bottom soft-double-top@lap-and-up"> <AddToCart accounts={[account]} donate /> </div> </div> </div> </Left> </div> ); export default Layout;
NewSpring/apollos-core
imports/pages/give/campaign/Layout.js
JavaScript
mit
2,414
'use strict'; import { Location } from '../../src/models/location'; describe('Location', () => { let mockLocation: Location = new Location({ "id": 178, "timestamp": "2018-04-09T16:17:26.464000-07:00", "target": "d--0000-0000-0000-0532", "lat": "37.406246", "lon": "-122.109423", "user": "kaylie" }); it('checks basic', () => { expect(mockLocation.target).toBe("d--0000-0000-0000-0532"); expect(mockLocation.timestamp).toEqual("2018-04-09T16:17:26.464000-07:00"); expect(mockLocation.lat).toBe("37.406246"); expect(mockLocation.lon).toBe("-122.109423"); expect(mockLocation.getPosition()).toEqual({ lat: 37.406246, lng: -122.109423 }); }); });
iotile/ng-iotile-cloud
tests/models/locations.spec.ts
TypeScript
mit
700
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel // // 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. using System; using SharpDX.Mathematics; using SharpDX.Toolkit.Graphics; namespace SharpDX.Toolkit { /// <summary> /// A GameSystem that allows to draw to another window or control. Currently only valid on desktop with Windows.Forms. /// </summary> public class GameWindowRenderer : GameSystem { private PixelFormat preferredBackBufferFormat; private int preferredBackBufferHeight; private int preferredBackBufferWidth; private DepthFormat preferredDepthStencilFormat; private bool isBackBufferToResize; private GraphicsPresenter savedPresenter; private ViewportF savedViewport; private bool beginDrawOk; private bool windowUserResized; /// <summary> /// Initializes a new instance of the <see cref="GameWindowRenderer" /> class. /// </summary> /// <param name="registry">The registry.</param> /// <param name="gameContext">The window context.</param> public GameWindowRenderer(IServiceRegistry registry, GameContext gameContext = null) : base(registry) { GameContext = gameContext ?? new GameContext(); } /// <summary> /// Initializes a new instance of the <see cref="GameWindowRenderer" /> class. /// </summary> /// <param name="game">The game.</param> /// <param name="gameContext">The window context.</param> public GameWindowRenderer(Game game, GameContext gameContext = null) : base(game) { GameContext = gameContext ?? new GameContext(); } /// <summary> /// Gets the underlying native window. /// </summary> /// <value>The underlying native window.</value> public GameContext GameContext { get; private set; } /// <summary> /// Gets the window. /// </summary> /// <value>The window.</value> public GameWindow Window { get; private set; } /// <summary> /// Gets or sets the presenter. /// </summary> /// <value>The presenter.</value> public GraphicsPresenter Presenter { get; protected set; } /// <summary> /// Gets or sets the preferred back buffer format. /// </summary> /// <value>The preferred back buffer format.</value> public PixelFormat PreferredBackBufferFormat { get { return preferredBackBufferFormat; } set { if (preferredBackBufferFormat != value) { preferredBackBufferFormat = value; isBackBufferToResize = true; } } } /// <summary> /// Gets or sets the height of the preferred back buffer. /// </summary> /// <value>The height of the preferred back buffer.</value> public int PreferredBackBufferHeight { get { return preferredBackBufferHeight; } set { if (preferredBackBufferHeight != value) { preferredBackBufferHeight = value; isBackBufferToResize = true; } } } /// <summary> /// Gets or sets the width of the preferred back buffer. /// </summary> /// <value>The width of the preferred back buffer.</value> public int PreferredBackBufferWidth { get { return preferredBackBufferWidth; } set { if (preferredBackBufferWidth != value) { preferredBackBufferWidth = value; isBackBufferToResize = true; } } } /// <summary> /// Gets or sets the preferred depth stencil format. /// </summary> /// <value>The preferred depth stencil format.</value> public DepthFormat PreferredDepthStencilFormat { get { return preferredDepthStencilFormat; } set { preferredDepthStencilFormat = value; } } public override void Initialize() { var gamePlatform = (IGamePlatform)this.Services.GetService(typeof(IGamePlatform)); GameContext.RequestedWidth = PreferredBackBufferWidth; GameContext.RequestedHeight = PreferredBackBufferHeight; Window = gamePlatform.CreateWindow(GameContext); Window.Visible = true; Window.ClientSizeChanged += WindowOnClientSizeChanged; base.Initialize(); } private Size2 GetRequestedSize(out PixelFormat format) { var bounds = Window.ClientBounds; format = PreferredBackBufferFormat == PixelFormat.Unknown ? PixelFormat.R8G8B8A8.UNorm : PreferredBackBufferFormat; return new Size2( PreferredBackBufferWidth == 0 || windowUserResized ? bounds.Width : PreferredBackBufferWidth, PreferredBackBufferHeight == 0 || windowUserResized ? bounds.Height : PreferredBackBufferHeight); } protected virtual void CreateOrUpdatePresenter() { if (Presenter == null) { PixelFormat resizeFormat; var size = GetRequestedSize(out resizeFormat); var presentationParameters = new PresentationParameters(size.Width, size.Height, Window.NativeWindow, resizeFormat) { DepthStencilFormat = PreferredDepthStencilFormat }; presentationParameters.PresentationInterval = PresentInterval.One; Presenter = new SwapChainGraphicsPresenter(GraphicsDevice, presentationParameters); isBackBufferToResize = false; } } public override bool BeginDraw() { if (GraphicsDevice != null && Window.Visible) { savedPresenter = GraphicsDevice.Presenter; savedViewport = GraphicsDevice.Viewport; CreateOrUpdatePresenter(); if (isBackBufferToResize || windowUserResized) { PixelFormat resizeFormat; var size = GetRequestedSize(out resizeFormat); Presenter.Resize(size.Width, size.Height, resizeFormat); isBackBufferToResize = false; windowUserResized = false; } GraphicsDevice.Presenter = Presenter; GraphicsDevice.SetViewport(Presenter.DefaultViewport); GraphicsDevice.SetRenderTargets(Presenter.DepthStencilBuffer, Presenter.BackBuffer); beginDrawOk = true; return true; } beginDrawOk = false; return false; } public override void EndDraw() { if (beginDrawOk && GraphicsDevice != null) { try { Presenter.Present(); } catch (SharpDXException ex) { // If this is not a DeviceRemoved or DeviceReset, than throw an exception if (ex.ResultCode != DXGI.ResultCode.DeviceRemoved && ex.ResultCode != DXGI.ResultCode.DeviceReset) { throw; } } if (savedPresenter != null) { GraphicsDevice.Presenter = savedPresenter; GraphicsDevice.SetRenderTargets(savedPresenter.DepthStencilBuffer, savedPresenter.BackBuffer); GraphicsDevice.SetViewport(savedViewport); } } } private void WindowOnClientSizeChanged(object sender, EventArgs eventArgs) { windowUserResized = true; } } }
sharpdx/Toolkit
Source/Toolkit/SharpDX.Toolkit.Game/GameWindowRenderer.cs
C#
mit
9,287
# frozen_string_literal: true require 'spec_helper' describe Tsubaki::MyNumber do describe '.rand' do it 'generates valid random my number' do n = Tsubaki::MyNumber.rand expect(Tsubaki::MyNumber.new(n, strict: true).valid?).to be_truthy end end describe '.calc_check_digit' do context 'given invalid digits' do [ nil, '12345678901X', '5678-1111-9018' ].each do |n| describe n.to_s do it 'raises RuntimeError' do expect { Tsubaki::MyNumber.calc_check_digit(n) }.to raise_error(RuntimeError) end end end end context 'given valid digits' do subject { Tsubaki::MyNumber.calc_check_digit(digits) } describe '37296774233' do let(:digits) { '37296774233' } it { is_expected.to eq 8 } end describe '29217589598' do let(:digits) { '29217589598' } it { is_expected.to eq 2 } end end end describe '#valid?' do subject { Tsubaki::MyNumber.new(digits, options).valid? } context 'when digits no options are specified' do let(:options) { {} } context 'given the valid my numbers' do %w[ 123456789012 987654321098 112233445566 ].each do |n| describe n.to_s do let(:digits) { n } it { is_expected.to be_truthy } end end end context 'given the invalid my numbers' do [ nil, '12345678901X', '5678-1111-9018' ].each do |n| describe n.to_s do let(:digits) { n } it { is_expected.to be_falsy } end end end end context 'when digits contains divider & not strict mode' do let(:options) { { divider: '-', strict: false } } context 'given the valid my numbers' do %w[ 123456789012 9876-5432-1098 112233--445566 ].each do |n| describe n.to_s do let(:digits) { n } it { is_expected.to be_truthy } end end end context 'given the invalid my numbers' do [ nil, '0234-5678-XXXX', '5678-9018' ].each do |n| describe n.to_s do let(:digits) { n } it { is_expected.to be_falsy } end end end end context 'when digits contains divider & strict mode' do let(:options) { { divider: '-', strict: true } } context 'given the valid my numbers' do %w[ 873321641958 2633-4829-1158 491131--223718 ].each do |n| describe n.to_s do let(:digits) { n } it { is_expected.to be_truthy } end end end context 'given the invalid my numbers' do [ nil, '0234-5678-XXXX', '5678-9018', '123456789012', '9876-5432-1098', '112233--445566' ].each do |n| describe n.to_s do let(:digits) { n } it { is_expected.to be_falsy } end end end end end describe '#valid_pattern?' do subject { Tsubaki::MyNumber.new(digits, {}).valid_pattern? } context 'given the valid pattern my numbers' do %w[ 023456789013 123456789018 333333333333 ].each do |n| describe n.to_s do let(:digits) { n } it 'should be valid' do is_expected.to be_truthy end end end end context 'given the invalid my numbers' do %w[ 12345678901 12345678901X 1234567890123 ].each do |n| describe n.to_s do let(:digits) { n } it 'should be invalid' do is_expected.to be_falsy end end end end end describe '#valid_check_digit?' do subject { Tsubaki::MyNumber.new(digits, {}).valid_check_digit? } context 'given the valid my numbers' do %w[ 185672239885 176521275740 654629853731 ].each do |n| describe n.to_s do let(:digits) { n } it 'should be valid' do is_expected.to be_truthy end end end end context 'given the invalid my numbers' do %w[ 185672239886 176521275741 654629853732 ].each do |n| describe n.to_s do let(:digits) { n } it 'should be invalid' do is_expected.to be_falsy end end end end end end
kakipo/tsubaki
spec/tsubaki/my_number_spec.rb
Ruby
mit
4,714
module Serve #:nodoc: # Many of the methods here have been extracted in some form from Rails module EscapeHelpers HTML_ESCAPE = { '&' => '&amp;', '>' => '&gt;', '<' => '&lt;', '"' => '&quot;' } JSON_ESCAPE = { '&' => '\u0026', '>' => '\u003E', '<' => '\u003C' } # A utility method for escaping HTML tag characters. # This method is also aliased as <tt>h</tt>. # # In your ERb templates, use this method to escape any unsafe content. For example: # <%=h @person.name %> # # ==== Example: # puts html_escape("is a > 0 & a < 10?") # # => is a &gt; 0 &amp; a &lt; 10? def html_escape(s) s.to_s.gsub(/[&"><]/) { |special| HTML_ESCAPE[special] } end alias h html_escape # A utility method for escaping HTML entities in JSON strings. # This method is also aliased as <tt>j</tt>. # # In your ERb templates, use this method to escape any HTML entities: # <%=j @person.to_json %> # # ==== Example: # puts json_escape("is a > 0 & a < 10?") # # => is a \u003E 0 \u0026 a \u003C 10? def json_escape(s) s.to_s.gsub(/[&"><]/) { |special| JSON_ESCAPE[special] } end alias j json_escape end module ContentHelpers def content_for(symbol, content = nil, &block) content = capture(&block) if block_given? set_content_for(symbol, content) if content get_content_for(symbol) unless content end def content_for?(symbol) !(get_content_for(symbol)).nil? end def get_content_for(symbol = :content) if symbol.to_s.intern == :content @content else instance_variable_get("@content_for_#{symbol}") end end def set_content_for(symbol, value) instance_variable_set("@content_for_#{symbol}", value) end def capture_erb(&block) buffer = "" old_buffer, @_out_buf = @_out_buf, buffer yield buffer ensure @_out_buf = old_buffer end alias capture_rhtml capture_erb alias capture_erubis capture_erb def capture(&block) capture_method = "capture_#{script_extension}" if respond_to? capture_method send capture_method, &block else raise "Capture not supported for `#{script_extension}' template (#{engine_name})" end end private def engine_name Tilt[script_extension].to_s end def script_extension parser.script_extension end end module FlashHelpers def flash @flash ||= {} end end module ParamHelpers # Key based access to query parameters. Keys can be strings or symbols. def params @params ||= request.params end # Extract the value for a bool param. Handy for rendering templates in # different states. def boolean_param(key, default = false) key = key.to_s.intern value = params[key] return default if value.blank? case value.strip.downcase when 'true', '1' then true when 'false', '0' then false else raise 'Invalid value' end end end module RenderHelpers def render(partial, options={}) if partial.is_a?(Hash) options = options.merge(partial) partial = options.delete(:partial) end template = options.delete(:template) case when partial render_partial(partial, options) when template render_template(template) else raise "render options not supported #{options.inspect}" end end def render_partial(partial, options={}) render_template(partial, options.merge(partial: true)) end def render_template(template, options={}) path = parser.template_path if template =~ %r{^/} template = template[1..-1] path = @root_path end filename = template_filename(path, template, partial: options[:partial]) if filename && File.file?(filename) parser.parse(File.read(filename), File.extname(filename).split(".").last, options[:locals]) else raise "File does not exist #{filename.inspect}" end end private def template_filename(path, template, options) template_path = File.dirname(template) template_file = File.basename(template) template_file = "_" + template_file if options[:partial] route = Serve::Router.resolve(path, File.join(template_path, template_file)) (route && File.join(path, route)) end def extname(filename) /(\.[a-z]+\.[a-z]+)$/.match(filename) $1 || File.extname(filename) || '' end end module TagHelpers def content_tag(name, content, html_options={}) %{<#{name}#{html_attributes(html_options)}>#{content}</#{name}>} end def tag(name, html_options={}) %{<#{name}#{html_attributes(html_options)} />} end def image_tag(src, html_options = {}) tag(:img, html_options.merge({src: src})) end def image(name, options = {}) image_tag(ensure_path(ensure_extension(name, 'png'), 'images'), options) end def javascript_tag(content = nil, html_options = {}) content_tag(:script, javascript_cdata_section(content), html_options.merge(type: "text/javascript")) end def link_to(name, href, html_options = {}) html_options = html_options.stringify_keys confirm = html_options.delete("confirm") onclick = "if (!confirm('#{html_escape(confirm)}')) return false;" if confirm content_tag(:a, name, html_options.merge(href: href, onclick: onclick)) end def link_to_function(name, *args, &block) html_options = extract_options!(args) function = args[0] || '' onclick = "#{"#{html_options[:onclick]}; " if html_options[:onclick]}#{function}; return false;" href = html_options[:href] || '#' content_tag(:a, name, html_options.merge(href: href, onclick: onclick)) end def mail_to(email_address, name = nil, html_options = {}) html_options = html_options.stringify_keys encode = html_options.delete("encode").to_s cc, bcc, subject, body = html_options.delete("cc"), html_options.delete("bcc"), html_options.delete("subject"), html_options.delete("body") string = '' extras = '' extras << "cc=#{CGI.escape(cc).gsub("+", "%20")}&" unless cc.nil? extras << "bcc=#{CGI.escape(bcc).gsub("+", "%20")}&" unless bcc.nil? extras << "body=#{CGI.escape(body).gsub("+", "%20")}&" unless body.nil? extras << "subject=#{CGI.escape(subject).gsub("+", "%20")}&" unless subject.nil? extras = "?" << extras.gsub!(/&?$/,"") unless extras.empty? email_address = email_address.to_s email_address_obfuscated = email_address.dup email_address_obfuscated.gsub!(/@/, html_options.delete("replace_at")) if html_options.has_key?("replace_at") email_address_obfuscated.gsub!(/\./, html_options.delete("replace_dot")) if html_options.has_key?("replace_dot") if encode == "javascript" "document.write('#{content_tag("a", name || email_address_obfuscated, html_options.merge({ "href" => "mailto:"+email_address+extras }))}');".each_byte do |c| string << sprintf("%%%x", c) end "<script type=\"#{Mime::JS}\">eval(decodeURIComponent('#{string}'))</script>" elsif encode == "hex" email_address_encoded = '' email_address_obfuscated.each_byte do |c| email_address_encoded << sprintf("&#%d;", c) end protocol = 'mailto:' protocol.each_byte { |c| string << sprintf("&#%d;", c) } email_address.each_byte do |c| char = c.chr string << (char =~ /\w/ ? sprintf("%%%x", c) : char) end content_tag "a", name || email_address_encoded, html_options.merge({ "href" => "#{string}#{extras}" }) else content_tag "a", name || email_address_obfuscated, html_options.merge({ "href" => "mailto:#{email_address}#{extras}" }) end end # Generates JavaScript script tags for the sources given as arguments. # # If the .js extension is not given, it will be appended to the source. # # Examples # javascript_include_tag 'application' # => # <script src="/javascripts/application.js" type="text/javascript" /> # # javascript_include_tag 'https://cdn/jquery.js' # => # <script src="https://cdn/jquery.js" type="text/javascript" /> # # javascript_include_tag 'application', 'books' # => # <script src="/javascripts/application.js" type="text/javascript" /> # <script src="/javascripts/books.js" type="text/javascript" /> # def javascript_include_tag(*sources) options = extract_options!(sources) sources.map do |source| content_tag('script', '', { 'type' => 'text/javascript', 'src' => ensure_path(ensure_extension(source, 'js'), 'javascripts') }.merge(options)) end.join("\n") end # Generates stylesheet link tags for the sources given as arguments. # # If the .css extension is not given, it will be appended to the source. # # Examples # stylesheet_link_tag 'screen' # => # <link href="/stylesheets/screen.css" media="screen" rel="stylesheet" type="text/css" /> # # stylesheet_link_tag 'print', :media => 'print' # => # <link href="/stylesheets/print.css" media="print" rel="stylesheet" type="text/css" /> # # stylesheet_link_tag 'application', 'books', 'authors' # => # <link href="/stylesheets/application.css" media="screen" rel="stylesheet" type="text/css" /> # <link href="/stylesheets/books.css" media="screen" rel="stylesheet" type="text/css" /> # <link href="/stylesheets/authors.css" media="screen" rel="stylesheet" type="text/css" /> # def stylesheet_link_tag(*sources) options = extract_options!(sources) sources.map do |source| tag('link', { 'rel' => 'stylesheet', 'type' => 'text/css', 'media' => 'screen', 'href' => ensure_path(ensure_extension(source, 'css'), 'stylesheets') }.merge(options)) end.join("\n") end private def cdata_section(content) "<![CDATA[#{content}]]>" end def javascript_cdata_section(content) #:nodoc: "\n//#{cdata_section("\n#{content}\n//")}\n" end def html_attributes(options) unless options.blank? attrs = [] options.each_pair do |key, value| if value == true attrs << %(#{key}="#{key}") if value else attrs << %(#{key}="#{value}") unless value.nil? end end " #{attrs.sort * ' '}" unless attrs.empty? end end # Ensures a proper extension is appended to the filename. # # If a URI with the http or https scheme name is given, it is assumed # to be absolute and will not be altered. # # Examples # ensure_extension('screen', 'css') => 'screen.css' # ensure_extension('screen.css', 'css') => 'screen.css' # ensure_extension('jquery.min', 'js') => 'jquery.min.js' # ensure_extension('https://cdn/jquery', 'js') => 'https://cdn/jquery' # def ensure_extension(source, extension) if source =~ /^https?:/ || source.end_with?(".#{extension}") return source end "#{source}.#{extension}" end # Ensures the proper path to the given source. # # If the source begins at the root of the public directory or is a URI # with the http or https scheme name, it is assumed to be absolute and # will not be altered. # # Examples # ensure_path('screen.css', 'stylesheets') => '/stylesheets/screen.css' # ensure_path('/screen.css', 'stylesheets') => '/screen.css' # ensure_path('http://cdn/jquery.js', 'javascripts') => 'http://cdn/jquery.js' # def ensure_path(source, path) if source =~ /^(\/|https?)/ return source end File.join('', path, source) end # Returns a hash of options if they exist at the end of an array. # # This is useful when working with splats. # # Examples # extract_options!([1, 2, { :name => 'sunny' }]) => { :name => 'sunny' } # extract_options!([1, 2, 3]) => {} # def extract_options!(array) array.last.instance_of?(Hash) ? array.pop : {} end end module ViewHelpers #:nodoc: include EscapeHelpers include ContentHelpers include FlashHelpers include ParamHelpers include RenderHelpers include TagHelpers end end
tka/serve
lib/serve/view_helpers.rb
Ruby
mit
12,835
// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package gcexportdata provides functions for locating, reading, and // writing export data files containing type information produced by the // gc compiler. This package supports go1.7 export data format and all // later versions. // // Although it might seem convenient for this package to live alongside // go/types in the standard library, this would cause version skew // problems for developer tools that use it, since they must be able to // consume the outputs of the gc compiler both before and after a Go // update such as from Go 1.7 to Go 1.8. Because this package lives in // golang.org/x/tools, sites can update their version of this repo some // time before the Go 1.8 release and rebuild and redeploy their // developer tools, which will then be able to consume both Go 1.7 and // Go 1.8 export data files, so they will work before and after the // Go update. (See discussion at https://github.com/golang/go/issues/15651.) // package gcexportdata // import "golang.org/x/tools/go/gcexportdata" import ( "bufio" "bytes" "fmt" "go/token" "go/types" "io" "io/ioutil" "golang.org/x/tools/go/internal/gcimporter" ) // Find returns the name of an object (.o) or archive (.a) file // containing type information for the specified import path, // using the workspace layout conventions of go/build. // If no file was found, an empty filename is returned. // // A relative srcDir is interpreted relative to the current working directory. // // Find also returns the package's resolved (canonical) import path, // reflecting the effects of srcDir and vendoring on importPath. func Find(importPath, srcDir string) (filename, path string) { return gcimporter.FindPkg(importPath, srcDir) } // NewReader returns a reader for the export data section of an object // (.o) or archive (.a) file read from r. The new reader may provide // additional trailing data beyond the end of the export data. func NewReader(r io.Reader) (io.Reader, error) { buf := bufio.NewReader(r) _, err := gcimporter.FindExportData(buf) // If we ever switch to a zip-like archive format with the ToC // at the end, we can return the correct portion of export data, // but for now we must return the entire rest of the file. return buf, err } // Read reads export data from in, decodes it, and returns type // information for the package. // The package name is specified by path. // File position information is added to fset. // // Read may inspect and add to the imports map to ensure that references // within the export data to other packages are consistent. The caller // must ensure that imports[path] does not exist, or exists but is // incomplete (see types.Package.Complete), and Read inserts the // resulting package into this map entry. // // On return, the state of the reader is undefined. func Read(in io.Reader, fset *token.FileSet, imports map[string]*types.Package, path string) (*types.Package, error) { data, err := ioutil.ReadAll(in) if err != nil { return nil, fmt.Errorf("reading export data for %q: %v", path, err) } if bytes.HasPrefix(data, []byte("!<arch>")) { return nil, fmt.Errorf("can't read export data for %q directly from an archive file (call gcexportdata.NewReader first to extract export data)", path) } // The App Engine Go runtime v1.6 uses the old export data format. // TODO(adonovan): delete once v1.7 has been around for a while. if bytes.HasPrefix(data, []byte("package ")) { return gcimporter.ImportData(imports, path, path, bytes.NewReader(data)) } _, pkg, err := gcimporter.BImportData(fset, imports, data, path) return pkg, err } // Write writes encoded type information for the specified package to out. // The FileSet provides file position information for named objects. func Write(out io.Writer, fset *token.FileSet, pkg *types.Package) error { _, err := out.Write(gcimporter.BExportData(fset, pkg)) return err }
johanbrandhorst/protobuf
vendor/golang.org/x/tools/go/gcexportdata/gcexportdata.go
GO
mit
4,046
import { Simple } from '@glimmer/interfaces'; import { DirtyableTag, Tag, TagWrapper, VersionedPathReference } from '@glimmer/reference'; import { Opaque, Option } from '@glimmer/util'; import { environment } from 'ember-environment'; import { run } from 'ember-metal'; import { assign, OWNER } from 'ember-utils'; import { Renderer } from '../renderer'; import { Container, OwnedTemplate } from '../template'; export class RootOutletStateReference implements VersionedPathReference<Option<OutletState>> { tag: Tag; constructor(public outletView: OutletView) { this.tag = outletView._tag; } get(key: string): VersionedPathReference<any> { return new ChildOutletStateReference(this, key); } value(): Option<OutletState> { return this.outletView.outletState; } getOrphan(name: string): VersionedPathReference<Option<OutletState>> { return new OrphanedOutletStateReference(this, name); } update(state: OutletState) { this.outletView.setOutletState(state); } } // So this is a relic of the past that SHOULD go away // in 3.0. Preferably it is deprecated in the release that // follows the Glimmer release. class OrphanedOutletStateReference extends RootOutletStateReference { public root: any; public name: string; constructor(root: RootOutletStateReference, name: string) { super(root.outletView); this.root = root; this.name = name; } value(): Option<OutletState> { let rootState = this.root.value(); let orphans = rootState.outlets.main.outlets.__ember_orphans__; if (!orphans) { return null; } let matched = orphans.outlets[this.name]; if (!matched) { return null; } let state = Object.create(null); state[matched.render.outlet] = matched; matched.wasUsed = true; return { outlets: state, render: undefined }; } } class ChildOutletStateReference implements VersionedPathReference<any> { public parent: VersionedPathReference<any>; public key: string; public tag: Tag; constructor(parent: VersionedPathReference<any>, key: string) { this.parent = parent; this.key = key; this.tag = parent.tag; } get(key: string): VersionedPathReference<any> { return new ChildOutletStateReference(this, key); } value(): any { let parent = this.parent.value(); return parent && parent[this.key]; } } export interface RenderState { owner: Container | undefined; into: string | undefined; outlet: string; name: string; controller: Opaque; template: OwnedTemplate | undefined; } export interface OutletState { outlets: { [name: string]: OutletState | undefined; }; render: RenderState | undefined; } export interface BootEnvironment { hasDOM: boolean; isInteractive: boolean; options: any; } export default class OutletView { private _environment: BootEnvironment; public renderer: Renderer; public owner: Container; public template: OwnedTemplate; public outletState: Option<OutletState>; public _tag: TagWrapper<DirtyableTag>; static extend(injections: any) { return class extends OutletView { static create(options: any) { if (options) { return super.create(assign({}, injections, options)); } else { return super.create(injections); } } }; } static reopenClass(injections: any) { assign(this, injections); } static create(options: any) { let { _environment, renderer, template } = options; let owner = options[OWNER]; return new OutletView(_environment, renderer, owner, template); } constructor(_environment: BootEnvironment, renderer: Renderer, owner: Container, template: OwnedTemplate) { this._environment = _environment; this.renderer = renderer; this.owner = owner; this.template = template; this.outletState = null; this._tag = DirtyableTag.create(); } appendTo(selector: string | Simple.Element) { let env = this._environment || environment; let target; if (env.hasDOM) { target = typeof selector === 'string' ? document.querySelector(selector) : selector; } else { target = selector; } run.schedule('render', this.renderer, 'appendOutletView', this, target); } rerender() { /**/ } setOutletState(state: OutletState) { this.outletState = { outlets: { main: state, }, render: { owner: undefined, into: undefined, outlet: 'main', name: '-top-level', controller: undefined, template: undefined, }, }; this._tag.inner.dirty(); } toReference() { return new RootOutletStateReference(this); } destroy() { /**/ } }
sivakumar-kailasam/ember.js
packages/ember-glimmer/lib/views/outlet.ts
TypeScript
mit
4,703
<?php $lang['widget_rss_title'] = "Seen on... "; ?>
lostfly2/g2
themes/fundation/widgets/rss/language/en/rss_lang.php
PHP
mit
54
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M22 5.18 10.59 16.6l-4.24-4.24 1.41-1.41 2.83 2.83 10-10L22 5.18zm-2.21 5.04c.13.57.21 1.17.21 1.78 0 4.42-3.58 8-8 8s-8-3.58-8-8 3.58-8 8-8c1.58 0 3.04.46 4.28 1.25l1.44-1.44C16.1 2.67 14.13 2 12 2 6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10c0-1.19-.22-2.33-.6-3.39l-1.61 1.61z" }), 'TaskAltSharp'); exports.default = _default;
oliviertassinari/material-ui
packages/mui-icons-material/lib/TaskAltSharp.js
JavaScript
mit
749
var API_PHP ="http://devtucompass.tk/pici/BackEnd/Clases/chatAdmin.php"; var API_REST = "http://devtucompass.tk/pici/API/"; $.support.cors = true; $.mobile.allowCrossDomainPages = true; function enviarInfo(){ $("#enviarInfo").click(function(){ $.ajax({ type: "POST", url: API_PHP, data: $("#info").serialize(), // serializes the form's elements. error: function(jqXHR, textStatus, errorThrown){ console.log("hi"); console.log(jqXHR); console.log(textStatus); console.log(errorThrown); //do stuff }, cache:false }).done( function (data){ localStorage.cedula= $("#cedula").val(); $("#cedulaH").attr('value',localStorage.cedula); localStorage.useradmin = -1; $.mobile.navigate( "#chat"); sendMessage(); }); }); } function sendMessage(){ $("#send").click(function(){ $.ajax({ type: "POST", url: API_PHP, data: $("#messagechat").serialize(), // serializes the form's elements. error: function(jqXHR, textStatus, errorThrown){ alert("hi"); alert(jqXHR); alert(textStatus); alert(errorThrown); //do stuff }, cache:false }).done( function (data){ console.log("la informacion es: "+data); }); }); $("#message").val(""); } function getLogMessages() { var cedula= localStorage.cedula ; //alert("la Cedula es: "+cedula); var content = ""; $.ajax({ type: "GET", url: API_REST+"lastLogChat?cedula="+cedula, error: function(jqXHR, textStatus, errorThrown){ console.log("hi"); console.log(jqXHR); console.log(textStatus); console.log(errorThrown); //do stuff }, cache:false, format:"jsonp", crossDomain: true, async: true }).done( function (data){ $.each( data, function ( i, item ){ //alert(item.id); if(item.por ==='si'){ content+='<li data-theme="c">'+ '<a href="#">'+ '<h2>Consulta Sena PICI Dice: </h2>'+ '<p>'+item.mensaje+'</p>'+ '<p class="ui-li-aside"></p>'+ '</a>'+ '</li>'; }else{ content+='<li data-theme="e">'+ '<a href="#">'+ '<h2>Tu Dices: </h2>'+ '<p>'+item.mensaje+'</p>'+ '<p class="ui-li-aside"></p>'+ '</a>'+ '</li>'; } }); $("#logMensajes").html(content); $( "#logMensajes" ).listview( "refresh" ); }); }
estigio/pici_prueba
js/chat.js
JavaScript
mit
2,859
import { IRole } from '../../models/IRole'; export interface IServerHeaderProps { serverName: string; numberOfUsers?: string; roles: Array<IRole>; }
Acceleratio/quick-react.ts
src/components/ServerHeader/ServerHeader.Props.ts
TypeScript
mit
169
(function(jiglib) { var MaterialProperties = jiglib.MaterialProperties; var CachedImpulse = jiglib.CachedImpulse; var PhysicsState = jiglib.PhysicsState; var RigidBody = jiglib.RigidBody; var HingeJoint = jiglib.HingeJoint; var BodyPair = jiglib.BodyPair; var PhysicsSystem = jiglib.PhysicsSystem; var PhysicsController = function() { this._controllerEnabled = null; // Boolean this._controllerEnabled = false; } PhysicsController.prototype.updateController = function(dt) { } PhysicsController.prototype.enableController = function() { } PhysicsController.prototype.disableController = function() { } PhysicsController.prototype.get_controllerEnabled = function() { return this._controllerEnabled; } jiglib.PhysicsController = PhysicsController; })(jiglib);
charlieschwabacher/Walking
public/JigLibJS2/physics/PhysicsController.js
JavaScript
mit
871
/* * SameValue() (E5 Section 9.12). * * SameValue() is difficult to test indirectly. It appears in E5 Section * 8.12.9, [[DefineOwnProperty]] several times. * * One relatively simple approach is to create a non-configurable, non-writable * property, and attempt to use Object.defineProperty() to set a new value for * the property. If SameValue(oldValue,newValue), no exception is thrown. * Otherwise, reject (TypeError); see E5 Section 8.12.9, step 10.a.ii.1. */ function sameValue(x,y) { var obj = {}; try { Object.defineProperty(obj, 'test', { writable: false, enumerable: false, configurable: false, value: x }); Object.defineProperty(obj, 'test', { value: y }); } catch (e) { if (e.name === 'TypeError') { return false; } else { throw e; } } return true; } function test(x,y) { print(sameValue(x,y)); } /*=== test: different types, first undefined false false false false false false ===*/ /* Different types, first is undefined */ print('test: different types, first undefined') test(undefined, null); test(undefined, true); test(undefined, false); test(undefined, 123.0); test(undefined, 'foo'); test(undefined, {}); /*=== test: different types, first null false false false false false false ===*/ /* Different types, first is null */ print('test: different types, first null') test(null, undefined); test(null, true); test(null, false); test(null, 123.0); test(null, 'foo'); test(null, {}); /*=== test: different types, first boolean false false false false false false false false false false ===*/ /* Different types, first is boolean */ print('test: different types, first boolean') test(true, undefined); test(true, null); test(true, 123.0); test(true, 'foo'); test(true, {}); test(false, undefined); test(false, null); test(false, 123.0); test(false, 'foo'); test(false, {}); /*=== test: different types, first number false false false false false false ===*/ /* Different types, first is number */ print('test: different types, first number') test(123.0, undefined); test(123.0, null); test(123.0, true); test(123.0, false); test(123.0, 'foo'); test(123.0, {}); /*=== test: different types, first string false false false false false false ===*/ /* Different types, first is string */ print('test: different types, first string') test('foo', undefined); test('foo', null); test('foo', true); test('foo', false); test('foo', 123.0); test('foo', {}); /*=== test: different types, first object false false false false false false ===*/ /* Different types, first is object */ print('test: different types, first object') test({}, undefined); test({}, null); test({}, true); test({}, false); test({}, 123.0); test({}, 'foo'); /*=== test: same types, undefined true ===*/ /* Same types: undefined */ print('test: same types, undefined') test(undefined, undefined); /*=== test: same types, null true ===*/ /* Same types: null */ print('test: same types, null') test(null, null); /*=== test: same types, boolean true false false true ===*/ /* Same types: boolean */ print('test: same types, boolean') test(true, true); test(true, false); test(false, true); test(false, false); /*=== test: same types, number true true false false true true false false true true true ===*/ /* Same types: number */ print('test: same types, number') test(NaN, NaN); test(-0, -0); test(-0, +0); test(+0, -0); test(+0, +0); test(Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY); test(Number.NEGATIVE_INFINITY, Number.POSITIVE_INFINITY); test(Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY); test(Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY); test(-123.0, -123.0); test(123.0, 123.0); /*=== test: same types, string true false false true ===*/ /* Same types: string */ print('test: same types, string') test('', ''); test('foo', '') test('', 'foo'); test('foo', 'foo'); /*=== test: same types, object true false false true ===*/ /* Same types: object */ var obj1 = {}; var obj2 = {}; print('test: same types, object') test(obj1, obj1); test(obj1, obj2); test(obj2, obj1); test(obj2, obj2);
andoma/duktape
ecmascript-testcases/test-conv-samevalue.js
JavaScript
mit
4,217
require "spec_helper" describe "Relevance::Tarantula::HtmlReporter file output" do before do FileUtils.rm_rf(test_output_dir) FileUtils.mkdir_p(test_output_dir) @test_name = "test_user_pages" Relevance::Tarantula::Result.next_number = 0 @success_results = (1..10).map do |index| Relevance::Tarantula::Result.new( :success => true, :method => "get", :url => "/widgets/#{index}", :response => stub(:code => "200", :body => "<h1>header</h1>\n<p>text</p>"), :referrer => "/random/#{rand(100)}", :test_name => @test_name, :log => <<-END, Made-up stack trace: /some_module/some_class.rb:697:in `bad_method' /some_module/other_class.rb:12345677:in `long_method' this link should be <a href="#">escaped</a> blah blah blah END :data => "{:param1 => :value, :param2 => :another_value}" ) end @fail_results = (1..10).map do |index| Relevance::Tarantula::Result.new( :success => false, :method => "get", :url => "/widgets/#{index}", :response => stub(:code => "500", :body => "<h1>header</h1>\n<p>text</p>"), :referrer => "/random/#{rand(100)}", :test_name => @test_name, :log => <<-END, Made-up stack trace: /some_module/some_class.rb:697:in `bad_method' /some_module/other_class.rb:12345677:in `long_method' this link should be <a href="#">escaped</a> blah blah blah END :data => "{:param1 => :value, :param2 => :another_value}" ) end @index = File.join(test_output_dir, "index.html") FileUtils.rm_f @index @detail = File.join(test_output_dir, @test_name,"1.html") FileUtils.rm_f @detail end it "creates a final report based on tarantula results" do Relevance::Tarantula::Result.any_instance.stubs(:rails_root).returns("STUB_ROOT") reporter = Relevance::Tarantula::HtmlReporter.new(test_output_dir) stub_puts_and_print(reporter) (@success_results + @fail_results).each {|r| reporter.report(r)} reporter.finish_report(@test_name) File.exist?(@index).should be_true end it "creates a final report with links to detailed reports in subdirs" do Relevance::Tarantula::Result.any_instance.stubs(:rails_root).returns("STUB_ROOT") reporter = Relevance::Tarantula::HtmlReporter.new(test_output_dir) stub_puts_and_print(reporter) (@success_results + @fail_results).each {|r| reporter.report(r)} reporter.finish_report(@test_name) links = Hpricot(File.read(@index)).search('.left a') links.each do |link| link['href'].should match(/#{@test_name}\/\d+\.html/) end end it "creates detailed reports based on tarantula results" do Relevance::Tarantula::Result.any_instance.stubs(:rails_root).returns("STUB_ROOT") reporter = Relevance::Tarantula::HtmlReporter.new(test_output_dir) stub_puts_and_print(reporter) (@success_results + @fail_results).each {|r| reporter.report(r)} reporter.finish_report(@test_name) File.exist?(@detail).should be_true end end
codez/tarantula
spec/relevance/tarantula/html_reporter_spec.rb
Ruby
mit
3,088
/** * marked - a markdown parser * Copyright (c) 2011-2014, Christopher Jeffrey. (MIT Licensed) * https://github.com/chjj/marked */ (function () { var block = { newline: /^\n+/, code: /^( {4}[^\n]+\n*)+/, fences: noop, hr: /^( *[-*_]){3,} *(?:\n+|$)/, heading: /^ *(#{1,6}) *([^\n]+?) *#* *(?:\n+|$)/, nptable: noop, lheading: /^([^\n]+)\n *(=|-){2,} *(?:\n+|$)/, blockquote: /^( *>[^\n]+(\n(?!def)[^\n]+)*\n*)+/, list: /^( *)(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?!\1bull )\n*|\s*$)/, html: /^ *(?:comment|closed|closing) *(?:\n{2,}|\s*$)/, def: /^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +["(]([^\n]+)[")])? *(?:\n+|$)/, table: noop, paragraph: /^((?:[^\n]+\n?(?!hr|heading|lheading|blockquote|tag|def))+)\n*/, text: /^[^\n]+/ }; block.bullet = /(?:[*+-]|\d+\.)/; block.item = /^( *)(bull) [^\n]*(?:\n(?!\1bull )[^\n]*)*/; block.item = replace(block.item, "gm")(/bull/g, block.bullet)(); block.list = replace(block.list)(/bull/g, block.bullet)("hr", "\\n+(?=\\1?(?:[-*_] *){3,}(?:\\n+|$))")("def", "\\n+(?=" + block.def.source + ")")(); block.blockquote = replace(block.blockquote)("def", block.def)(); block._tag = "(?!(?:" + "a|em|strong|small|s|cite|q|dfn|abbr|data|time|code" + "|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo" + "|span|br|wbr|ins|del|img)\\b)\\w+(?!:/|[^\\w\\s@]*@)\\b"; block.html = replace(block.html)("comment", /<!--[\s\S]*?-->/)("closed", /<(tag)[\s\S]+?<\/\1>/)("closing", /<tag(?:"[^"]*"|'[^']*'|[^'">])*?>/)(/tag/g, block._tag)(); block.paragraph = replace(block.paragraph)("hr", block.hr)("heading", block.heading)("lheading", block.lheading)("blockquote", block.blockquote)("tag", "<" + block._tag)("def", block.def)(); block.normal = merge({}, block); block.gfm = merge({}, block.normal, { fences: /^ *(`{3,}|~{3,}) *(\S+)? *\n([\s\S]+?)\s*\1 *(?:\n+|$)/, paragraph: /^/ }); block.gfm.paragraph = replace(block.paragraph)("(?!", "(?!" + block.gfm.fences.source.replace("\\1", "\\2") + "|" + block.list.source.replace("\\1", "\\3") + "|")(); block.tables = merge({}, block.gfm, { nptable: /^ *(\S.*\|.*)\n *([-:]+ *\|[-| :]*)\n((?:.*\|.*(?:\n|$))*)\n*/, table: /^ *\|(.+)\n *\|( *[-:]+[-| :]*)\n((?: *\|.*(?:\n|$))*)\n*/ }); function Lexer(options) { this.tokens = []; this.tokens.links = {}; this.options = options || marked.defaults; this.rules = block.normal; if (this.options.gfm) { if (this.options.tables) { this.rules = block.tables } else { this.rules = block.gfm } } } Lexer.rules = block; Lexer.lex = function (src, options) { var lexer = new Lexer(options); return lexer.lex(src) }; Lexer.prototype.lex = function (src) { src = src.replace(/\r\n|\r/g, "\n").replace(/\t/g, " ").replace(/\u00a0/g, " ").replace(/\u2424/g, "\n"); return this.token(src, true) }; Lexer.prototype.token = function (src, top, bq) { var src = src.replace(/^ +$/gm, ""), next, loose, cap, bull, b, item, space, i, l; while (src) { if (cap = this.rules.newline.exec(src)) { src = src.substring(cap[0].length); if (cap[0].length > 1) { this.tokens.push({type: "space"}) } } if (cap = this.rules.code.exec(src)) { src = src.substring(cap[0].length); cap = cap[0].replace(/^ {4}/gm, ""); this.tokens.push({type: "code", text: !this.options.pedantic ? cap.replace(/\n+$/, "") : cap}); continue } if (cap = this.rules.fences.exec(src)) { src = src.substring(cap[0].length); this.tokens.push({type: "code", lang: cap[2], text: cap[3]}); continue } if (cap = this.rules.heading.exec(src)) { src = src.substring(cap[0].length); this.tokens.push({type: "heading", depth: cap[1].length, text: cap[2]}); continue } if (top && (cap = this.rules.nptable.exec(src))) { src = src.substring(cap[0].length); item = { type: "table", header: cap[1].replace(/^ *| *\| *$/g, "").split(/ *\| */), align: cap[2].replace(/^ *|\| *$/g, "").split(/ *\| */), cells: cap[3].replace(/\n$/, "").split("\n") }; for (i = 0; i < item.align.length; i++) { if (/^ *-+: *$/.test(item.align[i])) { item.align[i] = "right" } else if (/^ *:-+: *$/.test(item.align[i])) { item.align[i] = "center" } else if (/^ *:-+ *$/.test(item.align[i])) { item.align[i] = "left" } else { item.align[i] = null } } for (i = 0; i < item.cells.length; i++) { item.cells[i] = item.cells[i].split(/ *\| */) } this.tokens.push(item); continue } if (cap = this.rules.lheading.exec(src)) { src = src.substring(cap[0].length); this.tokens.push({type: "heading", depth: cap[2] === "=" ? 1 : 2, text: cap[1]}); continue } if (cap = this.rules.hr.exec(src)) { src = src.substring(cap[0].length); this.tokens.push({type: "hr"}); continue } if (cap = this.rules.blockquote.exec(src)) { src = src.substring(cap[0].length); this.tokens.push({type: "blockquote_start"}); cap = cap[0].replace(/^ *> ?/gm, ""); this.token(cap, top, true); this.tokens.push({type: "blockquote_end"}); continue } if (cap = this.rules.list.exec(src)) { src = src.substring(cap[0].length); bull = cap[2]; this.tokens.push({type: "list_start", ordered: bull.length > 1}); cap = cap[0].match(this.rules.item); next = false; l = cap.length; i = 0; for (; i < l; i++) { item = cap[i]; space = item.length; item = item.replace(/^ *([*+-]|\d+\.) +/, ""); if (~item.indexOf("\n ")) { space -= item.length; item = !this.options.pedantic ? item.replace(new RegExp("^ {1," + space + "}", "gm"), "") : item.replace(/^ {1,4}/gm, "") } if (this.options.smartLists && i !== l - 1) { b = block.bullet.exec(cap[i + 1])[0]; if (bull !== b && !(bull.length > 1 && b.length > 1)) { src = cap.slice(i + 1).join("\n") + src; i = l - 1 } } loose = next || /\n\n(?!\s*$)/.test(item); if (i !== l - 1) { next = item.charAt(item.length - 1) === "\n"; if (!loose)loose = next } this.tokens.push({type: loose ? "loose_item_start" : "list_item_start"}); this.token(item, false, bq); this.tokens.push({type: "list_item_end"}) } this.tokens.push({type: "list_end"}); continue } if (cap = this.rules.html.exec(src)) { src = src.substring(cap[0].length); this.tokens.push({ type: this.options.sanitize ? "paragraph" : "html", pre: cap[1] === "pre" || cap[1] === "script" || cap[1] === "style", text: cap[0] }); continue } if (!bq && top && (cap = this.rules.def.exec(src))) { src = src.substring(cap[0].length); this.tokens.links[cap[1].toLowerCase()] = {href: cap[2], title: cap[3]}; continue } if (top && (cap = this.rules.table.exec(src))) { src = src.substring(cap[0].length); item = { type: "table", header: cap[1].replace(/^ *| *\| *$/g, "").split(/ *\| */), align: cap[2].replace(/^ *|\| *$/g, "").split(/ *\| */), cells: cap[3].replace(/(?: *\| *)?\n$/, "").split("\n") }; for (i = 0; i < item.align.length; i++) { if (/^ *-+: *$/.test(item.align[i])) { item.align[i] = "right" } else if (/^ *:-+: *$/.test(item.align[i])) { item.align[i] = "center" } else if (/^ *:-+ *$/.test(item.align[i])) { item.align[i] = "left" } else { item.align[i] = null } } for (i = 0; i < item.cells.length; i++) { item.cells[i] = item.cells[i].replace(/^ *\| *| *\| *$/g, "").split(/ *\| */) } this.tokens.push(item); continue } if (top && (cap = this.rules.paragraph.exec(src))) { src = src.substring(cap[0].length); this.tokens.push({ type: "paragraph", text: cap[1].charAt(cap[1].length - 1) === "\n" ? cap[1].slice(0, -1) : cap[1] }); continue } if (cap = this.rules.text.exec(src)) { src = src.substring(cap[0].length); this.tokens.push({type: "text", text: cap[0]}); continue } if (src) { throw new Error("Infinite loop on byte: " + src.charCodeAt(0)) } } return this.tokens }; var inline = { escape: /^\\([\\`*{}\[\]()#+\-.!_>])/, autolink: /^<([^ >]+(@|:\/)[^ >]+)>/, url: noop, tag: /^<!--[\s\S]*?-->|^<\/?\w+(?:"[^"]*"|'[^']*'|[^'">])*?>/, link: /^!?\[(inside)\]\(href\)/, reflink: /^!?\[(inside)\]\s*\[([^\]]*)\]/, nolink: /^!?\[((?:\[[^\]]*\]|[^\[\]])*)\]/, strong: /^__([\s\S]+?)__(?!_)|^\*\*([\s\S]+?)\*\*(?!\*)/, em: /^\b_((?:__|[\s\S])+?)_\b|^\*((?:\*\*|[\s\S])+?)\*(?!\*)/, code: /^(`+)\s*([\s\S]*?[^`])\s*\1(?!`)/, br: /^ {2,}\n(?!\s*$)/, del: noop, text: /^[\s\S]+?(?=[\\<!\[_*`]| {2,}\n|$)/ }; inline._inside = /(?:\[[^\]]*\]|[^\[\]]|\](?=[^\[]*\]))*/; inline._href = /\s*<?([\s\S]*?)>?(?:\s+['"]([\s\S]*?)['"])?\s*/; inline.link = replace(inline.link)("inside", inline._inside)("href", inline._href)(); inline.reflink = replace(inline.reflink)("inside", inline._inside)(); inline.normal = merge({}, inline); inline.pedantic = merge({}, inline.normal, { strong: /^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/, em: /^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/ }); inline.gfm = merge({}, inline.normal, { escape: replace(inline.escape)("])", "~|])")(), url: /^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/, del: /^~~(?=\S)([\s\S]*?\S)~~/, text: replace(inline.text)("]|", "~]|")("|", "|https?://|")() }); inline.breaks = merge({}, inline.gfm, { br: replace(inline.br)("{2,}", "*")(), text: replace(inline.gfm.text)("{2,}", "*")() }); function InlineLexer(links, options) { this.options = options || marked.defaults; this.links = links; this.rules = inline.normal; this.renderer = this.options.renderer || new Renderer; this.renderer.options = this.options; if (!this.links) { throw new Error("Tokens array requires a `links` property.") } if (this.options.gfm) { if (this.options.breaks) { this.rules = inline.breaks } else { this.rules = inline.gfm } } else if (this.options.pedantic) { this.rules = inline.pedantic } } InlineLexer.rules = inline; InlineLexer.output = function (src, links, options) { var inline = new InlineLexer(links, options); return inline.output(src) }; InlineLexer.prototype.output = function (src) { var out = "", link, text, href, cap; while (src) { if (cap = this.rules.escape.exec(src)) { src = src.substring(cap[0].length); out += cap[1]; continue } if (cap = this.rules.autolink.exec(src)) { src = src.substring(cap[0].length); if (cap[2] === "@") { text = cap[1].charAt(6) === ":" ? this.mangle(cap[1].substring(7)) : this.mangle(cap[1]); href = this.mangle("mailto:") + text } else { text = escape(cap[1]); href = text } out += this.renderer.link(href, null, text); continue } if (!this.inLink && (cap = this.rules.url.exec(src))) { src = src.substring(cap[0].length); text = escape(cap[1]); href = text; out += this.renderer.link(href, null, text); continue } if (cap = this.rules.tag.exec(src)) { if (!this.inLink && /^<a /i.test(cap[0])) { this.inLink = true } else if (this.inLink && /^<\/a>/i.test(cap[0])) { this.inLink = false } src = src.substring(cap[0].length); out += this.options.sanitize ? escape(cap[0]) : cap[0]; continue } if (cap = this.rules.link.exec(src)) { src = src.substring(cap[0].length); this.inLink = true; out += this.outputLink(cap, {href: cap[2], title: cap[3]}); this.inLink = false; continue } if ((cap = this.rules.reflink.exec(src)) || (cap = this.rules.nolink.exec(src))) { src = src.substring(cap[0].length); link = (cap[2] || cap[1]).replace(/\s+/g, " "); link = this.links[link.toLowerCase()]; if (!link || !link.href) { out += cap[0].charAt(0); src = cap[0].substring(1) + src; continue } this.inLink = true; out += this.outputLink(cap, link); this.inLink = false; continue } if (cap = this.rules.strong.exec(src)) { src = src.substring(cap[0].length); out += this.renderer.strong(this.output(cap[2] || cap[1])); continue } if (cap = this.rules.em.exec(src)) { src = src.substring(cap[0].length); out += this.renderer.em(this.output(cap[2] || cap[1])); continue } if (cap = this.rules.code.exec(src)) { src = src.substring(cap[0].length); out += this.renderer.codespan(escape(cap[2], true)); continue } if (cap = this.rules.br.exec(src)) { src = src.substring(cap[0].length); out += this.renderer.br(); continue } if (cap = this.rules.del.exec(src)) { src = src.substring(cap[0].length); out += this.renderer.del(this.output(cap[1])); continue } if (cap = this.rules.text.exec(src)) { src = src.substring(cap[0].length); out += escape(this.smartypants(cap[0])); continue } if (src) { throw new Error("Infinite loop on byte: " + src.charCodeAt(0)) } } return out }; InlineLexer.prototype.outputLink = function (cap, link) { var href = escape(link.href), title = link.title ? escape(link.title) : null; return cap[0].charAt(0) !== "!" ? this.renderer.link(href, title, this.output(cap[1])) : this.renderer.image(href, title, escape(cap[1])) }; InlineLexer.prototype.smartypants = function (text) { if (!this.options.smartypants)return text; return text.replace(/--/g, "—").replace(/(^|[-\u2014/(\[{"\s])'/g, "$1‘").replace(/'/g, "’").replace(/(^|[-\u2014/(\[{\u2018\s])"/g, "$1“").replace(/"/g, "”").replace(/\.{3}/g, "…") }; InlineLexer.prototype.mangle = function (text) { var out = "", l = text.length, i = 0, ch; for (; i < l; i++) { ch = text.charCodeAt(i); if (Math.random() > .5) { ch = "x" + ch.toString(16) } out += "&#" + ch + ";" } return out }; function Renderer(options) { this.options = options || {} } Renderer.prototype.code = function (code, lang, escaped) { if (this.options.highlight) { var out = this.options.highlight(code, lang); if (out != null && out !== code) { escaped = true; code = out } } if (!lang) { return "<pre><code>" + (escaped ? code : escape(code, true)) + "\n</code></pre>" } return '<pre><code class="' + this.options.langPrefix + escape(lang, true) + '">' + (escaped ? code : escape(code, true)) + "\n</code></pre>\n" }; Renderer.prototype.blockquote = function (quote) { return "<blockquote>\n" + quote + "</blockquote>\n" }; Renderer.prototype.html = function (html) { return html }; Renderer.prototype.heading = function (text, level, raw) { return "<h" + level + ' id="' + this.options.headerPrefix + raw.toLowerCase().replace(/[^\w]+/g, "-") + '">' + text + "</h" + level + ">\n" }; Renderer.prototype.hr = function () { return this.options.xhtml ? "<hr/>\n" : "<hr>\n" }; Renderer.prototype.list = function (body, ordered) { var type = ordered ? "ol" : "ul"; return "<" + type + ">\n" + body + "</" + type + ">\n" }; Renderer.prototype.listitem = function (text) { return "<li>" + text + "</li>\n" }; Renderer.prototype.paragraph = function (text) { return "<p>" + text + "</p>\n" }; Renderer.prototype.table = function (header, body) { return "<table>\n" + "<thead>\n" + header + "</thead>\n" + "<tbody>\n" + body + "</tbody>\n" + "</table>\n" }; Renderer.prototype.tablerow = function (content) { return "<tr>\n" + content + "</tr>\n" }; Renderer.prototype.tablecell = function (content, flags) { var type = flags.header ? "th" : "td"; var tag = flags.align ? "<" + type + ' style="text-align:' + flags.align + '">' : "<" + type + ">"; return tag + content + "</" + type + ">\n" }; Renderer.prototype.strong = function (text) { return "<strong>" + text + "</strong>" }; Renderer.prototype.em = function (text) { return "<em>" + text + "</em>" }; Renderer.prototype.codespan = function (text) { return "<code>" + text + "</code>" }; Renderer.prototype.br = function () { return this.options.xhtml ? "<br/>" : "<br>" }; Renderer.prototype.del = function (text) { return "<del>" + text + "</del>" }; Renderer.prototype.link = function (href, title, text) { if (this.options.sanitize) { try { var prot = decodeURIComponent(unescape(href)).replace(/[^\w:]/g, "").toLowerCase() } catch (e) { return "" } if (prot.indexOf("javascript:") === 0) { return "" } } var out = '<a href="' + href + '"'; if (title) { out += ' title="' + title + '"' } out += ">" + text + "</a>"; return out }; Renderer.prototype.image = function (href, title, text) { var out = '<img src="' + href + '" alt="' + text + '"'; if (title) { out += ' title="' + title + '"' } out += this.options.xhtml ? "/>" : ">"; return out }; function Parser(options) { this.tokens = []; this.token = null; this.options = options || marked.defaults; this.options.renderer = this.options.renderer || new Renderer; this.renderer = this.options.renderer; this.renderer.options = this.options } Parser.parse = function (src, options, renderer) { var parser = new Parser(options, renderer); return parser.parse(src) }; Parser.prototype.parse = function (src) { this.inline = new InlineLexer(src.links, this.options, this.renderer); this.tokens = src.reverse(); var out = ""; while (this.next()) { out += this.tok() } return out }; Parser.prototype.next = function () { return this.token = this.tokens.pop() }; Parser.prototype.peek = function () { return this.tokens[this.tokens.length - 1] || 0 }; Parser.prototype.parseText = function () { var body = this.token.text; while (this.peek().type === "text") { body += "\n" + this.next().text } return this.inline.output(body) }; Parser.prototype.tok = function () { switch (this.token.type) { case"space": { return "" } case"hr": { return this.renderer.hr() } case"heading": { return this.renderer.heading(this.inline.output(this.token.text), this.token.depth, this.token.text) } case"code": { return this.renderer.code(this.token.text, this.token.lang, this.token.escaped) } case"table": { var header = "", body = "", i, row, cell, flags, j; cell = ""; for (i = 0; i < this.token.header.length; i++) { flags = {header: true, align: this.token.align[i]}; cell += this.renderer.tablecell(this.inline.output(this.token.header[i]), { header: true, align: this.token.align[i] }) } header += this.renderer.tablerow(cell); for (i = 0; i < this.token.cells.length; i++) { row = this.token.cells[i]; cell = ""; for (j = 0; j < row.length; j++) { cell += this.renderer.tablecell(this.inline.output(row[j]), { header: false, align: this.token.align[j] }) } body += this.renderer.tablerow(cell) } return this.renderer.table(header, body) } case"blockquote_start": { var body = ""; while (this.next().type !== "blockquote_end") { body += this.tok() } return this.renderer.blockquote(body) } case"list_start": { var body = "", ordered = this.token.ordered; while (this.next().type !== "list_end") { body += this.tok() } return this.renderer.list(body, ordered) } case"list_item_start": { var body = ""; while (this.next().type !== "list_item_end") { body += this.token.type === "text" ? this.parseText() : this.tok() } return this.renderer.listitem(body) } case"loose_item_start": { var body = ""; while (this.next().type !== "list_item_end") { body += this.tok() } return this.renderer.listitem(body) } case"html": { var html = !this.token.pre && !this.options.pedantic ? this.inline.output(this.token.text) : this.token.text; return this.renderer.html(html) } case"paragraph": { return this.renderer.paragraph(this.inline.output(this.token.text)) } case"text": { return this.renderer.paragraph(this.parseText()) } } }; function escape(html, encode) { return html.replace(!encode ? /&(?!#?\w+;)/g : /&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;") } function unescape(html) { return html.replace(/&([#\w]+);/g, function (_, n) { n = n.toLowerCase(); if (n === "colon")return ":"; if (n.charAt(0) === "#") { return n.charAt(1) === "x" ? String.fromCharCode(parseInt(n.substring(2), 16)) : String.fromCharCode(+n.substring(1)) } return "" }) } function replace(regex, opt) { regex = regex.source; opt = opt || ""; return function self(name, val) { if (!name)return new RegExp(regex, opt); val = val.source || val; val = val.replace(/(^|[^\[])\^/g, "$1"); regex = regex.replace(name, val); return self } } function noop() { } noop.exec = noop; function merge(obj) { var i = 1, target, key; for (; i < arguments.length; i++) { target = arguments[i]; for (key in target) { if (Object.prototype.hasOwnProperty.call(target, key)) { obj[key] = target[key] } } } return obj } function marked(src, opt, callback) { if (callback || typeof opt === "function") { if (!callback) { callback = opt; opt = null } opt = merge({}, marked.defaults, opt || {}); var highlight = opt.highlight, tokens, pending, i = 0; try { tokens = Lexer.lex(src, opt) } catch (e) { return callback(e) } pending = tokens.length; var done = function (err) { if (err) { opt.highlight = highlight; return callback(err) } var out; try { out = Parser.parse(tokens, opt) } catch (e) { err = e } opt.highlight = highlight; return err ? callback(err) : callback(null, out) }; if (!highlight || highlight.length < 3) { return done() } delete opt.highlight; if (!pending)return done(); for (; i < tokens.length; i++) { (function (token) { if (token.type !== "code") { return --pending || done() } return highlight(token.text, token.lang, function (err, code) { if (err)return done(err); if (code == null || code === token.text) { return --pending || done() } token.text = code; token.escaped = true; --pending || done() }) })(tokens[i]) } return } try { if (opt)opt = merge({}, marked.defaults, opt); return Parser.parse(Lexer.lex(src, opt), opt) } catch (e) { e.message += "\nPlease report this to https://github.com/chjj/marked."; if ((opt || marked.defaults).silent) { return "<p>An error occured:</p><pre>" + escape(e.message + "", true) + "</pre>" } throw e } } marked.options = marked.setOptions = function (opt) { merge(marked.defaults, opt); return marked }; marked.defaults = { gfm: true, tables: true, breaks: false, pedantic: false, sanitize: false, smartLists: false, silent: false, highlight: null, langPrefix: "lang-", smartypants: false, headerPrefix: "", renderer: new Renderer, xhtml: false }; marked.Parser = Parser; marked.parser = Parser.parse; marked.Renderer = Renderer; marked.Lexer = Lexer; marked.lexer = Lexer.lex; marked.InlineLexer = InlineLexer; marked.inlineLexer = InlineLexer.output; marked.parse = marked; if (typeof module !== "undefined" && typeof exports === "object") { module.exports = marked } else if (typeof define === "function" && define.amd) { define(function () { return marked }) } else { this.marked = marked } }).call(function () { return this || (typeof window !== "undefined" ? window : global) }());
songziming/webmail
static/js/lib/marked.min.js
JavaScript
mit
30,419
/* * @name शेक बॉल बाउंस * @description एक बॉल क्लास बनाएं, कई ऑब्जेक्ट्स को इंस्टेंट करें, इसे स्क्रीन के चारों ओर घुमाएं, और कैनवास के किनारे को छूने पर बाउंस करें। * त्वरणX और त्वरण में कुल परिवर्तन के आधार पर शेक घटना का पता लगाएं और पता लगाने के आधार पर वस्तुओं को गति दें या धीमा करें। */ let balls = []; let threshold = 30; let accChangeX = 0; let accChangeY = 0; let accChangeT = 0; function setup() { createCanvas(displayWidth, displayHeight); for (let i = 0; i < 20; i++) { balls.push(new Ball()); } } function draw() { background(0); for (let i = 0; i < balls.length; i++) { balls[i].move(); balls[i].display(); } checkForShake(); } function checkForShake() { // Calculate total change in accelerationX and accelerationY accChangeX = abs(accelerationX - pAccelerationX); accChangeY = abs(accelerationY - pAccelerationY); accChangeT = accChangeX + accChangeY; // If shake if (accChangeT >= threshold) { for (let i = 0; i < balls.length; i++) { balls[i].shake(); balls[i].turn(); } } // If not shake else { for (let i = 0; i < balls.length; i++) { balls[i].stopShake(); balls[i].turn(); balls[i].move(); } } } // Ball class class Ball { constructor() { this.x = random(width); this.y = random(height); this.diameter = random(10, 30); this.xspeed = random(-2, 2); this.yspeed = random(-2, 2); this.oxspeed = this.xspeed; this.oyspeed = this.yspeed; this.direction = 0.7; } move() { this.x += this.xspeed * this.direction; this.y += this.yspeed * this.direction; } // Bounce when touch the edge of the canvas turn() { if (this.x < 0) { this.x = 0; this.direction = -this.direction; } else if (this.y < 0) { this.y = 0; this.direction = -this.direction; } else if (this.x > width - 20) { this.x = width - 20; this.direction = -this.direction; } else if (this.y > height - 20) { this.y = height - 20; this.direction = -this.direction; } } // Add to xspeed and yspeed based on // the change in accelerationX value shake() { this.xspeed += random(5, accChangeX / 3); this.yspeed += random(5, accChangeX / 3); } // Gradually slows down stopShake() { if (this.xspeed > this.oxspeed) { this.xspeed -= 0.6; } else { this.xspeed = this.oxspeed; } if (this.yspeed > this.oyspeed) { this.yspeed -= 0.6; } else { this.yspeed = this.oyspeed; } } display() { ellipse(this.x, this.y, this.diameter, this.diameter); } }
processing/p5.js-website
src/data/examples/hi/35_Mobile/03_Shake_Ball_Bounce.js
JavaScript
mit
3,037
import { removeFromArray } from '../../../utils/array'; import fireEvent from '../../../events/fireEvent'; import Fragment from '../../Fragment'; import createFunction from '../../../shared/createFunction'; import { unbind } from '../../../shared/methodCallers'; import noop from '../../../utils/noop'; import resolveReference from '../../resolvers/resolveReference'; const eventPattern = /^event(?:\.(.+))?$/; const argumentsPattern = /^arguments\.(\d*)$/; const dollarArgsPattern = /^\$(\d*)$/; export default class EventDirective { constructor ( owner, event, template ) { this.owner = owner; this.event = event; this.template = template; this.ractive = owner.parentFragment.ractive; this.parentFragment = owner.parentFragment; this.context = null; this.passthru = false; // method calls this.method = null; this.resolvers = null; this.models = null; this.argsFn = null; // handler directive this.action = null; this.args = null; } bind () { this.context = this.parentFragment.findContext(); const template = this.template; if ( template.m ) { this.method = template.m; if ( this.passthru = template.g ) { // on-click="foo(...arguments)" // no models or args, just pass thru values } else { this.resolvers = []; this.models = template.a.r.map( ( ref, i ) => { if ( eventPattern.test( ref ) ) { // on-click="foo(event.node)" return { event: true, keys: ref.length > 5 ? ref.slice( 6 ).split( '.' ) : [], unbind: noop }; } const argMatch = argumentsPattern.exec( ref ); if ( argMatch ) { // on-click="foo(arguments[0])" return { argument: true, index: argMatch[1] }; } const dollarMatch = dollarArgsPattern.exec( ref ); if ( dollarMatch ) { // on-click="foo($1)" return { argument: true, index: dollarMatch[1] - 1 }; } let resolver; const model = resolveReference( this.parentFragment, ref ); if ( !model ) { resolver = this.parentFragment.resolve( ref, model => { this.models[i] = model; removeFromArray( this.resolvers, resolver ); }); this.resolvers.push( resolver ); } return model; }); this.argsFn = createFunction( template.a.s, template.a.r.length ); } } else { // TODO deprecate this style of directive this.action = typeof template === 'string' ? // on-click='foo' template : typeof template.n === 'string' ? // on-click='{{dynamic}}' template.n : new Fragment({ owner: this, template: template.n }); this.args = template.a ? // static arguments ( typeof template.a === 'string' ? [ template.a ] : template.a ) : template.d ? // dynamic arguments new Fragment({ owner: this, template: template.d }) : []; // no arguments } if ( this.template.n && typeof this.template.n !== 'string' ) this.action.bind(); if ( this.template.d ) this.args.bind(); } bubble () { if ( !this.dirty ) { this.dirty = true; this.owner.bubble(); } } fire ( event, passedArgs ) { // augment event object if ( event ) { event.keypath = this.context.getKeypath(); event.context = this.context.get(); event.index = this.parentFragment.indexRefs; if ( passedArgs ) passedArgs.unshift( event ); } if ( this.method ) { if ( typeof this.ractive[ this.method ] !== 'function' ) { throw new Error( `Attempted to call a non-existent method ("${this.method}")` ); } let args; if ( this.passthru ) { args = passedArgs; } else { const values = this.models.map( model => { if ( !model ) return undefined; if ( model.event ) { let obj = event; let keys = model.keys.slice(); while ( keys.length ) obj = obj[ keys.shift() ]; return obj; } if ( model.argument ) { return passedArgs ? passedArgs[ model.index ] : void 0; } if ( model.wrapper ) { return model.wrapper.value; } return model.get(); }); args = this.argsFn.apply( null, values ); } // make event available as `this.event` const ractive = this.ractive; const oldEvent = ractive.event; ractive.event = event; ractive[ this.method ].apply( ractive, args ); ractive.event = oldEvent; } else { const action = this.action.toString(); let args = this.template.d ? this.args.getArgsList() : this.args; if ( event ) event.name = action; fireEvent( this.ractive, action, { event, args }); } } rebind () { throw new Error( 'EventDirective$rebind not yet implemented!' ); // TODO add tests } render () { this.event.listen( this ); } unbind () { const template = this.template; if ( template.m ) { this.resolvers.forEach( unbind ); this.resolvers = []; this.models.forEach( model => { if ( model ) model.unbind(); }); } else { // TODO this is brittle and non-explicit, fix it if ( this.action.unbind ) this.action.unbind(); if ( this.args.unbind ) this.args.unbind(); } } unrender () { this.event.unlisten(); } update () { if ( this.method ) return; // nothing to do // ugh legacy if ( this.action.update ) this.action.update(); if ( this.template.d ) this.args.update(); this.dirty = false; } }
magicdawn/ractive
src/view/items/shared/EventDirective.js
JavaScript
mit
5,387
/* Copyright 2012 by James McDermott Licensed under the Academic Free License version 3.0 See the file "LICENSE" for more information */ package ec.app.gpsemantics.func; import ec.*; import ec.gp.*; import ec.util.*; /* * SemanticNode.java * */ /** * @author James McDermott */ public class SemanticExtra extends SemanticNode { char value; int index; public SemanticExtra(char v, int i) { value = v; index = i; } public char value() { return value; } public int index() { return index; } }
Felix-Yan/ECJ
ec/app/gpsemantics/func/SemanticExtra.java
Java
mit
563
class AddAwaitingTwoFactorAuthenticationToTicketGrantingTickets < ActiveRecord::Migration def change add_column :ticket_granting_tickets, :awaiting_two_factor_authentication, :boolean, null: false, default: false end end
cognetoapps/CASinoCore
db/migrate/20130203155008_add_awaiting_two_factor_authentication_to_ticket_granting_tickets.rb
Ruby
mit
229
require 'helper' describe Twitter::Place do describe '#eql?' do it 'returns true when objects WOE IDs are the same' do place = Twitter::Place.new(:woeid => 1, :name => 'foo') other = Twitter::Place.new(:woeid => 1, :name => 'bar') expect(place).to eql(other) end it 'returns false when objects WOE IDs are different' do place = Twitter::Place.new(:woeid => 1) other = Twitter::Place.new(:woeid => 2) expect(place).not_to eql(other) end it 'returns false when classes are different' do place = Twitter::Place.new(:woeid => 1) other = Twitter::Base.new(:woeid => 1) expect(place).not_to eql(other) end end describe '#bounding_box' do it 'returns a Twitter::Geo when bounding_box is set' do place = Twitter::Place.new(:woeid => '247f43d441defc03', :bounding_box => {:type => 'Polygon', :coordinates => [[[-122.40348192, 37.77752898], [-122.387436, 37.77752898], [-122.387436, 37.79448597], [-122.40348192, 37.79448597]]]}) expect(place.bounding_box).to be_a Twitter::Geo::Polygon end it 'returns nil when not bounding_box is not set' do place = Twitter::Place.new(:woeid => '247f43d441defc03') expect(place.bounding_box).to be_nil end end describe '#==' do it 'returns true when objects WOE IDs are the same' do place = Twitter::Place.new(:woeid => 1, :name => 'foo') other = Twitter::Place.new(:woeid => 1, :name => 'bar') expect(place == other).to be true end it 'returns false when objects WOE IDs are different' do place = Twitter::Place.new(:woeid => 1) other = Twitter::Place.new(:woeid => 2) expect(place == other).to be false end it 'returns false when classes are different' do place = Twitter::Place.new(:woeid => 1) other = Twitter::Base.new(:woeid => 1) expect(place == other).to be false end end describe '#bounding_box' do it 'returns a Twitter::Geo when bounding_box is set' do place = Twitter::Place.new(:woeid => '247f43d441defc03', :bounding_box => {:type => 'Polygon', :coordinates => [[[-122.40348192, 37.77752898], [-122.387436, 37.77752898], [-122.387436, 37.79448597], [-122.40348192, 37.79448597]]]}) expect(place.bounding_box).to be_a Twitter::Geo::Polygon end it 'returns nil when not bounding_box is not set' do place = Twitter::Place.new(:woeid => '247f43d441defc03') expect(place.bounding_box).to be_nil end end describe '#bounding_box?' do it 'returns true when bounding_box is set' do place = Twitter::Place.new(:woeid => '247f43d441defc03', :bounding_box => {:type => 'Polygon', :coordinates => [[[-122.40348192, 37.77752898], [-122.387436, 37.77752898], [-122.387436, 37.79448597], [-122.40348192, 37.79448597]]]}) expect(place.bounding_box?).to be true end it 'returns false when bounding_box is not set' do place = Twitter::Place.new(:woeid => '247f43d441defc03') expect(place.bounding_box?).to be false end end describe '#contained_within' do it 'returns a Twitter::Place when contained_within is set' do place = Twitter::Place.new(:woeid => '247f43d441defc03', :contained_within => {:woeid => '247f43d441defc04'}) expect(place.contained_within).to be_a Twitter::Place end it 'returns nil when not contained_within is not set' do place = Twitter::Place.new(:woeid => '247f43d441defc03') expect(place.contained_within).to be_nil end end describe '#contained_within?' do it 'returns true when contained_within is set' do place = Twitter::Place.new(:woeid => '247f43d441defc03', :contained_within => {:woeid => '247f43d441defc04'}) expect(place.contained?).to be true end it 'returns false when contained_within is not set' do place = Twitter::Place.new(:woeid => '247f43d441defc03') expect(place.contained?).to be false end end describe '#country_code' do it 'returns a country code when set with country_code' do place = Twitter::Place.new(:woeid => '247f43d441defc03', :country_code => 'US') expect(place.country_code).to eq('US') end it 'returns a country code when set with countryCode' do place = Twitter::Place.new(:woeid => '247f43d441defc03', :countryCode => 'US') # rubocop:disable SymbolName expect(place.country_code).to eq('US') end it 'returns nil when not set' do place = Twitter::Place.new(:woeid => '247f43d441defc03') expect(place.country_code).to be_nil end end describe '#parent_id' do it 'returns a parent ID when set with parentid' do place = Twitter::Place.new(:woeid => '247f43d441defc03', :parentid => 1) expect(place.parent_id).to eq(1) end it 'returns nil when not set' do place = Twitter::Place.new(:woeid => '247f43d441defc03') expect(place.parent_id).to be_nil end end describe '#place_type' do it 'returns a place type when set with place_type' do place = Twitter::Place.new(:woeid => '247f43d441defc03', :place_type => 'city') expect(place.place_type).to eq('city') end it 'returns a place type when set with placeType[name]' do place = Twitter::Place.new(:woeid => '247f43d441defc03', :placeType => {:name => 'Town'}) # rubocop:disable SymbolName expect(place.place_type).to eq('Town') end it 'returns nil when not set' do place = Twitter::Place.new(:woeid => '247f43d441defc03') expect(place.place_type).to be_nil end end describe '#uri' do it 'returns a URI when the url is set' do place = Twitter::Place.new(:woeid => '247f43d441defc03', :url => 'https://api.twitter.com/1.1/geo/id/247f43d441defc03.json') expect(place.uri).to be_an Addressable::URI expect(place.uri.to_s).to eq('https://api.twitter.com/1.1/geo/id/247f43d441defc03.json') end it 'returns nil when the url is not set' do place = Twitter::Place.new(:woeid => '247f43d441defc03') expect(place.uri).to be_nil end end describe '#uri?' do it 'returns true when the url is set' do place = Twitter::Place.new(:woeid => '247f43d441defc03', :url => 'https://api.twitter.com/1.1/geo/id/247f43d441defc03.json') expect(place.uri?).to be true end it 'returns false when the url is not set' do place = Twitter::Place.new(:woeid => '247f43d441defc03') expect(place.uri?).to be false end end end
noahd1/twitter
spec/twitter/place_spec.rb
Ruby
mit
6,476
<?php return [ 'title' => 'FrameworkJet - UK', 'menu' => 'Menu', 'submenu' => 'Submenu', 'mainmenu' => [ 'home' => 'Home', 'explore' => 'Explore', 'contactus' => 'Contact Us' ], 'button' => [ 'clickme' => 'Click me!' ], 'copyright' => 'Copyright' ];
pavel-tashev/FrameworkJet
Config/Translations/en_UK.php
PHP
mit
314
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.Collections; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Globalization; using System.Windows.Forms; using OpenLiveWriter.ApplicationFramework.Preferences; using OpenLiveWriter.CoreServices; using OpenLiveWriter.CoreServices.Layout; using OpenLiveWriter.Localization; namespace OpenLiveWriter.SpellChecker { /// <summary> /// Summary description for SpellingOptions. /// </summary> public class SpellingPreferencesPanel : PreferencesPanel { //private GroupBox groupBoxInternationalDictionaries; private GroupBox _groupBoxGeneralOptions; private CheckBox _checkBoxIgnoreUppercase; private CheckBox _checkBoxIgnoreNumbers; //private PictureBox pictureBoxInternationalDictionaries; //private Label labelDictionary; /// <summary> /// Required designer variable. /// </summary> private Container components = null; private CheckBox _checkBoxCheckBeforePublish; private CheckBox _checkBoxRealTimeChecking; private CheckBox _checkBoxAutoCorrect; private System.Windows.Forms.Label _labelDictionaryLanguage; private System.Windows.Forms.ComboBox _comboBoxLanguage; private SpellingPreferences spellingPreferences; public SpellingPreferencesPanel() : this(new SpellingPreferences()) { } public SpellingPreferencesPanel(SpellingPreferences preferences) { // This call is required by the Windows.Forms Form Designer. InitializeComponent(); _labelDictionaryLanguage.Text = Res.Get(StringId.DictionaryLanguageLabel); _groupBoxGeneralOptions.Text = Res.Get(StringId.SpellingPrefOptions); _checkBoxRealTimeChecking.Text = Res.Get(StringId.SpellingPrefReal); _checkBoxIgnoreNumbers.Text = Res.Get(StringId.SpellingPrefNum); _checkBoxIgnoreUppercase.Text = Res.Get(StringId.SpellingPrefUpper); _checkBoxCheckBeforePublish.Text = Res.Get(StringId.SpellingPrefPub); _checkBoxAutoCorrect.Text = Res.Get(StringId.SpellingPrefAuto); PanelName = Res.Get(StringId.SpellingPrefName); // set panel bitmap PanelBitmap = _spellingPanelBitmap; // initialize preferences spellingPreferences = preferences; spellingPreferences.PreferencesModified += new EventHandler(spellingPreferences_PreferencesModified); // core options _checkBoxIgnoreUppercase.Checked = spellingPreferences.IgnoreUppercase; _checkBoxIgnoreNumbers.Checked = spellingPreferences.IgnoreWordsWithNumbers; _checkBoxCheckBeforePublish.Checked = spellingPreferences.CheckSpellingBeforePublish; _checkBoxRealTimeChecking.Checked = spellingPreferences.RealTimeSpellChecking; _checkBoxAutoCorrect.Checked = spellingPreferences.EnableAutoCorrect; // initialize language combo _comboBoxLanguage.BeginUpdate(); _comboBoxLanguage.Items.Clear(); SpellingCheckerLanguage currentLanguage = spellingPreferences.Language; SpellingLanguageEntry[] languages = SpellingSettings.GetInstalledLanguages(); Array.Sort(languages, new SentryLanguageEntryComparer(CultureInfo.CurrentUICulture)); foreach (SpellingLanguageEntry language in languages) { int index = _comboBoxLanguage.Items.Add(language); if (language.Language == currentLanguage) _comboBoxLanguage.SelectedIndex = index; } // defend against invalid value if (_comboBoxLanguage.SelectedIndex == -1) { Debug.Fail("Language in registry not supported!"); } _comboBoxLanguage.EndUpdate(); ManageSpellingOptions(); // hookup to changed events to update preferences _checkBoxIgnoreUppercase.CheckedChanged += new EventHandler(checkBoxIgnoreUppercase_CheckedChanged); _checkBoxIgnoreNumbers.CheckedChanged += new EventHandler(checkBoxIgnoreNumbers_CheckedChanged); _checkBoxCheckBeforePublish.CheckedChanged += new EventHandler(checkBoxCheckBeforePublish_CheckedChanged); _checkBoxRealTimeChecking.CheckedChanged += new EventHandler(checkBoxRealTimeChecking_CheckedChanged); _checkBoxAutoCorrect.CheckedChanged += new EventHandler(checkBoxAutoCorrect_CheckedChanged); _comboBoxLanguage.SelectedIndexChanged += new EventHandler(comboBoxLanguage_SelectedIndexChanged); } private void ManageSpellingOptions() { bool enabled = _comboBoxLanguage.SelectedIndex != 0; // "None" _checkBoxIgnoreUppercase.Enabled = enabled; _checkBoxIgnoreNumbers.Enabled = enabled; _checkBoxCheckBeforePublish.Enabled = enabled; _checkBoxRealTimeChecking.Enabled = enabled; _checkBoxAutoCorrect.Enabled = enabled; } private class SentryLanguageEntryComparer : IComparer { private CultureInfo cultureInfo; public SentryLanguageEntryComparer(CultureInfo cultureInfo) { this.cultureInfo = cultureInfo; } public int Compare(object x, object y) { return string.Compare( ((SpellingLanguageEntry)x).DisplayName, ((SpellingLanguageEntry)y).DisplayName, true, cultureInfo); } } protected override void OnLoad(EventArgs e) { base.OnLoad(e); DisplayHelper.AutoFitSystemCombo(_comboBoxLanguage, _comboBoxLanguage.Width, _groupBoxGeneralOptions.Width - _comboBoxLanguage.Left - 8, false); LayoutHelper.FixupGroupBox(8, _groupBoxGeneralOptions); } /// <summary> /// Save data /// </summary> public override void Save() { if (spellingPreferences.IsModified()) spellingPreferences.Save(); } /// <summary> /// flagsPreferences_PreferencesModified event handler. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">An EventArgs that contains the event data.</param> private void spellingPreferences_PreferencesModified(object sender, EventArgs e) { OnModified(EventArgs.Empty); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose(bool disposing) { if (disposing) { if (components != null) { components.Dispose(); } } base.Dispose(disposing); } private const string SPELLING_IMAGE_PATH = "Images."; //private Bitmap spellingDictionariesBitmap = ResourceHelper.LoadAssemblyResourceBitmap( SPELLING_IMAGE_PATH + "SpellingDictionaries.png") ; private readonly Bitmap _spellingPanelBitmap = ResourceHelper.LoadAssemblyResourceBitmap(SPELLING_IMAGE_PATH + "SpellingPanelBitmapSmall.png"); #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this._groupBoxGeneralOptions = new System.Windows.Forms.GroupBox(); this._comboBoxLanguage = new System.Windows.Forms.ComboBox(); this._labelDictionaryLanguage = new System.Windows.Forms.Label(); this._checkBoxRealTimeChecking = new System.Windows.Forms.CheckBox(); this._checkBoxIgnoreNumbers = new System.Windows.Forms.CheckBox(); this._checkBoxIgnoreUppercase = new System.Windows.Forms.CheckBox(); this._checkBoxCheckBeforePublish = new System.Windows.Forms.CheckBox(); this._checkBoxAutoCorrect = new System.Windows.Forms.CheckBox(); this._groupBoxGeneralOptions.SuspendLayout(); this.SuspendLayout(); // // _groupBoxGeneralOptions // this._groupBoxGeneralOptions.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this._groupBoxGeneralOptions.Controls.Add(this._comboBoxLanguage); this._groupBoxGeneralOptions.Controls.Add(this._labelDictionaryLanguage); this._groupBoxGeneralOptions.Controls.Add(this._checkBoxRealTimeChecking); this._groupBoxGeneralOptions.Controls.Add(this._checkBoxIgnoreNumbers); this._groupBoxGeneralOptions.Controls.Add(this._checkBoxIgnoreUppercase); this._groupBoxGeneralOptions.Controls.Add(this._checkBoxCheckBeforePublish); this._groupBoxGeneralOptions.Controls.Add(this._checkBoxAutoCorrect); this._groupBoxGeneralOptions.FlatStyle = System.Windows.Forms.FlatStyle.System; this._groupBoxGeneralOptions.Location = new System.Drawing.Point(8, 32); this._groupBoxGeneralOptions.Name = "_groupBoxGeneralOptions"; this._groupBoxGeneralOptions.Size = new System.Drawing.Size(345, 189); this._groupBoxGeneralOptions.TabIndex = 1; this._groupBoxGeneralOptions.TabStop = false; this._groupBoxGeneralOptions.Text = "General options"; // // _comboBoxLanguage // this._comboBoxLanguage.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this._comboBoxLanguage.Location = new System.Drawing.Point(48, 37); this._comboBoxLanguage.Name = "_comboBoxLanguage"; this._comboBoxLanguage.Size = new System.Drawing.Size(195, 21); this._comboBoxLanguage.TabIndex = 1; // // _labelDictionaryLanguage // this._labelDictionaryLanguage.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this._labelDictionaryLanguage.AutoSize = true; this._labelDictionaryLanguage.FlatStyle = System.Windows.Forms.FlatStyle.System; this._labelDictionaryLanguage.Location = new System.Drawing.Point(16, 18); this._labelDictionaryLanguage.Name = "_labelDictionaryLanguage"; this._labelDictionaryLanguage.Size = new System.Drawing.Size(106, 13); this._labelDictionaryLanguage.TabIndex = 0; this._labelDictionaryLanguage.Text = "Dictionary &language:"; // // _checkBoxRealTimeChecking // this._checkBoxRealTimeChecking.FlatStyle = System.Windows.Forms.FlatStyle.System; this._checkBoxRealTimeChecking.Location = new System.Drawing.Point(16, 65); this._checkBoxRealTimeChecking.Name = "_checkBoxRealTimeChecking"; this._checkBoxRealTimeChecking.Size = new System.Drawing.Size(323, 18); this._checkBoxRealTimeChecking.TabIndex = 2; this._checkBoxRealTimeChecking.Text = "Use &real time spell checking (squiggles)"; // // _checkBoxIgnoreNumbers // this._checkBoxIgnoreNumbers.FlatStyle = System.Windows.Forms.FlatStyle.System; this._checkBoxIgnoreNumbers.Location = new System.Drawing.Point(16, 111); this._checkBoxIgnoreNumbers.Name = "_checkBoxIgnoreNumbers"; this._checkBoxIgnoreNumbers.Size = new System.Drawing.Size(323, 18); this._checkBoxIgnoreNumbers.TabIndex = 4; this._checkBoxIgnoreNumbers.Text = "Ignore words with &numbers"; // // _checkBoxIgnoreUppercase // this._checkBoxIgnoreUppercase.FlatStyle = System.Windows.Forms.FlatStyle.System; this._checkBoxIgnoreUppercase.Location = new System.Drawing.Point(16, 88); this._checkBoxIgnoreUppercase.Name = "_checkBoxIgnoreUppercase"; this._checkBoxIgnoreUppercase.Size = new System.Drawing.Size(323, 18); this._checkBoxIgnoreUppercase.TabIndex = 3; this._checkBoxIgnoreUppercase.Text = "Ignore words in &UPPERCASE"; // // _checkBoxCheckBeforePublish // this._checkBoxCheckBeforePublish.FlatStyle = System.Windows.Forms.FlatStyle.System; this._checkBoxCheckBeforePublish.Location = new System.Drawing.Point(16, 134); this._checkBoxCheckBeforePublish.Name = "_checkBoxCheckBeforePublish"; this._checkBoxCheckBeforePublish.Size = new System.Drawing.Size(323, 18); this._checkBoxCheckBeforePublish.TabIndex = 5; this._checkBoxCheckBeforePublish.Text = "Check spelling before &publishing"; // // _checkBoxAutoCorrect // this._checkBoxAutoCorrect.FlatStyle = System.Windows.Forms.FlatStyle.System; this._checkBoxAutoCorrect.Location = new System.Drawing.Point(16, 157); this._checkBoxAutoCorrect.Name = "_checkBoxAutoCorrect"; this._checkBoxAutoCorrect.Size = new System.Drawing.Size(323, 18); this._checkBoxAutoCorrect.TabIndex = 6; this._checkBoxAutoCorrect.Text = "Automatically &correct common capitalization and spelling mistakes"; // // SpellingPreferencesPanel // this.AccessibleName = "Spelling"; this.Controls.Add(this._groupBoxGeneralOptions); this.Name = "SpellingPreferencesPanel"; this.PanelName = "Spelling"; this.Controls.SetChildIndex(this._groupBoxGeneralOptions, 0); this._groupBoxGeneralOptions.ResumeLayout(false); this._groupBoxGeneralOptions.PerformLayout(); this.ResumeLayout(false); } #endregion private void checkBoxIgnoreUppercase_CheckedChanged(object sender, EventArgs e) { spellingPreferences.IgnoreUppercase = _checkBoxIgnoreUppercase.Checked; } private void checkBoxIgnoreNumbers_CheckedChanged(object sender, EventArgs e) { spellingPreferences.IgnoreWordsWithNumbers = _checkBoxIgnoreNumbers.Checked; } private void checkBoxCheckBeforePublish_CheckedChanged(object sender, EventArgs e) { spellingPreferences.CheckSpellingBeforePublish = _checkBoxCheckBeforePublish.Checked; } private void checkBoxRealTimeChecking_CheckedChanged(object sender, EventArgs e) { spellingPreferences.RealTimeSpellChecking = _checkBoxRealTimeChecking.Checked; } private void checkBoxAutoCorrect_CheckedChanged(object sender, EventArgs e) { spellingPreferences.EnableAutoCorrect = _checkBoxAutoCorrect.Checked; } private void comboBoxLanguage_SelectedIndexChanged(object sender, EventArgs e) { spellingPreferences.Language = (_comboBoxLanguage.SelectedItem as SpellingLanguageEntry).Language; ManageSpellingOptions(); } } }
gduncan411/OpenLiveWriter
src/managed/OpenLiveWriter.SpellChecker/SpellingPreferencesPanel.cs
C#
mit
15,853
# -*- coding: utf-8 -*- from math import floor from typing import ( Tuple, Any ) from PyQt5.QtCore import ( QPointF, QRectF, Qt ) from PyQt5.QtGui import ( QBrush, QPen, QPainterPath, QPolygonF, QMouseEvent, QPainter ) from PyQt5.QtWidgets import ( qApp, QGraphicsItem, QGraphicsPathItem, QGraphicsRectItem, QGraphicsEllipseItem, QStyleOptionGraphicsItem, QWidget, QGraphicsSceneMouseEvent, QGraphicsSceneHoverEvent ) from cadnano.gui.palette import getColorObj from cadnano.views.pathview import pathstyles as styles from cadnano.views.pathview.tools.pathselection import SelectionItemGroup from cadnano.views.pathview import ( PathVirtualHelixItemT, PathXoverItemT, PathStrandItemT, PathNucleicAcidPartItemT ) from cadnano.cntypes import ( StrandT, DocT, Vec2T, WindowT ) _BASE_WIDTH = styles.PATH_BASE_WIDTH PP_L5 = QPainterPath() # Left 5' PainterPath PP_R5 = QPainterPath() # Right 5' PainterPath PP_L3 = QPainterPath() # Left 3' PainterPath PP_R3 = QPainterPath() # Right 3' PainterPath PP_53 = QPainterPath() # Left 5', Right 3' PainterPath PP_35 = QPainterPath() # Left 5', Right 3' PainterPath # set up PP_L5 (left 5' blue square) PP_L5.addRect(0.25 * _BASE_WIDTH, 0.125 * _BASE_WIDTH, 0.75 * _BASE_WIDTH, 0.75 * _BASE_WIDTH) # set up PP_R5 (right 5' blue square) PP_R5.addRect(0, 0.125 * _BASE_WIDTH, 0.75 * _BASE_WIDTH, 0.75 * _BASE_WIDTH) # set up PP_L3 (left 3' blue triangle) L3_POLY = QPolygonF() L3_POLY.append(QPointF(_BASE_WIDTH, 0)) L3_POLY.append(QPointF(0.25 * _BASE_WIDTH, 0.5 * _BASE_WIDTH)) L3_POLY.append(QPointF(_BASE_WIDTH, _BASE_WIDTH)) L3_POLY.append(QPointF(_BASE_WIDTH, 0)) PP_L3.addPolygon(L3_POLY) # set up PP_R3 (right 3' blue triangle) R3_POLY = QPolygonF() R3_POLY.append(QPointF(0, 0)) R3_POLY.append(QPointF(0.75 * _BASE_WIDTH, 0.5 * _BASE_WIDTH)) R3_POLY.append(QPointF(0, _BASE_WIDTH)) R3_POLY.append(QPointF(0, 0)) PP_R3.addPolygon(R3_POLY) # single base left 5'->3' PP_53.addRect(0, 0.125 * _BASE_WIDTH, 0.5 * _BASE_WIDTH, 0.75 * _BASE_WIDTH) POLY_53 = QPolygonF() POLY_53.append(QPointF(0.5 * _BASE_WIDTH, 0)) POLY_53.append(QPointF(_BASE_WIDTH, 0.5 * _BASE_WIDTH)) POLY_53.append(QPointF(0.5 * _BASE_WIDTH, _BASE_WIDTH)) PP_53.addPolygon(POLY_53) # single base left 3'<-5' PP_35.addRect(0.50 * _BASE_WIDTH, 0.125 * _BASE_WIDTH, 0.5 * _BASE_WIDTH, 0.75 * _BASE_WIDTH) POLY_35 = QPolygonF() POLY_35.append(QPointF(0.5 * _BASE_WIDTH, 0)) POLY_35.append(QPointF(0, 0.5 * _BASE_WIDTH)) POLY_35.append(QPointF(0.5 * _BASE_WIDTH, _BASE_WIDTH)) PP_35.addPolygon(POLY_35) _DEFAULT_RECT = QRectF(0, 0, _BASE_WIDTH, _BASE_WIDTH) _NO_PEN = QPen(Qt.NoPen) MOD_RECT = QRectF(.25*_BASE_WIDTH, -.25*_BASE_WIDTH, 0.5*_BASE_WIDTH, 0.5*_BASE_WIDTH) class EndpointItem(QGraphicsPathItem): FILTER_NAME = "endpoint" def __init__(self, strand_item: PathStrandItemT, cap_type: str, # low, high, dual is_drawn5to3: bool): """The parent should be a StrandItem.""" super(EndpointItem, self).__init__(strand_item.virtualHelixItem()) self._strand_item = strand_item self._getActiveTool = strand_item._getActiveTool self.cap_type = cap_type self._low_drag_bound = None self._high_drag_bound = None self._mod_item = None self._isdrawn5to3 = is_drawn5to3 self._initCapSpecificState(is_drawn5to3) p = QPen() p.setCosmetic(True) self.setPen(p) # for easier mouseclick self._click_area = cA = QGraphicsRectItem(_DEFAULT_RECT, self) self._click_area.setAcceptHoverEvents(True) cA.hoverMoveEvent = self.hoverMoveEvent cA.mousePressEvent = self.mousePressEvent cA.mouseMoveEvent = self.mouseMoveEvent cA.setPen(_NO_PEN) self.setFlag(QGraphicsItem.ItemIsSelectable) # end def ### SIGNALS ### ### SLOTS ### ### ACCESSORS ### def idx(self) -> int: """Look up ``base_idx``, as determined by :class:`StrandItem `idxs and cap type.""" if self.cap_type == 'low': return self._strand_item.idxs()[0] else: # high or dual, doesn't matter return self._strand_item.idxs()[1] # end def def partItem(self) -> PathNucleicAcidPartItemT: return self._strand_item.partItem() # end def def disableEvents(self): self._click_area.setAcceptHoverEvents(False) self.mouseMoveEvent = QGraphicsPathItem.mouseMoveEvent self.mousePressEvent = QGraphicsPathItem.mousePressEvent # end def def window(self) -> WindowT: return self._strand_item.window() ### PUBLIC METHODS FOR DRAWING / LAYOUT ### def updatePosIfNecessary(self, idx: int) -> Tuple[bool, SelectionItemGroup]: """Update position if necessary and return ``True`` if updated.""" group = self.group() self.tempReparent() x = int(idx * _BASE_WIDTH) if x != self.x(): self.setPos(x, self.y()) # if group: # group.addToGroup(self) return True, group else: # if group: # group.addToGroup(self) return False, group def safeSetPos(self, x: float, y: float): """ Required to ensure proper reparenting if selected """ group = self.group() self.tempReparent() self.setPos(x, y) if group: group.addToGroup(self) # end def def resetEndPoint(self, is_drawn5to3: bool): self.setParentItem(self._strand_item.virtualHelixItem()) self._initCapSpecificState(is_drawn5to3) upperLeftY = 0 if is_drawn5to3 else _BASE_WIDTH self.setY(upperLeftY) # end def def showMod(self, mod_id: str, color: str): self._mod_item = QGraphicsEllipseItem(MOD_RECT, self) self.changeMod(mod_id, color) self._mod_item.show() # print("Showing {}".format(mod_id)) # end def def changeMod(self, mod_id: str, color: str): self._mod_id = mod_id self._mod_item.setBrush(QBrush(getColorObj(color))) # end def def destroyMod(self): self.scene().removeItem(self._mod_item) self._mod_item = None self._mod_id = None # end def def destroyItem(self): '''Remove this object and references to it from the view ''' scene = self.scene() if self._mod_item is not None: self.destroyMod() scene.removeItem(self._click_area) self._click_area = None scene.removeItem(self) # end def ### PRIVATE SUPPORT METHODS ### def _initCapSpecificState(self, is_drawn5to3: bool): c_t = self.cap_type if c_t == 'low': path = PP_L5 if is_drawn5to3 else PP_L3 elif c_t == 'high': path = PP_R3 if is_drawn5to3 else PP_R5 elif c_t == 'dual': path = PP_53 if is_drawn5to3 else PP_35 self.setPath(path) # end def ### EVENT HANDLERS ### def mousePressEvent(self, event: QGraphicsSceneMouseEvent): """Parses a :meth:`mousePressEvent`, calling the appropriate tool method as necessary. Stores ``_move_idx`` for future comparison. """ self.scene().views()[0].addToPressList(self) idx = self._strand_item.setActiveEndpoint(self.cap_type) self._move_idx = idx active_tool_str = self._getActiveTool().methodPrefix() tool_method_name = active_tool_str + "MousePress" if hasattr(self, tool_method_name): # if the tool method exists modifiers = event.modifiers() getattr(self, tool_method_name)(modifiers, event, self.idx()) def hoverLeaveEvent(self, event: QGraphicsSceneHoverEvent): self._strand_item.hoverLeaveEvent(event) # end def def hoverMoveEvent(self, event: QGraphicsSceneHoverEvent): """Parses a :meth:`hoverMoveEvent`, calling the approproate tool method as necessary. """ vhi_num = self._strand_item.idNum() oligo_length = self._strand_item._model_strand.oligo().length() msg = "%d[%d]\tlength: %d" % (vhi_num, self.idx(), oligo_length) self.partItem().updateStatusBar(msg) active_tool_str = self._getActiveTool().methodPrefix() if active_tool_str == 'createTool': return self._strand_item.createToolHoverMove(event, self.idx()) elif active_tool_str == 'addSeqTool': return self.addSeqToolHoverMove(event, self.idx()) def mouseMoveEvent(self, event: QGraphicsSceneMouseEvent): """Parses a :meth:`mouseMoveEvent`, calling the appropriate tool method as necessary. Updates ``_move_idx`` if it changed. """ tool_method_name = self._getActiveTool().methodPrefix() + "MouseMove" if hasattr(self, tool_method_name): # if the tool method exists idx = int(floor((self.x() + event.pos().x()) / _BASE_WIDTH)) if idx != self._move_idx: # did we actually move? modifiers = event.modifiers() self._move_idx = idx getattr(self, tool_method_name)(modifiers, idx) def customMouseRelease(self, event: QMouseEvent): """Parses a :meth:`mouseReleaseEvent` from view, calling the appropriate tool method as necessary. Deletes ``_move_idx`` if necessary. """ tool_method_name = self._getActiveTool().methodPrefix() + "MouseRelease" if hasattr(self, tool_method_name): # if the tool method exists modifiers = event.modifiers() x = event.pos().x() getattr(self, tool_method_name)(modifiers, x) # call tool method if hasattr(self, '_move_idx'): del self._move_idx ### TOOL METHODS ### def modsToolMousePress(self, modifiers: Qt.KeyboardModifiers, event: QGraphicsSceneMouseEvent, idx: int): """ Checks that a scaffold was clicked, and then calls apply sequence to the clicked strand via its oligo. """ m_strand = self._strand_item._model_strand self._getActiveTool().applyMod(m_strand, idx) # end def def breakToolMouseRelease(self, modifiers: Qt.KeyboardModifiers, x): """Shift-click to merge without switching back to select tool.""" m_strand = self._strand_item._model_strand if modifiers & Qt.ShiftModifier: m_strand.merge(self.idx()) # end def def eraseToolMousePress(self, modifiers: Qt.KeyboardModifiers, event: QGraphicsSceneMouseEvent, idx: int): """Erase the strand.""" m_strand = self._strand_item._model_strand m_strand.strandSet().removeStrand(m_strand) # end def def insertionToolMousePress(self, modifiers: Qt.KeyboardModifiers, event: QGraphicsSceneMouseEvent, idx: int): """Add an insert to the strand if possible.""" m_strand = self._strand_item._model_strand m_strand.addInsertion(idx, 1) # end def def paintToolMousePress(self, modifiers: Qt.KeyboardModifiers, event: QGraphicsSceneMouseEvent, idx: int): """Add an insert to the strand if possible.""" m_strand = self._strand_item._model_strand if qApp.keyboardModifiers() & Qt.ShiftModifier: color = self.window().path_color_panel.shiftColorName() else: color = self.window().path_color_panel.colorName() m_strand.oligo().applyColor(color) # end def def addSeqToolMousePress(self, modifiers: Qt.KeyboardModifiers, event: QGraphicsSceneMouseEvent, idx: int): oligo = self._strand_item._model_strand.oligo() add_seq_tool = self._getActiveTool() add_seq_tool.applySequence(oligo) # end def def addSeqToolHoverMove(self, event: QGraphicsSceneHoverEvent, idx: int): # m_strand = self._model_strand # vhi = self._strand_item._virtual_helix_item add_seq_tool = self._getActiveTool() add_seq_tool.hoverMove(self, event, flag=self._isdrawn5to3) # end def def addSeqToolHoverLeave(self, event: QGraphicsSceneHoverEvent): self._getActiveTool().hoverLeaveEvent(event) # end def def createToolHoverMove(self, idx: int): """Create the strand is possible.""" m_strand = self._strand_item._model_strand vhi = self._strand_item._virtual_helix_item active_tool = self._getActiveTool() if not active_tool.isFloatingXoverBegin(): temp_xover = active_tool.floatingXover() temp_xover.updateFloatingFromStrandItem(vhi, m_strand, idx) # end def def createToolMousePress(self, modifiers: Qt.KeyboardModifiers, event: QGraphicsSceneMouseEvent, idx: int): """Break the strand is possible.""" m_strand = self._strand_item._model_strand vhi = self._strand_item._virtual_helix_item active_tool = self._getActiveTool() if active_tool.isFloatingXoverBegin(): if m_strand.idx5Prime() == idx: return else: temp_xover = active_tool.floatingXover() temp_xover.updateBase(vhi, m_strand, idx) active_tool.setFloatingXoverBegin(False) else: active_tool.setFloatingXoverBegin(True) # install Xover active_tool.attemptToCreateXover(vhi, m_strand, idx) # end def def selectToolMousePress(self, modifiers: Qt.KeyboardModifiers, event: QGraphicsSceneMouseEvent, idx: int): """Set the allowed drag bounds for use by selectToolMouseMove. """ # print("%s.%s [%d]" % (self, util.methodName(), self.idx())) self._low_drag_bound, self._high_drag_bound = self._strand_item._model_strand.getResizeBounds(self.idx()) s_i = self._strand_item viewroot = s_i.viewroot() current_filter_set = viewroot.selectionFilterSet() if (all(f in current_filter_set for f in s_i.strandFilter()) and self.FILTER_NAME in current_filter_set): selection_group = viewroot.strandItemSelectionGroup() mod = Qt.MetaModifier if not (modifiers & mod): selection_group.clearSelection(False) selection_group.setSelectionLock(selection_group) selection_group.pendToAdd(self) selection_group.processPendingToAddList() return selection_group.mousePressEvent(event) # end def def selectToolMouseMove(self, modifiers: Qt.KeyboardModifiers, idx: int): """ Given a new index (pre-validated as different from the prev index), calculate the new x coordinate for self, move there, and notify the parent strandItem to redraw its horizontal line. """ # end def def selectToolMouseRelease(self, modifiers: Qt.KeyboardModifiers, x): """ If the positional-calculated idx differs from the model idx, it means we have moved and should notify the model to resize. If the mouse event had a key modifier, perform special actions: shift = attempt to merge with a neighbor alt = extend to max drag bound """ m_strand = self._strand_item._model_strand if modifiers & Qt.ShiftModifier: self.setSelected(False) self.restoreParent() m_strand.merge(self.idx()) # end def def skipToolMousePress(self, modifiers: Qt.KeyboardModifiers, event: QGraphicsSceneMouseEvent, idx: int): """Add an insert to the strand if possible.""" m_strand = self._strand_item._model_strand m_strand.addInsertion(idx, -1) # end def def restoreParent(self, pos: QPointF = None): """ Required to restore parenting and positioning in the partItem """ # map the position self.tempReparent(pos=pos) self.setSelectedColor(False) self.setSelected(False) # end def def tempReparent(self, pos: QPointF = None): vh_item = self._strand_item.virtualHelixItem() if pos is None: pos = self.scenePos() self.setParentItem(vh_item) temp_point = vh_item.mapFromScene(pos) self.setPos(temp_point) # end def def setSelectedColor(self, use_default: bool): if use_default == True: color = getColorObj(styles.SELECTED_COLOR) else: oligo = self._strand_item.strand().oligo() if oligo.shouldHighlight(): color = getColorObj(oligo.getColor(), alpha=128) else: color = getColorObj(oligo.getColor()) brush = self.brush() brush.setColor(color) self.setBrush(brush) # end def def updateHighlight(self, brush: QBrush): if not self.isSelected(): self.setBrush(brush) # end def def itemChange(self, change: QGraphicsItem.GraphicsItemChange, value: Any) -> bool: """Used for selection of the :class:`EndpointItem` Args: change: parameter that is changing value : new value whose type depends on the ``change`` argument Returns: If the change is a ``QGraphicsItem.ItemSelectedChange``:: ``True`` if selected, other ``False`` Otherwise default to :meth:`QGraphicsPathItem.itemChange()` result """ # for selection changes test against QGraphicsItem.ItemSelectedChange # intercept the change instead of the has changed to enable features. if change == QGraphicsItem.ItemSelectedChange and self.scene(): active_tool = self._getActiveTool() if str(active_tool) == "select_tool": s_i = self._strand_item viewroot = s_i.viewroot() current_filter_set = viewroot.selectionFilterSet() selection_group = viewroot.strandItemSelectionGroup() # only add if the selection_group is not locked out if value == True and self.FILTER_NAME in current_filter_set: if all(f in current_filter_set for f in s_i.strandFilter()): if self.group() != selection_group or not self.isSelected(): selection_group.pendToAdd(self) selection_group.setSelectionLock(selection_group) self.setSelectedColor(True) return True else: return False # end if elif value == True: # don't select return False else: # Deselect # print("deselect ep") # Check if strand is being added to the selection group still if not selection_group.isPending(self._strand_item): selection_group.pendToRemove(self) self.tempReparent() self.setSelectedColor(False) return False else: # don't deselect, because the strand is still selected return True # end else # end if elif str(active_tool) == "paint_tool": s_i = self._strand_item viewroot = s_i.viewroot() current_filter_set = viewroot.selectionFilterSet() if all(f in current_filter_set for f in s_i.strandFilter()): if not active_tool.isMacrod(): active_tool.setMacrod() self.paintToolMousePress(None, None, None) # end elif return False # end if return QGraphicsPathItem.itemChange(self, change, value) # end def def modelDeselect(self, document: DocT): """A strand is selected based on whether its low or high endpoints are selected. this value is a tuple ``(is_low, is_high)`` of booleans """ strand = self._strand_item.strand() test = document.isModelStrandSelected(strand) low_val, high_val = document.getSelectedStrandValue(strand) if test else (False, False) if self.cap_type == 'low': out_value = (False, high_val) else: out_value = (low_val, False) if not out_value[0] and not out_value[1] and test: document.removeStrandFromSelection(strand) elif out_value[0] or out_value[1]: document.addStrandToSelection(strand, out_value) self.restoreParent() # end def def modelSelect(self, document: DocT): """A strand is selected based on whether its low or high endpoints are selected. this value is a tuple ``(is_low, is_high)`` of booleans """ strand = self._strand_item.strand() test = document.isModelStrandSelected(strand) low_val, high_val = document.getSelectedStrandValue(strand) if test else (False, False) if self.cap_type == 'low': out_value = (True, high_val) else: out_value = (low_val, True) self.setSelected(True) self.setSelectedColor(True) document.addStrandToSelection(strand, out_value) # end def def paint(self, painter: QPainter, option: QStyleOptionGraphicsItem, widget: QWidget): painter.setPen(self.pen()) painter.setBrush(self.brush()) painter.drawPath(self.path()) # end def
scholer/cadnano2.5
cadnano/views/pathview/strand/endpointitem.py
Python
mit
22,478
package infovis.gui; import java.awt.Graphics2D; import java.awt.event.MouseEvent; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; /** * Provides meaningful default implementations for a {@link Painter}. * * @author Joschi <josua.krause@googlemail.com> */ public class PainterAdapter implements Painter { @Override public void draw(final Graphics2D gfx, final Context ctx) { // draw nothing } @Override public void drawHUD(final Graphics2D gfx, final Context ctx) { // draw nothing } @Override public boolean click(final Point2D p, final MouseEvent e) { // the event is not consumed return false; } @Override public boolean clickHUD(final Point2D p) { // the event is not consumed return false; } @Override public String getTooltip(final Point2D p) { // no tool-tip return null; } @Override public String getTooltipHUD(final Point2D p) { // no tool-tip return null; } @Override public boolean acceptDrag(final Point2D p) { // the event is not consumed return false; } @Override public void drag(final Point2D start, final Point2D cur, final double dx, final double dy) { // do nothing } @Override public void endDrag(final Point2D start, final Point2D cur, final double dx, final double dy) { drag(start, cur, dx, dy); } @Override public void moveMouse(final Point2D cur) { // nothing to do } @Override public Rectangle2D getBoundingBox() { return null; } }
JosuaKrause/BusVis
src/main/java/infovis/gui/PainterAdapter.java
Java
mit
1,535
using System; using System.Diagnostics; using slnRun.Helper; namespace slnRun.SystemWrapper { public interface IProcessRunner { int Run(string path, string arguments, Action<OutputData> onOutput = null); } public class ProcessRunner : IProcessRunner { private readonly ILogger _logger; public ProcessRunner(ILogger logger) { _logger = logger; } public int Run(string path, string arguments, Action<OutputData> onOutput = null) { _logger.Verbose($"Executing: {path} {arguments}"); var p = new Process(); p.StartInfo = new ProcessStartInfo(); p.StartInfo.FileName = path; p.StartInfo.Arguments = arguments; p.StartInfo.UseShellExecute = false; if (onOutput != null) { p.StartInfo.RedirectStandardOutput = true; p.StartInfo.RedirectStandardError = true; p.OutputDataReceived += (sender, args) => onOutput(new OutputData(args.Data, false)); p.ErrorDataReceived += (sender, args) => onOutput(new OutputData(args.Data, true)); } p.Start(); p.WaitForExit(); _logger.Verbose("Process ended with exit code: " + p.ExitCode); return p.ExitCode; } } public class OutputData { public OutputData(string text, bool isError) { Text = text; IsError = isError; } public string Text { get; set; } public bool IsError { get; set; } } }
danielvetter86/slnRun
source/slnRun/SystemWrapper/ProcessRunner.cs
C#
mit
1,622
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO.Ports; using System.Diagnostics; using System.IO; using System.Windows.Threading; namespace NintendoSpy { public delegate void PacketEventHandler (object sender, byte[] packet); public class SerialMonitor { const int BAUD_RATE = 115200; const int TIMER_MS = 30; public event PacketEventHandler PacketReceived; public event EventHandler Disconnected; SerialPort _datPort; List <byte> _localBuffer; DispatcherTimer _timer; public SerialMonitor (string portName) { _localBuffer = new List <byte> (); _datPort = new SerialPort (portName, BAUD_RATE); } public void Start () { if (_timer != null) return; _localBuffer.Clear (); _datPort.Open (); _timer = new DispatcherTimer (); _timer.Interval = TimeSpan.FromMilliseconds (TIMER_MS); _timer.Tick += tick; _timer.Start (); } public void Stop () { if (_datPort != null) { try { // If the device has been unplugged, Close will throw an IOException. This is fine, we'll just keep cleaning up. _datPort.Close (); } catch (IOException) {} _datPort = null; } if (_timer != null) { _timer.Stop (); _timer = null; } } void tick (object sender, EventArgs e) { if (_datPort == null || !_datPort.IsOpen || PacketReceived == null) return; // Try to read some data from the COM port and append it to our localBuffer. // If there's an IOException then the device has been disconnected. try { int readCount = _datPort.BytesToRead; if (readCount < 1) return; byte[] readBuffer = new byte [readCount]; _datPort.Read (readBuffer, 0, readCount); _datPort.DiscardInBuffer (); _localBuffer.AddRange (readBuffer); } catch (IOException) { Stop (); if (Disconnected != null) Disconnected (this, EventArgs.Empty); return; } // Try and find 2 splitting characters in our buffer. int lastSplitIndex = _localBuffer.LastIndexOf (0x0A); if (lastSplitIndex <= 1) return; int sndLastSplitIndex = _localBuffer.LastIndexOf (0x0A, lastSplitIndex - 1); if (lastSplitIndex == -1) return; // Grab the latest packet out of the buffer and fire it off to the receive event listeners. int packetStart = sndLastSplitIndex + 1; int packetSize = lastSplitIndex - packetStart; PacketReceived (this, _localBuffer.GetRange (packetStart, packetSize).ToArray ()); // Clear our buffer up until the last split character. _localBuffer.RemoveRange (0, lastSplitIndex); } } }
dram55/NintendoSpy
SerialMonitor.cs
C#
mit
3,189
package vkutil import ( "fmt" "net/url" ) // NewCountOffsetParams return params with setted count and offset(optional) func NewCountOffsetParams(count int, offsets ...int) url.Values { if count == 0 { count = 1 } param := url.Values{ "count": {fmt.Sprint(count)}, } if len(offsets) > 0 && offsets[0] != 0 { param.Set("offset", fmt.Sprint(offsets[0])) } return param }
smolgu/lib
vendor/github.com/zhuharev/vkutil/params.go
GO
mit
385
package jp.ijufumi.sample.config; import org.springframework.stereotype.Component; @Component public class Config { }
ijufumi/demo
spring-doma/src/main/java/jp/ijufumi/sample/config/Config.java
Java
mit
120
describe 'dynamoid' do begin require 'dynamoid' require 'logger' require 'spec_helper' Dir[File.dirname(__FILE__) + "/../../models/dynamoid/*.rb"].sort.each do |f| require File.expand_path(f) end before(:all) do @model = DynamoidSimple end describe "instance methods" do let(:model) {@model.new} it "should respond to aasm persistence methods" do expect(model).to respond_to(:aasm_read_state) expect(model).to respond_to(:aasm_write_state) expect(model).to respond_to(:aasm_write_state_without_persistence) end it "should return the initial state when new and the aasm field is nil" do expect(model.aasm.current_state).to eq(:alpha) end it "should save the initial state" do model.save expect(model.status).to eq("alpha") end it "should return the aasm column when new and the aasm field is not nil" do model.status = "beta" expect(model.aasm.current_state).to eq(:beta) end it "should return the aasm column when not new and the aasm_column is not nil" do model.save model.status = "gamma" expect(model.aasm.current_state).to eq(:gamma) end it "should allow a nil state" do model.save model.status = nil expect(model.aasm.current_state).to be_nil end it "should not change the state if state is not loaded" do model.release model.save model.reload expect(model.aasm.current_state).to eq(:beta) end end describe 'subclasses' do it "should have the same states as its parent class" do expect(Class.new(@model).aasm.states).to eq(@model.aasm.states) end it "should have the same events as its parent class" do expect(Class.new(@model).aasm.events).to eq(@model.aasm.events) end it "should have the same column as its parent even for the new dsl" do expect(@model.aasm.attribute_name).to eq(:status) expect(Class.new(@model).aasm.attribute_name).to eq(:status) end end describe 'initial states' do it 'should support conditions' do @model.aasm do initial_state lambda{ |m| m.default } end expect(@model.new(:default => :beta).aasm.current_state).to eq(:beta) expect(@model.new(:default => :gamma).aasm.current_state).to eq(:gamma) end end rescue LoadError puts "------------------------------------------------------------------------" puts "Not running Dynamoid specs because dynamoid gem is not installed!!!" puts "------------------------------------------------------------------------" end end
hspazio/aasm
spec/unit/persistence/dynamoid_persistence_spec.rb
Ruby
mit
2,750
package de.stevenschwenke.java.writingawesomejavacodeworkshop.part3ApplyingToLegacyCode.legacy_ugly_trivia; import java.util.Random; /** * This is the Java implementation of the "ugly trivia game", see * https://github.com/jbrains/trivia/blob/master/java/src/main/java/com/adaptionsoft/games/uglytrivia/Game.java */ public class GameRunner { private static boolean notAWinner; public static void main(String[] args) { Game aGame = new Game(); aGame.add("Chet"); aGame.add("Pat"); aGame.add("Sue"); Random rand = new Random(); do { aGame.roll(rand.nextInt(5) + 1); if (rand.nextInt(9) == 7) { notAWinner = aGame.wrongAnswer(); } else { notAWinner = aGame.wasCorrectlyAnswered(); } } while (notAWinner); } }
stevenschwenke/WritingAwesomeJavaCodeWorkshop
src/test/java/de/stevenschwenke/java/writingawesomejavacodeworkshop/part3ApplyingToLegacyCode/legacy_ugly_trivia/GameRunner.java
Java
cc0-1.0
871
package mat.client.cqlworkspace; import java.util.List; import org.gwtbootstrap3.client.ui.Button; import org.gwtbootstrap3.client.ui.ButtonGroup; import org.gwtbootstrap3.client.ui.DropDownMenu; import org.gwtbootstrap3.client.ui.constants.ButtonType; import org.gwtbootstrap3.client.ui.constants.IconType; import org.gwtbootstrap3.client.ui.constants.Pull; import org.gwtbootstrap3.client.ui.gwt.FlowPanel; import com.google.gwt.dom.client.Style.Unit; import com.google.gwt.event.dom.client.KeyUpEvent; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.VerticalPanel; import edu.ycp.cs.dh.acegwt.client.ace.AceAnnotationType; import mat.client.buttons.InfoDropDownMenu; import mat.client.buttons.InfoToolBarButton; import mat.client.buttons.InsertToolBarButton; import mat.client.buttons.SaveButton; import mat.client.cqlworkspace.shared.CQLEditor; import mat.client.cqlworkspace.shared.CQLEditorPanel; import mat.client.inapphelp.component.InAppHelp; import mat.client.shared.MatContext; import mat.client.shared.SkipListBuilder; import mat.client.shared.SpacerWidget; import mat.shared.CQLError; public class CQLLibraryEditorView { private static final String CQL_LIBRARY_EDITOR_ID = "cqlLibraryEditor"; private VerticalPanel cqlLibraryEditorVP = new VerticalPanel(); private HTML heading = new HTML(); private InAppHelp inAppHelp = new InAppHelp(""); private CQLEditorPanel editorPanel = new CQLEditorPanel(CQL_LIBRARY_EDITOR_ID, "CQL Library Editor", false); private Button exportErrorFile = new Button(); private Button infoButton = new InfoToolBarButton(CQL_LIBRARY_EDITOR_ID); private Button insertButton = new InsertToolBarButton(CQL_LIBRARY_EDITOR_ID); private Button saveButton = new SaveButton(CQL_LIBRARY_EDITOR_ID); private ButtonGroup infoBtnGroup; public CQLLibraryEditorView(){ cqlLibraryEditorVP.clear(); exportErrorFile.setType(ButtonType.PRIMARY); exportErrorFile.setIcon(IconType.DOWNLOAD); exportErrorFile.setText("Export Error File"); exportErrorFile.setTitle("Click to download Export Error File."); exportErrorFile.setId("Button_exportErrorFile"); } public Button getSaveButton() { return this.saveButton; } public VerticalPanel buildView(boolean isEditorEditable, boolean isPageEditable){ editorPanel = new CQLEditorPanel(CQL_LIBRARY_EDITOR_ID, "CQL Library Editor", !isEditorEditable); cqlLibraryEditorVP.clear(); cqlLibraryEditorVP.getElement().setId("cqlLibraryEditor_Id"); heading.addStyleName("leftAligned"); cqlLibraryEditorVP.add(SharedCQLWorkspaceUtility.buildHeaderPanel(heading, inAppHelp)); cqlLibraryEditorVP.add(new SpacerWidget()); getCqlAceEditor().setText(""); getCqlAceEditor().clearAnnotations(); if(isPageEditable) { exportErrorFile.setPull(Pull.LEFT); cqlLibraryEditorVP.add(exportErrorFile); } FlowPanel fp = new FlowPanel(); buildInfoInsertBtnGroup(); fp.add(infoBtnGroup); fp.add(insertButton); cqlLibraryEditorVP.add(fp); getCqlAceEditor().setReadOnly(!isEditorEditable); getSaveButton().setEnabled(isEditorEditable); insertButton.setEnabled(isEditorEditable); this.editorPanel.getEditor().addDomHandler(event -> editorPanel.catchTabOutKeyCommand(event, saveButton), KeyUpEvent.getType()); editorPanel.setSize("650px", "500px"); cqlLibraryEditorVP.add(editorPanel); saveButton.setPull(Pull.RIGHT); cqlLibraryEditorVP.add(saveButton); cqlLibraryEditorVP.setStyleName("cqlRightContainer"); cqlLibraryEditorVP.setWidth("700px"); cqlLibraryEditorVP.setStyleName("marginLeft15px"); return cqlLibraryEditorVP; } private void buildInfoInsertBtnGroup() { DropDownMenu ddm = new InfoDropDownMenu(); ddm.getElement().getStyle().setMarginLeft(3, Unit.PX); infoButton.setMarginLeft(-10); infoBtnGroup = new ButtonGroup(); infoBtnGroup.getElement().setAttribute("class", "btn-group"); infoBtnGroup.add(infoButton); infoBtnGroup.add(ddm); infoBtnGroup.setPull(Pull.LEFT); insertButton.setPull(Pull.RIGHT); } public CQLEditor getCqlAceEditor() { return editorPanel.getEditor(); } public void resetAll() { editorPanel = new CQLEditorPanel(CQL_LIBRARY_EDITOR_ID, "CQL Library Editor", false); getCqlAceEditor().setText(""); } public void setHeading(String text,String linkName) { String linkStr = SkipListBuilder.buildEmbeddedString(linkName); heading.setHTML(linkStr +"<h4><b>" + text + "</b></h4>"); } public Button getExportErrorFile() { return exportErrorFile; } public void setExportErrorFile(Button exportErrorFile) { this.exportErrorFile = exportErrorFile; } public void setCQLLibraryEditorAnnotations(List<CQLError> cqlErrors, String prefix, AceAnnotationType aceAnnotationType) { for (CQLError error : cqlErrors) { int line = error.getErrorInLine(); int column = error.getErrorAtOffeset(); this.getCqlAceEditor().addAnnotation(line - 1, column, prefix + error.getErrorMessage(), aceAnnotationType); } } public InAppHelp getInAppHelp() { return inAppHelp; } public void setInAppHelp(InAppHelp inAppHelp) { this.inAppHelp = inAppHelp; } public Button getInsertButton() { return insertButton; } public Button getInfoButton() { return infoButton; } }
MeasureAuthoringTool/MeasureAuthoringTool_Release
mat/src/main/java/mat/client/cqlworkspace/CQLLibraryEditorView.java
Java
cc0-1.0
5,251
/** */ package tools.descartes.dlim; import org.eclipse.emf.ecore.EObject; /** * <!-- begin-user-doc --> A representation of the model object ' * <em><b>Polynomial Factor</b></em>'. <!-- end-user-doc --> * * <p> * The following features are supported: * <ul> * <li>{@link tools.descartes.dlim.PolynomialFactor#getFactor <em>Factor</em>}</li> * <li>{@link tools.descartes.dlim.PolynomialFactor#getOffset <em>Offset</em>}</li> * </ul> * </p> * * @see tools.descartes.dlim.DlimPackage#getPolynomialFactor() * @model * @generated */ public interface PolynomialFactor extends EObject { /** * Returns the value of the '<em><b>Factor</b></em>' attribute. The default * value is <code>"0.0"</code>. <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Factor</em>' attribute isn't clear, there * really should be more of a description here... * </p> * <!-- end-user-doc --> * * @return the value of the '<em>Factor</em>' attribute. * @see #setFactor(double) * @see tools.descartes.dlim.DlimPackage#getPolynomialFactor_Factor() * @model default="0.0" derived="true" * @generated */ double getFactor(); /** * Sets the value of the ' * {@link tools.descartes.dlim.PolynomialFactor#getFactor <em>Factor</em>}' * attribute. <!-- begin-user-doc --> <!-- end-user-doc --> * * @param value * the new value of the '<em>Factor</em>' attribute. * @see #getFactor() * @generated */ void setFactor(double value); /** * Returns the value of the '<em><b>Offset</b></em>' attribute. The default * value is <code>"0.0"</code>. <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Offset</em>' attribute isn't clear, there * really should be more of a description here... * </p> * <!-- end-user-doc --> * * @return the value of the '<em>Offset</em>' attribute. * @see #setOffset(double) * @see tools.descartes.dlim.DlimPackage#getPolynomialFactor_Offset() * @model default="0.0" derived="true" * @generated */ double getOffset(); /** * Sets the value of the ' * {@link tools.descartes.dlim.PolynomialFactor#getOffset <em>Offset</em>}' * attribute. <!-- begin-user-doc --> <!-- end-user-doc --> * * @param value * the new value of the '<em>Offset</em>' attribute. * @see #getOffset() * @generated */ void setOffset(double value); } // PolynomialFactor
groenda/LIMBO
dlim.generator/src/tools/descartes/dlim/PolynomialFactor.java
Java
epl-1.0
2,467
/** * Copyright (c) 2010-2021 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.velux.internal.handler; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.Nullable; import org.openhab.binding.velux.internal.handler.utils.StateUtils; import org.openhab.core.thing.ChannelUID; import org.openhab.core.types.State; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * <B>Channel-specific retrieval and modification.</B> * <P> * This class implements the Channel <B>scenes</B> of the Thing <B>klf200</B>: * <UL> * <LI><I>Velux</I> <B>bridge</B> &rarr; <B>OpenHAB</B>: * <P> * Information retrieval by method {@link #handleRefresh}.</LI> * </UL> * * @author Guenther Schreiner - Initial contribution. */ @NonNullByDefault final class ChannelBridgeScenes extends ChannelHandlerTemplate { private static final Logger LOGGER = LoggerFactory.getLogger(ChannelBridgeScenes.class); /* * ************************ * ***** Constructors ***** */ // Suppress default constructor for non-instantiability private ChannelBridgeScenes() { throw new AssertionError(); } /** * Communication method to retrieve information to update the channel value. * * @param channelUID The item passed as type {@link ChannelUID} for which a refresh is intended. * @param channelId The same item passed as type {@link String} for which a refresh is intended. * @param thisBridgeHandler The Velux bridge handler with a specific communication protocol which provides * information for this channel. * @return newState The value retrieved for the passed channel, or <I>null</I> in case if there is no (new) value. */ static @Nullable State handleRefresh(ChannelUID channelUID, String channelId, VeluxBridgeHandler thisBridgeHandler) { LOGGER.debug("handleRefresh({},{},{}) called.", channelUID, channelId, thisBridgeHandler); State newState = null; if (thisBridgeHandler.bridgeParameters.scenes.autoRefresh(thisBridgeHandler.thisBridge)) { LOGGER.trace("handleCommand(): there are some existing scenes."); } String sceneInfo = thisBridgeHandler.bridgeParameters.scenes.getChannel().existingScenes.toString(); LOGGER.trace("handleCommand(): found scenes {}.", sceneInfo); sceneInfo = sceneInfo.replaceAll("[^\\p{Punct}\\w]", "_"); newState = StateUtils.createState(sceneInfo); LOGGER.trace("handleRefresh() returns {}.", newState); return newState; } }
paulianttila/openhab2
bundles/org.openhab.binding.velux/src/main/java/org/openhab/binding/velux/internal/handler/ChannelBridgeScenes.java
Java
epl-1.0
2,914
package org.hamcrest.junit.internal; import java.io.PrintWriter; import java.io.StringWriter; import org.hamcrest.Description; import org.hamcrest.Matcher; /** * A matcher that delegates to throwableMatcher and in addition appends the * stacktrace of the actual Throwable in case of a mismatch. */ public class StacktracePrintingMatcher<T extends Throwable> extends org.hamcrest.TypeSafeMatcher<T> { private final Matcher<T> throwableMatcher; public StacktracePrintingMatcher(Matcher<T> throwableMatcher) { this.throwableMatcher = throwableMatcher; } public void describeTo(Description description) { throwableMatcher.describeTo(description); } @Override protected boolean matchesSafely(T item) { return throwableMatcher.matches(item); } @Override protected void describeMismatchSafely(T item, Description description) { throwableMatcher.describeMismatch(item, description); description.appendText("\nStacktrace was: "); description.appendText(readStacktrace(item)); } private String readStacktrace(Throwable throwable) { StringWriter stringWriter = new StringWriter(); throwable.printStackTrace(new PrintWriter(stringWriter)); return stringWriter.toString(); } public static <T extends Throwable> Matcher<T> isThrowable( Matcher<T> throwableMatcher) { return new StacktracePrintingMatcher<T>(throwableMatcher); } public static <T extends Exception> Matcher<T> isException( Matcher<T> exceptionMatcher) { return new StacktracePrintingMatcher<T>(exceptionMatcher); } }
alb-i986/hamcrest-junit
src/main/java/org/hamcrest/junit/internal/StacktracePrintingMatcher.java
Java
epl-1.0
1,670
/******************************************************************************* * Copyright (c) 2019 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ var apiUtils = (function() { "use strict"; var oauthProvider; var __initOauthProvider = function() { if (!oauthProvider) { var pathname = window.location.pathname; var urlToMatch = ".*/oidc/endpoint/([\\s\\S]*)/usersTokenManagement"; var regExpToMatch = new RegExp(urlToMatch, "g"); var groups = regExpToMatch.exec(pathname); oauthProvider = groups[1]; } }; var getAccountAppPasswords = function(userID) { __initOauthProvider(); var deferred = new $.Deferred(); $.ajax({ url: "/oidc/endpoint/" + oauthProvider + "/app-passwords", dataType: "json", data: {user_id: encodeURIComponent(userID)}, headers: { "Authorization": window.globalAuthHeader, // Basic clientID:clientSecret "access_token" : window.globalAccessToken // The OAuth access_token acquired in OIDC login, // which identifies an authenticated user. }, success: function(response) { deferred.resolve(response); }, error: function(jqXHR) { // Ajax request failed. console.log('Error on GET for app-passwords: ' + jqXHR.responseText); deferred.reject(jqXHR); } }); return deferred; }; var getAccountAppTokens = function(userID) { __initOauthProvider(); var deferred = new $.Deferred(); $.ajax({ url: "/oidc/endpoint/" + oauthProvider + "/app-tokens", dataType: "json", data: {user_id: encodeURIComponent(userID)}, headers: { "Authorization": window.globalAuthHeader, // Basic clientID:clientSecret "access_token" : window.globalAccessToken // The OAuth access_token acquired in OIDC login, // which identifies an authenticated user. }, success: function(response) { deferred.resolve(response); }, error: function(jqXHR) { // Ajax request failed. console.log('Error on GET for app-tokens: ' + jqXHR.responseText); deferred.reject(jqXHR); } }); return deferred; }; var deleteAcctAppPasswordToken = function(authID, authType, userID) { __initOauthProvider(); var deferred = new $.Deferred(); var authTypes = authType + 's'; $.ajax({ url: "/oidc/endpoint/" + oauthProvider + "/" + authTypes + "/" + authID + "?user_id=" + encodeURIComponent(userID), type: "DELETE", contentType: "application/x-www-form-urlencoded", headers: { "Authorization": window.globalAuthHeader, // Basic clientID:clientSecret "access_token" : window.globalAccessToken // The OAuth access_token acquired in OIDC login, // which identifies an authenticated user. }, success: function(response) { deferred.resolve(response); }, error: function(jqXHR) { deferred.reject(jqXHR); } }); return deferred; }; var deleteAllAppPasswordsTokens = function(userID, authType) { __initOauthProvider(); var deferred = new $.Deferred(); var authTypes = authType + 's'; $.ajax({ url: "/oidc/endpoint/" + oauthProvider + "/" + authTypes + "?user_id=" + encodeURIComponent(userID), type: "DELETE", accept: "application/json", headers: { "Authorization": window.globalAuthHeader, // Basic clientID:clientSecret "access_token" : window.globalAccessToken // The OAuth access_token acquired in OIDC login, // which identifies an authenticated user. }, success: function(response) { deferred.resolve(response); }, error: function(jqXHR) { deferred.reject(jqXHR); } }); return deferred; }; var deleteSelectedAppPasswordsTokens = function(authID, authType, name, userID) { __initOauthProvider(); var deferred = new $.Deferred(); var authTypes = authType + 's'; $.ajax({ url: "/oidc/endpoint/" + oauthProvider + "/" + authTypes + "/" + authID + "?user_id=" + encodeURIComponent(userID), type: "DELETE", contentType: "application/x-www-form-urlencoded", headers: { "Authorization": window.globalAuthHeader, // Basic clientID:clientSecret "access_token" : window.globalAccessToken // The OAuth access_token acquired in OIDC login, // which identifies an authenticated user. }, success: function(response) { table.deleteTableRow(authID); deferred.resolve(); }, error: function(jqXHR) { // Record the authentication that had the error and return it for processing var response = {status: "failure", authType: authType, authID: authID, name: name }; deferred.resolve(response); } }); return deferred; }; return { getAccountAppPasswords: getAccountAppPasswords, getAccountAppTokens: getAccountAppTokens, deleteAcctAppPasswordToken: deleteAcctAppPasswordToken, deleteAllAppPasswordsTokens: deleteAllAppPasswordsTokens, deleteSelectedAppPasswordsTokens: deleteSelectedAppPasswordsTokens }; })();
OpenLiberty/open-liberty
dev/com.ibm.ws.security.openidconnect.server/resources/WEB-CONTENT/tokenManager/js/apiUtils.js
JavaScript
epl-1.0
6,782
/*! * Copyright 2010 - 2015 Pentaho Corporation. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ define([ "cdf/lib/CCC/def", "./AbstractBarChart", "../util" ], function(def, AbstractBarChart, util) { return AbstractBarChart.extend({ methods: { _rolesToCccDimensionsMap: { 'measuresLine': 'value' // maps to same dim group as 'measures' role }, _noRoleInTooltipMeasureRoles: {'measures': true, 'measuresLine': true}, _options: { plot2: true, secondAxisIndependentScale: false, // prevent default of -1 (which means last series) // TODO: is this needed?? secondAxisSeriesIndexes: null }, _setNullInterpolationMode: function(options, value) { options.plot2NullInterpolationMode = value; }, _initAxes: function() { this.base(); this._measureDiscrimGem || def.assert("Must exist to distinguish measures."); var measureDiscrimCccDimName = this._measureDiscrimGem.cccDimName, meaAxis = this.axes.measure, barGems = meaAxis.gemsByRole[meaAxis.defaultRole], barGemsById = def.query(barGems) // bar: measures, line: measuresLine .uniqueIndex(function(gem) { return gem.id; }); // Create the dataPart dimension calculation this.options.calculations.push({ names: 'dataPart', calculation: function(datum, atoms) { var meaGemId = datum.atoms[measureDiscrimCccDimName].value; // Data part codes // 0 -> bars // 1 -> lines atoms.dataPart = def.hasOwn(barGemsById, meaGemId) ? '0' : '1'; } }); }, _readUserOptions: function(options, drawSpec) { this.base(options, drawSpec); var shape = drawSpec.shape; if(shape && shape === 'none') { options.pointDotsVisible = false; } else { options.pointDotsVisible = true; options.extensionPoints.pointDot_shape = shape; } }, _configure: function() { this.base(); this._configureAxisRange(/*isPrimary*/false, 'ortho2'); this._configureAxisTitle('ortho2',""); this.options.plot2OrthoAxis = 2; // Plot2 uses same color scale // options.plot2ColorAxis = 2; // options.color2AxisTransform = null; }, _configureLabels: function(options, drawSpec) { this.base.apply(this, arguments); // Plot2 var lineLabelsAnchor = drawSpec.lineLabelsOption; if(lineLabelsAnchor && lineLabelsAnchor !== 'none') { options.plot2ValuesVisible = true; options.plot2ValuesAnchor = lineLabelsAnchor; options.plot2ValuesFont = util.defaultFont(util.readFont(drawSpec, 'label')); options.extensionPoints.plot2Label_textStyle = drawSpec.labelColor; } }, _configureDisplayUnits: function() { this.base(); this._configureAxisDisplayUnits(/*isPrimary*/false, 'ortho2'); } } }); });
SteveSchafer-Innovent/innovent-pentaho-birt-plugin
js-lib/expanded/common-ui/visual/ccc/wrapper/charts/BarLineChart.js
JavaScript
epl-1.0
4,152
/****************************************************************************** * * Copyright 2014 Paphus Solutions Inc. * * Licensed under the Eclipse Public License, Version 1.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.eclipse.org/legal/epl-v10.html * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ package org.botlibre.sdk.config; import java.io.StringWriter; import org.w3c.dom.Element; /** * Represents a media file for an avatar (image, video, audio). * An avatar can have many media files that are tagged with emotions, actions, and poses. * This object can be converted to and from XML for usage with the web API. * The media is the short URL to the media file on the server. */ public class AvatarMedia extends Config { public String mediaId; public String name; public String type; public String media; public String emotions; public String actions; public String poses; public boolean hd; public boolean talking; public void parseXML(Element element) { super.parseXML(element); this.mediaId = element.getAttribute("mediaId"); this.name = element.getAttribute("name"); this.type = element.getAttribute("type"); this.media = element.getAttribute("media"); this.emotions = element.getAttribute("emotions"); this.actions = element.getAttribute("actions"); this.poses = element.getAttribute("poses"); this.hd = Boolean.valueOf(element.getAttribute("hd")); this.talking = Boolean.valueOf(element.getAttribute("talking")); } public String toXML() { StringWriter writer = new StringWriter(); writer.write("<avatar-media"); writeCredentials(writer); if (this.mediaId != null) { writer.write(" mediaId=\"" + this.mediaId + "\""); } if (this.name != null) { writer.write(" name=\"" + this.name + "\""); } if (this.type != null) { writer.write(" type=\"" + this.type + "\""); } if (this.emotions != null) { writer.write(" emotions=\"" + this.emotions + "\""); } if (this.actions != null) { writer.write(" actions=\"" + this.actions + "\""); } if (this.poses != null) { writer.write(" poses=\"" + this.poses + "\""); } writer.write(" hd=\"" + this.hd + "\""); writer.write(" talking=\"" + this.talking + "\""); writer.write("/>"); return writer.toString(); } public boolean isVideo() { return this.type != null && this.type.indexOf("video") != -1; } public boolean isAudio() { return this.type != null && this.type.indexOf("audio") != -1; } }
BOTlibre/BOTlibre
sdk/java/src/org/botlibre/sdk/config/AvatarMedia.java
Java
epl-1.0
2,939
/** * Copyright (C) 2014-2019 by Wen Yu. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Any modifications to this file must keep this entire header intact. */ package pixy.image.tiff; /** * TIFF SByte type field. * * @author Wen Yu, yuwen_66@yahoo.com * @version 1.0 02/24/2013 */ public final class SByteField extends AbstractByteField { public SByteField(short tag, byte[] data) { super(tag, FieldType.SBYTE, data); } }
dragon66/pixymeta
src/pixy/image/tiff/SByteField.java
Java
epl-1.0
644
/* * Copyright (c) 2017, 2019 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional * information regarding copyright ownership. * * Licensed under the Apache License, Version 2.0 (the "License"); * You may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.ws.microprofile.faulttolerance.spi; import java.time.Duration; /** * Define the Circuit Breaker policy */ public interface CircuitBreakerPolicy { /** * Define the failure criteria * * @return the failure exception */ public Class<? extends Throwable>[] getFailOn(); @SuppressWarnings("unchecked") public void setFailOn(Class<? extends Throwable>... failOn); /** * Define the skip criteria * * @return the skip exception */ Class<? extends Throwable>[] getSkipOn(); @SuppressWarnings("unchecked") public void setSkipOn(Class<? extends Throwable>... skipOn); /** * * @return The delay time after the circuit is open */ public Duration getDelay(); public void setDelay(Duration delay); /** * The number of consecutive requests in a rolling window * that will trip the circuit. * * @return the number of the consecutive requests in a rolling window * */ public int getRequestVolumeThreshold(); public void setRequestVolumeThreshold(int threshold); /** * The failure threshold to trigger the circuit to open. * e.g. if the requestVolumeThreshold is 20 and failureRation is .50, * more than 10 failures in 20 consecutive requests will trigger * the circuit to open. * * @return The failure threshold to open the circuit */ public double getFailureRatio(); public void setFailureRatio(double ratio); /** * For an open circuit, after the delay period is reached, once the successThreshold * is reached, the circuit is back to close again. * * @return The success threshold to fully close the circuit */ public int getSuccessThreshold(); public void setSuccessThreshold(int threshold); }
OpenLiberty/open-liberty
dev/com.ibm.ws.microprofile.faulttolerance.spi/src/com/ibm/ws/microprofile/faulttolerance/spi/CircuitBreakerPolicy.java
Java
epl-1.0
2,586
/******************************************************************************* * Copyright (c) 2011, 2019 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package com.ibm.ws.app.manager.war.internal; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import com.ibm.websphere.ras.Tr; import com.ibm.websphere.ras.TraceComponent; import com.ibm.websphere.ras.annotation.Trivial; import com.ibm.wsspi.kernel.service.utils.PathUtils; import com.ibm.ws.artifact.zip.cache.ZipCachingProperties; /** * File and zip file utilities. */ public class ZipUtils { private static final TraceComponent tc = Tr.register(ZipUtils.class); // Retry parameters: // // Total of twice the zip.reaper.slow.pend.max. public static final int RETRY_COUNT; public static final long RETRY_AMOUNT = 50; // Split into 50ms wait periods. public static final int RETRY_LIMIT = 1000; // Don't ever wait more than a second. static { if ( ZipCachingProperties.ZIP_CACHE_REAPER_MAX_PENDING == 0 ) { // MAX_PENDING == 0 means the reaper cache is disabled. // Allow just one retry for normal zip processing. RETRY_COUNT = 1; } else { // The quiesce time is expected to be no greater than twice the largest // wait time set for the zip file cache. Absent new activity, the reaper // cache will never wait longer than twice the largest wait time. // (The maximum wait time is more likely capped at 20% above the largest // wait time. That is changed to 100% as an added safety margin.) // // The quiesce time will not be correct if the reaper thread is starved // and is prevented from releasing zip files. long totalAmount = ZipCachingProperties.ZIP_CACHE_REAPER_SLOW_PEND_MAX * 2; if ( totalAmount <= 0 ) { // The pending max is supposed to be greater than zero. Put in safe // values just in case it isn't. RETRY_COUNT = 1; } else { // The slow pending max is not expected to be set to values larger // than tenth's of seconds. To make the limit explicit, don't accept // a retry limit which is more than 1/2 second. if ( totalAmount > RETRY_LIMIT ) { totalAmount = RETRY_LIMIT; // 1/2 second * 2 == 1 second } // Conversion to int is safe: The total amount must be // greater than 0 and less than or equal to 1000. The // retry count will be greater than 1 and less then or // equal to 20. int retryCount = (int) (totalAmount / RETRY_AMOUNT); if ( totalAmount % RETRY_AMOUNT > 0 ) { retryCount++; } RETRY_COUNT = retryCount; } } } /** * Attempt to recursively delete a target file. * * Answer null if the delete was successful. Answer the first * file which could not be deleted if the delete failed. * * If the delete fails, wait 400 MS then try again. Do this * for the entire delete operation, not for each file deletion. * * A test must be done to verify that the file exists before * invoking this method: If the file does not exist, the * delete operation will fail. * * @param file The file to delete recursively. * * @return Null if the file was deleted. The first file which * could not be deleted if the file could not be deleted. */ @Trivial public static File deleteWithRetry(File file) { String methodName = "deleteWithRetry"; String filePath; if ( tc.isDebugEnabled() ) { filePath = file.getAbsolutePath(); Tr.debug(tc, methodName + ": Recursively delete [ " + filePath + " ]"); } else { filePath = null; } File firstFailure = delete(file); if ( firstFailure == null ) { if ( filePath != null ) { Tr.debug(tc, methodName + ": Successful first delete [ " + filePath + " ]"); } return null; } if ( filePath != null ) { Tr.debug(tc, methodName + ": Failed first delete [ " + filePath + " ]: Sleep up to 50 ms and retry"); } // Extract can occur with the server running, and not long after activity // on the previously extracted archives. // // If the first delete attempt failed, try again, up to a limit based on // the expected quiesce time of the zip file cache. File secondFailure = firstFailure; for ( int tryNo = 0; (secondFailure != null) && tryNo < RETRY_COUNT; tryNo++ ) { try { Thread.sleep(RETRY_AMOUNT); } catch ( InterruptedException e ) { // FFDC } secondFailure = delete(file); } if ( secondFailure == null ) { if ( filePath != null ) { Tr.debug(tc, methodName + ": Successful first delete [ " + filePath + " ]"); } return null; } else { if ( filePath != null ) { Tr.debug(tc, methodName + ": Failed second delete [ " + filePath + " ]"); } return secondFailure; } } /** * Attempt to recursively delete a file. * * Do not retry in case of a failure. * * A test must be done to verify that the file exists before * invoking this method: If the file does not exist, the * delete operation will fail. * * @param file The file to recursively delete. * * @return Null if the file was deleted. The first file which * could not be deleted if the file could not be deleted. */ @Trivial public static File delete(File file) { String methodName = "delete"; String filePath; if ( tc.isDebugEnabled() ) { filePath = file.getAbsolutePath(); } else { filePath = null; } if ( file.isDirectory() ) { if ( filePath != null ) { Tr.debug(tc, methodName + ": Delete directory [ " + filePath + " ]"); } File firstFailure = null; File[] subFiles = file.listFiles(); if ( subFiles != null ) { for ( File subFile : subFiles ) { File nextFailure = delete(subFile); if ( (nextFailure != null) && (firstFailure == null) ) { firstFailure = nextFailure; } } } if ( firstFailure != null ) { if ( filePath != null ) { Tr.debug(tc, methodName + ": Cannot delete [ " + filePath + " ]" + " Child [ " + firstFailure.getAbsolutePath() + " ] could not be deleted."); } return firstFailure; } } else { if ( filePath != null ) { Tr.debug(tc, methodName + ": Delete simple file [ " + filePath + " ]"); } } if ( !file.delete() ) { if ( filePath != null ) { Tr.debug(tc, methodName + ": Failed to delete [ " + filePath + " ]"); } return file; } else { if ( filePath != null ) { Tr.debug(tc, methodName + ": Deleted [ " + filePath + " ]"); } return null; } } // public static final boolean IS_EAR = true; public static final boolean IS_NOT_EAR = false; private static final String WAR_EXTENSION = ".war"; /** * Unpack a source archive into a target directory. * * If the source archive is a WAR, package web module archives as well. * * This operation is not smart enough to avoid unpacking WAR files * in an application library folder. However, that is very unlikely to * happen. * * @param source The source archive which is to be unpacked. * @param target The directory into which to unpack the source archive. * @param isEar Control parameter: Is the source archive an EAR file. * When the source archive is an EAR, unpack nested WAR files. * @param lastModified The last modified value to use for the expanded * archive. * * @throws IOException Thrown in case of a failure. */ public static void unzip( File source, File target, boolean isEar, long lastModified) throws IOException { byte[] transferBuffer = new byte[16 * 1024]; unzip(source, target, isEar, lastModified, transferBuffer); } @Trivial public static void unzip( File source, File target, boolean isEar, long lastModified, byte[] transferBuffer) throws IOException { String methodName = "unzip"; String sourcePath = source.getAbsolutePath(); String targetPath = target.getAbsolutePath(); if ( tc.isDebugEnabled() ) { Tr.debug(tc, methodName + ": Source [ " + sourcePath + " ] Size [ " + source.length() + " ]"); Tr.debug(tc, methodName + ": Target [ " + targetPath + " ]"); } if ( !source.exists() ) { throw new IOException("Source [ " + sourcePath + " ] does not exist"); } else if ( !source.isFile() ) { throw new IOException("Source [ " + sourcePath + " ] is not a simple file"); } else if ( !target.exists() ) { throw new IOException("Target [ " + targetPath + " ] does not exist"); } else if ( !target.isDirectory() ) { throw new IOException("Target [ " + targetPath + " ] is not a directory"); } List<Object[]> warData = ( isEar ? new ArrayList<Object[]>() : null ); ZipFile sourceZip = new ZipFile(source); try { Enumeration<? extends ZipEntry> sourceEntries = sourceZip.entries(); while ( sourceEntries.hasMoreElements() ) { ZipEntry sourceEntry = sourceEntries.nextElement(); String sourceEntryName = sourceEntry.getName(); if ( reachesOut(sourceEntryName) ) { Tr.error(tc, "error.file.outside.archive", sourceEntryName, sourcePath); continue; } String targetFileName; Object[] nextWarData; if ( isEar && !sourceEntry.isDirectory() && sourceEntryName.endsWith(WAR_EXTENSION) ) { for ( int tmpNo = 0; sourceZip.getEntry( targetFileName = sourceEntryName + ".tmp" + tmpNo ) != null; tmpNo++ ) { // Empty } nextWarData = new Object[] { sourceEntryName, targetFileName, null }; } else { targetFileName = sourceEntryName; nextWarData = null; } File targetFile = new File(target, targetFileName); if ( sourceEntry.isDirectory() ) { if ( tc.isDebugEnabled() ) { Tr.debug(tc, methodName + ": Directory [ " + sourceEntryName + " ]"); } if ( !targetFile.exists() && !targetFile.mkdirs() ) { throw new IOException("Failed to create directory [ + " + targetFile.getAbsolutePath() + " ]"); } } else { if ( tc.isDebugEnabled() ) { Tr.debug(tc, methodName + ": Simple file [ " + sourceEntryName + " ] [ " + sourceEntry.getSize() + " ]"); } File targetParent = targetFile.getParentFile(); if ( !targetParent.mkdirs() && !targetParent.exists() ) { throw new IOException("Failed to create directory [ " + targetParent.getAbsolutePath() + " ]"); } transfer(sourceZip, sourceEntry, targetFile, transferBuffer); // throws IOException } // If the entry doesn't provide a meaningful last modified time, // use the parent file's last modified time. long entryModified = sourceEntry.getTime(); if ( entryModified == -1 ) { entryModified = lastModified; } targetFile.setLastModified(entryModified); if ( nextWarData != null ) { nextWarData[2] = Long.valueOf(entryModified); warData.add(nextWarData); } } } finally { if ( sourceZip != null ) { sourceZip.close(); } } if ( isEar ) { for ( Object[] nextWarData : warData ) { String unpackedWarName = (String) nextWarData[0]; String packedWarName = (String) nextWarData[1]; long warLastModified = ((Long) nextWarData[2]).longValue(); File unpackedWarFile = new File(target, unpackedWarName); if ( !unpackedWarFile.exists() && !unpackedWarFile.mkdirs() ) { throw new IOException("Failed to create [ " + unpackedWarFile.getAbsolutePath() + " ]"); } File packedWarFile = new File(target, packedWarName); unzip(packedWarFile, unpackedWarFile, IS_NOT_EAR, warLastModified, transferBuffer); if ( !packedWarFile.delete() ) { if ( tc.isDebugEnabled() ) { Tr.debug(tc, methodName + ": Failed to delete temporary WAR [ " + packedWarFile.getAbsolutePath() + " ]"); } } } } // Do this last: The extraction into the target will update // the target time stamp. We need the time stamp to be the time stamp // of the source. if ( tc.isDebugEnabled() ) { Tr.debug(tc, methodName + ": Set last modified [ " + lastModified + " ]"); } target.setLastModified(lastModified); } @Trivial private static void transfer( ZipFile sourceZip, ZipEntry sourceEntry, File targetFile, byte[] transferBuffer) throws IOException { InputStream inputStream = null; OutputStream outputStream = null; try { inputStream = sourceZip.getInputStream(sourceEntry); outputStream = new FileOutputStream(targetFile); int lastRead; while ( (lastRead = inputStream.read(transferBuffer)) != -1) { outputStream.write(transferBuffer, 0, lastRead); } } finally { if ( inputStream != null ) { inputStream.close(); } if ( outputStream != null ) { outputStream.close(); } } } private static boolean reachesOut(String entryPath) { if ( !entryPath.contains("..") ) { return false; } String normalizedPath = PathUtils.normalizeUnixStylePath(entryPath); return PathUtils.isNormalizedPathAbsolute(normalizedPath); // Leading ".." or "/.." // The following is very inefficient ... and doesn't work when there // are symbolic links. // return targetFile.getCanonicalPath().startsWith(targetDirectory.getCanonicalPath() + File.separator); } }
OpenLiberty/open-liberty
dev/com.ibm.ws.app.manager.war/src/com/ibm/ws/app/manager/war/internal/ZipUtils.java
Java
epl-1.0
16,415
var deps = [ 'common-ui/angular', 'test/karma/unit/angular-directives/templateUtil', 'common-ui/angular-ui-bootstrap', 'angular-mocks', 'common-ui/angular-directives/recurrence/recurrence' ]; define(deps, function (angular, templateUtil) { describe('weeklyRecurrence', function () { var $scope, httpBackend, templateCache; beforeEach(module('recurrence', 'dateTimePicker')); beforeEach(inject(function ($rootScope, $httpBackend, $templateCache) { $scope = $rootScope; httpBackend = $httpBackend; templateCache = $templateCache; templateUtil.addTemplate("common-ui/angular-directives/recurrence/weekly.html", httpBackend, templateCache); templateUtil.addTemplate("common-ui/angular-directives/dateTimePicker/dateTimePicker.html", httpBackend, templateCache); })); describe('weekly', function () { var scope, $compile; var element; beforeEach(inject(function (_$rootScope_, _$compile_) { scope = _$rootScope_; $compile = _$compile_; })); afterEach(function () { element = scope = $compile = undefined; }); describe('with static panels', function () { beforeEach(function () { var tpl = "<div weekly weekly-label='Run every week on' start-label='Start' until-label='Until' no-end-label='No end date' end-by-label='End by' weekly-recurrence-info='model'></div>"; element = angular.element(tpl); $compile(element)(scope); scope.$digest(); //Set model to initially have 2 days check along with dates set scope.model.startTime = new Date(); scope.model.endTime = new Date(); scope.model.daysOfWeek = [0, 6]; scope.$apply(); }); afterEach(function () { element.remove(); }); it('rehydrated model should reflect initial changes', function () { expect(scope.model.daysOfWeek.length).toEqual(2); expect(scope.model.endTime).toBeDefined(); expect(scope.model.startTime).toBeDefined(); //Grab first checkbox and un-check it element.find('input.SUN').click(); //ensure that the first checkbox is unchecked expect(scope.model.daysOfWeek.length).toBe(1); //Grab last checkbox and un-check it element.find('input.SAT').click(); //ensure that the last checkbox is unchecked expect(scope.model.daysOfWeek.length).toBe(0); }); it('should create weekly panel with content', function () { expect(element.attr('weekly')).toBeDefined(); expect(element.attr('weekly-label')).toEqual("Run every week on"); expect(element.attr('start-label')).toEqual("Start"); expect(element.attr('until-label')).toEqual("Until"); expect(element.attr('no-end-label')).toEqual("No end date"); expect(element.attr('end-by-label')).toEqual("End by"); }); it('clicking checkbox set model on the scope', function () { //Grab checkbox and check it element.find('input.MON').click(); //ensure that the second checkbox is checked expect(scope.model.daysOfWeek.length).toBe(3); //Grab checkbox and check it element.find('input.TUES').click(); //ensure that the third checkbox is checked expect(scope.model.daysOfWeek.length).toBe(4); //Grab checkbox and check it element.find('input.WED').click(); //ensure that the fourth checkbox is checked expect(scope.model.daysOfWeek.length).toBe(5); //Grab checkbox and check it element.find('input.THURS').click(); //ensure that the fifth checkbox is checked expect(scope.model.daysOfWeek.length).toBe(6); //Grab checkbox and check it element.find('input.FRI').click(); //ensure that the sixth checkbox is checked expect(scope.model.daysOfWeek.length).toBe(7); //Click checkbox again to deselect it element.find('input.WED').click(); //ensure that the seventh checkbox is deselected expect(scope.model.daysOfWeek.length).toBe(6); }); it('clicking radio button should update something', function () { }); describe("start datetime directive initialization from scope", function () { var startDatetime, isolateScope; beforeEach(function () { startDatetime = angular.element(element.find('div')[1]); isolateScope = startDatetime.isolateScope(); }); it('should update model on the scope', function () { //Change the start hour to 10 AM isolateScope.hour = 10; isolateScope.tod = "AM"; //Change the start minute to :00 isolateScope.minute = 59; scope.$apply(); expect(scope.model.startTime.getHours()).toBe(10); expect(scope.model.startTime.getMinutes()).toBe(59); var myDate = new Date(2014,4,1,23,15,0); isolateScope.selectedDate = myDate; scope.$apply(); expect(scope.model.startTime).toBe(myDate); }); }); }); describe("Weekly validation tests", function () { var $myscope, isolateScope; beforeEach(inject(function ($rootScope, $compile) { var tpl = "<div weekly weekly-label='Run every week on' start-label='Start' until-label='Until' no-end-label='No end date' end-by-label='End by' weekly-recurrence-info='model'></div>"; $myscope = $rootScope.$new(); element = angular.element(tpl); $compile(element)($myscope); $myscope.$digest(); // get the isolate scope from the element isolateScope = element.isolateScope(); $myscope.model = {}; $myscope.$apply(); })); afterEach(function () { element.remove(); }); it("should not be valid by default", function () { var v = isolateScope.isValid(); expect(v).toBeFalsy(); }); it("should have at least one day selected considered valid", function () { expect(isolateScope.isValid()).toBeFalsy(); // this should be defaulted to the current date/time expect(isolateScope.startDate).toBeDefined(); expect(isolateScope.startDate).toBeLessThan(new Date()); element.find("input.SUN").click(); expect(isolateScope.isValid()).toBeTruthy(); element.find("input.SUN").click(); expect(isolateScope.isValid()).toBeFalsy(); element.find("input.SUN").click(); // turn it back on expect(isolateScope.isValid()).toBeTruthy(); }); it("should have an end date after the start date to be valid", function () { expect(isolateScope.isValid()).toBeFalsy(); element.find("input.SUN").click(); isolateScope.data.endDateDisabled = false; // select the end date radio isolateScope.endDate = new Date(); expect(isolateScope.isValid()).toBeTruthy(); isolateScope.endDate = "2014-04-01"; // before now and a string version of the date expect(isolateScope.isValid()).toBeFalsy(); }); it("should hydrate from strings for start and end time", function () { $myscope.model = { startTime: "2014-04-01", endTime: "2014-04-02" }; $myscope.$apply(); element.find("input.SUN").click(); isolateScope.data.endDateDisabled = false; // select the end date radio expect(isolateScope.isValid()).toBeTruthy(); }); }); describe("Weekly validation tests", function() { var $myscope, isolateScope; beforeEach(inject(function ($rootScope, $compile) { var tpl = "<div weekly weekly-label='Run every week on' start-label='Start' until-label='Until' no-end-label='No end date' end-by-label='End by' weekly-recurrence-info='model'></div>"; $myscope = $rootScope.$new(); element = angular.element(tpl); $compile(element)($myscope); $myscope.$digest(); // get the isolate scope from the element isolateScope = element.isolateScope(); $myscope.model = {}; $myscope.$apply(); })); afterEach(function() { element.remove(); }); it("should not be valid by default", function() { var v = isolateScope.isValid(); expect(v).toBeFalsy(); }); it("should have at least one day selected considered valid", function() { expect(isolateScope.isValid()).toBeFalsy(); // this should be defaulted to the current date/time expect(isolateScope.startDate).toBeDefined(); expect(isolateScope.startDate).toBeLessThan(new Date()); element.find("input.SUN").click(); expect(isolateScope.isValid()).toBeTruthy(); element.find("input.SUN").click(); expect(isolateScope.isValid()).toBeFalsy(); element.find("input.SUN").click(); // turn it back on expect(isolateScope.isValid()).toBeTruthy(); }); it("should have an end date after the start date to be valid", function() { expect(isolateScope.isValid()).toBeFalsy(); element.find("input.SUN").click(); isolateScope.data.endDateDisabled = false; // select the end date radio isolateScope.endDate = new Date(); expect(isolateScope.isValid()).toBeTruthy(); isolateScope.endDate = "2014-04-01"; // before now and a string version of the date expect(isolateScope.isValid()).toBeFalsy(); }); it("should hydrate from strings for start and end time", function() { $myscope.model = { startTime: "2014-04-01", endTime: "2014-04-02" }; $myscope.$apply(); element.find("input.SUN").click(); isolateScope.data.endDateDisabled = false; // select the end date radio expect(isolateScope.isValid()).toBeTruthy(); }); }); }); }); });
SteveSchafer-Innovent/innovent-pentaho-birt-plugin
js-lib/expanded/common-ui/test/karma/unit/angular-directives/weeklyRecurrenceSpec.js
JavaScript
epl-1.0
11,930
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cxf.microprofile.client.cdi; import java.lang.reflect.Method; import java.security.AccessController; import java.security.PrivilegedExceptionAction; import java.util.concurrent.Callable; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.cxf.common.logging.LogUtils; import com.ibm.websphere.ras.annotation.Trivial; public interface CDIInterceptorWrapper { Logger LOG = LogUtils.getL7dLogger(CDIInterceptorWrapper.class); class BasicCDIInterceptorWrapper implements CDIInterceptorWrapper { BasicCDIInterceptorWrapper() { } @Trivial //Liberty change @Override public Object invoke(Object restClient, Method m, Object[] params, Callable<Object> callable) throws Exception { return callable.call(); } } static CDIInterceptorWrapper createWrapper(Class<?> restClient) { try { return AccessController.doPrivileged((PrivilegedExceptionAction<CDIInterceptorWrapper>) () -> { Object beanManager = CDIFacade.getBeanManager().orElseThrow(() -> new Exception("CDI not available")); return new CDIInterceptorWrapperImpl(restClient, beanManager); }); //} catch (PrivilegedActionException pae) { } catch (Exception pae) { //Liberty change // expected for environments where CDI is not supported if (LOG.isLoggable(Level.FINEST)) { LOG.log(Level.FINEST, "Unable to load CDI SPI classes, assuming no CDI is available", pae); } return new BasicCDIInterceptorWrapper(); } } Object invoke(Object restClient, Method m, Object[] params, Callable<Object> callable) throws Exception; }
OpenLiberty/open-liberty
dev/com.ibm.ws.org.apache.cxf.cxf.rt.rs.mp.client.3.3/src/org/apache/cxf/microprofile/client/cdi/CDIInterceptorWrapper.java
Java
epl-1.0
2,578
/** * Copyright (c) 2021 Bosch.IO GmbH and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.eclipse.hawkbit.ui.error.extractors; import java.util.Collections; import java.util.List; import java.util.Optional; import org.eclipse.hawkbit.ui.error.UiErrorDetails; /** * Base class for single UI error details extractors. */ public abstract class AbstractSingleUiErrorDetailsExtractor implements UiErrorDetailsExtractor { @Override public List<UiErrorDetails> extractErrorDetailsFrom(final Throwable error) { return findDetails(error).map(Collections::singletonList).orElseGet(Collections::emptyList); } /** * Extracts single ui error details from given error. * * @param error * error to extract details from * @return ui error details if found */ protected abstract Optional<UiErrorDetails> findDetails(Throwable error); }
eclipse/hawkbit
hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/error/extractors/AbstractSingleUiErrorDetailsExtractor.java
Java
epl-1.0
1,123
/** * Copyright (c) 2010-2019 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.buienradar.internal.buienradarapi; import java.math.BigDecimal; import java.time.ZonedDateTime; import org.eclipse.jdt.annotation.NonNullByDefault; /** * The {@link Prediction} interface contains a prediction of rain at a specific time. * * @author Edwin de Jong - Initial contribution */ @NonNullByDefault public interface Prediction { /** * Intensity of rain in mm/hour */ BigDecimal getIntensity(); /** * Date-time of prediction. */ ZonedDateTime getDateTime(); }
clinique/openhab2
bundles/org.openhab.binding.buienradar/src/main/java/org/openhab/binding/buienradar/internal/buienradarapi/Prediction.java
Java
epl-1.0
920
package org.eclipse.epsilon.eol.metamodel.visitor; import org.eclipse.epsilon.eol.metamodel.*; public abstract class RealTypeVisitor<T, R> { public boolean appliesTo(RealType realType, T context) { return true; } public abstract R visit (RealType realType, T context, EolVisitorController<T, R> controller); }
epsilonlabs/epsilon-static-analysis
org.eclipse.epsilon.haetae.eol.metamodel.visitor/src/org/eclipse/epsilon/eol/metamodel/visitor/RealTypeVisitor.java
Java
epl-1.0
323
/** * Copyright (c) 2010-2021 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.evohome.internal; import java.util.concurrent.TimeoutException; /** * Provides an interface for a delegate that can throw a timeout * * @author Jasper van Zuijlen - Initial contribution * */ public interface RunnableWithTimeout { public abstract void run() throws TimeoutException; }
paulianttila/openhab2
bundles/org.openhab.binding.evohome/src/main/java/org/openhab/binding/evohome/internal/RunnableWithTimeout.java
Java
epl-1.0
705
/** * Copyright (c) 2014 openHAB UG (haftungsbeschraenkt) and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.eclipse.smarthome.core.library.types; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; import org.eclipse.smarthome.core.types.Command; import org.eclipse.smarthome.core.types.PrimitiveType; import org.eclipse.smarthome.core.types.State; public class DateTimeType implements PrimitiveType, State, Command { public final static SimpleDateFormat DATE_FORMATTER = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); protected Calendar calendar; public DateTimeType() { this(Calendar.getInstance()); } public DateTimeType(Calendar calendar) { this.calendar = calendar; } public DateTimeType(String calendarValue) { Date date = null; try { date = DATE_FORMATTER.parse(calendarValue); } catch (ParseException fpe) { throw new IllegalArgumentException(calendarValue + " is not in a valid format.", fpe); } if (date != null) { calendar = Calendar.getInstance(); calendar.setTime(date); } } public Calendar getCalendar() { return calendar; } public static DateTimeType valueOf(String value) { return new DateTimeType(value); } public String format(String pattern) { try { return String.format(pattern, calendar); } catch (NullPointerException npe) { return DATE_FORMATTER.format(calendar.getTime()); } } public String format(Locale locale, String pattern) { return String.format(locale, pattern, calendar); } @Override public String toString() { return DATE_FORMATTER.format(calendar.getTime()); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((calendar == null) ? 0 : calendar.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; DateTimeType other = (DateTimeType) obj; if (calendar == null) { if (other.calendar != null) return false; } else if (!calendar.equals(other.calendar)) return false; return true; } }
innoq/smarthome
bundles/core/org.eclipse.smarthome.core.library/src/main/java/org/eclipse/smarthome/core/library/types/DateTimeType.java
Java
epl-1.0
2,571
/******************************************************************************* * Copyright (c) 2020 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package com.ibm.ws.transaction.ejb.third; import static javax.ejb.TransactionAttributeType.REQUIRES_NEW; import java.util.logging.Logger; import javax.annotation.PostConstruct; import javax.ejb.LocalBean; import javax.ejb.Singleton; import javax.ejb.Startup; import javax.ejb.TransactionAttribute; @Singleton @Startup @LocalBean public class InitNewTxBean3 { private static final Logger logger = Logger.getLogger(InitNewTxBean3.class.getName()); @PostConstruct @TransactionAttribute(REQUIRES_NEW) public void initTx3() { logger.info("---- InitTx3 invoked ----"); } }
OpenLiberty/open-liberty
dev/com.ibm.ws.transaction.core_fat.startMultiEJB/test-applications/newEJBTx3/src/com/ibm/ws/transaction/ejb/third/InitNewTxBean3.java
Java
epl-1.0
1,135
/******************************************************************************* * Copyright (c) 2017 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ @org.osgi.annotation.versioning.Version("1.0.16") package com.ibm.ws.security.wim.registry.dataobject;
OpenLiberty/open-liberty
dev/com.ibm.ws.security.wim.registry/src/com/ibm/ws/security/wim/registry/dataobject/package-info.java
Java
epl-1.0
638
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.weather.internal.model.common; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import org.openhab.binding.weather.internal.model.ProviderName; import org.openhab.binding.weather.internal.model.common.adapter.ProviderNameAdapter; import org.openhab.binding.weather.internal.model.common.adapter.ValueListAdapter; /** * Simple class with the JAXB mapping for a provider id configuration. * * @author Gerhard Riegler * @since 1.6.0 */ @XmlRootElement(name = "provider") @XmlAccessorType(XmlAccessType.FIELD) public class CommonIdProvider { @XmlAttribute(name = "name", required = true) @XmlJavaTypeAdapter(value = ProviderNameAdapter.class) private ProviderName name; @XmlAttribute(name = "ids") @XmlJavaTypeAdapter(value = ValueListAdapter.class) private String[] ids; @XmlAttribute(name = "icons") @XmlJavaTypeAdapter(value = ValueListAdapter.class) private String[] icons; /** * Returns the ProviderName. */ public ProviderName getName() { return name; } /** * Returns the mapped ids. */ public String[] getIds() { return ids; } /** * Returns the mapped icons. */ public String[] getIcons() { return icons; } }
openhab/openhab
bundles/binding/org.openhab.binding.weather/src/main/java/org/openhab/binding/weather/internal/model/common/CommonIdProvider.java
Java
epl-1.0
1,868
/******************************************************************************* * Copyright (c) 2020 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package com.ibm.ws.ormdiag.example.ejb; import java.util.stream.Stream; import com.ibm.ws.ormdiag.example.jpa.ExampleEntity; import jakarta.ejb.Stateless; import jakarta.persistence.EntityManager; import jakarta.persistence.PersistenceContext; @Stateless public class ExampleEJBService { @PersistenceContext private EntityManager em; public void addEntity(ExampleEntity entity) { em.merge(entity); } public Stream<ExampleEntity> retrieveAllEntities() { return em.createNamedQuery("findAllEntities", ExampleEntity.class).getResultStream(); } }
OpenLiberty/open-liberty
dev/com.ibm.ws.jpa.tests.ormdiagnostics_3.0_fat/test-applications/example/src/com/ibm/ws/ormdiag/example/ejb/ExampleEJBService.java
Java
epl-1.0
1,124
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.myfaces.view.facelets.compiler; import javax.faces.view.facelets.FaceletHandler; import org.apache.myfaces.view.facelets.tag.composite.CompositeComponentDefinitionTagHandler; /** * This compilation unit is used to wrap cc:interface and cc:implementation in * a base handler, to allow proper handling of composite component metadata. * * @author Leonardo Uribe (latest modification by $Author: bommel $) * @version $Revision: 1187701 $ $Date: 2011-10-22 12:21:54 +0000 (Sat, 22 Oct 2011) $ */ class CompositeComponentUnit extends CompilationUnit { public CompositeComponentUnit() { } public FaceletHandler createFaceletHandler() { return new CompositeComponentDefinitionTagHandler(this.getNextFaceletHandler()); } }
OpenLiberty/open-liberty
dev/com.ibm.ws.jsf.2.2/src/org/apache/myfaces/view/facelets/compiler/CompositeComponentUnit.java
Java
epl-1.0
1,587
/******************************************************************************* * Copyright (c) 2004-2010 Sunil Kamath (IcemanK). * All rights reserved. * This program is made available under the terms of the Common Public License * v1.0 which is available at http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Sunil Kamath (IcemanK) - initial API and implementation *******************************************************************************/ package net.sf.eclipsensis.installoptions.model; import net.sf.eclipsensis.installoptions.ini.INISection; public class InstallOptionsPassword extends InstallOptionsText { private static final long serialVersionUID = -8185800757229481950L; protected InstallOptionsPassword(INISection section) { super(section); } @Override public String getType() { return InstallOptionsModel.TYPE_PASSWORD; } @Override protected String getDefaultState() { return ""; //$NON-NLS-1$ } }
chrismathis/eclipsensis
plugins/net.sf.eclipsensis.installoptions/src/net/sf/eclipsensis/installoptions/model/InstallOptionsPassword.java
Java
epl-1.0
1,051
/** * Copyright (c) 2010-2021 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.insteon.internal.message; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.Map; import java.util.TreeSet; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.Nullable; import org.openhab.binding.insteon.internal.device.InsteonAddress; import org.openhab.binding.insteon.internal.utils.Utils; import org.openhab.binding.insteon.internal.utils.Utils.ParsingException; import org.osgi.framework.FrameworkUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Contains an Insteon Message consisting of the raw data, and the message definition. * For more info, see the public Insteon Developer's Guide, 2nd edition, * and the Insteon Modem Developer's Guide. * * @author Bernd Pfrommer - Initial contribution * @author Daniel Pfrommer - openHAB 1 insteonplm binding * @author Rob Nielsen - Port to openHAB 2 insteon binding */ @NonNullByDefault public class Msg { private static final Logger logger = LoggerFactory.getLogger(Msg.class); /** * Represents the direction of the message from the host's view. * The host is the machine to which the modem is attached. */ public enum Direction { TO_MODEM("TO_MODEM"), FROM_MODEM("FROM_MODEM"); private static Map<String, Direction> map = new HashMap<>(); private String directionString; static { map.put(TO_MODEM.getDirectionString(), TO_MODEM); map.put(FROM_MODEM.getDirectionString(), FROM_MODEM); } Direction(String dirString) { this.directionString = dirString; } public String getDirectionString() { return directionString; } public static Direction getDirectionFromString(String dir) { Direction direction = map.get(dir); if (direction != null) { return direction; } else { throw new IllegalArgumentException("Unable to find direction for " + dir); } } } // has the structure of all known messages private static final Map<String, Msg> MSG_MAP = new HashMap<>(); // maps between command number and the length of the header private static final Map<Integer, Integer> HEADER_MAP = new HashMap<>(); // has templates for all message from modem to host private static final Map<Integer, Msg> REPLY_MAP = new HashMap<>(); private int headerLength = -1; private byte[] data; private MsgDefinition definition = new MsgDefinition(); private Direction direction = Direction.TO_MODEM; private long quietTime = 0; /** * Constructor * * @param headerLength length of message header (in bytes) * @param data byte array with message * @param dataLength length of byte array data (in bytes) * @param dir direction of the message (from/to modem) */ public Msg(int headerLength, byte[] data, int dataLength, Direction dir) { this.headerLength = headerLength; this.direction = dir; this.data = new byte[dataLength]; System.arraycopy(data, 0, this.data, 0, dataLength); } /** * Copy constructor, needed to make a copy of the templates when * generating messages from them. * * @param m the message to make a copy of */ public Msg(Msg m) { headerLength = m.headerLength; data = m.data.clone(); // the message definition usually doesn't change, but just to be sure... definition = new MsgDefinition(m.definition); direction = m.direction; } static { // Use xml msg loader to load configs try { InputStream stream = FrameworkUtil.getBundle(Msg.class).getResource("/msg_definitions.xml").openStream(); if (stream != null) { Map<String, Msg> msgs = XMLMessageReader.readMessageDefinitions(stream); MSG_MAP.putAll(msgs); } else { logger.warn("could not get message definition resource!"); } } catch (IOException e) { logger.warn("i/o error parsing xml insteon message definitions", e); } catch (ParsingException e) { logger.warn("parse error parsing xml insteon message definitions", e); } catch (FieldException e) { logger.warn("got field exception while parsing xml insteon message definitions", e); } buildHeaderMap(); buildLengthMap(); } // // ------------------ simple getters and setters ----------------- // /** * Experience has shown that if Insteon messages are sent in close succession, * only the first one will make it. The quiet time parameter says how long to * wait after a message before the next one can be sent. * * @return the time (in milliseconds) to pause after message has been sent */ public long getQuietTime() { return quietTime; } public byte @Nullable [] getData() { return data; } public int getLength() { return data.length; } public int getHeaderLength() { return headerLength; } public Direction getDirection() { return direction; } public MsgDefinition getDefinition() { return definition; } public byte getCommandNumber() { return data.length < 2 ? -1 : data[1]; } public boolean isPureNack() { return data.length == 2 && data[1] == 0x15; } public boolean isExtended() { if (getLength() < 2) { return false; } if (!definition.containsField("messageFlags")) { return (false); } try { byte flags = getByte("messageFlags"); return ((flags & 0x10) == 0x10); } catch (FieldException e) { // do nothing } return false; } public boolean isUnsolicited() { // if the message has an ACK/NACK, it is in response to our message, // otherwise it is out-of-band, i.e. unsolicited return !definition.containsField("ACK/NACK"); } public boolean isEcho() { return isPureNack() || !isUnsolicited(); } public boolean isOfType(MsgType mt) { try { MsgType t = MsgType.fromValue(getByte("messageFlags")); return (t == mt); } catch (FieldException e) { return false; } } public boolean isBroadcast() { return isOfType(MsgType.ALL_LINK_BROADCAST) || isOfType(MsgType.BROADCAST); } public boolean isCleanup() { return isOfType(MsgType.ALL_LINK_CLEANUP); } public boolean isAllLink() { return isOfType(MsgType.ALL_LINK_BROADCAST) || isOfType(MsgType.ALL_LINK_CLEANUP); } public boolean isAckOfDirect() { return isOfType(MsgType.ACK_OF_DIRECT); } public boolean isAllLinkCleanupAckOrNack() { return isOfType(MsgType.ALL_LINK_CLEANUP_ACK) || isOfType(MsgType.ALL_LINK_CLEANUP_NACK); } public boolean isX10() { try { int cmd = getByte("Cmd") & 0xff; if (cmd == 0x63 || cmd == 0x52) { return true; } } catch (FieldException e) { } return false; } public void setDefinition(MsgDefinition d) { definition = d; } public void setQuietTime(long t) { quietTime = t; } public void addField(Field f) { definition.addField(f); } public @Nullable InsteonAddress getAddr(String name) { @Nullable InsteonAddress a = null; try { a = definition.getField(name).getAddress(data); } catch (FieldException e) { // do nothing, we'll return null } return a; } public int getHopsLeft() throws FieldException { int hops = (getByte("messageFlags") & 0x0c) >> 2; return hops; } /** * Will put a byte at the specified key * * @param key the string key in the message definition * @param value the byte to put */ public void setByte(@Nullable String key, byte value) throws FieldException { Field f = definition.getField(key); f.setByte(data, value); } /** * Will put an int at the specified field key * * @param key the name of the field * @param value the int to put */ public void setInt(String key, int value) throws FieldException { Field f = definition.getField(key); f.setInt(data, value); } /** * Will put address bytes at the field * * @param key the name of the field * @param adr the address to put */ public void setAddress(String key, InsteonAddress adr) throws FieldException { Field f = definition.getField(key); f.setAddress(data, adr); } /** * Will fetch a byte * * @param key the name of the field * @return the byte */ public byte getByte(String key) throws FieldException { return (definition.getField(key).getByte(data)); } /** * Will fetch a byte array starting at a certain field * * @param key the name of the first field * @param number of bytes to get * @return the byte array */ public byte[] getBytes(String key, int numBytes) throws FieldException { int offset = definition.getField(key).getOffset(); if (offset < 0 || offset + numBytes > data.length) { throw new FieldException("data index out of bounds!"); } byte[] section = new byte[numBytes]; byte[] data = this.data; System.arraycopy(data, offset, section, 0, numBytes); return section; } /** * Will fetch address from field * * @param field the filed name to fetch * @return the address */ public InsteonAddress getAddress(String field) throws FieldException { return (definition.getField(field).getAddress(data)); } /** * Fetch 3-byte (24bit) from message * * @param key1 the key of the msb * @param key2 the key of the second msb * @param key3 the key of the lsb * @return the integer */ public int getInt24(String key1, String key2, String key3) throws FieldException { int i = (definition.getField(key1).getByte(data) << 16) & (definition.getField(key2).getByte(data) << 8) & definition.getField(key3).getByte(data); return i; } public String toHexString() { return Utils.getHexString(data); } /** * Sets the userData fields from a byte array * * @param data */ public void setUserData(byte[] arg) { byte[] data = Arrays.copyOf(arg, 14); // appends zeros if short try { setByte("userData1", data[0]); setByte("userData2", data[1]); setByte("userData3", data[2]); setByte("userData4", data[3]); setByte("userData5", data[4]); setByte("userData6", data[5]); setByte("userData7", data[6]); setByte("userData8", data[7]); setByte("userData9", data[8]); setByte("userData10", data[9]); setByte("userData11", data[10]); setByte("userData12", data[11]); setByte("userData13", data[12]); setByte("userData14", data[13]); } catch (FieldException e) { logger.warn("got field exception on msg {}:", e.getMessage()); } } /** * Calculate and set the CRC with the older 1-byte method * * @return the calculated crc */ public int setCRC() { int crc; try { crc = getByte("command1") + getByte("command2"); byte[] bytes = getBytes("userData1", 13); // skip userData14! for (byte b : bytes) { crc += b; } crc = ((~crc) + 1) & 0xFF; setByte("userData14", (byte) (crc & 0xFF)); } catch (FieldException e) { logger.warn("got field exception on msg {}:", this, e); crc = 0; } return crc; } /** * Calculate and set the CRC with the newer 2-byte method * * @return the calculated crc */ public int setCRC2() { int crc = 0; try { byte[] bytes = getBytes("command1", 14); for (int loop = 0; loop < bytes.length; loop++) { int b = bytes[loop] & 0xFF; for (int bit = 0; bit < 8; bit++) { int fb = b & 0x01; if ((crc & 0x8000) == 0) { fb = fb ^ 0x01; } if ((crc & 0x4000) == 0) { fb = fb ^ 0x01; } if ((crc & 0x1000) == 0) { fb = fb ^ 0x01; } if ((crc & 0x0008) == 0) { fb = fb ^ 0x01; } crc = ((crc << 1) | fb) & 0xFFFF; b = b >> 1; } } setByte("userData13", (byte) ((crc >> 8) & 0xFF)); setByte("userData14", (byte) (crc & 0xFF)); } catch (FieldException e) { logger.warn("got field exception on msg {}:", this, e); crc = 0; } return crc; } @Override public String toString() { String s = (direction == Direction.TO_MODEM) ? "OUT:" : "IN:"; // need to first sort the fields by offset Comparator<Field> cmp = new Comparator<Field>() { @Override public int compare(Field f1, Field f2) { return f1.getOffset() - f2.getOffset(); } }; TreeSet<Field> fields = new TreeSet<>(cmp); for (Field f : definition.getFields().values()) { fields.add(f); } for (Field f : fields) { if (f.getName().equals("messageFlags")) { byte b; try { b = f.getByte(data); MsgType t = MsgType.fromValue(b); s += f.toString(data) + "=" + t.toString() + ":" + (b & 0x03) + ":" + ((b & 0x0c) >> 2) + "|"; } catch (FieldException e) { logger.warn("toString error: ", e); } catch (IllegalArgumentException e) { logger.warn("toString msg type error: ", e); } } else { s += f.toString(data) + "|"; } } return s; } /** * Factory method to create Msg from raw byte stream received from the * serial port. * * @param buf the raw received bytes * @param msgLen length of received buffer * @param isExtended whether it is an extended message or not * @return message, or null if the Msg cannot be created */ public static @Nullable Msg createMessage(byte[] buf, int msgLen, boolean isExtended) { if (buf.length < 2) { return null; } Msg template = REPLY_MAP.get(cmdToKey(buf[1], isExtended)); if (template == null) { return null; // cannot find lookup map } if (msgLen != template.getLength()) { logger.warn("expected msg {} len {}, got {}", template.getCommandNumber(), template.getLength(), msgLen); return null; } Msg msg = new Msg(template.getHeaderLength(), buf, msgLen, Direction.FROM_MODEM); msg.setDefinition(template.getDefinition()); return (msg); } /** * Finds the header length from the insteon command in the received message * * @param cmd the insteon command received in the message * @return the length of the header to expect */ public static int getHeaderLength(byte cmd) { Integer len = HEADER_MAP.get((int) cmd); if (len == null) { return (-1); // not found } return len; } /** * Tries to determine the length of a received Insteon message. * * @param b Insteon message command received * @param isExtended flag indicating if it is an extended message * @return message length, or -1 if length cannot be determined */ public static int getMessageLength(byte b, boolean isExtended) { int key = cmdToKey(b, isExtended); Msg msg = REPLY_MAP.get(key); if (msg == null) { return -1; } return msg.getLength(); } /** * From bytes received thus far, tries to determine if an Insteon * message is extended or standard. * * @param buf the received bytes * @param len the number of bytes received so far * @param headerLength the known length of the header * @return true if it is definitely extended, false if cannot be * determined or if it is a standard message */ public static boolean isExtended(byte[] buf, int len, int headerLength) { if (headerLength <= 2) { return false; } // extended messages are longer if (len < headerLength) { return false; } // not enough data to tell if extended byte flags = buf[headerLength - 1]; // last byte says flags boolean isExtended = (flags & 0x10) == 0x10; // bit 4 is the message return (isExtended); } /** * Creates Insteon message (for sending) of a given type * * @param type the type of message to create, as defined in the xml file * @return reference to message created * @throws IOException if there is no such message type known */ public static Msg makeMessage(String type) throws InvalidMessageTypeException { Msg m = MSG_MAP.get(type); if (m == null) { throw new InvalidMessageTypeException("unknown message type: " + type); } return new Msg(m); } private static int cmdToKey(byte cmd, boolean isExtended) { return (cmd + (isExtended ? 256 : 0)); } private static void buildHeaderMap() { for (Msg m : MSG_MAP.values()) { if (m.getDirection() == Direction.FROM_MODEM) { HEADER_MAP.put((int) m.getCommandNumber(), m.getHeaderLength()); } } } private static void buildLengthMap() { for (Msg m : MSG_MAP.values()) { if (m.getDirection() == Direction.FROM_MODEM) { int key = cmdToKey(m.getCommandNumber(), m.isExtended()); REPLY_MAP.put(key, m); } } } }
paulianttila/openhab2
bundles/org.openhab.binding.insteon/src/main/java/org/openhab/binding/insteon/internal/message/Msg.java
Java
epl-1.0
19,302
/******************************************************************************* * Copyright (c) 2016, 2021 Eurotech and/or its affiliates and others * * This program and the accompanying materials are made * available under the terms of the Eclipse Public License 2.0 * which is available at https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 * * Contributors: * Eurotech - initial API and implementation * Red Hat Inc *******************************************************************************/ package org.eclipse.kapua.message.internal; import org.eclipse.kapua.message.KapuaPayload; import java.util.HashMap; import java.util.Map; /** * {@link KapuaPayload} implementation. * * @since 1.0.0 */ public class KapuaPayloadImpl implements KapuaPayload { private Map<String, Object> metrics; private byte[] body; /** * Constructor */ public KapuaPayloadImpl() { } @Override public Map<String, Object> getMetrics() { if (metrics == null) { metrics = new HashMap<>(); } return metrics; } @Override public void setMetrics(Map<String, Object> metrics) { this.metrics = metrics; } @Override public byte[] getBody() { return body; } @Override public void setBody(byte[] body) { this.body = body; } }
stzilli/kapua
message/internal/src/main/java/org/eclipse/kapua/message/internal/KapuaPayloadImpl.java
Java
epl-1.0
1,395
/******************************************************************************* * Copyright (c) 2021 Eurotech and/or its affiliates and others * * This program and the accompanying materials are made * available under the terms of the Eclipse Public License 2.0 * which is available at https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 * * Contributors: * Eurotech - initial API and implementation *******************************************************************************/ package org.eclipse.kapua.service.authorization.access.shiro; import org.eclipse.kapua.qa.markers.junit.JUnitTests; import org.junit.Assert; import org.junit.Test; import org.junit.experimental.categories.Category; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; @Category(JUnitTests.class) public class AccessRoleCacheFactoryTest extends Assert { @Test public void accessRoleCacheFactoryTest() throws Exception { Constructor<AccessRoleCacheFactory> accessRoleCacheFactory = AccessRoleCacheFactory.class.getDeclaredConstructor(); accessRoleCacheFactory.setAccessible(true); accessRoleCacheFactory.newInstance(); assertTrue("True expected.", Modifier.isPrivate(accessRoleCacheFactory.getModifiers())); } @Test public void getInstanceTest() { assertTrue("True expected.", AccessRoleCacheFactory.getInstance() instanceof AccessRoleCacheFactory); assertEquals("Expected and actual values should be the same.", "AccessRoleId", AccessRoleCacheFactory.getInstance().getEntityIdCacheName()); } }
stzilli/kapua
service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/access/shiro/AccessRoleCacheFactoryTest.java
Java
epl-1.0
1,610
/* * Copyright (C) 2004, 2005, 2007, 2008 Nikolas Zimmermann <zimmermann@kde.org> * Copyright (C) 2004, 2005, 2006, 2007, 2008 Rob Buis <buis@kde.org> * Copyright (C) Research In Motion Limited 2009-2010. All rights reserved. * Copyright (C) 2011 Dirk Schulze <krit@webkit.org> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "config.h" #include "RenderSVGResourceClipper.h" #include "ElementIterator.h" #include "Frame.h" #include "FrameView.h" #include "HitTestRequest.h" #include "HitTestResult.h" #include "IntRect.h" #include "RenderObject.h" #include "RenderStyle.h" #include "RenderView.h" #include "SVGNames.h" #include "SVGRenderingContext.h" #include "SVGResources.h" #include "SVGResourcesCache.h" #include "SVGUseElement.h" namespace WebCore { RenderSVGResourceClipper::RenderSVGResourceClipper(SVGClipPathElement& element, RenderStyle&& style) : RenderSVGResourceContainer(element, WTFMove(style)) { } RenderSVGResourceClipper::~RenderSVGResourceClipper() { } void RenderSVGResourceClipper::removeAllClientsFromCache(bool markForInvalidation) { m_clipBoundaries = FloatRect(); m_clipper.clear(); markAllClientsForInvalidation(markForInvalidation ? LayoutAndBoundariesInvalidation : ParentOnlyInvalidation); } void RenderSVGResourceClipper::removeClientFromCache(RenderElement& client, bool markForInvalidation) { m_clipper.remove(&client); markClientForInvalidation(client, markForInvalidation ? BoundariesInvalidation : ParentOnlyInvalidation); } bool RenderSVGResourceClipper::applyResource(RenderElement& renderer, const RenderStyle&, GraphicsContext*& context, unsigned short resourceMode) { ASSERT(context); ASSERT_UNUSED(resourceMode, resourceMode == ApplyToDefaultMode); return applyClippingToContext(renderer, renderer.objectBoundingBox(), renderer.repaintRectInLocalCoordinates(), *context); } bool RenderSVGResourceClipper::pathOnlyClipping(GraphicsContext& context, const AffineTransform& animatedLocalTransform, const FloatRect& objectBoundingBox) { // If the current clip-path gets clipped itself, we have to fallback to masking. if (!style().svgStyle().clipperResource().isEmpty()) return false; WindRule clipRule = RULE_NONZERO; Path clipPath = Path(); // If clip-path only contains one visible shape or path, we can use path-based clipping. Invisible // shapes don't affect the clipping and can be ignored. If clip-path contains more than one // visible shape, the additive clipping may not work, caused by the clipRule. EvenOdd // as well as NonZero can cause self-clipping of the elements. // See also http://www.w3.org/TR/SVG/painting.html#FillRuleProperty for (Node* childNode = clipPathElement().firstChild(); childNode; childNode = childNode->nextSibling()) { RenderObject* renderer = childNode->renderer(); if (!renderer) continue; // Only shapes or paths are supported for direct clipping. We need to fallback to masking for texts. if (renderer->isSVGText()) return false; if (!childNode->isSVGElement() || !downcast<SVGElement>(*childNode).isSVGGraphicsElement()) continue; SVGGraphicsElement& styled = downcast<SVGGraphicsElement>(*childNode); const RenderStyle& style = renderer->style(); if (style.display() == NONE || style.visibility() != VISIBLE) continue; const SVGRenderStyle& svgStyle = style.svgStyle(); // Current shape in clip-path gets clipped too. Fallback to masking. if (!svgStyle.clipperResource().isEmpty()) return false; // Fallback to masking, if there is more than one clipping path. if (clipPath.isEmpty()) { styled.toClipPath(clipPath); clipRule = svgStyle.clipRule(); } else return false; } // Only one visible shape/path was found. Directly continue clipping and transform the content to userspace if necessary. if (clipPathElement().clipPathUnits() == SVGUnitTypes::SVG_UNIT_TYPE_OBJECTBOUNDINGBOX) { AffineTransform transform; transform.translate(objectBoundingBox.x(), objectBoundingBox.y()); transform.scaleNonUniform(objectBoundingBox.width(), objectBoundingBox.height()); clipPath.transform(transform); } // Transform path by animatedLocalTransform. clipPath.transform(animatedLocalTransform); // The SVG specification wants us to clip everything, if clip-path doesn't have a child. if (clipPath.isEmpty()) clipPath.addRect(FloatRect()); context.clipPath(clipPath, clipRule); return true; } bool RenderSVGResourceClipper::applyClippingToContext(RenderElement& renderer, const FloatRect& objectBoundingBox, const FloatRect& repaintRect, GraphicsContext& context) { ClipperMaskImage& clipperMaskImage = addRendererToClipper(renderer); bool shouldCreateClipperMaskImage = !clipperMaskImage; AffineTransform animatedLocalTransform = clipPathElement().animatedLocalTransform(); if (shouldCreateClipperMaskImage && pathOnlyClipping(context, animatedLocalTransform, objectBoundingBox)) return true; AffineTransform absoluteTransform = SVGRenderingContext::calculateTransformationToOutermostCoordinateSystem(renderer); if (shouldCreateClipperMaskImage && !repaintRect.isEmpty()) { // FIXME (149469): This image buffer should not be unconditionally unaccelerated. Making it match the context breaks nested clipping, though. clipperMaskImage = SVGRenderingContext::createImageBuffer(repaintRect, absoluteTransform, ColorSpaceSRGB, Unaccelerated); if (!clipperMaskImage) return false; GraphicsContext& maskContext = clipperMaskImage->context(); maskContext.concatCTM(animatedLocalTransform); // clipPath can also be clipped by another clipPath. auto* resources = SVGResourcesCache::cachedResourcesForRenderer(*this); RenderSVGResourceClipper* clipper; bool succeeded; if (resources && (clipper = resources->clipper())) { GraphicsContextStateSaver stateSaver(maskContext); if (!clipper->applyClippingToContext(*this, objectBoundingBox, repaintRect, maskContext)) return false; succeeded = drawContentIntoMaskImage(clipperMaskImage, objectBoundingBox); // The context restore applies the clipping on non-CG platforms. } else succeeded = drawContentIntoMaskImage(clipperMaskImage, objectBoundingBox); if (!succeeded) clipperMaskImage.reset(); } if (!clipperMaskImage) return false; SVGRenderingContext::clipToImageBuffer(context, absoluteTransform, repaintRect, clipperMaskImage, shouldCreateClipperMaskImage); return true; } bool RenderSVGResourceClipper::drawContentIntoMaskImage(const ClipperMaskImage& clipperMaskImage, const FloatRect& objectBoundingBox) { ASSERT(clipperMaskImage); GraphicsContext& maskContext = clipperMaskImage->context(); AffineTransform maskContentTransformation; if (clipPathElement().clipPathUnits() == SVGUnitTypes::SVG_UNIT_TYPE_OBJECTBOUNDINGBOX) { maskContentTransformation.translate(objectBoundingBox.x(), objectBoundingBox.y()); maskContentTransformation.scaleNonUniform(objectBoundingBox.width(), objectBoundingBox.height()); maskContext.concatCTM(maskContentTransformation); } // Switch to a paint behavior where all children of this <clipPath> will be rendered using special constraints: // - fill-opacity/stroke-opacity/opacity set to 1 // - masker/filter not applied when rendering the children // - fill is set to the initial fill paint server (solid, black) // - stroke is set to the initial stroke paint server (none) PaintBehavior oldBehavior = view().frameView().paintBehavior(); view().frameView().setPaintBehavior(oldBehavior | PaintBehaviorRenderingSVGMask); // Draw all clipPath children into a global mask. for (auto& child : childrenOfType<SVGElement>(clipPathElement())) { auto renderer = child.renderer(); if (!renderer) continue; if (renderer->needsLayout()) { view().frameView().setPaintBehavior(oldBehavior); return false; } const RenderStyle& style = renderer->style(); if (style.display() == NONE || style.visibility() != VISIBLE) continue; WindRule newClipRule = style.svgStyle().clipRule(); bool isUseElement = child.hasTagName(SVGNames::useTag); if (isUseElement) { SVGUseElement& useElement = downcast<SVGUseElement>(child); renderer = useElement.rendererClipChild(); if (!renderer) continue; if (!useElement.hasAttributeWithoutSynchronization(SVGNames::clip_ruleAttr)) newClipRule = renderer->style().svgStyle().clipRule(); } // Only shapes, paths and texts are allowed for clipping. if (!renderer->isSVGShape() && !renderer->isSVGText()) continue; maskContext.setFillRule(newClipRule); // In the case of a <use> element, we obtained its renderere above, to retrieve its clipRule. // We have to pass the <use> renderer itself to renderSubtreeToImageBuffer() to apply it's x/y/transform/etc. values when rendering. // So if isUseElement is true, refetch the childNode->renderer(), as renderer got overriden above. SVGRenderingContext::renderSubtreeToImageBuffer(clipperMaskImage.get(), isUseElement ? *child.renderer() : *renderer, maskContentTransformation); } view().frameView().setPaintBehavior(oldBehavior); return true; } void RenderSVGResourceClipper::calculateClipContentRepaintRect() { // This is a rough heuristic to appraise the clip size and doesn't consider clip on clip. for (Node* childNode = clipPathElement().firstChild(); childNode; childNode = childNode->nextSibling()) { RenderObject* renderer = childNode->renderer(); if (!childNode->isSVGElement() || !renderer) continue; if (!renderer->isSVGShape() && !renderer->isSVGText() && !childNode->hasTagName(SVGNames::useTag)) continue; const RenderStyle& style = renderer->style(); if (style.display() == NONE || style.visibility() != VISIBLE) continue; m_clipBoundaries.unite(renderer->localToParentTransform().mapRect(renderer->repaintRectInLocalCoordinates())); } m_clipBoundaries = clipPathElement().animatedLocalTransform().mapRect(m_clipBoundaries); } ClipperMaskImage& RenderSVGResourceClipper::addRendererToClipper(const RenderObject& object) { return m_clipper.add(&object, ClipperMaskImage()).iterator->value; } bool RenderSVGResourceClipper::hitTestClipContent(const FloatRect& objectBoundingBox, const FloatPoint& nodeAtPoint) { FloatPoint point = nodeAtPoint; if (!SVGRenderSupport::pointInClippingArea(*this, point)) return false; if (clipPathElement().clipPathUnits() == SVGUnitTypes::SVG_UNIT_TYPE_OBJECTBOUNDINGBOX) { AffineTransform transform; transform.translate(objectBoundingBox.x(), objectBoundingBox.y()); transform.scaleNonUniform(objectBoundingBox.width(), objectBoundingBox.height()); point = transform.inverse().value_or(AffineTransform()).mapPoint(point); } point = clipPathElement().animatedLocalTransform().inverse().value_or(AffineTransform()).mapPoint(point); for (Node* childNode = clipPathElement().firstChild(); childNode; childNode = childNode->nextSibling()) { RenderObject* renderer = childNode->renderer(); if (!childNode->isSVGElement() || !renderer) continue; if (!renderer->isSVGShape() && !renderer->isSVGText() && !childNode->hasTagName(SVGNames::useTag)) continue; IntPoint hitPoint; HitTestResult result(hitPoint); if (renderer->nodeAtFloatPoint(HitTestRequest(HitTestRequest::SVGClipContent | HitTestRequest::DisallowUserAgentShadowContent), result, point, HitTestForeground)) return true; } return false; } FloatRect RenderSVGResourceClipper::resourceBoundingBox(const RenderObject& object) { // Resource was not layouted yet. Give back the boundingBox of the object. if (selfNeedsLayout()) { addRendererToClipper(object); return object.objectBoundingBox(); } if (m_clipBoundaries.isEmpty()) calculateClipContentRepaintRect(); if (clipPathElement().clipPathUnits() == SVGUnitTypes::SVG_UNIT_TYPE_OBJECTBOUNDINGBOX) { FloatRect objectBoundingBox = object.objectBoundingBox(); AffineTransform transform; transform.translate(objectBoundingBox.x(), objectBoundingBox.y()); transform.scaleNonUniform(objectBoundingBox.width(), objectBoundingBox.height()); return transform.mapRect(m_clipBoundaries); } return m_clipBoundaries; } }
Debian/openjfx
modules/web/src/main/native/Source/WebCore/rendering/svg/RenderSVGResourceClipper.cpp
C++
gpl-2.0
13,796
/* * Copyright © 2011, Petro Protsyk, Denys Vuika * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Scripting.SSharp.Execution.Compilers.Dom { internal abstract class CodeStatement : CodeObject { } }
Myvar/eStd
eStd/System.Scripting/Engines/SSharp/Execution/Compilers/Dom/CodeStatement.cs
C#
gpl-2.0
735
/*************************************************************************** qgswmsgetmap.h ------------------------- begin : December 20 , 2016 copyright : (C) 2007 by Marco Hugentobler (original code) (C) 2014 by Alessandro Pasotti (original code) (C) 2016 by David Marteau email : marco dot hugentobler at karto dot baug dot ethz dot ch a dot pasotti at itopen dot it david dot marteau at 3liz dot com ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "qgswmsutils.h" #include "qgswmsgetcapabilities.h" #include "qgsserverprojectutils.h" #include "qgslayoutmanager.h" #include "qgsprintlayout.h" #include "qgslayoutitemmap.h" #include "qgslayoutitemlabel.h" #include "qgslayoutitemhtml.h" #include "qgslayoutframe.h" #include "qgslayoutpagecollection.h" #include "qgslayertreenode.h" #include "qgslayertreegroup.h" #include "qgslayertreelayer.h" #include "qgslayertreemodel.h" #include "qgslayertree.h" #include "qgsmaplayerstylemanager.h" #include "qgsexception.h" #include "qgsexpressionnodeimpl.h" #include "qgsvectorlayer.h" namespace QgsWms { namespace { void appendLayerProjectSettings( QDomDocument &doc, QDomElement &layerElem, QgsMapLayer *currentLayer ); void appendDrawingOrder( QDomDocument &doc, QDomElement &parentElem, QgsServerInterface *serverIface, const QgsProject *project ); void combineExtentAndCrsOfGroupChildren( QDomDocument &doc, QDomElement &groupElem, const QgsProject *project, bool considerMapExtent = false ); bool crsSetFromLayerElement( const QDomElement &layerElement, QSet<QString> &crsSet ); QgsRectangle layerBoundingBoxInProjectCrs( const QDomDocument &doc, const QDomElement &layerElem, const QgsProject *project ); void appendLayerBoundingBox( QDomDocument &doc, QDomElement &layerElem, const QgsRectangle &layerExtent, const QgsCoordinateReferenceSystem &layerCRS, const QString &crsText, const QgsProject *project ); void appendLayerBoundingBoxes( QDomDocument &doc, QDomElement &layerElem, const QgsRectangle &lExtent, const QgsCoordinateReferenceSystem &layerCRS, const QStringList &crsList, const QStringList &constrainedCrsList, const QgsProject *project ); void appendCrsElementToLayer( QDomDocument &doc, QDomElement &layerElement, const QDomElement &precedingElement, const QString &crsText ); void appendCrsElementsToLayer( QDomDocument &doc, QDomElement &layerElement, const QStringList &crsList, const QStringList &constrainedCrsList ); void appendLayerStyles( QDomDocument &doc, QDomElement &layerElem, QgsMapLayer *currentLayer, const QgsProject *project, const QString &version, const QgsServerRequest &request ); void appendLayersFromTreeGroup( QDomDocument &doc, QDomElement &parentLayer, QgsServerInterface *serverIface, const QgsProject *project, const QString &version, const QgsServerRequest &request, const QgsLayerTreeGroup *layerTreeGroup, bool projectSettings ); void addKeywordListElement( const QgsProject *project, QDomDocument &doc, QDomElement &parent ); } void writeGetCapabilities( QgsServerInterface *serverIface, const QgsProject *project, const QString &version, const QgsServerRequest &request, QgsServerResponse &response, bool projectSettings ) { QgsAccessControl *accessControl = serverIface->accessControls(); QDomDocument doc; const QDomDocument *capabilitiesDocument = nullptr; // Data for WMS capabilities server memory cache QString configFilePath = serverIface->configFilePath(); QgsCapabilitiesCache *capabilitiesCache = serverIface->capabilitiesCache(); QStringList cacheKeyList; cacheKeyList << ( projectSettings ? QStringLiteral( "projectSettings" ) : version ); cacheKeyList << request.url().host(); bool cache = true; if ( accessControl ) cache = accessControl->fillCacheKey( cacheKeyList ); QString cacheKey = cacheKeyList.join( '-' ); QgsServerCacheManager *cacheManager = serverIface->cacheManager(); if ( cacheManager && cacheManager->getCachedDocument( &doc, project, request, accessControl ) ) { capabilitiesDocument = &doc; } if ( !capabilitiesDocument && cache ) //capabilities xml not in cache plugins { capabilitiesDocument = capabilitiesCache->searchCapabilitiesDocument( configFilePath, cacheKey ); } if ( !capabilitiesDocument ) //capabilities xml not in cache. Create a new one { QgsMessageLog::logMessage( QStringLiteral( "WMS capabilities document not found in cache" ) ); doc = getCapabilities( serverIface, project, version, request, projectSettings ); if ( cacheManager && cacheManager->setCachedDocument( &doc, project, request, accessControl ) ) { capabilitiesDocument = &doc; } else if ( cache ) { capabilitiesCache->insertCapabilitiesDocument( configFilePath, cacheKey, &doc ); capabilitiesDocument = capabilitiesCache->searchCapabilitiesDocument( configFilePath, cacheKey ); } if ( !capabilitiesDocument ) { capabilitiesDocument = &doc; } else { QgsMessageLog::logMessage( QStringLiteral( "Set WMS capabilities document in cache" ) ); } } else { QgsMessageLog::logMessage( QStringLiteral( "Found WMS capabilities document in cache" ) ); } response.setHeader( QStringLiteral( "Content-Type" ), QStringLiteral( "text/xml; charset=utf-8" ) ); response.write( capabilitiesDocument->toByteArray() ); } QDomDocument getCapabilities( QgsServerInterface *serverIface, const QgsProject *project, const QString &version, const QgsServerRequest &request, bool projectSettings ) { QDomDocument doc; QDomElement wmsCapabilitiesElement; QgsServerRequest::Parameters parameters = request.parameters(); // Get service URL QUrl href = serviceUrl( request, project ); //href needs to be a prefix QString hrefString = href.toString(); hrefString.append( href.hasQuery() ? "&" : "?" ); // XML declaration QDomProcessingInstruction xmlDeclaration = doc.createProcessingInstruction( QStringLiteral( "xml" ), QStringLiteral( "version=\"1.0\" encoding=\"utf-8\"" ) ); // Append format helper std::function < void ( QDomElement &, const QString & ) > appendFormat = [&doc]( QDomElement & elem, const QString & format ) { QDomElement formatElem = doc.createElement( QStringLiteral( "Format" )/*wms:Format*/ ); formatElem.appendChild( doc.createTextNode( format ) ); elem.appendChild( formatElem ); }; if ( version == QLatin1String( "1.1.1" ) ) { doc = QDomDocument( QStringLiteral( "WMT_MS_Capabilities SYSTEM 'http://schemas.opengis.net/wms/1.1.1/WMS_MS_Capabilities.dtd'" ) ); //WMS 1.1.1 needs DOCTYPE "SYSTEM http://schemas.opengis.net/wms/1.1.1/WMS_MS_Capabilities.dtd" doc.appendChild( xmlDeclaration ); wmsCapabilitiesElement = doc.createElement( QStringLiteral( "WMT_MS_Capabilities" )/*wms:WMS_Capabilities*/ ); } else // 1.3.0 as default { doc.appendChild( xmlDeclaration ); wmsCapabilitiesElement = doc.createElement( QStringLiteral( "WMS_Capabilities" )/*wms:WMS_Capabilities*/ ); wmsCapabilitiesElement.setAttribute( QStringLiteral( "xmlns" ), QStringLiteral( "http://www.opengis.net/wms" ) ); wmsCapabilitiesElement.setAttribute( QStringLiteral( "xmlns:sld" ), QStringLiteral( "http://www.opengis.net/sld" ) ); wmsCapabilitiesElement.setAttribute( QStringLiteral( "xmlns:qgs" ), QStringLiteral( "http://www.qgis.org/wms" ) ); wmsCapabilitiesElement.setAttribute( QStringLiteral( "xmlns:xsi" ), QStringLiteral( "http://www.w3.org/2001/XMLSchema-instance" ) ); QString schemaLocation = QStringLiteral( "http://www.opengis.net/wms" ); schemaLocation += QLatin1String( " http://schemas.opengis.net/wms/1.3.0/capabilities_1_3_0.xsd" ); schemaLocation += QLatin1String( " http://www.opengis.net/sld" ); schemaLocation += QLatin1String( " http://schemas.opengis.net/sld/1.1.0/sld_capabilities.xsd" ); schemaLocation += QLatin1String( " http://www.qgis.org/wms" ); if ( QgsServerProjectUtils::wmsInspireActivate( *project ) ) { wmsCapabilitiesElement.setAttribute( QStringLiteral( "xmlns:inspire_common" ), QStringLiteral( "http://inspire.ec.europa.eu/schemas/common/1.0" ) ); wmsCapabilitiesElement.setAttribute( QStringLiteral( "xmlns:inspire_vs" ), QStringLiteral( "http://inspire.ec.europa.eu/schemas/inspire_vs/1.0" ) ); schemaLocation += QLatin1String( " http://inspire.ec.europa.eu/schemas/inspire_vs/1.0" ); schemaLocation += QLatin1String( " http://inspire.ec.europa.eu/schemas/inspire_vs/1.0/inspire_vs.xsd" ); } schemaLocation += " " + hrefString + "SERVICE=WMS&REQUEST=GetSchemaExtension"; wmsCapabilitiesElement.setAttribute( QStringLiteral( "xsi:schemaLocation" ), schemaLocation ); } wmsCapabilitiesElement.setAttribute( QStringLiteral( "version" ), version ); doc.appendChild( wmsCapabilitiesElement ); //INSERT Service wmsCapabilitiesElement.appendChild( getServiceElement( doc, project, version, request ) ); //wms:Capability element QDomElement capabilityElement = getCapabilityElement( doc, project, version, request, projectSettings ); wmsCapabilitiesElement.appendChild( capabilityElement ); if ( projectSettings ) { //Insert <ComposerTemplate> elements derived from wms:_ExtendedCapabilities capabilityElement.appendChild( getComposerTemplatesElement( doc, project ) ); //WFS layers capabilityElement.appendChild( getWFSLayersElement( doc, project ) ); } capabilityElement.appendChild( getLayersAndStylesCapabilitiesElement( doc, serverIface, project, version, request, projectSettings ) ); if ( projectSettings ) { appendDrawingOrder( doc, capabilityElement, serverIface, project ); } return doc; } QDomElement getServiceElement( QDomDocument &doc, const QgsProject *project, const QString &version, const QgsServerRequest &request ) { //Service element QDomElement serviceElem = doc.createElement( QStringLiteral( "Service" ) ); //Service name QDomElement nameElem = doc.createElement( QStringLiteral( "Name" ) ); QDomText nameText = doc.createTextNode( QStringLiteral( "WMS" ) ); nameElem.appendChild( nameText ); serviceElem.appendChild( nameElem ); QString title = QgsServerProjectUtils::owsServiceTitle( *project ); if ( !title.isEmpty() ) { QDomElement titleElem = doc.createElement( QStringLiteral( "Title" ) ); QDomText titleText = doc.createTextNode( title ); titleElem.appendChild( titleText ); serviceElem.appendChild( titleElem ); } QString abstract = QgsServerProjectUtils::owsServiceAbstract( *project ); if ( !abstract.isEmpty() ) { QDomElement abstractElem = doc.createElement( QStringLiteral( "Abstract" ) ); QDomText abstractText = doc.createCDATASection( abstract ); abstractElem.appendChild( abstractText ); serviceElem.appendChild( abstractElem ); } addKeywordListElement( project, doc, serviceElem ); QString onlineResource = QgsServerProjectUtils::owsServiceOnlineResource( *project ); if ( onlineResource.isEmpty() ) { onlineResource = serviceUrl( request, project ).toString(); } QDomElement onlineResourceElem = doc.createElement( QStringLiteral( "OnlineResource" ) ); onlineResourceElem.setAttribute( QStringLiteral( "xmlns:xlink" ), QStringLiteral( "http://www.w3.org/1999/xlink" ) ); onlineResourceElem.setAttribute( QStringLiteral( "xlink:type" ), QStringLiteral( "simple" ) ); onlineResourceElem.setAttribute( QStringLiteral( "xlink:href" ), onlineResource ); serviceElem.appendChild( onlineResourceElem ); QString contactPerson = QgsServerProjectUtils::owsServiceContactPerson( *project ); QString contactOrganization = QgsServerProjectUtils::owsServiceContactOrganization( *project ); QString contactPosition = QgsServerProjectUtils::owsServiceContactPosition( *project ); QString contactMail = QgsServerProjectUtils::owsServiceContactMail( *project ); QString contactPhone = QgsServerProjectUtils::owsServiceContactPhone( *project ); if ( !contactPerson.isEmpty() || !contactOrganization.isEmpty() || !contactPosition.isEmpty() || !contactMail.isEmpty() || !contactPhone.isEmpty() ) { //Contact information QDomElement contactInfoElem = doc.createElement( QStringLiteral( "ContactInformation" ) ); //Contact person primary if ( !contactPerson.isEmpty() || !contactOrganization.isEmpty() || !contactPosition.isEmpty() ) { QDomElement contactPersonPrimaryElem = doc.createElement( QStringLiteral( "ContactPersonPrimary" ) ); if ( !contactPerson.isEmpty() ) { QDomElement contactPersonElem = doc.createElement( QStringLiteral( "ContactPerson" ) ); QDomText contactPersonText = doc.createTextNode( contactPerson ); contactPersonElem.appendChild( contactPersonText ); contactPersonPrimaryElem.appendChild( contactPersonElem ); } if ( !contactOrganization.isEmpty() ) { QDomElement contactOrganizationElem = doc.createElement( QStringLiteral( "ContactOrganization" ) ); QDomText contactOrganizationText = doc.createTextNode( contactOrganization ); contactOrganizationElem.appendChild( contactOrganizationText ); contactPersonPrimaryElem.appendChild( contactOrganizationElem ); } if ( !contactPosition.isEmpty() ) { QDomElement contactPositionElem = doc.createElement( QStringLiteral( "ContactPosition" ) ); QDomText contactPositionText = doc.createTextNode( contactPosition ); contactPositionElem.appendChild( contactPositionText ); contactPersonPrimaryElem.appendChild( contactPositionElem ); } contactInfoElem.appendChild( contactPersonPrimaryElem ); } if ( !contactPhone.isEmpty() ) { QDomElement phoneElem = doc.createElement( QStringLiteral( "ContactVoiceTelephone" ) ); QDomText phoneText = doc.createTextNode( contactPhone ); phoneElem.appendChild( phoneText ); contactInfoElem.appendChild( phoneElem ); } if ( !contactMail.isEmpty() ) { QDomElement mailElem = doc.createElement( QStringLiteral( "ContactElectronicMailAddress" ) ); QDomText mailText = doc.createTextNode( contactMail ); mailElem.appendChild( mailText ); contactInfoElem.appendChild( mailElem ); } serviceElem.appendChild( contactInfoElem ); } QDomElement feesElem = doc.createElement( QStringLiteral( "Fees" ) ); QDomText feesText = doc.createTextNode( QStringLiteral( "None" ) ); // default value if fees are unknown QString fees = QgsServerProjectUtils::owsServiceFees( *project ); if ( !fees.isEmpty() ) { feesText = doc.createTextNode( fees ); } feesElem.appendChild( feesText ); serviceElem.appendChild( feesElem ); QDomElement accessConstraintsElem = doc.createElement( QStringLiteral( "AccessConstraints" ) ); QDomText accessConstraintsText = doc.createTextNode( QStringLiteral( "None" ) ); // default value if access constraints are unknown QString accessConstraints = QgsServerProjectUtils::owsServiceAccessConstraints( *project ); if ( !accessConstraints.isEmpty() ) { accessConstraintsText = doc.createTextNode( accessConstraints ); } accessConstraintsElem.appendChild( accessConstraintsText ); serviceElem.appendChild( accessConstraintsElem ); if ( version == QLatin1String( "1.3.0" ) ) { int maxWidth = QgsServerProjectUtils::wmsMaxWidth( *project ); if ( maxWidth > 0 ) { QDomElement maxWidthElem = doc.createElement( QStringLiteral( "MaxWidth" ) ); QDomText maxWidthText = doc.createTextNode( QString::number( maxWidth ) ); maxWidthElem.appendChild( maxWidthText ); serviceElem.appendChild( maxWidthElem ); } int maxHeight = QgsServerProjectUtils::wmsMaxHeight( *project ); if ( maxHeight > 0 ) { QDomElement maxHeightElem = doc.createElement( QStringLiteral( "MaxHeight" ) ); QDomText maxHeightText = doc.createTextNode( QString::number( maxHeight ) ); maxHeightElem.appendChild( maxHeightText ); serviceElem.appendChild( maxHeightElem ); } } return serviceElem; } QDomElement getCapabilityElement( QDomDocument &doc, const QgsProject *project, const QString &version, const QgsServerRequest &request, bool projectSettings ) { QgsServerRequest::Parameters parameters = request.parameters(); // Get service URL QUrl href = serviceUrl( request, project ); //href needs to be a prefix QString hrefString = href.toString(); hrefString.append( href.hasQuery() ? "&" : "?" ); QDomElement capabilityElem = doc.createElement( QStringLiteral( "Capability" )/*wms:Capability*/ ); //wms:Request element QDomElement requestElem = doc.createElement( QStringLiteral( "Request" )/*wms:Request*/ ); capabilityElem.appendChild( requestElem ); QDomElement dcpTypeElem = doc.createElement( QStringLiteral( "DCPType" )/*wms:DCPType*/ ); QDomElement httpElem = doc.createElement( QStringLiteral( "HTTP" )/*wms:HTTP*/ ); dcpTypeElem.appendChild( httpElem ); // Append format helper std::function < void ( QDomElement &, const QString & ) > appendFormat = [&doc]( QDomElement & elem, const QString & format ) { QDomElement formatElem = doc.createElement( QStringLiteral( "Format" )/*wms:Format*/ ); formatElem.appendChild( doc.createTextNode( format ) ); elem.appendChild( formatElem ); }; QDomElement elem; //wms:GetCapabilities elem = doc.createElement( QStringLiteral( "GetCapabilities" )/*wms:GetCapabilities*/ ); appendFormat( elem, ( version == QLatin1String( "1.1.1" ) ? "application/vnd.ogc.wms_xml" : "text/xml" ) ); elem.appendChild( dcpTypeElem ); requestElem.appendChild( elem ); // SOAP platform //only give this information if it is not a WMS request to be in sync with the WMS capabilities schema // XXX Not even sure that cam be ever true if ( parameters.value( QStringLiteral( "SERVICE" ) ).compare( QLatin1String( "WMS" ), Qt::CaseInsensitive ) != 0 ) { QDomElement soapElem = doc.createElement( QStringLiteral( "SOAP" )/*wms:SOAP*/ ); httpElem.appendChild( soapElem ); QDomElement soapResourceElem = doc.createElement( QStringLiteral( "OnlineResource" )/*wms:OnlineResource*/ ); soapResourceElem.setAttribute( QStringLiteral( "xmlns:xlink" ), QStringLiteral( "http://www.w3.org/1999/xlink" ) ); soapResourceElem.setAttribute( QStringLiteral( "xlink:type" ), QStringLiteral( "simple" ) ); soapResourceElem.setAttribute( QStringLiteral( "xlink:href" ), hrefString ); soapElem.appendChild( soapResourceElem ); } //only Get supported for the moment QDomElement getElem = doc.createElement( QStringLiteral( "Get" )/*wms:Get*/ ); httpElem.appendChild( getElem ); QDomElement olResourceElem = doc.createElement( QStringLiteral( "OnlineResource" )/*wms:OnlineResource*/ ); olResourceElem.setAttribute( QStringLiteral( "xmlns:xlink" ), QStringLiteral( "http://www.w3.org/1999/xlink" ) ); olResourceElem.setAttribute( QStringLiteral( "xlink:type" ), QStringLiteral( "simple" ) ); olResourceElem.setAttribute( QStringLiteral( "xlink:href" ), hrefString ); getElem.appendChild( olResourceElem ); //wms:GetMap elem = doc.createElement( QStringLiteral( "GetMap" )/*wms:GetMap*/ ); appendFormat( elem, QStringLiteral( "image/jpeg" ) ); appendFormat( elem, QStringLiteral( "image/png" ) ); appendFormat( elem, QStringLiteral( "image/png; mode=16bit" ) ); appendFormat( elem, QStringLiteral( "image/png; mode=8bit" ) ); appendFormat( elem, QStringLiteral( "image/png; mode=1bit" ) ); appendFormat( elem, QStringLiteral( "application/dxf" ) ); elem.appendChild( dcpTypeElem.cloneNode().toElement() ); //this is the same as for 'GetCapabilities' requestElem.appendChild( elem ); //wms:GetFeatureInfo elem = doc.createElement( QStringLiteral( "GetFeatureInfo" ) ); appendFormat( elem, QStringLiteral( "text/plain" ) ); appendFormat( elem, QStringLiteral( "text/html" ) ); appendFormat( elem, QStringLiteral( "text/xml" ) ); appendFormat( elem, QStringLiteral( "application/vnd.ogc.gml" ) ); appendFormat( elem, QStringLiteral( "application/vnd.ogc.gml/3.1.1" ) ); elem.appendChild( dcpTypeElem.cloneNode().toElement() ); //this is the same as for 'GetCapabilities' requestElem.appendChild( elem ); //wms:GetLegendGraphic elem = doc.createElement( ( version == QLatin1String( "1.1.1" ) ? "GetLegendGraphic" : "sld:GetLegendGraphic" )/*wms:GetLegendGraphic*/ ); appendFormat( elem, QStringLiteral( "image/jpeg" ) ); appendFormat( elem, QStringLiteral( "image/png" ) ); elem.appendChild( dcpTypeElem.cloneNode().toElement() ); //this is the same as for 'GetCapabilities' requestElem.appendChild( elem ); //wms:DescribeLayer elem = doc.createElement( ( version == QLatin1String( "1.1.1" ) ? "DescribeLayer" : "sld:DescribeLayer" )/*wms:GetLegendGraphic*/ ); appendFormat( elem, QStringLiteral( "text/xml" ) ); elem.appendChild( dcpTypeElem.cloneNode().toElement() ); //this is the same as for 'GetCapabilities' requestElem.appendChild( elem ); //wms:GetStyles elem = doc.createElement( ( version == QLatin1String( "1.1.1" ) ? "GetStyles" : "qgs:GetStyles" )/*wms:GetStyles*/ ); appendFormat( elem, QStringLiteral( "text/xml" ) ); elem.appendChild( dcpTypeElem.cloneNode().toElement() ); //this is the same as for 'GetCapabilities' requestElem.appendChild( elem ); if ( projectSettings ) //remove composer templates from GetCapabilities in the long term { //wms:GetPrint elem = doc.createElement( QStringLiteral( "GetPrint" ) /*wms:GetPrint*/ ); appendFormat( elem, QStringLiteral( "svg" ) ); appendFormat( elem, QStringLiteral( "png" ) ); appendFormat( elem, QStringLiteral( "pdf" ) ); elem.appendChild( dcpTypeElem.cloneNode().toElement() ); //this is the same as for 'GetCapabilities' requestElem.appendChild( elem ); } //Exception element is mandatory elem = doc.createElement( QStringLiteral( "Exception" ) ); appendFormat( elem, ( version == QLatin1String( "1.1.1" ) ? "application/vnd.ogc.se_xml" : "XML" ) ); capabilityElem.appendChild( elem ); //UserDefinedSymbolization element if ( version == QLatin1String( "1.3.0" ) ) { elem = doc.createElement( QStringLiteral( "sld:UserDefinedSymbolization" ) ); elem.setAttribute( QStringLiteral( "SupportSLD" ), QStringLiteral( "1" ) ); elem.setAttribute( QStringLiteral( "UserLayer" ), QStringLiteral( "0" ) ); elem.setAttribute( QStringLiteral( "UserStyle" ), QStringLiteral( "1" ) ); elem.setAttribute( QStringLiteral( "RemoteWFS" ), QStringLiteral( "0" ) ); elem.setAttribute( QStringLiteral( "InlineFeature" ), QStringLiteral( "0" ) ); elem.setAttribute( QStringLiteral( "RemoteWCS" ), QStringLiteral( "0" ) ); capabilityElem.appendChild( elem ); if ( QgsServerProjectUtils::wmsInspireActivate( *project ) ) { capabilityElem.appendChild( getInspireCapabilitiesElement( doc, project ) ); } } return capabilityElem; } QDomElement getInspireCapabilitiesElement( QDomDocument &doc, const QgsProject *project ) { QDomElement inspireCapabilitiesElem; if ( !QgsServerProjectUtils::wmsInspireActivate( *project ) ) return inspireCapabilitiesElem; inspireCapabilitiesElem = doc.createElement( QStringLiteral( "inspire_vs:ExtendedCapabilities" ) ); QString inspireMetadataUrl = QgsServerProjectUtils::wmsInspireMetadataUrl( *project ); // inspire scenario 1 if ( !inspireMetadataUrl.isEmpty() ) { QDomElement inspireCommonMetadataUrlElem = doc.createElement( QStringLiteral( "inspire_common:MetadataUrl" ) ); inspireCommonMetadataUrlElem.setAttribute( QStringLiteral( "xsi:type" ), QStringLiteral( "inspire_common:resourceLocatorType" ) ); QDomElement inspireCommonMetadataUrlUrlElem = doc.createElement( QStringLiteral( "inspire_common:URL" ) ); inspireCommonMetadataUrlUrlElem.appendChild( doc.createTextNode( inspireMetadataUrl ) ); inspireCommonMetadataUrlElem.appendChild( inspireCommonMetadataUrlUrlElem ); QString inspireMetadataUrlType = QgsServerProjectUtils::wmsInspireMetadataUrlType( *project ); if ( !inspireMetadataUrlType.isNull() ) { QDomElement inspireCommonMetadataUrlMediaTypeElem = doc.createElement( QStringLiteral( "inspire_common:MediaType" ) ); inspireCommonMetadataUrlMediaTypeElem.appendChild( doc.createTextNode( inspireMetadataUrlType ) ); inspireCommonMetadataUrlElem.appendChild( inspireCommonMetadataUrlMediaTypeElem ); } inspireCapabilitiesElem.appendChild( inspireCommonMetadataUrlElem ); } else { QDomElement inspireCommonResourceTypeElem = doc.createElement( QStringLiteral( "inspire_common:ResourceType" ) ); inspireCommonResourceTypeElem.appendChild( doc.createTextNode( QStringLiteral( "service" ) ) ); inspireCapabilitiesElem.appendChild( inspireCommonResourceTypeElem ); QDomElement inspireCommonSpatialDataServiceTypeElem = doc.createElement( QStringLiteral( "inspire_common:SpatialDataServiceType" ) ); inspireCommonSpatialDataServiceTypeElem.appendChild( doc.createTextNode( QStringLiteral( "view" ) ) ); inspireCapabilitiesElem.appendChild( inspireCommonSpatialDataServiceTypeElem ); QString inspireTemporalReference = QgsServerProjectUtils::wmsInspireTemporalReference( *project ); if ( !inspireTemporalReference.isNull() ) { QDomElement inspireCommonTemporalReferenceElem = doc.createElement( QStringLiteral( "inspire_common:TemporalReference" ) ); QDomElement inspireCommonDateOfLastRevisionElem = doc.createElement( QStringLiteral( "inspire_common:DateOfLastRevision" ) ); inspireCommonDateOfLastRevisionElem.appendChild( doc.createTextNode( inspireTemporalReference ) ); inspireCommonTemporalReferenceElem.appendChild( inspireCommonDateOfLastRevisionElem ); inspireCapabilitiesElem.appendChild( inspireCommonTemporalReferenceElem ); } QDomElement inspireCommonMetadataPointOfContactElem = doc.createElement( QStringLiteral( "inspire_common:MetadataPointOfContact" ) ); QString contactOrganization = QgsServerProjectUtils::owsServiceContactOrganization( *project ); QDomElement inspireCommonOrganisationNameElem = doc.createElement( QStringLiteral( "inspire_common:OrganisationName" ) ); if ( !contactOrganization.isNull() ) { inspireCommonOrganisationNameElem.appendChild( doc.createTextNode( contactOrganization ) ); } inspireCommonMetadataPointOfContactElem.appendChild( inspireCommonOrganisationNameElem ); QString contactMail = QgsServerProjectUtils::owsServiceContactMail( *project ); QDomElement inspireCommonEmailAddressElem = doc.createElement( QStringLiteral( "inspire_common:EmailAddress" ) ); if ( !contactMail.isNull() ) { inspireCommonEmailAddressElem.appendChild( doc.createTextNode( contactMail ) ); } inspireCommonMetadataPointOfContactElem.appendChild( inspireCommonEmailAddressElem ); inspireCapabilitiesElem.appendChild( inspireCommonMetadataPointOfContactElem ); QString inspireMetadataDate = QgsServerProjectUtils::wmsInspireMetadataDate( *project ); if ( !inspireMetadataDate.isNull() ) { QDomElement inspireCommonMetadataDateElem = doc.createElement( QStringLiteral( "inspire_common:MetadataDate" ) ); inspireCommonMetadataDateElem.appendChild( doc.createTextNode( inspireMetadataDate ) ); inspireCapabilitiesElem.appendChild( inspireCommonMetadataDateElem ); } } // Supported languages QDomElement inspireCommonSupportedLanguagesElem = doc.createElement( QStringLiteral( "inspire_common:SupportedLanguages" ) ); inspireCommonSupportedLanguagesElem.setAttribute( QStringLiteral( "xsi:type" ), QStringLiteral( "inspire_common:supportedLanguagesType" ) ); QDomElement inspireCommonLanguageElem = doc.createElement( QStringLiteral( "inspire_common:Language" ) ); inspireCommonLanguageElem.appendChild( doc.createTextNode( QgsServerProjectUtils::wmsInspireLanguage( *project ) ) ); QDomElement inspireCommonDefaultLanguageElem = doc.createElement( QStringLiteral( "inspire_common:DefaultLanguage" ) ); inspireCommonDefaultLanguageElem.appendChild( inspireCommonLanguageElem ); inspireCommonSupportedLanguagesElem.appendChild( inspireCommonDefaultLanguageElem ); #if 0 /* Supported language has to be different from default one */ QDomElement inspireCommonSupportedLanguageElem = doc.createElement( "inspire_common:SupportedLanguage" ); inspireCommonSupportedLanguageElem.appendChild( inspireCommonLanguageElem.cloneNode().toElement() ); inspireCommonSupportedLanguagesElem.appendChild( inspireCommonSupportedLanguageElem ); #endif inspireCapabilitiesElem.appendChild( inspireCommonSupportedLanguagesElem ); QDomElement inspireCommonResponseLanguageElem = doc.createElement( QStringLiteral( "inspire_common:ResponseLanguage" ) ); inspireCommonResponseLanguageElem.appendChild( inspireCommonLanguageElem.cloneNode().toElement() ); inspireCapabilitiesElem.appendChild( inspireCommonResponseLanguageElem ); return inspireCapabilitiesElem; } QDomElement getComposerTemplatesElement( QDomDocument &doc, const QgsProject *project ) { QList< QgsPrintLayout * > projectComposers = project->layoutManager()->printLayouts(); if ( projectComposers.size() == 0 ) return QDomElement(); QStringList restrictedComposers = QgsServerProjectUtils::wmsRestrictedComposers( *project ); QDomElement composerTemplatesElem = doc.createElement( QStringLiteral( "ComposerTemplates" ) ); QList<QgsPrintLayout *>::const_iterator cIt = projectComposers.constBegin(); for ( ; cIt != projectComposers.constEnd(); ++cIt ) { QgsPrintLayout *layout = *cIt; if ( restrictedComposers.contains( layout->name() ) ) continue; // Check that we have at least one page if ( layout->pageCollection()->pageCount() < 1 ) continue; // Get width and height from first page of the collection QgsLayoutSize layoutSize( layout->pageCollection()->page( 0 )->sizeWithUnits() ); QgsLayoutMeasurement width( layout->convertFromLayoutUnits( layoutSize.width(), QgsUnitTypes::LayoutUnit::LayoutMillimeters ) ); QgsLayoutMeasurement height( layout->convertFromLayoutUnits( layoutSize.height(), QgsUnitTypes::LayoutUnit::LayoutMillimeters ) ); QDomElement composerTemplateElem = doc.createElement( QStringLiteral( "ComposerTemplate" ) ); composerTemplateElem.setAttribute( QStringLiteral( "name" ), layout->name() ); //get paper width and height in mm from composition composerTemplateElem.setAttribute( QStringLiteral( "width" ), width.length() ); composerTemplateElem.setAttribute( QStringLiteral( "height" ), height.length() ); //add available composer maps and their size in mm QList<QgsLayoutItemMap *> layoutMapList; layout->layoutItems<QgsLayoutItemMap>( layoutMapList ); QList<QgsLayoutItemMap *>::const_iterator cmIt = layoutMapList.constBegin(); // Add map id int mapId = 0; for ( ; cmIt != layoutMapList.constEnd(); ++cmIt ) { const QgsLayoutItemMap *composerMap = *cmIt; QDomElement composerMapElem = doc.createElement( QStringLiteral( "ComposerMap" ) ); composerMapElem.setAttribute( QStringLiteral( "name" ), QStringLiteral( "map%1" ).arg( mapId ) ); mapId++; composerMapElem.setAttribute( QStringLiteral( "width" ), composerMap->rect().width() ); composerMapElem.setAttribute( QStringLiteral( "height" ), composerMap->rect().height() ); composerTemplateElem.appendChild( composerMapElem ); } //add available composer labels QList<QgsLayoutItemLabel *> composerLabelList; layout->layoutItems<QgsLayoutItemLabel>( composerLabelList ); QList<QgsLayoutItemLabel *>::const_iterator clIt = composerLabelList.constBegin(); for ( ; clIt != composerLabelList.constEnd(); ++clIt ) { QgsLayoutItemLabel *composerLabel = *clIt; QString id = composerLabel->id(); if ( id.isEmpty() ) continue; QDomElement composerLabelElem = doc.createElement( QStringLiteral( "ComposerLabel" ) ); composerLabelElem.setAttribute( QStringLiteral( "name" ), id ); composerTemplateElem.appendChild( composerLabelElem ); } //add available composer HTML QList<QgsLayoutItemHtml *> composerHtmlList; layout->layoutObjects<QgsLayoutItemHtml>( composerHtmlList ); QList<QgsLayoutItemHtml *>::const_iterator chIt = composerHtmlList.constBegin(); for ( ; chIt != composerHtmlList.constEnd(); ++chIt ) { QgsLayoutItemHtml *composerHtml = *chIt; if ( composerHtml->frameCount() == 0 ) continue; QString id = composerHtml->frame( 0 )->id(); if ( id.isEmpty() ) continue; QDomElement composerHtmlElem = doc.createElement( QStringLiteral( "ComposerHtml" ) ); composerHtmlElem.setAttribute( QStringLiteral( "name" ), id ); composerTemplateElem.appendChild( composerHtmlElem ); } composerTemplatesElem.appendChild( composerTemplateElem ); } if ( composerTemplatesElem.childNodes().size() == 0 ) return QDomElement(); return composerTemplatesElem; } QDomElement getWFSLayersElement( QDomDocument &doc, const QgsProject *project ) { QStringList wfsLayerIds = QgsServerProjectUtils::wfsLayerIds( *project ); if ( wfsLayerIds.size() == 0 ) return QDomElement(); QDomElement wfsLayersElem = doc.createElement( QStringLiteral( "WFSLayers" ) ); for ( int i = 0; i < wfsLayerIds.size(); ++i ) { QgsMapLayer *layer = project->mapLayer( wfsLayerIds.at( i ) ); if ( layer->type() != QgsMapLayer::LayerType::VectorLayer ) { continue; } QDomElement wfsLayerElem = doc.createElement( QStringLiteral( "WFSLayer" ) ); if ( QgsServerProjectUtils::wmsUseLayerIds( *project ) ) { wfsLayerElem.setAttribute( QStringLiteral( "name" ), layer->id() ); } else { wfsLayerElem.setAttribute( QStringLiteral( "name" ), layer->name() ); } wfsLayersElem.appendChild( wfsLayerElem ); } return wfsLayersElem; } QDomElement getLayersAndStylesCapabilitiesElement( QDomDocument &doc, QgsServerInterface *serverIface, const QgsProject *project, const QString &version, const QgsServerRequest &request, bool projectSettings ) { QStringList nonIdentifiableLayers = project->nonIdentifiableLayers(); const QgsLayerTree *projectLayerTreeRoot = project->layerTreeRoot(); QDomElement layerParentElem = doc.createElement( QStringLiteral( "Layer" ) ); if ( !project->title().isEmpty() ) { // Root Layer title QDomElement layerParentTitleElem = doc.createElement( QStringLiteral( "Title" ) ); QDomText layerParentTitleText = doc.createTextNode( project->title() ); layerParentTitleElem.appendChild( layerParentTitleText ); layerParentElem.appendChild( layerParentTitleElem ); // Root Layer abstract QDomElement layerParentAbstElem = doc.createElement( QStringLiteral( "Abstract" ) ); QDomText layerParentAbstText = doc.createTextNode( project->title() ); layerParentAbstElem.appendChild( layerParentAbstText ); layerParentElem.appendChild( layerParentAbstElem ); } // Root Layer name QString rootLayerName = QgsServerProjectUtils::wmsRootName( *project ); if ( rootLayerName.isEmpty() && !project->title().isEmpty() ) { rootLayerName = project->title(); } if ( !rootLayerName.isEmpty() ) { QDomElement layerParentNameElem = doc.createElement( QStringLiteral( "Name" ) ); QDomText layerParentNameText = doc.createTextNode( rootLayerName ); layerParentNameElem.appendChild( layerParentNameText ); layerParentElem.appendChild( layerParentNameElem ); } // Keyword list addKeywordListElement( project, doc, layerParentElem ); // Root Layer tree name if ( projectSettings ) { QDomElement treeNameElem = doc.createElement( QStringLiteral( "TreeName" ) ); QDomText treeNameText = doc.createTextNode( project->title() ); treeNameElem.appendChild( treeNameText ); layerParentElem.appendChild( treeNameElem ); } appendLayersFromTreeGroup( doc, layerParentElem, serverIface, project, version, request, projectLayerTreeRoot, projectSettings ); combineExtentAndCrsOfGroupChildren( doc, layerParentElem, project, true ); return layerParentElem; } namespace { void appendLayersFromTreeGroup( QDomDocument &doc, QDomElement &parentLayer, QgsServerInterface *serverIface, const QgsProject *project, const QString &version, const QgsServerRequest &request, const QgsLayerTreeGroup *layerTreeGroup, bool projectSettings ) { bool useLayerIds = QgsServerProjectUtils::wmsUseLayerIds( *project ); bool siaFormat = QgsServerProjectUtils::wmsInfoFormatSia2045( *project ); QStringList restrictedLayers = QgsServerProjectUtils::wmsRestrictedLayers( *project ); QList< QgsLayerTreeNode * > layerTreeGroupChildren = layerTreeGroup->children(); for ( int i = 0; i < layerTreeGroupChildren.size(); ++i ) { QgsLayerTreeNode *treeNode = layerTreeGroupChildren.at( i ); QDomElement layerElem = doc.createElement( QStringLiteral( "Layer" ) ); if ( projectSettings ) { layerElem.setAttribute( QStringLiteral( "visible" ), treeNode->isVisible() ); } if ( treeNode->nodeType() == QgsLayerTreeNode::NodeGroup ) { QgsLayerTreeGroup *treeGroupChild = static_cast<QgsLayerTreeGroup *>( treeNode ); QString name = treeGroupChild->name(); if ( restrictedLayers.contains( name ) ) //unpublished group { continue; } if ( projectSettings ) { layerElem.setAttribute( QStringLiteral( "mutuallyExclusive" ), treeGroupChild->isMutuallyExclusive() ); } QString shortName = treeGroupChild->customProperty( QStringLiteral( "wmsShortName" ) ).toString(); QString title = treeGroupChild->customProperty( QStringLiteral( "wmsTitle" ) ).toString(); QDomElement nameElem = doc.createElement( QStringLiteral( "Name" ) ); QDomText nameText; if ( !shortName.isEmpty() ) nameText = doc.createTextNode( shortName ); else nameText = doc.createTextNode( name ); nameElem.appendChild( nameText ); layerElem.appendChild( nameElem ); QDomElement titleElem = doc.createElement( QStringLiteral( "Title" ) ); QDomText titleText; if ( !title.isEmpty() ) titleText = doc.createTextNode( title ); else titleText = doc.createTextNode( name ); titleElem.appendChild( titleText ); layerElem.appendChild( titleElem ); QString abstract = treeGroupChild->customProperty( QStringLiteral( "wmsAbstract" ) ).toString(); if ( !abstract.isEmpty() ) { QDomElement abstractElem = doc.createElement( QStringLiteral( "Abstract" ) ); QDomText abstractText = doc.createTextNode( abstract ); abstractElem.appendChild( abstractText ); layerElem.appendChild( abstractElem ); } // Layer tree name if ( projectSettings ) { QDomElement treeNameElem = doc.createElement( QStringLiteral( "TreeName" ) ); QDomText treeNameText = doc.createTextNode( name ); treeNameElem.appendChild( treeNameText ); layerElem.appendChild( treeNameElem ); } appendLayersFromTreeGroup( doc, layerElem, serverIface, project, version, request, treeGroupChild, projectSettings ); combineExtentAndCrsOfGroupChildren( doc, layerElem, project ); } else { QgsLayerTreeLayer *treeLayer = static_cast<QgsLayerTreeLayer *>( treeNode ); QgsMapLayer *l = treeLayer->layer(); if ( restrictedLayers.contains( l->name() ) ) //unpublished layer { continue; } QgsAccessControl *accessControl = serverIface->accessControls(); if ( accessControl && !accessControl->layerReadPermission( l ) ) { continue; } QString wmsName = l->name(); if ( useLayerIds ) { wmsName = l->id(); } else if ( !l->shortName().isEmpty() ) { wmsName = l->shortName(); } // queryable layer if ( project->nonIdentifiableLayers().contains( l->id() ) ) { layerElem.setAttribute( QStringLiteral( "queryable" ), QStringLiteral( "0" ) ); } else { layerElem.setAttribute( QStringLiteral( "queryable" ), QStringLiteral( "1" ) ); } QDomElement nameElem = doc.createElement( QStringLiteral( "Name" ) ); QDomText nameText = doc.createTextNode( wmsName ); nameElem.appendChild( nameText ); layerElem.appendChild( nameElem ); QDomElement titleElem = doc.createElement( QStringLiteral( "Title" ) ); QString title = l->title(); if ( title.isEmpty() ) { title = l->name(); } QDomText titleText = doc.createTextNode( title ); titleElem.appendChild( titleText ); layerElem.appendChild( titleElem ); QString abstract = l->abstract(); if ( !abstract.isEmpty() ) { QDomElement abstractElem = doc.createElement( QStringLiteral( "Abstract" ) ); QDomText abstractText = doc.createTextNode( abstract ); abstractElem.appendChild( abstractText ); layerElem.appendChild( abstractElem ); } //keyword list if ( !l->keywordList().isEmpty() ) { QStringList keywordStringList = l->keywordList().split( ',' ); QDomElement keywordListElem = doc.createElement( QStringLiteral( "KeywordList" ) ); for ( int i = 0; i < keywordStringList.size(); ++i ) { QDomElement keywordElem = doc.createElement( QStringLiteral( "Keyword" ) ); QDomText keywordText = doc.createTextNode( keywordStringList.at( i ).trimmed() ); keywordElem.appendChild( keywordText ); if ( siaFormat ) { keywordElem.setAttribute( QStringLiteral( "vocabulary" ), QStringLiteral( "SIA_Geo405" ) ); } keywordListElem.appendChild( keywordElem ); } layerElem.appendChild( keywordListElem ); } //vector layer without geometry bool geometryLayer = true; if ( l->type() == QgsMapLayer::VectorLayer ) { QgsVectorLayer *vLayer = qobject_cast<QgsVectorLayer *>( l ); if ( vLayer ) { if ( vLayer->wkbType() == QgsWkbTypes::NoGeometry ) { geometryLayer = false; } } } //CRS if ( geometryLayer ) { QStringList crsList; crsList << l->crs().authid(); QStringList outputCrsList = QgsServerProjectUtils::wmsOutputCrsList( *project ); appendCrsElementsToLayer( doc, layerElem, crsList, outputCrsList ); //Ex_GeographicBoundingBox appendLayerBoundingBoxes( doc, layerElem, l->extent(), l->crs(), crsList, outputCrsList, project ); } // add details about supported styles of the layer appendLayerStyles( doc, layerElem, l, project, version, request ); //min/max scale denominatorScaleBasedVisibility if ( l->hasScaleBasedVisibility() ) { if ( version == QLatin1String( "1.1.1" ) ) { double OGC_PX_M = 0.00028; // OGC reference pixel size in meter, also used by qgis double SCALE_TO_SCALEHINT = OGC_PX_M * M_SQRT2; QDomElement scaleHintElem = doc.createElement( QStringLiteral( "ScaleHint" ) ); scaleHintElem.setAttribute( QStringLiteral( "min" ), QString::number( l->maximumScale() * SCALE_TO_SCALEHINT ) ); scaleHintElem.setAttribute( QStringLiteral( "max" ), QString::number( l->minimumScale() * SCALE_TO_SCALEHINT ) ); layerElem.appendChild( scaleHintElem ); } else { QString minScaleString = QString::number( l->maximumScale() ); QDomElement minScaleElem = doc.createElement( QStringLiteral( "MinScaleDenominator" ) ); QDomText minScaleText = doc.createTextNode( minScaleString ); minScaleElem.appendChild( minScaleText ); layerElem.appendChild( minScaleElem ); QString maxScaleString = QString::number( l->minimumScale() ); QDomElement maxScaleElem = doc.createElement( QStringLiteral( "MaxScaleDenominator" ) ); QDomText maxScaleText = doc.createTextNode( maxScaleString ); maxScaleElem.appendChild( maxScaleText ); layerElem.appendChild( maxScaleElem ); } } // layer data URL QString dataUrl = l->dataUrl(); if ( !dataUrl.isEmpty() ) { QDomElement dataUrlElem = doc.createElement( QStringLiteral( "DataURL" ) ); QDomElement dataUrlFormatElem = doc.createElement( QStringLiteral( "Format" ) ); QString dataUrlFormat = l->dataUrlFormat(); QDomText dataUrlFormatText = doc.createTextNode( dataUrlFormat ); dataUrlFormatElem.appendChild( dataUrlFormatText ); dataUrlElem.appendChild( dataUrlFormatElem ); QDomElement dataORElem = doc.createElement( QStringLiteral( "OnlineResource" ) ); dataORElem.setAttribute( QStringLiteral( "xmlns:xlink" ), QStringLiteral( "http://www.w3.org/1999/xlink" ) ); dataORElem.setAttribute( QStringLiteral( "xlink:type" ), QStringLiteral( "simple" ) ); dataORElem.setAttribute( QStringLiteral( "xlink:href" ), dataUrl ); dataUrlElem.appendChild( dataORElem ); layerElem.appendChild( dataUrlElem ); } // layer attribution QString attribution = l->attribution(); if ( !attribution.isEmpty() ) { QDomElement attribElem = doc.createElement( QStringLiteral( "Attribution" ) ); QDomElement attribTitleElem = doc.createElement( QStringLiteral( "Title" ) ); QDomText attribText = doc.createTextNode( attribution ); attribTitleElem.appendChild( attribText ); attribElem.appendChild( attribTitleElem ); QString attributionUrl = l->attributionUrl(); if ( !attributionUrl.isEmpty() ) { QDomElement attribORElem = doc.createElement( QStringLiteral( "OnlineResource" ) ); attribORElem.setAttribute( QStringLiteral( "xmlns:xlink" ), QStringLiteral( "http://www.w3.org/1999/xlink" ) ); attribORElem.setAttribute( QStringLiteral( "xlink:type" ), QStringLiteral( "simple" ) ); attribORElem.setAttribute( QStringLiteral( "xlink:href" ), attributionUrl ); attribElem.appendChild( attribORElem ); } layerElem.appendChild( attribElem ); } // layer metadata URL QString metadataUrl = l->metadataUrl(); if ( !metadataUrl.isEmpty() ) { QDomElement metaUrlElem = doc.createElement( QStringLiteral( "MetadataURL" ) ); QString metadataUrlType = l->metadataUrlType(); if ( version == QLatin1String( "1.1.1" ) ) { metaUrlElem.setAttribute( QStringLiteral( "type" ), metadataUrlType ); } else if ( metadataUrlType == QLatin1String( "FGDC" ) ) { metaUrlElem.setAttribute( QStringLiteral( "type" ), QStringLiteral( "FGDC:1998" ) ); } else if ( metadataUrlType == QLatin1String( "TC211" ) ) { metaUrlElem.setAttribute( QStringLiteral( "type" ), QStringLiteral( "ISO19115:2003" ) ); } else { metaUrlElem.setAttribute( QStringLiteral( "type" ), metadataUrlType ); } QString metadataUrlFormat = l->metadataUrlFormat(); if ( !metadataUrlFormat.isEmpty() ) { QDomElement metaUrlFormatElem = doc.createElement( QStringLiteral( "Format" ) ); QDomText metaUrlFormatText = doc.createTextNode( metadataUrlFormat ); metaUrlFormatElem.appendChild( metaUrlFormatText ); metaUrlElem.appendChild( metaUrlFormatElem ); } QDomElement metaUrlORElem = doc.createElement( QStringLiteral( "OnlineResource" ) ); metaUrlORElem.setAttribute( QStringLiteral( "xmlns:xlink" ), QStringLiteral( "http://www.w3.org/1999/xlink" ) ); metaUrlORElem.setAttribute( QStringLiteral( "xlink:type" ), QStringLiteral( "simple" ) ); metaUrlORElem.setAttribute( QStringLiteral( "xlink:href" ), metadataUrl ); metaUrlElem.appendChild( metaUrlORElem ); layerElem.appendChild( metaUrlElem ); } if ( projectSettings ) { appendLayerProjectSettings( doc, layerElem, l ); } } parentLayer.appendChild( layerElem ); } } void appendLayerStyles( QDomDocument &doc, QDomElement &layerElem, QgsMapLayer *currentLayer, const QgsProject *project, const QString &version, const QgsServerRequest &request ) { // Get service URL QUrl href = serviceUrl( request, project ); //href needs to be a prefix QString hrefString = href.toString(); hrefString.append( href.hasQuery() ? "&" : "?" ); for ( const QString &styleName : currentLayer->styleManager()->styles() ) { QDomElement styleElem = doc.createElement( QStringLiteral( "Style" ) ); QDomElement styleNameElem = doc.createElement( QStringLiteral( "Name" ) ); QDomText styleNameText = doc.createTextNode( styleName ); styleNameElem.appendChild( styleNameText ); QDomElement styleTitleElem = doc.createElement( QStringLiteral( "Title" ) ); QDomText styleTitleText = doc.createTextNode( styleName ); styleTitleElem.appendChild( styleTitleText ); styleElem.appendChild( styleNameElem ); styleElem.appendChild( styleTitleElem ); // QString LegendURL for explicit layerbased GetLegendGraphic request QDomElement getLayerLegendGraphicElem = doc.createElement( QStringLiteral( "LegendURL" ) ); QString customHrefString = currentLayer->legendUrl(); QStringList getLayerLegendGraphicFormats; if ( !customHrefString.isEmpty() ) { getLayerLegendGraphicFormats << currentLayer->legendUrlFormat(); } else { getLayerLegendGraphicFormats << QStringLiteral( "image/png" ); // << "jpeg" << "image/jpeg" } for ( int i = 0; i < getLayerLegendGraphicFormats.size(); ++i ) { QDomElement getLayerLegendGraphicFormatElem = doc.createElement( QStringLiteral( "Format" ) ); QString getLayerLegendGraphicFormat = getLayerLegendGraphicFormats[i]; QDomText getLayerLegendGraphicFormatText = doc.createTextNode( getLayerLegendGraphicFormat ); getLayerLegendGraphicFormatElem.appendChild( getLayerLegendGraphicFormatText ); getLayerLegendGraphicElem.appendChild( getLayerLegendGraphicFormatElem ); } // no parameters on custom hrefUrl, because should link directly to graphic if ( customHrefString.isEmpty() ) { QString layerName = currentLayer->name(); if ( QgsServerProjectUtils::wmsUseLayerIds( *project ) ) layerName = currentLayer->id(); else if ( !currentLayer->shortName().isEmpty() ) layerName = currentLayer->shortName(); QUrlQuery mapUrl( hrefString ); mapUrl.addQueryItem( QStringLiteral( "SERVICE" ), QStringLiteral( "WMS" ) ); mapUrl.addQueryItem( QStringLiteral( "VERSION" ), version ); mapUrl.addQueryItem( QStringLiteral( "REQUEST" ), QStringLiteral( "GetLegendGraphic" ) ); mapUrl.addQueryItem( QStringLiteral( "LAYER" ), layerName ); mapUrl.addQueryItem( QStringLiteral( "FORMAT" ), QStringLiteral( "image/png" ) ); mapUrl.addQueryItem( QStringLiteral( "STYLE" ), styleNameText.data() ); if ( version == QLatin1String( "1.3.0" ) ) { mapUrl.addQueryItem( QStringLiteral( "SLD_VERSION" ), QStringLiteral( "1.1.0" ) ); } customHrefString = mapUrl.toString(); } QDomElement getLayerLegendGraphicORElem = doc.createElement( QStringLiteral( "OnlineResource" ) ); getLayerLegendGraphicORElem.setAttribute( QStringLiteral( "xmlns:xlink" ), QStringLiteral( "http://www.w3.org/1999/xlink" ) ); getLayerLegendGraphicORElem.setAttribute( QStringLiteral( "xlink:type" ), QStringLiteral( "simple" ) ); getLayerLegendGraphicORElem.setAttribute( QStringLiteral( "xlink:href" ), customHrefString ); getLayerLegendGraphicElem.appendChild( getLayerLegendGraphicORElem ); styleElem.appendChild( getLayerLegendGraphicElem ); layerElem.appendChild( styleElem ); } } void appendCrsElementsToLayer( QDomDocument &doc, QDomElement &layerElement, const QStringList &crsList, const QStringList &constrainedCrsList ) { if ( layerElement.isNull() ) { return; } //insert the CRS elements after the title element to be in accordance with the WMS 1.3 specification QDomElement titleElement = layerElement.firstChildElement( QStringLiteral( "Title" ) ); QDomElement abstractElement = layerElement.firstChildElement( QStringLiteral( "Abstract" ) ); QDomElement CRSPrecedingElement = abstractElement.isNull() ? titleElement : abstractElement; //last element before the CRS elements if ( CRSPrecedingElement.isNull() ) { // keyword list element is never empty const QDomElement keyElement = layerElement.firstChildElement( QStringLiteral( "KeywordList" ) ); CRSPrecedingElement = keyElement; } //In case the number of advertised CRS is constrained if ( !constrainedCrsList.isEmpty() ) { for ( int i = constrainedCrsList.size() - 1; i >= 0; --i ) { appendCrsElementToLayer( doc, layerElement, CRSPrecedingElement, constrainedCrsList.at( i ) ); } } else //no crs constraint { for ( const QString &crs : crsList ) { appendCrsElementToLayer( doc, layerElement, CRSPrecedingElement, crs ); } } //Support for CRS:84 is mandatory (equals EPSG:4326 with reversed axis) appendCrsElementToLayer( doc, layerElement, CRSPrecedingElement, QString( "CRS:84" ) ); } void appendCrsElementToLayer( QDomDocument &doc, QDomElement &layerElement, const QDomElement &precedingElement, const QString &crsText ) { if ( crsText.isEmpty() ) return; QString version = doc.documentElement().attribute( QStringLiteral( "version" ) ); QDomElement crsElement = doc.createElement( version == QLatin1String( "1.1.1" ) ? "SRS" : "CRS" ); QDomText crsTextNode = doc.createTextNode( crsText ); crsElement.appendChild( crsTextNode ); layerElement.insertAfter( crsElement, precedingElement ); } void appendLayerBoundingBoxes( QDomDocument &doc, QDomElement &layerElem, const QgsRectangle &lExtent, const QgsCoordinateReferenceSystem &layerCRS, const QStringList &crsList, const QStringList &constrainedCrsList, const QgsProject *project ) { if ( layerElem.isNull() ) { return; } QgsRectangle layerExtent = lExtent; if ( qgsDoubleNear( layerExtent.xMinimum(), layerExtent.xMaximum() ) || qgsDoubleNear( layerExtent.yMinimum(), layerExtent.yMaximum() ) ) { //layer bbox cannot be empty layerExtent.grow( 0.000001 ); } QgsCoordinateReferenceSystem wgs84 = QgsCoordinateReferenceSystem::fromOgcWmsCrs( GEO_EPSG_CRS_AUTHID ); QString version = doc.documentElement().attribute( QStringLiteral( "version" ) ); //Ex_GeographicBoundingBox QDomElement ExGeoBBoxElement; //transform the layers native CRS into WGS84 QgsRectangle wgs84BoundingRect; if ( !layerExtent.isNull() ) { QgsCoordinateTransform exGeoTransform( layerCRS, wgs84, project ); try { wgs84BoundingRect = exGeoTransform.transformBoundingBox( layerExtent ); } catch ( const QgsCsException & ) { wgs84BoundingRect = QgsRectangle(); } } if ( version == QLatin1String( "1.1.1" ) ) // WMS Version 1.1.1 { ExGeoBBoxElement = doc.createElement( QStringLiteral( "LatLonBoundingBox" ) ); ExGeoBBoxElement.setAttribute( QStringLiteral( "minx" ), QString::number( wgs84BoundingRect.xMinimum() ) ); ExGeoBBoxElement.setAttribute( QStringLiteral( "maxx" ), QString::number( wgs84BoundingRect.xMaximum() ) ); ExGeoBBoxElement.setAttribute( QStringLiteral( "miny" ), QString::number( wgs84BoundingRect.yMinimum() ) ); ExGeoBBoxElement.setAttribute( QStringLiteral( "maxy" ), QString::number( wgs84BoundingRect.yMaximum() ) ); } else // WMS Version 1.3.0 { ExGeoBBoxElement = doc.createElement( QStringLiteral( "EX_GeographicBoundingBox" ) ); QDomElement wBoundLongitudeElement = doc.createElement( QStringLiteral( "westBoundLongitude" ) ); QDomText wBoundLongitudeText = doc.createTextNode( QString::number( wgs84BoundingRect.xMinimum() ) ); wBoundLongitudeElement.appendChild( wBoundLongitudeText ); ExGeoBBoxElement.appendChild( wBoundLongitudeElement ); QDomElement eBoundLongitudeElement = doc.createElement( QStringLiteral( "eastBoundLongitude" ) ); QDomText eBoundLongitudeText = doc.createTextNode( QString::number( wgs84BoundingRect.xMaximum() ) ); eBoundLongitudeElement.appendChild( eBoundLongitudeText ); ExGeoBBoxElement.appendChild( eBoundLongitudeElement ); QDomElement sBoundLatitudeElement = doc.createElement( QStringLiteral( "southBoundLatitude" ) ); QDomText sBoundLatitudeText = doc.createTextNode( QString::number( wgs84BoundingRect.yMinimum() ) ); sBoundLatitudeElement.appendChild( sBoundLatitudeText ); ExGeoBBoxElement.appendChild( sBoundLatitudeElement ); QDomElement nBoundLatitudeElement = doc.createElement( QStringLiteral( "northBoundLatitude" ) ); QDomText nBoundLatitudeText = doc.createTextNode( QString::number( wgs84BoundingRect.yMaximum() ) ); nBoundLatitudeElement.appendChild( nBoundLatitudeText ); ExGeoBBoxElement.appendChild( nBoundLatitudeElement ); } if ( !wgs84BoundingRect.isNull() ) //LatLonBoundingBox / Ex_GeographicBounding box is optional { QDomElement lastCRSElem = layerElem.lastChildElement( version == QLatin1String( "1.1.1" ) ? "SRS" : "CRS" ); if ( !lastCRSElem.isNull() ) { layerElem.insertAfter( ExGeoBBoxElement, lastCRSElem ); } else { layerElem.appendChild( ExGeoBBoxElement ); } } //In case the number of advertised CRS is constrained if ( !constrainedCrsList.isEmpty() ) { for ( int i = constrainedCrsList.size() - 1; i >= 0; --i ) { appendLayerBoundingBox( doc, layerElem, layerExtent, layerCRS, constrainedCrsList.at( i ), project ); } } else //no crs constraint { for ( const QString &crs : crsList ) { appendLayerBoundingBox( doc, layerElem, layerExtent, layerCRS, crs, project ); } } } void appendLayerBoundingBox( QDomDocument &doc, QDomElement &layerElem, const QgsRectangle &layerExtent, const QgsCoordinateReferenceSystem &layerCRS, const QString &crsText, const QgsProject *project ) { if ( layerElem.isNull() ) { return; } if ( crsText.isEmpty() ) { return; } QString version = doc.documentElement().attribute( QStringLiteral( "version" ) ); QgsCoordinateReferenceSystem crs = QgsCoordinateReferenceSystem::fromOgcWmsCrs( crsText ); //transform the layers native CRS into CRS QgsRectangle crsExtent; if ( !layerExtent.isNull() ) { QgsCoordinateTransform crsTransform( layerCRS, crs, project ); try { crsExtent = crsTransform.transformBoundingBox( layerExtent ); } catch ( QgsCsException &cse ) { Q_UNUSED( cse ); return; } } if ( crsExtent.isNull() ) { return; } //BoundingBox element QDomElement bBoxElement = doc.createElement( QStringLiteral( "BoundingBox" ) ); if ( crs.isValid() ) { bBoxElement.setAttribute( version == QLatin1String( "1.1.1" ) ? "SRS" : "CRS", crs.authid() ); } if ( version != QLatin1String( "1.1.1" ) && crs.hasAxisInverted() ) { crsExtent.invert(); } bBoxElement.setAttribute( QStringLiteral( "minx" ), QString::number( crsExtent.xMinimum() ) ); bBoxElement.setAttribute( QStringLiteral( "miny" ), QString::number( crsExtent.yMinimum() ) ); bBoxElement.setAttribute( QStringLiteral( "maxx" ), QString::number( crsExtent.xMaximum() ) ); bBoxElement.setAttribute( QStringLiteral( "maxy" ), QString::number( crsExtent.yMaximum() ) ); QDomElement lastBBoxElem = layerElem.lastChildElement( QStringLiteral( "BoundingBox" ) ); if ( !lastBBoxElem.isNull() ) { layerElem.insertAfter( bBoxElement, lastBBoxElem ); } else { lastBBoxElem = layerElem.lastChildElement( version == QLatin1String( "1.1.1" ) ? "LatLonBoundingBox" : "EX_GeographicBoundingBox" ); if ( !lastBBoxElem.isNull() ) { layerElem.insertAfter( bBoxElement, lastBBoxElem ); } else { layerElem.appendChild( bBoxElement ); } } } QgsRectangle layerBoundingBoxInProjectCrs( const QDomDocument &doc, const QDomElement &layerElem, const QgsProject *project ) { QgsRectangle BBox; if ( layerElem.isNull() ) { return BBox; } //read box coordinates and layer auth. id QDomElement boundingBoxElem = layerElem.firstChildElement( QStringLiteral( "BoundingBox" ) ); if ( boundingBoxElem.isNull() ) { return BBox; } double minx, miny, maxx, maxy; bool conversionOk; minx = boundingBoxElem.attribute( QStringLiteral( "minx" ) ).toDouble( &conversionOk ); if ( !conversionOk ) { return BBox; } miny = boundingBoxElem.attribute( QStringLiteral( "miny" ) ).toDouble( &conversionOk ); if ( !conversionOk ) { return BBox; } maxx = boundingBoxElem.attribute( QStringLiteral( "maxx" ) ).toDouble( &conversionOk ); if ( !conversionOk ) { return BBox; } maxy = boundingBoxElem.attribute( QStringLiteral( "maxy" ) ).toDouble( &conversionOk ); if ( !conversionOk ) { return BBox; } QString version = doc.documentElement().attribute( QStringLiteral( "version" ) ); //create layer crs QgsCoordinateReferenceSystem layerCrs = QgsCoordinateReferenceSystem::fromOgcWmsCrs( boundingBoxElem.attribute( version == QLatin1String( "1.1.1" ) ? "SRS" : "CRS" ) ); if ( !layerCrs.isValid() ) { return BBox; } BBox.setXMinimum( minx ); BBox.setXMaximum( maxx ); BBox.setYMinimum( miny ); BBox.setYMaximum( maxy ); if ( version != QLatin1String( "1.1.1" ) && layerCrs.hasAxisInverted() ) { BBox.invert(); } //get project crs QgsCoordinateTransform t( layerCrs, project->crs(), project ); //transform try { BBox = t.transformBoundingBox( BBox ); } catch ( const QgsCsException & ) { BBox = QgsRectangle(); } return BBox; } bool crsSetFromLayerElement( const QDomElement &layerElement, QSet<QString> &crsSet ) { if ( layerElement.isNull() ) { return false; } crsSet.clear(); QDomNodeList crsNodeList; crsNodeList = layerElement.elementsByTagName( QStringLiteral( "CRS" ) ); // WMS 1.3.0 for ( int i = 0; i < crsNodeList.size(); ++i ) { crsSet.insert( crsNodeList.at( i ).toElement().text() ); } crsNodeList = layerElement.elementsByTagName( QStringLiteral( "SRS" ) ); // WMS 1.1.1 for ( int i = 0; i < crsNodeList.size(); ++i ) { crsSet.insert( crsNodeList.at( i ).toElement().text() ); } return true; } void combineExtentAndCrsOfGroupChildren( QDomDocument &doc, QDomElement &groupElem, const QgsProject *project, bool considerMapExtent ) { QgsRectangle combinedBBox; QSet<QString> combinedCRSSet; bool firstBBox = true; bool firstCRSSet = true; QDomNodeList layerChildren = groupElem.childNodes(); for ( int j = 0; j < layerChildren.size(); ++j ) { QDomElement childElem = layerChildren.at( j ).toElement(); if ( childElem.tagName() != QLatin1String( "Layer" ) ) continue; QgsRectangle bbox = layerBoundingBoxInProjectCrs( doc, childElem, project ); if ( bbox.isNull() ) { continue; } if ( !bbox.isEmpty() ) { if ( firstBBox ) { combinedBBox = bbox; firstBBox = false; } else { combinedBBox.combineExtentWith( bbox ); } } //combine crs set QSet<QString> crsSet; if ( crsSetFromLayerElement( childElem, crsSet ) ) { if ( firstCRSSet ) { combinedCRSSet = crsSet; firstCRSSet = false; } else { combinedCRSSet.intersect( crsSet ); } } } QStringList outputCrsList = QgsServerProjectUtils::wmsOutputCrsList( *project ); appendCrsElementsToLayer( doc, groupElem, combinedCRSSet.toList(), outputCrsList ); QgsCoordinateReferenceSystem groupCRS = project->crs(); if ( considerMapExtent ) { QgsRectangle mapRect = QgsServerProjectUtils::wmsExtent( *project ); if ( !mapRect.isEmpty() ) { combinedBBox = mapRect; } } appendLayerBoundingBoxes( doc, groupElem, combinedBBox, groupCRS, combinedCRSSet.toList(), outputCrsList, project ); } void appendDrawingOrder( QDomDocument &doc, QDomElement &parentElem, QgsServerInterface *serverIface, const QgsProject *project ) { QgsAccessControl *accessControl = serverIface->accessControls(); bool useLayerIds = QgsServerProjectUtils::wmsUseLayerIds( *project ); QStringList restrictedLayers = QgsServerProjectUtils::wmsRestrictedLayers( *project ); QStringList layerList; const QgsLayerTree *projectLayerTreeRoot = project->layerTreeRoot(); QList< QgsMapLayer * > projectLayerOrder = projectLayerTreeRoot->layerOrder(); for ( int i = 0; i < projectLayerOrder.size(); ++i ) { QgsMapLayer *l = projectLayerOrder.at( i ); if ( restrictedLayers.contains( l->name() ) ) //unpublished layer { continue; } if ( accessControl && !accessControl->layerReadPermission( l ) ) { continue; } QString wmsName = l->name(); if ( useLayerIds ) { wmsName = l->id(); } else if ( !l->shortName().isEmpty() ) { wmsName = l->shortName(); } layerList << wmsName; } if ( !layerList.isEmpty() ) { QStringList reversedList; reversedList.reserve( layerList.size() ); for ( int i = layerList.size() - 1; i >= 0; --i ) reversedList << layerList[ i ]; QDomElement layerDrawingOrderElem = doc.createElement( QStringLiteral( "LayerDrawingOrder" ) ); QDomText drawingOrderText = doc.createTextNode( reversedList.join( ',' ) ); layerDrawingOrderElem.appendChild( drawingOrderText ); parentElem.appendChild( layerDrawingOrderElem ); } } void appendLayerProjectSettings( QDomDocument &doc, QDomElement &layerElem, QgsMapLayer *currentLayer ) { if ( !currentLayer ) { return; } // Layer tree name QDomElement treeNameElem = doc.createElement( QStringLiteral( "TreeName" ) ); QDomText treeNameText = doc.createTextNode( currentLayer->name() ); treeNameElem.appendChild( treeNameText ); layerElem.appendChild( treeNameElem ); if ( currentLayer->type() == QgsMapLayer::VectorLayer ) { QgsVectorLayer *vLayer = static_cast<QgsVectorLayer *>( currentLayer ); const QSet<QString> &excludedAttributes = vLayer->excludeAttributesWms(); int displayFieldIdx = -1; QString displayField = QStringLiteral( "maptip" ); QgsExpression exp( vLayer->displayExpression() ); if ( exp.isField() ) { displayField = static_cast<const QgsExpressionNodeColumnRef *>( exp.rootNode() )->name(); displayFieldIdx = vLayer->fields().lookupField( displayField ); } //attributes QDomElement attributesElem = doc.createElement( QStringLiteral( "Attributes" ) ); const QgsFields layerFields = vLayer->fields(); for ( int idx = 0; idx < layerFields.count(); ++idx ) { QgsField field = layerFields.at( idx ); if ( excludedAttributes.contains( field.name() ) ) { continue; } // field alias in case of displayField if ( idx == displayFieldIdx ) { displayField = vLayer->attributeDisplayName( idx ); } QDomElement attributeElem = doc.createElement( QStringLiteral( "Attribute" ) ); attributeElem.setAttribute( QStringLiteral( "name" ), field.name() ); attributeElem.setAttribute( QStringLiteral( "type" ), QVariant::typeToName( field.type() ) ); attributeElem.setAttribute( QStringLiteral( "typeName" ), field.typeName() ); QString alias = field.alias(); if ( !alias.isEmpty() ) { attributeElem.setAttribute( QStringLiteral( "alias" ), alias ); } //edit type to text attributeElem.setAttribute( QStringLiteral( "editType" ), vLayer->editorWidgetSetup( idx ).type() ); attributeElem.setAttribute( QStringLiteral( "comment" ), field.comment() ); attributeElem.setAttribute( QStringLiteral( "length" ), field.length() ); attributeElem.setAttribute( QStringLiteral( "precision" ), field.precision() ); attributesElem.appendChild( attributeElem ); } //displayfield layerElem.setAttribute( QStringLiteral( "displayField" ), displayField ); //geometry type layerElem.setAttribute( QStringLiteral( "geometryType" ), QgsWkbTypes::displayString( vLayer->wkbType() ) ); layerElem.appendChild( attributesElem ); } else if ( currentLayer->type() == QgsMapLayer::RasterLayer ) { const QgsDataProvider *provider = currentLayer->dataProvider(); if ( provider && provider->name() == "wms" ) { //advertise as web map background layer QVariant wmsBackgroundLayer = currentLayer->customProperty( QStringLiteral( "WMSBackgroundLayer" ), false ); QDomElement wmsBackgroundLayerElem = doc.createElement( "WMSBackgroundLayer" ); QDomText wmsBackgroundLayerText = doc.createTextNode( wmsBackgroundLayer.toBool() ? QStringLiteral( "1" ) : QStringLiteral( "0" ) ); wmsBackgroundLayerElem.appendChild( wmsBackgroundLayerText ); layerElem.appendChild( wmsBackgroundLayerElem ); //publish datasource QVariant wmsPublishDataSourceUrl = currentLayer->customProperty( QStringLiteral( "WMSPublishDataSourceUrl" ), false ); if ( wmsPublishDataSourceUrl.toBool() ) { QList< QVariant > resolutionList = provider->property( "resolutions" ).toList(); bool tiled = resolutionList.size() > 0; QDomElement dataSourceElem = doc.createElement( tiled ? QStringLiteral( "WMTSDataSource" ) : QStringLiteral( "WMSDataSource" ) ); QDomText dataSourceUri = doc.createTextNode( provider->dataSourceUri() ); dataSourceElem.appendChild( dataSourceUri ); layerElem.appendChild( dataSourceElem ); } } QVariant wmsPrintLayer = currentLayer->customProperty( QStringLiteral( "WMSPrintLayer" ) ); if ( wmsPrintLayer.isValid() ) { QDomElement wmsPrintLayerElem = doc.createElement( "WMSPrintLayer" ); QDomText wmsPrintLayerText = doc.createTextNode( wmsPrintLayer.toString() ); wmsPrintLayerElem.appendChild( wmsPrintLayerText ); layerElem.appendChild( wmsPrintLayerElem ); } } } void addKeywordListElement( const QgsProject *project, QDomDocument &doc, QDomElement &parent ) { bool sia2045 = QgsServerProjectUtils::wmsInfoFormatSia2045( *project ); QDomElement keywordsElem = doc.createElement( QStringLiteral( "KeywordList" ) ); //add default keyword QDomElement keywordElem = doc.createElement( QStringLiteral( "Keyword" ) ); keywordElem.setAttribute( QStringLiteral( "vocabulary" ), QStringLiteral( "ISO" ) ); QDomText keywordText = doc.createTextNode( QStringLiteral( "infoMapAccessService" ) ); keywordElem.appendChild( keywordText ); keywordsElem.appendChild( keywordElem ); parent.appendChild( keywordsElem ); QStringList keywords = QgsServerProjectUtils::owsServiceKeywords( *project ); for ( const QString &keyword : qgis::as_const( keywords ) ) { if ( !keyword.isEmpty() ) { keywordElem = doc.createElement( QStringLiteral( "Keyword" ) ); keywordText = doc.createTextNode( keyword ); keywordElem.appendChild( keywordText ); if ( sia2045 ) { keywordElem.setAttribute( QStringLiteral( "vocabulary" ), QStringLiteral( "SIA_Geo405" ) ); } keywordsElem.appendChild( keywordElem ); } } parent.appendChild( keywordsElem ); } } } // namespace QgsWms
raymondnijssen/QGIS
src/server/services/wms/qgswmsgetcapabilities.cpp
C++
gpl-2.0
78,633
/* * Copyright 2010,2011 Ippon Technologies * * This file is part of Web Integration Portlet (WIP). * Web Integration Portlet (WIP) is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Web Integration Portlet (WIP) is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Web Integration Portlet (WIP). If not, see <http://www.gnu.org/licenses/>. */ package fr.ippon.wip.http.hc; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; /** * Implementation of HttpSessionListener. Must be declared in web.xml to release * resources associated to a session when it is destroyed. * * @author François Prot */ public class HttpClientSessionListener implements HttpSessionListener { public void sessionCreated(HttpSessionEvent httpSessionEvent) { // Nothing to do } public void sessionDestroyed(HttpSessionEvent httpSessionEvent) { HttpClientResourceManager.getInstance().releaseSessionResources(httpSessionEvent.getSession().getId()); } }
aubelix/liferay-samples
wip-portlet/src/main/java/fr/ippon/wip/http/hc/HttpClientSessionListener.java
Java
gpl-2.0
1,491
<?php /** * @author mr.v */ class MY_Input extends CI_Input { function __construct() { parent::__construct(); }// __construct function ip_address() { if ( $this->ip_address !== false ) { return $this->ip_address; } // IMPROVED!! CI ip address cannot detect through http_x_forwarded_for. this one can do. if (isset($_SERVER['HTTP_CLIENT_IP'])) { // //check ip from share internet $this->ip_address = $_SERVER['HTTP_CLIENT_IP']; } elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { //to check ip is pass from proxy $this->ip_address = $_SERVER['HTTP_X_FORWARDED_FOR']; } else { $this->ip_address = $_SERVER['REMOTE_ADDR']; } // if ( $this->ip_address === false ) { $this->ip_address = "0.0.0.0"; return $this->ip_address; } // if (strpos($this->ip_address, ',') !== FALSE) { $x = explode(',', $this->ip_address); $this->ip_address = trim(end($x)); } // if ( ! $this->valid_ip($this->ip_address)){ $this->ip_address = '0.0.0.0'; } // return $this->ip_address; } } /* end of file */
OkveeNet/vee-manga-reader-pro
application/core/MY_Input.php
PHP
gpl-2.0
1,068
/* * Copyright 2009 Mike Cumings * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.kenai.jbosh; /** * Abstract base class for creating BOSH attribute classes. Concrete * implementations of this class will naturally inherit the underlying type's * behavior for {@code equals()}, {@code hashCode()}, {@code toString()}, and * {@code compareTo()}, allowing for the easy creation of objects which extend * existing trivial types. This was done to comply with the prefactoring rule * declaring, "when you are being abstract, be abstract all the way". * * @param <T> * type of the extension object */ abstract class AbstractAttr<T extends Comparable> implements Comparable { /** * Captured value. */ private final T value; /** * Creates a new encapsulated object instance. * * @param aValue * encapsulated getValue */ protected AbstractAttr(final T aValue) { value = aValue; } /** * Gets the encapsulated data value. * * @return data value */ public final T getValue() { return value; } // ///////////////////////////////////////////////////////////////////////// // Object method overrides: /** * {@inheritDoc} * * @param otherObj * object to compare to * @return true if the objects are equal, false otherwise */ @Override public boolean equals(final Object otherObj) { if (otherObj == null) { return false; } else if (otherObj instanceof AbstractAttr) { AbstractAttr other = (AbstractAttr) otherObj; return value.equals(other.value); } else { return false; } } /** * {@inheritDoc} * * @return hashCode of the encapsulated object */ @Override public int hashCode() { return value.hashCode(); } /** * {@inheritDoc} * * @return string representation of the encapsulated object */ @Override public String toString() { return value.toString(); } // ///////////////////////////////////////////////////////////////////////// // Comparable interface: /** * {@inheritDoc} * * @param otherObj * object to compare to * @return -1, 0, or 1 */ @SuppressWarnings("unchecked") public int compareTo(final Object otherObj) { if (otherObj == null) { return 1; } else { return value.compareTo(otherObj); } } }
ikantech/xmppsupport_v2
src/com/kenai/jbosh/AbstractAttr.java
Java
gpl-2.0
2,814
<?php /** * @package T3 Blank * @copyright Copyright (C) 2005 - 2012 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ defined('_JEXEC') or die; ?> <!-- META FOR IOS & HANDHELD --> <?php if($this->getParam('responsive', 1)): ?> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/> <?php endif ?> <meta name="HandheldFriendly" content="true" /> <meta name="apple-mobile-web-app-capable" content="YES" /> <!-- //META FOR IOS & HANDHELD --> <?php // SYSTEM CSS $this->addStyleSheet(JUri::base(true).'/templates/system/css/system.css'); ?> <?php // T3 BASE HEAD $this->addHead(); ?> <?php // CUSTOM CSS if(is_file(T3_TEMPLATE_PATH . '/css/custom.css')) { $this->addStyleSheet(T3_TEMPLATE_URL.'/css/custom.css'); } ?> <!-- Le HTML5 shim, for IE6-8 support of HTML5 elements --> <!--[if lt IE 9]> <script src="//html5shim.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <!-- For IE6-8 support of media query --> <!--[if lt IE 9]> <script type="text/javascript" src="<?php echo T3_URL ?>/js/respond.min.js"></script> <![endif]--> <!-- You can add Google Analytics here-->
taylorsuccessor/t3
templates/mapscccccccccc/tpls/blocks/head.php
PHP
gpl-2.0
1,226
<?php get_header(); ?> <div id="content" class="wrap clearfix"> <div id="main" class="clearfix" role="main"> <?php if (have_posts()) : while (have_posts()) : the_post(); ?> <article id="post-<?php the_ID(); ?>" <?php post_class('clearfix'); ?> role="article" itemscope itemtype="http://schema.org/BlogPosting"> <header class="article-header"> <h1 class="page-title" itemprop="headline"><?php the_title(); ?></h1> </header> <!-- end article header --> <section class="entry-content clearfix" itemprop="articleBody"> <?php the_content(); ?> </section> <!-- end article section --> <footer class="article-footer"> <?php wp_link_pages(); ?> </footer> <?php comments_template(); ?> </article> <!-- end article --> <?php endwhile; else : ?> <article id="post-not-found" class="hentry clearfix"> <header class="article-header"> <h1><?php _e("Article Missing", "serena"); ?></h1> </header> <section class="entry-content"> <p><?php _e("Sorry, but something is missing. Please try again!", "serena"); ?></p> </section> <footer class="article-footer"> </footer> </article> <?php endif; ?> </div> <!-- end #main --> </div> <!-- end #content --> <?php get_footer(); ?>
joeross/blog.joeross.me
wp-content/themes/serena/page.php
PHP
gpl-2.0
1,536
/* * Copyright (c) 1998-2010 Caucho Technology -- all rights reserved * * This file is part of Resin(R) Open Source * * Each copy or derived work must preserve the copyright notice and this * notice unmodified. * * Resin Open Source is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Resin Open Source is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty * of NON-INFRINGEMENT. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with Resin Open Source; if not, write to the * * Free Software Foundation, Inc. * 59 Temple Place, Suite 330 * Boston, MA 02111-1307 USA * * @author Scott Ferguson */ package com.caucho.log; import com.caucho.util.L10N; import java.util.logging.Handler; import java.util.logging.LogRecord; /** * Proxy for an underlying handler, e.g. to handle different * logging levels. */ public class SubHandler extends Handler { private static final L10N L = new L10N(SubHandler.class); private Handler _handler; SubHandler(Handler handler) { _handler = handler; } /** * Publishes the record. */ public void publish(LogRecord record) { if (! isLoggable(record)) return; if (_handler != null) _handler.publish(record); } /** * Flushes the buffer. */ public void flush() { if (_handler != null) _handler.flush(); } /** * Closes the handler. */ public void close() { if (_handler != null) _handler.close(); _handler = null; } /** * Returns the hash code. */ public int hashCode() { if (_handler == null) return super.hashCode(); else return _handler.hashCode(); } /** * Test for equality. */ public boolean equals(Object o) { if (this == o) return true; else if (o == null) return false; if (_handler == null) return false; else if (o.equals(_handler)) return true; if (! (o instanceof SubHandler)) return false; SubHandler subHandler = (SubHandler) o; return _handler.equals(subHandler._handler); } public String toString() { return "SubHandler[" + _handler + "]"; } }
CleverCloud/Quercus
resin/src/main/java/com/caucho/log/SubHandler.java
Java
gpl-2.0
2,558
<?php /** * AmanCMS * * LICENSE * * This source file is subject to the GNU GENERAL PUBLIC LICENSE Version 2 * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://www.gnu.org/licenses/gpl-2.0.txt * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@amancms.com so we can send you a copy immediately. * * @copyright Copyright (c) 2010-2012 KhanSoft Limited (http://www.khansoft.com) * @license http://www.gnu.org/licenses/gpl-2.0.txt GNU GENERAL PUBLIC LICENSE Version 2 * @version $Id: RuleLoader.php 4537 2010-08-12 09:53:42Z mehrab $ * @since 1.0.0 */ class Core_View_Helper_RuleLoader extends Zend_View_Helper_Abstract { public function ruleLoader() { return $this; } public function getResources($module) { $conn = Aman_Db_Connection::factory()->getMasterConnection(); $resourceDao = Aman_Model_Dao_Factory::getInstance()->setModule('core')->getResourceDao(); $resourceDao->setDbConnection($conn); return $resourceDao->getResources($module); } public function getByRole($resource, $roleId) { $conn = Aman_Db_Connection::factory()->getMasterConnection(); $privilegeDao = Aman_Model_Dao_Factory::getInstance()->setModule('core')->getPrivilegeDao(); $privilegeDao->setDbConnection($conn); return $privilegeDao->getByRole($resource, $roleId); } public function getByUser($resource, $userId) { $conn = Aman_Db_Connection::factory()->getMasterConnection(); $privilegeDao = Aman_Model_Dao_Factory::getInstance()->setModule('core')->getPrivilegeDao(); $privilegeDao->setDbConnection($conn); return $privilegeDao->getByUser($resource, $userId); } }
salem/aman
application/modules/core/views_delted/helpers/RuleLoader.php
PHP
gpl-2.0
1,834
<?php /** * @Project NUKEVIET 4.x * @Author VINADES (contact@vinades.vn) * @Copyright 2014 VINADES. All rights reserved * @License GNU/GPL version 2 or any later version * @Createdate Apr 22, 2010 3:00:20 PM */ if( ! defined( 'NV_IS_FILE_ADMIN' ) ) die( 'Stop!!!' ); $xtpl = new XTemplate( 'list_row.tpl', NV_ROOTDIR . '/themes/' . $global_config['module_theme'] . '/modules/' . $module_file ); $xtpl->assign( 'LANG', $lang_module ); $xtpl->assign( 'GLANG', $lang_global ); $a = 0; $sql = 'SELECT * FROM ' . NV_PREFIXLANG . '_' . $module_data . '_rows ORDER BY full_name'; $result = $db->query( $sql ); while( $row = $result->fetch() ) { ++$a; $xtpl->assign( 'ROW', array( 'full_name' => $row['full_name'], 'email' => $row['email'], 'phone' => $row['phone'], 'fax' => $row['fax'], 'id' => $row['id'], 'url_part' => NV_BASE_SITEURL . 'index.php?' . NV_LANG_VARIABLE . '=' . NV_LANG_DATA . '&amp;' . NV_NAME_VARIABLE . '=' . $module_name . '&amp;' . NV_OP_VARIABLE . '=' . $row['id'] . '/0/1', 'url_edit' => NV_BASE_ADMINURL . 'index.php?' . NV_LANG_VARIABLE . '=' . NV_LANG_DATA . '&amp;' . NV_NAME_VARIABLE . '=' . $module_name . '&amp;' . NV_OP_VARIABLE . '=row&amp;id=' . $row['id'] ) ); $array = array( $lang_global['disable'], $lang_global['active'] ); foreach( $array as $key => $val ) { $xtpl->assign( 'STATUS', array( 'key' => $key, 'selected' => $key == $row['act'] ? ' selected="selected"' : '', 'title' => $val ) ); $xtpl->parse( 'main.row.status' ); } $xtpl->parse( 'main.row' ); } if( empty( $a ) ) { Header( 'Location: ' . NV_BASE_ADMINURL . 'index.php?' . NV_LANG_VARIABLE . '=' . NV_LANG_DATA . '&' . NV_NAME_VARIABLE . '=' . $module_name . '&' . NV_OP_VARIABLE . '=row' ); die(); } $xtpl->assign( 'URL_ADD', NV_BASE_ADMINURL . 'index.php?' . NV_LANG_VARIABLE . '=' . NV_LANG_DATA . '&amp;' . NV_NAME_VARIABLE . '=' . $module_name . '&amp;' . NV_OP_VARIABLE . '=row' ); $xtpl->parse( 'main' ); $contents = $xtpl->text( 'main' ); $page_title = $lang_module['list_row_title']; include NV_ROOTDIR . '/includes/header.php'; echo nv_admin_theme( $contents ); include NV_ROOTDIR . '/includes/footer.php'; ?>
doan281/nukeviet4_dev
modules/contact/admin/list_row.php
PHP
gpl-2.0
2,173
/** * Metis - Bootstrap-Admin-Template v2.2.7 * Author : onokumus * Copyright 2014 * Licensed under MIT (https://github.com/onokumus/Bootstrap-Admin-Template/blob/master/LICENSE.md) */ window.fakeStorage = { _data: { }, setItem: function (id, val) { return this._data[id] = String(val); }, getItem: function (id) { return this._data.hasOwnProperty(id) ? this._data[id] : undefined; }, removeItem: function (id) { return delete this._data[id]; }, clear: function () { return this._data = { }; } }; function LocalStorageManager() { this.bgColor = 'bgColor'; this.fgcolor = 'fgcolor'; this.bgImage = 'bgImage'; var supported = this.localStorageSupported(); this.storage = supported ? window.localStorage : window.fakeStorage; } LocalStorageManager.prototype.localStorageSupported = function () { var testKey = 'test'; var storage = window.localStorage; try { storage.setItem(testKey, '1'); storage.removeItem(testKey); return true; } catch (error) { return false; } }; LocalStorageManager.prototype.getBgColor = function () { return this.storage.getItem(this.bgColor) || '#333'; }; LocalStorageManager.prototype.setBgColor = function (color) { this.storage.setItem(this.bgColor, color); }; LocalStorageManager.prototype.getFgColor = function () { return this.storage.getItem(this.fgColor) || '#fff'; }; LocalStorageManager.prototype.setFgColor = function (color) { this.storage.setItem(this.fgColor, color); }; LocalStorageManager.prototype.getBgImage = function () { return this.storage.getItem(this.bgImage) || 'arches'; }; LocalStorageManager.prototype.setBgImage = function (image) { this.storage.setItem(this.bgImage, image); }; LocalStorageManager.prototype.clearItems = function () { this.storage.removeItem(this.bgColor); this.storage.removeItem(this.fgColor); this.storage.removeItem(this.bgImage); }; function InputTypeManager() { var ci = this.colorTypeSupported(); this.ci = ci; } InputTypeManager.prototype.colorTypeSupported = function () { var ci = document.createElement('input'); ci.setAttribute('type', 'color'); return ci.type !== 'text'; }; StyleSwitcher = function () { this.inputManager = new InputTypeManager(); this.storageManager = new LocalStorageManager(); this.init(); }; StyleSwitcher.prototype.init = function () { this.showChange(); this.build(); }; StyleSwitcher.prototype.showChange = function () { this.bgColor = this.storageManager.getBgColor(); this.fgColor = this.storageManager.getFgColor(); this.bgImage = this.storageManager.getBgImage(); this.postLess(this.bgColor, this.fgColor, this.bgImage); }; StyleSwitcher.prototype.build = function () { var $this = this; $this.storageManager = new LocalStorageManager(); var winlocpath = window.location.pathname.toString(); var imgPath = ""; if ($('body').css('direction') === "rtl") { $('body').addClass('rtl'); } if (winlocpath.indexOf("/rtl/") > -1) { imgPath += "../"; } $('body').css({ 'background-image': 'url(' + imgPath + 'assets/img/pattern/' + $this.storageManager.getBgImage() + '.png)', 'background-repeat': ' repeat' }); var modalHTML = '<div id="getCSSModal" class="modal fade">' + '<div class="modal-dialog">' + '<div class="modal-content">' + '<div class="modal-header">' + '<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>' + '<h4 class="modal-title">Theme CSS</h4>' + '<code>Copy textarea content and paste into theme.css</code>' + '</div> ' + '<div class="modal-body">' + '<textarea class="form-control" name="cssbeautify" id="cssbeautify" readonly></textarea>' + '</div> ' + '<div class="modal-footer">' + '<button aria-hidden="true" data-dismiss="modal" class="btn btn-danger">Close</button>' + '</div> ' + '</div>' + '</div> ' + '</div>'; $('body').append(modalHTML); var switchDiv = $('<div />').attr('id', 'style-switcher').addClass('style-switcher hidden-xs'); var h5Ai = $('<i />').addClass('fa fa-cogs fa-2x'); var h5A = $('<a />').attr({ 'href': '#', 'id': 'switcher-link' }).on(Metis.buttonPressedEvent, function (e) { e.preventDefault(); switchDiv.toggleClass('open'); $(this).find('i').toggleClass('fa-spin'); }).append(h5Ai); var h5 = $('<h5 />').html('Style Switcher').append(h5A); var colorList = $('<ul />').addClass('options').attr('data-type', 'colors'); var colors = [ { 'Hex': '#0088CC', 'colorName': 'Blue' }, { 'Hex': '#4EB25C', 'colorName': 'Green' }, { 'Hex': '#4A5B7D', 'colorName': 'Navy' }, { 'Hex': '#E05048', 'colorName': 'Red' }, { 'Hex': '#B8A279', 'colorName': 'Beige' }, { 'Hex': '#c71c77', 'colorName': 'Pink' }, { 'Hex': '#734BA9', 'colorName': 'Purple' }, { 'Hex': '#2BAAB1', 'colorName': 'Cyan' } ]; $.each(colors, function (i) { var listElement = $('<li/>').append($('<a/>').css('background-color', colors[i].Hex).attr({ 'data-color-hex': colors[i].Hex, 'data-color-name': colors[i].colorName, 'href': '#', 'title': colors[i].colorName }).tooltip({ 'placement': 'bottom' }) ); colorList.append(listElement); }); var colorSelector; var itm = new InputTypeManager(); if (itm.ci) { colorSelector = $('<input/>').addClass('color-picker-icon').attr({ 'id': 'colorSelector', 'type': 'color' }).val($this.storageManager.getBgColor()); colorSelector.on('change', function (ev) { $this.storageManager.setBgColor($(this).val()); $this.showChange(); }); } else { var colorSelStyle = $('<link/>') .attr({ 'rel': 'stylesheet', 'href': imgPath + 'assets/lib/colorpicker/css/colorpicker.css' }), colorSelHackStyle = $('<link/>').attr({ 'rel': 'stylesheet', 'href': imgPath + 'assets/css/colorpicker_hack.css' }); colorSelector = $('<div/>').addClass('color-picker').attr({ 'id': 'colorSelector', 'data-color': $this.storageManager.getBgColor(), 'data-color-format': 'hex' }); var url = imgPath + 'assets/lib/colorpicker/js/bootstrap-colorpicker.js'; $.getScript(url, function () { $('head').append(colorSelStyle, colorSelHackStyle); colorSelector.append( $('<a/>') .css({ 'background-color': $this.storageManager.getBgColor() }) .attr({ 'href': '#', 'id': 'colorSelectorA' }) ); colorSelector.colorpicker().on('changeColor', function (ev) { colorSelector.find('a').css('background-color', ev.color.toHex()); $this.storageManager.setBgColor(ev.color.toHex()); $this.showChange(); }); }); } var colorPicker = $('<li/>').append(colorSelector); colorList.find('a').on(Metis.buttonPressedEvent, function (e) { e.preventDefault(); $this.storageManager.setBgColor($(this).data('colorHex')); $this.showChange(); colorSelector.attr('data-color', $(this).data('colorHex')); colorSelector.val($(this).data('colorHex')); colorSelector.find('a').css('background-color', $(this).data('colorHex')); }); colorList.append(colorPicker); var styleSwitcherWrap = $('<div />') .addClass('style-switcher-wrap') .append($('<h6 />').html('Background Colors'), colorList, $('<hr/>')); var fgwbtn = $('<input/>').attr({ 'type': 'radio', 'name': 'fgcolor' }).val('#ffffff').on('change', function (e) { $this.storageManager.setFgColor('#ffffff'); $this.showChange(); }); var fontWhite = $('<label/>').addClass('btn btn-xs btn-primary').html('White').append(fgwbtn); var fgbbtn = $('<input/>').attr({ 'type': 'radio', 'name': 'fgcolor' }).val('#333333').on('change', function (e) { $this.storageManager.setFgColor('#333333'); $this.showChange(); }); var fontBlack = $('<label/>').addClass('btn btn-xs btn-danger').html('Black').append(fgbbtn); var fgBtnGroup = $('<div/>').addClass('btn-group').attr('data-toggle', 'buttons').append(fontWhite, fontBlack); styleSwitcherWrap.append($('<div/>').addClass('options-link').append($('<h6/>').html('Font Colors'), fgBtnGroup)); var patternList = $('<ul />').addClass('options').attr('data-type', 'pattern'); var patternImages = [ { 'image': 'brillant', 'title': 'Brillant' }, { 'image': 'always_grey', 'title': 'Always Grey' }, { 'image': 'retina_wood', 'title': 'Retina Wood' }, { 'image': 'low_contrast_linen', 'title': 'Low Constrat Linen' }, { 'image': 'egg_shell', 'title': 'Egg Shel' }, { 'image': 'cartographer', 'title': 'Cartographer' }, { 'image': 'batthern', 'title': 'Batthern' }, { 'image': 'noisy_grid', 'title': 'Noisy Grid' }, { 'image': 'diamond_upholstery', 'title': 'Diamond Upholstery' }, { 'image': 'greyfloral', 'title': 'Gray Floral' }, { 'image': 'white_tiles', 'title': 'White Tiles' }, { 'image': 'gplaypattern', 'title': 'GPlay' }, { 'image': 'arches', 'title': 'Arches' }, { 'image': 'purty_wood', 'title': 'Purty Wood' }, { 'image': 'diagonal_striped_brick', 'title': 'Diagonal Striped Brick' }, { 'image': 'large_leather', 'title': 'Large Leather' }, { 'image': 'bo_play_pattern', 'title': 'BO Play' }, { 'image': 'irongrip', 'title': 'Iron Grip' }, { 'image': 'wood_1', 'title': 'Dark Wood' }, { 'image': 'pool_table', 'title': 'Pool Table' }, { 'image': 'crissXcross', 'title': 'crissXcross' }, { 'image': 'rip_jobs', 'title': 'R.I.P Steve Jobs' }, { 'image': 'random_grey_variations', 'title': 'Random Grey Variations' }, { 'image': 'carbon_fibre', 'title': 'Carbon Fibre' } ]; $.each(patternImages, function (i) { var listElement = $('<li/>').append($('<a/>').css({ 'background': 'url(' + imgPath + 'assets/img/pattern/' + patternImages[i].image + '.png) repeat' }).attr({ 'href': '#', 'title': patternImages[i].title, 'data-pattern-image': patternImages[i].image }).tooltip({ 'placement': 'bottom' }) ); patternList.append(listElement); }); patternList.find('a').on(Metis.buttonPressedEvent, function (e) { e.preventDefault(); $('body').css({ 'background-image': 'url(' + imgPath + 'assets/img/pattern/' + $(this).data('patternImage') + '.png)', 'background-repeat': ' repeat' }); $this.patternImage = $(this).data('patternImage'); $this.storageManager.setBgImage($this.patternImage); $this.showChange(); }); styleSwitcherWrap.append($('<div/>').addClass('pattern').append($('<h6/>').html('Background Pattern'), patternList ) ); var resetLink = $('<a/>').html('Reset').attr('href', '#').on(Metis.buttonPressedEvent, function (e) { $this.reset(); e.preventDefault(); }); var cssLink = $('<a/>').html('Get CSS').attr('href', '#').on(Metis.buttonPressedEvent, function (e) { e.preventDefault(); $this.getCss(); }); styleSwitcherWrap.append($('<div/>').addClass('options-link').append($('<hr/>'), resetLink, cssLink ) ); switchDiv.append(h5, styleSwitcherWrap); $('body').append(switchDiv); }; StyleSwitcher.prototype.postLess = function (bgColor, fgColor, bgImage) { this.bgc = bgColor; this.fgc = fgColor; this.bgi = bgImage; less.modifyVars({ '@bgColor': this.bgc, '@fgColor': this.fgc, '@bgImage': this.bgi }); }; StyleSwitcher.prototype.getCss = function () { var $this = this; var raw = '', options; var isFixed = $('body').hasClass('fixed'); var cssBeautify = $('#cssbeautify'); if (isFixed) { raw = 'body { background-image: url("../img/pattern/' + $this.patternImage + '.png"); }'; $('#boxedBodyAlert').removeClass('hide'); } else { $('#boxedBodyAlert').addClass('hide'); } cssBeautify.text(''); raw = raw + $('style[id^="less:"]').text(); cssBeautify.text(raw); $('#getCSSModal').modal('show'); }; StyleSwitcher.prototype.reset = function () { this.storageManager.clearItems(); this.showChange(); }; window.StyleSwitcher = new StyleSwitcher();
simtsit/gtasks
dist/assets/js/style-switcher.js
JavaScript
gpl-2.0
14,257
<?php /** * Elgg pageshell * The standard HTML page shell that everything else fits into * * @package Elgg * @subpackage Core * * @uses $vars['derecha'] Seccion derecha de la pagina (menu) * @uses $vars['izquierda'] Seccion Izquierda de la Pagina (Contenido) */ // backward compatability support for plugins that are not using the new approach // of routing through admin. See reportedcontent plugin for a simple example. if (elgg_get_context() == 'admin') { if (get_input('handler') != 'admin') { elgg_deprecated_notice("admin plugins should route through 'admin'.", 1.8); } elgg_admin_add_plugin_settings_menu(); elgg_unregister_css('elgg'); echo elgg_view('page/admin', $vars); return true; } // render content before head so that JavaScript and CSS can be loaded. See #4032 if (!elgg_is_rol_logged_user("coordinador")) { $site_url = elgg_get_site_url(); forward($site_url); } $messages = elgg_view('page/elements/messages', array('object' => $vars['sysmessages'])); $header = elgg_view('page/elements/coordinacion/header', $vars); $body = elgg_view('page/elements/coordinacion/body', $vars); // Set the content type elgg_unregister_css('inicio'); header("Content-type: text/html; charset=UTF-8"); $lang = get_current_language(); ?> <!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" xml:lang="<?php echo $lang; ?>" lang="<?php echo $lang; ?>"> <head> <?php echo elgg_view('page/elements/logged/head', $vars); ?> </head> <body> <div class="elgg-page-messages"> <?php echo $messages; ?> <?php echo $notices_html; ?> </div> <div class="todo"> <div class="header"> <?php echo $header; ?> </div> <div class="contenido"> <?php echo $body; ?> </div> </div> <footer> <?php echo elgg_view('page/elements/footer_chat', array()); ?> </footer> </body> </html>
jonreycas/enjambre
mod/tema_comunidad_ondas/views/views/default/page/coordinacion_one_column.php
PHP
gpl-2.0
2,175
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace DAI.Exception.Test { public static class Islem1 { public static void IslemYap() { ExceptionManager.getInstance().TryCatch(() => { int a = 1; int b = 2; int c = a + b; string d = IslemYap2(c); }, MethodBase.GetCurrentMethod(), "Benim hata mesajım"); } public static string IslemYap2(int c) { return ExceptionManager.getInstance().TryCatch(() => { return IslemYap3(c *= 2); }, MethodBase.GetCurrentMethod()); } public static string IslemYap3(int d) { return ExceptionManager.getInstance().TryCatch(() => { ThrowException(); return d.ToString(); }, MethodBase.GetCurrentMethod()); } public static void ThrowException() { ExceptionManager.getInstance().TryCatch(() => { int x = 1; int y = 0; int z = x / y; }, MethodBase.GetCurrentMethod(),null,i=> Console.WriteLine(i.Message.ToString())); } } }
uQr/FrameworkWithDesingPatterns
DAI.Exception.Test/Islem1.cs
C#
gpl-2.0
1,404
class GivePlayerDialog { idd = -1; movingenable = 0; enableSimulation = true; class controlsBackground { class Life_RscTitleBackground2:Life_RscText { colorBackground[] = {"(profilenamespace getvariable ['GUI_BCG_RGB_R',0.3843])", "(profilenamespace getvariable ['GUI_BCG_RGB_G',0.7019])", "(profilenamespace getvariable ['GUI_BCG_RGB_B',0.8862])", "(profilenamespace getvariable ['GUI_BCG_RGB_A',0.7])"}; idc = -1; x = 0.35; y = 0.2; w = 0.3; h = (1 / 25); }; class MainBackground2:Life_RscText { colorBackground[] = {0, 0, 0, 0.7}; idc = -1; x = 0.35; y = 0.2 + (11 / 250); w = 0.3; h = 0.6 - (22 / 250); }; }; class Controls { class CashTitle5 : Life_RscStructuredText { idc = 2710; text = "You"; colorText[] = {0.8784,0.8471,0.651,1}; x = 0.39; y = 0.26; w = 0.3; h = 0.2; }; class RscTextT_10052 : RscTextT { idc = 14001; text = ""; colorText[] = {1,1,1,1}; x = 0.39; y = 0.27; w = 0.6; h = 0.2; }; class moneyEdit2 : Life_RscEdit { idc = 14000; colorText[] = {0.8784,0.8471,0.651,1}; text = "1"; sizeEx = 0.030; x = 0.4; y = 0.41; w = 0.2; h = 0.03; }; class Title2 : Life_RscTitle { colorBackground[] = {0, 0, 0, 0}; idc = -1; text = "Transfer Coins"; colorText[] = {1,1,1,1}; x = 0.35; y = 0.2; w = 0.6; h = (1 / 25); }; class DepositButton2 : life_RscButtonMenu { idc = -1; text = "Give"; colorBackground[] = {"(profilenamespace getvariable ['GUI_BCG_RGB_R',0.3843])", "(profilenamespace getvariable ['GUI_BCG_RGB_G',0.7019])", "(profilenamespace getvariable ['GUI_BCG_RGB_B',0.8862])", 0.5}; onButtonClick = "[(ctrlText 14000)] spawn GivePlayerAmount; ((ctrlParent (_this select 0)) closeDisplay 9000);"; colorText[] = {0.8784,0.8471,0.651,1}; x = 0.432; y = 0.512; w = (6 / 40); h = (1 / 25); }; class RscTextT_10005 : RscTextT { idc = 14003; text = ""; colorText[] = {0.8784,0.8471,0.651,1}; x = 0.39; y = 0.58; w = 0.3; h = 0.2; }; class CloseButtonKey2 : Life_RscButtonMenu { idc = -1; text = "Close"; onButtonClick = "((ctrlParent (_this select 0)) closeDisplay 9000);"; x = 0.35; y = 0.8 - (1 / 25); w = (6.25 / 40); h = (1 / 25); }; }; };
rmnelson/dayz
mission_files/MPMissions/DayZ_Overpoch_Test.Chernarus/gold/give_player_dialog.hpp
C++
gpl-2.0
2,347
/* ** File: evisgenericeventbrowsergui.cpp ** Author: Peter J. Ersts ( ersts at amnh.org ) ** Creation Date: 2007-03-08 ** ** Copyright ( c ) 2007, American Museum of Natural History. All rights reserved. ** ** This library/program is free software; you can redistribute it ** and/or modify it under the terms of the GNU Library General Public ** License as published by the Free Software Foundation; either ** version 2 of the License, or ( at your option ) any later version. ** ** This library/program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Library General Public License for more details. ** ** This work was made possible through a grant by the the John D. and ** Catherine T. MacArthur Foundation. Additionally, this program was prepared by ** the American Museum of Natural History under award No. NA05SEC46391002 ** from the National Oceanic and Atmospheric Administration, U.S. Department ** of Commerce. The statements, findings, conclusions, and recommendations ** are those of the author( s ) and do not necessarily reflect the views of the ** National Oceanic and Atmospheric Administration or the Department of Commerce. ** **/ #include "evisgenericeventbrowsergui.h" #include "qgsapplication.h" #include "qgsmaprenderer.h" #include "qgsmaptopixel.h" #include "qgsmapcanvas.h" #include "qgsgeometry.h" #include "qgslogger.h" #include "qgspoint.h" #include "qgsfield.h" #include "qgsrectangle.h" #include <QMessageBox> #include <QTreeWidgetItem> #include <QGraphicsScene> #include <QSettings> #include <QPainter> #include <QProcess> #include <QFileDialog> /** * Constructor called when browser is launched from the application plugin tool bar * @param parent - Pointer the to parent QWidget for modality * @param interface - Pointer the the application interface * @param fl - Window flags */ eVisGenericEventBrowserGui::eVisGenericEventBrowserGui( QWidget* parent, QgisInterface* interface, Qt::WFlags fl ) : QDialog( parent, fl ) { setupUi( this ); QSettings settings; restoreGeometry( settings.value( "/eVis/browser-geometry" ).toByteArray() ); mCurrentFeatureIndex = 0; mInterface = interface; mDataProvider = 0; mVectorLayer = 0; mCanvas = 0; mIgnoreEvent = false; if ( initBrowser( ) ) { loadRecord( ); show( ); } else { close( ); } } /** * Constructor called when browser is launched by the eVisEventIdTool * @param parent - Pointer to the parent QWidget for modality * @param canvas - Pointer to the map canvas * @param fl - Window flags */ eVisGenericEventBrowserGui::eVisGenericEventBrowserGui( QWidget* parent, QgsMapCanvas* canvas, Qt::WFlags fl ) : QDialog( parent, fl ) { setupUi( this ); mCurrentFeatureIndex = 0; mInterface = 0; mDataProvider = 0; mVectorLayer = 0; mCanvas = canvas; mIgnoreEvent = false; if ( initBrowser( ) ) { loadRecord( ); show( ); } else { close( ); } } /** * Basic descructor */ eVisGenericEventBrowserGui::~eVisGenericEventBrowserGui( ) { QSettings settings; settings.setValue( "/eVis/browser-geometry", saveGeometry() ); //Clean up, disconnect the highlighting routine and refesh the canvase to clear highlighting symbol if ( 0 != mCanvas ) { disconnect( mCanvas, SIGNAL( renderComplete( QPainter * ) ), this, SLOT( renderSymbol( QPainter * ) ) ); mCanvas->refresh( ); } //On close, clear selected feature if ( 0 != mVectorLayer ) { mVectorLayer->removeSelection( false ); } } /** * This method is an extension of the constructor. It was implemented to reduce the amount of code duplicated between the constuctors. */ bool eVisGenericEventBrowserGui::initBrowser( ) { //setup gui setWindowTitle( tr( "Generic Event Browser" ) ); connect( treeEventData, SIGNAL( itemDoubleClicked( QTreeWidgetItem *, int ) ), this, SLOT( launchExternalApplication( QTreeWidgetItem *, int ) ) ); mHighlightSymbol.load( ":/evis/eVisHighlightSymbol.png" ); mPointerSymbol.load( ":/evis/eVisPointerSymbol.png" ); mCompassOffset = 0.0; //Flag to let us know if the browser fully loaded mBrowserInitialized = false; //Initialize some class variables mDefaultEventImagePathField = 0; mDefaultCompassBearingField = 0; mDefaultCompassOffsetField = 0; //initialize Display tab GUI elements pbtnNext->setEnabled( false ); pbtnPrevious->setEnabled( false ); //Set up Attribute display treeEventData->setColumnCount( 2 ); QStringList treeHeaders; treeHeaders << tr( "Field" ) << tr( "Value" ); treeEventData->setHeaderLabels( treeHeaders ); //Initialize Options tab GUI elements cboxEventImagePathField->setEnabled( true ); chkboxEventImagePathRelative->setChecked( false ); chkboxDisplayCompassBearing->setChecked( false ); cboxCompassBearingField->setEnabled( true ); rbtnManualCompassOffset->setChecked( false ); dsboxCompassOffset->setEnabled( true ); dsboxCompassOffset->setValue( 0.0 ); rbtnAttributeCompassOffset->setChecked( false ); cboxCompassOffsetField->setEnabled( true ); chkboxUseOnlyFilename->setChecked( false ); QString myThemePath = QgsApplication::activeThemePath( ); pbtnResetEventImagePathData->setIcon( QIcon( QPixmap( myThemePath + "/mActionDraw.png" ) ) ); pbtnResetCompassBearingData->setIcon( QIcon( QPixmap( myThemePath + "/mActionDraw.png" ) ) ); pbtnResetCompassOffsetData->setIcon( QIcon( QPixmap( myThemePath + "/mActionDraw.png" ) ) ); pbtnResetBasePathData->setIcon( QIcon( QPixmap( myThemePath + "/mActionDraw.png" ) ) ); pbtnResetUseOnlyFilenameData->setIcon( QIcon( QPixmap( myThemePath + "/mActionDraw.png" ) ) ); pbtnResetApplyPathRulesToDocs->setIcon( QIcon( QPixmap( myThemePath + "/mActionDraw.png" ) ) ); chkboxSaveEventImagePathData->setChecked( false ); chkboxSaveCompassBearingData->setChecked( false ); chkboxSaveCompassOffsetData->setChecked( false ); chkboxSaveBasePathData->setChecked( false ); chkboxSaveUseOnlyFilenameData->setChecked( false ); //Set up Configure External Application buttons pbtnAddFileType->setIcon( QIcon( QPixmap( myThemePath + "/mActionNewAttribute.png" ) ) ); pbtnDeleteFileType->setIcon( QIcon( QPixmap( myThemePath + "/mActionDeleteAttribute.png" ) ) ); //Check to for interface, not null when launched from plugin toolbar, otherwise expect map canvas if ( 0 != mInterface ) { //check for active layer if ( mInterface->activeLayer( ) ) { //verify that the active layer is a vector layer if ( QgsMapLayer::VectorLayer == mInterface->activeLayer( )->type( ) ) { mVectorLayer = ( QgsVectorLayer* )mInterface->activeLayer( ); mCanvas = mInterface->mapCanvas( ); } else { QMessageBox::warning( this, tr( "Warning" ), tr( "This tool only supports vector data" ) ); return false; } } else { QMessageBox::warning( this, tr( "Warning" ), tr( "No active layers found" ) ); return false; } } //check for map canvas, if map canvas is null, throw error else if ( 0 != mCanvas ) { //check for active layer if ( mCanvas->currentLayer( ) ) { //verify that the active layer is a vector layer if ( QgsMapLayer::VectorLayer == mCanvas->currentLayer( )->type( ) ) { mVectorLayer = ( QgsVectorLayer* )mCanvas->currentLayer( ); } else { QMessageBox::warning( this, tr( "Warning" ), tr( "This tool only supports vector data" ) ); return false; } } else { QMessageBox::warning( this, tr( "Warning" ), tr( "No active layers found" ) ); return false; } } else { QMessageBox::warning( this, tr( "Error" ), tr( "Unable to connect to either the map canvas or application interface" ) ); return false; } //Connect rendering routine for highlighting symbols and load symbols connect( mCanvas, SIGNAL( renderComplete( QPainter * ) ), this, SLOT( renderSymbol( QPainter * ) ) ); mDataProvider = mVectorLayer->dataProvider( ); /* * A list of the selected feature ids is made so that we can move forward and backward through * the list. The data providers only have the ability to get one feature at a time or * sequentially move forward through the selected features */ if ( 0 == mVectorLayer->selectedFeatureCount( ) ) //if nothing is selected select everything { mVectorLayer->invertSelection(); mFeatureIds = mVectorLayer->selectedFeaturesIds().toList(); } else //use selected features { mFeatureIds = mVectorLayer->selectedFeaturesIds().toList(); } if ( 0 == mFeatureIds.size() ) return false; //get the first feature in the list so we can set the field in the pulldown menues QgsFeature* myFeature = featureAtId( mFeatureIds.at( mCurrentFeatureIndex ) ); if ( !myFeature ) { QMessageBox::warning( this, tr( "Error" ), tr( "An invalid feature was received during initialization" ) ); return false; } QgsFieldMap myFieldMap = mDataProvider->fields( ); QgsAttributeMap myAttributeMap = myFeature->attributeMap( ); mIgnoreEvent = true; //Ignore indexChanged event when adding items to combo boxes for ( int x = 0; x < myFieldMap.size( ); x++ ) { cboxEventImagePathField->addItem( myFieldMap[x].name( ) ); cboxCompassBearingField->addItem( myFieldMap[x].name( ) ); cboxCompassOffsetField->addItem( myFieldMap[x].name( ) ); if ( myAttributeMap[x].toString( ).contains( QRegExp( "(jpg|jpeg|tif|tiff|gif)", Qt::CaseInsensitive ) ) ) { mDefaultEventImagePathField = x; } if ( myFieldMap[x].name( ).contains( QRegExp( "(comp|bear)", Qt::CaseInsensitive ) ) ) { mDefaultCompassBearingField = x; } if ( myFieldMap[x].name( ).contains( QRegExp( "(offset|declination)", Qt::CaseInsensitive ) ) ) { mDefaultCompassOffsetField = x; } } mIgnoreEvent = false; //Set Display tab gui items if ( mFeatureIds.size( ) > 1 ) { pbtnNext->setEnabled( true ); } setWindowTitle( tr( "Event Browser - Displaying records 01 of %1" ).arg( mFeatureIds.size(), 2, 10, QChar( '0' ) ) ); //Set Options tab gui items initOptionsTab( ); //Load file associations into Configure External Applications tab gui items QSettings myQSettings; myQSettings.beginWriteArray( "/eVis/filetypeassociations" ); int myTotalAssociations = myQSettings.childGroups( ).count( ); int myIterator = 0; while ( myIterator < myTotalAssociations ) { myQSettings.setArrayIndex( myIterator ); tableFileTypeAssociations->insertRow( tableFileTypeAssociations->rowCount( ) ); tableFileTypeAssociations->setItem( myIterator, 0, new QTableWidgetItem( myQSettings.value( "extension", "" ).toString( ) ) ); tableFileTypeAssociations->setItem( myIterator, 1, new QTableWidgetItem( myQSettings.value( "application", "" ).toString( ) ) ); myIterator++; } myQSettings.endArray( ); mBrowserInitialized = true; return true; } /** * This method is an extension of the constructor. It was implemented so that it could be called by the GUI at anytime. */ void eVisGenericEventBrowserGui::initOptionsTab( ) { //The base path has to be set first. If not if/when cboxEventImagePathRelative state change slot //will all ways over write the base path with the path to the data source //TODO: Find some better logic to prevent this from happening. leBasePath->setText( mConfiguration.basePath( ) ); chkboxUseOnlyFilename->setChecked( mConfiguration.isUseOnlyFilenameSet( ) ); //Set Options tab gui items int myIndex = cboxEventImagePathField->findText( mConfiguration.eventImagePathField( ), Qt::MatchExactly ); if ( -1 != myIndex ) { cboxEventImagePathField->setCurrentIndex( myIndex ); } else { cboxEventImagePathField->setCurrentIndex( mDefaultEventImagePathField ); } chkboxEventImagePathRelative->setChecked( mConfiguration.isEventImagePathRelative( ) ); myIndex = cboxCompassBearingField->findText( mConfiguration.compassBearingField( ), Qt::MatchExactly ); if ( -1 != myIndex ) { cboxCompassBearingField->setCurrentIndex( myIndex ); } else { cboxCompassBearingField->setCurrentIndex( mDefaultCompassBearingField ); } chkboxDisplayCompassBearing->setChecked( mConfiguration.isDisplayCompassBearingSet( ) ); if ( !mConfiguration.isDisplayCompassBearingSet( ) ) { cboxCompassBearingField->setEnabled( false ); } dsboxCompassOffset->setValue( mConfiguration.compassOffset( ) ); myIndex = cboxCompassOffsetField->findText( mConfiguration.compassOffsetField( ), Qt::MatchExactly ); if ( -1 != myIndex ) { cboxCompassOffsetField->setCurrentIndex( myIndex ); } else { loadRecord( ); cboxCompassOffsetField->setCurrentIndex( mDefaultCompassOffsetField ); } if ( mConfiguration.isManualCompassOffsetSet( ) ) { rbtnManualCompassOffset->setChecked( true ); rbtnAttributeCompassOffset->setChecked( false ); } else if ( !mConfiguration.compassOffsetField().isEmpty() ) { rbtnManualCompassOffset->setChecked( false ); rbtnAttributeCompassOffset->setChecked( true ); } else { rbtnManualCompassOffset->setChecked( false ); rbtnAttributeCompassOffset->setChecked( false ); dsboxCompassOffset->setEnabled( false ); cboxCompassOffsetField->setEnabled( false ); } chkboxApplyPathRulesToDocs->setChecked( mConfiguration.isApplyPathRulesToDocsSet( ) ); } void eVisGenericEventBrowserGui::closeEvent( QCloseEvent *event ) { if ( mBrowserInitialized ) { accept( ); event->accept( ); } } void eVisGenericEventBrowserGui::accept( ) { QSettings myQSettings; if ( chkboxSaveEventImagePathData->isChecked( ) ) { myQSettings.setValue( "/eVis/eventimagepathfield", cboxEventImagePathField->currentText( ) ); myQSettings.setValue( "/eVis/eventimagepathrelative", chkboxEventImagePathRelative->isChecked( ) ); } if ( chkboxSaveCompassBearingData->isChecked( ) ) { myQSettings.setValue( "/eVis/compassbearingfield", cboxCompassBearingField->currentText( ) ); myQSettings.setValue( "/eVis/displaycompassbearing", chkboxDisplayCompassBearing->isChecked( ) ); } if ( chkboxSaveCompassOffsetData->isChecked( ) ) { myQSettings.setValue( "/eVis/manualcompassoffset", rbtnManualCompassOffset->isChecked( ) ); myQSettings.setValue( "/eVis/compassoffset", dsboxCompassOffset->value( ) ); myQSettings.setValue( "/eVis/attributecompassoffset", rbtnAttributeCompassOffset->isChecked( ) ); myQSettings.setValue( "/eVis/compassoffsetfield", cboxCompassOffsetField->currentText( ) ); } if ( chkboxSaveBasePathData->isChecked( ) ) { myQSettings.setValue( "/eVis/basepath", leBasePath->text( ) ); } if ( chkboxSaveUseOnlyFilenameData->isChecked( ) ) { myQSettings.setValue( "/eVis/useonlyfilename", chkboxUseOnlyFilename->isChecked( ) ); } if ( chkboxSaveApplyPathRulesToDocs->isChecked( ) ) { myQSettings.setValue( "/eVis/applypathrulestodocs", chkboxApplyPathRulesToDocs->isChecked( ) ); } myQSettings.remove( "/eVis/filetypeassociations" ); myQSettings.beginWriteArray( "/eVis/filetypeassociations" ); int myIterator = 0; int myIndex = 0; while ( myIterator < tableFileTypeAssociations->rowCount( ) ) { myQSettings.setArrayIndex( myIndex ); if ( 0 != tableFileTypeAssociations->item( myIterator, 0 ) && 0 != tableFileTypeAssociations->item( myIterator, 1 ) ) { myQSettings.setValue( "extension", tableFileTypeAssociations->item( myIterator, 0 )->text( ) ); myQSettings.setValue( "application", tableFileTypeAssociations->item( myIterator, 1 )->text( ) ); myIndex++; } myIterator++; } myQSettings.endArray( ); } /** * Modifies the Event Image Path according to the local and global settings */ void eVisGenericEventBrowserGui::buildEventImagePath( ) { //This if statement is a bit of a hack, have to track down where the 0 is comming from on initalization if ( "0" != mEventImagePath ) { int myImageNameMarker = 0; if ( mEventImagePath.contains( '/' ) ) { myImageNameMarker = mEventImagePath.lastIndexOf( '/' ); } else { myImageNameMarker = mEventImagePath.lastIndexOf( '\\' ); } QString myImageName = mEventImagePath; myImageName.remove( 0, myImageNameMarker + 1 ); if ( mConfiguration.isUseOnlyFilenameSet( ) ) { mEventImagePath = mConfiguration.basePath( ) + myImageName; } else { if ( mConfiguration.isEventImagePathRelative( ) ) { mEventImagePath = mConfiguration.basePath( ) + mEventImagePath; } } } } /** * Chooses which image loading method to use and centers the map canvas on the current feature */ void eVisGenericEventBrowserGui::displayImage( ) { //This if statement is a bit of a hack, have to track down where the 0 is comming from on initalization if ( "0" != mEventImagePath && 0 == displayArea->currentIndex( ) ) { if ( mEventImagePath.startsWith( "http://", Qt::CaseInsensitive ) ) { imageDisplayArea->displayUrlImage( mEventImagePath ); } else { imageDisplayArea->displayImage( mEventImagePath ); } //clear any selection that may be present mVectorLayer->removeSelection( false ); if ( mFeatureIds.size( ) > 0 ) { //select the current feature in the layer mVectorLayer->select( mFeatureIds.at( mCurrentFeatureIndex ), true ); //get a copy of the feature QgsFeature* myFeature = featureAtId( mFeatureIds.at( mCurrentFeatureIndex ) ); if ( 0 == myFeature ) return; QgsPoint myPoint = myFeature->geometry( )->asPoint( ); myPoint = mCanvas->mapRenderer( )->layerToMapCoordinates( mVectorLayer, myPoint ); //keep the extent the same just center the map canvas in the display so our feature is in the middle QgsRectangle myRect( myPoint.x( ) - ( mCanvas->extent( ).width( ) / 2 ), myPoint.y( ) - ( mCanvas->extent( ).height( ) / 2 ), myPoint.x( ) + ( mCanvas->extent( ).width( ) / 2 ), myPoint.y( ) + ( mCanvas->extent( ).height( ) / 2 ) ); // only change the extents if the point is beyond the current extents to minimise repaints if ( !mCanvas->extent().contains( myPoint ) ) { mCanvas->setExtent( myRect ); } mCanvas->refresh( ); } } } /** * Returns a pointer to the reqested feature with a given featureid * @param id - FeatureId of the feature to find/select */ QgsFeature* eVisGenericEventBrowserGui::featureAtId( QgsFeatureId id ) { //This method was originally necessary because delimited text data provider did not support featureAtId( ) //It has mostly been stripped down now if ( mDataProvider && mFeatureIds.size( ) != 0 ) { if ( !mVectorLayer->featureAtId( id, mFeature, true, true ) ) { return 0; } } return &mFeature; } /** * Display the attrbiutes for the current feature and load the image */ void eVisGenericEventBrowserGui::loadRecord( ) { treeEventData->clear(); //Get a pointer to the current feature QgsFeature* myFeature; myFeature = featureAtId( mFeatureIds.at( mCurrentFeatureIndex ) ); if ( 0 == myFeature ) return; QString myCompassBearingField = cboxCompassBearingField->currentText( ); QString myCompassOffsetField = cboxCompassOffsetField->currentText( ); QString myEventImagePathField = cboxEventImagePathField->currentText( ); QgsFieldMap myFieldMap = mDataProvider->fields( ); QgsAttributeMap myAttributeMap = myFeature->attributeMap( ); //loop through the attributes and display their contents for ( QgsAttributeMap::const_iterator it = myAttributeMap.begin( ); it != myAttributeMap.end( ); ++it ) { QStringList myValues; myValues << myFieldMap[it.key( )].name( ) << it->toString( ); QTreeWidgetItem* myItem = new QTreeWidgetItem( myValues ); if ( myFieldMap[it.key( )].name( ) == myEventImagePathField ) { mEventImagePath = it->toString( ); } if ( myFieldMap[it.key( )].name( ) == myCompassBearingField ) { mCompassBearing = it->toDouble( ); } if ( mConfiguration.isAttributeCompassOffsetSet( ) ) { if ( myFieldMap[it.key( )].name( ) == myCompassOffsetField ) { mCompassOffset = it->toDouble( ); } } else { mCompassOffset = 0.0; } //Check to see if the attribute is a know file type int myIterator = 0; while ( myIterator < tableFileTypeAssociations->rowCount( ) ) { if ( tableFileTypeAssociations->item( myIterator, 0 ) && ( it->toString( ).startsWith( tableFileTypeAssociations->item( myIterator, 0 )->text( ) + ":", Qt::CaseInsensitive ) || it->toString( ).endsWith( tableFileTypeAssociations->item( myIterator, 0 )->text( ), Qt::CaseInsensitive ) ) ) { myItem->setBackground( 1, QBrush( QColor( 183, 216, 125, 255 ) ) ); break; } else myIterator++; } treeEventData->addTopLevelItem( myItem ); } //Modify EventImagePath as needed buildEventImagePath( ); //Request the image to be displayed in the browser displayImage( ); } /** * Restore the default configuration options */ void eVisGenericEventBrowserGui::restoreDefaultOptions( ) { chkboxEventImagePathRelative->setChecked( false ); cboxEventImagePathField->setCurrentIndex( mDefaultEventImagePathField ); cboxCompassBearingField->setEnabled( true ); cboxCompassBearingField->setCurrentIndex( mDefaultCompassBearingField ); cboxCompassBearingField->setEnabled( false ); chkboxDisplayCompassBearing->setChecked( false ); cboxCompassOffsetField->setEnabled( true ); cboxCompassOffsetField->setCurrentIndex( mDefaultCompassOffsetField ); cboxCompassOffsetField->setEnabled( false ); rbtnManualCompassOffset->setChecked( true ); dsboxCompassOffset->setValue( 0.0 ); leBasePath->setText( "" ); chkboxUseOnlyFilename->setChecked( false ); chkboxSaveEventImagePathData->setChecked( false ); chkboxSaveCompassBearingData->setChecked( false ); chkboxSaveCompassOffsetData->setChecked( false ); chkboxSaveBasePathData->setChecked( false ); chkboxSaveUseOnlyFilenameData->setChecked( false ); chkboxApplyPathRulesToDocs->setChecked( false ); } /** * Sets the base path to the path of the data source */ void eVisGenericEventBrowserGui::setBasePathToDataSource( ) { //Noticed some strangeness here while cleaning up for migration to the QGIS trunk - PJE 2009-07-01 //TODO: The check for windows paths not longer does anything, remove or fix int myPathMarker = 0; bool isWindows = false; QString mySourceUri = mDataProvider->dataSourceUri( ); //Check to see which way the directory symbol goes, I think this is actually unnecessary in qt if ( mySourceUri.contains( '/' ) ) { myPathMarker = mySourceUri.lastIndexOf( '/' ); } else { myPathMarker = mySourceUri.lastIndexOf( '\\' ); } //Strip off the actual filename so we just have path mySourceUri.truncate( myPathMarker + 1 ); //check for duplicate directory symbols when concatinating the two strings if ( isWindows ) { mySourceUri.replace( "\\\\", "\\" ); } else { if ( mySourceUri.startsWith( "http://", Qt::CaseInsensitive ) ) { mySourceUri.replace( "//", "/" ); mySourceUri.replace( "http:/", "http://", Qt::CaseInsensitive ); } else { mySourceUri.replace( "//", "/" ); } } leBasePath->setText( mySourceUri ); } /* * * Public and Private Slots * */ /** * Slot called when a column is clicked in the tree displaying the attribute data * @param theItem - The tree widget item click * @param theColumn - The column that was clicked */ void eVisGenericEventBrowserGui::launchExternalApplication( QTreeWidgetItem * theItem, int theColumn ) { // At this point there is only attribute data with no children, ignore clicks on field name if ( 1 == theColumn ) { int myIterator = 0; bool startsWithExtension = false; while ( myIterator < tableFileTypeAssociations->rowCount( ) ) { if ( theItem->text( theColumn ).startsWith( tableFileTypeAssociations->item( myIterator, 0 )->text( ) + ":", Qt::CaseInsensitive ) ) { startsWithExtension = true; break; } else if ( theItem->text( theColumn ).endsWith( tableFileTypeAssociations->item( myIterator, 0 )->text( ), Qt::CaseInsensitive ) ) { startsWithExtension = false; break; } else myIterator++; } if ( myIterator != tableFileTypeAssociations->rowCount( ) ) { QProcess *myProcess = new QProcess( ); QString myApplication = tableFileTypeAssociations->item( myIterator, 1 )->text( ); QString myDocument = theItem->text( theColumn ); if ( startsWithExtension ) { myDocument = theItem->text( theColumn ).remove( tableFileTypeAssociations->item( myIterator, 0 )->text( ) + ":", Qt::CaseInsensitive ); } if ( "" != myApplication ) { if ( mConfiguration.isApplyPathRulesToDocsSet( ) ) { int myDocumentNameMarker = 0; if ( myDocument.contains( '/' ) ) { myDocumentNameMarker = myDocument.lastIndexOf( '/' ); } else { myDocumentNameMarker = myDocument.lastIndexOf( '\\' ); } QString myDocumentName = myDocument; myDocumentName.remove( 0, myDocumentNameMarker + 1 ); if ( mConfiguration.isUseOnlyFilenameSet( ) ) { myDocument = mConfiguration.basePath( ) + myDocumentName; } else { if ( mConfiguration.isEventImagePathRelative( ) ) { myDocument = mConfiguration.basePath( ) + myDocument; } } } myProcess->start( myApplication, QStringList( ) << myDocument ); } } else { QMessageBox::information( this, tr( "Attribute Contents" ), theItem->text( theColumn ) ); } } } /** * Slot called when the restore or save button is click on the options panel * @param state - The new state of the checkbox */ void eVisGenericEventBrowserGui::on_buttonboxOptions_clicked( QAbstractButton* theButton ) { if ( QDialogButtonBox::ResetRole == buttonboxOptions->buttonRole( theButton ) ) { restoreDefaultOptions( ); } else if ( QDialogButtonBox::AcceptRole == buttonboxOptions->buttonRole( theButton ) ) { accept( ); } } /** * Slot called when the state changes for the chkboxApplyPathRulesToDocs check box. * @param theState - The new state of the checkbox */ void eVisGenericEventBrowserGui::on_chkboxApplyPathRulesToDocs_stateChanged( int theState ) { Q_UNUSED( theState ); mConfiguration.setApplyPathRulesToDocs( chkboxApplyPathRulesToDocs->isChecked( ) ); } /** * Slot called when the index changes for the cboxEventImagePathField combo box. * @param theIndex - The index of the new selected item */ void eVisGenericEventBrowserGui::on_cboxEventImagePathField_currentIndexChanged( int theIndex ) { Q_UNUSED( theIndex ); if ( !mIgnoreEvent ) { mConfiguration.setEventImagePathField( cboxEventImagePathField->currentText( ) ); QgsFieldMap myFieldMap = mDataProvider->fields( ); QgsFeature* myFeature = featureAtId( mFeatureIds.at( mCurrentFeatureIndex ) ); if ( 0 == myFeature ) return; QgsAttributeMap myAttributeMap = myFeature->attributeMap( ); for ( QgsAttributeMap::const_iterator it = myAttributeMap.begin( ); it != myAttributeMap.end( ); ++it ) { if ( myFieldMap[it.key( )].name( ) == cboxEventImagePathField->currentText( ) ) { mEventImagePath = it->toString( ); } } } } /** * Slot called when the index changes for the cboxCompassBearingField combo box. * @param theIndex - The index of the new selected item */ void eVisGenericEventBrowserGui::on_cboxCompassBearingField_currentIndexChanged( int theIndex ) { Q_UNUSED( theIndex ); if ( !mIgnoreEvent ) { mConfiguration.setCompassBearingField( cboxCompassBearingField->currentText( ) ); QgsFieldMap myFieldMap = mDataProvider->fields( ); QgsFeature* myFeature = featureAtId( mFeatureIds.at( mCurrentFeatureIndex ) ); if ( 0 == myFeature ) return; QgsAttributeMap myAttributeMap = myFeature->attributeMap( ); for ( QgsAttributeMap::const_iterator it = myAttributeMap.begin( ); it != myAttributeMap.end( ); ++it ) { if ( myFieldMap[it.key( )].name( ) == cboxCompassBearingField->currentText( ) ) { mCompassBearing = it->toDouble( ); } } } } /** * Slot called when the index changes for the cboxCompassBearingField combo box. * @param theIndex - The index of the new selected item */ void eVisGenericEventBrowserGui::on_cboxCompassOffsetField_currentIndexChanged( int theIndex ) { Q_UNUSED( theIndex ); if ( !mIgnoreEvent ) { mConfiguration.setCompassOffsetField( cboxCompassOffsetField->currentText( ) ); QgsFieldMap myFieldMap = mDataProvider->fields( ); QgsFeature* myFeature = featureAtId( mFeatureIds.at( mCurrentFeatureIndex ) ); if ( 0 == myFeature ) return; QgsAttributeMap myAttributeMap = myFeature->attributeMap( ); for ( QgsAttributeMap::const_iterator it = myAttributeMap.begin( ); it != myAttributeMap.end( ); ++it ) { if ( myFieldMap[it.key( )].name( ) == cboxCompassOffsetField->currentText( ) ) { mCompassOffset = it->toDouble( ); } } } } /** * Slot called when the chkDisplayCompassBearing radio button is toggled * @param theState - The current selection state of the radio button */ void eVisGenericEventBrowserGui::on_chkboxDisplayCompassBearing_stateChanged( int theState ) { Q_UNUSED( theState ); mConfiguration.setDisplayCompassBearing( chkboxDisplayCompassBearing->isChecked( ) ); cboxCompassBearingField->setEnabled( chkboxDisplayCompassBearing->isChecked( ) ); } /** * Slot called when the state changes for the chkboxEventImagePathRelative check box. * @param theState - The new state of the checkbox */ void eVisGenericEventBrowserGui::on_chkboxEventImagePathRelative_stateChanged( int theState ) { Q_UNUSED( theState ); mConfiguration.setEventImagePathRelative( chkboxEventImagePathRelative->isChecked( ) ); if ( chkboxEventImagePathRelative->isChecked( ) && "" == leBasePath->text( ) ) { setBasePathToDataSource( ); } } /** * Slot called when the state changes for the chkboxUseOnlyFilename check box. * @param theState - The new state of the checkbox */ void eVisGenericEventBrowserGui::on_chkboxUseOnlyFilename_stateChanged( int theState ) { Q_UNUSED( theState ); mConfiguration.setUseOnlyFilename( chkboxUseOnlyFilename->isChecked( ) ); } /** * Slot called when the tabs in the tabWidget are selected * @param theCurrentTabIndex - The index of the currently selected tab */ void eVisGenericEventBrowserGui::on_displayArea_currentChanged( int theCurrentTabIndex ) { //Force redraw when we switching back to the Display tab if ( 0 == theCurrentTabIndex ) { loadRecord( ); } } /** * Slot called when a manual compass offset is entered * @param theValue - The new compass offset */ void eVisGenericEventBrowserGui::on_dsboxCompassOffset_valueChanged( double theValue ) { mConfiguration.setCompassOffset( theValue ); } /** * Slot called the text in leBasePath is set or changed * @param theText - The new base path */ void eVisGenericEventBrowserGui::on_leBasePath_textChanged( QString theText ) { mConfiguration.setBasePath( theText ); } /** * Slot called when the pbtnAddFileType button is clicked - adds a new row to the file associations table */ void eVisGenericEventBrowserGui::on_pbtnAddFileType_clicked( ) { tableFileTypeAssociations->insertRow( tableFileTypeAssociations->rowCount( ) ); } /** * Slot called when the pbtnDeleteFileType button is clicked - removes arow from the file associations table */ void eVisGenericEventBrowserGui::on_pbtnDeleteFileType_clicked( ) { if ( 1 <= tableFileTypeAssociations->rowCount( ) ) { tableFileTypeAssociations->removeRow( tableFileTypeAssociations->currentRow( ) ); } } /** * Slot called when the pbtnNext button is pressed */ void eVisGenericEventBrowserGui::on_pbtnNext_clicked( ) { if ( mCurrentFeatureIndex != mFeatureIds.size( ) - 1 ) { pbtnPrevious->setEnabled( true ); mCurrentFeatureIndex++; setWindowTitle( tr( "Event Browser - Displaying records %1 of %2" ) .arg( mCurrentFeatureIndex + 1, 2, 10, QChar( '0' ) ).arg( mFeatureIds.size(), 2, 10, QChar( '0' ) ) ); loadRecord( ); } if ( mCurrentFeatureIndex == mFeatureIds.size( ) - 1 ) { pbtnNext->setEnabled( false ); } } /** * Slot called when the pbtnPrevious button is pressed */ void eVisGenericEventBrowserGui::on_pbtnPrevious_clicked( ) { if ( mCurrentFeatureIndex > 0 ) { pbtnNext->setEnabled( true ); mCurrentFeatureIndex--; setWindowTitle( tr( "Event Browser - Displaying records %1 of %2" ) .arg( mCurrentFeatureIndex + 1, 2, 10, QChar( '0' ) ).arg( mFeatureIds.size(), 2, 10, QChar( '0' ) ) ); loadRecord( ); } if ( mCurrentFeatureIndex == 0 ) { pbtnPrevious->setEnabled( false ); } } void eVisGenericEventBrowserGui::on_pbtnResetApplyPathRulesToDocs_clicked( ) { chkboxApplyPathRulesToDocs->setChecked( false ); } void eVisGenericEventBrowserGui::on_pbtnResetBasePathData_clicked( ) { leBasePath->setText( "" ); if ( chkboxEventImagePathRelative->isChecked( ) ) { setBasePathToDataSource( ); } } void eVisGenericEventBrowserGui::on_pbtnResetCompassBearingData_clicked( ) { cboxCompassBearingField->setEnabled( true ); cboxCompassBearingField->setCurrentIndex( mDefaultCompassBearingField ); cboxCompassBearingField->setEnabled( false ); chkboxDisplayCompassBearing->setChecked( false ); } void eVisGenericEventBrowserGui::on_pbtnResetCompassOffsetData_clicked( ) { cboxCompassOffsetField->setEnabled( true ); cboxCompassOffsetField->setCurrentIndex( mDefaultCompassOffsetField ); cboxCompassOffsetField->setEnabled( false ); rbtnManualCompassOffset->setChecked( true ); dsboxCompassOffset->setValue( 0.0 ); } void eVisGenericEventBrowserGui::on_pbtnResetEventImagePathData_clicked( ) { chkboxEventImagePathRelative->setChecked( false ); cboxEventImagePathField->setCurrentIndex( mDefaultEventImagePathField ); } void eVisGenericEventBrowserGui::on_pbtnResetUseOnlyFilenameData_clicked( ) { chkboxUseOnlyFilename->setChecked( false ); } void eVisGenericEventBrowserGui::on_rbtnManualCompassOffset_toggled( bool theState ) { mConfiguration.setManualCompassOffset( theState ); mConfiguration.setAttributeCompassOffset( !theState ); dsboxCompassOffset->setEnabled( theState ); cboxCompassOffsetField->setEnabled( !theState ); } /** * Slot called when an entry in the file associations table is clicked * @param theRow - the row that was clicked * @param theColumn - the column that was clicked */ void eVisGenericEventBrowserGui::on_tableFileTypeAssociations_cellDoubleClicked( int theRow, int theColumn ) { if ( 1 == theColumn ) { QString myApplication = QFileDialog::getOpenFileName( this, tr( "Select Application" ), "", tr( "All ( * )" ) ); if ( "" != myApplication ) { tableFileTypeAssociations->setItem( theRow, theColumn, new QTableWidgetItem( myApplication ) ); } } } /** * This slot is coonnected to the map canvas. When the canvas is done drawing the slot is fired to display thee highlighting symbol * @param thePainter - Pointer to the QPainter object */ void eVisGenericEventBrowserGui::renderSymbol( QPainter* thePainter ) { if ( mFeatureIds.size( ) > 0 && mVectorLayer != 0 ) { //Get a pointer to the current feature QgsFeature* myFeature = featureAtId( mFeatureIds.at( mCurrentFeatureIndex ) ); if ( 0 == myFeature ) return; QgsPoint myPoint = myFeature->geometry( )->asPoint( ); myPoint = mCanvas->mapRenderer( )->layerToMapCoordinates( mVectorLayer, myPoint ); mCanvas->getCoordinateTransform( )->transform( &myPoint ); if ( mConfiguration.isDisplayCompassBearingSet( ) ) { //Make a copy of the pointersymbol and rotate it based on the values in the attribute field QPixmap myTempPixmap( mPointerSymbol.height( ), mPointerSymbol.height( ) ); myTempPixmap.fill( QColor( 255, 255, 255, 0 ) ); QPainter p( &myTempPixmap ); QMatrix wm; wm.translate( myTempPixmap.width( ) / 2, myTempPixmap.height( ) / 2 ); // really center double myBearing = mCompassBearing; if ( mConfiguration.isManualCompassOffsetSet( ) ) { myBearing = mCompassBearing + mConfiguration.compassOffset( ); } else { myBearing = mCompassBearing + mCompassOffset; } if ( myBearing < 0.0 ) { while ( myBearing < 0.0 ) myBearing = 360.0 + myBearing; } else if ( myBearing >= 360.0 ) { while ( myBearing >= 360.0 ) myBearing = myBearing - 360.0; } wm.rotate( myBearing ); p.setWorldMatrix( wm ); p.drawPixmap( -mPointerSymbol.width( ) / 2, -mPointerSymbol.height( ) / 2, mPointerSymbol ); int xShift = ( int )myPoint.x( ) - ( myTempPixmap.width( ) / 2 ); int yShift = ( int )myPoint.y( ) - ( myTempPixmap.height( ) / 2 ); thePainter->drawPixmap( xShift, yShift, myTempPixmap ); } else { int xShift = ( int )myPoint.x( ) - ( mHighlightSymbol.width( ) / 2 ); int yShift = ( int )myPoint.y( ) - ( mHighlightSymbol.height( ) / 2 ); thePainter->drawPixmap( xShift, yShift, mHighlightSymbol ); } } }
polymeris/qgis
src/plugins/evis/eventbrowser/evisgenericeventbrowsergui.cpp
C++
gpl-2.0
37,902
import matplotlib.pyplot as plt import numpy as np from matplotlib.lines import lineStyles Light_cnames={'mistyrose':'#FFE4E1','navajowhite':'#FFDEAD','seashell':'#FFF5EE','papayawhip':'#FFEFD5','blanchedalmond':'#FFEBCD','white':'#FFFFFF','mintcream':'#F5FFFA','antiquewhite':'#FAEBD7','moccasin':'#FFE4B5','ivory':'#FFFFF0','lightgoldenrodyellow':'#FAFAD2','lightblue':'#ADD8E6','floralwhite':'#FFFAF0','ghostwhite':'#F8F8FF','honeydew':'#F0FFF0','linen':'#FAF0E6','snow':'#FFFAFA','lightcyan':'#E0FFFF','cornsilk':'#FFF8DC','bisque':'#FFE4C4','aliceblue':'#F0F8FF','gainsboro':'#DCDCDC','lemonchiffon':'#FFFACD','lightyellow':'#FFFFE0','lavenderblush':'#FFF0F5','whitesmoke':'#F5F5F5','beige':'#F5F5DC','azure':'#F0FFFF','oldlace':'#FDF5E6'} def plot10seperate(): mons=["201603","201604","201605","201606","201607","201608","201609","201610","201611","201612","201701","201702","201703","201704","201705","201706"] days=['01','02','03','04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31'] rootpath="F:/workspace/git/TranWeatherProject/data/mesonet_data/" for mon in mons: for day in days: print mon+day fileName=rootpath+mon+day+".txt" day_data=[] with open(fileName,"r") as df: for line in df.readlines(): terms=line.strip().split() sta_name=terms[0] data=map(float,terms[1:]) day_data.append((sta_name,mon+day,data)) X=[(i*5.0/60.0) for i in range(1,len(day_data[0][2]),1)] fig=plt.figure(1) fig.add_subplot(10,1,1) plt.plot(X,day_data[0][2],'b*-',linewidth='2.0', markersize=5,label='Temperature') plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,ncol=1, mode="expand", borderaxespad=0.) #plt.plot([0.2,0.1,0.0],[0.5,0.5,0.5]) plt.ylim([-20.0,60.0]) plt.xlabel('time Period') #plt.xlim([0.2,0.0]) plt.legend(loc='best',fontsize=8) plt.title(day_data[0][0]+" Station Date: "+mon+day +"Temperature") fig.add_subplot(10,1,2) plt.plot(X,day_data[1][2],'b*-',linewidth='2.0', markersize=5,label='Temperature') plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,ncol=1, mode="expand", borderaxespad=0.) #plt.plot([0.2,0.1,0.0],[0.5,0.5,0.5]) plt.ylim([-20.0,60.0]) plt.xlabel('time Period') #plt.xlim([0.2,0.0]) plt.legend(loc='best',fontsize=8) plt.title(day_data[1][0]+" Station Date: "+mon+day +"Temperature") fig.add_subplot(10,1,3) plt.plot(X,day_data[2][2],'b*-',linewidth='2.0', markersize=5,label='Temperature') plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,ncol=1, mode="expand", borderaxespad=0.) #plt.plot([0.2,0.1,0.0],[0.5,0.5,0.5]) plt.ylim([-20.0,60.0]) plt.xlabel('time Period') #plt.xlim([0.2,0.0]) plt.legend(loc='best',fontsize=8) plt.title(day_data[2][0]+" Station Date: "+mon+day +"Temperature") fig.add_subplot(10,1,4) plt.plot(X,day_data[3][2],'b*-',linewidth='2.0', markersize=5,label='Temperature') plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,ncol=1, mode="expand", borderaxespad=0.) #plt.plot([0.2,0.1,0.0],[0.5,0.5,0.5]) plt.ylim([-20.0,60.0]) plt.xlabel('time Period') #plt.xlim([0.2,0.0]) plt.legend(loc='best',fontsize=8) plt.title(day_data[3][0]+" Station Date: "+mon+day +"Temperature") fig.add_subplot(10,1,5) plt.plot(X,day_data[4][2],'b*-',linewidth='2.0', markersize=5,label='Temperature') plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,ncol=1, mode="expand", borderaxespad=0.) #plt.plot([0.2,0.1,0.0],[0.5,0.5,0.5]) plt.ylim([-20.0,60.0]) plt.xlabel('time Period') #plt.xlim([0.2,0.0]) plt.legend(loc='best',fontsize=8) plt.title(day_data[4][0]+" Station Date: "+mon+day +"Temperature") fig.add_subplot(10,1,6) plt.plot(X,day_data[5][2],'b*-',linewidth='2.0', markersize=5,label='Temperature') plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,ncol=1, mode="expand", borderaxespad=0.) #plt.plot([0.2,0.1,0.0],[0.5,0.5,0.5]) plt.ylim([-20.0,60.0]) plt.xlabel('time Period') #plt.xlim([0.2,0.0]) plt.legend(loc='best',fontsize=8) plt.title(day_data[5][0]+" Station Date: "+mon+day +"Temperature") fig.add_subplot(10,1,7) plt.plot(X,day_data[6][2],'b*-',linewidth='2.0', markersize=5,label='Temperature') plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,ncol=1, mode="expand", borderaxespad=0.) #plt.plot([0.2,0.1,0.0],[0.5,0.5,0.5]) plt.ylim([-20.0,60.0]) plt.xlabel('time Period') #plt.xlim([0.2,0.0]) plt.legend(loc='best',fontsize=8) plt.title(day_data[6][0]+" Station Date: "+mon+day +"Temperature") fig.add_subplot(10,1,8) plt.plot(X,day_data[7][2],'b*-',linewidth='2.0', markersize=5,label='Temperature') plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,ncol=1, mode="expand", borderaxespad=0.) #plt.plot([0.2,0.1,0.0],[0.5,0.5,0.5]) plt.ylim([-20.0,60.0]) plt.xlabel('time Period') #plt.xlim([0.2,0.0]) plt.legend(loc='best',fontsize=8) plt.title(day_data[7][0]+" Station Date: "+mon+day +"Temperature") fig.add_subplot(10,1,9) plt.plot(X,day_data[8][2],'b*-',linewidth='2.0', markersize=5,label='Temperature') plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,ncol=1, mode="expand", borderaxespad=0.) #plt.plot([0.2,0.1,0.0],[0.5,0.5,0.5]) plt.ylim([-20.0,60.0]) plt.xlabel('time Period From 00:00am ~23:59') #plt.xlim([0.2,0.0]) plt.legend(loc='best',fontsize=8) plt.title(day_data[8][0]+" Station Date: "+mon+day +"Temperature") fig.add_subplot(10,1,10) plt.plot(X,day_data[9][2],'b*-',linewidth='2.0', markersize=5,label='Temperature') plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,ncol=1, mode="expand", borderaxespad=0.) #plt.plot([0.2,0.1,0.0],[0.5,0.5,0.5]) plt.ylim([-20.0,60.0]) plt.xlabel('time Period') #plt.xlim([0.2,0.0]) plt.legend(loc='best',fontsize=8) plt.title(day_data[9][0]+" Station Date: "+mon+day +"Temperature") plt.tight_layout(pad=0.4, w_pad=0.5, h_pad=1.0) plt.show() fig.savefig('F:/workspace/git/TranWeatherProject/outputs/mesonetPlots/'+str(mon+day)+'.png') plt.close() import os def plotSignle(): mons=["201603","201604","201605","201606","201607","201608","201609"] #mons=["201604"] #mons=["201609"] days=['01','02','03','04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31'] #days=[""] sta_names={0:"BATA",1:"SBRI",2:"WATE",3:"JORD",4:"CSQR",5:"WEST",6:"COLD",7:"SPRA",8:"COBL",9:"STEP"} var_type="precip" rootpath="F:/workspace/git/Graph-MP/data/mesonet_data/"+var_type+"/" for mon in mons: for day in days: fileName=rootpath+mon+day+".txt" print fileName day_data=[] if not os.path.exists(fileName): continue with open(fileName,"r") as df: for line in df.readlines(): terms=line.strip().split() sta_name=terms[0] data=map(float,terms[1:]) day_data.append((sta_name,mon+day,data)) X=[i for i in range(0,len(day_data[0][2]))] label=[(str(i)+"\n"+str(i*5/60)+"h") for i in range(0,len(day_data[0][2])+1,12)] print sta_names[int(day_data[0][0])] fig=plt.figure(1) plt.plot(X,day_data[0][2],'b-',linewidth='1.0', markersize=5,label=sta_names[int(day_data[0][0])]+day_data[0][0]) plt.plot(X,day_data[1][2],'r-',linewidth='1.0', markersize=5,label=str(sta_names[int(day_data[1][0])])+day_data[1][0]) plt.plot(X,day_data[2][2],'k-',linewidth='1.0', markersize=5,label=str(sta_names[int(day_data[2][0])])+day_data[2][0]) plt.plot(X,day_data[3][2],'g-',linewidth='1.0', markersize=5,label=str(sta_names[int(day_data[3][0])])+day_data[3][0]) plt.plot(X,day_data[4][2],'y-',linewidth='1.0', markersize=5,label=str(sta_names[int(day_data[4][0])])+day_data[4][0]) plt.plot(X,day_data[5][2],'c-',linewidth='1.0', markersize=5,label=str(sta_names[int(day_data[5][0])])+day_data[5][0]) plt.plot(X,day_data[6][2],'m-',linewidth='1.0', markersize=5,label=str(sta_names[int(day_data[6][0])])+day_data[6][0]) plt.plot(X,day_data[7][2],color ='#B47CC7',linewidth='1.0', markersize=5,label=str(sta_names[int(day_data[7][0])])+day_data[7][0]) plt.plot(X,day_data[8][2],color='#FBC15E',linewidth='1.0', markersize=5,label=str(sta_names[int(day_data[8][0])])+day_data[8][0]) plt.plot(X,day_data[9][2],color='#e5ee38',linewidth='1.0', markersize=5,label=str(sta_names[int(day_data[9][0])])+day_data[9][0]) plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,ncol=1, mode="expand", borderaxespad=0.) plt.plot([0.2,0.1,0.0],[0.5,0.5,0.5]) if var_type=="wind": plt.ylim([-5.0,70.0]) plt.ylabel('Avg. Wind Speed(mph)') plt.title(mon+day +"Every 5min Avg. Wind") elif type=="temp": plt.ylim([-10.0,100.0]) plt.ylabel('Temperature(F)') plt.title(mon+day +"Temperature") else: plt.ylim([-1.0,2.0]) plt.ylabel('Precipitation Est (Inch)') plt.title(mon+day +"Precipitation") #plt.xticks(np.arange(min(X), max(X)+2, 12.0)) print len(X) plt.xticks(np.arange(min(X), max(X)+2, 12.0),label) plt.tick_params(axis='both', which='major', labelsize=7) plt.xlabel('Time from 00:00 ~23:59,each 5min') #plt.xlim([0.2,0.0]) plt.legend(loc='best',fontsize=8) plt.grid() #plt.tight_layout(pad=0.4, w_pad=0.5, h_pad=1.0) #plt.show() fig.savefig('F:/workspace/git/Graph-MP/outputs/mesonetPlots/'+var_type+'_plots/'+str(mon+day)+'.png') plt.close() def expAvg(fileName): expAvgs=[] expMin=[] expMax=[] with open(fileName,"r") as oF: for line in oF.readlines(): expAvgs.append(float(line.strip().split()[0])) expMin.append(float(line.strip().split()[1])) expMax.append(float(line.strip().split()[3])) return expAvgs,expMin,expMax def plotCaseDays(): dates=["20160301","20160302","20160308","20160309","20160312","20160313","20160324","20160325","20160328","20160405","20160412","20160419","20160421","20160514","20160529","20160621","20160628","20160813","20160911","20160922"] mons=["201603","201604","201605","201606","201607","201608","201609"] days=['01','02','03','04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31'] sta_names={0:"BATA",1:"SBRI",2:"WATE",3:"JORD",4:"CSQR",5:"WEST",6:"COLD",7:"SPRA",8:"COBL",9:"STEP"} var_type="temp" rootpath="F:/workspace/git/TranWeatherProject/data/mesonet_data/"+var_type+"/" #expRoot="F:/workspace/git/TranWeatherProject/data/mesonet_data/mesonetExpData/statExpData/" for mon in mons: for day in days: date=str(mon+day) # if date not in dates: # print "Not ",date # continue #expAvgs=expAvg(expRoot+mon+day+".txt") fileName=rootpath+mon+day+".txt" print fileName day_data=[] if not os.path.exists(fileName): print "File Not Found",fileName continue with open(fileName,"r") as df: for line in df.readlines(): terms=line.strip().split() sta_name=terms[0] data=map(float,terms[1:]) day_data.append((sta_name,mon+day,data)) X=[i for i in range(0,len(day_data[0][2]))] label=[(str(i)+"\n"+str(i*5/60)+"h") for i in range(0,len(day_data[0][2])+1,12)] labelY=[str(i) for i in range(0,100+1,5)] print sta_names[int(day_data[0][0])] fig=plt.figure(1) plt.plot(X,day_data[0][2],'b-',linewidth='2.0', markersize=5,label=sta_names[int(day_data[0][0])]+day_data[0][0]) plt.plot(X,day_data[1][2],'r-',linewidth='2.0', markersize=5,label=str(sta_names[int(day_data[1][0])])+day_data[1][0]) plt.plot(X,day_data[2][2],'k-',linewidth='2.0', markersize=5,label=str(sta_names[int(day_data[2][0])])+day_data[2][0]) plt.plot(X,day_data[3][2],'g-',linewidth='2.0', markersize=5,label=str(sta_names[int(day_data[3][0])])+day_data[3][0]) plt.plot(X,day_data[4][2],'y-',linewidth='2.0', markersize=5,label=str(sta_names[int(day_data[4][0])])+day_data[4][0]) plt.plot(X,day_data[5][2],'c-',linewidth='2.0', markersize=5,label=str(sta_names[int(day_data[5][0])])+day_data[5][0]) plt.plot(X,day_data[6][2],'m-',linewidth='2.0', markersize=5,label=str(sta_names[int(day_data[6][0])])+day_data[6][0]) plt.plot(X,day_data[7][2],color ='#B47CC7',linewidth='2.0', markersize=5,label=str(sta_names[int(day_data[7][0])])+day_data[7][0]) plt.plot(X,day_data[8][2],color='#FBC15E',linewidth='2.0', markersize=5,label=str(sta_names[int(day_data[8][0])])+day_data[8][0]) plt.plot(X,day_data[9][2],color='#e5ee38',linewidth='2.0', markersize=5,label=str(sta_names[int(day_data[9][0])])+day_data[9][0]) plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,ncol=1, mode="expand", borderaxespad=0.) plt.plot([0.2,0.1,0.0],[0.5,0.5,0.5]) if var_type=="wind": #plt.ylim([-5.0,70.0]) plt.ylabel('Avg. Wind Speed(mph)') plt.title(mon+day +"Every 5min Avg. Wind") else: plt.ylim([-10.0,100.0]) plt.ylabel('Temperature(F)') plt.title(mon+day +"Temperature") #plt.xticks(np.arange(min(X), max(X)+2, 12.0)) plt.xticks(np.arange(min(X), max(X)+2, 12.0),label) #plt.yticks(np.arange(0, 100, 5.0),labelY) plt.tick_params(axis='both', which='major', labelsize=7) plt.xlabel('Time from 00:00 ~23:59,every 5min') #plt.xlim([0.2,0.0]) plt.legend(loc='best',fontsize=8) plt.grid() #plt.tight_layout(pad=0.4, w_pad=0.5, h_pad=1.0) #plt.show() fig.savefig('F:/workspace/git/Graph-MP/outputs/mesonetPlots/'+var_type+'_CaseStudy/'+str(mon+day)+'.png', dpi=300) plt.close() def plotSingleDays(): fileName="F:/workspace/git/Graph-MP/data/mesonet_data/test_4.txt" sta_names={0:"BATA",1:"SBRI",2:"WATE",3:"JORD",4:"CSQR",5:"WEST",6:"COLD",7:"SPRA",8:"COBL",9:"STEP"} day_data=[] with open(fileName,"r") as df: for line in df.readlines(): terms=line.strip().split() sta_name=terms[0] data=map(float,terms[1:288]) day_data.append((sta_name,'201603001',data)) X=[i for i in range(0,len(day_data[0][2]))] label=[(str(i)+"\n"+str(i*5/60)+"h") for i in range(0,len(day_data[0][2])+1,12)] labelY=[str(i) for i in range(0,100+1,5)] print sta_names[int(day_data[0][0])] fig=plt.figure(1) plt.plot(X,day_data[0][2],'b-',linewidth='1.0', markersize=5,label=sta_names[int(day_data[0][0])]+day_data[0][0]) plt.plot(X,day_data[1][2],'r-',linewidth='1.0', markersize=5,label=str(sta_names[int(day_data[1][0])])+day_data[1][0]) plt.plot(X,day_data[2][2],'k-',linewidth='1.0', markersize=5,label=str(sta_names[int(day_data[2][0])])+day_data[2][0]) plt.plot(X,day_data[3][2],'g-',linewidth='1.0', markersize=5,label=str(sta_names[int(day_data[3][0])])+day_data[3][0]) plt.plot(X,day_data[4][2],'y-',linewidth='1.0', markersize=5,label=str(sta_names[int(day_data[4][0])])+day_data[4][0]) plt.plot(X,day_data[5][2],'c-',linewidth='1.0', markersize=5,label=str(sta_names[int(day_data[5][0])])+day_data[5][0]) plt.plot(X,day_data[6][2],'m-',linewidth='1.0', markersize=5,label=str(sta_names[int(day_data[6][0])])+day_data[6][0]) plt.plot(X,day_data[7][2],color ='#B47CC7',linewidth='1.0', markersize=5,label=str(sta_names[int(day_data[7][0])])+day_data[7][0]) plt.plot(X,day_data[8][2],color='#FBC15E',linewidth='1.0', markersize=5,label=str(sta_names[int(day_data[8][0])])+day_data[8][0]) plt.plot(X,day_data[9][2],color='#e5ee38',linewidth='1.0', markersize=5,label=str(sta_names[int(day_data[9][0])])+day_data[9][0]) plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,ncol=1, mode="expand", borderaxespad=0.) plt.plot([0.2,0.1,0.0],[0.5,0.5,0.5]) # if var_type=="wind": # #plt.ylim([-5.0,70.0]) # plt.ylabel('Avg. Wind Speed(mph)') # plt.title(mon+day +"Every 5min Avg. Wind") # else: # plt.ylim([-10.0,100.0]) # plt.ylabel('Temperature(F)') # plt.title(mon+day +"Temperature") plt.ylim([-10.0,100.0]) plt.ylabel('Temperature(F)') plt.title('201603001 ' +"Temperature") #plt.xticks(np.arange(min(X), max(X)+2, 12.0)) plt.xticks(np.arange(min(X), max(X)+2, 12.0),label) #plt.yticks(np.arange(0, 100, 5.0),labelY) plt.tick_params(axis='both', which='major', labelsize=7) plt.xlabel('Time from 00:00 ~23:59,each 5min') #plt.xlim([0.2,0.0]) plt.legend(loc='best',fontsize=8) plt.grid() #plt.tight_layout(pad=0.4, w_pad=0.5, h_pad=1.0) #plt.show() fig.savefig('F:/workspace/git/Graph-MP/data/mesonet_data/201603001_4.png', dpi=300) plt.close() import time def loadTop(fileName): results=[] with open(fileName,"r") as rF: for i,line in enumerate(rF.readlines()): terms=line.strip().split(" ") results.append((int(terms[0]),map(int,terms[1].split(",")),terms[2],map(int,terms[3].split(",")))) if i>19 : break return results def plotCaseDaysSingleStation(): #dates=["20160301","20160302","20160308","20160309","20160312","20160313","20160324","20160325","20160328","20160405","20160412","20160419","20160421","20160514","20160529","20160621","20160628","20160813","20160911","20160922"] vars=['i0','i1','i2','i3','i4','i5','i6','i7','i8','i9'] topResults=loadTop("F:/workspace/git/Graph-MP/outputs/mesonetPlots/multi_CaseStudy/CP/2/20multi_TopK_result-CP_baseMeanDiff_20_s_2_wMax_18_filter_TIncld_0.7_Top.txt") for result in topResults: dates=[] top=result[0]+1 vals=result[1] dates.append(result[2]) for i,var in enumerate(vars): if i in vals: exec "%s=%s"%(vars[i], 1) else: exec "%s=%s"%(vars[i], 0) print i0,i1,i2,i3,i4,i5,i6,i7,i8,i9 # i0=0 # i1=0 # i2=0 # i3=1 # i4=1 # i5=1 # i6=1 # i7=0 # i8=0 # i9=0 mons=["201603","201604","201605","201606","201607","201608","201609"] days=['01','02','03','04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31'] sta_names={0:"BATA",1:"SBRI",2:"WATE",3:"JORD",4:"CSQR",5:"WEST",6:"COLD",7:"SPRA",8:"COBL",9:"STEP"} var_type="wind" rootpath="F:/workspace/git/Graph-MP/data/mesonet_data/"+var_type+"/" rootpath2="F:/workspace/git/Graph-MP/data/mesonet_data/temp/" rootpath3="F:/workspace/git/Graph-MP/data/mesonet_data/precip/" #expRoot="F:/workspace/git/TranWeatherProject/data/mesonet_data/mesonetExpData/statExpData/" for mon in mons: for day in days: date=str(mon+day) if date not in dates: #print "Not ",date continue #expAvgs=expAvg(expRoot+mon+day+".txt") fileName=rootpath+mon+day+".txt" fileName2=rootpath2+mon+day+".txt" fileName3=rootpath3+mon+day+".txt" print fileName if not os.path.exists(fileName): print "File Not Found",fileName continue if not os.path.exists(fileName2): print "File Not Found",fileName2 continue if not os.path.exists(fileName3): print "File Not Found",fileName2 continue day_data=[] with open(fileName,"r") as df: for line in df.readlines(): terms=line.strip().split() sta_name=terms[0] data=map(float,terms[1:]) day_data.append((sta_name,mon+day,data)) day_data2=[] with open(fileName2,"r") as df2: for line in df2.readlines(): terms=line.strip().split() sta_name=terms[0] data=map(float,terms[1:]) day_data2.append((sta_name,mon+day,data)) day_data3=[] with open(fileName3,"r") as df3: for line in df3.readlines(): terms=line.strip().split() sta_name=terms[0] data=map(float,terms[1:]) day_data3.append((sta_name,mon+day,data)) X=[i for i in range(0,len(day_data[0][2]))] label=[(str(i)+"\n"+str(i*5/60)+"h") for i in range(0,len(day_data[0][2])+1,12)] labelY=[str(i) for i in range(0,100+1,5)] print sta_names[int(day_data[0][0])] print day_data[i3][2] fig=plt.figure(1) if i0!=0: plt.plot(X,day_data[0][2],'b-',linewidth='0.5', markersize=5,label='Wind '+sta_names[int(day_data[0][0])]+day_data[0][0]) if i1!=0: plt.plot(X,day_data[1][2],'r-',linewidth='0.5', markersize=5,label=str(sta_names[int(day_data[1][0])])+day_data[1][0]) if i2!=0: plt.plot(X,day_data[2][2],'k-',linewidth='0.5', markersize=5,label=str(sta_names[int(day_data[2][0])])+day_data[2][0]) if i3!=0: plt.plot(X,day_data[3][2],'g-',linewidth='0.5', markersize=5,label=str(sta_names[int(day_data[3][0])])+day_data[3][0]) if i4!=0: plt.plot(X,day_data[4][2],'y-',linewidth='0.5', markersize=5,label=str(sta_names[int(day_data[4][0])])+day_data[4][0]) if i5!=0: plt.plot(X,day_data[5][2],'c-',linewidth='0.5', markersize=5,label=str(sta_names[int(day_data[5][0])])+day_data[5][0]) if i6!=0: plt.plot(X,day_data[6][2],'m-',linewidth='0.5', markersize=5,label=str(sta_names[int(day_data[6][0])])+day_data[6][0]) if i7!=0: plt.plot(X,day_data[7][2],color ='#B47CC7',linewidth='0.5', markersize=5,label=str(sta_names[int(day_data[7][0])])+day_data[7][0]) if i8!=0: plt.plot(X,day_data[8][2],color='#FBC15E',linewidth='0.5', markersize=5,label=str(sta_names[int(day_data[8][0])])+day_data[8][0]) if i9!=0: plt.plot(X,day_data[9][2],color='#e5ee38',linewidth='0.5', markersize=5,label=str(sta_names[int(day_data[9][0])])+day_data[9][0]) plt.axvline(x=result[3][0], ymin=-1.0, ymax=50.0,color='k',linestyle='--') plt.axvline(x=result[3][1], ymin=-1.0, ymax=50.0,color='k',linestyle='--') plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,ncol=1, mode="expand", borderaxespad=0.) plt.plot([0.2,0.1,0.0],[0.5,0.5,0.5]) plt.ylim([-1.0,50.0]) plt.title("Top"+str(result[0]+1)+" "+mon+day +"Wind") #plt.xticks(np.arange(min(X), max(X)+2, 12.0)) plt.xticks(np.arange(min(X), max(X)+2, 12.0),label) plt.yticks(np.arange(-1, 50, 5.0),labelY) plt.tick_params(axis='both', which='major', labelsize=7) plt.xlabel('Time from 00:00 ~23:59,each 5min') plt.grid() #plt.xlim([0.2,0.0]) plt.legend(loc='best',fontsize=8) # fig.subplots_adjust(bottom = 2) # fig.subplots_adjust(top = 2) # fig.subplots_adjust(right = 2) # fig.subplots_adjust(left = 0) #plt.plot(X,day_data2[i][2],'r-',linewidth='1.0', markersize=5,label='Temp '+sta_names[int(day_data2[i][0])]+day_data2[i][0]) fig.savefig('F:/workspace/git/Graph-MP/outputs/mesonetPlots/multi_CaseStudy/mvPlots/'+str(top)+'_wind_'+str(mon+day)+'.png', dpi=300) fig.clf() fig=plt.figure(2) if i0!=0: plt.plot(X,day_data2[0][2],'b-',linewidth='0.5', markersize=5) if i1!=0: plt.plot(X,day_data2[1][2],'r-',linewidth='0.5', markersize=5) if i2!=0: plt.plot(X,day_data2[2][2],'k-',linewidth='0.5', markersize=5) if i3!=0: plt.plot(X,day_data2[3][2],'g-',linewidth='0.5', markersize=5) if i4!=0: plt.plot(X,day_data2[4][2],'y-',linewidth='0.5', markersize=5) if i5!=0: plt.plot(X,day_data2[5][2],'c-',linewidth='0.5', markersize=5) if i6!=0: plt.plot(X,day_data2[6][2],'m-',linewidth='0.5', markersize=5) if i7!=0: plt.plot(X,day_data2[7][2],color ='#B47CC7',linewidth='0.5', markersize=5) if i8!=0: plt.plot(X,day_data2[8][2],color='#FBC15E',linewidth='0.5', markersize=5) if i9!=0: plt.plot(X,day_data2[9][2],color='#e5ee38',linewidth='0.5', markersize=5) # if var_type=="wind": # plt.ylim([-1.0,50.0]) # plt.ylabel('Avg. Wind Speed(mph)') # plt.title(mon+day +"Every 5min Avg. Wind") # else: # plt.ylim([-10.0,100.0]) # plt.ylabel('Temperature(F)') # plt.title(mon+day +"Temperature") plt.axvline(x=result[3][0], ymin=-10.0, ymax=100.0,color='k',linestyle='--') plt.axvline(x=result[3][1], ymin=-10.0, ymax=100.0,color='k',linestyle='--') plt.ylim([-10.0,100.0]) plt.title("Top"+str(result[0]+1)+" "+mon+day +"Temperature ") #plt.xticks(np.arange(min(X), max(X)+2, 12.0)) plt.xticks(np.arange(min(X), max(X)+2, 12.0),label) plt.yticks(np.arange(0, 100, 5.0),labelY) plt.tick_params(axis='both', which='major', labelsize=7) plt.xlabel('Time from 00:00 ~23:59,each 5min') plt.grid() #plt.xlim([0.2,0.0]) plt.legend(loc='best',fontsize=8) # # fig.subplots_adjust(bottom = 0) # fig.subplots_adjust(top = 1) # fig.subplots_adjust(right = 1) # fig.subplots_adjust(left = 0) #plt.tight_layout(pad=0.4, w_pad=0.5, h_pad=1.0) #plt.show() fig.savefig('F:/workspace/git/Graph-MP/outputs/mesonetPlots/multi_CaseStudy/mvPlots/'+str(top)+'_temp_'+str(mon+day)+'.png', dpi=300) fig.clf() fig=plt.figure(3) if i0!=0: plt.plot(X,day_data3[0][2],'b-',linewidth='0.5', markersize=5) if i1!=0: plt.plot(X,day_data3[1][2],'r-',linewidth='0.5', markersize=5) if i2!=0: plt.plot(X,day_data3[2][2],'k-',linewidth='0.5', markersize=5) if i3!=0: plt.plot(X,day_data3[3][2],'g-',linewidth='0.5', markersize=5) if i4!=0: plt.plot(X,day_data3[4][2],'y-',linewidth='0.5', markersize=5) if i5!=0: plt.plot(X,day_data3[5][2],'c-',linewidth='0.5', markersize=5) if i6!=0: plt.plot(X,day_data3[6][2],'m-',linewidth='0.5', markersize=5) if i7!=0: plt.plot(X,day_data3[7][2],color ='#B47CC7',linewidth='0.5', markersize=5) if i8!=0: plt.plot(X,day_data3[8][2],color='#FBC15E',linewidth='0.5', markersize=5) if i9!=0: plt.plot(X,day_data3[9][2],color='#e5ee38',linewidth='0.5', markersize=5) # if var_type=="wind": # plt.ylim([-1.0,50.0]) # plt.ylabel('Avg. Wind Speed(mph)') # plt.title(mon+day +"Every 5min Avg. Wind") # else: # plt.ylim([-10.0,100.0]) # plt.ylabel('Temperature(F)') # plt.title(mon+day +"Temperature") plt.axvline(x=result[3][0], ymin=-0.2, ymax=2.0,color='k',linestyle='--') plt.axvline(x=result[3][1], ymin=-0.2, ymax=2.0,color='k',linestyle='--') plt.ylim([-0.2,2.0]) plt.title("Top"+str(result[0]+1)+" "+mon+day +"Precipitation ") #plt.xticks(np.arange(min(X), max(X)+2, 12.0)) plt.xticks(np.arange(min(X), max(X)+2, 12.0),label) #plt.yticks(np.arange(-0.2, 2.0, 0.5),labelY) plt.tick_params(axis='both', which='major', labelsize=7) plt.xlabel('Time from 00:00 ~23:59,each 5min') plt.grid() #plt.xlim([0.2,0.0]) plt.legend(loc='best',fontsize=8) # fig.subplots_adjust(bottom = 0) # fig.subplots_adjust(top = 1) # fig.subplots_adjust(right = 1) # fig.subplots_adjust(left = 0) #plt.tight_layout(pad=0.4, w_pad=0.5, h_pad=1.0) #plt.show() fig.savefig('F:/workspace/git/Graph-MP/outputs/mesonetPlots/multi_CaseStudy/mvPlots/'+str(top)+'_precip_'+str(mon+day)+'.png', dpi=300) fig.clf() plt.close() def plotAllDays(): root="F:/workspace/git/WeatherTransportationProject/" #dates=["20160301","20160302","20160308","20160309","20160312","20160313","20160324","20160325","20160328","20160405","20160412","20160419","20160421","20160514","20160529","20160621","20160628","20160813","20160911","20160922"] dates=[] #"201603","201604","201605","201606","201607","201608" mons=["201609","201610","201611","201612","201701","201702","201703","201704","201705","201706"] days=['01','02','03','04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31'] sta_names={0:"BATA",1:"SBRI",2:"WATE",3:"JORD",4:"CSQR",5:"WEST",6:"COLD",7:"SPRA",8:"COBL",9:"STEP"} var_types=["temp","temp9","press","wind","windDir","windMax","rh","rad"] #var_types=["wind"] for var_type in var_types: rootpath=root+"data/mesonet_data/"+var_type+"/" #expRoot="F:/workspace/git/Graph-MP/data/mesonet_data/mesonetExpData/statExpData/" for mon in mons: for day in days: date=str(mon+day) # if date in dates: # print "Not ",date # continue fileName=rootpath+mon+day+".txt" print fileName day_data=[] if not os.path.exists(fileName): print "File Not Found",fileName continue with open(fileName,"r") as df: for line in df.readlines(): terms=line.strip().split() sta_name=terms[0] data=map(float,terms[1:]) day_data.append((sta_name,mon+day,data)) X=[i for i in range(0,len(day_data[0][2]))] label=[(str(i)+"\n"+str(i*5/60)+"h") for i in range(0,len(day_data[0][2])+1,12)] labelY=[str(i) for i in range(0,100+1,5)] print sta_names[int(day_data[0][0])] fig=plt.figure(1) plt.plot(X,day_data[0][2],'b-',linewidth='1.5', markersize=5,label=sta_names[int(day_data[0][0])]+day_data[0][0]) plt.plot(X,day_data[1][2],'r-',linewidth='1.5', markersize=5,label=str(sta_names[int(day_data[1][0])])+day_data[1][0]) plt.plot(X,day_data[2][2],'k-',linewidth='1.5', markersize=5,label=str(sta_names[int(day_data[2][0])])+day_data[2][0]) plt.plot(X,day_data[3][2],'g-',linewidth='1.5', markersize=5,label=str(sta_names[int(day_data[3][0])])+day_data[3][0]) plt.plot(X,day_data[4][2],'y-',linewidth='1.5', markersize=5,label=str(sta_names[int(day_data[4][0])])+day_data[4][0]) plt.plot(X,day_data[5][2],'c-',linewidth='1.5', markersize=5,label=str(sta_names[int(day_data[5][0])])+day_data[5][0]) plt.plot(X,day_data[6][2],'m-',linewidth='1.5', markersize=5,label=str(sta_names[int(day_data[6][0])])+day_data[6][0]) plt.plot(X,day_data[7][2],color ='#B47CC7',linewidth='1.5', markersize=5,label=str(sta_names[int(day_data[7][0])])+day_data[7][0]) plt.plot(X,day_data[8][2],color='#FBC15E',linewidth='1.5', markersize=5,label=str(sta_names[int(day_data[8][0])])+day_data[8][0]) plt.plot(X,day_data[9][2],color='#e5ee38',linewidth='1.5', markersize=5,label=str(sta_names[int(day_data[9][0])])+day_data[9][0]) plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,ncol=1, mode="expand", borderaxespad=0.) plt.plot([0.2,0.1,0.0],[0.5,0.5,0.5]) if var_type=="wind": plt.ylim([-5.0,70.0]) plt.ylabel('Average Wind Speed(mph)') plt.title(mon+day +" Every 5min Average Wind Speed") elif var_type=="windMax": plt.ylim([-5.0,70.0]) plt.ylabel('Max Wind Speed(mph)') plt.title(mon+day +"Every 5min Max Wind") elif var_type=="windDir": #plt.ylim([-5.0,70.0]) plt.ylabel('Max Wind Speed(mph)') plt.title(mon+day +" Wind Direction Degree") elif var_type=="temp": plt.ylim([-10.0,100.0]) plt.ylabel('Temperature(F)') plt.title(mon+day +" 2m Temperature") elif var_type=="temp9": plt.ylim([-10.0,100.0]) plt.ylabel('Temperature(F)') plt.title(mon+day +" 9m Temperature") elif var_type=="press": #plt.ylim([-10.0,100.0]) plt.ylabel('Pressure(mbar)') plt.title(mon+day +" Pressure") elif var_type=="rad": #plt.ylim([-10.0,100.0]) plt.ylabel('Solar Radiation(W/m^2)') plt.title(mon+day +" Solar Radiation") elif var_type=="rh": plt.ylim([0.0,100.0]) plt.ylabel('Relative Humidity %') plt.title(mon+day +" rh") #plt.xticks(np.arange(min(X), max(X)+2, 12.0)) plt.xticks(np.arange(min(X), max(X)+2, 12.0),label) #plt.yticks(np.arange(0, 100, 5.0),labelY) plt.tick_params(axis='both', which='major', labelsize=7) plt.xlabel('Time from 00:00 ~23:59,every 5min') #plt.xlim([0.2,0.0]) plt.legend(loc='best',fontsize=10) plt.grid() #plt.tight_layout(pad=0.4, w_pad=0.5, h_pad=1.0) #plt.show() fig.savefig(root+'/outputs/mesonetPlots/'+var_type+'_plots/'+str(mon+day)+'.png') plt.close() def plotTravTimeAllDays(): import matplotlib #dates=["20160301","20160302","20160308","20160309","20160312","20160313","20160324","20160325","20160328","20160405","20160412","20160419","20160421","20160514","20160529","20160621","20160628","20160813","20160911","20160922"] dates=[] mons=["201603","201604","201605","201606","201607","201608","201609"] days=['01','02','03','04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31'] var_types=["TravelTimeToWest","TravelTimeToWest"] #var_types=["wind"] colors=[] for name, hex in matplotlib.colors.cnames.iteritems(): if name not in Light_cnames.keys(): colors.append(hex) for var_type in var_types: rootpath="F:/workspace/git/Graph-MP/data/trafficData/I90_TravelTime/"+var_type+"/" #expRoot="F:/workspace/git/Graph-MP/data/mesonet_data/mesonetExpData/statExpData/" for mon in mons: for day in days: date=str(mon+day) # if date in dates: # print "Not ",date # continue fileName=rootpath+mon+day+".txt" print fileName day_data=[] if not os.path.exists(fileName): print "File Not Found",fileName continue with open(fileName,"r") as df: for idx,line in enumerate(df.readlines()): terms=line.strip().split() sta_name="TMC "+str(idx) data=map(float,terms) day_data.append((sta_name,mon+day,data)) X=[i for i in range(0,len(day_data[0][2]))] label=[(str(i)+"\n"+str(i*5/60)+"h") for i in range(0,len(day_data[0][2])+1,12)] labelY=[str(i) for i in range(0,100+1,5)] print len(day_data) fig=plt.figure(1) for i in range(len(day_data)): plt.plot(X,day_data[i][2],colors[i],linewidth='0.5', markersize=5,label=day_data[i][0]) # art = [] # lgd = plt.legend(loc=3, bbox_to_anchor=(0, -0.5), ncol=5) # art.append(lgd) #plt.plot([0.2,0.1,0.0],[0.5,0.5,0.5]) plt.ylabel('Traveling Time (sec)') if var_type=="TravelTimeToWest": plt.title(mon+day +" Travel Time I90 East To West") else: plt.title(mon+day +" Travel Time I90 West To East") #plt.xticks(np.arange(min(X), max(X)+2, 12.0)) plt.xticks(np.arange(min(X), max(X)+2, 12.0),label) #plt.yticks(np.arange(0, 100, 5.0),labelY) plt.tick_params(axis='both', which='major', labelsize=7) plt.xlabel('Time: 00:00 ~ 23:59,every 5min') #plt.xlim([0.2,0.0]) plt.ylim([0.0,3600.0]) # plt.legend(loc='best',fontsize=10) plt.grid() #plt.tight_layout(pad=0.4, w_pad=0.5, h_pad=1.0) #plt.show() fig.savefig('F:/workspace/git/Graph-MP/outputs/trafficData/'+var_type+'_plots/'+str(mon+day)+'.png') plt.close() plotAllDays()
newera912/WeatherTransportationProject
target/classes/edu/albany/cs/transWeatherPy/plotMesonetOrgData.py
Python
gpl-2.0
43,328
#!/usr/bin/env python # -*- coding: UTF-8 -*- # If this page isn't working, try executing `chmod +x app.py` in terminal. # enable debugging import cgitb, cgi; cgitb.enable() from classes import Factory fieldStorage = cgi.FieldStorage() factory = Factory.Factory() webApp = factory.makeWebApp(fieldStorage) def outputHeaders(): print "Content-Type: text/html" print # signals end of headers outputHeaders() print webApp.getOutput()
OuachitaHillsMinistries/OHCFS
htbin/app.py
Python
gpl-2.0
447
<?php use mvc\routing\routingClass as routing ?> <?php use mvc\i18n\i18nClass as i18n ?> <?php use mvc\view\viewClass as view ?> <?php use mvc\config\configClass as config ?> <?php use mvc\request\requestClass as request ?> <?php use mvc\session\sessionClass as session ?> <?php $id = jugoTableClass::ID ?> <?php $procedencia = jugoTableClass::PROCEDENCIA ?> <?php $brix = jugoTableClass::BRIX ?> <?php $ph = jugoTableClass::PH ?> <?php $control_id = jugoTableClass::CONTROL_ID ?> <?php $proveedor_id = proveedorTableClass::ID ?> <?php $razon_social = proveedorTableClass::RAZON_SOCIAL ?> <?php view::includePartial('menu/menu') ?> <div class="container container-fluid"> <div class="page-header titulo"> <h1><i class="glyphicon glyphicon-filter"> <?php echo i18n::__('juiceProcess') ?></i></h1> </div> <form id="frmDeleteAll" action="<?php echo routing::getInstance()->getUrlWeb('jugo', 'deleteSelect') ?>" method="POST"> <div style="margin-bottom: 10px; margin-top: 30px"> <?php if (session::getInstance()->hasCredential('admin')): ?> <a href="<?php echo routing::getInstance()->getUrlWeb('jugo', 'insert') ?>" class="btn btn-success btn-xs"><?php echo i18n::__('new') ?></a> <a href="javascript:eliminarMasivo()" class="btn btn-danger btn-xs" id="btnDeleteMass" data-toggle="modal" data-target="#myModalDeleteMass"><?php echo i18n::__('deleteSelect') ?></a> <?php endif; ?> <button type="button" data-toggle="modal" data-target="#myModalFilters" class="btn btn-primary btn-xs"><?php echo i18n::__('filters') ?></button> <a href="<?php echo routing::getInstance()->getUrlWeb('jugo', 'deleteFilters') ?>" class="btn btn-default btn-xs"><?php echo i18n::__('deleteFilters') ?></a> <a class="btn btn-warning btn-xs col-lg-offset-7" data-toggle="modal" data-target="#myModalFILTROSREPORTE" ><?php echo i18n::__('printReport') ?></a> </div> <?php view::includeHandlerMessage() ?> <table class="tablaUsuario table table-bordered table-responsive table-hover tables"> <thead> <tr class="columna tr_table"> <th class="tamano"><input type="checkbox" id="chkAll"></th> <th><?php echo i18n::__('provenance') ?></th> <th class="tamanoAccion"><?php echo i18n::__('actions') ?></th> </tr> </thead> <tbody> <?php foreach ($objJugo as $jugo): ?> <tr> <td class="tamano"><input type="checkbox" name="chk[]" value="<?php echo $jugo->$id ?>"></td> <td><?php echo jugoTableClass::getNameProveedor($jugo->$procedencia) ?></td> <td> <a href="<?php echo routing::getInstance()->getUrlWeb('jugo', 'view', array(jugoTableClass::ID => $jugo->$id)) ?>" class="btn btn-info btn-xs"><?php echo i18n::__('view') ?></a> <?php if (session::getInstance()->hasCredential('admin')): ?> <a href="<?php echo routing::getInstance()->getUrlWeb('jugo', 'edit', array(jugoTableClass::ID => $jugo->$id)) ?>" class="btn btn-primary btn-xs"><?php echo i18n::__('edit') ?></a> <a href="#" data-toggle="modal" data-target="#myModalDelete<?php echo $jugo->$id ?>" class="btn btn-danger btn-xs"><?php echo i18n::__('delete') ?></a> <?php endif; ?> </td> </tr> <div class="modal fade" id="myModalDelete<?php echo $jugo->$id ?>" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title" id="myModalLabel"><?php echo i18n::__('confirmDelete') ?></h4> </div> <div class="modal-body"> <?php echo i18n::__('questionDelete') ?> <?php echo $jugo->$id ?>? </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal"><?php echo i18n::__('cancel') ?></button> <button type="button" class="btn btn-primary" onclick="eliminar(<?php echo $jugo->$id ?>, '<?php echo jugoTableClass::getNameField(jugoTableClass::ID, true) ?>', '<?php echo routing::getInstance()->getUrlWeb('jugo', 'delete') ?>')"><?php echo i18n::__('confirmDelete') ?></button> </div> </div> </div> </div> <?php endforeach ?> </tbody> </table> </form> <div class="text-right"> <?php echo i18n::__('page') ?> <select id="slqPaginador" onchange="paginador(this, '<?php echo routing::getInstance()->getUrlWeb('jugo', 'index') ?>')"> <?php for ($x = 1; $x <= $cntPages; $x++): ?> <option <?php echo(isset($page) and $page == $x) ? 'selected' : '' ?> value="<?php echo $x ?>"><?php echo $x ?></option> <?php endfor ?> </select> <?php echo i18n::__('of') ?> <?php echo $cntPages ?> </div> <form id="frmDelete" action="<?php echo routing::getInstance()->getUrlWeb('jugo', 'delete') ?>" method="POST"> <input type="hidden" id="idDelete" name="<?php echo jugoTableClass::getNameField(jugoTableClass::ID, true) ?>"> </form> </div> <div class="modal fade" id="myModalDeleteMass" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title" id="myModalLabel"><?php echo i18n::__('confirmDeleteMass') ?></h4> </div> <div class="modal-body"> <?php echo i18n::__('confirmDeleteMass') ?> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal"><?php echo i18n::__('cancel') ?></button> <button type="button" class="btn btn-primary" onclick="$('#frmDeleteAll').submit()"><?php echo i18n::__('confirmDelete') ?></button> </div> </div> </div> </div> <!-- ventana Modal Error al Eliminar Foraneas--> <div class="modal fade" id="myModalErrorDelete" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title" id="myModalLabel"><?php echo i18n::__('delete') ?></h4> </div> <div class="modal-body"></div> <div class="modal-footer"> <button type="button" class="btn btn-warning" data-dismiss="modal"><?php echo i18n::__('cancel') ?></button> </div> </div> </div> </div> <!-- Fin Ventana Modal Error al Eliminar Foraneas--> <!-- Uso de ventana modal para reportes con filtro--> <div class="modal fade" id="myModalFILTROSREPORTE" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title" id="myModalLabel"><?php echo i18n::__('generate report') ?></h4> </div> <div class="modal-body"> <form method="POST" class="form-horizontal" id="reportFilterForm" action="<?php echo routing::getInstance()->getUrlWeb('jugo', 'report') ?>"> <div class="form-group"> <label class="col-lg-2 control-label"><?php echo i18n::__('provenance') ?>:</label> <div class="col-lg-10"> <select class="form-control" id="reportProcedencia" name="report[procedencia]" id="<?php echo jugoTableClass::getNameField(jugoTableClass::ID, true) ?>" name="<?php echo jugoTableClass::getNameField(jugoTableClass::PROCEDENCIA, TRUE) ?>"> <?php foreach ($objProveedor as $proveedor): ?> <option <?php echo (isset($objJugo[0]->$procedencia) === true and $objJugo[0]->$procedencia == $proveedor->$proveedor_id ) ? 'selected' : '' ?> value="<?php echo $proveedor->$proveedor_id ?>"> <?php echo $proveedor->$razon_social ?> </option> <?php endforeach ?> </select> </div> </div> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal"><?php echo i18n::__('cancel') ?></button> <button type="button" onclick="$('#reportFilterForm').submit()" class="btn btn-primary"><?php echo i18n::__('generate') ?></button> </div> </div> </div> </div> <!--Ventana modal para uso de filtros--> <div class="modal fade" id="myModalFilters" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title" id="myModalLabel"><?php echo i18n::__('filters') ?></h4> </div> <div class="modal-body"> <form method="POST" role="form" class="form-horizontal" id="filterForm" action="<?php echo routing::getInstance()->getUrlWeb('jugo', 'index') ?>"> <div class="form-group"> <label class="col-lg-2 control-label" for="filterProcedencia"><?php echo i18n::__('provenance') ?>:</label> <div class="col-lg-10"> <select class="form-control" id="filterProcedencia" name="filter[procedencia]" id="<?php echo jugoTableClass::getNameField(jugoTableClass::ID, true) ?>" name="<?php echo jugoTableClass::getNameField(jugoTableClass::PROCEDENCIA, TRUE) ?>"> <?php foreach ($objProveedor as $proveedor): ?> <option <?php echo (isset($objJugo[0]->$procedencia) === true and $objJugo[0]->$procedencia == $proveedor->$proveedor_id ) ? 'selected' : '' ?> value="<?php echo $proveedor->$proveedor_id ?>"> <?php echo $proveedor->$razon_social ?> </option> <?php endforeach ?> </select> </div> </div> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal"><?php echo i18n::__('cancel') ?></button> <button type="button" onclick="$('#filterForm').submit()" class="btn btn-primary"><?php echo i18n::__('filtrate') ?></button> </div> </div> </div> </div>
Carlosbarrera585c/proyectoSantaHelena
view/jugo/indexTemplate.html.php
PHP
gpl-2.0
11,228
/** * This package provides custom string manipulation capabilities * @see com.dreamer.string.Expressions */ package com.dreamer.string;
gerryDreamer/dreamerLib
src/com/dreamer/string/package-info.java
Java
gpl-2.0
143
/* Copyright (c) 2004-2005 The Dojo Foundation, Licensed under the Academic Free License version 2.1 or above */dojo.provide("dojo.reflect"); /***************************************************************** reflect.js v.1.5.0 (c) 2003-2004 Thomas R. Trenka, Ph.D. Derived from the reflection functions of f(m). http://dojotoolkit.org http://fm.dept-z.com There is a dependency on the variable dJ_global, which should always refer to the global object. ******************************************************************/ if(!dj_global){ var dj_global = this; } dojo.reflect = {} ; dojo.reflect.$unknownType = function(){ } ; dojo.reflect.ParameterInfo = function(name, type){ this.name = name ; this.type = (type) ? type : dojo.reflect.$unknownType ; } ; dojo.reflect.PropertyInfo = function(name, type) { this.name = name ; this.type = (type) ? type : dojo.reflect.$unknownType ; } ; dojo.reflect.MethodInfo = function(name, fn){ var parse = function(f) { var o = {} ; var s = f.toString() ; var param = ((s.substring(s.indexOf('(')+1, s.indexOf(')'))).replace(/\s+/g, "")).split(",") ; o.parameters = [] ; for (var i = 0; i < param.length; i++) { o.parameters.push(new dojo.reflect.ParameterInfo(param[i])) ; } o.body = (s.substring(s.indexOf('{')+1, s.lastIndexOf('}'))).replace(/(^\s*)|(\s*$)/g, "") ; return o ; } ; var tmp = parse(fn) ; var p = tmp.parameters ; var body = tmp.body ; this.name = (name) ? name : "anonymous" ; this.getParameters = function(){ return p ; } ; this.getNullArgumentsObject = function() { var a = [] ; for (var i = 0; i < p.length; i++){ a.push(null); } return a ; } ; this.getBody = function() { return body ; } ; this.type = Function ; this.invoke = function(src, args){ return fn.apply(src, args) ; } ; } ; // Static object that can activate instances of the passed type. dojo.reflect.Activator = new (function(){ this.createInstance = function(type, args) { switch (typeof(type)) { case "function" : { var o = {} ; type.apply(o, args) ; return o ; } ; case "string" : { var o = {} ; (dojo.reflect.Reflector.getTypeFromString(type)).apply(o, args) ; return o ; } ; } throw new Error("dojo.reflect.Activator.createInstance(): no such type exists."); } })() ; dojo.reflect.Reflector = new (function(){ this.getTypeFromString = function(s) { var parts = s.split("."), i = 0, obj = dj_global ; do { obj = obj[parts[i++]] ; } while (i < parts.length && obj) ; return (obj != dj_global) ? obj : null ; }; this.typeExists = function(s) { var parts = s.split("."), i = 0, obj = dj_global ; do { obj = obj[parts[i++]] ; } while (i < parts.length && obj) ; return (obj && obj != dj_global) ; }; this.getFieldsFromType = function(s) { var type = s ; if (typeof(s) == "string") { type = this.getTypeFromString(s) ; } var nullArgs = (new dojo.reflect.MethodInfo(type)).getNullArgumentsObject() ; return this.getFields(dojo.reflect.Activator.createInstance(s, nullArgs)) ; }; this.getPropertiesFromType = function(s) { var type = s ; if (typeof(s) == "string") { type = this.getTypeFromString(s); } var nullArgs = (new dojo.reflect.MethodInfo(type)).getNullArgumentsObject() ; return this.getProperties(dojo.reflect.Activator.createInstance(s, nullArgs)) ; }; this.getMethodsFromType = function(s) { var type = s ; if (typeof(s) == "string") { type = this.getTypeFromString(s) ; } var nullArgs = (new dojo.reflect.MethodInfo(type)).getNullArgumentsObject() ; return this.getMethods(dojo.reflect.Activator.createInstance(s, nullArgs)) ; }; this.getType = function(o) { return o.constructor ; } ; this.getFields = function(obj) { var arr = [] ; for (var p in obj) { if(this.getType(obj[p]) != Function){ arr.push(new dojo.reflect.PropertyInfo(p, this.getType(obj[p]))) ; }else{ arr.push(new dojo.reflect.MethodInfo(p, obj[p])); } } return arr ; }; this.getProperties = function(obj) { var arr = [] ; var fi = this.getFields(obj) ; for (var i = 0; i < fi.length; i++){ if (this.isInstanceOf(fi[i], dojo.reflect.PropertyInfo)){ arr.push(fi[i]) ; } } return arr ; }; this.getMethods = function(obj) { var arr = [] ; var fi = this.getFields(obj) ; for (var i = 0; i < fi.length; i++){ if (this.isInstanceOf(fi[i], dojo.reflect.MethodInfo)){ arr.push(fi[i]) ; } } return arr ; }; /* this.implements = function(o, type) { if (this.isSubTypeOf(o, type)) return false ; var f = this.getFieldsFromType(type) ; for (var i = 0; i < f.length; i++) { if (typeof(o[(f[i].name)]) == "undefined"){ return false; } } return true ; }; */ this.getBaseClass = function(o) { if (o.getType().prototype.prototype.constructor){ return (o.getType()).prototype.prototype.constructor ; } return Object ; } ; this.isInstanceOf = function(o, type) { return (this.getType(o) == type) ; }; this.isSubTypeOf = function(o, type) { return (o instanceof type) ; }; this.isBaseTypeOf = function(o, type) { return (type instanceof o); }; })(); // back-compat dojo.provide("dojo.reflect.reflection");
BradNeuberg/hyperscope
prototype_1_basic_outline_viewspecs/trunk/src/client/lib/dojo/src/reflect/reflection.js
JavaScript
gpl-2.0
5,393
/****************************************************************************** * Wormux is a convivial mass murder game. * Copyright (C) 2001-2007 Wormux Team. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA ****************************************************************************** * Refresh des fichiers. *****************************************************************************/ #include "tool/file_tools.h" #include <fstream> #include <sys/stat.h> #ifdef WIN32 // To get SHGetSpecialFolderPath # define _WIN32_IE 0x400 # include <shlobj.h> #else # include <stdlib.h> // getenv #endif #include "i18n.h" // Test if a file exists bool IsFileExist(const std::string &name) { std::ifstream f(name.c_str()); bool exist = f.good(); f.close(); return exist; } // Check if the folder exists bool IsFolderExist(const std::string &name) { // Is it a directory ? struct stat stat_file; if (stat(name.c_str(), &stat_file) != 0) return false; return (stat_file.st_mode & S_IFMT) == S_IFDIR; } // Find the extension part of a filename std::string FileExtension (const std::string &name) { int pos = name.rfind('.'); if (pos != -1) return name.substr(pos+1); else return ""; } #ifdef WIN32 // Return the path to the home directory of the user std::string GetHome (){ TCHAR szPath[MAX_PATH]; // "Documents and Settings\user" is CSIDL_PROFILE if(SHGetSpecialFolderPath(NULL, szPath, CSIDL_APPDATA, FALSE) == TRUE) return szPath; return ""; } #include <windows.h> struct _FolderSearch { WIN32_FIND_DATA file; HANDLE file_search; }; FolderSearch *OpenFolder(const std::string& dirname) { std::string pattern = dirname + "*.*"; FolderSearch *f = new FolderSearch; f->file_search = FindFirstFile(pattern.c_str(), &f->file); if (f->file_search == INVALID_HANDLE_VALUE) { FindClose(f->file_search); delete f; return NULL; } return f; } const char* FolderSearchNext(FolderSearch *f) { while (FindNextFile(f->file_search, &f->file)) { if (f->file.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) return f->file.cFileName; } return NULL; } void CloseFolder(FolderSearch *f) { if (f) { FindClose(f->file_search); delete f; } } #else // Return the path to the home directory of the user std::string GetHome() { char *txt = getenv("HOME"); if (txt == NULL) Error (_("HOME directory (environment variable $HOME) could not be found!")); return txt; } #include <dirent.h> struct _FolderSearch { DIR *dir; struct dirent *file; }; FolderSearch* OpenFolder(const std::string& dirname) { FolderSearch *f = new FolderSearch; f->dir = opendir(dirname.c_str()); if (!f->dir) { delete f; return NULL; } return f; } const char* FolderSearchNext(FolderSearch *f) { f->file = readdir(f->dir); return (f->file) ? f->file->d_name : NULL; } void CloseFolder(FolderSearch *f) { if (f) { closedir(f->dir); delete f; } } #endif // Replace ~ by its true name std::string TranslateDirectory(const std::string &directory) { std::string home = GetHome(); std::string txt = directory; for (int pos = txt.length()-1; (pos = txt.rfind ('~', pos)) != -1; --pos) { txt.replace(pos,1,home); } return txt; }
yeKcim/warmux
old/wormux-0.8beta2/src/tool/file_tools.cpp
C++
gpl-2.0
4,011
<?php /** * The Backbone class of Framework. * * This class provides core functionality to all types of classes used * throughout PremiumPress Framework. * */ class PPT_API { /** * Wraps content into an HTML element. * * @since 0.3.0 * * @param string $tag The HTML tag to wrap the content in. * @param string $content The content to display. * @param string $attrs Optional. HTML attributes to add to the element. * @param bool $echo Whether to echo the content or return it. */ function wrap( $tag, $content = '', $attrs = array(), $echo = true ) { $attrs = $this->parse_attrs( $attrs ); $tag = esc_attr( $tag ); $the_content = ''; if ( is_array($content) ) { foreach ( $content as $line ) { $the_content .= $line; } } else { $the_content = $content; } $output = "<{$tag}{$attrs}>{$the_content}</{$tag}>"; if ( !$echo ) return $output; echo $output; } /** * Parses a key => value array into a valid format as HTML attributes. * * @since 0.3.0 * * @param array $args Key value pairs of attributes. * @return string Valid HTML attribute format. */ function parse_attrs( $args = array() ) { if ( empty($args) ) return ''; $attrs = ''; foreach ( (array) $args as $key => $value ) { if ( $value ) { $attrs .= ' '. sanitize_key($key) .'="'. esc_attr($value) .'"'; } } return $attrs; } /** * Checks to see if a method exists within the specified object. * * @since 0.3.0 * * @param object $object Object to check. * @param string $method Method to check to see if it exists. * @return bool True if the method exists, else false. */ function is_method( $object, $method ) { if ( method_exists( $object, $method ) ) return true; return false; } /** * Calls a method from an object if it exists. * * @since 0.3.0 * * @param object $object Objcet to check. * @param string $method Method to check to see if it exists. * @param string $args Optional. Parameteres to pass to the method. * @return void */ function callback( $object, $method, $args = array() ) { if ( $this->is_method( $object, $method ) ) { return call_user_func_array( array( $object, $method ), $args ); } } /** * Returns a formated method, replacing dashes with underscores. * * @since 0.3.0 * * @param string $prefix String to prepend to the $context * @param string $context String to sanitize. * @return string Formatted contextual method. */ function contextual_method( $prefix, $context ) { return "{$prefix}_" . str_replace( '-', '_', sanitize_title_with_dashes($context) ); } /** * Trys to call a contextual method if it exists. * If it doesn't, call the default method. * * @since 0.3.0 * * @param string $method Base method name. * @param mixed $args Optional. Parameters to pass to the method. * @return void */ function contextual_callback( $method, $args = array() ) { $callback = $this->contextual_method( $method, $this->slug ); if ( $this->is_method( $this, $callback ) ) { return $this->callback( $this, $callback, $args ); } elseif ( $this->is_method( $this, $method ) ) { return $this->callback( $this, $method, $args ); } } } ?>
magictortoise/voucheroffer
wp-content/themes/couponpress/PPT/framework/ppt_api.php
PHP
gpl-2.0
3,236
/* import_text_dialog.cpp * * $Id$ * * Wireshark - Network traffic analyzer * By Gerald Combs <gerald@wireshark.org> * Copyright 1998 Gerald Combs * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "config.h" #include <time.h> #include <import_text_dialog.h> #include "wiretap/wtap.h" #include "wiretap/pcap-encap.h" #include <epan/prefs.h> #include "ui/text_import_scanner.h" #include "ui/last_open_dir.h" #include "ui/alert_box.h" #include "ui/help_url.h" #include "file.h" #include "wsutil/file_util.h" #include "tempfile.h" #include <ui_import_text_dialog.h> #include <wireshark_application.h> #include <QFileDialog> #include <QDebug> #include <QFile> ImportTextDialog::ImportTextDialog(QWidget *parent) : QDialog(parent), ti_ui_(new Ui::ImportTextDialog), import_info_() { int encap; int i; ti_ui_->setupUi(this); memset(&import_info_, 0, sizeof(import_info_)); ok_button_ = ti_ui_->buttonBox->button(QDialogButtonBox::Ok); ok_button_->setEnabled(false); #ifdef Q_WS_MAC // The grid layout squishes each line edit otherwise. int le_height = ti_ui_->textFileLineEdit->sizeHint().height(); ti_ui_->ethertypeLineEdit->setMinimumHeight(le_height); ti_ui_->protocolLineEdit->setMinimumHeight(le_height); ti_ui_->sourcePortLineEdit->setMinimumHeight(le_height); ti_ui_->destinationPortLineEdit->setMinimumHeight(le_height); ti_ui_->tagLineEdit->setMinimumHeight(le_height); ti_ui_->ppiLineEdit->setMinimumHeight(le_height); #endif on_dateTimeLineEdit_textChanged(ti_ui_->dateTimeLineEdit->text()); for (i = 0; i < ti_ui_->headerGridLayout->count(); i++) { QRadioButton *rb = qobject_cast<QRadioButton *>(ti_ui_->headerGridLayout->itemAt(i)->widget()); if (rb) encap_buttons_.append(rb); } /* Scan all Wiretap encapsulation types */ import_info_.encapsulation = WTAP_ENCAP_ETHERNET; for (encap = import_info_.encapsulation; encap < wtap_get_num_encap_types(); encap++) { /* Check if we can write to a PCAP file * * Exclude wtap encapsulations that require a pseudo header, * because we won't setup one from the text we import and * wiretap doesn't allow us to write 'raw' frames */ if ((wtap_wtap_encap_to_pcap_encap(encap) > 0) && !wtap_encap_requires_phdr(encap)) { const char *name; /* If it has got a name */ if ((name = wtap_encap_string(encap))) { ti_ui_->encapComboBox->addItem(name, QVariant(encap)); } } } } ImportTextDialog::~ImportTextDialog() { delete ti_ui_; } QString &ImportTextDialog::capfileName() { return capfile_name_; } void ImportTextDialog::convertTextFile() { int import_file_fd; char *tmpname; int err; capfile_name_.clear(); /* Choose a random name for the temporary import buffer */ import_file_fd = create_tempfile(&tmpname, "import"); capfile_name_.append(tmpname); import_info_.wdh = wtap_dump_fdopen(import_file_fd, WTAP_FILE_PCAP, import_info_.encapsulation, import_info_.max_frame_length, FALSE, &err); qDebug() << capfile_name_ << ":" << import_info_.wdh << import_info_.encapsulation << import_info_.max_frame_length; if (import_info_.wdh == NULL) { open_failure_alert_box(capfile_name_.toUtf8().constData(), err, TRUE); fclose(import_info_.import_text_file); setResult(QDialog::Rejected); return; } text_import_setup(&import_info_); text_importin = import_info_.import_text_file; text_importlex(); text_import_cleanup(); if (fclose(import_info_.import_text_file)) { read_failure_alert_box(import_info_.import_text_filename, errno); } if (!wtap_dump_close(import_info_.wdh, &err)) { write_failure_alert_box(capfile_name_.toUtf8().constData(), err); } } void ImportTextDialog::enableHeaderWidgets(bool enable_buttons) { bool ethertype = false; bool ipv4_proto = false; bool port = false; bool sctp_tag = false; bool sctp_ppi = false; if (enable_buttons) { if (ti_ui_->ethernetButton->isChecked()) { ethertype = true; on_ethertypeLineEdit_textChanged(ti_ui_->ethertypeLineEdit->text()); } else if (ti_ui_->ipv4Button->isChecked()) { ipv4_proto = true; on_protocolLineEdit_textChanged(ti_ui_->protocolLineEdit->text()); } else if (ti_ui_->udpButton->isChecked() || ti_ui_->tcpButton->isChecked()) { port = true; on_sourcePortLineEdit_textChanged(ti_ui_->sourcePortLineEdit->text()); on_destinationPortLineEdit_textChanged(ti_ui_->destinationPortLineEdit->text()); } else if (ti_ui_->sctpButton->isChecked()) { port = true; sctp_tag = true; on_sourcePortLineEdit_textChanged(ti_ui_->sourcePortLineEdit->text()); on_destinationPortLineEdit_textChanged(ti_ui_->destinationPortLineEdit->text()); on_tagLineEdit_textChanged(ti_ui_->tagLineEdit->text()); } if (ti_ui_->sctpDataButton->isChecked()) { port = true; sctp_ppi = true; on_sourcePortLineEdit_textChanged(ti_ui_->sourcePortLineEdit->text()); on_destinationPortLineEdit_textChanged(ti_ui_->destinationPortLineEdit->text()); on_ppiLineEdit_textChanged(ti_ui_->ppiLineEdit->text()); } } foreach (QRadioButton *rb, encap_buttons_) { rb->setEnabled(enable_buttons); } ti_ui_->ethertypeLabel->setEnabled(ethertype); ti_ui_->ethertypeLineEdit->setEnabled(ethertype); ti_ui_->protocolLabel->setEnabled(ipv4_proto); ti_ui_->protocolLineEdit->setEnabled(ipv4_proto); ti_ui_->sourcePortLabel->setEnabled(port); ti_ui_->sourcePortLineEdit->setEnabled(port); ti_ui_->destinationPortLabel->setEnabled(port); ti_ui_->destinationPortLineEdit->setEnabled(port); ti_ui_->tagLabel->setEnabled(sctp_tag); ti_ui_->tagLineEdit->setEnabled(sctp_tag); ti_ui_->ppiLabel->setEnabled(sctp_ppi); ti_ui_->ppiLineEdit->setEnabled(sctp_ppi); } int ImportTextDialog::exec() { QVariant encap_val; QDialog::exec(); if (result() != QDialog::Accepted) { return result(); } import_info_.import_text_filename = strdup(ti_ui_->textFileLineEdit->text().toUtf8().data()); import_info_.import_text_file = ws_fopen(import_info_.import_text_filename, "rb"); if (!import_info_.import_text_file) { open_failure_alert_box(import_info_.import_text_filename, errno, FALSE); setResult(QDialog::Rejected); return QDialog::Rejected; } import_info_.offset_type = ti_ui_->hexOffsetButton->isChecked() ? OFFSET_HEX : ti_ui_->decimalOffsetButton->isChecked() ? OFFSET_DEC : ti_ui_->octalOffsetButton->isChecked() ? OFFSET_OCT : OFFSET_NONE; import_info_.date_timestamp = ti_ui_->dateTimeLineEdit->text().length() > 0; import_info_.date_timestamp_format = strdup(ti_ui_->dateTimeLineEdit->text().toUtf8().data()); encap_val = ti_ui_->encapComboBox->itemData(ti_ui_->encapComboBox->currentIndex()); import_info_.dummy_header_type = HEADER_NONE; if (encap_val.isValid() && encap_val.toUInt() == WTAP_ENCAP_ETHERNET && !ti_ui_->noDummyButton->isChecked()) { // Inputs were validated in the on_xxx_textChanged slots. if (ti_ui_->ethernetButton->isChecked()) { import_info_.dummy_header_type = HEADER_ETH; } else if (ti_ui_->ipv4Button->isChecked()) { import_info_.dummy_header_type = HEADER_IPV4; } else if(ti_ui_->udpButton->isChecked()) { import_info_.dummy_header_type = HEADER_UDP; } else if(ti_ui_->tcpButton->isChecked()) { import_info_.dummy_header_type = HEADER_TCP; } else if(ti_ui_->sctpButton->isChecked()) { import_info_.dummy_header_type = HEADER_SCTP; } else if(ti_ui_->sctpDataButton->isChecked()) { import_info_.dummy_header_type = HEADER_SCTP_DATA; } } if (import_info_.max_frame_length == 0) { import_info_.max_frame_length = IMPORT_MAX_PACKET; } convertTextFile(); return QDialog::Accepted; } void ImportTextDialog::on_textFileBrowseButton_clicked() { char *open_dir = NULL; switch (prefs.gui_fileopen_style) { case FO_STYLE_LAST_OPENED: /* The user has specified that we should start out in the last directory we looked in. If we've already opened a file, use its containing directory, if we could determine it, as the directory, otherwise use the "last opened" directory saved in the preferences file if there was one. */ /* This is now the default behaviour in file_selection_new() */ open_dir = get_last_open_dir(); break; case FO_STYLE_SPECIFIED: /* The user has specified that we should always start out in a specified directory; if they've specified that directory, start out by showing the files in that dir. */ if (prefs.gui_fileopen_dir[0] != '\0') open_dir = prefs.gui_fileopen_dir; break; } QString file_name = QFileDialog::getOpenFileName(this, tr("Wireshark: Import text file"), open_dir); ti_ui_->textFileLineEdit->setText(file_name); } void ImportTextDialog::on_textFileLineEdit_textChanged(const QString &file_name) { QFile *text_file; text_file = new QFile(file_name); if (text_file->open(QIODevice::ReadOnly)) { ok_button_->setEnabled(true); text_file->close(); } else { ok_button_->setEnabled(false); } } void ImportTextDialog::on_encapComboBox_currentIndexChanged(int index) { QVariant val = ti_ui_->encapComboBox->itemData(index); bool enabled = false; if (val != QVariant::Invalid) { import_info_.encapsulation = val.toUInt(); if (import_info_.encapsulation == WTAP_ENCAP_ETHERNET) enabled = true; } enableHeaderWidgets(enabled); } void ImportTextDialog::on_dateTimeLineEdit_textChanged(const QString &time_format) { if (time_format.length() > 0) { time_t cur_time; struct tm *cur_tm; char time_str[100]; time(&cur_time); cur_tm = localtime(&cur_time); strftime(time_str, 100, ti_ui_->dateTimeLineEdit->text().toUtf8().constData(), cur_tm); ti_ui_->timestampExampleLabel->setText(QString(tr("Example: %1")).arg(time_str)); } else { ti_ui_->timestampExampleLabel->setText(tr("<i>(No format will be applied)</i>")); } } void ImportTextDialog::on_directionIndicationCheckBox_toggled(bool checked) { import_info_.has_direction = checked; } void ImportTextDialog::on_noDummyButton_toggled(bool checked) { if (checked) enableHeaderWidgets(); } void ImportTextDialog::on_ethernetButton_toggled(bool checked) { on_noDummyButton_toggled(checked); } void ImportTextDialog::on_ipv4Button_toggled(bool checked) { on_noDummyButton_toggled(checked); } void ImportTextDialog::on_udpButton_toggled(bool checked) { on_noDummyButton_toggled(checked); } void ImportTextDialog::on_tcpButton_toggled(bool checked) { on_noDummyButton_toggled(checked); } void ImportTextDialog::on_sctpButton_toggled(bool checked) { on_noDummyButton_toggled(checked); } void ImportTextDialog::on_sctpDataButton_toggled(bool checked) { on_noDummyButton_toggled(checked); } void ImportTextDialog::check_line_edit(SyntaxLineEdit *le, const QString &num_str, int base, guint max_val, bool is_short, guint *val_ptr) { bool conv_ok; SyntaxLineEdit::SyntaxState syntax_state = SyntaxLineEdit::Empty; bool ok_enabled = true; if (!le || !val_ptr) return; if (num_str.length() < 1) { *val_ptr = 0; } else { if (is_short) { *val_ptr = num_str.toUShort(&conv_ok, base); } else { *val_ptr = num_str.toULong(&conv_ok, base); } if (conv_ok && *val_ptr <= max_val) { syntax_state = SyntaxLineEdit::Valid; } else { syntax_state = SyntaxLineEdit::Invalid; ok_enabled = false; } } le->setSyntaxState(syntax_state); ok_button_->setEnabled(ok_enabled); } void ImportTextDialog::on_ethertypeLineEdit_textChanged(const QString &ethertype_str) { check_line_edit(ti_ui_->ethertypeLineEdit, ethertype_str, 16, 0xffff, true, &import_info_.pid); } void ImportTextDialog::on_protocolLineEdit_textChanged(const QString &protocol_str) { check_line_edit(ti_ui_->protocolLineEdit, protocol_str, 10, 0xff, true, &import_info_.protocol); } void ImportTextDialog::on_sourcePortLineEdit_textChanged(const QString &source_port_str) { check_line_edit(ti_ui_->sourcePortLineEdit, source_port_str, 10, 0xffff, true, &import_info_.src_port); } void ImportTextDialog::on_destinationPortLineEdit_textChanged(const QString &destination_port_str) { check_line_edit(ti_ui_->destinationPortLineEdit, destination_port_str, 10, 0xffff, true, &import_info_.dst_port); } void ImportTextDialog::on_tagLineEdit_textChanged(const QString &tag_str) { check_line_edit(ti_ui_->tagLineEdit, tag_str, 10, 0xffffffff, false, &import_info_.tag); } void ImportTextDialog::on_ppiLineEdit_textChanged(const QString &ppi_str) { check_line_edit(ti_ui_->ppiLineEdit, ppi_str, 10, 0xffffffff, false, &import_info_.ppi); } void ImportTextDialog::on_maxLengthLineEdit_textChanged(const QString &max_frame_len_str) { check_line_edit(ti_ui_->maxLengthLineEdit, max_frame_len_str, 10, IMPORT_MAX_PACKET, true, &import_info_.max_frame_length); } void ImportTextDialog::on_buttonBox_helpRequested() { wsApp->helpTopicAction(HELP_IMPORT_DIALOG); } /* * Editor modelines * * Local Variables: * c-basic-offset: 4 * tab-width: 8 * indent-tabs-mode: nil * End: * * ex: set shiftwidth=4 tabstop=8 expandtab: * :indentSize=4:tabSize=8:noTabs=true: */
masonh/wireshark
ui/qt/import_text_dialog.cpp
C++
gpl-2.0
14,751
<?php // $Id$ // perceptivity.eu websitecrew.com /** * @file maintenance-page.tpl.php * * Theme implementation to display a single Drupal page while off-line. * * Groundwork maintenance page does not include sidebars by default, nor * does it print messages, tabs or anything else that typically you would * not see on a maintenance page. If you require any of these additional variables * you will need to add them. Also the columns layout has been totally removed. * * themename_preprocess is disabled when the database is not active (see * template.php). This is because it calls many functions that rely on the database * being active and will cause errors when the maintenance page is viewed. * * @see template_preprocess() * @see template_preprocess_maintenance_page() */ ?> <!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" xml:lang="<?php print $language->language ?>" lang="<?php print $language->language ?>" dir="<?php print $language->dir ?>"> <head> <title><?php print $head_title; ?></title> <?php print $head; ?> <?php print $styles; ?> <?php print $scripts; ?> </head> <body class="<?php print $body_classes; ?>"> <div id="container"> <div id="header" class="clearfix"> <?php if ($logo or $site_name or $site_slogan): ?> <div id="branding"> <?php if ($logo or $site_name): ?> <div class="logo-site-name"><strong> <?php if (!empty($logo)): ?> <span id="logo"> <a href="<?php print $base_path; ?>" title="<?php print t('Home page'); ?>" rel="home"> <img src="<?php print $logo; ?>" alt="<?php print t('Home page'); ?>" /> </a> </span> <?php endif; ?> <?php if (!empty($site_name)): ?> <span id="site-name"> <a href="<?php print $base_path ?>" title="<?php print t('Home page'); ?>" rel="home"> <?php print $site_name; ?> </a> </span> <?php endif; ?> </strong></div> <!-- /logo and site name --> <?php if ($site_slogan): ?> <div id="site-slogan"><?php print $site_slogan; ?></div> <?php endif; ?> <!-- /slogan --> <?php endif; ?> </div> <!-- /branding --> <?php endif; ?> </div> <!-- /header --> <div id="main-content"> <?php if ($title): ?><h1 id="page-title"><?php print $title; ?></h1><?php endif; ?> <div id="content"><?php print $content; ?></div> </div> <!-- /main-content --> </div> <!-- /container --> <?php print $closure ?> </body> </html>
drupalnorge/oslo2012.drupalcamp.no
sites/all/themes/groundwork/templates/maintenance-page.tpl.php
PHP
gpl-2.0
2,750
/*************************************************************************** qgsstylemanagerdialog.cpp --------------------- begin : November 2009 copyright : (C) 2009 by Martin Dobias email : wonder dot sk at gmail dot com *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "qgsstylemanagerdialog.h" #include "qgsstylesavedialog.h" #include "qgsstyle.h" #include "qgssymbol.h" #include "qgssymbollayerutils.h" #include "qgscolorramp.h" #include "qgssymbolselectordialog.h" #include "qgsgradientcolorrampdialog.h" #include "qgslimitedrandomcolorrampdialog.h" #include "qgscolorbrewercolorrampdialog.h" #include "qgspresetcolorrampdialog.h" #include "qgscptcitycolorrampdialog.h" #include "qgsstyleexportimportdialog.h" #include "qgssmartgroupeditordialog.h" #include "qgssettings.h" #include <QAction> #include <QFile> #include <QFileDialog> #include <QInputDialog> #include <QMessageBox> #include <QPushButton> #include <QStandardItemModel> #include <QMenu> #include "qgsapplication.h" #include "qgslogger.h" QgsStyleManagerDialog::QgsStyleManagerDialog( QgsStyle *style, QWidget *parent ) : QDialog( parent ) , mStyle( style ) , mModified( false ) { setupUi( this ); connect( tabItemType, &QTabWidget::currentChanged, this, &QgsStyleManagerDialog::tabItemType_currentChanged ); connect( buttonBox, &QDialogButtonBox::helpRequested, this, &QgsStyleManagerDialog::showHelp ); connect( buttonBox, &QDialogButtonBox::rejected, this, &QgsStyleManagerDialog::onClose ); #ifdef Q_OS_MAC setWindowModality( Qt::WindowModal ); #endif QgsSettings settings; restoreGeometry( settings.value( QStringLiteral( "Windows/StyleV2Manager/geometry" ) ).toByteArray() ); mSplitter->setSizes( QList<int>() << 170 << 540 ); mSplitter->restoreState( settings.value( QStringLiteral( "Windows/StyleV2Manager/splitter" ) ).toByteArray() ); tabItemType->setDocumentMode( true ); searchBox->setPlaceholderText( trUtf8( "Filter symbols…" ) ); connect( this, &QDialog::finished, this, &QgsStyleManagerDialog::onFinished ); connect( listItems, &QAbstractItemView::doubleClicked, this, &QgsStyleManagerDialog::editItem ); connect( btnAddItem, &QPushButton::clicked, this, [ = ]( bool ) { addItem(); } ); connect( btnEditItem, &QPushButton::clicked, this, [ = ]( bool ) { editItem(); } ); connect( actnEditItem, &QAction::triggered, this, [ = ]( bool ) { editItem(); } ); connect( btnRemoveItem, &QPushButton::clicked, this, [ = ]( bool ) { removeItem(); } ); connect( actnRemoveItem, &QAction::triggered, this, [ = ]( bool ) { removeItem(); } ); QMenu *shareMenu = new QMenu( tr( "Share menu" ), this ); QAction *exportAction = new QAction( tr( "Export symbol(s)…" ), this ); exportAction->setIcon( QIcon( QgsApplication::iconPath( "mActionFileSave.svg" ) ) ); shareMenu->addAction( exportAction ); QAction *importAction = new QAction( tr( "Import symbol(s)…" ), this ); importAction->setIcon( QIcon( QgsApplication::iconPath( "mActionFileOpen.svg" ) ) ); shareMenu->addAction( importAction ); shareMenu->addSeparator(); shareMenu->addAction( actnExportAsPNG ); shareMenu->addAction( actnExportAsSVG ); connect( actnExportAsPNG, &QAction::triggered, this, &QgsStyleManagerDialog::exportItemsPNG ); connect( actnExportAsSVG, &QAction::triggered, this, &QgsStyleManagerDialog::exportItemsSVG ); connect( exportAction, &QAction::triggered, this, &QgsStyleManagerDialog::exportItems ); connect( importAction, &QAction::triggered, this, &QgsStyleManagerDialog::importItems ); btnShare->setMenu( shareMenu ); // Set editing mode off by default mGrouppingMode = false; QStandardItemModel *model = new QStandardItemModel( listItems ); listItems->setModel( model ); listItems->setSelectionMode( QAbstractItemView::ExtendedSelection ); connect( model, &QStandardItemModel::itemChanged, this, &QgsStyleManagerDialog::itemChanged ); connect( listItems->selectionModel(), &QItemSelectionModel::currentChanged, this, &QgsStyleManagerDialog::symbolSelected ); connect( listItems->selectionModel(), &QItemSelectionModel::selectionChanged, this, &QgsStyleManagerDialog::selectedSymbolsChanged ); populateTypes(); QStandardItemModel *groupModel = new QStandardItemModel( groupTree ); groupTree->setModel( groupModel ); groupTree->setHeaderHidden( true ); populateGroups(); groupTree->setCurrentIndex( groupTree->model()->index( 0, 0 ) ); connect( groupTree->selectionModel(), &QItemSelectionModel::currentChanged, this, &QgsStyleManagerDialog::groupChanged ); connect( groupModel, &QStandardItemModel::itemChanged, this, &QgsStyleManagerDialog::groupRenamed ); QMenu *groupMenu = new QMenu( tr( "Group actions" ), this ); connect( actnTagSymbols, &QAction::triggered, this, &QgsStyleManagerDialog::tagSymbolsAction ); groupMenu->addAction( actnTagSymbols ); connect( actnFinishTagging, &QAction::triggered, this, &QgsStyleManagerDialog::tagSymbolsAction ); actnFinishTagging->setVisible( false ); groupMenu->addAction( actnFinishTagging ); groupMenu->addAction( actnEditSmartGroup ); btnManageGroups->setMenu( groupMenu ); connect( searchBox, &QLineEdit::textChanged, this, &QgsStyleManagerDialog::filterSymbols ); // Context menu for groupTree groupTree->setContextMenuPolicy( Qt::CustomContextMenu ); connect( groupTree, &QWidget::customContextMenuRequested, this, &QgsStyleManagerDialog::grouptreeContextMenu ); // Context menu for listItems listItems->setContextMenuPolicy( Qt::CustomContextMenu ); connect( listItems, &QWidget::customContextMenuRequested, this, &QgsStyleManagerDialog::listitemsContextMenu ); // Menu for the "Add item" toolbutton when in colorramp mode QStringList rampTypes; rampTypes << tr( "Gradient" ) << tr( "Color presets" ) << tr( "Random" ) << tr( "Catalog: cpt-city" ); rampTypes << tr( "Catalog: ColorBrewer" ); mMenuBtnAddItemColorRamp = new QMenu( this ); Q_FOREACH ( const QString &rampType, rampTypes ) mMenuBtnAddItemColorRamp->addAction( new QAction( rampType, this ) ); connect( mMenuBtnAddItemColorRamp, &QMenu::triggered, this, static_cast<bool ( QgsStyleManagerDialog::* )( QAction * )>( &QgsStyleManagerDialog::addColorRamp ) ); // Context menu for symbols/colorramps. The menu entries for every group are created when displaying the menu. mGroupMenu = new QMenu( this ); connect( actnAddFavorite, &QAction::triggered, this, &QgsStyleManagerDialog::addFavoriteSelectedSymbols ); mGroupMenu->addAction( actnAddFavorite ); connect( actnRemoveFavorite, &QAction::triggered, this, &QgsStyleManagerDialog::removeFavoriteSelectedSymbols ); mGroupMenu->addAction( actnRemoveFavorite ); mGroupMenu->addSeparator()->setParent( this ); mGroupListMenu = new QMenu( mGroupMenu ); mGroupListMenu->setTitle( tr( "Add to tag" ) ); mGroupListMenu->setEnabled( false ); mGroupMenu->addMenu( mGroupListMenu ); actnDetag->setData( 0 ); connect( actnDetag, &QAction::triggered, this, &QgsStyleManagerDialog::detagSelectedSymbols ); mGroupMenu->addAction( actnDetag ); mGroupMenu->addSeparator()->setParent( this ); mGroupMenu->addAction( actnRemoveItem ); mGroupMenu->addAction( actnEditItem ); mGroupMenu->addSeparator()->setParent( this ); mGroupMenu->addAction( actnExportAsPNG ); mGroupMenu->addAction( actnExportAsSVG ); // Context menu for the group tree mGroupTreeContextMenu = new QMenu( this ); connect( actnEditSmartGroup, &QAction::triggered, this, &QgsStyleManagerDialog::editSmartgroupAction ); mGroupTreeContextMenu->addAction( actnEditSmartGroup ); connect( actnAddTag, &QAction::triggered, this, [ = ]( bool ) { addTag(); } ); mGroupTreeContextMenu->addAction( actnAddTag ); connect( actnAddSmartgroup, &QAction::triggered, this, [ = ]( bool ) { addSmartgroup(); } ); mGroupTreeContextMenu->addAction( actnAddSmartgroup ); connect( actnRemoveGroup, &QAction::triggered, this, &QgsStyleManagerDialog::removeGroup ); mGroupTreeContextMenu->addAction( actnRemoveGroup ); tabItemType_currentChanged( 0 ); } void QgsStyleManagerDialog::onFinished() { if ( mModified ) { mStyle->save(); } QgsSettings settings; settings.setValue( QStringLiteral( "Windows/StyleV2Manager/geometry" ), saveGeometry() ); settings.setValue( QStringLiteral( "Windows/StyleV2Manager/splitter" ), mSplitter->saveState() ); } void QgsStyleManagerDialog::populateTypes() { #if 0 // save current selection index in types combo int current = ( tabItemType->count() > 0 ? tabItemType->currentIndex() : 0 ); // no counting of style items int markerCount = 0, lineCount = 0, fillCount = 0; QStringList symbolNames = mStyle->symbolNames(); for ( int i = 0; i < symbolNames.count(); ++i ) { switch ( mStyle->symbolRef( symbolNames[i] )->type() ) { case QgsSymbol::Marker: markerCount++; break; case QgsSymbol::Line: lineCount++; break; case QgsSymbol::Fill: fillCount++; break; default: Q_ASSERT( 0 && "unknown symbol type" ); break; } } cboItemType->clear(); cboItemType->addItem( tr( "Marker symbol (%1)" ).arg( markerCount ), QVariant( QgsSymbol::Marker ) ); cboItemType->addItem( tr( "Line symbol (%1)" ).arg( lineCount ), QVariant( QgsSymbol::Line ) ); cboItemType->addItem( tr( "Fill symbol (%1)" ).arg( fillCount ), QVariant( QgsSymbol::Fill ) ); cboItemType->addItem( tr( "Color ramp (%1)" ).arg( mStyle->colorRampCount() ), QVariant( 3 ) ); // update current index to previous selection cboItemType->setCurrentIndex( current ); #endif } void QgsStyleManagerDialog::tabItemType_currentChanged( int ) { // when in Color Ramp tab, add menu to add item button and hide "Export symbols as PNG/SVG" bool flag = currentItemType() != 3; searchBox->setPlaceholderText( flag ? trUtf8( "Filter symbols…" ) : trUtf8( "Filter color ramps…" ) ); btnAddItem->setMenu( flag ? nullptr : mMenuBtnAddItemColorRamp ); actnExportAsPNG->setVisible( flag ); actnExportAsSVG->setVisible( flag ); listItems->setIconSize( QSize( 100, 90 ) ); listItems->setGridSize( QSize( 120, 110 ) ); populateList(); } void QgsStyleManagerDialog::populateList() { if ( currentItemType() > 3 ) { Q_ASSERT( false && "not implemented" ); return; } groupChanged( groupTree->selectionModel()->currentIndex() ); } void QgsStyleManagerDialog::populateSymbols( const QStringList &symbolNames, bool check ) { QStandardItemModel *model = qobject_cast<QStandardItemModel *>( listItems->model() ); model->clear(); int type = currentItemType(); for ( int i = 0; i < symbolNames.count(); ++i ) { QString name = symbolNames[i]; QgsSymbol *symbol = mStyle->symbol( name ); if ( symbol && symbol->type() == type ) { QStringList tags = mStyle->tagsOfSymbol( QgsStyle::SymbolEntity, name ); QStandardItem *item = new QStandardItem( name ); QIcon icon = QgsSymbolLayerUtils::symbolPreviewIcon( symbol, listItems->iconSize(), 18 ); item->setIcon( icon ); item->setData( name ); // used to find out original name when user edited the name item->setCheckable( check ); item->setToolTip( QStringLiteral( "<b>%1</b><br><i>%2</i>" ).arg( name, tags.count() > 0 ? tags.join( QStringLiteral( ", " ) ) : tr( "Not tagged" ) ) ); // add to model model->appendRow( item ); } delete symbol; } selectedSymbolsChanged( QItemSelection(), QItemSelection() ); symbolSelected( listItems->currentIndex() ); } void QgsStyleManagerDialog::populateColorRamps( const QStringList &colorRamps, bool check ) { QStandardItemModel *model = qobject_cast<QStandardItemModel *>( listItems->model() ); model->clear(); for ( int i = 0; i < colorRamps.count(); ++i ) { QString name = colorRamps[i]; std::unique_ptr< QgsColorRamp > ramp( mStyle->colorRamp( name ) ); QStandardItem *item = new QStandardItem( name ); QIcon icon = QgsSymbolLayerUtils::colorRampPreviewIcon( ramp.get(), listItems->iconSize(), 18 ); item->setIcon( icon ); item->setData( name ); // used to find out original name when user edited the name item->setCheckable( check ); item->setToolTip( name ); model->appendRow( item ); } selectedSymbolsChanged( QItemSelection(), QItemSelection() ); symbolSelected( listItems->currentIndex() ); } int QgsStyleManagerDialog::currentItemType() { switch ( tabItemType->currentIndex() ) { case 0: return QgsSymbol::Marker; case 1: return QgsSymbol::Line; case 2: return QgsSymbol::Fill; case 3: return 3; default: return 0; } } QString QgsStyleManagerDialog::currentItemName() { QModelIndex index = listItems->selectionModel()->currentIndex(); if ( !index.isValid() ) return QString(); return index.model()->data( index, 0 ).toString(); } void QgsStyleManagerDialog::addItem() { bool changed = false; if ( currentItemType() < 3 ) { changed = addSymbol(); } else if ( currentItemType() == 3 ) { changed = addColorRamp(); } else { Q_ASSERT( false && "not implemented" ); } if ( changed ) { populateList(); populateTypes(); } } bool QgsStyleManagerDialog::addSymbol() { // create new symbol with current type QgsSymbol *symbol = nullptr; QString name = tr( "new symbol" ); switch ( currentItemType() ) { case QgsSymbol::Marker: symbol = new QgsMarkerSymbol(); name = tr( "new marker" ); break; case QgsSymbol::Line: symbol = new QgsLineSymbol(); name = tr( "new line" ); break; case QgsSymbol::Fill: symbol = new QgsFillSymbol(); name = tr( "new fill symbol" ); break; default: Q_ASSERT( false && "unknown symbol type" ); return false; } // get symbol design // NOTE : Set the parent widget as "this" to notify the Symbol selector // that, it is being called by Style Manager, so recursive calling // of style manager and symbol selector can be arrested // See also: editSymbol() QgsSymbolSelectorDialog dlg( symbol, mStyle, nullptr, this ); if ( dlg.exec() == 0 ) { delete symbol; return false; } QgsStyleSaveDialog saveDlg( this ); if ( !saveDlg.exec() ) { delete symbol; return false; } name = saveDlg.name(); // request valid/unique name bool nameInvalid = true; while ( nameInvalid ) { // validate name if ( name.isEmpty() ) { QMessageBox::warning( this, tr( "Save symbol" ), tr( "Cannot save symbol without name. Enter a name." ) ); } else if ( mStyle->symbolNames().contains( name ) ) { int res = QMessageBox::warning( this, tr( "Save symbol" ), tr( "Symbol with name '%1' already exists. Overwrite?" ) .arg( name ), QMessageBox::Yes | QMessageBox::No ); if ( res == QMessageBox::Yes ) { mStyle->removeSymbol( name ); nameInvalid = false; } } else { // valid name nameInvalid = false; } if ( nameInvalid ) { bool ok; name = QInputDialog::getText( this, tr( "Symbol Name" ), tr( "Please enter a name for new symbol:" ), QLineEdit::Normal, name, &ok ); if ( !ok ) { delete symbol; return false; } } } QStringList symbolTags = saveDlg.tags().split( ',' ); // add new symbol to style and re-populate the list mStyle->addSymbol( name, symbol ); mStyle->saveSymbol( name, symbol, saveDlg.isFavorite(), symbolTags ); mModified = true; return true; } QString QgsStyleManagerDialog::addColorRampStatic( QWidget *parent, QgsStyle *style, QString rampType ) { // let the user choose the color ramp type if rampType is not given bool ok = true; if ( rampType.isEmpty() ) { QStringList rampTypes; rampTypes << tr( "Gradient" ) << tr( "Color presets" ) << tr( "Random" ) << tr( "Catalog: cpt-city" ); rampTypes << tr( "Catalog: ColorBrewer" ); rampType = QInputDialog::getItem( parent, tr( "Color ramp type" ), tr( "Please select color ramp type:" ), rampTypes, 0, false, &ok ); } if ( !ok || rampType.isEmpty() ) return QString(); QString name = tr( "new ramp" ); std::unique_ptr< QgsColorRamp > ramp; if ( rampType == tr( "Gradient" ) ) { QgsGradientColorRampDialog dlg( QgsGradientColorRamp(), parent ); if ( !dlg.exec() ) { return QString(); } ramp.reset( dlg.ramp().clone() ); name = tr( "new gradient ramp" ); } else if ( rampType == tr( "Random" ) ) { QgsLimitedRandomColorRampDialog dlg( QgsLimitedRandomColorRamp(), parent ); if ( !dlg.exec() ) { return QString(); } ramp.reset( dlg.ramp().clone() ); name = tr( "new random ramp" ); } else if ( rampType == tr( "Catalog: ColorBrewer" ) ) { QgsColorBrewerColorRampDialog dlg( QgsColorBrewerColorRamp(), parent ); if ( !dlg.exec() ) { return QString(); } ramp.reset( dlg.ramp().clone() ); name = dlg.ramp().schemeName() + QString::number( dlg.ramp().colors() ); } else if ( rampType == tr( "Color presets" ) ) { QgsPresetColorRampDialog dlg( QgsPresetSchemeColorRamp(), parent ); if ( !dlg.exec() ) { return QString(); } ramp.reset( dlg.ramp().clone() ); name = tr( "new preset ramp" ); } else if ( rampType == tr( "Catalog: cpt-city" ) ) { QgsCptCityColorRampDialog dlg( QgsCptCityColorRamp( QLatin1String( "" ), QLatin1String( "" ) ), parent ); if ( !dlg.exec() ) { return QString(); } // name = dlg.selectedName(); name = QFileInfo( dlg.ramp().schemeName() ).baseName() + dlg.ramp().variantName(); if ( dlg.saveAsGradientRamp() ) { ramp.reset( dlg.ramp().cloneGradientRamp() ); } else { ramp.reset( dlg.ramp().clone() ); } } else { // Q_ASSERT( 0 && "invalid ramp type" ); // bailing out is rather harsh! QgsDebugMsg( "invalid ramp type " + rampType ); return QString(); } QgsStyleSaveDialog saveDlg( parent, QgsStyle::ColorrampEntity ); if ( !saveDlg.exec() ) { return QString(); } name = saveDlg.name(); // get valid/unique name bool nameInvalid = true; while ( nameInvalid ) { // validate name if ( name.isEmpty() ) { QMessageBox::warning( parent, tr( "Save Color Ramp" ), tr( "Cannot save color ramp without name. Enter a name." ) ); } else if ( style->colorRampNames().contains( name ) ) { int res = QMessageBox::warning( parent, tr( "Save color ramp" ), tr( "Color ramp with name '%1' already exists. Overwrite?" ) .arg( name ), QMessageBox::Yes | QMessageBox::No ); if ( res == QMessageBox::Yes ) { nameInvalid = false; } } else { // valid name nameInvalid = false; } if ( nameInvalid ) { bool ok; name = QInputDialog::getText( parent, tr( "Color Ramp Name" ), tr( "Please enter a name for new color ramp:" ), QLineEdit::Normal, name, &ok ); if ( !ok ) { return QString(); } } } QStringList colorRampTags = saveDlg.tags().split( ',' ); QgsColorRamp *r = ramp.release(); // add new symbol to style and re-populate the list style->addColorRamp( name, r ); style->saveColorRamp( name, r, saveDlg.isFavorite(), colorRampTags ); return name; } bool QgsStyleManagerDialog::addColorRamp() { return addColorRamp( nullptr ); } bool QgsStyleManagerDialog::addColorRamp( QAction *action ) { // pass the action text, which is the color ramp type QString rampName = addColorRampStatic( this, mStyle, action ? action->text() : QString() ); if ( !rampName.isEmpty() ) { mModified = true; populateList(); return true; } return false; } void QgsStyleManagerDialog::editItem() { bool changed = false; if ( currentItemType() < 3 ) { changed = editSymbol(); } else if ( currentItemType() == 3 ) { changed = editColorRamp(); } else { Q_ASSERT( false && "not implemented" ); } if ( changed ) populateList(); } bool QgsStyleManagerDialog::editSymbol() { QString symbolName = currentItemName(); if ( symbolName.isEmpty() ) return false; QgsSymbol *symbol = mStyle->symbol( symbolName ); // let the user edit the symbol and update list when done QgsSymbolSelectorDialog dlg( symbol, mStyle, nullptr, this ); if ( dlg.exec() == 0 ) { delete symbol; return false; } // by adding symbol to style with the same name the old effectively gets overwritten mStyle->addSymbol( symbolName, symbol, true ); mModified = true; return true; } bool QgsStyleManagerDialog::editColorRamp() { QString name = currentItemName(); if ( name.isEmpty() ) return false; std::unique_ptr< QgsColorRamp > ramp( mStyle->colorRamp( name ) ); if ( ramp->type() == QLatin1String( "gradient" ) ) { QgsGradientColorRamp *gradRamp = static_cast<QgsGradientColorRamp *>( ramp.get() ); QgsGradientColorRampDialog dlg( *gradRamp, this ); if ( !dlg.exec() ) { return false; } ramp.reset( dlg.ramp().clone() ); } else if ( ramp->type() == QLatin1String( "random" ) ) { QgsLimitedRandomColorRamp *randRamp = static_cast<QgsLimitedRandomColorRamp *>( ramp.get() ); QgsLimitedRandomColorRampDialog dlg( *randRamp, this ); if ( !dlg.exec() ) { return false; } ramp.reset( dlg.ramp().clone() ); } else if ( ramp->type() == QLatin1String( "colorbrewer" ) ) { QgsColorBrewerColorRamp *brewerRamp = static_cast<QgsColorBrewerColorRamp *>( ramp.get() ); QgsColorBrewerColorRampDialog dlg( *brewerRamp, this ); if ( !dlg.exec() ) { return false; } ramp.reset( dlg.ramp().clone() ); } else if ( ramp->type() == QLatin1String( "preset" ) ) { QgsPresetSchemeColorRamp *presetRamp = static_cast<QgsPresetSchemeColorRamp *>( ramp.get() ); QgsPresetColorRampDialog dlg( *presetRamp, this ); if ( !dlg.exec() ) { return false; } ramp.reset( dlg.ramp().clone() ); } else if ( ramp->type() == QLatin1String( "cpt-city" ) ) { QgsCptCityColorRamp *cptCityRamp = static_cast<QgsCptCityColorRamp *>( ramp.get() ); QgsCptCityColorRampDialog dlg( *cptCityRamp, this ); if ( !dlg.exec() ) { return false; } if ( dlg.saveAsGradientRamp() ) { ramp.reset( dlg.ramp().cloneGradientRamp() ); } else { ramp.reset( dlg.ramp().clone() ); } } else { Q_ASSERT( false && "invalid ramp type" ); } mStyle->addColorRamp( name, ramp.release(), true ); mModified = true; return true; } void QgsStyleManagerDialog::removeItem() { bool changed = false; if ( currentItemType() < 3 ) { changed = removeSymbol(); } else if ( currentItemType() == 3 ) { changed = removeColorRamp(); } else { Q_ASSERT( false && "not implemented" ); } if ( changed ) { populateList(); populateTypes(); } } bool QgsStyleManagerDialog::removeSymbol() { QModelIndexList indexes = listItems->selectionModel()->selectedIndexes(); if ( QMessageBox::Yes != QMessageBox::question( this, tr( "Confirm removal" ), QString( tr( "Do you really want to remove %n symbol(s)?", nullptr, indexes.count() ) ), QMessageBox::Yes, QMessageBox::No ) ) return false; Q_FOREACH ( const QModelIndex &index, indexes ) { QString symbolName = index.data().toString(); // delete from style and update list if ( !symbolName.isEmpty() ) mStyle->removeSymbol( symbolName ); } mModified = true; return true; } bool QgsStyleManagerDialog::removeColorRamp() { QModelIndexList indexes = listItems->selectionModel()->selectedIndexes(); if ( QMessageBox::Yes != QMessageBox::question( this, tr( "Confirm removal" ), QString( tr( "Do you really want to remove %n ramp(s)?", nullptr, indexes.count() ) ), QMessageBox::Yes, QMessageBox::No ) ) return false; Q_FOREACH ( const QModelIndex &index, indexes ) { QString rampName = index.data().toString(); // delete from style and update list if ( !rampName.isEmpty() ) mStyle->removeColorRamp( rampName ); } mModified = true; return true; } void QgsStyleManagerDialog::itemChanged( QStandardItem *item ) { // an item has been edited QString oldName = item->data().toString(); bool changed = false; if ( currentItemType() < 3 ) { changed = mStyle->renameSymbol( oldName, item->text() ); } else if ( currentItemType() == 3 ) { changed = mStyle->renameColorRamp( oldName, item->text() ); } if ( changed ) { populateList(); mModified = true; } else { QMessageBox::critical( this, tr( "Cannot rename item" ), tr( "Name is already taken by another item. Choose a different name." ) ); item->setText( oldName ); } } void QgsStyleManagerDialog::exportItemsPNG() { QString dir = QFileDialog::getExistingDirectory( this, tr( "Exported selected symbols as PNG" ), QDir::home().absolutePath(), QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks ); exportSelectedItemsImages( dir, QStringLiteral( "png" ), QSize( 32, 32 ) ); } void QgsStyleManagerDialog::exportItemsSVG() { QString dir = QFileDialog::getExistingDirectory( this, tr( "Exported selected symbols as SVG" ), QDir::home().absolutePath(), QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks ); exportSelectedItemsImages( dir, QStringLiteral( "svg" ), QSize( 32, 32 ) ); } void QgsStyleManagerDialog::exportSelectedItemsImages( const QString &dir, const QString &format, QSize size ) { if ( dir.isEmpty() ) return; QModelIndexList indexes = listItems->selectionModel()->selection().indexes(); Q_FOREACH ( const QModelIndex &index, indexes ) { QString name = index.data().toString(); QString path = dir + '/' + name + '.' + format; QgsSymbol *sym = mStyle->symbol( name ); sym->exportImage( path, format, size ); } } void QgsStyleManagerDialog::exportItems() { QgsStyleExportImportDialog dlg( mStyle, this, QgsStyleExportImportDialog::Export ); dlg.exec(); } void QgsStyleManagerDialog::importItems() { QgsStyleExportImportDialog dlg( mStyle, this, QgsStyleExportImportDialog::Import ); dlg.exec(); populateList(); populateGroups(); } void QgsStyleManagerDialog::setBold( QStandardItem *item ) { QFont font = item->font(); font.setBold( true ); item->setFont( font ); } void QgsStyleManagerDialog::populateGroups() { QStandardItemModel *model = qobject_cast<QStandardItemModel *>( groupTree->model() ); model->clear(); QStandardItem *favoriteSymbols = new QStandardItem( tr( "Favorites" ) ); favoriteSymbols->setData( "favorite" ); favoriteSymbols->setEditable( false ); setBold( favoriteSymbols ); model->appendRow( favoriteSymbols ); QStandardItem *allSymbols = new QStandardItem( tr( "All Symbols" ) ); allSymbols->setData( "all" ); allSymbols->setEditable( false ); setBold( allSymbols ); model->appendRow( allSymbols ); QStandardItem *taggroup = new QStandardItem( QLatin1String( "" ) ); //require empty name to get first order groups taggroup->setData( "tags" ); taggroup->setEditable( false ); QStringList tags = mStyle->tags(); tags.sort(); Q_FOREACH ( const QString &tag, tags ) { QStandardItem *item = new QStandardItem( tag ); item->setData( mStyle->tagId( tag ) ); taggroup->appendRow( item ); } taggroup->setText( tr( "Tags" ) );//set title later setBold( taggroup ); model->appendRow( taggroup ); QStandardItem *smart = new QStandardItem( tr( "Smart Groups" ) ); smart->setData( "smartgroups" ); smart->setEditable( false ); setBold( smart ); QgsSymbolGroupMap sgMap = mStyle->smartgroupsListMap(); QgsSymbolGroupMap::const_iterator i = sgMap.constBegin(); while ( i != sgMap.constEnd() ) { QStandardItem *item = new QStandardItem( i.value() ); item->setData( i.key() ); smart->appendRow( item ); ++i; } model->appendRow( smart ); // expand things in the group tree int rows = model->rowCount( model->indexFromItem( model->invisibleRootItem() ) ); for ( int i = 0; i < rows; i++ ) { groupTree->setExpanded( model->indexFromItem( model->item( i ) ), true ); } } void QgsStyleManagerDialog::groupChanged( const QModelIndex &index ) { QStringList symbolNames; QStringList groupSymbols; QgsStyle::StyleEntity type = currentItemType() < 3 ? QgsStyle::SymbolEntity : QgsStyle::ColorrampEntity; if ( currentItemType() > 3 ) { QgsDebugMsg( "Entity not implemented" ); return; } QString category = index.data( Qt::UserRole + 1 ).toString(); if ( category == QLatin1String( "all" ) || category == QLatin1String( "tags" ) || category == QLatin1String( "smartgroups" ) ) { enableGroupInputs( false ); if ( category == QLatin1String( "tags" ) ) { actnAddTag->setEnabled( true ); actnAddSmartgroup->setEnabled( false ); } else if ( category == QLatin1String( "smartgroups" ) ) { actnAddTag->setEnabled( false ); actnAddSmartgroup->setEnabled( true ); } symbolNames = currentItemType() < 3 ? mStyle->symbolNames() : mStyle->colorRampNames(); } else if ( category == QLatin1String( "favorite" ) ) { enableGroupInputs( false ); symbolNames = mStyle->symbolsOfFavorite( type ); } else if ( index.parent().data( Qt::UserRole + 1 ) == "smartgroups" ) { actnRemoveGroup->setEnabled( true ); btnManageGroups->setEnabled( true ); int groupId = index.data( Qt::UserRole + 1 ).toInt(); symbolNames = mStyle->symbolsOfSmartgroup( type, groupId ); } else // tags { enableGroupInputs( true ); int tagId = index.data( Qt::UserRole + 1 ).toInt(); symbolNames = mStyle->symbolsWithTag( type, tagId ); if ( mGrouppingMode && tagId ) { groupSymbols = symbolNames; symbolNames = type == QgsStyle::SymbolEntity ? mStyle->symbolNames() : mStyle->colorRampNames(); } } symbolNames.sort(); if ( currentItemType() < 3 ) { populateSymbols( symbolNames, mGrouppingMode ); } else if ( currentItemType() == 3 ) { populateColorRamps( symbolNames, mGrouppingMode ); } if ( mGrouppingMode ) { setSymbolsChecked( groupSymbols ); } actnEditSmartGroup->setVisible( false ); actnAddTag->setVisible( false ); actnAddSmartgroup->setVisible( false ); actnRemoveGroup->setVisible( false ); actnTagSymbols->setVisible( false ); actnFinishTagging->setVisible( false ); if ( index.parent().isValid() ) { if ( index.parent().data( Qt::UserRole + 1 ).toString() == QLatin1String( "smartgroups" ) ) { actnEditSmartGroup->setVisible( !mGrouppingMode ); } else if ( index.parent().data( Qt::UserRole + 1 ).toString() == QLatin1String( "tags" ) ) { actnAddTag->setVisible( !mGrouppingMode ); actnTagSymbols->setVisible( !mGrouppingMode ); actnFinishTagging->setVisible( mGrouppingMode ); } actnRemoveGroup->setVisible( true ); } else if ( index.data( Qt::UserRole + 1 ) == "smartgroups" ) { actnAddSmartgroup->setVisible( !mGrouppingMode ); } else if ( index.data( Qt::UserRole + 1 ) == "tags" ) { actnAddTag->setVisible( !mGrouppingMode ); } } int QgsStyleManagerDialog::addTag() { QStandardItemModel *model = qobject_cast<QStandardItemModel *>( groupTree->model() ); QModelIndex index; for ( int i = 0; i < groupTree->model()->rowCount(); i++ ) { index = groupTree->model()->index( i, 0 ); QString data = index.data( Qt::UserRole + 1 ).toString(); if ( data == QLatin1String( "tags" ) ) { break; } } QString itemName; int id; bool ok; itemName = QInputDialog::getText( this, tr( "Tag name" ), tr( "Please enter name for the new tag:" ), QLineEdit::Normal, tr( "New tag" ), &ok ).trimmed(); if ( !ok || itemName.isEmpty() ) return 0; int check = mStyle->tagId( itemName ); if ( check > 0 ) { QMessageBox::critical( this, tr( "Error!" ), tr( "Tag name already exists in your symbol database." ) ); return 0; } id = mStyle->addTag( itemName ); if ( !id ) { QMessageBox::critical( this, tr( "Error!" ), tr( "New tag could not be created.\n" "There was a problem with your symbol database." ) ); return 0; } QStandardItem *parentItem = model->itemFromIndex( index ); QStandardItem *childItem = new QStandardItem( itemName ); childItem->setData( id ); parentItem->appendRow( childItem ); return id; } int QgsStyleManagerDialog::addSmartgroup() { QStandardItemModel *model = qobject_cast<QStandardItemModel *>( groupTree->model() ); QModelIndex index; for ( int i = 0; i < groupTree->model()->rowCount(); i++ ) { index = groupTree->model()->index( i, 0 ); QString data = index.data( Qt::UserRole + 1 ).toString(); if ( data == QLatin1String( "smartgroups" ) ) { break; } } QString itemName; int id; QgsSmartGroupEditorDialog dlg( mStyle, this ); if ( dlg.exec() == QDialog::Rejected ) return 0; id = mStyle->addSmartgroup( dlg.smartgroupName(), dlg.conditionOperator(), dlg.conditionMap() ); if ( !id ) return 0; itemName = dlg.smartgroupName(); QStandardItem *parentItem = model->itemFromIndex( index ); QStandardItem *childItem = new QStandardItem( itemName ); childItem->setData( id ); parentItem->appendRow( childItem ); return id; } void QgsStyleManagerDialog::removeGroup() { QStandardItemModel *model = qobject_cast<QStandardItemModel *>( groupTree->model() ); QModelIndex index = groupTree->currentIndex(); // do not allow removal of system-defined groupings QString data = index.data( Qt::UserRole + 1 ).toString(); if ( data == QLatin1String( "all" ) || data == QLatin1String( "favorite" ) || data == QLatin1String( "tags" ) || index.data() == "smartgroups" ) { int err = QMessageBox::critical( this, tr( "Invalid selection" ), tr( "Cannot delete system defined categories.\n" "Kindly select a group or smart group you might want to delete." ) ); if ( err ) return; } QStandardItem *parentItem = model->itemFromIndex( index.parent() ); if ( parentItem->data( Qt::UserRole + 1 ).toString() == QLatin1String( "smartgroups" ) ) { mStyle->remove( QgsStyle::SmartgroupEntity, index.data( Qt::UserRole + 1 ).toInt() ); } else { mStyle->remove( QgsStyle::TagEntity, index.data( Qt::UserRole + 1 ).toInt() ); } parentItem->removeRow( index.row() ); } void QgsStyleManagerDialog::groupRenamed( QStandardItem *item ) { QgsDebugMsg( "Symbol group edited: data=" + item->data( Qt::UserRole + 1 ).toString() + " text=" + item->text() ); int id = item->data( Qt::UserRole + 1 ).toInt(); QString name = item->text(); if ( item->parent()->data( Qt::UserRole + 1 ) == "smartgroups" ) { mStyle->rename( QgsStyle::SmartgroupEntity, id, name ); } else { mStyle->rename( QgsStyle::TagEntity, id, name ); } } void QgsStyleManagerDialog::tagSymbolsAction() { QStandardItemModel *treeModel = qobject_cast<QStandardItemModel *>( groupTree->model() ); QStandardItemModel *model = qobject_cast<QStandardItemModel *>( listItems->model() ); if ( mGrouppingMode ) { mGrouppingMode = false; actnTagSymbols->setVisible( true ); actnFinishTagging->setVisible( false ); // disconnect slot which handles regrouping disconnect( model, &QStandardItemModel::itemChanged, this, &QgsStyleManagerDialog::regrouped ); // disabel all items except groups in groupTree enableItemsForGroupingMode( true ); groupChanged( groupTree->currentIndex() ); // Finally: Reconnect all Symbol editing functionalities connect( treeModel, &QStandardItemModel::itemChanged, this, &QgsStyleManagerDialog::groupRenamed ); connect( model, &QStandardItemModel::itemChanged, this, &QgsStyleManagerDialog::itemChanged ); // Reset the selection mode listItems->setSelectionMode( QAbstractItemView::ExtendedSelection ); } else { bool validGroup = false; // determine whether it is a valid group QModelIndex present = groupTree->currentIndex(); while ( present.parent().isValid() ) { if ( present.parent().data() == "Tags" ) { validGroup = true; break; } present = present.parent(); } if ( !validGroup ) return; mGrouppingMode = true; // Change visibility of actions actnTagSymbols->setVisible( false ); actnFinishTagging->setVisible( true ); // Remove all Symbol editing functionalities disconnect( treeModel, &QStandardItemModel::itemChanged, this, &QgsStyleManagerDialog::groupRenamed ); disconnect( model, &QStandardItemModel::itemChanged, this, &QgsStyleManagerDialog::itemChanged ); // disabel all items except groups in groupTree enableItemsForGroupingMode( false ); groupChanged( groupTree->currentIndex() ); btnManageGroups->setEnabled( true ); // Connect to slot which handles regrouping connect( model, &QStandardItemModel::itemChanged, this, &QgsStyleManagerDialog::regrouped ); // No selection should be possible listItems->setSelectionMode( QAbstractItemView::NoSelection ); } } void QgsStyleManagerDialog::regrouped( QStandardItem *item ) { QgsStyle::StyleEntity type = ( currentItemType() < 3 ) ? QgsStyle::SymbolEntity : QgsStyle::ColorrampEntity; if ( currentItemType() > 3 ) { QgsDebugMsg( "Unknown style entity" ); return; } QStandardItemModel *treeModel = qobject_cast<QStandardItemModel *>( groupTree->model() ); QString tag = treeModel->itemFromIndex( groupTree->currentIndex() )->text(); QString symbolName = item->text(); bool regrouped; if ( item->checkState() == Qt::Checked ) regrouped = mStyle->tagSymbol( type, symbolName, QStringList( tag ) ); else regrouped = mStyle->detagSymbol( type, symbolName, QStringList( tag ) ); if ( !regrouped ) { int er = QMessageBox::critical( this, tr( "Database Error" ), tr( "There was a problem with the Symbols database while regrouping." ) ); // call the slot again to get back to normal if ( er ) tagSymbolsAction(); } } void QgsStyleManagerDialog::setSymbolsChecked( const QStringList &symbols ) { QStandardItemModel *model = qobject_cast<QStandardItemModel *>( listItems->model() ); Q_FOREACH ( const QString &symbol, symbols ) { QList<QStandardItem *> items = model->findItems( symbol ); Q_FOREACH ( QStandardItem *item, items ) item->setCheckState( Qt::Checked ); } } void QgsStyleManagerDialog::filterSymbols( const QString &qword ) { QStringList items; items = mStyle->findSymbols( currentItemType() < 3 ? QgsStyle::SymbolEntity : QgsStyle::ColorrampEntity, qword ); items.sort(); if ( currentItemType() == 3 ) { populateColorRamps( items ); } else { populateSymbols( items ); } } void QgsStyleManagerDialog::symbolSelected( const QModelIndex &index ) { actnEditItem->setEnabled( index.isValid() && !mGrouppingMode ); } void QgsStyleManagerDialog::selectedSymbolsChanged( const QItemSelection &selected, const QItemSelection &deselected ) { Q_UNUSED( selected ); Q_UNUSED( deselected ); bool nothingSelected = listItems->selectionModel()->selectedIndexes().empty(); actnRemoveItem->setDisabled( nothingSelected ); actnAddFavorite->setDisabled( nothingSelected ); actnRemoveFavorite->setDisabled( nothingSelected ); mGroupListMenu->setDisabled( nothingSelected ); actnDetag->setDisabled( nothingSelected ); actnExportAsPNG->setDisabled( nothingSelected ); actnExportAsSVG->setDisabled( nothingSelected ); actnEditItem->setDisabled( nothingSelected ); } void QgsStyleManagerDialog::enableSymbolInputs( bool enable ) { groupTree->setEnabled( enable ); btnAddTag->setEnabled( enable ); btnAddSmartgroup->setEnabled( enable ); actnAddTag->setEnabled( enable ); actnAddSmartgroup->setEnabled( enable ); actnRemoveGroup->setEnabled( enable ); btnManageGroups->setEnabled( enable || mGrouppingMode ); // always enabled in grouping mode, as it is the only way to leave grouping mode searchBox->setEnabled( enable ); } void QgsStyleManagerDialog::enableGroupInputs( bool enable ) { actnRemoveGroup->setEnabled( enable ); btnManageGroups->setEnabled( enable || mGrouppingMode ); // always enabled in grouping mode, as it is the only way to leave grouping mode } void QgsStyleManagerDialog::enableItemsForGroupingMode( bool enable ) { QStandardItemModel *treeModel = qobject_cast<QStandardItemModel *>( groupTree->model() ); for ( int i = 0; i < treeModel->rowCount(); i++ ) { treeModel->item( i )->setEnabled( enable ); if ( treeModel->item( i )->data() == "smartgroups" ) { for ( int j = 0; j < treeModel->item( i )->rowCount(); j++ ) { treeModel->item( i )->child( j )->setEnabled( enable ); } } } // The buttons // NOTE: if you ever change the layout name in the .ui file edit here too for ( int i = 0; i < symbolBtnsLayout->count(); i++ ) { QWidget *w = qobject_cast<QWidget *>( symbolBtnsLayout->itemAt( i )->widget() ); if ( w ) w->setEnabled( enable ); } // The actions actnRemoveItem->setEnabled( enable ); actnEditItem->setEnabled( enable ); } void QgsStyleManagerDialog::grouptreeContextMenu( QPoint point ) { QPoint globalPos = groupTree->viewport()->mapToGlobal( point ); QModelIndex index = groupTree->indexAt( point ); QgsDebugMsg( "Now you clicked: " + index.data().toString() ); if ( index.isValid() && !mGrouppingMode ) mGroupTreeContextMenu->popup( globalPos ); } void QgsStyleManagerDialog::listitemsContextMenu( QPoint point ) { QPoint globalPos = listItems->viewport()->mapToGlobal( point ); // Clear all actions and create new actions for every group mGroupListMenu->clear(); QAction *a = nullptr; QStringList tags = mStyle->tags(); tags.sort(); Q_FOREACH ( const QString &tag, tags ) { a = new QAction( tag, mGroupListMenu ); a->setData( tag ); connect( a, &QAction::triggered, this, [ = ]( bool ) { tagSelectedSymbols(); } ); mGroupListMenu->addAction( a ); } if ( tags.count() > 0 ) { mGroupListMenu->addSeparator(); } a = new QAction( tr( "Create new tag…" ), mGroupListMenu ); connect( a, &QAction::triggered, this, [ = ]( bool ) { tagSelectedSymbols( true ); } ); mGroupListMenu->addAction( a ); mGroupMenu->popup( globalPos ); } void QgsStyleManagerDialog::addFavoriteSelectedSymbols() { QgsStyle::StyleEntity type = ( currentItemType() < 3 ) ? QgsStyle::SymbolEntity : QgsStyle::ColorrampEntity; if ( currentItemType() > 3 ) { QgsDebugMsg( "unknown entity type" ); return; } QModelIndexList indexes = listItems->selectionModel()->selectedIndexes(); Q_FOREACH ( const QModelIndex &index, indexes ) { mStyle->addFavorite( type, index.data().toString() ); } populateList(); } void QgsStyleManagerDialog::removeFavoriteSelectedSymbols() { QgsStyle::StyleEntity type = ( currentItemType() < 3 ) ? QgsStyle::SymbolEntity : QgsStyle::ColorrampEntity; if ( currentItemType() > 3 ) { QgsDebugMsg( "unknown entity type" ); return; } QModelIndexList indexes = listItems->selectionModel()->selectedIndexes(); Q_FOREACH ( const QModelIndex &index, indexes ) { mStyle->removeFavorite( type, index.data().toString() ); } populateList(); } void QgsStyleManagerDialog::tagSelectedSymbols( bool newTag ) { QAction *selectedItem = qobject_cast<QAction *>( sender() ); if ( selectedItem ) { QgsStyle::StyleEntity type = ( currentItemType() < 3 ) ? QgsStyle::SymbolEntity : QgsStyle::ColorrampEntity; if ( currentItemType() > 3 ) { QgsDebugMsg( "unknown entity type" ); return; } QString tag; if ( newTag ) { int id = addTag(); if ( id == 0 ) { return; } tag = mStyle->tag( id ); } else { tag = selectedItem->data().toString(); } QModelIndexList indexes = listItems->selectionModel()->selectedIndexes(); Q_FOREACH ( const QModelIndex &index, indexes ) { mStyle->tagSymbol( type, index.data().toString(), QStringList( tag ) ); } populateList(); QgsDebugMsg( "Selected Action: " + selectedItem->text() ); } } void QgsStyleManagerDialog::detagSelectedSymbols() { QAction *selectedItem = qobject_cast<QAction *>( sender() ); if ( selectedItem ) { QgsStyle::StyleEntity type = ( currentItemType() < 3 ) ? QgsStyle::SymbolEntity : QgsStyle::ColorrampEntity; if ( currentItemType() > 3 ) { QgsDebugMsg( "unknown entity type" ); return; } QModelIndexList indexes = listItems->selectionModel()->selectedIndexes(); Q_FOREACH ( const QModelIndex &index, indexes ) { mStyle->detagSymbol( type, index.data().toString() ); } populateList(); QgsDebugMsg( "Selected Action: " + selectedItem->text() ); } } void QgsStyleManagerDialog::editSmartgroupAction() { QStandardItemModel *treeModel = qobject_cast<QStandardItemModel *>( groupTree->model() ); // determine whether it is a valid group QModelIndex present = groupTree->currentIndex(); if ( present.parent().data( Qt::UserRole + 1 ) != "smartgroups" ) { QMessageBox::critical( this, tr( "Invalid Selection" ), tr( "You have not selected a Smart Group. Kindly select a Smart Group to edit." ) ); return; } QStandardItem *item = treeModel->itemFromIndex( present ); QgsSmartGroupEditorDialog dlg( mStyle, this ); QgsSmartConditionMap map = mStyle->smartgroup( present.data( Qt::UserRole + 1 ).toInt() ); dlg.setSmartgroupName( item->text() ); dlg.setOperator( mStyle->smartgroupOperator( item->data().toInt() ) ); dlg.setConditionMap( map ); if ( dlg.exec() == QDialog::Rejected ) return; mStyle->remove( QgsStyle::SmartgroupEntity, item->data().toInt() ); int id = mStyle->addSmartgroup( dlg.smartgroupName(), dlg.conditionOperator(), dlg.conditionMap() ); if ( !id ) { QMessageBox::critical( this, tr( "Database Error!" ), tr( "There was some error while editing the smart group." ) ); return; } item->setText( dlg.smartgroupName() ); item->setData( id ); groupChanged( present ); } void QgsStyleManagerDialog::onClose() { reject(); } void QgsStyleManagerDialog::showHelp() { QgsHelp::openHelp( QStringLiteral( "working_with_vector/style_library.html#the-style-manager" ) ); }
sbrunner/QGIS
src/gui/symbology/qgsstylemanagerdialog.cpp
C++
gpl-2.0
48,339
<?php /***************************************************************************** * * i18n.php - Instantiates the internationalization in NagVis and registers * the global l() method to translate strings in NagVis * * Copyright (c) 2004-2011 NagVis Project (Contact: info@nagvis.org) * * License: * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * *****************************************************************************/ /* * l() needs to be available in MainCfg initialization and config parsing, * but GlobalLanguage initialization relies on the main configuration in * some parts. * The cleanest way to solve this problem is to skip the i18n in the main * configuration init code until all needed values are initialized and then * initialize the i18n code. */ // ---------------------------------------------------------------------------- $_MAINCFG = new GlobalMainCfg(); $_MAINCFG->init(); /** * This is mainly a short access to config options. In the past the whole * language object method call was used all arround NagVis. This has been * introduced to keep the code shorter */ function cfg($sec, $key, $ignoreDefaults = false) { global $_MAINCFG; return $_MAINCFG->getValue($sec, $key, $ignoreDefaults); } function path($type, $loc, $var, $relfile = '') { global $_MAINCFG; return $_MAINCFG->getPath($type, $loc, $var, $relfile); } // ---------------------------------------------------------------------------- $_LANG = new GlobalLanguage(); /** * This is mainly a short access to localized strings. In the past the whole * language object method call was used all arround NagVis. This has been * introduced to keep the code shorter */ function l($txt, $vars = null) { global $_LANG; if(isset($_LANG)) return $_LANG->getText($txt, $vars); elseif($vars !== null) return GlobalLanguage::getReplacedString($txt, $vars); else return $txt; } function curLang() { global $_LANG; return $_LANG->getCurrentLanguage(); } // ---------------------------------------------------------------------------- /** * Initialize the backend management for all pages. But don't open backend * connections. This is only done when the pages request data from any backend */ $_BACKEND = new CoreBackendMgmt(); ?>
titilambert/nagvis
share/server/core/functions/core.php
PHP
gpl-2.0
2,908