repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
TruthBean/ssm
src/test/java/com/truthbean/ssm/demo/test/Starter.java
2736
package com.truthbean.ssm.demo.test; import org.apache.log4j.Logger; import org.eclipse.jetty.server.*; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Slf4jLog; import org.eclipse.jetty.util.ssl.SslContextFactory; import org.eclipse.jetty.webapp.WebAppContext; import java.io.File; /** * @author Truthbean * @since 2015-12-23 18:54:07 */ public class Starter { static { try { Log.setLog(new Slf4jLog()); } catch (final Exception e) { e.printStackTrace(); } } private Starter() { } public static void main(String[] args) throws Exception { final Logger logger = Logger.getLogger(Starter.class); String webapp = "src/main/webapp/"; logger.info("webapp location is: " + webapp); final File file = new File(webapp); if (!file.exists()) { webapp = "."; // prod env } logger.info("webapp location is: " + webapp); /*Server server = new Server(8080); WebAppContext root = new WebAppContext(); root.setContextPath("/ssm"); root.setDescriptor(webapp + "/WEB-INF/web.xml"); root.setResourceBase(webapp); server.setHandler(root); server.start(); server.join();*/ Server server = new Server(); HttpConfiguration https_config = new HttpConfiguration(); https_config.setSecureScheme("https"); https_config.setSecurePort(8443); https_config.setOutputBufferSize(32768); https_config.addCustomizer(new SecureRequestCustomizer()); SslContextFactory sslContextFactory = new SslContextFactory(); sslContextFactory.setKeyStorePath("src/main/resources/config/jetty/keystore"); sslContextFactory.setKeyStorePassword("OBF:1v2j1uum1xtv1zej1zer1xtn1uvk1v1v"); sslContextFactory.setKeyManagerPassword("OBF:1v2j1uum1xtv1zej1zer1xtn1uvk1v1v"); ServerConnector httpsConnector = new ServerConnector(server, new SslConnectionFactory(sslContextFactory, "http/1.1"), new HttpConnectionFactory(https_config)); httpsConnector.setPort(8443); httpsConnector.setIdleTimeout(500000); server.addConnector(httpsConnector); WebAppContext root = new WebAppContext(); root.setContextPath("/ssm"); root.setDescriptor(webapp + "/WEB-INF/web.xml"); root.setResourceBase(webapp); root.setInitParameter("org.eclipse.jetty.servlet.Default.dirAllowed", "false"); root.setInitParameter("org.eclipse.jetty.servlet.Default.useFileMappedBuffer", "false"); server.setHandler(root); server.start(); server.join(); } }
gpl-2.0
dalder/TYPO3.CMS
typo3/sysext/backend/Tests/Unit/Form/FormDataProvider/DatabaseEditRowTest.php
4093
<?php namespace TYPO3\CMS\Backend\Tests\Unit\Form\FormDataProvider; /* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ use Prophecy\Argument; use Prophecy\Prophecy\ObjectProphecy; use TYPO3\CMS\Backend\Form\Exception\DatabaseRecordException; use TYPO3\CMS\Backend\Form\FormDataProvider\DatabaseEditRow; use TYPO3\CMS\Core\Database\DatabaseConnection; use TYPO3\CMS\Core\Tests\UnitTestCase; /** * Test case */ class DatabaseEditRowTest extends UnitTestCase { /** * @var DatabaseEditRow */ protected $subject; /** * @var DatabaseConnection | ObjectProphecy */ protected $dbProphecy; protected function setUp() { $this->dbProphecy = $this->prophesize(DatabaseConnection::class); $GLOBALS['TYPO3_DB'] = $this->dbProphecy->reveal(); $this->subject = new DatabaseEditRow(); } /** * @test */ public function addDataRetrievesRecordInformationFromDatabase() { $input = [ 'tableName' => 'tt_content', 'command' => 'edit', 'vanillaUid' => 10, ]; $resultRow = [ 'uid' => 10, 'pid' => 123 ]; $this->dbProphecy->quoteStr($input['tableName'], $input['tableName'])->willReturn($input['tableName']); $this->dbProphecy->exec_SELECTgetSingleRow('*', 'tt_content', 'uid=' . $input['vanillaUid'])->willReturn($resultRow); $this->dbProphecy->exec_SELECTgetSingleRow(Argument::cetera())->willReturn([]); $result = $this->subject->addData($input); $this->assertSame($resultRow, $result['databaseRow']); } /** * @test */ public function addDataThrowsExceptionIfRetrievedRowHasNoPid() { $input = [ 'tableName' => 'tt_content', 'command' => 'edit', 'vanillaUid' => 10, ]; $resultRow = [ 'uid' => 10, ]; $this->dbProphecy->quoteStr($input['tableName'], $input['tableName'])->willReturn($input['tableName']); $this->dbProphecy->exec_SELECTgetSingleRow('*', 'tt_content', 'uid=' . $input['vanillaUid'])->willReturn($resultRow); $this->setExpectedException(\UnexpectedValueException::class, $this->anything(), 1437663061); $this->subject->addData($input); } /** * @test */ public function addDataThrowsExceptionIfGivenUidIsNotPositive() { $input = [ 'tableName' => 'tt_content', 'command' => 'edit', 'vanillaUid' => -10, ]; $this->setExpectedException(\InvalidArgumentException::class, $this->anything(), 1437656456); $this->subject->addData($input); } /** * @test */ public function addDataThrowsExceptionIfNoRecordForEditingCouldBeRetrievedFromDatabase() { $input = [ 'tableName' => 'tt_content', 'command' => 'edit', 'vanillaUid' => 10, ]; $this->setExpectedException(\RuntimeException::class, $this->anything(), 1437655862); $this->subject->addData($input); } /** * @test */ public function addDataThrowsExceptionIfDatabaseFetchingReturnsFalse() { $input = [ 'tableName' => 'tt_content', 'command' => 'edit', 'vanillaUid' => 10, ]; $this->dbProphecy->quoteStr(Argument::cetera())->willReturn($input['tableName']); $this->dbProphecy->exec_SELECTgetSingleRow(Argument::cetera())->willReturn(FALSE); $this->setExpectedException(DatabaseRecordException::class, $this->anything(), 1437656081); $this->subject->addData($input); } /** * @test */ public function addDataThrowsExceptionIfDatabaseFetchingReturnsInvalidRowResultData() { $input = [ 'tableName' => 'tt_content', 'command' => 'edit', 'vanillaUid' => 10, ]; $this->dbProphecy->quoteStr(Argument::cetera())->willReturn($input['tableName']); $this->dbProphecy->exec_SELECTgetSingleRow(Argument::cetera())->willReturn('invalid result data'); $this->setExpectedException(\UnexpectedValueException::class, $this->anything(), 1437656323); $this->subject->addData($input); } }
gpl-2.0
utds3lab/SMVHunter
dynamic/src/com/android/hierarchyviewer/AboutDialog.java
2907
/* * Copyright (C) 2010 The Android Open Source Project * * 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.android.hierarchyviewer; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CLabel; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import com.android.ddmuilib.ImageLoader; import com.android.hierarchyviewerlib.HierarchyViewerDirector; public class AboutDialog extends Dialog { private Image mAboutImage; private Image mSmallImage; public AboutDialog(Shell shell) { super(shell); ImageLoader imageLoader = ImageLoader.getLoader(HierarchyViewerDirector.class); mSmallImage = imageLoader.loadImage("sdk-hierarchyviewer-16.png", Display.getDefault()); //$NON-NLS-1$ mAboutImage = imageLoader.loadImage("sdk-hierarchyviewer-128.png", Display.getDefault()); //$NON-NLS-1$ } @Override protected void createButtonsForButtonBar(Composite parent) { createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true); } @Override protected Control createDialogArea(Composite parent) { Composite control = new Composite(parent, SWT.NONE); control.setLayout(new GridLayout(2, true)); Composite imageControl = new Composite(control, SWT.BORDER); imageControl.setLayout(new FillLayout()); imageControl.setLayoutData(new GridData(GridData.FILL_VERTICAL)); Label imageLabel = new Label(imageControl, SWT.CENTER); imageLabel.setImage(mAboutImage); CLabel textLabel = new CLabel(control, SWT.NONE); // TODO: update with new year date (search this to find other occurrences to update) textLabel.setText("Hierarchy Viewer\nCopyright 2012, The Android Open Source Project\nAll Rights Reserved."); textLabel.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, true, true)); getShell().setText("About..."); getShell().setImage(mSmallImage); return control; } }
gpl-2.0
emundus/v6
plugins/fabrik_element/googlemap/googlemap.js
46481
/** * Googlemap Element * * @copyright: Copyright (C) 2005-2013, fabrikar.com - All rights reserved. * @license: GNU/GPL http://www.gnu.org/copyleft/gpl.html */ /** call back method when maps api is loaded*/ function googlemapload() { if (typeOf(Fabrik.googleMapRadius) === 'null') { var script2 = document.createElement('script'), l = document.location, path = l.pathname.split('/'), index = path.indexOf('index.php'); // For URLs such as /index.php/elements/form/4/97 - we only want the segment before index.php if (index !== -1) { path = path.slice(0, index); } path.shift(); path = path.join('/'); script2.type = 'text/javascript'; //script2.src = l.protocol + '//' + l.host + '/' + path + '/components/com_fabrik/libs/googlemaps/distancewidget.js'; script2.src = Fabrik.liveSite + '/components/com_fabrik/libs/googlemaps/distancewidget.js'; document.body.appendChild(script2); Fabrik.googleMapRadius = true; } if (document.body) { window.fireEvent('google.map.loaded'); } else { console.log('no body'); } } function googleradiusloaded() { if (document.body) { window.fireEvent('google.radius.loaded'); } else { console.log('no body'); } } define(['jquery', 'fab/element', 'lib/debounce/jquery.ba-throttle-debounce', 'fab/fabrik'], function (jQuery, FbElement, Debounce, Fabrik) { window.FbGoogleMap = new Class({ Extends: FbElement, watchGeoCodeDone: false, options: { 'lat' : 0, 'lat_dms' : 0, 'lon' : 0, 'lon_dms' : 0, 'zoomlevel' : '13', 'control' : '', 'maptypecontrol' : false, 'maptypeids' : false, 'overviewcontrol' : false, 'scalecontrol' : false, 'drag' : false, 'maptype' : 'G_NORMAL_MAP', 'geocode' : false, 'latlng' : false, 'latlng_dms' : false, 'staticmap' : false, 'auto_center' : false, 'scrollwheel' : false, 'streetView' : false, 'sensor' : false, 'center' : 0, 'reverse_geocode' : false, 'use_radius' : false, 'geocode_on_load' : false, 'traffic' : false, 'debounceDelay' : 500, 'styles' : [], 'directionsFrom' : false, 'directionsFromLat' : 0, 'directionsFromLon' : 0, 'reverse_geocode_fields': {}, 'key' : false, 'language' : '', 'mapShown' : true, 'use_overlays' : false, 'overlays' : [], 'overlay_urls' : [], 'overlay_labels' : [], 'overlay_events' : [], 'lat_element' : '', 'lon_element' : '' }, loadScript: function () { Fabrik.loadGoogleMap(this.options.key, 'googlemapload', this.options.language); }, initialize: function (element, options) { this.mapMade = false; this.redrawn = false; this.parent(element, options); if (!this.options.mapShown) { return; } this.loadFn = function () { // experimental support for OSM rendering this.mapTypeIds = []; if (typeOf(this.options.maptypeids) !== 'array') { for (var type in google.maps.MapTypeId) { this.mapTypeIds.push(google.maps.MapTypeId[type]); } } else { for (var type in this.options.maptypeids) { this.mapTypeIds.push(this.options.maptypeids[type]); } } this.mapTypeIds.push('OSM'); switch (this.options.maptype) { case 'OSM': this.options.maptype = 'OSM'; break; case 'G_SATELLITE_MAP': this.options.maptype = google.maps.MapTypeId.SATELLITE; break; case 'G_HYBRID_MAP': this.options.maptype = google.maps.MapTypeId.HYBRID; break; case 'TERRAIN': this.options.maptype = google.maps.MapTypeId.TERRAIN; break; default: /* falls through */ case 'G_NORMAL_MAP': this.options.maptype = google.maps.MapTypeId.ROADMAP; break; } this.makeMap(); // @TODO test google object when offline typeOf(google) isnt working if (this.options.center === 1 && (this.options.rowid === '' || this.options.rowid === 0)) { if (geo_position_js.init()) { geo_position_js.getCurrentPosition(this.geoCenter.bind(this), this.geoCenterErr.bind(this), { enableHighAccuracy: true }); } else { fconsole('Geo location functionality not available'); } } }.bind(this); this.radFn = function () { this.makeRadius(); }.bind(this); window.addEvent('google.map.loaded', this.loadFn); window.addEvent('google.radius.loaded', this.radFn); this.loadScript(); }, /** * Called when form closed in ajax window */ destroy: function () { window.removeEvent('google.map.loaded', this.loadFn); window.removeEvent('google.radius.loaded', this.radFn); }, getValue: function () { if (typeOf(this.field) !== 'null') { return this.field.get('value'); } return false; }, makeMap: function () { if (this.mapMade === true) { return; } this.mapMade = true; var self = this; if (typeof(this.map) !== 'undefined' && this.map !== null) { return; } if (typeOf(this.element) === 'null') { return; } if (this.options.geocode || this.options.reverse_geocode) { this.geocoder = new google.maps.Geocoder(); } // Need to use this.options.element as if loading from ajax popup win in list view for some reason // this.element refers to the first loaded row, which should have been removed from the dom this.element = document.id(this.options.element); if (typeOf(this.element) === 'null') { return; } this.field = this.element.getElement('input.fabrikinput'); /** * watchGeoCode() needs to run after all the elements have been added to the form, but * the elements.added event may have already fired. Typically on first load, where we * waited for the maps API to load, it will have already fired. But (say) opening a popup * for a second time, API is already loaded, so no delay. So call it direct, AND from the event, * and watchGeoCode() will keep track of whether it can / has run. */ this.watchGeoCode(); Fabrik.addEvent('fabrik.form.elements.added', function (form) { if (form === self.form) { self.watchGeoCode(); } }); if (this.options.staticmap) { var i = this.element.getElement('img'); var w = i.getStyle('width').toInt(); var h = i.getStyle('height').toInt(); } this.center = new google.maps.LatLng(this.options.lat, this.options.lon); if (!this.options.staticmap) { var zoomControlStyle = this.options.control === 'GSmallMapControl' ? google.maps.ZoomControlStyle.SMALL : google.maps.ZoomControlStyle.LARGE; var vzoomControl = this.options.control !== 'none'; var mapOpts = { center : this.center, zoom : this.options.zoomlevel.toInt(), mapTypeId : this.options.maptype, scaleControl : this.options.scalecontrol, mapTypeControl : this.options.maptypecontrol, overviewMapControl : this.options.overviewcontrol, scrollwheel : this.options.scrollwheel, streetViewControl : this.options.streetView, zoomControl : vzoomControl, zoomControlOptions : { style: zoomControlStyle }, mapTypeControlOptions: { mapTypeIds: this.mapTypeIds } }; this.map = new google.maps.Map(document.id(this.element).getElement('.map'), mapOpts); this.map.setOptions({'styles': this.options.styles}); /** * Experimental support for OSM tile rendering, see ... * http://wiki.openstreetmap.org/wiki/Google_Maps_Example */ if (this.options.maptype === 'OSM') { this.map.mapTypes.set('OSM', new google.maps.ImageMapType({ getTileUrl: function (coord, zoom) { // See above example if you need smooth wrapping at 180th meridian return 'http://tile.openstreetmap.org/' + zoom + '/' + coord.x + '/' + coord.y + '.png'; }, tileSize : new google.maps.Size(256, 256), name : 'OpenStreetMap', maxZoom : 18 })); } if (this.options.traffic) { var trafficLayer = new google.maps.TrafficLayer(); trafficLayer.setMap(this.map); } var opts = { map : this.map, position: this.center }; opts.draggable = this.options.drag; if (this.options.latlng === true) { this.element.getElement('.lat').addEvent('blur', function (e) { this.updateFromLatLng(e); }.bind(this)); this.element.getElement('.lng').addEvent('blur', function (e) { this.updateFromLatLng(e); }.bind(this)); } if (this.options.latlng_dms === true) { this.element.getElement('.latdms').addEvent('blur', function (e) { this.updateFromDMS(e); }.bind(this)); this.element.getElement('.lngdms').addEvent('blur', function (e) { this.updateFromDMS(e); }.bind(this)); } if (this.options.latlng_elements === true) { var latEl = this.form.formElements.get(this.options.lat_element); var lonEl = this.form.formElements.get(this.options.lon_element); if (latEl && lonEl) { latEl.addNewEventAux(latEl.getChangeEvent(), function (e) { this.updateFromLatLngElements(e); }.bind(this)); lonEl.addNewEventAux(lonEl.getChangeEvent(), function (e) { this.updateFromLatLngElements(e); }.bind(this)); } } this.marker = new google.maps.Marker(opts); if (this.options.latlng === true) { this.element.getElement('.lat').value = this.marker.getPosition().lat() + '° N'; this.element.getElement('.lng').value = this.marker.getPosition().lng() + '° E'; } if (this.options.latlng_dms === true) { this.element.getElement('.latdms').value = this.latDecToDMS(); this.element.getElement('.lngdms').value = this.lngDecToDMS(); } if (this.options.directionsFrom) { this.directionsService = new google.maps.DirectionsService(); this.directionsDisplay = new google.maps.DirectionsRenderer(); this.directionsDisplay.setMap(this.map); this.directionsFromPoint = new google.maps.LatLng( this.options.directionsFromLat, this.options.directionsFromLon ); this.calcRoute(); } google.maps.event.addListener(this.marker, 'dragend', function () { if (this.options.auto_center) { this.center = this.marker.getPosition(); this.map.setCenter(this.center); } this.field.value = this.marker.getPosition() + ':' + this.map.getZoom(); if (this.options.latlng === true) { this.element.getElement('.lat').value = this.marker.getPosition().lat() + '° N'; this.element.getElement('.lng').value = this.marker.getPosition().lng() + '° E'; } if (this.options.latlng_dms === true) { this.element.getElement('.latdms').value = this.latDecToDMS(); this.element.getElement('.lngdms').value = this.lngDecToDMS(); } if (this.options.latlng_elements === true) { var latEl = this.form.formElements.get(this.options.lat_element); var lonEl = this.form.formElements.get(this.options.lon_element); if (latEl && lonEl) { latEl.update(this.marker.getPosition().lat()); lonEl.update(this.marker.getPosition().lng()); } } if (this.options.latlng_osref === true) { this.element.getElement('.osref').value = this.latLonToOSRef(); } if (this.options.reverse_geocode) { this.reverseGeocode(); } if (this.options.directionsFrom) { this.calcRoute(); } Fabrik.fireEvent('fabrik.map.marker.moved', this); }.bind(this)); //google.maps.event.addListener(map, 'drag', centerMarker); google.maps.event.addListener(this.map, 'zoom_changed', function (oldLevel, newLevel) { this.field.value = this.marker.getPosition() + ':' + this.map.getZoom(); }.bind(this)); google.maps.event.addListener(this.map, 'center_changed', function () { this.center = this.map.getCenter(); if (this.options.auto_center && this.options.editable) { this.marker.setPosition(this.map.getCenter()); this.field.value = this.marker.getPosition() + ':' + this.map.getZoom(); if (this.options.latlng === true) { this.element.getElement('.lat').value = this.marker.getPosition().lat() + '° N'; this.element.getElement('.lng').value = this.marker.getPosition().lng() + '° E'; } if (this.options.latlng_dms === true) { this.element.getElement('.latdms').value = this.latDecToDMS(); this.element.getElement('.lngdms').value = this.lngDecToDMS(); } if (this.options.latlng_elements === true) { var latEl = this.form.formElements.get(this.options.lat_element); var lonEl = this.form.formElements.get(this.options.lon_element); if (latEl && lonEl) { latEl.update(this.marker.getPosition().lat()); lonEl.update(this.marker.getPosition().lng()); } } } }.bind(this)); this.addOverlays(); } this.watchTab(); Fabrik.addEvent('fabrik.form.page.change.end', function (form) { this.redraw(); }.bind(this)); Fabrik.fireEvent('fabrik.map.make.end', this); }, calcRoute: function () { var request = { origin : this.directionsFromPoint, destination: this.marker.getPosition(), travelMode : google.maps.TravelMode.DRIVING }; this.directionsService.route(request, function (result, status) { if (status == google.maps.DirectionsStatus.OK) { this.directionsDisplay.setDirections(result); } }.bind(this)); }, radiusUpdatePosition: function () { }, radiusUpdateDistance: function () { if (this.options.radius_write_element) { var distance = this.distanceWidget.get('distance'); if (this.options.radius_unit === 'm') { distance = distance / 1.609344; } $(this.options.radius_write_element).value = parseFloat(distance).toFixed(2); //$(this.options.radius_write_element).fireEvent('change', new Event.Mock($(this.options.radius_write_element), 'change')); } }, radiusActiveChanged: function () { // fired by the radius widget when move / drag operation is complete // so let's fire the write element's change event. Don't do this in updateDistance, // as it'll keep firing as they drag. We don't want to fire 'change' until the changing is finished if (this.options.radius_write_element) { if (!this.distanceWidget.get('active')) { document.id(this.options.radius_write_element).fireEvent('change', new Event.Mock(document.id(this.options.radius_write_element), 'change')); } } }, radiusSetDistance: function () { if (this.options.radius_read_element) { var distance = document.id(this.options.radius_read_element).value; if (this.options.radius_unit === 'm') { distance = distance * 1.609344; } var pos = this.distanceWidget.get('sizer_position'); this.distanceWidget.set('distance', distance); var center = this.distanceWidget.get('center'); this.distanceWidget.set('center', center); } }, makeRadius: function () { if (this.options.use_radius) { if (this.options.radius_read_element && this.options.repeatCounter > 0) { this.options.radius_read_element = this.options.radius_read_element.replace(/_\d+$/, '_' + this.options.repeatCounter); } if (this.options.radius_write_element && this.options.repeatCounter > 0) { this.options.radius_write_element = this.options.radius_write_element.replace(/_\d+$/, '_' + this.options.repeatCounter); } var distance = this.options.radius_default; if (!this.options.editable) { distance = this.options.radius_ro_value; } else { if (this.options.radius_read_element) { distance = document.id(this.options.radius_read_element).value; } else if (this.options.radius_write_element) { distance = document.id(this.options.radius_write_element).value; } } if (this.options.radius_unit === 'm') { distance = distance * 1.609344; } this.distanceWidget = new DistanceWidget({ map : this.map, marker : this.marker, distance : distance, // Starting distance in km. maxDistance : 2500, // Twitter has a max distance of 2500km. color : '#000000', activeColor : '#5599bb', sizerIcon : new google.maps.MarkerImage(this.options.radius_resize_off_icon), activeSizerIcon: new google.maps.MarkerImage(this.options.radius_resize_icon) }); google.maps.event.addListener(this.distanceWidget, 'distance_changed', this.radiusUpdateDistance.bind(this)); google.maps.event.addListener(this.distanceWidget, 'position_changed', this.radiusUpdatePosition.bind(this)); google.maps.event.addListener(this.distanceWidget, 'active_changed', this.radiusActiveChanged.bind(this)); if (this.options.radius_fitmap) { this.map.setZoom(20); this.map.fitBounds(this.distanceWidget.get('bounds')); } this.radiusUpdateDistance(); this.radiusUpdatePosition(); this.radiusAddActions(); } }, radiusAddActions: function () { if (this.options.radius_read_element) { document.id(this.options.radius_read_element).addEvent('change', this.radiusSetDistance.bind(this)); } }, updateFromLatLngElements: function () { var latEl = this.form.formElements.get(this.options.lat_element); var lonEl = this.form.formElements.get(this.options.lon_element); if (latEl && lonEl) { var lat = latEl.getValue(); var lon = lonEl.getValue(); if (lat !== '' && lon !== '') { lat = lat.replace('° N', '').replace(',', '.').toFloat(); lon = lon.replace('° E', '').replace(',', '.').toFloat(); var pnt = new google.maps.LatLng(lat, lon); this.marker.setPosition(pnt); this.doSetCenter(pnt, this.map.getZoom(), true); } } }, updateFromLatLng: function () { var lat = this.element.getElement('.lat').get('value').replace('° N', ''); lat = lat.replace(',', '.').toFloat(); var lng = this.element.getElement('.lng').get('value').replace('° E', ''); lng = lng.replace(',', '.').toFloat(); var pnt = new google.maps.LatLng(lat, lng); this.marker.setPosition(pnt); this.doSetCenter(pnt, this.map.getZoom(), true); }, updateFromDMS: function () { var dms = this.element.getElement('.latdms'); var latdms = dms.get('value').replace('S', '-'); latdms = latdms.replace('N', ''); dms = this.element.getElement('.lngdms'); var lngdms = dms.get('value').replace('W', '-'); lngdms = lngdms.replace('E', ''); var latdms_d_ms = latdms.split('°'); var latdms_topnt = latdms_d_ms[0]; var latdms_m_s = latdms_d_ms[1].split('\''); var latdms_m = latdms_m_s[0].toFloat() * 60; var latdms_ms = (latdms_m + latdms_m_s[1].replace('"', '').toFloat()) / 3600; latdms_topnt = Math.abs(latdms_topnt.toFloat()) + latdms_ms.toFloat(); if (latdms_d_ms[0].toString().indexOf('-') !== -1) { latdms_topnt = -latdms_topnt; } var lngdms_d_ms = lngdms.toString().split('°'); var lngdms_topnt = lngdms_d_ms[0]; var lngdms_m_s = lngdms_d_ms[1].split('\''); var lngdms_m = Math.abs(lngdms_m_s[0].toFloat()) * 60; var lngdms_ms = (lngdms_m + Math.abs(lngdms_m_s[1].replace('"', '').toFloat())) / 3600; lngdms_topnt = Math.abs(lngdms_topnt.toFloat()) + lngdms_ms.toFloat(); if (lngdms_d_ms[0].toString().indexOf('-') !== -1) { lngdms_topnt = -lngdms_topnt; } var pnt = new google.maps.LatLng(latdms_topnt.toFloat(), lngdms_topnt.toFloat()); this.marker.setPosition(pnt); this.doSetCenter(pnt, this.map.getZoom(), true); }, latDecToDMS: function () { var latdec = this.marker.getPosition().lat(); var dmslat_d = parseInt(Math.abs(latdec), 10); var dmslat_m_float = 60 * (Math.abs(latdec).toFloat() - dmslat_d.toFloat()); var dmslat_m = parseInt(dmslat_m_float, 10); var dmslat_s_float = 60 * (dmslat_m_float.toFloat() - dmslat_m.toFloat()); // var dmslat_s = Math.round(dmslat_s_float.toFloat()*100)/100; var dmslat_s = dmslat_s_float.toFloat(); if (dmslat_s === 60) { dmslat_m = dmslat_m.toFloat() + 1; dmslat_s = 0; } if (dmslat_m === 60) { dmslat_d = dmslat_d.toFloat() + 1; dmslat_m = 0; } var dmslat_dir = 'N'; if (latdec.toString().indexOf('-') !== -1) { dmslat_dir = 'S'; } else { dmslat_dir = 'N'; } return dmslat_dir + dmslat_d + '°' + dmslat_m + '\'' + dmslat_s + '"'; }, lngDecToDMS: function () { var lngdec = this.marker.getPosition().lng(); var dmslng_d = parseInt(Math.abs(lngdec), 10); var dmslng_m_float = 60 * (Math.abs(lngdec).toFloat() - dmslng_d.toFloat()); var dmslng_m = parseInt(dmslng_m_float, 10); var dmslng_s_float = 60 * (dmslng_m_float.toFloat() - dmslng_m.toFloat()); // var dmslng_s = Math.round(dmslng_s_float.toFloat()*100)/100; var dmslng_s = dmslng_s_float.toFloat(); if (dmslng_s === 60) { dmslng_m.value = dmslng_m.toFloat() + 1; dmslng_s.value = 0; } if (dmslng_m === 60) { dmslng_d.value = dmslng_d.toFloat() + 1; dmslng_m.value = 0; } var dmslng_dir = ''; if (lngdec.toString().indexOf('-') !== -1) { dmslng_dir = 'W'; } else { dmslng_dir = 'E'; } return dmslng_dir + dmslng_d + '°' + dmslng_m + '\'' + dmslng_s + '"'; }, latLonToOSRef: function () { var ll2 = new LatLng(this.marker.getPosition().lng(), this.marker.getPosition().lng()); var OSRef = ll2.toOSRef(); return OSRef.toSixFigureString(); }, geoCode: function (e) { var address = ''; if (this.options.geocode === '2') { this.options.geocode_fields.each(function (field) { var f = this.form.formElements.get(field); if (f) { address += f.get('value') + ','; } }.bind(this)); address = address.slice(0, -1); } else { address = this.element.getElement('.geocode_input').value; } // Strip HTML var d = new Element('div').set('html', address); address = d.get('text'); this.geocoder.geocode({'address': address}, function (results, status) { if (status !== google.maps.GeocoderStatus.OK || results.length === 0) { fconsole(address + ' not found!'); } else { this.options.lat = results[0].geometry.location.lat(); this.options.lon = results[0].geometry.location.lng(); this.marker.setPosition(results[0].geometry.location); this.doSetCenter(results[0].geometry.location, this.map.getZoom(), false); if (this.options.reverse_geocode) { if (this.options.reverse_geocode_fields.formatted_address) { this.form.formElements.get(this.options.reverse_geocode_fields.formatted_address).update( results[0].formatted_address ); } } } }.bind(this)); }, watchGeoCode: function () { if (!this.options.geocode || !this.options.editable) { return; } if (typeof this.form === 'undefined') { return; } if (this.watchGeoCodeDone) { return; } if (this.options.geocode === '2') { if (this.options.geocode_event !== 'button') { this.options.geocode_fields.each(function (field) { var f = document.id(field); if (typeOf(f) !== 'null') { var that = this; var el = this.form.formElements.get(field); // if it's a field element with geocomplete, don't do keyup, wait for element to fire change if (!el.options.geocomplete) { jQuery(f).on('keyup', Debounce(this.options.debounceDelay, function (e) { that.geoCode(e); })); // Select lists, radios whatnots f.addEvent('change', function (e) { this.geoCode(); }.bind(this)); } else { Fabrik.addEvent('fabrik.element.field.geocode', function(el, results) { //fconsole('fired: ' + el.element.id); this.geoCode(); }.bind(this)); } } }.bind(this)); if (this.options.reverse_geocode_fields.formatted_address) { var el = this.form.formElements.get(this.options.reverse_geocode_fields.formatted_address); if (el.options.geocomplete) { Fabrik.addEvent('fabrik.element.field.geocode', function (el, result) { if (el.element.id === this.options.reverse_geocode_fields.formatted_address) { var pnt = new google.maps.LatLng( result.geometry.location.lat(), result.geometry.location.lng() ); this.marker.setPosition(pnt); this.doSetCenter(pnt, this.map.getZoom(), false); this.fillReverseGeocode(result); } }.bind(this)); } } } else { if (this.options.geocode_event === 'button') { this.element.getElement('.geocode').addEvent('click', function (e) { this.geoCode(e); }.bind(this)); } } } if (this.options.geocode === '1' && document.id(this.element).getElement('.geocode_input')) { if (this.options.geocode_event === 'button') { this.element.getElement('.geocode').addEvent('click', function (e) { this.geoCode(e); }.bind(this)); // Stop enter in geocode field submitting the form. this.element.getElement('.geocode_input').addEvent('keypress', function (e) { if (e.key === 'enter') { e.stop(); } }.bind(this)); } else { /* this.element.getElement('.geocode_input').addEvent('keyup', function (e) { e.stop(); this.geoCode(e); }.bind(this)); */ var that = this; jQuery(this.element.getElement('.geocode_input')).on('keyup', Debounce(this.options.debounceDelay, function (e) { that.geoCode(e); })); } } this.watchGeoCodeDone = true; }, unclonableProperties: function () { return ['form', 'marker', 'map', 'maptype']; }, cloned: function (c) { var f = []; this.options.geocode_fields.each(function (field) { var bits = field.split('_'); var i = bits.getLast(); if (typeOf(i.toInt()) === 'null') { return bits.join('_'); } bits.splice(bits.length - 1, 1, c); f.push(bits.join('_')); }); this.options.geocode_fields = f; this.mapMade = false; this.map = null; this.makeMap(); this.parent(c); }, update: function (v) { v = v.split(':'); if (v.length < 2) { v[1] = this.options.zoomlevel; } if (!this.map) { return; } var zoom = v[1].toInt(); this.map.setZoom(zoom); v[0] = v[0].replace('(', ''); v[0] = v[0].replace(')', ''); var pnts = v[0].split(','); if (pnts.length < 2) { pnts[0] = this.options.lat; pnts[1] = this.options.lon; } // $$$ hugh - updateFromLatLng blows up if not displayinbg lat lng // also, not sure why we would do this, as all we want to do is set map back // to default // location, not read location from lat lng fields? // this.updateFromLatLng(pnts[0], pnts[1]); // So instead, lets just set marker to default and recenter var pnt = new google.maps.LatLng(pnts[0], pnts[1]); this.marker.setPosition(pnt); this.doSetCenter(pnt, this.map.getZoom(), true); }, geoCenter: function (p) { var pnt = new google.maps.LatLng(p.coords.latitude, p.coords.longitude); this.marker.setPosition(pnt); this.doSetCenter(pnt, this.map.getZoom(), true); }, geoCenterErr: function (p) { fconsole('geo location error=' + p.message); }, /** * Redraw the map when inside a tab, and the tab is activated. Triggered from element.watchTab() */ redraw: function () { google.maps.event.trigger(this.map, 'resize'); if (!this.redrawn) { this.map.setCenter(this.center); this.map.setZoom(this.map.getZoom()); this.redrawn = true; } }, fillReverseGeocode: function(result) { if (this.options.reverse_geocode_fields.formatted_address) { this.form.formElements.get(this.options.reverse_geocode_fields.formatted_address).update(result.formatted_address); } var streetAddress = ''; var streetNumber = ''; var streetRoute = ''; result.address_components.each(function (component) { component.types.each(function (type) { if (type === 'street_number') { if (this.options.reverse_geocode_fields.street_number || this.options.reverse_geocode_fields.route) { streetNumber = component.long_name; } } else if (type === 'route') { if (this.options.reverse_geocode_fields.route) { streetRoute = component.long_name; } } else if (type === 'street_address') { if (this.options.reverse_geocode_fields.route) { streetAddress = component.long_name; } } else if (type === 'neighborhood') { if (this.options.reverse_geocode_fields.neighborhood) { this.form.formElements.get(this.options.reverse_geocode_fields.neighborhood).update(component.long_name); } } else if (type === 'locality') { if (this.options.reverse_geocode_fields.locality) { this.form.formElements.get(this.options.reverse_geocode_fields.locality).updateByLabel(component.long_name); } } else if (type === 'administrative_area_level_1') { if (this.options.reverse_geocode_fields.administrative_area_level_1) { this.form.formElements.get(this.options.reverse_geocode_fields.administrative_area_level_1).updateByLabel(component.long_name); } } else if (type === 'postal_code') { if (this.options.reverse_geocode_fields.postal_code) { this.form.formElements.get(this.options.reverse_geocode_fields.postal_code).updateByLabel(component.long_name); } } else if (type === 'country') { if (this.options.reverse_geocode_fields.country) { this.form.formElements.get(this.options.reverse_geocode_fields.country).updateByLabel(component.long_name); } } }.bind(this)); }.bind(this)); if (this.options.reverse_geocode_fields.street_number) { this.form.formElements.get(this.options.reverse_geocode_fields.street_number).update(streetNumber); this.form.formElements.get(this.options.reverse_geocode_fields.route).update(streetRoute); } else if (this.options.reverse_geocode_fields.route) { /** * Create the street address. I'm really not sure what the difference between 'route' * and 'street_address' is in Google's component types, so for now just use 'street_address' * as the preference, use 'route' if no 'street_address', and prepend 'street_number' */ if (streetRoute !== '') { if (streetAddress === '') { streetAddress = streetRoute; } } if (streetNumber !== '') { streetAddress = streetNumber + ' ' + streetAddress; } this.form.formElements.get(this.options.reverse_geocode_fields.route).update(streetAddress); } }, reverseGeocode: function () { this.geocoder.geocode({'latLng': this.marker.getPosition()}, function (results, status) { if (status === google.maps.GeocoderStatus.OK) { if (results[0]) { this.fillReverseGeocode(results[0]); } else { window.alert('No results found'); } } else { window.alert('Geocoder failed due to: ' + status); } }.bind(this)); }, doSetCenter: function (pnt, zoom, doReverseGeocode) { this.map.setCenter(pnt, zoom); this.field.value = this.marker.getPosition() + ':' + this.map.getZoom(); if (this.options.latlng === true) { this.element.getElement('.lat').value = pnt.lat() + '° N'; this.element.getElement('.lng').value = pnt.lng() + '° E'; } if (this.options.latlng_dms === true) { this.element.getElement('.latdms').value = this.latDecToDMS(); this.element.getElement('.lngdms').value = this.lngDecToDMS(); } if (this.options.latlng_elements === true) { var latEl = this.form.formElements.get(this.options.lat_element); var lonEl = this.form.formElements.get(this.options.lon_element); if (latEl && lonEl) { latEl.update(pnt.lat()); lonEl.update(pnt.lng()); } } if (doReverseGeocode && this.options.reverse_geocode) { this.reverseGeocode(); } }, attachedToForm: function () { if (this.options.geocode && this.options.geocode_on_load) { this.geoCode(); } this.parent(); }, toggleOverlayAux: function (el) { }, toggleOverlay: function (e) { if (e.target.id.test(/overlay_select_(\d+)/)) { var self = this; jQuery(e.target).closest('div').find('.fabrik_googlemap_overlay_select').each( function(k, el) { var olk = el.id.match(/overlay_select_(\d+)/)[1].toInt(); if (el.checked) { self.options.overlays[olk].setMap(self.map); } else { self.options.overlays[olk].setMap(null); } } ); } }, addOverlays: function () { if (this.options.use_overlays) { if (this.options.use_overlays_select === 'radio' && this.options.use_overlays_checked === '') { this.options.use_overlays_checked = '0'; } this.options.overlay_urls.each(function (overlay_url, k) { var pv = this.options.overlay_preserveviewports[k] === '1'; var so = this.options.overlay_suppressinfowindows[k] === '1'; this.options.overlays[k] = new google.maps.KmlLayer({ url : overlay_url, preserveViewport : pv, suppressInfoWindows: so }); if ((this.options.use_overlays_select === 'checkbox' && this.options.use_overlays_checked === '') || (this.options.use_overlays_checked.toInt() === k)) { this.options.overlays[k].setMap(this.map); } this.options.overlay_events[k] = function (e) { this.toggleOverlay(e); }.bind(this); if (typeOf(document.id(this.options.element + '_overlay_select_' + k)) !== 'null') { document.id(this.options.element + '_overlay_select_' + k).addEvent('click', this.options.overlay_events[k]); } }.bind(this)); Fabrik.fireEvent('fabrik.viz.googlemap.overlays.added', [this]); } } }); return window.FbGoogleMap; });
gpl-2.0
pavanmankala/ditaa
src/main/java/org/stathissideris/ascii2image/graphics/ImageHandler.java
3829
/* * DiTAA - Diagrams Through Ascii Art * * Copyright (C) 2004 Efstathios Sideris * * 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. * */ package org.stathissideris.ascii2image.graphics; import java.awt.Color; import java.awt.Image; import java.awt.MediaTracker; import java.awt.Toolkit; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URL; import javax.imageio.ImageIO; import javax.swing.JLabel; import org.stathissideris.ascii2image.core.FileUtils; public class ImageHandler { private static OffScreenSVGRenderer svgRenderer = new OffScreenSVGRenderer(); private static ImageHandler instance = new ImageHandler(); public static ImageHandler instance(){ return instance; } private static final MediaTracker tracker = new MediaTracker(new JLabel()); public BufferedImage loadBufferedImage(File file) throws IOException { return ImageIO.read(file); } public Image loadImage(String filename){ URL url = ClassLoader.getSystemResource(filename); Image result = null; if(url != null) result = Toolkit.getDefaultToolkit().getImage(url); else result = Toolkit.getDefaultToolkit().getImage(filename); // result = null; //wait for the image to load before returning tracker.addImage(result, 0); try { tracker.waitForID(0); } catch (InterruptedException e) { System.err.println("Failed to load image "+filename); e.printStackTrace(); } tracker.removeImage(result, 0); return result; } public BufferedImage renderSVG(String filename, int width, int height, boolean stretch) throws IOException { File file = new File(filename); URI uri = file.toURI(); return svgRenderer.renderToImage(uri.toString(), width, height, stretch, null, null); } public BufferedImage renderSVG(String filename, int width, int height, boolean stretch, String idRegex, Color color) throws IOException { File file = new File(filename); URI uri = file.toURI(); return svgRenderer.renderToImage(uri.toString(), width, height, stretch, idRegex, color); } public static void main(String[] args) throws IOException{ OffScreenSVGRenderer renderer = new OffScreenSVGRenderer(); //BufferedImage image = instance.renderSVG("sphere.svg", 200, 200, false); //BufferedImage image = renderer.renderToImage("file:///Users/sideris/Documents/workspace/ditaa/joystick.svg", FileUtils.readFile(new File("joystick.svg")), 400, 200, false); // BufferedImage image = renderer.renderToImage( // null, FileUtils.readFile(new File("sphere.svg")).replaceFirst("#187637", "#3333FF"), 200, 200, false); String content = FileUtils.readFile(new File("sphere.svg")).replaceAll("#187637", "#1133FF"); System.out.println(content); // BufferedImage image = renderer.renderToImage( // "file:/K:/devel/ditaa/sphere.svg", content, 200, 200, false); BufferedImage image = renderer.renderXMLToImage(content, 200, 200, false, null, null); try { File file = new File("testing.png"); ImageIO.write(image, "png", file); } catch (IOException e) { //e.printStackTrace(); System.err.println("Error: Cannot write to file"); } } }
gpl-2.0
jneug/bluej-lejos
src/de/upb/bluej/lejos/LeJOSUtils.java
4603
package de.upb.bluej.lejos; import java.io.File; import bluej.extensions.BClass; import bluej.extensions.BMethod; import bluej.extensions.BPackage; import bluej.extensions.BProject; import bluej.extensions.ClassNotFoundException; import bluej.extensions.PackageNotFoundException; import bluej.extensions.ProjectNotOpenException; public class LeJOSUtils { public static final String OS_NAME = getOSName(); static String getOSName() { try { String os = System.getProperty("os.name"); return (os == null ? "" : os); } catch( SecurityException ex ) { return ""; } } public static final boolean IS_MAC = isOS("Mac"); public static final boolean IS_LINUX = isOS("Linux") || isOS("LINUX"); public static final boolean IS_WINDOWS = isOS("Windows"); public static final boolean IS_UNIX = IS_MAC || IS_LINUX || isOS("AIX","HP-UX","Irix","FreeBSD","OpenBSD","NetBSD","OS/2","Solaris","SunOS"); static boolean isOS(final String osNamePrefix) { return OS_NAME.startsWith(osNamePrefix); } static boolean isOS(final String... osNamePrefix) { for( String prefix: osNamePrefix) { if( !isOS(prefix) ) return false; } return true; } /** * Checks if the provided class has a main method. * * @param clazz * @return */ public static boolean hasMain( BClass clazz ) { try { BMethod main = clazz.getMethod("main", new Class<?>[] { String[].class }); return (main != null); } catch( ProjectNotOpenException e1 ) { return false; } catch( ClassNotFoundException e2 ) { return false; } } public static BClass findClassForJavaFile( File f, BProject bproject ) { try { BPackage[] bpackages = bproject.getPackages(); for( BPackage bpackage: bpackages ) { BClass[] bclasses = bpackage.getClasses(); for( BClass bclass: bclasses ) { if( bclass.getJavaFile().equals(f) ) return bclass; } } } catch( PackageNotFoundException e1 ) { } catch( ProjectNotOpenException e2 ) { } return null; } /** * Read the {@code NXJ_HOME} environment variable and return an empty string * if it is not set. * * @return */ public static String getNxjHomeEnv() { String nxjHome = System.getenv("NXJ_HOME"); if( nxjHome == null ) nxjHome = ""; return nxjHome; } /** * Returns the path to the {@code java} command to run new java processes. * It will not check if the returned java command is valid. * * @return */ public static String getJavaHome() { return getJavaHome("java"); } public static String getJavaHome( String cmd ) { String java_home = ""; String path = cmd; java_home = System.getenv("JAVA_HOME"); if( java_home != null ) { path = java_home + File.separator + "bin" + File.separator + cmd; } java_home = System.getenv("LEJOS_NXT_JAVA_HOME"); if( java_home != null ) { path = java_home + File.separator + "bin" + File.separator + cmd; } // java_home = System.getProperty("java.home"); // if( java_home != null ) // return Paths.get(java_home, "bin", "java").toString(); return path; } /** * Checks if the "-d32" flag need to be present for invoked java processes. * This is necessary for running leJOS on Mac OS. * * @return */ public static boolean isForce32() { String os_name = System.getProperty("os.name"); return (os_name != null && os_name.startsWith("MAC")); } /** * Builds a classpath string for the provided absolute path names. * * @param paths * @return */ public static String buildClasspath( String[] paths ) { return buildClasspath(null, paths); } /** * Builds a classpath string for the provided path names relative to the * provided root directory. * * @param root * @param paths * @return */ public static String buildClasspath( File root, String[] paths ) { if( paths.length == 0 ) return ""; String dir = ""; if( root != null ) { if( root.isDirectory() ) dir = root.getAbsolutePath() + File.separator; else dir = root.getParentFile().getAbsolutePath() + File.separator; } String sep = File.pathSeparator; String cp = ""; for( int i = 0; i < paths.length; i++ ) { String new_cp = dir + paths[i]; // if( new_cp.indexOf(" ") != -1 ) // new_cp = "\""+new_cp+"\""; if( cp.isEmpty() ) cp = new_cp; else cp += sep + new_cp; } return cp; } public static String buildClasspath( File[] files ) { String[] paths = new String[files.length]; for( int i = 0; i < files.length; i++ ) { paths[i] = files[i].getAbsolutePath(); } return buildClasspath(null, paths); } }
gpl-2.0
cfloersch/JSONMarshaller
src/test/java/xpertss/json/generic/Tuple.java
769
package xpertss.json.generic; import xpertss.json.Entity; import xpertss.json.Value; import java.util.Objects; @Entity public class Tuple<L,R> { @Value private L left; @Value private R right; public Tuple() { } public Tuple(L left, R right) { this.left = left; this.right = right; } public L getLeft() { return left; } public R getRight() { return right; } public boolean equals(Object obj) { if(obj instanceof Tuple) { Tuple o = (Tuple) obj; return Objects.equals(left, o.left) && Objects.equals(right, o.right); } return false; } public int hashCode() { return Objects.hash(left, right); } }
gpl-2.0
hrishiko/gavkiwp
wp-content/themes/shopme/woocommerce/auth/form-login.php
1629
<?php /** * Auth form login * * @author WooThemes * @package WooCommerce/Templates/Auth * @version 2.4.0 */ if ( ! defined( 'ABSPATH' ) ) { exit; } ?> <?php do_action( 'woocommerce_auth_page_header' ); ?> <h1><?php printf( esc_html__( '%s would like to connect to your store' , 'woocommerce' ), esc_html( $app_name ) ); ?></h1> <?php wc_print_notices(); ?> <p><?php printf( esc_html__( 'To connect to %1$s you need to be logged in. Log in to your store below, or %2$scancel and return to %1$s%3$s', 'woocommerce' ), wc_clean( $app_name ), '<a href="' . esc_url( $return_url ) . '">', '</a>' ); ?></p> <form method="post" class="wc-auth-login"> <p class="form-row form-row-wide"> <label for="username"><?php esc_html_e( 'Username or email address', 'woocommerce' ); ?> <span class="required">*</span></label> <input type="text" class="input-text" name="username" id="username" value="<?php echo ( ! empty( $_POST['username'] ) ) ? esc_attr( $_POST['username'] ) : ''; ?>" /> </p> <p class="form-row form-row-wide"> <label for="password"><?php esc_html_e( 'Password', 'woocommerce' ); ?> <span class="required">*</span></label> <input class="input-text" type="password" name="password" id="password" /> </p> <p class="wc-auth-actions"> <?php wp_nonce_field( 'woocommerce-login' ); ?> <input type="submit" class="button button-large button-primary wc-auth-login-button" name="login" value="<?php esc_attr_e( 'Login', 'woocommerce' ); ?>" /> <input type="hidden" name="redirect" value="<?php echo esc_url( $redirect_url ); ?>" /> </p> </form> <?php do_action( 'woocommerce_auth_page_footer' ); ?>
gpl-2.0
mrkn/movabletype
php/lib/block.mtifcommentparent.php
766
<?php # Movable Type (r) Open Source (C) 2001-2010 Six Apart, Ltd. # This program is distributed under the terms of the # GNU General Public License, version 2. # # $Id$ function smarty_block_mtifcommentparent($args, $content, &$ctx, &$repeat) { if (!isset($content)) { $comment = $ctx->stash('comment'); $has_parent = 0; if ($comment && $comment->comment_parent_id) { $parent = $ctx->mt->db()->fetch_comment_parent(array( 'parent_id' => $comment->comment_parent_id, 'blog_id' => $comment->comment_blog_id)); $has_parent = $parent ? 1 : 0; } return $ctx->_hdlr_if($args, $content, $ctx, $repeat, $has_parent); } else { return $ctx->_hdlr_if($args, $content, $ctx, $repeat); } } ?>
gpl-2.0
wzlee/oauth2-server
src/main/java/com/wzlee/oauth/domain/shared/Repository.java
104
package com.wzlee.oauth.domain.shared; /** * @author Shengzhao Li */ public interface Repository { }
gpl-2.0
sourcepole/qgis
qgis/python/plugins/plugin_installer/installer_data.py
30522
# -*- coding: utf-8 -*- """ Copyright (C) 2007-2008 Matthew Perry Copyright (C) 2008-2010 Borys Jurgiel /*************************************************************************** * * * 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. * * * ***************************************************************************/ """ from PyQt4.QtCore import * from PyQt4.QtXml import QDomDocument from PyQt4.QtNetwork import * from qgis.core import * from unzip import unzip from version_compare import compareVersions, normalizeVersion import sys """ Data structure: mRepositories = dict of dicts: {repoName : {"url" QString, "enabled" bool, "valid" bool, "QPHttp" QPHttp, "Relay" Relay, # Relay object for transmitting signals from QPHttp with adding the repoName information "xmlData" QBuffer, "state" int, (0 - disabled, 1-loading, 2-loaded ok, 3-error (to be retried), 4-rejected) "error" QString}} mPlugins = dict of dicts {id : {"name" QString, "version_avail" QString, "version_inst" QString, "desc_repo" QString, "desc_local" QString, "author" QString, "status" QString, ("not installed", "installed", "upgradeable", "orphan", "new", "newer") "error" QString, ("", "broken", "incompatible", "dependent") "error_details" QString, "homepage" QString, "url" QString, "experimental" bool "filename" QString, "repository" QString, "localdir" QString, "read-only" boolean}} """ QGIS_VER = QGis.QGIS_VERSION QGIS_14 = (QGIS_VER[2] > "3") QGIS_15 = (QGIS_VER[2] > "4") def setIface(qgisIface): global iface iface = qgisIface reposGroup = "/Qgis/plugin-repos" settingsGroup = "/Qgis/plugin-installer" seenPluginGroup = "/Qgis/plugin-seen" # Repositories: (name, url, possible depreciated url) officialRepo = ("QGIS Official Repository", "http://pyqgis.org/repo/official","") contribRepo = ("QGIS Contributed Repository", "http://pyqgis.org/repo/contributed","") authorRepos = [("Aaron Racicot's Repository", "http://qgisplugins.z-pulley.com", ""), ("Barry Rowlingson's Repository", "http://www.maths.lancs.ac.uk/~rowlings/Qgis/Plugins/plugins.xml", ""), # depreciated: ("Bob Bruce's Repository", "http://www.mappinggeek.ca/QGISPythonPlugins/Bobs-QGIS-plugins.xml", ""), # depreciated: ("Borys Jurgiel's Repository", "http://bwj.aster.net.pl/qgis/plugins.xml", "http://bwj.aster.net.pl/qgis-oldapi/plugins.xml"), ("Carson Farmer's Repository", "http://www.ftools.ca/cfarmerQgisRepo.xml", "http://www.ftools.ca/cfarmerQgisRepo_0.xx.xml"), ("CatAIS Repository", "http://www.catais.org/qgis/plugins.xml", ""), ("Faunalia Repository", "http://www.faunalia.it/qgis/plugins.xml", "http://faunalia.it/qgis/plugins.xml"), ("GIS-Lab Repository", "http://gis-lab.info/programs/qgis/qgis-repo.xml", ""), ("Martin Dobias' Sandbox", "http://mapserver.sk/~wonder/qgis/plugins-sandbox.xml", ""), ("Marco Hugentobler's Repository","http://karlinapp.ethz.ch/python_plugins/python_plugins.xml", ""), ("Sourcepole Repository", "http://build.sourcepole.ch/qgis/plugins.xml", ""), ("Volkan Kepoglu's Repository","http://ggit.metu.edu.tr/~volkan/plugins.xml", "")] # --- class History ----------------------------------------------------------------------- # class History(dict): """ Dictionary for keeping changes made duging the session - will be used to complete the (un/re)loading """ # ----------------------------------------- # def markChange(self, plugin, change): """ mark the status change: A-added, D-deleted, R-reinstalled """ if change == "A" and self.get(plugin) == "D": # installation right after uninstallation self.__setitem__(plugin, "R") elif change == "A": # any other installation self.__setitem__(plugin, "A") elif change == "D" and self.get(plugin) == "A": # uninstallation right after installation self.pop(plugin) elif change == "D": # any other uninstallation self.__setitem__(plugin, "D") elif change == "R" and self.get(plugin) == "A": # reinstallation right after installation self.__setitem__(plugin, "A") elif change == "R": # any other reinstallation self.__setitem__(plugin, "R") # ----------------------------------------- # def toList(self, change): """ return a list of plugins matching the given change """ result = [] for i in self.items(): if i[1] == change: result += [i[0]] return result # --- /class History ---------------------------------------------------------------------- # # --- class QPHttp ----------------------------------------------------------------------- # # --- It's a temporary workaround for broken proxy handling in Qt ------------------------- # class QPHttp(QHttp): def __init__(self,*args): QHttp.__init__(self,*args) settings = QSettings() settings.beginGroup("proxy") if settings.value("/proxyEnabled").toBool(): self.proxy=QNetworkProxy() proxyType = settings.value( "/proxyType", QVariant(0)).toString() if len(args)>0 and settings.value("/proxyExcludedUrls").toString().contains(args[0]): proxyType = "NoProxy" if proxyType in ["1","Socks5Proxy"]: self.proxy.setType(QNetworkProxy.Socks5Proxy) elif proxyType in ["2","NoProxy"]: self.proxy.setType(QNetworkProxy.NoProxy) elif proxyType in ["3","HttpProxy"]: self.proxy.setType(QNetworkProxy.HttpProxy) elif proxyType in ["4","HttpCachingProxy"] and QT_VERSION >= 0X040400: self.proxy.setType(QNetworkProxy.HttpCachingProxy) elif proxyType in ["5","FtpCachingProxy"] and QT_VERSION >= 0X040400: self.proxy.setType(QNetworkProxy.FtpCachingProxy) else: self.proxy.setType(QNetworkProxy.DefaultProxy) self.proxy.setHostName(settings.value("/proxyHost").toString()) self.proxy.setPort(settings.value("/proxyPort").toUInt()[0]) self.proxy.setUser(settings.value("/proxyUser").toString()) self.proxy.setPassword(settings.value("/proxyPassword").toString()) self.setProxy(self.proxy) settings.endGroup() return None # --- /class QPHttp ---------------------------------------------------------------------- # # --- class Relay ----------------------------------------------------------------------- # class Relay(QObject): """ Relay object for transmitting signals from QPHttp with adding the repoName information """ # ----------------------------------------- # def __init__(self, key): QObject.__init__(self) self.key = key def stateChanged(self, state): self.emit(SIGNAL("anythingChanged(QString, int, int)"), self.key, state, 0) # ----------------------------------------- # def dataReadProgress(self, done, total): state = 4 if total: progress = int(float(done)/float(total)*100) else: progress = 0 self.emit(SIGNAL("anythingChanged(QString, int, int)"), self.key, state, progress) # --- /class Relay ---------------------------------------------------------------------- # # --- class Repositories ----------------------------------------------------------------- # class Repositories(QObject): """ A dict-like class for handling repositories data """ # ----------------------------------------- # def __init__(self): QObject.__init__(self) self.mRepositories = {} self.httpId = {} # {httpId : repoName} # ----------------------------------------- # def addKnownRepos(self): """ add known 3rd party repositories to QSettings """ presentURLs = [] for i in self.all().values(): presentURLs += [QString(i["url"])] settings = QSettings() settings.beginGroup(reposGroup) # add the central repositories if presentURLs.count(officialRepo[1]) == 0: settings.setValue(officialRepo[0]+"/url", QVariant(officialRepo[1])) settings.setValue(officialRepo[0]+"/enabled", QVariant(True)) if presentURLs.count(contribRepo[1]) == 0: settings.setValue(contribRepo[0]+"/url", QVariant(contribRepo[1])) settings.setValue(contribRepo[0]+"/enabled", QVariant(True)) # add author repositories for i in authorRepos: if i[1] and presentURLs.count(i[1]) == 0: repoName = QString(i[0]) if self.all().has_key(repoName): repoName = repoName + " (original)" settings.setValue(repoName+"/url", QVariant(i[1])) settings.setValue(repoName+"/enabled", QVariant(True)) # ----------------------------------------- # def all(self): """ return dict of all repositories """ return self.mRepositories # ----------------------------------------- # def allEnabled(self): """ return dict of all enabled and valid repositories """ repos = {} for i in self.mRepositories: if self.mRepositories[i]["enabled"] and self.mRepositories[i]["valid"]: repos[i] = self.mRepositories[i] return repos # ----------------------------------------- # def allUnavailable(self): """ return dict of all unavailable repositories """ repos = {} for i in self.mRepositories: if self.mRepositories[i]["enabled"] and self.mRepositories[i]["valid"] and self.mRepositories[i]["state"] == 3: repos[i] = self.mRepositories[i] return repos # ----------------------------------------- # def setRepositoryData(self, reposName, key, value): """ write data to the mRepositories dict """ self.mRepositories[reposName][key] = value # ----------------------------------------- # def remove(self, reposName): """ remove given item from the mRepositories dict """ del self.mRepositories[reposName] # ----------------------------------------- # def rename(self, oldName, newName): """ rename repository key """ if oldName == newName: return self.mRepositories[newName] = self.mRepositories[oldName] del self.mRepositories[oldName] # ----------------------------------------- # def checkingOnStart(self): """ return true if checking for news and updates is enabled """ settings = QSettings() return settings.value(settingsGroup+"/checkOnStart", QVariant(False)).toBool() # ----------------------------------------- # def setCheckingOnStart(self, state): """ set state of checking for news and updates """ settings = QSettings() settings.setValue(settingsGroup+"/checkOnStart", QVariant(state)) # ----------------------------------------- # def checkingOnStartInterval(self): """ return checking for news and updates interval """ settings = QSettings() (i, ok) = settings.value(settingsGroup+"/checkOnStartInterval").toInt() if i < 0 or not ok: i = 1 # allowed values: 0,1,3,7,14,30 days interval = 0 for j in [1,3,7,14,30]: if i >= j: interval = j return interval # ----------------------------------------- # def setCheckingOnStartInterval(self, interval): """ set checking for news and updates interval """ settings = QSettings() settings.setValue(settingsGroup+"/checkOnStartInterval", QVariant(interval)) # ----------------------------------------- # def saveCheckingOnStartLastDate(self): """ set today's date as the day of last checking """ settings = QSettings() settings.setValue(settingsGroup+"/checkOnStartLastDate", QVariant(QDate.currentDate())) # ----------------------------------------- # def timeForChecking(self): """ determine whether it's the time for checking for news and updates now """ if self.checkingOnStartInterval() == 0: return True settings = QSettings() interval = settings.value(settingsGroup+"/checkOnStartLastDate").toDate().daysTo(QDate.currentDate()) if interval >= self.checkingOnStartInterval(): return True else: return False # ----------------------------------------- # def load(self): """ populate the mRepositories dict""" self.mRepositories = {} settings = QSettings() settings.beginGroup(reposGroup) # first, update repositories in QSettings if needed officialRepoPresent = False for key in settings.childGroups(): url = settings.value(key+"/url", QVariant()).toString() if url == contribRepo[1]: settings.setValue(key+"/valid", QVariant(True)) # unlock the contrib repo in qgis 1.x else: settings.setValue(key+"/valid", QVariant(True)) # unlock any other repo if url == officialRepo[1]: officialRepoPresent = True for authorRepo in authorRepos: if url == authorRepo[2]: settings.setValue(key+"/url", QVariant(authorRepo[1])) # correct a depreciated url if not officialRepoPresent: settings.setValue(officialRepo[0]+"/url", QVariant(officialRepo[1])) for key in settings.childGroups(): self.mRepositories[key] = {} self.mRepositories[key]["url"] = settings.value(key+"/url", QVariant()).toString() self.mRepositories[key]["enabled"] = settings.value(key+"/enabled", QVariant(True)).toBool() self.mRepositories[key]["valid"] = settings.value(key+"/valid", QVariant(True)).toBool() self.mRepositories[key]["QPHttp"] = QPHttp() self.mRepositories[key]["Relay"] = Relay(key) self.mRepositories[key]["xmlData"] = QBuffer() self.mRepositories[key]["state"] = 0 self.mRepositories[key]["error"] = QString() settings.endGroup() # ----------------------------------------- # def requestFetching(self,key): """ start fetching the repository given by key """ self.mRepositories[key]["state"] = 1 url = QUrl(self.mRepositories[key]["url"]) path = QString(url.toPercentEncoding(url.path(), "!$&'()*+,;=:@/")) port = url.port() if port < 0: port = 80 self.mRepositories[key]["QPHttp"] = QPHttp(url.host(), port) self.connect(self.mRepositories[key]["QPHttp"], SIGNAL("requestFinished (int, bool)"), self.xmlDownloaded) self.connect(self.mRepositories[key]["QPHttp"], SIGNAL("stateChanged ( int )"), self.mRepositories[key]["Relay"].stateChanged) self.connect(self.mRepositories[key]["QPHttp"], SIGNAL("dataReadProgress ( int , int )"), self.mRepositories[key]["Relay"].dataReadProgress) self.connect(self.mRepositories[key]["Relay"], SIGNAL("anythingChanged(QString, int, int)"), self, SIGNAL("anythingChanged (QString, int, int)")) i = self.mRepositories[key]["QPHttp"].get(path, self.mRepositories[key]["xmlData"]) self.httpId[i] = key # ----------------------------------------- # def fetchingInProgress(self): """ return true if fetching repositories is still in progress """ for key in self.mRepositories: if self.mRepositories[key]["state"] == 1: return True return False # ----------------------------------------- # def killConnection(self, key): """ kill the fetching on demand """ if self.mRepositories[key]["QPHttp"].state(): self.mRepositories[key]["QPHttp"].abort() # ----------------------------------------- # def xmlDownloaded(self,nr,state): """ populate the plugins object with the fetched data """ if not self.httpId.has_key(nr): return reposName = self.httpId[nr] if state: # fetching failed self.mRepositories[reposName]["state"] = 3 self.mRepositories[reposName]["error"] = self.mRepositories[reposName]["QPHttp"].errorString() else: repoData = self.mRepositories[reposName]["xmlData"] reposXML = QDomDocument() reposXML.setContent(repoData.data()) pluginNodes = reposXML.elementsByTagName("pyqgis_plugin") if pluginNodes.size(): for i in range(pluginNodes.size()): fileName = pluginNodes.item(i).firstChildElement("file_name").text().simplified() if not fileName: fileName = QFileInfo(pluginNodes.item(i).firstChildElement("download_url").text().trimmed().split("?")[0]).fileName() name = fileName.section(".", 0, 0) name = unicode(name) experimental = False if pluginNodes.item(i).firstChildElement("experimental").text().simplified().toUpper() in ["TRUE","YES"]: experimental = True plugin = { "name" : pluginNodes.item(i).toElement().attribute("name"), "version_avail" : pluginNodes.item(i).toElement().attribute("version"), "desc_repo" : pluginNodes.item(i).firstChildElement("description").text().simplified(), "desc_local" : "", "author" : pluginNodes.item(i).firstChildElement("author_name").text().simplified(), "homepage" : pluginNodes.item(i).firstChildElement("homepage").text().simplified(), "url" : pluginNodes.item(i).firstChildElement("download_url").text().simplified(), "experimental" : experimental, "filename" : fileName, "status" : "not installed", "error" : "", "error_details" : "", "version_inst" : "", "repository" : reposName, "localdir" : name, "read-only" : False} qgisMinimumVersion = pluginNodes.item(i).firstChildElement("qgis_minimum_version").text().simplified() if not qgisMinimumVersion: qgisMinimumVersion = "0" # please use the tag below only if really needed! (for example if plugin development is abandoned) qgisMaximumVersion = pluginNodes.item(i).firstChildElement("qgis_maximum_version").text().simplified() if not qgisMaximumVersion: qgisMaximumVersion = "2" #if compatible, add the plugin to the list if not pluginNodes.item(i).firstChildElement("disabled").text().simplified().toUpper() in ["TRUE","YES"]: if compareVersions(QGIS_VER, qgisMinimumVersion) < 2 and compareVersions(qgisMaximumVersion, QGIS_VER) < 2: if QGIS_VER[0]==qgisMinimumVersion[0] or (qgisMinimumVersion!="0" and qgisMaximumVersion!="2"): # to be deleted #add the plugin to the cache plugins.addFromRepository(plugin) self.mRepositories[reposName]["state"] = 2 else: #print "Repository parsing error" self.mRepositories[reposName]["state"] = 3 self.mRepositories[reposName]["error"] = QCoreApplication.translate("QgsPluginInstaller","Couldn't parse output from the repository") self.emit(SIGNAL("repositoryFetched(QString)"), reposName ) # is the checking done? if not self.fetchingInProgress(): plugins.rebuild() self.saveCheckingOnStartLastDate() self.emit(SIGNAL("checkingDone()")) # --- /class Repositories ---------------------------------------------------------------- # # --- class Plugins ---------------------------------------------------------------------- # class Plugins(QObject): """ A dict-like class for handling plugins data """ # ----------------------------------------- # def __init__(self): QObject.__init__(self) self.mPlugins = {} # the dict of plugins (dicts) self.repoCache = {} # the dict of lists of plugins (dicts) self.localCache = {} # the dict of plugins (dicts) self.obsoletePlugins = [] # the list of outdated 'user' plugins masking newer 'system' ones # ----------------------------------------- # def all(self): """ return all plugins """ return self.mPlugins # ----------------------------------------- # def keyByUrl(self, name): """ return plugin key by given url """ plugins = [i for i in self.mPlugins if self.mPlugins[i]["url"] == name] if plugins: return plugins[0] return None # ----------------------------------------- # def addInstalled(self, plugin): """ add given plugin to the localCache """ key = plugin["localdir"] self.localCache[key] = plugin # ----------------------------------------- # def addFromRepository(self, plugin): """ add given plugin to the repoCache """ repo = plugin["repository"] try: self.repoCache[repo] += [plugin] except: self.repoCache[repo] = [plugin] # ----------------------------------------- # def removeInstalledPlugin(self, key): """ remove given plugin from the localCache """ if self.localCache.has_key(key): del self.localCache[key] # ----------------------------------------- # def removeRepository(self, repo): """ remove whole repository from the repoCache """ if self.repoCache.has_key(repo): del self.repoCache[repo] # ----------------------------------------- # def getInstalledPlugin(self, key, readOnly): """ get the metadata of an installed plugin """ if readOnly: path = QgsApplication.pkgDataPath() else: path = QgsApplication.qgisSettingsDirPath() path = QDir.cleanPath(path) + "/python/plugins/" + key if not QDir(path).exists(): return nam = "" ver = "" desc = "" auth = "" homepage = "" error = "" errorDetails = "" try: exec("import %s" % key) exec("reload (%s)" % key) try: exec("nam = %s.name()" % key) except: pass try: exec("ver = %s.version()" % key) except: pass try: exec("desc = %s.description()" % key) except: pass try: exec("auth = %s.authorName()" % key) except: pass try: exec("homepage = %s.homepage()" % key) except: pass try: exec("qgisMinimumVersion = %s.qgisMinimumVersion()" % key) if compareVersions(QGIS_VER, qgisMinimumVersion) == 2: error = "incompatible" errorDetails = qgisMinimumVersion except: pass try: exec ("%s.classFactory(iface)" % key) except Exception, error: error = unicode(error.args[0]) except Exception, error: error = unicode(error.args[0]) if not nam: nam = key if error[:16] == "No module named ": mona = error.replace("No module named ","") if mona != key: error = "dependent" errorDetails = mona if not error in ["", "dependent", "incompatible"]: errorDetails = error error = "broken" plugin = { "name" : nam, "version_inst" : normalizeVersion(ver), "version_avail" : "", "desc_local" : desc, "desc_repo" : "", "author" : auth, "homepage" : homepage, "url" : path, "experimental" : False, "filename" : "", "status" : "orphan", "error" : error, "error_details" : errorDetails, "repository" : "", "localdir" : key, "read-only" : readOnly} return plugin # ----------------------------------------- # def getAllInstalled(self): """ Build the localCache """ self.localCache = {} # first, try to add the read-only plugins... pluginsPath = unicode(QDir.convertSeparators(QDir.cleanPath(QgsApplication.pkgDataPath() + "/python/plugins"))) # temporarily add the system path as the first element to force loading the read-only plugins, even if masked by user ones. sys.path = [pluginsPath] + sys.path try: pluginDir = QDir(pluginsPath) pluginDir.setFilter(QDir.AllDirs) for key in pluginDir.entryList(): key = unicode(key) if not key in [".",".."]: self.localCache[key] = self.getInstalledPlugin(key, True) except: # return QCoreApplication.translate("QgsPluginInstaller","Couldn't open the system plugin directory") pass # it's not necessary to stop due to this error # remove the temporarily added path sys.path.remove(pluginsPath) # ...then try to add locally installed ones try: pluginDir = QDir.convertSeparators(QDir.cleanPath(QgsApplication.qgisSettingsDirPath() + "/python/plugins")) pluginDir = QDir(pluginDir) pluginDir.setFilter(QDir.AllDirs) except: return QCoreApplication.translate("QgsPluginInstaller","Couldn't open the local plugin directory") for key in pluginDir.entryList(): key = unicode(key) if not key in [".",".."]: plugin = self.getInstalledPlugin(key, False) if key in self.localCache.keys() and compareVersions(self.localCache[key]["version_inst"],plugin["version_inst"]) == 1: # An obsolete plugin in the "user" location is masking a newer one in the "system" location! self.obsoletePlugins += [key] self.localCache[key] = plugin # ----------------------------------------- # def rebuild(self): """ build or rebuild the mPlugins from the caches """ self.mPlugins = {} for i in self.localCache.keys(): self.mPlugins[i] = self.localCache[i].copy() settings = QSettings() (allowed, ok) = settings.value(settingsGroup+"/allowedPluginType", QVariant(2)).toInt() for i in self.repoCache.values(): for plugin in i: key = plugin["localdir"] # check if the plugin is allowed and if there isn't any better one added already. if (allowed != 1 or plugin["repository"] == officialRepo[0]) and (allowed == 3 or not plugin["experimental"]) \ and not (self.mPlugins.has_key(key) and self.mPlugins[key]["version_avail"] and compareVersions(self.mPlugins[key]["version_avail"], plugin["version_avail"]) < 2): # The mPlugins doct contains now locally installed plugins. # Now, add the available one if not present yet or update it if present already. if not self.mPlugins.has_key(key): self.mPlugins[key] = plugin # just add a new plugin else: self.mPlugins[key]["version_avail"] = plugin["version_avail"] self.mPlugins[key]["desc_repo"] = plugin["desc_repo"] self.mPlugins[key]["filename"] = plugin["filename"] self.mPlugins[key]["repository"] = plugin["repository"] self.mPlugins[key]["experimental"] = plugin["experimental"] # use remote name if local one is not available if self.mPlugins[key]["name"] == key and plugin["name"]: self.mPlugins[key]["name"] = plugin["name"] # those metadata has higher priority for their remote instances: if plugin["author"]: self.mPlugins[key]["author"] = plugin["author"] if plugin["homepage"]: self.mPlugins[key]["homepage"] = plugin["homepage"] if plugin["url"]: self.mPlugins[key]["url"] = plugin["url"] # set status # # installed available status # --------------------------------------- # none any "not installed" (will be later checked if is "new") # any none "orphan" # same same "installed" # less greater "upgradeable" # greater less "newer" if not self.mPlugins[key]["version_avail"]: self.mPlugins[key]["status"] = "orphan" elif self.mPlugins[key]["error"] in ["broken","dependent"]: self.mPlugins[key]["status"] = "installed" elif not self.mPlugins[key]["version_inst"]: self.mPlugins[key]["status"] = "not installed" elif compareVersions(self.mPlugins[key]["version_avail"],self.mPlugins[key]["version_inst"]) == 0: self.mPlugins[key]["status"] = "installed" elif compareVersions(self.mPlugins[key]["version_avail"],self.mPlugins[key]["version_inst"]) == 1: self.mPlugins[key]["status"] = "upgradeable" else: self.mPlugins[key]["status"] = "newer" self.markNews() # ----------------------------------------- # def markNews(self): """ mark all new plugins as new """ settings = QSettings() seenPlugins = settings.value(seenPluginGroup, QVariant(QStringList(self.mPlugins.keys()))).toStringList() if len(seenPlugins) > 0: for i in self.mPlugins.keys(): if seenPlugins.count(QString(i)) == 0 and self.mPlugins[i]["status"] == "not installed": self.mPlugins[i]["status"] = "new" # ----------------------------------------- # def updateSeenPluginsList(self): """ update the list of all seen plugins """ settings = QSettings() seenPlugins = settings.value(seenPluginGroup, QVariant(QStringList(self.mPlugins.keys()))).toStringList() for i in self.mPlugins.keys(): if seenPlugins.count(QString(i)) == 0: seenPlugins += [i] settings.setValue(seenPluginGroup, QVariant(QStringList(seenPlugins))) # ----------------------------------------- # def isThereAnythingNew(self): """ return true if an upgradeable or new plugin detected """ for i in self.mPlugins.values(): if i["status"] in ["upgradeable","new"]: return True return False # --- /class Plugins --------------------------------------------------------------------- # # public members: history = History() repositories = Repositories() plugins = Plugins()
gpl-2.0
mayankTUM/ScalesIDP
extensions/SemanticMediaWiki/tests/phpunit/SpecialPageTestCase.php
2636
<?php namespace SMW\Test; use RequestContext; use Language; use SpecialPage; use FauxRequest; use WebRequest; use OutputPage; /** * @ingroup Test * * @group SMW * @group SMWExtension * @group medium * * @licence GNU GPL v2+ * @since 1.9.0.2 * * @author mwjames */ abstract class SpecialPageTestCase extends \PHPUnit_Framework_TestCase { protected $obLevel; protected function setUp() { parent::setUp(); $this->obLevel = ob_get_level(); } protected function tearDown() { $obLevel = ob_get_level(); while ( ob_get_level() > $this->obLevel ) { ob_end_clean(); } parent::tearDown(); } /** * @return SpecialPage */ protected abstract function getInstance(); /** * Borrowed from \Wikibase\Test\SpecialPageTestBase * * @param string $sub The subpage parameter to call the page with * @param WebRequest $request Web request that may contain URL parameters, etc */ protected function execute( $sub = '', WebRequest $request = null, $user = null ) { $request = $request === null ? new FauxRequest() : $request; $response = $request->response(); $page = $this->getInstance(); $page->setContext( $this->makeRequestContext( $request, $user, $this->getTitle( $page ) ) ); $out = $page->getOutput(); ob_start(); $page->execute( $sub ); if ( $out->getRedirect() !== '' ) { $out->output(); $text = ob_get_contents(); } elseif ( $out->isDisabled() ) { $text = ob_get_contents(); } else { $text = $out->getHTML(); } ob_end_clean(); $code = $response->getStatusCode(); if ( $code > 0 ) { $response->header( "Status: " . $code . ' ' . \HttpStatus::getMessage( $code ) ); } $this->text = $text; $this->response = $response; } /** * @return string */ protected function getText() { return $this->text; } /** * @return FauxResponse */ protected function getResponse() { return $this->response; } /** * @return RequestContext */ private function makeRequestContext( WebRequest $request, $user, $title ) { $context = new RequestContext(); $context->setRequest( $request ); $out = new OutputPage( $context ); $out->setTitle( $title ); $context->setOutput( $out ); $context->setLanguage( Language::factory( 'en' ) ); $user = $user === null ? new MockSuperUser() : $user; $context->setUser( $user ); return $context; } /** * Deprecated: Use of SpecialPage::getTitle was deprecated in MediaWiki 1.23 * * @return Title */ private function getTitle( SpecialPage $page ) { return method_exists( $page, 'getPageTitle') ? $page->getPageTitle() : $page->getTitle(); } }
gpl-2.0
futurice/vdsm
tests/netmodelsTests.py
6346
# # Copyright (C) 2013, IBM Corporation # Copyright (C) 2013-2014, Red Hat, Inc. # # 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 # # Refer to the README and COPYING files for full details of the license # import os from vdsm import netinfo from network import errors from network.models import Bond, Bridge, IPv4, Nic, Vlan from network.models import _nicSort from testrunner import VdsmTestCase as TestCaseBase from testValidation import ValidateRunningAsRoot from nose.plugins.skip import SkipTest from monkeypatch import MonkeyPatch class TestNetmodels(TestCaseBase): def testIsVlanIdValid(self): vlanIds = ('badValue', Vlan.MAX_ID + 1) for vlanId in vlanIds: with self.assertRaises(errors.ConfigNetworkError) as cneContext: Vlan.validateTag(vlanId) self.assertEqual(cneContext.exception.errCode, errors.ERR_BAD_VLAN) self.assertEqual(Vlan.validateTag(0), None) self.assertEqual(Vlan.validateTag(Vlan.MAX_ID), None) def testIsBridgeNameValid(self): invalidBrName = ('', '-abc', 'abcdefghijklmnop', 'a:b', 'a.b') for i in invalidBrName: with self.assertRaises(errors.ConfigNetworkError) as cneContext: Bridge.validateName(i) self.assertEqual(cneContext.exception.errCode, errors.ERR_BAD_BRIDGE) def testIsNicValid(self): invalidNicName = ('toni', 'livnat', 'dan') class FakeNetInfo(object): def __init__(self): self.nics = ['eth0', 'eth1'] for nic in invalidNicName: with self.assertRaises(errors.ConfigNetworkError) as cneContext: Nic(nic, None, _netinfo=FakeNetInfo()) self.assertEqual(cneContext.exception.errCode, errors.ERR_BAD_NIC) def testIsBondingNameValid(self): bondNames = ('badValue', ' bond14', 'bond14 ', 'bond14a', 'bond0 0') for bondName in bondNames: with self.assertRaises(errors.ConfigNetworkError) as cneContext: Bond.validateName(bondName) self.assertEqual(cneContext.exception.errCode, errors.ERR_BAD_BONDING) self.assertEqual(Bond.validateName('bond11'), None) self.assertEqual(Bond.validateName('bond11128421982'), None) @ValidateRunningAsRoot def testValidateBondingOptions(self): if not os.path.exists(netinfo.BONDING_MASTERS): raise SkipTest("bonding kernel module could not be found.") opts = 'mode=802.3ad miimon=150' badOpts = 'foo=bar badopt=one' with self.assertRaises(errors.ConfigNetworkError) as cne: Bond.validateOptions('bond0', badOpts) self.assertEqual(cne.exception.errCode, errors.ERR_BAD_BONDING) self.assertEqual(Bond.validateOptions('bond0', opts), None) def testIsIpValid(self): addresses = ('10.18.1.254', '10.50.25.177', '250.0.0.1', '20.20.25.25') badAddresses = ('192.168.1.256', '10.50.25.1777', '256.0.0.1', '20.20.25.25.25') for address in badAddresses: with self.assertRaises(errors.ConfigNetworkError) as cneContext: IPv4.validateAddress(address) self.assertEqual(cneContext.exception.errCode, errors.ERR_BAD_ADDR) for address in addresses: self.assertEqual(IPv4.validateAddress(address), None) def testIsNetmaskValid(self): masks = ('254.0.0.0', '255.255.255.0', '255.255.255.128', '255.255.255.224') badMasks = ('192.168.1.0', '10.50.25.17', '255.0.255.0', '253.0.0.0') for mask in badMasks: with self.assertRaises(errors.ConfigNetworkError) as cneContext: IPv4.validateNetmask(mask) self.assertEqual(cneContext.exception.errCode, errors.ERR_BAD_ADDR) for mask in masks: self.assertEqual(IPv4.validateNetmask(mask), None) @MonkeyPatch(netinfo, 'getMtu', lambda *x: 1500) @MonkeyPatch(Bond, 'validateOptions', lambda *x: 0) def testTextualRepr(self): _netinfo = {'networks': {}, 'vlans': {}, 'nics': ['testnic1', 'testnic2'], 'bondings': {}, 'bridges': {}} fakeInfo = netinfo.NetInfo(_netinfo) nic1 = Nic('testnic1', None, _netinfo=fakeInfo) nic2 = Nic('testnic2', None, _netinfo=fakeInfo) bond1 = Bond('bond42', None, slaves=(nic1, nic2)) vlan1 = Vlan(bond1, '4', None) bridge1 = Bridge('testbridge', None, port=vlan1) self.assertEqual('%r' % bridge1, 'Bridge(testbridge: Vlan(bond42.4: ' 'Bond(bond42: (Nic(testnic1), Nic(testnic2)))))') def testNicSort(self): nics = {'nics_init': ('p33p1', 'eth1', 'lan0', 'em0', 'p331', 'Lan1', 'eth0', 'em1', 'p33p2', 'p33p10'), 'nics_expected': ('Lan1', 'em0', 'em1', 'eth0', 'eth1', 'lan0', 'p33p1', 'p33p10', 'p33p2', 'p331')} nics_res = _nicSort(nics['nics_init']) self.assertEqual(nics['nics_expected'], tuple(nics_res)) def testBondReorderOptions(self): empty = Bond._reorderOptions('') self.assertEqual(empty, '') modeless = Bond._reorderOptions('miimon=250') self.assertEqual(modeless, 'miimon=250') ordered = Bond._reorderOptions('mode=4 miimon=250') self.assertEqual(ordered, 'mode=4 miimon=250') inverted = Bond._reorderOptions('miimon=250 mode=4') self.assertEqual(inverted, 'mode=4 miimon=250')
gpl-2.0
oat-sa/extension-tao-proctoring
test/unit/model/ActivityMonitoringServiceTest.php
2613
<?php /** * 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; under version 2 * of the License (non-upgradable). * * 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. * * Copyright (c) 2017 (original work) Open Assessment Technologies SA; * * */ namespace oat\taoProctoring\test\unit\model; use oat\generis\test\TestCase; use oat\taoProctoring\model\ActivityMonitoringService; /** * Class ActivityMonitoringServiceTest * @package oat\taoProctoring\test\model * @author Aleh Hutnikau, <hutnikau@1pt.com> */ class ActivityMonitoringServiceTest extends TestCase { public function testGetTimeKeys() { $date = new \DateTime('now', new \DateTimeZone('UTC')); $service = new ActivityMonitoringService(); $timeKeys = $service->getTimeKeys(new \DateInterval('PT1M'), clone($date)); $this->assertEquals(60, count($timeKeys)); $this->assertEquals(((int)$date->format('i') + 1) % 60, (int)$timeKeys[0]->format('i')); $this->assertEquals(0, $timeKeys[0]->format('s')); $timeKeys = $service->getTimeKeys(new \DateInterval('PT1H'), clone($date)); $this->assertEquals(24, count($timeKeys)); $this->assertEquals(((int)$date->format('H') + 1) % 24, (int)$timeKeys[0]->format('H')); $this->assertEquals(0, $timeKeys[0]->format('i')); $timeKeys = $service->getTimeKeys(new \DateInterval('P1D'), clone($date)); $tomorrow = (new \DateTime('now', new \DateTimeZone('UTC')))->add(new \DateInterval('P1D')); $this->assertEquals($tomorrow->format('t'), count($timeKeys)); $this->assertEquals($tomorrow->format('d'), $timeKeys[0]->format('d')); $this->assertEquals('00', $timeKeys[0]->format('H')); $timeKeys = $service->getTimeKeys(new \DateInterval('P1M'), clone($date)); $this->assertEquals(12, count($timeKeys)); $this->assertEquals((int)$date->format('m') % 12 + 1, (int)$timeKeys[0]->format('m')); $this->assertEquals(0, $timeKeys[0]->format('H')); $this->assertEquals('01', $timeKeys[0]->format('d')); } }
gpl-2.0
bruno-barros/weloquent-starter-theme
app/views/partials/header.blade.php
1488
<header id="header"> <div class="container"> <div class="row"> <div class="col-sm-4"> <a href="{{ get_home_url() }}" class="brand" title="w.eloquent"> <img src="{{ assets('img/weloquent-o.svg') }}" alt="w.eloquent" class="img-responsive"/> </a> </div> <div class="col-sm-8"></div> </div> </div> <nav class="navbar" role="navigation"> <div class="container"> <div class="row"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> {{ Menu::render('primary') }} </div> <!-- /.navbar-collapse --> </div> <!-- /.row --> </div> <!-- /.container-fluid --> </nav> </header>
gpl-2.0
emundus/v6
components/com_hikamarket/views/ordermarket/tmpl/edit_additional.php
10663
<?php /** * @package HikaMarket for Joomla! * @version 4.0.0 * @author Obsidev S.A.R.L. * @copyright (C) 2011-2021 OBSIDEV. All rights reserved. * @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html */ defined('_JEXEC') or die('Restricted access'); ?><form action="<?php echo hikamarket::completeLink('order&task=save&subtask=additional&tmpl=component'); ?>" name="hikamarket_order_additional_form" id="hikamarket_order_additional_form" method="post" enctype="multipart/form-data"> <dl class="hikam_options"> <dt class="hikamarket_order_additional_subtotal"><label><?php echo JText::_('SUBTOTAL'); ?></label></dt> <dd class="hikamarket_order_additional_subtotal"><span><?php echo $this->currencyHelper->format($this->order->order_subtotal,$this->order->order_currency_id); ?></span></dd> <?php if(isset($this->edit) && $this->edit === true && hikamarket::acl('order/edit/coupon')) { ?> <dt class="hikamarket_order_additional_coupon"><label><?php echo JText::_('HIKASHOP_COUPON'); ?></label></dt> <dd class="hikamarket_order_additional_coupon"> <input type="text" name="data[order][order_discount_code]" value="<?php echo $this->escape(@$this->order->order_discount_code); ?>" /><br/> <input type="text" name="data[order][order_discount_price]" value="<?php echo @$this->order->order_discount_price; ?>" /><br/> <input type="text" name="data[order][order_discount_tax]" value="<?php echo @$this->order->order_discount_tax; ?>" /> <?php echo $this->ratesType->display( "data[order][order_discount_tax_namekey]" , @$this->order->order_discount_tax_namekey ); ?> </dd> <?php } else { ?> <dt class="hikamarket_order_additional_coupon"><label><?php echo JText::_('HIKASHOP_COUPON'); ?></label></dt> <dd class="hikamarket_order_additional_coupon"><span><?php echo $this->currencyHelper->format($this->order->order_discount_price*-1.0,$this->order->order_currency_id); ?> <?php echo $this->order->order_discount_code; ?></span></dd> <?php } if(isset($this->edit) && $this->edit === true && hikamarket::acl('order/edit/shipping')) { ?> <dt class="hikamarket_order_additional_shipping"><label><?php echo JText::_('SHIPPING'); ?></label></dt> <dd class="hikamarket_order_additional_shipping"> <?php if(strpos($this->order->order_shipping_id, ';') === false) { ?> <?php echo $this->shippingPlugins->display('data[order][shipping]',$this->order->order_shipping_method,$this->order->order_shipping_id); ?><br/> <?php } ?> <input type="text" name="data[order][order_shipping_price]" value="<?php echo $this->order->order_shipping_price; ?>" /><br/> <input type="text" name="data[order][order_shipping_tax]" value="<?php echo @$this->order->order_shipping_tax; ?>" /> <?php echo $this->ratesType->display( "data[order][order_shipping_tax_namekey]" , @$this->order->order_shipping_tax_namekey ); ?><br/> <?php if(strpos($this->order->order_shipping_id, ';') !== false) { ?> <table class="hikam_table table table-striped"> <thead> <tr> <th><?php echo JText::_('WAREHOUSE'); ?></th> <th><?php echo JText::_('HIKASHOP_SHIPPING_METHOD'); ?></th> <th><?php echo JText::_('PRICE'); ?></th> <th><?php echo JText::_('SHIPPING_TAX'); ?></th> </tr> </thead> <tbody> <?php $warehouses = array( JHTML::_('select.option', 0, JText::_('HIKA_NONE')) ); $shipping_ids = explode(';', $this->order->order_shipping_id); foreach($shipping_ids as $shipping_key) { $shipping_warehouse = 0; if(strpos($shipping_key, '@') !== false) list($shipping_id, $shipping_warehouse) = explode('@', $shipping_key, 2); else $shipping_id = (int)$shipping_key; $warehouses[] = JHTML::_('select.option', $shipping_warehouse, $shipping_warehouse); $shipping_method = ''; foreach($this->order->shippings as $s) { if((int)$s->shipping_id == $shipping_id) { $shipping_method = $s->shipping_type; break; } } $k = $shipping_id.'_'.$shipping_warehouse; $prices = @$this->order->order_shipping_params->prices[$shipping_key]; ?> <tr> <td><?php echo $shipping_warehouse; ?></td> <td><?php echo $this->shippingPlugins->display('data[order][shipping]['.$shipping_warehouse.']', $shipping_method,$shipping_id, true, ' style="max-width:160px;"'); ?></td> <td><input type="text" name="data[order][order_shipping_prices][<?php echo $shipping_warehouse; ?>]" value="<?php echo @$prices->price_with_tax; ?>" /></td> <td><input type="text" name="data[order][order_shipping_taxs][<?php echo $shipping_warehouse; ?>]" value="<?php echo @$prices->tax; ?>" /></td> </tr> <?php } ?> </tbody> </table> <table class="hikam_table table table-striped"> <thead> <tr> <th><?php echo JText::_('PRODUCT'); ?></th> <th><?php echo JText::_('WAREHOUSE'); ?></th> </tr> </thead> <tbody> <?php foreach($this->order->products as $k => $product) { $map = 'data[order][warehouses]['.$product->order_product_id.']'; $value = 0; if(strpos($product->order_product_shipping_id, '@') !== false) $value = substr($product->order_product_shipping_id, strpos($product->order_product_shipping_id, '@')+1); ?> <tr> <td><?php echo $product->order_product_name; ?></td> <td><?php echo JHTML::_('select.genericlist', $warehouses, $map, 'class="inputbox"', 'value', 'text', $value); ?></td> </tr> <?php } ?> </tbody> </table> <?php } ?> </dd> <?php } else { ?> <dt class="hikamarket_order_additional_shipping"><label><?php echo JText::_('SHIPPING'); ?></label></dt> <dd class="hikamarket_order_additional_shipping"><span><?php echo $this->currencyHelper->format($this->order->order_shipping_price, $this->order->order_currency_id); ?> - <?php if(empty($this->order->order_shipping_method)) echo '<em>'.JText::_('NONE').'</em>'; else echo $this->order->order_shipping_method; ?></span></dd> <?php } if(isset($this->edit) && $this->edit === true && hikamarket::acl('order/edit/payment')) { ?> <dt class="hikamarket_order_additional_payment"><label><?php echo JText::_('HIKASHOP_PAYMENT'); ?></label></dt> <dd class="hikamarket_order_additional_payment"> <?php echo $this->paymentPlugins->display('data[order][payment]',$this->order->order_payment_method,$this->order->order_payment_id); ?><br/> <input type="text" name="data[order][order_payment_price]" value="<?php echo $this->order->order_payment_price; ?>" /><br/> <input type="text" name="data[order][order_payment_tax]" value="<?php echo @$this->order->order_payment_tax; ?>" /> <?php echo $this->ratesType->display( "data[order][order_payment_tax_namekey]" , @$this->order->order_payment_tax_namekey); ?> </dd> <?php } else { ?> <dt class="hikamarket_order_additional_payment_fee"><label><?php echo JText::_('HIKASHOP_PAYMENT'); ?></label></dt> <dd class="hikamarket_order_additional_payment_fee"><span><?php echo $this->currencyHelper->format($this->order->order_payment_price, $this->order->order_currency_id); ?> - <?php if(empty($this->order->order_payment_method)) echo '<em>'.JText::_('NONE').'</em>'; else echo $this->order->order_payment_method; ?></span></dd> <?php } if(!empty($this->order->additional)) { foreach($this->order->additional as $additional) { ?> <dt class="hikamarket_order_additional_additional"><label><?php echo JText::_($additional->order_product_name); ?></label></dt> <dd class="hikamarket_order_additional_additional"><span><?php if(!empty($additional->order_product_price)) { $additional->order_product_price = (float)$additional->order_product_price; } if(!empty($additional->order_product_price) || empty($additional->order_product_options)) { echo $this->currencyHelper->format($additional->order_product_price, $this->order->order_currency_id); } else { echo $additional->order_product_options; } ?></span></dd> <?php } } ?> <dt class="hikamarket_order_additional_total"><label><?php echo JText::_('HIKASHOP_TOTAL'); ?></label></dt> <dd class="hikamarket_order_additional_total"><span><?php echo $this->currencyHelper->format($this->order->order_full_price,$this->order->order_currency_id); ?></span></dd> <?php if(!empty($this->fields['order'])) { $editCustomFields = false; if(isset($this->edit) && $this->edit === true && hikamarket::acl('order/edit/customfields')) { $editCustomFields = true; } foreach($this->fields['order'] as $fieldName => $oneExtraField) { ?> <dt class="hikamarket_order_additional_customfield hikamarket_order_additional_customfield_<?php echo $fieldName; ?>"><?php echo $this->fieldsClass->getFieldName($oneExtraField);?></dt> <dd class="hikamarket_order_additional_customfield hikamarket_order_additional_customfield_<?php echo $fieldName; ?>"><span><?php if($editCustomFields) { echo $this->fieldsClass->display($oneExtraField, @$this->order->$fieldName, 'data[orderfields]['.$fieldName.']'); } else { echo $this->fieldsClass->show($oneExtraField, @$this->order->$fieldName); } ?></span></dd> <?php } } if(hikamarket::acl('order/edit/history')) { ?> <dt class="hikamarket_orderadditional_history"><label><?php echo JText::_('HISTORY'); ?></label></dt> <dd class="hikamarket_orderadditional_history"> <span><input onchange="window.orderMgr.orderadditional_history_changed(this);" type="checkbox" id="hikamarket_history_orderadditional_store" name="data[history][store_data]" value="1"/><label for="hikamarket_history_orderadditional_store" style="display:inline-block"><?php echo JText::_('SET_HISTORY_MESSAGE');?></label></span><br/> <textarea id="hikamarket_history_orderadditional_msg" name="data[history][msg]" style="display:none;"></textarea> </dd> <script type="text/javascript"> if(!window.orderMgr) window.orderMgr = {}; window.orderMgr.orderadditional_history_changed = function(el) { var fields = ['hikamarket_history_orderadditional_msg'], displayValue = ''; if(!el.checked) displayValue = 'none'; window.hikamarket.setArrayDisplay(fields, displayValue); } </script> <?php } ?> </dl> <input type="hidden" name="data[additional]" value="1" /> <input type="hidden" name="data[customfields]" value="1" /> <input type="hidden" name="cid[]" value="<?php echo @$this->order->order_id; ?>" /> <input type="hidden" name="option" value="<?php echo HIKAMARKET_COMPONENT; ?>" /> <input type="hidden" name="task" value="save" /> <input type="hidden" name="subtask" value="additional" /> <input type="hidden" name="tmpl" value="component" /> <input type="hidden" name="ctrl" value="order" /> <?php echo JHTML::_( 'form.token' ); ?> </form>
gpl-2.0
xponen/Zero-K
units/empmissile.lua
3889
unitDef = { unitname = [[empmissile]], name = [[Shockley]], description = [[EMP missile]], acceleration = 1, brakeRate = 0, buildAngle = 8192, buildCostEnergy = 600, buildCostMetal = 600, builder = false, buildPic = [[empmissile.png]], buildTime = 600, canAttack = true, canGuard = true, canstop = [[1]], category = [[SINK UNARMED]], collisionVolumeOffsets = [[0 15 0]], collisionVolumeScales = [[20 50 20]], collisionVolumeTest = 1, collisionVolumeType = [[CylY]], customParams = { description_de = [[EMP Rakete]], description_pl = [[Rakieta EMP]], helptext = [[The Shockley disables units in a small area for up to 45 seconds.]], helptext_de = [[Der Shockley paralysiert Einheiten in seiner kleinen Reichweite für bis zu 45 Sekunden.]], helptext_pl = [[Jednorazowa rakieta dalekiego zasięgu, która paraliżuje trafione jednostki do 45 sekund.]], mobilebuilding = [[1]], }, explodeAs = [[EMP_WEAPON]], footprintX = 1, footprintZ = 1, iconType = [[cruisemissilesmall]], idleAutoHeal = 5, idleTime = 1800, mass = 217, maxDamage = 1000, maxSlope = 18, maxVelocity = 0, maxWaterDepth = 0, minCloakDistance = 150, noAutoFire = false, objectName = [[wep_empmissile.s3o]], script = [[cruisemissile.lua]], seismicSignature = 4, selfDestructAs = [[EMP_WEAPON]], sfxtypes = { explosiongenerators = { [[custom:RAIDMUZZLE]] }, }, side = [[CORE]], sightDistance = 0, turnRate = 0, useBuildingGroundDecal = false, workerTime = 0, yardMap = [[o]], weapons = { { def = [[EMP_WEAPON]], badTargetCategory = [[SWIM LAND SHIP HOVER]], onlyTargetCategory = [[SWIM LAND SINK TURRET FLOAT SHIP HOVER FIXEDWING GUNSHIP SUB]], }, }, weaponDefs = { EMP_WEAPON = { name = [[EMP Missile]], areaOfEffect = 280, avoidFriendly = false, cegTag = [[bigemptrail]], collideFriendly = false, craterBoost = 0, craterMult = 0, damage = { default = 30000, empresistant75 = 7500, empresistant99 = 300, }, edgeEffectiveness = 1, explosionGenerator = [[custom:EMPMISSILE_EXPLOSION]], fireStarter = 0, impulseBoost = 0, impulseFactor = 0, interceptedByShieldType = 1, model = [[wep_empmissile.s3o]], paralyzer = true, paralyzeTime = 45, propeller = [[1]], range = 3500, reloadtime = 3, smokedelay = [[0.1]], smokeTrail = false, soundHit = [[weapon/missile/emp_missile_hit]], soundStart = [[weapon/missile/tacnuke_launch]], startsmoke = [[1]], tolerance = 4000, tracks = false, turnrate = 12000, weaponAcceleration = 180, weaponTimer = 5, weaponType = [[StarburstLauncher]], weaponVelocity = 1200, }, }, featureDefs = { }, } return lowerkeys({ empmissile = unitDef })
gpl-2.0
deepstupid/fred
test/org/spaceroots/mantissa/quadrature/scalar/RiemannIntegrator.java
1302
package org.spaceroots.mantissa.quadrature.scalar; import org.spaceroots.mantissa.functions.FunctionException; import org.spaceroots.mantissa.functions.ExhaustedSampleException; import org.spaceroots.mantissa.functions.scalar.SampledFunctionIterator; /** This class implements a Riemann integrator. * <p>A Riemann integrator is a very simple one that assumes the * function is constant over the integration step. Since it is very * simple, this algorithm needs very small steps to achieve high * accuracy, and small steps lead to numerical errors and * instabilities.</p> * <p>This algorithm is almost never used and has been included in * this package only as a simple template for more useful * integrators.</p> * @see TrapezoidIntegrator * @version $Id: RiemannIntegrator.java 1237 2002-03-20 21:01:57Z luc $ * @author L. Maisonobe */ public class RiemannIntegrator implements SampledFunctionIntegrator { public double integrate(SampledFunctionIterator iter) throws ExhaustedSampleException, FunctionException { RiemannIntegratorSampler sampler = new RiemannIntegratorSampler(iter); double sum = 0.0; try { while (true) { sum = sampler.nextSamplePoint().getY(); } } catch(ExhaustedSampleException e) { } return sum; } }
gpl-2.0
pleed/pyqemu
target-i386/pyqemu/msg.py
3737
#!/usr/bin/env python # This file defines Events that will be instantiated by # ev_* in PyQemu.py # # Event classes are used to handle them correctly in # VirtualMachine/OS/Heuristic ... # class QemuEvent: def __init__(self, event_type, *args): self.event_type = event_type self.args = args class QemuFunctionEntropyEvent(QemuEvent): def getStart(self): return self.args[0] def getEntropyChange(self): return self.args[1] start = property(getStart) entropychange = property(getEntropyChange) class QemuFunctionTaintEvent(QemuEvent): def getStart(self): return self.args[0] def getQuotient(self): return self.args[1] start = property(getStart) quotient = property(getQuotient) class QemuConstSearchEvent(QemuEvent): def getEIP(self): return self.args[1] def getPattern(self): return self.args[0] eip = property(getEIP) pattern = property(getPattern) class QemuCodeSearchEvent(QemuEvent): def getEIP(self): return self.args[1] def getPattern(self): return self.args[0] eip = property(getEIP) pattern = property(getPattern) class QemuFunctiontraceEvent(QemuEvent): def getEIP(self): return self.args[0] def getType(self): return self.args[1] def isCall(self): return self.args[1] == 0 def isRet(self): return self.args[1] == 1 def isLateRet(self): return self.args[1] == 2 eip = property(getEIP) type = property(getType) class QemuArithwindowEvent(QemuEvent): def getEIP(self): return self.args[0] eip = property(getEIP) class QemuCaballeroEvent(QemuEvent): def getEIP(self): return self.args[0] def getICount(self): return self.args[1] def getArithCount(self): return self.args[2] eip = property(getEIP) icount = property(getICount) arith = property(getArithCount) class QemuBranchEvent(QemuEvent): def getFrom(self): return self.args[0] def getTo(self): return self.args[1] fromaddr = property(getFrom) toaddr = property(getTo) class QemuCallEvent(QemuBranchEvent): def getNext(self): return self.args[2] def getESP(self): return self.args[3] nextaddr = property(getNext) esp = property(getESP) class QemuJmpEvent(QemuBranchEvent): pass class QemuSyscallEvent(QemuEvent): def getNumber(self): return self.args[0] number = property(getNumber) class QemuRetEvent(QemuBranchEvent): pass class QemuBreakpointEvent(QemuEvent): def getAddr(self): return self.args[0] addr = property(getAddr) class QemuMemtraceEvent(QemuEvent): def getAddr(self): return self.args[0] def getValue(self): return self.args[1] def getSize(self): return self.args[2] def isWrite(self): return self.args[3]==1 addr = property(getAddr) value = property(getValue) size = property(getSize) writes = property(isWrite) class QemuBBLEvent(QemuEvent): def getEIP(self): return self.args[0] def getESP(self): return self.args[1] eip = property(getEIP) esp = property(getESP) class QemuScheduleEvent(QemuEvent): def getPrevious(self): return self.args[0] def getCurrent(self): return self.args[1] prev = property(getPrevious) cur = property(getCurrent) QemuEventTypes = { "call":QemuCallEvent, "jmp":QemuJmpEvent, "ret":QemuRetEvent, "syscall":QemuSyscallEvent, "breakpoint":QemuBreakpointEvent, "memtrace":QemuMemtraceEvent, "schedule":QemuScheduleEvent, "bbl":QemuBBLEvent, "caballero":QemuCaballeroEvent, "arithwindow":QemuArithwindowEvent, "functiontrace":QemuFunctiontraceEvent, "functionentropy":QemuFunctionEntropyEvent, "functiontaint":QemuFunctionTaintEvent, "constsearch":QemuConstSearchEvent, "codesearch":QemuCodeSearchEvent, } def createEventObject(ev, *args): try: return QemuEventTypes[ev](ev, *args) except KeyError: raise Exception("Unknown event type: %s"%ev)
gpl-2.0
csdms-contrib/Hilltop_flow_routing
LSDFlowInfo.hpp
36881
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // // LSDFlowInfo // Land Surface Dynamics FlowInfo // // An object within the University // of Edinburgh Land Surface Dynamics group topographic toolbox // for organizing flow routing under the Fastscape algorithm // (see Braun and Willett, Geomorphology 2013, v180, p 170-179) // // // Developed by: // Simon M. Mudd // Martin D. Hurst // David T. Milodowski // Stuart W.D. Grieve // Declan A. Valters // Fiona Clubb // // Copyright (C) 2013 Simon M. Mudd 2013 // // Developer can be contacted by simon.m.mudd _at_ ed.ac.uk // // Simon Mudd // University of Edinburgh // School of GeoSciences // Drummond Street // Edinburgh, EH8 9XP // Scotland // United Kingdom // // 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: // Free Software Foundation, Inc., // 51 Franklin Street, Fifth Floor, // Boston, MA 02110-1301 // USA // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= /** @file LSDFlowInfo.hpp @author Simon M. Mudd, University of Edinburgh @author David Milodowski, University of Edinburgh @author Martin D. Hurst, British Geological Survey @author Stuart W. D. Grieve, University of Edinburgh @author Fiona Clubb, University of Edinburgh @version Version 1.0 @brief Object to perform flow routing. @details This is a data object which generates and then stores information about flow routing. It is the object that is used to generate contributing area, etc. @date 29/08/2012 */ //----------------------------------------------------------------- //DOCUMENTATION URL: http://www.geos.ed.ac.uk/~s0675405/LSD_Docs/ //----------------------------------------------------------------- #ifndef LSDFlowInfo_H #define LSDFlowInfo_H #include <string> #include <vector> #include <algorithm> #include "TNT/tnt.h" #include "LSDRaster.hpp" #include "LSDIndexRaster.hpp" using namespace std; using namespace TNT; /// @brief Object to perform flow routing. class LSDFlowInfo { public: /// @brief The create function. This is default and throws an error. /// @author SMM /// @date 01/016/12 LSDFlowInfo() { create(); } /// @brief Creates a FlowInfo object from a binary flowinfo data. /// @param fname String of the binary flowinfo data file to be read. /// @author SMM /// @date 01/016/12 LSDFlowInfo(string fname) { create(fname); } /// @brief Creates a FlowInfo object from topography. /// @param BoundaryConditions Vector<string> of the boundary conditions at each edge of the /// DEM file. Boundary conditions can start with 'P' or 'p' for periodic, /// 'B' or 'b' for base level, or anything else for no flux. /// the vector shold have 4 elements, 0 is north, 1 is east, 2 is south and 3 is west /// @param TopoRaster LSDRaster object containing the topographic data. /// @author SMM /// @date 01/016/12 LSDFlowInfo(vector<string>& BoundaryConditions, LSDRaster& TopoRaster) { create(BoundaryConditions, TopoRaster); } /// @brief Copy of the LSDJunctionNetwork description here when written. friend class LSDJunctionNetwork; // some functions for retrieving information out of the data vectors /// @brief this check to see if a point is within the raster /// @param X_coordinate the x location of the point /// @param Y_coordinate the y location of the point /// @return is_in_raster a boolean telling if the point is in the raster /// @author SMM /// @date 13/11/2014 bool check_if_point_is_in_raster(float X_coordinate,float Y_coordinate); ///@brief Gives the reciever information for a given node. ///@param current_node Integer ///@param reveiver_node Empty integer to be assigned the index of the reciever ///node. ///@param receiver_row Empty integer to be assigned the row index of the ///reciever node. ///@param receiver_col Empty integer to be assigned the column index of the ///reciever node. /// @author SMM /// @date 01/016/12 void retrieve_receiver_information(int current_node,int& reveiver_node, int& receiver_row, int& receiver_col); ///@brief Get the row and column indices of a given node. ///@param current_node Integer index of a given node. ///@param curr_row Empty integer to be assigned the row index of the given ///node. ///@param curr_col Empty integer to be assigned the column index of the given ///node. /// @author SMM /// @date 01/016/12 void retrieve_current_row_and_col(int current_node,int& curr_row, int& curr_col); ///@brief This function takes a vector of node indices and prints a csv ///file that can be read by arcmap ///@param nodeindex vec is a vector of nodeindices (which are ints) ///@param outfilename is a string of the filename /// @author SMM /// @date 03/06/14 void print_vector_of_nodeindices_to_csv_file(vector<int>& nodeindex_vec, string outfilename); ///@brief Get the number of pixels flowing into a node. ///@param node Integer of node index value. ///@return Integer of the number of contributing pixels. /// @author SMM /// @date 01/016/12 int retrieve_contributing_pixels_of_node(int node) { return NContributingNodes[node]; } ///@brief Get the FlowLengthCode of a given node. ///@param node Integer of node index value. ///@return Integer of the FlowLengthCode. /// @author SMM /// @date 01/016/12 int retrieve_flow_length_code_of_node(int node) { return FlowLengthCode[ RowIndex[node] ][ ColIndex[node] ]; } ///@brief Get the FlowDirection of a row and column pair. ///@param row Integer of row index. ///@param col Integer of col index. ///@return Integer of the flow direction. ///@author SWDG ///@date 04/02/14 int get_LocalFlowDirection(int row, int col) { return FlowDirection[row][col]; } /// @brief get the number of donors to a given node /// @param current_node the node index from which to get n donors /// @return the number of donors to this cell /// @author SMM /// @date 19/9/2014 int retrieve_ndonors_to_node(int current_node) { return NDonorsVector[current_node]; } ///@brief Get the node for a cell at a given row and column ///@param row index ///@param column index ///@return node index ///@author DTM ///@date 08/11/2013 int retrieve_node_from_row_and_column(int row, int column); /// @brief gets a vector of all the donors to a given node /// @param current_node the node index from which to get n donors /// @return a vector containing all the donors to this node /// @author SMM /// @date 19/9/2014 vector<int> retrieve_donors_to_node(int current_node); // get functions /// @return Number of rows as an integer. int get_NRows() const { return NRows; } /// @return Number of columns as an integer. int get_NCols() const { return NCols; } /// @return Minimum X coordinate as an integer. float get_XMinimum() const { return XMinimum; } /// @return Minimum Y coordinate as an integer. float get_YMinimum() const { return YMinimum; } /// @return Data resolution as an integer. float get_DataResolution() const { return DataResolution; } /// @return No Data Value as an integer. int get_NoDataValue() const { return NoDataValue; } /// @return Georeferencing information map<string,string> get_GeoReferencingStrings() const { return GeoReferencingStrings; } /// @return Number of nodes with data as an integer. int get_NDataNodes () const { return NDataNodes; } /// @return Vector of all base level nodes. vector<int> get_BaseLevelNodeList () { return BaseLevelNodeList; } /// @return donor stack vector (depth first search sequence of nodes) vector <int> get_donorStack() const { return DonorStackVector; } /// @return the S vector, which is a sorted list of nodes (see Braun and Willett 2012) vector <int> get_SVector() const { return SVector; } /// @return FlowDirection values as a 2D Array. Array2D<int> get_FlowDirection() const { return FlowDirection; } ///@brief Recursive add_to_stack routine, from Braun and Willett (2012) ///equations 12 and 13. ///@param lm_index Integer ///@param j_index Integer ///@param bl_node Integer void add_to_stack(int lm_index, int& j_index, int bl_node); // some functions that print out indices to rasters ///@brief Write NodeIndex to an LSDIndexRaster. ///@return LSDIndexRaster of node index data. /// @author SMM /// @date 01/016/12 LSDIndexRaster write_NodeIndex_to_LSDIndexRaster(); ///@brief Write FlowDirection to an LSDIndexRaster. ///@return LSDIndexRaster of flow directions. /// @author SMM /// @date 01/016/12 LSDIndexRaster write_FlowDirection_to_LSDIndexRaster(); ///@brief Write FlowLengthCode to an LSDIndexRaster. ///@return LSDIndexRaster of flow lengths. /// @author SMM /// @date 01/016/12 LSDIndexRaster write_FlowLengthCode_to_LSDIndexRaster(); /// @brief This function writes and LSDIndexRaster containing the location of nodes in the nodeindexvector. /// @param nodeindexvec a vector containing node indices one use is to export /// the LSDIndexRaster of pixels that are in the node index vector. /// @return LSDIndexRaster of pixels that are in the node index vector. /// @author SMM /// @date 01/016/12 LSDIndexRaster write_NodeIndexVector_to_LSDIndexRaster(vector<int>& nodeindexvec); ///@brief Write NContributingNodes to an LSDIndexRaster. ///@return LSDIndexRaster of number of contributing nodes for each cell. /// @author SMM /// @date 01/016/12 LSDIndexRaster write_NContributingNodes_to_LSDIndexRaster(); ///@brief Writes flow directions to an LSDIndexRaster. ///Flow direction in arcmap format is: \n\n /// 32 64 128 \n /// 16 0 1 \n /// 8 4 2 \n /// ///@return LSDIndexRaster of flow directions in arcgis format. /// @author SMM /// @date 01/016/12 LSDIndexRaster write_FlowDirection_to_LSDIndexRaster_Arcformat(); ///@brief ///@return ///@author Fiona Clubb ///@date 15/11/12 LSDRaster write_DrainageArea_to_LSDRaster(); ///@brief Prints the flow information to file. ///@param filename String of the output file to be written. /// @author SMM /// @date 01/016/12 void print_flow_info_vectors(string filename); ///@brief Unpickles flow information data from a binary file. ///@param filename String of the binary file to be read. /// @author SMM /// @date 01/016/12 void unpickle(string filename); ///@brief Pickles flow information data from a binary file. ///@details WARNING!!! This creates HUGE files (sometimes 10x bigger than /// original file). Testing indicates reading this file takes /// almost as long as recalculating the flowinfo object so /// is probably not worth doing ///@param filename String of the binary file to be written. /// @author SMM /// @date 01/016/12 void pickle(string filename); /// @brief Method to ingest the channel heads raster generated using channel_heads_driver.cpp /// into a vector of source nodes so that an LSDJunctionNetwork can be created easily /// from them. **UPDATE** if the extension is a csv file it reads the node indices directly /// /// @details Assumes the FlowInfo object has the same dimensions as the channel heads raster. /// @param filename of the channel heads raster. /// @param extension of the channel heads raster. /// @param (optional) input_switch, ONLY NEEDED FOR LOADING .csv FILES! An integer to determine whether to use the node index (0 -> default), row and column indices (1), or point coordinates from .csv file (2) to locate the channel heads /// @return Vector of source nodes. /// @author SWDG updated SMM updated DTM /// @date 6/6/14 Happy 3rd birthday Skye!! vector<int> Ingest_Channel_Heads(string filename, string extension, int input_switch = 0); // functions for getting flow, discharge, sediment flux, etc ///@brief This function calculates the contributing pixels. ///It can be converted to contributing area by multiplying by the ///DataResolution^2. In this function a pixel that has no donors has a ///contributing pixel value of 0. ///@return LSDIndexRaster of upslope contributing pixels. /// @author SMM /// @date 01/016/12 LSDIndexRaster calculate_n_pixels_contributing_from_upslope(); ///@brief This calculates area and makes an index into the s vector for ///efficient calculation of the basin upslope of a given node. /// @author SMM /// @date 01/016/12 void calculate_upslope_reference_indices(); // algorithms for basin collection ///@brief This function returns the base level node with the greatest ///drainage area. ///@return Integer node index. int retrieve_largest_base_level(); ///@brief This function returns an integer vector containing all the node ///indexes upslope of of the node with number node_number_outlet. ///@param node_number_outlet Integer of the target node. ///@return Integer vector of upslope node indexes. /// @author SMM /// @date 01/016/12 vector<int> get_upslope_nodes(int node_number_outlet); ///@brief This function accumulates some variable from an LSDRaster ///The most probably use is to accumulate precipitation in order ///to get a discharge raster ///@param A raster that contains the variable to be accumulated (e.g., precipitation) ///@return A raster containing the accumulated variable: NOTE the accumulation ///does not include the node itself ///@author SMM ///@date 09/06/2014 LSDRaster upslope_variable_accumulator(LSDRaster& accum_raster); ///@brief This function tests whether one node is upstream of another node ///@param current_node ///@param test_node ///@return Boolean indicating whether node is upstream or not ///@author FC ///@date 08/10/13 int is_node_upstream(int current_node, int test_node); /// @brief this function gets a list of the node indices of the donors to a particular node /// @param node this is the nodeindex of the node for which you want to find the donors /// @return a vector of the donor nodes /// @author SMM /// @date 21/10/2013 vector<int> get_donor_nodes(int node); // algorithms for stream profile analysis /// @brief This function calculates the chi function for all the nodes upslope /// of a given node. /// @param starting_node Integer index of node to analyse upslope of. /// @param m_over_n /// @param A_0 /// @return Vector of chi values. The node indices of these values are those /// that would be retured from get_uplope_nodes /// @author SMM /// @date 01/16/2012 vector<float> get_upslope_chi(int starting_node, float m_over_n, float A_0); /// @brief This function calculates the chi function for a list of nodes /// it isn't really a standalone modules, but is only called from get_upslope_chi /// above /// @param upslope_pixel_list Vector of nodes to analyse. /// @param m_over_n /// @param A_0 /// @return Vector of chi values. /// @author SMM /// @date 01/016/12 vector<float> get_upslope_chi(vector<int>& upslope_pixel_list, float m_over_n, float A_0); /// @brief this function takes a vector that contains the node indices of /// starting nodes, and then calculates chi upslope of these nodes /// to produce a chi map. A threshold drainage area can be used /// to only map chi where nodes have greater than the threshold drainage area /// @details this function is meant to mimic the function of the Willett et al /// (2014) Science paper. You do need to extract the wanted node indices /// for your starting nodes from a node index map /// @param starting_nodes an integer vector containing all the node indices /// of the node from which you want to start the chi analysis. All of these /// nodes will be considered to have a starting chi of 0 /// @param m_over_n the m/n ratio. Chi is quite sensitive to this /// @param A_0 the reference drainage area. This is a but arbitrary. We usually use /// 1000 m^2. Willet et al(2014, Science) used 1m^2. As of 28 July 2014 we've not /// done any detailed sensitivity analysis on this parameter /// @param area_threshold the threshold area (in m^2) that sets the area above /// which chi is recorded in the chi raster /// @return this returns an LSDRaster for the chi values upslope of all of the /// nodes indicated in starting_nodes /// @author SMM /// @date 28/14/2014 LSDRaster get_upslope_chi_from_multiple_starting_nodes(vector<int>& starting_nodes, float m_over_n, float A_0, float area_threshold); /// @brief This function gets the chi upslope of every base level node /// that is, it gets the chi values of the entire DEM, assuming all /// base level nodes have a chi of 0 /// @detail because this assumes all base level nodes have a chi of 0, /// this function is probably only appropriate for numerical models. /// @param m_over_n the m/n ratio. Chi is quite sensitive to this /// @param A_0 the reference drainage area. This is a but arbitrary. We usually use /// 1000 m^2. Willet et al(2014, Science) used 1m^2. As of 28 July 2014 we've not /// done any detailed sensitivity analysis on this parameter /// @param area_threshold the threshold area (in m^2) that sets the area above /// which chi is recorded in the chi raster /// @return this returns an LSDRaster for the chi values of the entire raster, /// with base level nodes assumed to have chi = 0 /// @author SMM /// @date 28/14/2014 LSDRaster get_upslope_chi_from_all_baselevel_nodes(float m_over_n, float A_0, float area_threshold); /// @brief Calculates the distance from outlet of all the base level nodes. /// Distance is given in spatial units, not in pixels. /// @return LSDRaster of the distance to the outlet for all baselevel nodes. /// @author SMM /// @date 01/016/12 LSDRaster distance_from_outlet(); /// @biref calculates the slope measured in the d8 flow direction /// base level nodes have slope of 0; slope is measured from node to receiver /// @param the elevation raster /// @return A raster of the d8 slope /// @author SMM /// @date 21/09/2014 LSDRaster calculate_d8_slope(LSDRaster& Elevation); /// @brief This returns the node index of the pixel farthest upslope from the input node. /// @param node the node from which you want to find the farthest upslope pixel. /// @param DistFromOutlet an LSDRaster containing the distance from the outlet. /// @return This returns the node index of the pixel farthest upslope /// from the input node. /// @author SMM /// @date 25/19/13 int find_farthest_upslope_node(int node, LSDRaster& DistFromOutlet); /// @brief Function to get the node index for a point using its X and Y coordinates /// @param X_coordinate X_coord of point /// @param Y_coordinate Y_coord of point /// @return int with node index of point /// @author FJC /// @date 11/02/14 int get_node_index_of_coordinate_point(float X_coordinate, float Y_coordinate); ///@brief A get sources version that uses the flow accumulation pixels. ///@param FlowPixels LSDIndexRaster of flow accumulation in pixels. ///@param threshold Integer flow accumulation threshold. ///@return Vector of source integers. /// @author SMM /// @date 01/016/12 vector<int> get_sources_index_threshold(LSDIndexRaster& FlowPixels, int threshold); /// @brief A get sources version that uses AS^2 (area and slope). /// @param FlowPixels LSDIndexRaster of flow accumulation in pixels. /// @param Slope LSDRaster of slope values /// @param threshold Integer AS^2 threshold /// @return Vector of source integers. /// @author FJC /// @date 11/02/14 vector<int> get_sources_slope_area(LSDIndexRaster& FlowPixels, LSDRaster& Slope, int threshold); /// @brief Gets a vector of source nodes based on the X and Y coordinates of mapped channel /// heads. Can be used if all the channel heads in a basin were mapped to get the stream /// network and calculate the drainage density /// @param X_coords X coordinates of channel heads /// @param Y_coords Y coordinates of channel heads /// @return Vector of source nodes /// @author FJC /// @date 17/02/14 vector<int> get_sources_from_mapped_channel_heads(vector<float>& X_coords, vector<float>& Y_coords); /// @brief Perform a downslope trace using D8 from a given point source (i,j). /// /// @details Overwrites input parameters to return a raster of the path, the length of the /// trace and the final pixel coordinates of the trace. /// @param i Row index of starting point for trace. /// @param j Column index of starting point for trace. /// @param StreamNetwork An LSDIndexRaster of the stream network. /// @param length Length of trace in spatial units. /// @param receiver_row Row index of ending point for trace. /// @param receiver_col Column index of ending point for trace. /// @param Path Empty raster to store the final trace path. /// @author SWDG /// @date 20/1/14 void D8_Trace(int i, int j, LSDIndexRaster StreamNetwork, float& length, int& receiver_row, int& receiver_col, Array2D<int>& Path); void HilltopFlowRoutingOriginal(LSDRaster Elevation, LSDRaster Hilltops, LSDRaster Slope, LSDRaster Aspect, LSDIndexRaster StreamNetwork); /// @brief Hilltop flow routing. /// /// @details Hilltop flow routing code built around original code from Martin Hurst. Based on /// Lea (1992), with improvements discussed by Tarboton (1997) and a solution to the /// problem of looping flow paths implemented. /// /// This code is SLOW but robust, a refactored version may appear, but there may not be /// enough whisky in Scotland to support that endeavour. /// /// The algorithm now checks for local uphill flows and in the case of identifying one, /// D8 flow path is used to push the flow into the centre of the steepest downslope /// cell, at which point the trace is restarted. The same technique is used to cope /// with self intersections of the flow path. These problems are not solved in the /// original paper and I think they are caused at least in part by the high resolution /// topogrpahy we are using. /// /// The code is also now built to take a d infinity flow direction raster instead of an /// aspect raster. See Tarboton (1997) for discussions on why this is the best solution. /// /// The Basins input raster is used to code each hilltop into a basin to allow basin /// averaging to take place. /// /// The final 5 parameters are used to set up printing flow paths to files for visualisation, /// if this is not needed simply pass in false to the two boolean switches and empty variables for the /// others, and the code will run as normal. /// /// The structure of the returned vector< Array2D<float> > is as follows: \n\n /// [0] Hilltop Network coded with stream ID \n /// [1] Hillslope Lengths \n /// [2] Slope \n /// [3] Relief \n /// /// @param Elevation LSDRaster of elevation values. /// @param Slope LSDRaster of slope values. /// @param Hilltops LSDRaster of hilltops. /// @param StreamNetwork LSDIndexRaster of the stream network. /// @param Aspect LSDRaster of Aspect. /// @param Prefix String Prefix for output data filename. /// @param Basins LSDIndexRaster of basin outlines. /// @param PlanCurvature LSDRaster of planform curvature. /// @param print_paths_switch If true paths will be printed. /// @param thinning Thinning factor, value used to skip hilltops being printed, use 1 to print every hilltop. /// @param trace_path The file path to be used to write the path files to, must end with a slash. /// @param basin_filter_switch If this switch is true only basins in Target_Basin_Vector will have their paths printed. /// @param Target_Basin_Vector Vector of Basin IDs that the user wants to print traces for. /// @return Vector of Array2D<float> containing hillslope metrics. /// @author SWDG /// @date 12/2/14 vector< Array2D<float> > HilltopFlowRouting(LSDRaster Elevation, LSDRaster Hilltops, LSDRaster Slope, LSDIndexRaster StreamNetwork, LSDRaster Aspect, string Prefix, LSDIndexRaster Basins, LSDRaster PlanCurvature, bool print_paths_switch, int thinning, string trace_path, bool basin_filter_switch, vector<int> Target_Basin_Vector); /// @brief Hilltop flow routing which runs on unsmoothed topography. /// /// @details Hilltop flow routing code built around original code from Martin Hurst. Based on /// Lea (1992), with improvements discussed by Tarboton (1997) and a solution to the /// problem of looping flow paths implemented. /// /// THIS VERSION OF THE CODE RETAINS THE FLOODING METHOD TO ALLOW TRACES TO BE USED /// ON RAW TOPOGRPAHY TO GET EVENT SCALE HILLSLOPE LENGTHS WITH NO SMOOTHING. IN /// MOST CASES USE THE MAIN METHOD, TO ANALYSE SEDIMENT TRANSPORT OVER GEOMORPHIC TIME. /// /// This code is SLOW but robust, a refactored version may appear, but there may not be /// enough whisky in Scotland to support that endeavour. /// /// The algorithm now checks for local uphill flows and in the case of identifying one, /// D8 flow path is used to push the flow into the centre of the steepest downslope /// cell, at which point the trace is restarted. The same technique is used to cope /// with self intersections of the flow path. These problems are not solved in the /// original paper and I think they are caused at least in part by the high resolution /// topogrpahy we are using. /// /// The code is also now built to take a d infinity flow direction raster instead of an /// aspect raster. See Tarboton (1997) for discussions on why this is the best solution. /// /// The Basins input raster is used to code each hilltop into a basin to allow basin /// averaging to take place. /// /// The final 5 parameters are used to set up printing flow paths to files for visualisation, /// if this is not needed simply pass in false to the two boolean switches and empty variables for the /// others, and the code will run as normal. /// /// The structure of the returned vector< Array2D<float> > is as follows: \n\n /// [0] Hilltop Network coded with stream ID \n /// [1] Hillslope Lengths \n /// [2] Slope \n /// [3] Relief \n /// /// @param Elevation LSDRaster of elevation values. /// @param Slope LSDRaster of slope values. /// @param Hilltops LSDRaster of hilltops. /// @param StreamNetwork LSDIndexRaster of the stream network. /// @param D_inf_Flowdir LSDRaster of flow directions. /// @param Prefix String Prefix for output data filename. /// @param Basins LSDIndexRaster of basin outlines. /// @param PlanCurvature LSDRaster of planform curvature. /// @param print_paths_switch If true paths will be printed. /// @param thinning Thinning factor, value used to skip hilltops being printed, use 1 to print every hilltop. /// @param trace_path The file path to be used to write the path files to, must end with a slash. /// @param basin_filter_switch If this switch is true only basins in Target_Basin_Vector will have their paths printed. /// @param Target_Basin_Vector Vector of Basin IDs that the user wants to print traces for. /// @return Vector of Array2D<float> containing hillslope metrics. /// @author SWDG /// @date 12/2/14 vector< Array2D<float> > HilltopFlowRouting_RAW(LSDRaster Elevation, LSDRaster Hilltops, LSDRaster Slope, LSDIndexRaster StreamNetwork, LSDRaster D_inf_Flowdir, string Prefix, LSDIndexRaster Basins, LSDRaster PlanCurvature, bool print_paths_switch, int thinning, string trace_path, bool basin_filter_switch, vector<int> Target_Basin_Vector); /// @brief Hilltop flow routing which generates elevation profiles. /// /// @details Hilltop flow routing code built around original code from Martin Hurst. Based on /// Lea (1992), with improvements discussed by Tarboton (1997) and a solution to the /// problem of looping flow paths implemented. /// /// THIS VERSION OF THE CODE RETAINS THE FLOODING METHOD TO ALLOW TRACES TO BE USED /// ON RAW TOPOGRPAHY TO GET EVENT SCALE HILLSLOPE LENGTHS WITH NO SMOOTHING. IN /// MOST CASES USE THE MAIN METHOD, TO ANALYSE SEDIMENT TRANSPORT OVER GEOMORPHIC TIME. /// /// This code is SLOW but robust, a refactored version may appear, but there may not be /// enough whisky in Scotland to support that endeavour. /// /// The algorithm now checks for local uphill flows and in the case of identifying one, /// D8 flow path is used to push the flow into the centre of the steepest downslope /// cell, at which point the trace is restarted. The same technique is used to cope /// with self intersections of the flow path. These problems are not solved in the /// original paper and I think they are caused at least in part by the high resolution /// topogrpahy we are using. /// /// The code is also now built to take a d infinity flow direction raster instead of an /// aspect raster. See Tarboton (1997) for discussions on why this is the best solution. /// /// The Basins input raster is used to code each hilltop into a basin to allow basin /// averaging to take place. /// /// The final 5 parameters are used to set up printing flow paths to files for visualisation, /// if this is not needed simply pass in false to the two boolean switches and empty variables for the /// others, and the code will run as normal. /// /// The structure of the returned vector< Array2D<float> > is as follows: \n\n /// [0] Hilltop Network coded with stream ID \n /// [1] Hillslope Lengths \n /// [2] Slope \n /// [3] Relief \n /// /// @param Elevation LSDRaster of elevation values. /// @param Slope LSDRaster of slope values. /// @param Hilltops LSDRaster of hilltops. /// @param StreamNetwork LSDIndexRaster of the stream network. /// @param D_inf_Flowdir LSDRaster of flow directions. /// @param Prefix String Prefix for output data filename. /// @param Basins LSDIndexRaster of basin outlines. /// @param print_paths_switch If true paths will be printed. /// @param thinning Thinning factor, value used to skip hilltops being printed, use 1 to print every hilltop. /// @param trace_path The file path to be used to write the path files to, must end with a slash. /// @param basin_filter_switch If this switch is true only basins in Target_Basin_Vector will have their paths printed. /// @param Target_Basin_Vector Vector of Basin IDs that the user wants to print traces for. /// @return Vector of Array2D<float> containing hillslope metrics. /// @author SWDG /// @date 25/03/15 vector< Array2D<float> > HilltopFlowRouting_Profile(LSDRaster Elevation, LSDRaster Hilltops, LSDRaster Slope, LSDIndexRaster StreamNetwork, LSDRaster D_inf_Flowdir, string Prefix, LSDIndexRaster Basins, bool print_paths_switch, int thinning, string trace_path, bool basin_filter_switch, vector<int> Target_Basin_Vector); /// @brief This function creates a mask depicting all cells that are influenced /// by a pixel that is either on the edge of the DEM or adjacent to a /// NoData node /// @param Bordered_mask and LSDIndexRaster that is created by the function /// find_cells_bordered_by_nodata() in LSDRaster /// @param Topography this is the LSDRaster containing topographic data /// @return Influenced_mask the LSDIndexRaster that has values 1 where pixels /// are influenced by a pixel on the border or next to nodata. They have 0 otherwise /// @author SMM /// @date 31/10/14 LSDIndexRaster find_cells_influenced_by_nodata(LSDIndexRaster& Bordered_mask, LSDRaster& Topography); /// @brief This function returns all the values from a raster for a corresponding /// input vector of node indices. /// @param An LSDRaster - must have same dimensions as the LSDFlowInfo object /// @param vector<float> - the node indices for which you want the values vector<float> get_raster_values_for_nodes(LSDRaster& Raster, vector<int>& node_indices); void D_Inf_single_trace_to_channel(LSDRaster Elevation, int start_node, LSDIndexRaster StreamNetwork, LSDRaster D_inf_Flowdir, vector< vector<float> >& output_trace_coordinates, vector<float>& output_trace_metrics, int& output_channel_node, bool& skip_trace); protected: ///Number of rows. int NRows; ///Number of columns. int NCols; ///Minimum X coordinate. float XMinimum; ///Minimum Y coordinate. float YMinimum; ///Data resolution. float DataResolution; ///No data value. int NoDataValue; ///A map of strings for holding georeferencing information map<string,string> GeoReferencingStrings; /// The number of nodes in the raster that have data. int NDataNodes; /// An array that says what node number is at a given row and column. Array2D<int> NodeIndex; /// @brief A raster of flow direction information. /// /// In the format: /// /// 7 0 1 \n /// 6 -1 2 \n /// 5 4 3 \n /// /// Nodes with flow direction of -1 drain to themselvs and are base level/sink nodes. Array2D<int> FlowDirection; /// @brief A code to denote the flow length from the node to its reciever node. /// <b>Each node has one and only one receiver.</b> /// \n\n /// 0 == no receiver/self receiver (base level) \n /// 1 == cardinal direction, flow length = DataResolution \n /// 2 == diagonal, flow length = DataResolution*(1/sqrt(2)) \n Array2D<int> FlowLengthCode; /// @brief This stores the row of a node in the vectorized /// node index. It, combined with ColIndex, is the /// inverse of NodeIndex. vector<int> RowIndex; /// @brief This stores the column of a node in the vectorized /// node index. It, combined with RowIndex, is the /// inverse of NodeIndex. vector<int> ColIndex; /// A list of base level nodes. vector<int> BaseLevelNodeList; /// Stores the number of donors to each node. vector<int> NDonorsVector; /// Stores the node index of the receiving node. vector<int> ReceiverVector; /// @brief Stores the delta vector which is used to index into the donor stack /// and order contributing nodes. See Braun and Willett (2012). vector<int> DeltaVector; /// This is a vector that stores the donor nodes of of the nodes and is /// indexed by the DeltaVector. vector<int> DonorStackVector; /// @brief This vector is used to caluculate flow accumulation. For each base /// level node it progresses from a hilltop to a confluence and then jumps to /// the next hilltop so that by cascading down through the node indices in /// this list one can quickly calculate drainage area, discharge, sediment /// flux, etc. vector<int> SVector; /// This stores the base level node for all of the nodes in the DEM. vector<int> BLBasinVector; /// This points to the starting point in the S vector of each node. vector<int> SVectorIndex; /// @brief The number of contributing nodes <b>INCULDING SELF</b> to a current /// pixel. It is used in conjunction with the SVectorIndex to build /// basins upslope of any and all nodes in the node list. vector<int> NContributingNodes; /// @brief Boundary conditions stored in a vector of four strings. /// The conditions are North[0] East[1] South[2] West[3]. /// /// There are 3 kinds of edge boundaries: no flux, base level and periodic. /// /// The strings can be any length, as long as the first letter corresponds to the /// first letter of the boundary condition. It is not case sensitive. vector<string> BoundaryConditions; private: void create(); void create(string fname); void create(vector<string>& temp_BoundaryConditions, LSDRaster& TopoRaster); }; #endif
gpl-2.0
plahoi/wpcorp
wp-content/themes/corp/template-parts/content-none.php
1136
<?php /** * The template part for displaying a message that posts cannot be found. * * Learn more: http://codex.wordpress.org/Template_Hierarchy * * @package corp */ ?> <section class="no-results not-found"> <header class="page-header"> <h1 class="page-title"><?php esc_html_e( 'Nothing Found', 'corp' ); ?></h1> </header><!-- .page-header --> <div class="page-content"> <?php if ( is_home() && current_user_can( 'publish_posts' ) ) : ?> <p><?php printf( wp_kses( __( 'Ready to publish your first post? <a href="%1$s">Get started here</a>.', 'corp' ), array( 'a' => array( 'href' => array() ) ) ), esc_url( admin_url( 'post-new.php' ) ) ); ?></p> <?php elseif ( is_search() ) : ?> <p><?php esc_html_e( 'Sorry, but nothing matched your search terms. Please try again with some different keywords.', 'corp' ); ?></p> <?php get_search_form(); ?> <?php else : ?> <p><?php esc_html_e( 'It seems we can&rsquo;t find what you&rsquo;re looking for. Perhaps searching can help.', 'corp' ); ?></p> <?php get_search_form(); ?> <?php endif; ?> </div><!-- .page-content --> </section><!-- .no-results -->
gpl-2.0
WildbookOrg/Wildbook
src/main/java/org/ecocean/MultiValue.java
15246
package org.ecocean; import java.util.Map; import java.util.HashMap; import java.util.List; import java.util.ArrayList; import java.util.Set; import java.util.TreeSet; import java.util.HashSet; import java.util.Iterator; import java.util.Collection; import java.util.Collections; import javax.servlet.http.HttpServletRequest; import javax.jdo.Query; import org.json.JSONObject; import org.json.JSONArray; import org.apache.commons.lang3.builder.ToStringBuilder; public class MultiValue implements java.io.Serializable { static final long serialVersionUID = 8831423450447974780L; private int id; protected JSONObject values; protected String valuesAsString; public static final String DEFAULT_KEY_VALUE = "*"; // sorted standard keys so we can always display them before other keys and in the desired order public static final String[] SORTED_DEFAULT_KEYS = { DEFAULT_KEY_VALUE, MarkedIndividual.NAMES_KEY_ALTERNATEID, MarkedIndividual.NAMES_KEY_NICKNAME }; public MultiValue() { } /* a note on 'keyHint': this should be used carefully, especially when *setting* using this, as it will (likely?) include the DEFAULT key. this means you will be setting the value for default as well. if you wish to avoid this behavior, access (set or get) by a specific list of keys. in particular, check out generateKeys() with a second arg ('includeDefault') */ public MultiValue(Object keyHint, String initialValue) { super(); this.addValuesByKeys(generateKeys(keyHint), initialValue); } public int getId() { return id; } public static boolean isDefault(String str) { return (DEFAULT_KEY_VALUE.equals(str)); } public JSONObject getValues() { if (values != null) return values; JSONObject j = Util.stringToJSONObject(valuesAsString); values = j; return j; } public void setValues(JSONObject j) { if (j == null) return; values = j; valuesAsString = j.toString(); } public String getValuesAsString() { if (valuesAsString != null) return valuesAsString; if (values == null) return null; valuesAsString = values.toString(); return valuesAsString; } public void merge(MultiValue other) { for (String key: other.getKeys()) { for (String val: other.getValuesByKey(key)) { addValues(key, val); } } } public static MultiValue merge(MultiValue a, MultiValue b) { MultiValue c = new MultiValue(); c.merge(a); c.merge(b); return c; } public void setValuesAsString(String s) { valuesAsString = s; values = Util.stringToJSONObject(s); } public void addValuesByKeys(Set<String> keys, String value) { if (keys == null) return; if (value == null) return; for (String key : keys) { addValuesByKey(key, value); } } public void addValuesByKey(String key, String value) { if (key == null) return; if (value == null) return; JSONObject clone = getValues(); if (clone == null) clone = new JSONObject(); if (clone.optJSONArray(key) == null) clone.put(key, new JSONArray()); List<String> vals = getValuesByKey(key); //getValuesByKey is fine working on orig values if ((vals == null) || !vals.contains(value)) clone.getJSONArray(key).put(value); setValues(clone); } public void addValues(Object keyHint, String value) { addValuesByKeys(generateKeys(keyHint), value); } public void addValuesDefault(String value) { addValuesByKey(DEFAULT_KEY_VALUE, value); } public String getValue(Object keyHint) { List<String> vals = getValuesAsList(keyHint); if (vals==null || vals.size()==0) return null; return vals.get(0); } public int size() { JSONObject vals = getValues(); if (vals==null) return 0; int total = 0; // Iterator below due to weirdness in our JSON library Iterator<String> keys = vals.keys(); while (keys.hasNext()) { String key = keys.next(); JSONArray v = values.optJSONArray(key); if (v == null) continue; total += v.length(); } return total; } //this could get values across multiple keys, but wont get duplicates public List<String> getValuesAsList(Object keyHint) { return getValuesByKeys(generateKeys(keyHint)); } public List<String> getValuesByKeys(Set<String> keys) { List<String> rtn = new ArrayList<String>(); if (getValues() == null) return null; for (String key : keys) { JSONArray v = values.optJSONArray(key); if (v == null) continue; for (int i = 0 ; i < v.length() ; i++) { String val = v.optString(i, null); if ((val != null) && !rtn.contains(val)) rtn.add(val); } } return rtn; } public List<String> getValuesByKey(String key) { //convenience singular key Set<String> keys = new HashSet<String>(); keys.add(key); return getValuesByKeys(keys); } public List<String> getValuesDefault() { return getValuesByKey(DEFAULT_KEY_VALUE); } public void removeKey(String key) { System.out.println("removeKey called on "+this.toString()); if (key == null) return; JSONObject clone = getValues(); if (clone == null) return; clone.remove(key); setValues(clone); System.out.println("removeKey completed, now "+this.toString()); } public void removeValuesByKeys(Set<String> keys, String value) { if (keys == null) return; if (value == null) return; JSONObject clone = getValues(); if (clone == null) return; for (String k : getKeys()) { if (!keys.contains(k)) continue; //even tho we "expect" to not have duplicates in the array, we check for them anyway JSONArray orig = clone.optJSONArray(k); if (orig == null) continue; JSONArray smaller = new JSONArray(); for (int i = 0 ; i < orig.length() ; i++) { String el = orig.optString(i, null); if (!value.equals(el)) smaller.put(el); } clone.put(k, smaller); } setValues(clone); } public void removeValuesByKey(String key, String value) { //convenience singular key System.out.println("removeValuesByKey called on "+this.toString()); Set<String> keys = new HashSet<String>(); keys.add(key); removeValuesByKeys(keys, value); System.out.println("removeValuesByKey completed, now "+this.toString()); } public void removeValues(Object keyHint, String value) { removeValuesByKeys(generateKeys(keyHint), value); } public void removeValues(String value) { //regardless of key removeValuesByKeys(getKeys(), value); } ////// do we needs something like removeKey() ?? //this is made to contain only one of each (in the event of duplicates) public Set<String> getAllValues() { Set<String> rtn = new HashSet<String>(); if (getValues() == null) return rtn; Iterator it = values.keys(); while (it.hasNext()) { String key = (String)it.next(); JSONArray v = values.optJSONArray(key); if (v == null) continue; for (int i = 0 ; i < v.length() ; i++) { String val = v.optString(i, null); if ((val != null) && !rtn.contains(val)) rtn.add(val); } } return rtn; } public boolean hasValue(String val) { return (getAllValues().contains(val)); } public boolean hasValueSubstring(String val) { for (String nameVal: getAllValues()) { if (nameVal.contains(val)) return true; } return false; } public Set<String> getKeys() { if (getValues() == null) return null; Set<String> rtn = new HashSet<String>(); Iterator it = values.keys(); while (it.hasNext()) { rtn.add((String)it.next()); } return rtn; } // like getKeys above, but returns in a canonical ordering so we can display all names in a consistent ordering // The canonical ordering is: default, alternateId, nickname, then the rest alphebatized public List<String> getSortedKeys() { if (getValues()==null) return new ArrayList<String>(); // so we can iterate elsewhere without an NPE Set<String> unsortedKeys = getKeys(); List<String> sortedKeys = new ArrayList<String>(); // add default keys in order to the beginning of the list for (String key: SORTED_DEFAULT_KEYS) { if (!unsortedKeys.contains(key)) continue; sortedKeys.add(key); unsortedKeys.remove(key); } // sort the rest of the (nondefault) keys and add them at the end sortedKeys.addAll(Util.asSortedList(unsortedKeys)); return sortedKeys; } // returns the alphebatized list version of Set<String> getKeys(); public List<String> getKeyList() { Set<String> keys = getKeys(); if (keys==null) return new ArrayList<String>(); return new ArrayList<String>(new TreeSet<String>(keys)); } public JSONObject toJSONObject(Object keyHint) { JSONObject rtn = new JSONObject(); if (getValues() == null) return rtn; for (String key : generateKeys(keyHint)) { rtn.put(key, values.optJSONArray(key)); } return rtn; } public JSONObject toJSONObject() { //default only JSONObject rtn = new JSONObject(); if (getValues() == null) return rtn; rtn.put(DEFAULT_KEY_VALUE, values.optJSONArray(DEFAULT_KEY_VALUE)); return rtn; } //this does a bunch of magic to get a "key" that matches the "user context" (whatever that means!) public static Set<String> generateKeys(Object keyHint) { return generateKeys(keyHint, false); //default includes DEFAULT_KEY_VALUE -- you have been warned! } public static Set<String> generateKeys(Object keyHint, boolean includeDefault) { Set<String> rtn = new HashSet(); if (includeDefault) rtn.add(DEFAULT_KEY_VALUE); if (keyHint == null) return rtn; //gets us just default (or empty if !includeDefault !!) if (keyHint instanceof HttpServletRequest) { Shepherd myShepherd = new Shepherd("context0"); //ok cuz all users live in context0, no???? myShepherd.setAction("MultiValue.generateKeys"); myShepherd.beginDBTransaction(); try { User u = myShepherd.getUser((HttpServletRequest)keyHint); if (u != null) rtn.addAll(u.getMultiValueKeys()); } catch(Exception e) {e.printStackTrace();} finally { myShepherd.rollbackDBTransaction(); myShepherd.closeDBTransaction(); } //if possible, supply Organization rather than User, as User will set on all their Organizations } else if (keyHint instanceof Organization) { Organization org = (Organization)keyHint; rtn.addAll(org.getMultiValueKeys()); } else if (keyHint instanceof User) { User u = (User)keyHint; rtn.addAll(u.getMultiValueKeys()); } else if (keyHint instanceof String) { //this may(?) only be for testing purposes //rtn.add("_RAW_:" + (String)keyHint); rtn.add((String)keyHint); } return rtn; } public String toString() { return new ToStringBuilder(this) .append("id", id) //.append("keys", this.getKeys()) .append("values", this.getValuesAsString()) .toString(); } public JSONObject debug() { JSONObject j = new JSONObject(); j.put("values_raw", getValues()); j.put("id", id); return j; } public static List<MultiValue> withNameLike(String regex, Shepherd myShepherd) { String filter = "SELECT FROM org.ecocean.MultiValue WHERE valuesAsString.matches(\""+regex+"\")"; System.out.println("have filter "+filter); Query query=myShepherd.getPM().newQuery(filter); Collection c = (Collection) (query.execute()); List<MultiValue> names = new ArrayList<MultiValue>(); for (Object m : c) { // have to do this weird iteration bc even loading a List doesn't unpack the query names.add((MultiValue) m); } query.closeAll(); return names; } // "Secret name" returns "Secret name":[" public static String searchRegexForNameKey(String nameKey) { String substring = nameKey+"\\\":["; return ".*"+substring+".*"; } // Gets a sorted list of all name values with a given key public static List<String> valuesForKey(String nameKey, Shepherd myShepherd) { String regex = searchRegexForNameKey(nameKey); System.out.println("in valuesForKey with regex: "+regex); List<MultiValue> multis = withNameLike(regex, myShepherd); List<String> values = new ArrayList<String>(); for (MultiValue mult: multis) values.addAll(mult.getValuesAsList(nameKey)); Collections.sort(values); return values; } // returns N, where N is the lowest number that is NOT a value in a name w/ nameKey. // valuePrefix comes before N for weird double-labeled values like indocet- public static String nextUnusedValueForKey(String nameKey, String valuePrefix, Shepherd myShepherd) { return nextUnusedValueForKey(nameKey, valuePrefix, myShepherd, "%s"); } public static String nextUnusedValueForKey(String nameKey, String valuePrefix, Shepherd myShepherd, String stringFormat) { // set so we can compute .contains() super fast Set<String> oldVals = new HashSet(valuesForKey(nameKey, myShepherd)); if (oldVals==null || oldVals.size()==0) return valuePrefix+String.format(stringFormat,1); int maxVal = Math.min(10000000, oldVals.size()); // I don't think biologists want their lists starting at 0, but instead at 1 like the godless heathens they are for (int i=1;i<maxVal;i++) { String candidate = valuePrefix+String.format(stringFormat,i); if (!oldVals.contains(candidate)) return candidate; } return valuePrefix+1; // default } public static String nextUnusedValueForKey(String nameKey, Shepherd myShepherd) { return nextUnusedValueForKey(nameKey, "", myShepherd, "%s"); } public static String nextUnusedValueForKey(String nameKey, Shepherd myShepherd, String stringFormat) { return nextUnusedValueForKey(nameKey, "", myShepherd, stringFormat); } }
gpl-2.0
pingdynasty/BlipBox
SerialTest/applet/serialtest.cpp
857
#include "WProgram.h" // #include <Wire.h> #define SERIAL_SPEED 115200 // #define DELAY 100 #define CTS_PIN 7 #define LED_PIN 8 uint8_t incoming; void setup() { Serial.begin(SERIAL_SPEED); #ifdef LED_PIN pinMode(LED_PIN, OUTPUT); digitalWrite(LED_PIN, HIGH); #endif // LED_PIN #ifdef CTS_PIN pinMode(CTS_PIN, OUTPUT); #endif // CTS_PIN } void loop() { #ifdef CTS_PIN digitalWrite(CTS_PIN, LOW); #endif // CTS_PIN if(serialAvailable()){ #ifdef LED_PIN digitalWrite(LED_PIN, HIGH); #endif // LED_PIN incoming = serialRead(); serialWrite(incoming); #ifdef CTS_PIN digitalWrite(CTS_PIN, HIGH); #endif // CTS_PIN }else{ #ifdef LED_PIN digitalWrite(LED_PIN, LOW); #endif // LED_PIN } #ifdef DELAY delay(DELAY); #endif // DELAY } int main(void) { init(); setup(); for (;;) loop(); return 0; }
gpl-2.0
Tomasen/SPlayer
Thirdparty/atlmfc/src/mfc/afxcolormenubutton.cpp
10812
// This is a part of the Microsoft Foundation Classes C++ library. // Copyright (C) Microsoft Corporation // All rights reserved. // // This source code is only intended as a supplement to the // Microsoft Foundation Classes Reference and related // electronic documentation provided with the library. // See these sources for detailed information regarding the // Microsoft Foundation Classes product. #include "stdafx.h" #include "afxmenutearoffmanager.h" #include "afxcontrolbarutil.h" #include "afxmenuimages.h" #include "afxpopupmenubar.h" #include "afxcolormenubutton.h" #include "afxcolordialog.h" #include "afxcolorbar.h" #include "afxsettingsstore.h" #include "afxcolorpopupmenu.h" #include "afxglobals.h" #include "afxvisualmanager.h" #ifdef _DEBUG #define new DEBUG_NEW #endif static const int SEPARATOR_SIZE = 2; CMap<UINT,UINT,COLORREF, COLORREF> CMFCColorMenuButton::m_ColorsByID; UINT AFX_WM_GETDOCUMENTCOLORS = ::RegisterWindowMessage(_T("TOOLBAR__GETDOCUMENTCOLORS")); IMPLEMENT_SERIAL(CMFCColorMenuButton, CMFCToolBarMenuButton, VERSIONABLE_SCHEMA | 1) // Construction/Destruction CMFCColorMenuButton::CMFCColorMenuButton() { Initialize(); } CMFCColorMenuButton::CMFCColorMenuButton(UINT uiCmdID, LPCTSTR lpszText, CPalette* pPalette) : CMFCToolBarMenuButton(uiCmdID, NULL, afxCommandManager->GetCmdImage(uiCmdID, FALSE), lpszText) { Initialize(); CMFCColorBar::InitColors(pPalette, m_Colors); m_Color = GetColorByCmdID(uiCmdID); } void CMFCColorMenuButton::Initialize() { m_Color = (COLORREF) -1; // Default(automatic) color m_colorAutomatic = 0; m_nColumns = -1; m_nVertDockColumns = -1; m_nHorzDockRows = -1; m_bIsAutomaticButton = FALSE; m_bIsOtherButton = FALSE; m_bIsDocumentColors = FALSE; m_bStdColorDlg = FALSE; } CMFCColorMenuButton::~CMFCColorMenuButton() { } void CMFCColorMenuButton::EnableAutomaticButton(LPCTSTR lpszLabel, COLORREF colorAutomatic, BOOL bEnable) { m_bIsAutomaticButton = bEnable; if (bEnable) { ENSURE(lpszLabel != NULL); m_strAutomaticButtonLabel = lpszLabel; m_colorAutomatic = colorAutomatic; } } void CMFCColorMenuButton::EnableOtherButton(LPCTSTR lpszLabel, BOOL bAltColorDlg, BOOL bEnable) { m_bIsOtherButton = bEnable; if (bEnable) { ENSURE(lpszLabel != NULL); m_strOtherButtonLabel = lpszLabel; m_bStdColorDlg = !bAltColorDlg; } } void CMFCColorMenuButton::EnableDocumentColors(LPCTSTR lpszLabel, BOOL bEnable) { m_bIsDocumentColors = bEnable; if (bEnable) { ENSURE(lpszLabel != NULL); m_strDocumentColorsLabel = lpszLabel; } } void CMFCColorMenuButton::EnableTearOff(UINT uiID, int nVertDockColumns, int nHorzDockRows) { if (g_pTearOffMenuManager != NULL && g_pTearOffMenuManager->IsDynamicID(uiID)) { ASSERT(FALSE); // SHould be static ID! uiID = 0; } m_uiTearOffBarID = uiID; m_nVertDockColumns = nVertDockColumns; m_nHorzDockRows = nHorzDockRows; } void CMFCColorMenuButton::OnDraw(CDC* pDC, const CRect& rect, CMFCToolBarImages* pImages, BOOL bHorz, BOOL bCustomizeMode, BOOL bHighlight, BOOL bDrawBorder, BOOL bGrayDisabledButtons) { ASSERT_VALID(this); ASSERT_VALID(pDC); CMFCToolBarMenuButton::OnDraw(pDC, rect, pImages, bHorz, bCustomizeMode, bHighlight, bDrawBorder, bGrayDisabledButtons); if (!IsDrawImage() || pImages == NULL) { return; } CPalette* pOldPalette = NULL; if (afxGlobalData.m_nBitsPerPixel == 8) // 256 colors { if (m_Palette.GetSafeHandle() == NULL) { // Palette not created yet; create it now CMFCColorBar::CreatePalette(m_Colors, m_Palette); } ENSURE(m_Palette.GetSafeHandle() != NULL); pOldPalette = pDC->SelectPalette(&m_Palette, FALSE); pDC->RealizePalette(); } else if (m_Palette.GetSafeHandle() != NULL) { ::DeleteObject(m_Palette.Detach()); ENSURE(m_Palette.GetSafeHandle() == NULL); } ENSURE(pImages != NULL); CRect rectColor = pImages->GetLastImageRect(); const int nColorBoxSize = CMFCToolBar::IsLargeIcons() && !m_bMenuMode ? 10 : 5; rectColor.top = rectColor.bottom - nColorBoxSize; rectColor.OffsetRect(0, 1); // Draw color bar: BOOL bDrawImageShadow = bHighlight && !bCustomizeMode && CMFCVisualManager::GetInstance()->IsShadowHighlightedImage() && !afxGlobalData.IsHighContrastMode() && ((m_nStyle & TBBS_PRESSED) == 0) && ((m_nStyle & TBBS_CHECKED) == 0) && ((m_nStyle & TBBS_DISABLED) == 0); if (bDrawImageShadow) { CBrush brShadow(afxGlobalData.clrBarShadow); pDC->FillRect(rectColor, &brShadow); rectColor.OffsetRect(-1, -1); } COLORREF color = (m_nStyle & TBBS_DISABLED) ? afxGlobalData.clrBarShadow : (m_Color == (COLORREF)-1 ? m_colorAutomatic : m_Color); CBrush br(PALETTERGB( GetRValue(color), GetGValue(color), GetBValue(color))); CBrush* pOldBrush = pDC->SelectObject(&br); CPen* pOldPen = (CPen*) pDC->SelectStockObject(NULL_PEN); pDC->Rectangle(&rectColor); pDC->SelectObject(pOldPen); pDC->SelectObject(pOldBrush); if (CMFCVisualManager::GetInstance()->IsMenuFlatLook()) { if (color == afxGlobalData.clrBarFace) { pDC->Draw3dRect(rectColor, afxGlobalData.clrBarDkShadow, afxGlobalData.clrBarDkShadow); } } else { pDC->Draw3dRect(rectColor, afxGlobalData.clrBarShadow, afxGlobalData.clrBarLight); } if (pOldPalette != NULL) { pDC->SelectPalette(pOldPalette, FALSE); } } int CMFCColorMenuButton::OnDrawOnCustomizeList(CDC* pDC, const CRect& rect, BOOL bSelected) { int nID = m_nID; m_nID = 0; // Force draw right arrow CRect rectColor = rect; rectColor.DeflateRect(1, 0); int iRes = CMFCToolBarMenuButton::OnDrawOnCustomizeList(pDC, rect, bSelected); m_nID = nID; return iRes; } void CMFCColorMenuButton::SetColor(COLORREF clr, BOOL bNotify) { m_Color = clr; m_ColorsByID.SetAt(m_nID, m_Color); if (m_pWndParent->GetSafeHwnd() != NULL) { m_pWndParent->InvalidateRect(m_rect); } if (bNotify) { CObList listButtons; if (CMFCToolBar::GetCommandButtons(m_nID, listButtons) > 0) { for (POSITION pos = listButtons.GetHeadPosition(); pos != NULL;) { CMFCColorMenuButton* pOther = DYNAMIC_DOWNCAST(CMFCColorMenuButton, listButtons.GetNext(pos)); if (pOther != NULL && pOther != this) { pOther->SetColor(clr, FALSE); } } } const CObList& lstToolBars = CMFCToolBar::GetAllToolbars(); for (POSITION pos = lstToolBars.GetHeadPosition(); pos != NULL;) { CMFCColorBar* pColorBar = DYNAMIC_DOWNCAST(CMFCColorBar, lstToolBars.GetNext(pos)); if (pColorBar != NULL && pColorBar->m_nCommandID == m_nID) { pColorBar->SetColor(clr); } } } } void CMFCColorMenuButton::OnChangeParentWnd(CWnd* pWndParent) { CMFCToolBarButton::OnChangeParentWnd(pWndParent); if (pWndParent != NULL) { if (pWndParent->IsKindOf(RUNTIME_CLASS(CMFCMenuBar))) { m_bText = TRUE; } if (pWndParent->IsKindOf(RUNTIME_CLASS(CMFCPopupMenuBar))) { m_bMenuMode = TRUE; m_bText = TRUE; } else { m_bMenuMode = FALSE; } } m_bDrawDownArrow = TRUE; m_pWndParent = pWndParent; } void CMFCColorMenuButton::Serialize(CArchive& ar) { CMFCToolBarMenuButton::Serialize(ar); if (ar.IsLoading()) { int nColorsCount; ar >> nColorsCount; m_Colors.SetSize(nColorsCount); for (int i = 0; i < nColorsCount; i++) { COLORREF color; ar >> color; m_Colors [i] = color; } ar >> m_nColumns; ar >> m_nVertDockColumns; ar >> m_nHorzDockRows; ar >> m_bIsAutomaticButton; ar >> m_bIsOtherButton; ar >> m_bIsDocumentColors; ar >> m_strAutomaticButtonLabel; ar >> m_strOtherButtonLabel; ar >> m_strDocumentColorsLabel; ar >> m_colorAutomatic; ar >> m_bStdColorDlg; // Synchromize color with another buttons with the same ID: CObList listButtons; if (CMFCToolBar::GetCommandButtons(m_nID, listButtons) > 0) { for (POSITION pos = listButtons.GetHeadPosition(); pos != NULL;) { CMFCColorMenuButton* pOther = DYNAMIC_DOWNCAST(CMFCColorMenuButton, listButtons.GetNext(pos)); if (pOther != NULL && pOther != this && pOther->m_Color != (COLORREF) -1) { m_Color = pOther->m_Color; } } } } else { ar <<(int) m_Colors.GetSize(); for (int i = 0; i < m_Colors.GetSize(); i++) { ar << m_Colors [i]; } ar << m_nColumns; ar << m_nVertDockColumns; ar << m_nHorzDockRows; ar << m_bIsAutomaticButton; ar << m_bIsOtherButton; ar << m_bIsDocumentColors; ar << m_strAutomaticButtonLabel; ar << m_strOtherButtonLabel; ar << m_strDocumentColorsLabel; ar << m_colorAutomatic; ar << m_bStdColorDlg; } } void CMFCColorMenuButton::CopyFrom(const CMFCToolBarButton& s) { CMFCToolBarMenuButton::CopyFrom(s); const CMFCColorMenuButton& src = (const CMFCColorMenuButton&) s; m_Color = src.m_Color; m_ColorsByID.SetAt(m_nID, m_Color); // Just to be happy :-) m_Colors.SetSize(src.m_Colors.GetSize()); for (int i = 0; i < m_Colors.GetSize(); i++) { m_Colors [i] = src.m_Colors [i]; } m_bIsAutomaticButton = src.m_bIsAutomaticButton; m_colorAutomatic = src.m_colorAutomatic; m_bIsOtherButton = src.m_bIsOtherButton; m_bIsDocumentColors = src.m_bIsDocumentColors; m_strAutomaticButtonLabel = src.m_strAutomaticButtonLabel; m_strOtherButtonLabel = src.m_strOtherButtonLabel; m_strDocumentColorsLabel = src.m_strDocumentColorsLabel; m_nColumns = src.m_nColumns; m_nVertDockColumns = src.m_nVertDockColumns; m_nHorzDockRows = src.m_nHorzDockRows; m_bStdColorDlg = src.m_bStdColorDlg; } BOOL CMFCColorMenuButton::OpenColorDialog(const COLORREF colorDefault, COLORREF& colorRes) { BOOL bResult = FALSE; if (m_bStdColorDlg) { CColorDialog dlg(colorDefault, CC_FULLOPEN | CC_ANYCOLOR); if (dlg.DoModal() == IDOK) { colorRes = dlg.GetColor(); bResult = TRUE; } } else { CMFCColorDialog dlg(colorDefault); if (dlg.DoModal() == IDOK) { colorRes = dlg.GetColor(); bResult = TRUE; } } return bResult; } CMFCPopupMenu* CMFCColorMenuButton::CreatePopupMenu() { CList<COLORREF,COLORREF> lstDocColors; if (m_bIsDocumentColors && m_pWndParent != NULL) { CFrameWnd* pOwner = AFXGetTopLevelFrame(m_pWndParent); ASSERT_VALID(pOwner); // Fill document colors list: pOwner->SendMessage(AFX_WM_GETDOCUMENTCOLORS, (WPARAM) m_nID, (LPARAM) &lstDocColors); } return new CMFCColorPopupMenu(m_Colors, m_Color, (m_bIsAutomaticButton ?(LPCTSTR) m_strAutomaticButtonLabel : NULL), (m_bIsOtherButton ?(LPCTSTR) m_strOtherButtonLabel : NULL), (m_bIsDocumentColors ?(LPCTSTR) m_strDocumentColorsLabel : NULL), lstDocColors, m_nColumns, m_nHorzDockRows, m_nVertDockColumns, m_colorAutomatic, m_nID, m_bStdColorDlg); } void __stdcall CMFCColorMenuButton::SetColorName(COLORREF color, const CString& strName) { CMFCColorBar::m_ColorNames.SetAt(color, strName); } COLORREF __stdcall CMFCColorMenuButton::GetColorByCmdID(UINT uiCmdID) { COLORREF color = (COLORREF)-1; m_ColorsByID.Lookup(uiCmdID, color); return color; }
gpl-2.0
Irvandoval/reservasfia
server/api/docente/docente.controller.js
3045
'use strict'; var _ = require('lodash'); var Docente = require('./docente.model'); // Get list of docentes exports.index = function(req, res) { Docente.find() .populate('materias') .populate('escuela') .populate('usuario') .exec(function (err, docentes) { if(err) { return handleError(res, err); } return res.status(200).json(docentes); }); }; // Get list of docentes exports.indexByMaterias = function(req, res) { Docente.find({materias:req.params.id}) .populate('materias') .populate('escuela') .exec(function (err, docentes) { if(err) { return handleError(res, err); } return res.status(200).json(docentes); }); }; // Get list of docentes search by regular Expression exports.regexNombreByMateria = function(req, res) { var regex = new RegExp(req.params.nombre, "i"); var query = { nombre: regex, materias: [req.query.materia] }; Docente.find(query,function (err, aulas) { if(err) { return handleError(res, err); } return res.json(200, aulas); }); }; //get a single docente by user id exports.byuser = function(req, res) { Docente .findOne({usuario: req.params.id}) .populate('materias') .exec(function (err, docente) { if(err) { return handleError(res, err); } return res.status(200).json(docente); }) }; //get a single docente by escuela id exports.byEscuela = function(req, res) { Docente .find({escuela: req.params.id}) .populate('materias') .exec(function (err, docente) { if(err) { return handleError(res, err); } return res.status(200).json(docente); }) }; // Get a single docente exports.show = function(req, res) { Docente .findById(req.params.id) .populate('materias') .exec(function (err, docente) { if(err) { return handleError(res, err); } if(!docente) { return res.status(404).send('Not Found'); } return res.json(docente); }); }; // Creates a new docente in the DB. exports.create = function(req, res) { Docente.create(req.body, function(err, docente) { if(err) { return handleError(res, err); } return res.status(201).json(docente); }); }; // Updates an existing docente in the DB. exports.update = function(req, res) { if(req.body._id) { delete req.body._id; } Docente.findById(req.params.id, function (err, docente) { if (err) { return handleError(res, err); } if(!docente) { return res.status(404).send('Not Found'); } var updated = _.assign(docente, req.body); updated.save(function (err) { if (err) { return handleError(res, err); } return res.status(200).json(docente); }); }); }; // Deletes a docente from the DB. exports.destroy = function(req, res) { Docente.findById(req.params.id, function (err, docente) { if(err) { return handleError(res, err); } if(!docente) { return res.status(404).send('Not Found'); } docente.remove(function(err) { if(err) { return handleError(res, err); } return res.status(204).send('No Content'); }); }); }; function handleError(res, err) { return res.status(500).send(err); }
gpl-2.0
bgribble/mfp
mfp/utils.py
7300
#! /usr/bin/env python ''' utils.py Various utility routines not specific to MFP Copyright (c) 2012 Bill Gribble <grib@billgribble.com> ''' import cProfile from threading import Thread, Lock, Condition import time from mfp import log from datetime import datetime, timedelta def homepath(fn): import os.path import os return os.path.join(os.environ.get("HOME", "~"), fn) def splitpath(p): if not p: return [] parts = p.split(":") unescaped = [] prefix = None for p in parts: if not p: continue if p[-1] == '\\': newpart = p[:-1] + ':' if prefix is not None: prefix = prefix + newpart else: prefix = newpart elif prefix is None: unescaped.append(p) else: unescaped.append(prefix + p) prefix = None return unescaped def joinpath(elts): parts = [] for e in elts: parts.append(e.replace(':', '\\:')) return ':'.join(parts) def find_file_in_path(filename, pathspec): import os.path import os searchdirs = splitpath(pathspec) for d in searchdirs: path = os.path.join(d, filename) try: s = os.stat(path) if s: return path except: continue return None def prepend_path(newpath, searchpath): searchdirs = splitpath(searchpath) if newpath in searchdirs: searchdirs.remove(newpath) searchdirs[:0] = [newpath] return joinpath(searchdirs) def logcall(func): def wrapper(*args, **kwargs): from mfp import log if "log" not in func.__name__: log.debug("called: %s.%s (%s)" % (type(args[0]).__name__, func.__name__, args[0])) return func(*args, **kwargs) return wrapper def profile(func): ''' Decorator to profile the decorated function using cProfile Usage: To profile function foo, @profile def foo(*args): pass ''' def wrapper(*args, **kwargs): if not hasattr(func, 'profinfo'): setattr(func, 'profinfo', cProfile.Profile()) p = getattr(func, 'profinfo') # Name the data file sensibly p.enable() retval = func(*args, **kwargs) p.disable() datafn = func.__name__ + ".profile" p.dump_stats(datafn) return retval return wrapper def extends(klass): ''' Decorator applied to methods defined outside the scope of a class declaration. Usage: To add a method meth to class Foo, @extends(Foo) def meth(self, *args): pass This creates a monkeypatch method so will probably not work for all purposes, but it does help in breaking up large files. Need to add an import at the end of the class def file. ''' def ext_decor(func): fn = func.__name__ setattr(klass, fn, func) return func return ext_decor def isiterable(obj): try: if hasattr(obj, '__iter__'): return True except: pass return False def catchall(thunk): from functools import wraps @wraps(thunk) def handled(*args, **kwargs): try: return thunk(*args, **kwargs) except Exception as e: log.debug("Error in", thunk.__name__, e) log.debug_traceback() return handled class QuittableThread(Thread): _all_threads = [] _all_threads_lock = None def __init__(self, target=None, args=()): self.join_req = False self.target = target if QuittableThread._all_threads_lock is None: QuittableThread._all_threads_lock = Lock() with QuittableThread._all_threads_lock: QuittableThread._all_threads.append(self) if self.target is not None: Thread.__init__(self, target=self.target, args=tuple([self] + list(args))) else: Thread.__init__(self) def finish(self): with QuittableThread._all_threads_lock: try: QuittableThread._all_threads.remove(self) except ValueError: print("QuittableThread.finish() error:", self, "not in _all_threads") except Exception as e: print("QuittableThread.finish() error:", self, e) print("Remaining threads:", QuittableThread._all_threads) self.join_req = True self.join() @classmethod def finish_all(klass): with QuittableThread._all_threads_lock: work = [t for t in QuittableThread._all_threads] for t in work: t.finish() @classmethod def wait_for_all(klass): next_victim = True while next_victim: if isinstance(next_victim, Thread) and next_victim.isAlive(): next_victim.join(.2) with QuittableThread._all_threads_lock: living_threads = [ t for t in QuittableThread._all_threads if t.isAlive() ] if len(living_threads) > 0: next_victim = living_threads[0] else: next_victim = False class TaskNibbler (QuittableThread): class NoData (object): pass NODATA = NoData() def __init__(self): self.lock = Lock() self.cv = Condition(self.lock) self.queue = [] self.failed = [] QuittableThread.__init__(self) self.start() def run(self): work = [] retry = [] while not self.join_req: with self.lock: self.cv.wait(0.25) work = [] if self.queue: work.extend(self.queue) self.queue = [] if self.failed: toonew = [] newest = datetime.utcnow() - timedelta(milliseconds=250) for jobs, timestamp in self.failed: if timestamp < newest: work.extend(jobs) else: toonew.append((jobs, timestamp)) self.failed = toonew retry = [] for unit, retry_count, data in work: try: done = unit(*data) except Exception as e: log.debug("Exception while running", unit) log.debug_traceback() if not done and retry_count: if isinstance(retry_count, (int, float)): if retry_count > 1: retry_count -= 1 else: log.warning("[TaskNibbler] ran out of retries for", unit, data) retry_count = False retry.append((unit, retry_count, data)) if retry: with self.lock: self.failed.append((retry, datetime.utcnow())) def add_task(self, task, retry, *data): with self.lock: self.queue.append((task, retry, data)) self.cv.notify()
gpl-2.0
rjbaniel/upoor
wp-content/themes/eNews/js/init.js
1073
jQuery(function(){ jQuery.noConflict(); jQuery('ul.superfish').superfish({ delay: 300, // one second delay on mouseout animation: {opacity:'show',height:'show'}, // fade-in and slide-down animation speed: 'fast', // faster animation speed autoArrows: true, // disable generation of arrow mark-up dropShadows: false // disable drop shadows }); var pagemenuwidth = jQuery("ul#page-menu").width(); var pagemleft = Math.round((950 - pagemenuwidth) / 2); if (pagemenuwidth < 950) jQuery("ul#page-menu").css('padding-left',pagemleft); var catmenuwidth = jQuery("ul#cats-menu").width(); var catmleft = Math.round((950 - catmenuwidth) / 2); if (catmenuwidth < 950) jQuery("ul#cats-menu").css('padding-left',catmleft); var maxHeight = 0; jQuery("#footer-widgets-inside .widget").each(function() { if ( jQuery(this).height() > maxHeight ) { maxHeight = jQuery(this).height(); } }).height(maxHeight); });
gpl-2.0
jactadmin/pepi
sites/all/vendor/square/connect/lib/Model/Customer.php
12575
<?php /** * Customer * * PHP version 5 * * @category Class * @package SquareConnect * @author http://github.com/swagger-api/swagger-codegen * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 * @link https://github.com/swagger-api/swagger-codegen */ /** * Copyright 2016 Square, Inc. * * 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. */ /** * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen * Do not edit the class manually. */ namespace SquareConnect\Model; use \ArrayAccess; /** * Customer Class Doc Comment * * @category Class * @description * @package SquareConnect * @author http://github.com/swagger-api/swagger-codegen * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 * @link https://github.com/swagger-api/swagger-codegen */ class Customer implements ArrayAccess { /** * Array of property to type mappings. Used for (de)serialization * @var string[] */ static $swaggerTypes = array( 'id' => 'string', 'created_at' => 'string', 'updated_at' => 'string', 'cards' => '\SquareConnect\Model\Card[]', 'given_name' => 'string', 'family_name' => 'string', 'nickname' => 'string', 'company_name' => 'string', 'email_address' => 'string', 'address' => '\SquareConnect\Model\Address', 'phone_number' => 'string', 'reference_id' => 'string', 'note' => 'string' ); /** * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ static $attributeMap = array( 'id' => 'id', 'created_at' => 'created_at', 'updated_at' => 'updated_at', 'cards' => 'cards', 'given_name' => 'given_name', 'family_name' => 'family_name', 'nickname' => 'nickname', 'company_name' => 'company_name', 'email_address' => 'email_address', 'address' => 'address', 'phone_number' => 'phone_number', 'reference_id' => 'reference_id', 'note' => 'note' ); /** * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ static $setters = array( 'id' => 'setId', 'created_at' => 'setCreatedAt', 'updated_at' => 'setUpdatedAt', 'cards' => 'setCards', 'given_name' => 'setGivenName', 'family_name' => 'setFamilyName', 'nickname' => 'setNickname', 'company_name' => 'setCompanyName', 'email_address' => 'setEmailAddress', 'address' => 'setAddress', 'phone_number' => 'setPhoneNumber', 'reference_id' => 'setReferenceId', 'note' => 'setNote' ); /** * Array of attributes to getter functions (for serialization of requests) * @var string[] */ static $getters = array( 'id' => 'getId', 'created_at' => 'getCreatedAt', 'updated_at' => 'getUpdatedAt', 'cards' => 'getCards', 'given_name' => 'getGivenName', 'family_name' => 'getFamilyName', 'nickname' => 'getNickname', 'company_name' => 'getCompanyName', 'email_address' => 'getEmailAddress', 'address' => 'getAddress', 'phone_number' => 'getPhoneNumber', 'reference_id' => 'getReferenceId', 'note' => 'getNote' ); /** * $id The customer's unique ID. * @var string */ protected $id; /** * $created_at The time when the customer was created, in RFC 3339 format. * @var string */ protected $created_at; /** * $updated_at The time when the customer was updated, in RFC 3339 format. * @var string */ protected $updated_at; /** * $cards Cards on file for the customer. * @var \SquareConnect\Model\Card[] */ protected $cards; /** * $given_name * @var string */ protected $given_name; /** * $family_name * @var string */ protected $family_name; /** * $nickname * @var string */ protected $nickname; /** * $company_name * @var string */ protected $company_name; /** * $email_address * @var string */ protected $email_address; /** * $address * @var \SquareConnect\Model\Address */ protected $address; /** * $phone_number * @var string */ protected $phone_number; /** * $reference_id * @var string */ protected $reference_id; /** * $note * @var string */ protected $note; /** * Constructor * @param mixed[] $data Associated array of property value initalizing the model */ public function __construct(array $data = null) { if ($data != null) { $this->id = $data["id"]; $this->created_at = $data["created_at"]; $this->updated_at = $data["updated_at"]; $this->cards = $data["cards"]; $this->given_name = $data["given_name"]; $this->family_name = $data["family_name"]; $this->nickname = $data["nickname"]; $this->company_name = $data["company_name"]; $this->email_address = $data["email_address"]; $this->address = $data["address"]; $this->phone_number = $data["phone_number"]; $this->reference_id = $data["reference_id"]; $this->note = $data["note"]; } } /** * Gets id * @return string */ public function getId() { return $this->id; } /** * Sets id * @param string $id The customer's unique ID. * @return $this */ public function setId($id) { $this->id = $id; return $this; } /** * Gets created_at * @return string */ public function getCreatedAt() { return $this->created_at; } /** * Sets created_at * @param string $created_at The time when the customer was created, in RFC 3339 format. * @return $this */ public function setCreatedAt($created_at) { $this->created_at = $created_at; return $this; } /** * Gets updated_at * @return string */ public function getUpdatedAt() { return $this->updated_at; } /** * Sets updated_at * @param string $updated_at The time when the customer was updated, in RFC 3339 format. * @return $this */ public function setUpdatedAt($updated_at) { $this->updated_at = $updated_at; return $this; } /** * Gets cards * @return \SquareConnect\Model\Card[] */ public function getCards() { return $this->cards; } /** * Sets cards * @param \SquareConnect\Model\Card[] $cards Cards on file for the customer. * @return $this */ public function setCards($cards) { $this->cards = $cards; return $this; } /** * Gets given_name * @return string */ public function getGivenName() { return $this->given_name; } /** * Sets given_name * @param string $given_name * @return $this */ public function setGivenName($given_name) { $this->given_name = $given_name; return $this; } /** * Gets family_name * @return string */ public function getFamilyName() { return $this->family_name; } /** * Sets family_name * @param string $family_name * @return $this */ public function setFamilyName($family_name) { $this->family_name = $family_name; return $this; } /** * Gets nickname * @return string */ public function getNickname() { return $this->nickname; } /** * Sets nickname * @param string $nickname * @return $this */ public function setNickname($nickname) { $this->nickname = $nickname; return $this; } /** * Gets company_name * @return string */ public function getCompanyName() { return $this->company_name; } /** * Sets company_name * @param string $company_name * @return $this */ public function setCompanyName($company_name) { $this->company_name = $company_name; return $this; } /** * Gets email_address * @return string */ public function getEmailAddress() { return $this->email_address; } /** * Sets email_address * @param string $email_address * @return $this */ public function setEmailAddress($email_address) { $this->email_address = $email_address; return $this; } /** * Gets address * @return \SquareConnect\Model\Address */ public function getAddress() { return $this->address; } /** * Sets address * @param \SquareConnect\Model\Address $address * @return $this */ public function setAddress($address) { $this->address = $address; return $this; } /** * Gets phone_number * @return string */ public function getPhoneNumber() { return $this->phone_number; } /** * Sets phone_number * @param string $phone_number * @return $this */ public function setPhoneNumber($phone_number) { $this->phone_number = $phone_number; return $this; } /** * Gets reference_id * @return string */ public function getReferenceId() { return $this->reference_id; } /** * Sets reference_id * @param string $reference_id * @return $this */ public function setReferenceId($reference_id) { $this->reference_id = $reference_id; return $this; } /** * Gets note * @return string */ public function getNote() { return $this->note; } /** * Sets note * @param string $note * @return $this */ public function setNote($note) { $this->note = $note; return $this; } /** * Returns true if offset exists. False otherwise. * @param integer $offset Offset * @return boolean */ public function offsetExists($offset) { return isset($this->$offset); } /** * Gets offset. * @param integer $offset Offset * @return mixed */ public function offsetGet($offset) { return $this->$offset; } /** * Sets value based on offset. * @param integer $offset Offset * @param mixed $value Value to be set * @return void */ public function offsetSet($offset, $value) { $this->$offset = $value; } /** * Unsets offset. * @param integer $offset Offset * @return void */ public function offsetUnset($offset) { unset($this->$offset); } /** * Gets the string presentation of the object * @return string */ public function __toString() { if (defined('JSON_PRETTY_PRINT')) { return json_encode(\SquareConnect\ObjectSerializer::sanitizeForSerialization($this), JSON_PRETTY_PRINT); } else { return json_encode(\SquareConnect\ObjectSerializer::sanitizeForSerialization($this)); } } }
gpl-2.0
ornicar/scalascrabble
src/main/scala/Score.scala
92
package scrabble case class Score (overAllScore: Int, individualScores: List[(String,Int)])
gpl-2.0
oat-sa/qti-sdk
src/qtism/data/content/interactions/OrderInteraction.php
11269
<?php /** * 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; under version 2 * of the License (non-upgradable). * * 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. * * Copyright (c) 2013-2020 (original work) Open Assessment Technologies SA (under the project TAO-PRODUCT); * * @author Jérôme Bogaerts <jerome@taotesting.com> * @license GPLv2 */ namespace qtism\data\content\interactions; use InvalidArgumentException; use qtism\data\QtiComponentCollection; use qtism\data\state\ResponseValidityConstraint; /** * From IMS QTI: * * In an order interaction the candidate's task is to reorder the choices, the order * in which the choices are displayed initially is significant. By default the candidate's * task is to order all of the choices but a subset of the choices can be requested using * the maxChoices and minChoices attributes. When specified the candidate must select a * subset of the choices and impose an ordering on them. * * If a default value is specified for the response variable associated with an order * interaction then its value should be used to override the order of the choices * specified here. * * By its nature, an order interaction may be difficult to render in an unanswered state, * especially in the default case where all choices are to be ordered. Implementors should * be aware of the issues concerning the use of default values described in the section * on Response Variables. * * The orderInteraction must be bound to a response variable with a baseType of identifier * and ordered cardinality only. */ class OrderInteraction extends BlockInteraction { /** * From IMS QTI: * * An ordered list of the choices that are displayed to the user. The order * is the initial order of the choices presented to the user unless shuffle * is true. * * @var SimpleChoiceCollection * @qtism-bean-property */ private $simpleChoices; /** * From IMS QTI: * * If the shuffle attribute is true then the delivery engine must randomize the order * in which the choices are initially presented, subject to the value of the fixed * attribute of each choice. * * @var bool * @qtism-bean-property */ private $shuffle = false; /** * From IMS QTI: * * The minimum number of choices that the candidate must select and order to form a valid * response to the interaction. If specified, minChoices must be 1 or greater but must not * exceed the number of choices available. If unspecified, all of the choices must be ordered * and maxChoices is ignored. * * @var int * @qtism-bean-property */ private $minChoices = -1; /** * From IMS QTI: * * The maximum number of choices that the candidate may select and order when responding to the * interaction. Used in conjunction with minChoices, if specified, maxChoices must be greater * than or equal to minChoices and must not exceed the number of choices available. If unspecified, * all of the choices may be ordered. * * @var int * @qtism-bean-property */ private $maxChoices = -1; /** * From IMS QTI: * * The orientation attribute provides a hint to rendering systems that * the ordering has an inherent vertical or horizontal interpretation. * * @var int * @qtism-bean-property */ private $orientation = Orientation::VERTICAL; /** * Create a new OrderInteraction object. * * @param string $responseIdentifier The identifier of the associated response variable. * @param SimpleChoiceCollection $simpleChoices A collection of at least one SimpleChoice object. * @param string $id The id of the bodyElement. * @param string $class The class of the bodyElement. * @param string $lang The language of the bodyElement. * @param string $label The label of the bodyElement. * @throws InvalidArgumentException If one of the arguments is invalid. */ public function __construct($responseIdentifier, SimpleChoiceCollection $simpleChoices, $id = '', $class = '', $lang = '', $label = '') { parent::__construct($responseIdentifier, $id, $class, $lang, $label); $this->setSimpleChoices($simpleChoices); $this->setShuffle(false); $this->setMinChoices(-1); $this->setMaxChoices(-1); $this->setOrientation(Orientation::VERTICAL); } /** * Set the ordered list of choices that are displayed to the user. * * @param SimpleChoiceCollection $simpleChoices A list of at lease one SimpleChoice object. * @throws InvalidArgumentException If $simpleChoices is empty. */ public function setSimpleChoices(SimpleChoiceCollection $simpleChoices) { if (count($simpleChoices) > 0) { $this->simpleChoices = $simpleChoices; } else { $msg = 'An OrderInteraction object must be composed of at lease one SimpleChoice object, none given.'; throw new InvalidArgumentException($msg); } } /** * Get the ordered list of choices that are displayed to the user. * * @return SimpleChoiceCollection A list of at lease one SimpleChoice object. */ public function getSimpleChoices() { return $this->simpleChoices; } /** * Set whether the delivery engine must randomize the choices. * * @param bool $shuffle A boolean value. * @throws InvalidArgumentException If $shuffle is not a boolean value. */ public function setShuffle($shuffle) { if (is_bool($shuffle)) { $this->shuffle = $shuffle; } else { $msg = "The 'shuffle' argument must be a boolean value, '" . gettype($shuffle) . "' given."; throw new InvalidArgumentException($msg); } } /** * Whether the delivery engine must randomize the choices. * * @return bool */ public function mustShuffle() { return $this->shuffle; } /** * Set the minimum number of choices that the candidate may select. * * @param int $minChoices A strictly (> 0) positive integer or -1 if no value is specified for the attribute. * @throws InvalidArgumentException If $minChoices is not a strictly positive integer nor -1. */ public function setMinChoices($minChoices) { if (is_int($minChoices) && ($minChoices > 0 || $minChoices === -1)) { if ($minChoices > count($this->getSimpleChoices())) { $msg = "The value of 'minChoices' cannot exceed the number of available choices."; throw new InvalidArgumentException($msg); } $this->minChoices = $minChoices; } else { $msg = "The 'minChoices' argument must be a strictly positive (> 0) integer or -1, '" . gettype($minChoices) . "' given."; throw new InvalidArgumentException($msg); } } /** * Get the minimum number of choices that the candidate may select. * * @return int A strictly positive (> 0) integer. */ public function getMinChoices() { return $this->minChoices; } /** * Whether a value is defined for the minChoices attribute. * * @return bool */ public function hasMinChoices() { return $this->getMinChoices() !== -1; } /** * Set the maximum number of choices that the candidate may select and order when responding to the interaction. * * @param int $maxChoices A strictly positive (> 0) integer or -1 if no value is specified for the attribuite. * @throws InvalidArgumentException If $maxChoices is not a strictly positive integer nor -1. */ public function setMaxChoices($maxChoices) { if (is_int($maxChoices) && $maxChoices > 0 || $maxChoices === -1) { if ($this->hasMinChoices() === true && $maxChoices > count($this->getSimpleChoices())) { $msg = "The 'maxChoices' argument cannot exceed the number of available choices."; throw new InvalidArgumentException($msg); } $this->maxChoices = $maxChoices; } else { $msg = "The 'maxChoices' argument must be a strictly positive (> 0) integer or -1, '" . gettype($maxChoices) . "' given."; throw new InvalidArgumentException($msg); } } /** * Get the maximum number of choices that the candidate may select and order when responding to the interaction. * * @return int A strictly positive (> 0) integer or -1 if no value is defined for the maxChoices attribute. */ public function getMaxChoices() { return $this->maxChoices; } /** * Whether a value is defined for the maxChoices attribute. * * @return bool */ public function hasMaxChoices() { return $this->getMaxChoices() !== -1; } /** * Set the orientation of the choices. * * @param int $orientation A value from the Orientation enumeration. * @throws InvalidArgumentException If $orientation is not a value from the Orientation enumeration. */ public function setOrientation($orientation) { if (in_array($orientation, Orientation::asArray(), true)) { $this->orientation = $orientation; } else { $msg = "The 'orientation' argument must be a value from the Orientation enumeration, '" . gettype($orientation) . "' given."; throw new InvalidArgumentException($msg); } } /** * Get the orientation of the choices. * * @return int A value from the Orientation enumeration. */ public function getOrientation() { return $this->orientation; } /** * @return ResponseValidityConstraint */ public function getResponseValidityConstraint() { return new ResponseValidityConstraint( $this->getResponseIdentifier(), ($this->hasMinChoices() === true) ? $this->getMinChoices() : count($this->getSimpleChoices()), $this->hasMinChoices() && $this->hasMaxChoices() ? $this->getMaxChoices() : 0 ); } /** * @return QtiComponentCollection */ public function getComponents() { $parentComponents = parent::getComponents(); return new QtiComponentCollection(array_merge($parentComponents->getArrayCopy(), $this->getSimpleChoices()->getArrayCopy())); } /** * @return string */ public function getQtiClassName() { return 'orderInteraction'; } }
gpl-2.0
Forage/Gramps
gramps/gen/filters/rules/family/_hassourceof.py
1812
# # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2002-2006 Donald N. Allingham # Copyright (C) 2011 Tim G L Lyons # # 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 # # $Id$ #------------------------------------------------------------------------- # # Standard Python modules # #------------------------------------------------------------------------- from ....const import GRAMPS_LOCALE as glocale _ = glocale.get_translation().gettext #------------------------------------------------------------------------- # # GRAMPS modules # #------------------------------------------------------------------------- from .._hassourceofbase import HasSourceOfBase #------------------------------------------------------------------------- # # HasSourceOf # #------------------------------------------------------------------------- class HasSourceOf(HasSourceOfBase): """Rule that checks family that have a particular source.""" labels = [ _('Source ID:') ] name = _('Families with the <source>') category = _('Citation/source filters') description = _('Matches families who have a particular source')
gpl-2.0
h0MER247/jPC
src/Hardware/CPU/Intel8086/Pointer/Pointer.java
876
/* * Copyright (C) 2017 h0MER247 * * 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. */ package Hardware.CPU.Intel8086.Pointer; public interface Pointer { int getAddress(); }
gpl-2.0
blazar-nacho/Intergalactic
SF_Crime/CSV_reader.cpp
7189
/* * CSV_reader.cpp * * Created on: 8 de nov. de 2015 * Author: Intergalactic */ #include "CSV_reader.h" #include "Standard_Scaler.h" using namespace std; Row::Row(string line, bool test, bool originalSet, const vector<string>* tr_l, const vector<string>* te_l, const lbl_num* ca_m, const lbl_num* da_m, const lbl_num* pd_m){ if (originalSet){ // donde empieza el campo size_t found = 0; size_t cant_cols = TRAIN_COLS; if (test) cant_cols = TEST_COLS; // for en vez de while porque necesito todas las columnas // sino devolver vacio for (size_t i= 0; i < cant_cols; i++) { // extrae el campo string field = extractField(line, &found); // si no se parsea bien un campo, marco para quitar if (field.compare("") == 0) { fieldsNum.clear(); break; } // opera el campo dependiendo del tipo double fieldNum = operateField(field, i, test, tr_l, te_l, ca_m, da_m, pd_m); // mejorar logica del i, ya if ((fieldNum != DROP) && ((i>1 && !test) || (i != 1 && test))) { fieldsNum.push_back(fieldNum); } // si i=0 es Dates, corregir // double para std scaling if ((i==0 && !test) || (i == 1 && test)) { fieldsNum.push_back((double)dates.t_year); fieldsNum.push_back((double)dates.t_month); fieldsNum.push_back((double)dates.t_day); fieldsNum.push_back((double)(dates.t_hour - (dates.t_min/60.0))); //fieldsNum.push_back((double)dates.t_min); } // si i=1 es Category, corregir // lo pone al principio, para shark first_column if (i==1 && !test) fieldsNum.insert(fieldsNum.begin(), fieldNum); } } } string Row::extractField(string line, size_t* pos) { size_t posAux; size_t posPre = *pos; if (line.size() == 0) return ""; if (line[posPre] == '"'){ posAux= line.find('"', posPre+2); *pos = posAux+2; return line.substr(posPre+1, posAux - posPre -1); } posAux= line.find(",", posPre+1); *pos = posAux+1; return line.substr(posPre, posAux - posPre); } vector<double> Row::getFieldsNum(){ return fieldsNum; } timedates_t Row::getDates(){ return dates; } double Row::operateTrainField(string field, size_t fieldId, const vector<string>* tr_l, const vector<string>* te_l, const lbl_num* ca_m, const lbl_num* da_m, const lbl_num* pd_m) { if (tr_l->at(fieldId).compare("Dates") == 0) { parseDates(field); return 0.0f; } if ((tr_l->at(fieldId).compare("X") == 0) || (tr_l->at(fieldId).compare("Y") == 0)){ return (double)atof(field.c_str()); } if (tr_l->at(fieldId).compare("Category") == 0) return ca_m->at(field); if (tr_l->at(fieldId).compare("PdDistrict") == 0) return pd_m->at(field); if (tr_l->at(fieldId).compare("DayOfWeek") == 0) return da_m->at(field); /*if ((tr_l->at(fieldId).compare("Descript") == 0) || (tr_l->at(fieldId).compare("Resolution") == 0)) return DROP;*/ return DROP; } double Row::operateTestField(string field, size_t fieldId , const vector<string>* tr_l, const vector<string>* te_l, const lbl_num* ca_m, const lbl_num* da_m, const lbl_num* pd_m) { if (te_l->at(fieldId).compare("Dates") == 0) { parseDates(field); return 0.0f; } if ((te_l->at(fieldId).compare("X") == 0) || (te_l->at(fieldId).compare("Y") == 0)){ return (double)atof(field.c_str()); } if (te_l->at(fieldId).compare("Id") == 0) return (double)atof(field.c_str()); if (te_l->at(fieldId).compare("PdDistrict") == 0) return pd_m->at(field); if (te_l->at(fieldId).compare("DayOfWeek") == 0) return da_m->at(field); /*if ((te_l->at(fieldId).compare("Descript") == 0) || (te_l->at(fieldId).compare("Resolution") == 0)) return DROP;*/ return DROP; } double Row::operateField(string field, size_t fieldId, bool test, const vector<string>* tr_l, const vector<string>* te_l, const lbl_num* ca_m, const lbl_num* da_m, const lbl_num* pd_m) { if (test) return operateTestField(field, fieldId, tr_l, te_l, ca_m, da_m, pd_m); return operateTrainField(field, fieldId, tr_l, te_l, ca_m, da_m, pd_m); } void Row::parseDates(string field){ if (field.size() < 2) return; size_t ff1 = field.find("-", 1); dates.t_year = atoi(field.substr(0, ff1).c_str()); size_t ff2 = field.find("-", ff1 + 1); dates.t_month = atoi(field.substr(ff1+1, ff2 - ff1).c_str()); ff1 = field.find(" ", ff2 + 1); dates.t_day = atoi(field.substr(ff2+1, ff1 - ff2).c_str()); ff2 = field.find(":", ff1 +1); dates.t_hour = atoi(field.substr(ff1+1 , ff2 -ff1).c_str()); ff1 = field.find(":", ff2 + 1); dates.t_min = atoi(field.substr(ff2+1, ff1 - ff2).c_str()); } double Row::get(size_t pos) { return fieldsNum.at(pos); } size_t Row::get_size() { return fieldsNum.size(); } void Row::set(size_t pos, double newval){ fieldsNum[pos] = newval; } void Row::remove(size_t pos){ fieldsNum.erase(fieldsNum.begin() + pos); } Row::~Row(){ fieldsNum.clear(); } CSV_reader::CSV_reader(){} vector<Row*> CSV_reader::parse(string file_path, bool test, bool originalSet){ maps_init(); ifstream csv_file(file_path.c_str()); vector<Row*> output; if (!csv_file.is_open()) return output; string line; getline(csv_file, line); while (!csv_file.eof()){ getline(csv_file, line); //if (!test) Row* oneRow = new Row(line, test, originalSet, tr_l, te_l, ca_m, da_m, pd_m); // si se parseo bien la agrego if (!oneRow->getFieldsNum().empty()) output.push_back(oneRow); else delete oneRow; } Standard_Scaler* scaler = new Standard_Scaler(); scaler->fit(output); output = scaler->transform(output); delete scaler; csv_file.close(); return output; } void CSV_reader::write(vector<Row*> input, string out){ remove(out.c_str()); ofstream output(out.c_str(), ios::app); for (size_t i=0; i<input.size(); i++) { output<< fixed << setprecision(0) << input[i]->get(0) << "," ; output<< fixed << setprecision(14) ; for (size_t j = 1; j<input[i]->get_size()-1; j++) output << input[i]->get(j) << "," ; output << input[i]->get(input[i]->get_size()-1) << endl; } } void CSV_reader::write(vector<double> input, string out){ remove(out.c_str()); ofstream output(out.c_str(), ios::app); output<< fixed << setprecision(14) ; for (size_t i=0; i < input.size(); i++) output << input.at(i) << endl; } void CSV_reader::remove_column(vector<Row*> data, size_t pos){ for (size_t i=0; i< data.size(); i++) data[i]->remove(pos); } void CSV_reader::maps_init() { const string train_cons[] = TRAIN_VEC; tr_l = new vector<string>(train_cons, train_cons + sizeof(train_cons) / sizeof(train_cons) ); const string test_cons[] = TEST_VEC; te_l = new vector<string>(test_cons, test_cons + sizeof(test_cons) / sizeof(test_cons) ); const pair<string, double> cat_cons[] = CAT_VEC; ca_m = new lbl_num(cat_cons, cat_cons + sizeof(cat_cons) / sizeof(cat_cons[0])); const pair<string, double> day_cons[] = DAY_VEC; da_m = new lbl_num(day_cons, day_cons + sizeof(day_cons) / sizeof(day_cons[0])); const pair<string, double> pd_cons[] = PD_VEC; pd_m = new lbl_num(pd_cons, pd_cons + sizeof(pd_cons) / sizeof(pd_cons[0])); }
gpl-2.0
xuechong87/Moegirlwiki
extensions/MoeUpload/MoeUpload.php
2706
<?php //ugly but useful //在上传界面增加三个字段 if (!defined('MEDIAWIKI')) { exit; } $wgExtensionCredits['specialpage'][] = array( 'path' => __FILE__, 'name' => 'MoeUpload', 'descriptionmsg' => 'moemoeQdec', 'author' => array('March','nybux.tsui','XpAhH','baskice',), 'url' => 'http://wiki.moegirl.org/Mainpage', 'version' => '1.0' ); $wgExtensionMessagesFiles['moemoeQ'] = dirname(__FILE__).'/'. 'MoeUpload.i18n.php'; $wgHooks['UploadFormInitDescriptor'][] = 'onUploadFormInitDescriptor'; $wgHooks['UploadForm:BeforeProcessing'][] = 'BeforeProcessing'; $wgHooks['BeforePageDisplay'][] = 'onBeforePageDisplay'; function onBeforePageDisplay( &$out, &$skin ) { global $wgScriptPath; $path = "$wgScriptPath/extensions/MoeUpload/MoeUpload.js"; $out->addScriptFile( $path ); return true; } function onUploadFormInitDescriptor( &$descriptor ) { $descriptor += array( 'CharName' => array( 'type' => 'text', 'section' => 'description', 'id' => 'wpCharName', 'label-message' => 'moemoeQCharName', 'size' => 60, //'default' => $this->mCharName, ), 'Author' => array( 'type' => 'text', 'section' => 'description', 'id' => 'wpAuthor', 'label-message' => 'moemoeQAuthor', 'size' => 60, //'default' => $this->mAuthor, ), 'SrcUrl' => array( 'type' => 'text', 'section' => 'description', 'id' => 'wpSrcUrl', 'label-message' => 'moemoeQSrcUrl', 'size' => 60, //'default' => $this->mSrcUrl, ) ); return true; } function BeforeProcessing( &$uploadFormObj ) { if( $uploadFormObj->mRequest->getFileName( 'wpUploadFile' ) !== null ) { $uploadFormObj->mAuthor = $uploadFormObj->mRequest->getText( 'wpAuthor' ); $uploadFormObj->mSrcUrl = $uploadFormObj->mRequest->getText( 'wpSrcUrl' ); $uploadFormObj->mCharName = $uploadFormObj->mRequest->getText( 'wpCharName' ); foreach (explode(" ", $uploadFormObj->mAuthor) as $author) { if ($author != "") { $uploadFormObj->mComment .= "[[分类:作者:$author]]"; } } foreach (explode(" ", $uploadFormObj->mCharName) as $catagory) { if ($catagory != "") { $uploadFormObj->mComment .= "[[分类:$catagory]]"; } } if ($uploadFormObj->mSrcUrl != "") { $uploadFormObj->mComment .= "源地址:".$uploadFormObj->mSrcUrl; } if ($uploadFormObj->mRequest->getText( 'wpUploadDescription' ) != "") { if ($uploadFormObj->mSrcUrl != "") { $uploadFormObj->mComment .= " "; } $uploadFormObj->mComment .= $uploadFormObj->mRequest->getText( 'wpUploadDescription' ); } } return $uploadFormObj; } ?>
gpl-2.0
JohnTendik/jtrt-tables
admin/js/jtrt-responsive-tables-admin.js
5071
(function( $ ) { 'use strict'; /** * All of the code for your admin-facing JavaScript source * should reside in this file. * * Note: It has been assumed you will write jQuery code here, so the * $ function reference has been prepared for usage within the scope * of this function. * * This enables you to define handlers, for when the DOM is ready: * * $(function() { * * }); * * When the window is loaded: * * $( window ).load(function() { * * }); * * ...and/or other possibilities. * * Ideally, it is not considered best practise to attach more than a * single DOM-ready or window-load handler for a particular page. * Although scripts in the WordPress core, Plugins and Themes may be * practising this, we should strive to set a better example in our own work. */ // Global table obj var JTrtTableEditor = {}; $(document).ready(function(){ jQuery('ul#jt-steps li').on('click',function(){ var thisid = jQuery(this).attr('data-jtrt-editor-section-id'); if(jQuery('.jtrteditorsection#step'+thisid).hasClass('jtrteditorshow')){ return false; } var activeLi = $(this).siblings('.active').removeClass('active'); $(this).addClass('active'); var currentShownSection = jQuery('.jtrteditorsection.jtrteditorshow').fadeOut(); window.setTimeout(function(){ currentShownSection.removeClass('jtrteditorshow'); jQuery('.jtrteditorsection#step'+thisid).fadeIn().addClass('jtrteditorshow'); },400); }); jQuery('.leftSidejt ul li').on('click',function(){ var thisid = jQuery(this).attr('data-jtrt-editor-section-id'); if(jQuery('.rightSidejt #optionsSection'+thisid).hasClass('jtoptionsshow')){ return false; } var activeLi = $(this).siblings('.active').removeClass('active'); $(this).addClass('active'); var currentShownSection = jQuery('.rightSidejt .optionsPagejt.jtoptionsshow').fadeOut(); window.setTimeout(function(){ currentShownSection.removeClass('jtoptionsshow'); jQuery('.rightSidejt #optionsSection'+thisid).fadeIn().addClass('jtoptionsshow'); },400); }); JTrtTableEditor = new JTrtEditor(document.getElementById('jtrt-table-handson')); //Setup the click event for the publish/update/draft button jQuery('#publish, #save-post').on('click',JTrtTableEditor.handleOnSave); //click event for the undo/redo button jQuery('#jtundo,#jtredo').on('click',function(){ JTrtTableEditor.rudo($(this).attr('data-jtrt-btnType')); }); var modal = document.getElementById('jtFindAndReplaceModal'); var linkModal = document.getElementById('jtlinkModal'); // When the user clicks anywhere outside of the modal, close it window.onclick = function(event) { if (event.target == modal) { modal.style.display = "none"; } if (event.target == linkModal) { linkModal.style.display = "none"; } } $('#jtrt_tables_post').removeClass("postbox"); $('#normal-sortables, #jtrt_tables_post .hndle, #jtrt_tables_post .handlediv').remove(); $('#jtrt_tables_post').prepend("<h1>JT Responsive Tables</h1>"); $('#jtresponsiveoptionscontainer div[data-jtresponsive-select="'+$('#jtresponsiveoptionscontainerselect').val()+'"]').fadeIn(); $('#jtresponsiveoptionscontainerselect').on('change',function(){ $('#jtresponsiveoptionscontainer div').hide(); $('#jtresponsiveoptionscontainer div[data-jtresponsive-select="'+$(this).val()+'"]').show(); }); $('#jtrt-trytoconvertolddata').on('click',function(){ var data = { 'action': 'get_old_table', 'tableId': $('#post_ID').val(), 'tableOpt': 'convert' }; // since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php makeDBcall(data); }); $('#jtrt-dontshowconvert').on('click',function(){ var data = { 'action': 'get_old_table', 'tableId': $('#post_ID').val(), 'tableOpt': 'delete' }; // since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php makeDBcall(data); }); function makeDBcall(data){ jQuery.post(ajaxurl, data, function(response) { if(response == false){ alert('This message will no longer appear. Thank you for using JTRT plugin!'); $('#jtConverAvailMessage').fadeOut(); }else{ var tableHolder = $("<div></div>").html(response.substring(0, response.length - 1)); var newData = []; tableHolder.find('table tr:not(.jtrt_custom_header)').each(function(indx,val){ var thisRow = []; $(val).find('td:not(.jtrt_custom_td)').each(function(colind,colval){ thisRow.push($(colval).html()); }); newData.push(thisRow); }); JTrtTableEditor.handsOnTab.populateFromArray(0,0,newData); } }); } $('input.jtcoloreditpicker').wpColorPicker(); $('input.jtcoloreditpickerOpts').wpColorPicker(); jQuery('.submitbox').append('<div style="text-align:center;padding:14px;"><strong>Shortcode</strong><br/><span style="padding:8px">[jtrt_tables id="'+jQuery('#post_ID').val()+'"]</span></div>') }); // .ready })( jQuery );
gpl-2.0
QuantiModo/quantimodo-android-chrome-ios-web-app
src/api/node/services/ConnectorsService.js
11765
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; Object.defineProperty(exports, "__esModule", { value: true }); exports.ConnectorsService = void 0; var request_1 = require("../core/request"); var ConnectorsService = /** @class */ (function () { function ConnectorsService() { } /** * Mobile connect page * This page is designed to be opened in a webview. Instead of using popup authentication boxes, it uses redirection. You can include the user's access_token as a URL parameter like https://app.quantimo.do/api/v3/connect/mobile?access_token=123 * @param userId User's id * @returns any Mobile connect page was returned * @throws ApiError */ ConnectorsService.getMobileConnectPage = function (userId) { return __awaiter(this, void 0, void 0, function () { var result; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, request_1.request({ method: 'GET', path: "/v3/connect/mobile", query: { 'userId': userId, }, errors: { 401: "User token is missing", 403: "User token is incorrect", }, })]; case 1: result = _a.sent(); return [2 /*return*/, result.body]; } }); }); }; /** * List of Connectors * A connector pulls data from other data providers using their API or a screenscraper. Returns a list of all available connectors and information about them such as their id, name, whether the user has provided access, logo url, connection instructions, and the update history. * @param clientId Your QuantiModo client id can be obtained by creating an app at https://builder.quantimo.do * @returns GetConnectorsResponse Successful operation * @throws ApiError */ ConnectorsService.getConnectors = function (clientId) { return __awaiter(this, void 0, void 0, function () { var result; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, request_1.request({ method: 'GET', path: "/v3/connectors/list", query: { 'clientId': clientId, }, errors: { 401: "Not Authenticated", }, })]; case 1: result = _a.sent(); return [2 /*return*/, result.body]; } }); }); }; /** * Obtain a token from 3rd party data source * Attempt to obtain a token from the data provider, store it in the database. With this, the connector to continue to obtain new user data until the token is revoked. * @param connectorName Lowercase system name of the source application or device. Get a list of available connectors from the /v3/connectors/list endpoint. * @param userId User's id * @returns any Successful operation * @throws ApiError */ ConnectorsService.connectConnector = function (connectorName, userId) { return __awaiter(this, void 0, void 0, function () { var result; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, request_1.request({ method: 'GET', path: "/v3/connectors/" + connectorName + "/connect", query: { 'userId': userId, }, errors: { 401: "Not Authenticated", 404: "Method not found. Could not execute the requested method.", 500: "Error during update. Unsupported response from update().", }, })]; case 1: result = _a.sent(); return [2 /*return*/, result.body]; } }); }); }; /** * Delete stored connection info * The disconnect method deletes any stored tokens or connection information from the connectors database. * @param connectorName Lowercase system name of the source application or device. Get a list of available connectors from the /v3/connectors/list endpoint. * @returns any Successful operation * @throws ApiError */ ConnectorsService.disconnectConnector = function (connectorName) { return __awaiter(this, void 0, void 0, function () { var result; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, request_1.request({ method: 'GET', path: "/v3/connectors/" + connectorName + "/disconnect", errors: { 401: "Not Authenticated", 404: "Method not found. Could not execute the requested method.", 500: "Error during update. Unsupported response from update().", }, })]; case 1: result = _a.sent(); return [2 /*return*/, result.body]; } }); }); }; /** * Sync with data source * The update method tells the QM Connector Framework to check with the data provider (such as Fitbit or MyFitnessPal) and retrieve any new measurements available. * @param connectorName Lowercase system name of the source application or device. Get a list of available connectors from the /v3/connectors/list endpoint. * @param userId User's id * @returns any Connection Successful * @throws ApiError */ ConnectorsService.updateConnector = function (connectorName, userId) { return __awaiter(this, void 0, void 0, function () { var result; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, request_1.request({ method: 'GET', path: "/v3/connectors/" + connectorName + "/update", query: { 'userId': userId, }, errors: { 401: "Not Authenticated", 404: "Method not found. Could not execute the requested method.", 500: "Error during update. Unsupported response from update().", }, })]; case 1: result = _a.sent(); return [2 /*return*/, result.body]; } }); }); }; /** * Get embeddable connect javascript * Get embeddable connect javascript. Usage: * - Embedding in applications with popups for 3rd-party authentication * windows. * Use `qmSetupInPopup` function after connecting `connect.js`. * - Embedding in applications with popups for 3rd-party authentication * windows. * Requires a selector to block. It will be embedded in this block. * Use `qmSetupOnPage` function after connecting `connect.js`. * - Embedding in mobile applications without popups for 3rd-party * authentication. * Use `qmSetupOnMobile` function after connecting `connect.js`. * If using in a Cordova application call `qmSetupOnIonic` function after connecting `connect.js`. * @param clientId Your QuantiModo client id can be obtained by creating an app at https://builder.quantimo.do * @returns any Embeddable connect javascript was returned * @throws ApiError */ ConnectorsService.getIntegrationJs = function (clientId) { return __awaiter(this, void 0, void 0, function () { var result; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, request_1.request({ method: 'GET', path: "/v3/integration.js", query: { 'clientId': clientId, }, })]; case 1: result = _a.sent(); return [2 /*return*/, result.body]; } }); }); }; return ConnectorsService; }()); exports.ConnectorsService = ConnectorsService; //# sourceMappingURL=ConnectorsService.js.map
gpl-2.0
fabianschuiki/Maxwell
test/base64.cpp
1181
/* Copyright (c) 2013 Fabian Schuiki */ /// @file /// This program tests the base64 encoding/decoding. #include "maxwell/base64.hpp" #include <iostream> #include <string> using std::cout; using std::string; int main() { // Test cases. struct { const char* raw; const char* b64; } tests[] = { {"Hello World", "SGVsbG8gV29ybGQ="}, {"Maxwell Programming Language", "TWF4d2VsbCBQcm9ncmFtbWluZyBMYW5ndWFnZQ=="}, {"C++ is... a lot of boilerplate.", "QysrIGlzLi4uIGEgbG90IG9mIGJvaWxlcnBsYXRlLg=="}, {NULL, NULL} }; // Run the test. int fails = 0; for (int i = 0; i < 100000; i++) { if (!tests[i].raw || !tests[i].b64) break; string raw(tests[i].raw); string b64(tests[i].b64); cout << "Testing \033[36m" << raw << "\033[0m <-> " << b64 << "... "; string encoded = base64::encode(raw); string decoded = base64::decode(b64); if (encoded == b64) { cout << "\033[32mok\033[0m"; } else { cout << "\033[31;1m" << encoded << "\033[0m"; fails++; } cout << ", "; if (decoded == raw) { cout << "\033[32mok\033[0m"; } else { cout << "\033[31;1m" << decoded << "\033[0m"; fails++; } cout << "\n"; } return (fails > 0 ? 1 : 0); }
gpl-2.0
wintermind/pypedal
PyPedal/pyp_graphics.py
43266
#!/usr/bin/python # -*- coding: utf-8 -*- ############################################################################### # NAME: pyp_graphics.py # VERSION: 2.0.0 (29SEPTEMBER2010) # AUTHOR: John B. Cole, PhD (john.cole@ars.usda.gov) # LICENSE: LGPL ############################################################################### # FUNCTIONS: # rmuller_spy_matrix_pil() [1] # rmuller_pcolor_matrix_pil() [1] # rmuller_get_color() [1] # draw_pedigree() # plot_founders_by_year() # plot_founders_pct_by_year() # plot_line_xy() # pcolor_matrix_pylab() # spy_matrix_pylab() # new_draw_pedigree() ############################################################################### # [1] These routines were taken from the ASPN Python Cookbook # (http://aspn.activestate.com/ASPN/Cookbook/Python/) and are used under # terms of the license, "Python Cookbook code is freely available for use # and review" as I understand it. I did not write them; Rick Muller # properly deserves credit for that. I THINK Rick's homepage's is: # http://www.cs.sandia.gov/~rmuller/. # Python Cookbook notes: # Title: Matlab-like 'spy' and 'pcolor' functions # Submitter: Rick Muller (other recipes) # Last Updated: 2005/03/02 # Version no: 1.0 # Category: Image # Description: # I really like the 'spy' and 'pcolor' functions, which are useful in viewing # matrices. 'spy' prints colored blocks for values that are above a threshold, # and 'pcolor' prints out each element in a continuous range of colors. The # attached is a little Python/PIL script that does these functions for Numpy # arrays. # URL: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/390208 ############################################################################### ## @package pyp_graphics # pyp_graphics contains routines for working with graphics in PyPedal, such as # creating directed graphs from pedigrees using PyDot and visualizing relationship # matrices using Rick Muller's spy and pcolor routines # (http://aspn.activestate.com/ASPN/Cookbook/Python/). # # The Python Imaging Library (http://www.pythonware.com/products/pil/), # matplotlib (http://matplotlib.sourceforge.net/), Graphviz (http://www.graphviz.org/), # and pydot (http://dkbza.org/pydot.html) are required by one or more routines in this # module. They ARE NOT distributed with PyPedal and must be installed by the end-user! # Note that the matplotlib functionality in PyPedal requires only the Agg backend, which # means that you do not have to install GTK/PyGTK or WxWidgets/PyWxWidgets just to use # PyPedal. Please consult the sites above for licensing and installation information. ## # rmuller_spy_matrix_pil() implements a matlab-like 'spy' function to display the # sparsity of a matrix using the Python Imaging Library. # @param A Input Numpy matrix (such as a numerator relationship matrix). # @param fname Output filename to which to dump the graphics (default 'tmp.png') # @param cutoff Threshold value for printing an element (default 0.1) # @param do_outline Whether or not to print an outline around the block (default 0) # @param height The height of the image (default 300) # @param width The width of the image (default 300) # @retval None def rmuller_spy_matrix_pil(A,fname='tmp.png',cutoff=0.1,do_outline=0, height=300, width=300): """ rmuller_spy_matrix_pil() implements a matlab-like 'spy' function to display the sparsity of a matrix using the Python Imaging Library. """ try: import Image, ImageDraw except: return 0 img = Image.new("RGB",(width,height),(255,255,255)) draw = ImageDraw.Draw(img) n,m = A.shape if n > width or m > height: raise "Rectangle too big %d %d %d %d" % (n,m,width,height) for i in range(n): xmin = width*i/float(n) xmax = width*(i+1)/float(n) # If the matrix is square, we can save a few cycles by only # doing the calculations for the upper triangle and reflecting # around the diagonal. if n == m: for j in range(i,n-1): # print 'i: %s, j: %s' % ( i, j ) ymin = height*j/float(m) ymax = height*(j+1)/float(m) if abs(A[i,j]) > cutoff: if do_outline: draw.rectangle((xmin,ymin,xmax,ymax),fill=(0,0,255), outline=(0,0,0)) draw.rectangle((ymin,xmin,ymax,xmax),fill=(0,0,255), outline=(0,0,0)) else: draw.rectangle((xmin,ymin,xmax,ymax),fill=(0,0,255)) draw.rectangle((ymin,xmin,ymax,xmax),fill=(0,0,255)) # If the matrix is not square, we can't shave a bit else: for j in range(m): ymin = height*j/float(m) ymax = height*(j+1)/float(m) if abs(A[i,j]) > cutoff: if do_outline: draw.rectangle((xmin,ymin,xmax,ymax),fill=(0,0,255), outline=(0,0,0)) else: draw.rectangle((xmin,ymin,xmax,ymax),fill=(0,0,255)) img.save(fname) return ## # rmuller_pcolor_matrix_pil() implements a matlab-like 'pcolor' function to # display the large elements of a matrix in pseudocolor using the Python Imaging # Library. # @param A Input Numpy matrix (such as a numerator relationship matrix). # @param fname Output filename to which to dump the graphics (default 'tmp.png') # @param do_outline Whether or not to print an outline around the block (default 0) # @param height The height of the image (default 300) # @param width The width of the image (default 300) # @retval A list of Animal() objects; a pedigree metadata object. def rmuller_pcolor_matrix_pil(A, fname='tmp.png', do_outline=0, height=300, width=300): """ rmuller_pcolor_matrix_pil() implements a matlab-like 'pcolor' function to display the large elements of a matrix in pseudocolor using the Python Imaging Library. """ try: import Image, ImageDraw except: return 0 key_dict = {} color_cache = {} img = Image.new("RGB",(width,height),(255,255,255)) draw = ImageDraw.Draw(img) # For Numeric #mina = min(min(A)) #maxa = max(max(A)) # For NumPy mina = A.min() maxa = A.max() n,m = A.shape if n > width or m > height: raise "Rectangle too big %d %d %d %d" % (n,m,width,height) for i in range(n): xmin = width*i/float(n) xmax = width*(i+1)/float(n) for j in range(m): ymin = height*j/float(m) ymax = height*(j+1)/float(m) # JBC added a dictionary to cache colors to reduce the number of calls # to rmuller_get_color(). This may lead to a dramatic improvement in the # performance of rmuller_pcolor_matrix_pil(), which currently makes a call # to rmuller_get_color() for each of the n**2 elements of A. The cache will # reduce that to the number of unique values in A, which should be much # smaller. _cache_key = '%s_%s_%s' % (A[i,j],mina,maxa) try: color = color_cache[_cache_key] except KeyError: color = rmuller_get_color(A[i,j],mina,maxa) color_cache[_cache_key] = color # JBC added this to generate a color key. try: _v = key_dict[color] except KeyError: #_key = round( (A[i,j] * 1000), 0 ) key_dict[A[i,j]] = color if do_outline: draw.rectangle((xmin,ymin,xmax,ymax),fill=color,outline=(0,0,0)) else: draw.rectangle((xmin,ymin,xmax,ymax),fill=color) #print key_dict img.save(fname) return ## # rmuller_get_color() Converts a float value to one of a continuous range of colors # using recipe 9.10 from the Python Cookbook. # @param a Float value to convert to a color. # @param cmin Minimum value in array. # @param cmax Maximum value in array. # @retval An integer containins an RGB triplet. def rmuller_get_color(a, cmin, cmax): """ Convert a float value to one of a continuous range of colors. Rewritten to use recipe 9.10 from the O'Reilly Python Cookbook. """ try: a = float(a-cmin)/(cmax-cmin) except ZeroDivisionError: a = 0.5 # cmax == cmin blue = min((max((4*(0.75-a),0.)),1.)) red = min((max((4*(a-0.25),0.)),1.)) green = min((max((4*math.fabs(a-0.5)-1.,0)),1.)) return '#%1x%1x%1x' % (int(15*red),int(15*green),int(15*blue)) ## # draw_pedigree() uses the pydot bindings to the graphviz library -- if they # are available on your system -- to produce a directed graph of your pedigree # with paths of inheritance as edges and animals as nodes. If there is more than # one generation in the pedigree as determind by the "gen" attributes of the animals # in the pedigree, draw_pedigree() will use subgraphs to try and group animals in the # same generation together in the drawing. # @param pedobj A PyPedal pedigree object. # @param gfilename The name of the file to which the pedigree should be drawn # @param gtitle The title of the graph. # @param gformat The format in which the output file should be written (JPG|PNG|PS). # @param gsize The size of the graph: 'f': full-size, 'l': letter-sized page. # @param gdot Whether or not to write the dot code for the pedigree graph to a file (can produce large files). # @param gorient The orientation of the graph: 'p': portrait, 'l': landscape. # @param gdirec Direction of flow from parents to offspring: 'TB': top-bottom, 'LR': left-right, 'RL': right-left. # @param gname Flag indicating whether ID numbers (0) or names (1) should be used to label nodes. # @param gfontsize Integer indicating the typeface size to be used in labelling nodes. # @param garrow Flag indicating whether or not arrowheads should be drawn. # @param gtitloc Indicates if the title be drawn or above ('t') or below ('b') the graph. # @param gtitjust Indicates if the title should be center- ('c'), left- ('l'), or right-justified ('r'). # @param gshowall Draws animals with no links to other ancestors in the pedigree (1) or suppresses them (0). # @param gclusters Indicates if subgraph clusters should be used when drawing the pedigree, which may improve layout in some pedigrees. # @param gwidth Width of the canvas to plot on, in inches # @param gheight Height of the canvas to plot on, in inches # @param gdpi Resolution of image in DPI # @retval A 1 for success and a 0 for failure. def draw_pedigree(pedobj, gfilename='pedigree', gtitle='', gformat='jpg', gsize='f', gdot='1', gorient='p', gdirec='', gname=0, gfontsize=10, garrow=1, gtitloc='b', gtitjust='c', gshowall=1, gclusters=0, gwidth=8.5, gheight=11, gdpi=150): """ draw_pedigree() uses the pydot bindings to the graphviz library -- if they are available on your system -- to produce a directed graph of your pedigree with paths of inheritance as edges and animals as nodes. If there is more than one generation in the pedigree as determind by the "gen" attributes of the animals in the pedigree, draw_pedigree() will use subgraphs to try and group animals in the same generation together in the drawing. """ if gtitle == '': gtitle = pedobj.kw['pedname'] from pyp_utils import string_to_table_name _gtitle = string_to_table_name(gtitle) # if pedobj.kw['messages'] == 'verbose': # print 'gtitle: %s' % ( gtitle ) # print '_gtitle: %s' % ( _gtitle ) if gtitloc not in ['t','b']: gtitloc = 'b' if gtitjust not in ['c','l','r']: gtitjust = 'c' #print pedobj.metadata.unique_gen_list if not pedobj.kw['pedigree_is_renumbered']: if pedobj.kw['messages'] != 'quiet': print '[GRAPH]: The pedigree that you passed to pyp_graphics/draw_pedigree() is not renumbered. Because of this, there may be errors in the rendered pedigree. In order to insure that the pedigree drawing is accurate, you should renumber the pedigree before calling draw_pedigree().' logging.error('The pedigree that you passed to pyp_graphics/draw_pedigree() is not renumbered. Because of this, there may be errors in the rendered pedigree. In order to insure that the pedigree drawing is accurate, you should renumber the pedigree before calling draw_pedigree().') #try: import pydot # Set some properties for the graph. The label attribute is based on the gtitle. # In cases where an empty string, e.g. '', is provided as the gtitle dot engine # processing breaks. In such cases, don't add a label. if gtitle == '': if gshowall: g = pydot.Dot(graph_name=str(_gtitle), graph_type='digraph', strict=False, suppress_disconnected=False, simplify=True) else: g = pydot.Dot(graph_name=str(_gtitle), graph_type='digraph', strict=False, suppress_disconnected=True, simplify=True) else: if gshowall: g = pydot.Dot(label=str(_gtitle), labelloc=str(gtitloc), labeljust=str(gtitjust), graph_name=str(_gtitle), graph_type='digraph', strict=False, suppress_disconnected=False, simplify=True) else: g = pydot.Dot(label=str(_gtitle), labelloc=str(gtitloc), labeljust=str(gtitjust), graph_name=str(_gtitle), graph_type='digraph', strict=False, suppress_disconnected=True, simplify=True) # Make sure that gfontsize has a valid value. try: gfontsize = int(gfontsize) except: gfontsize = 10 if gfontsize < 10: gfontsize = 10 gfontsize = str(gfontsize) # print 'gfontsize = %s' % (gfontsize) # Check the resolution and set if it's a positive integer, otherwise set it to the default. dpi = int(gdpi) if dpi <= 0: dpi = 150 g.set_dpi(dpi) # If the user specifies a height and width for the canvas use it if it's a plausible # value. Anything smaller than 8.5 x 11 is set to that size. Values larger than 8.5 x 11 # are left alone. if gheight and gwidth: gheight = float(gheight) gwidth = float(gwidth) if gwidth <= 8.5: gwidth = 8.5 if gheight <= 11.: gwidth = 11. try: page = "%.1f,%.1f" % ( gwidth, gheight ) size = "%.1f,%.1f" % ( gwidth-1, gheight-1 ) except: page = "8.5,11" size = "7.5,10" else: page = "8.5,11" size = "7.5,10" g.set_page(page) g.set_size(size) # Handle the orientation of the document. if gorient == 'l': g.set_orientation("landscape") else: g.set_orientation("portrait") if gsize != 'l': g.set_ratio("auto") if gdirec not in ['RL', 'LR', 'TB', 'BT']: gdirec = 'TB' g.set_rankdir(gdirec) g.set_center('true') g.set_concentrate('true') g.set_ordering('out') if gformat not in g.formats: gformat = 'jpg' # If we do not have any generations, we have to draw a less-nice graph. if len(pedobj.metadata.unique_gen_list) <= 1: for _m in pedobj.pedigree: # Add a node for the current animal and set some properties. if str(_m.animalID) != str(pedobj.kw['missing_parent']): if gname: _node_name = _m.name else: _node_name = _m.animalID _an_node = pydot.Node(str(_node_name)) _an_node.set_fontname('Helvetica') # _an_node.set_fontsize('10') _an_node.set_fontsize(str(gfontsize)) _an_node.set_height('0.35') if _m.sex == 'M' or _m.sex == 'm': _an_node.set_shape('box') elif _m.sex == 'F' or _m.sex == 'f': _an_node.set_shape('ellipse') else: pass g.add_node(_an_node) # Add the edges to the parent nodes, if any. if str(_m.sireID) != str(pedobj.kw['missing_parent']): if gname: if garrow: g.add_edge(pydot.Edge(str(pedobj.pedigree[int(_m.sireID)-1].name), str(_m.name))) else: g.add_edge(pydot.Edge(str(pedobj.pedigree[int(_m.sireID)-1].name), str(_m.name), dir='none')) else: if garrow: g.add_edge(pydot.Edge(str(pedobj.pedigree[int(_m.sireID)-1].originalID), str(_m.originalID))) else: g.add_edge(pydot.Edge(str(pedobj.pedigree[int(_m.sireID)-1].originalID), str(_m.originalID), dir='none')) if str(_m.damID) != str(pedobj.kw['missing_parent']): if gname: if garrow: g.add_edge(pydot.Edge(str(pedobj.pedigree[int(_m.damID)-1].name), str(_m.name))) else: g.add_edge(pydot.Edge(str(pedobj.pedigree[int(_m.damID)-1].name), str(_m.name), dir='none')) else: if garrow: g.add_edge(pydot.Edge(str(pedobj.pedigree[int(_m.damID)-1].originalID), str(_m.originalID))) else: g.add_edge(pydot.Edge(str(pedobj.pedigree[int(_m.damID)-1].originalID), str(_m.originalID), dir='none')) # Or test the new subgraph clusters elif gclusters: for _g in pedobj.metadata.unique_gen_list: _sg_anims = [] _sg_name = 'sg%s' % (_g) if gshowall: sg = pydot.Cluster(graph_name=str(_sg_name), suppress_disconnected=False, simplify=True) else: sg = pydot.Cluster(graph_name=str(_sg_name), suppress_disconnected=True, simplify=True) for _m in pedobj.pedigree: if int(_m.gen) == int(_g): _sg_anims.append(_m.animalID) # Add a node for the current animal and set some properties. if str(_m.animalID) != str(pedobj.kw['missing_parent']): if gname: _node_name = _m.name else: _node_name = str(_m.animalID) _an_node = pydot.Node(str(_node_name)) _an_node.set_fontname('Helvetica') _an_node.set_fontsize(gfontsize) _an_node.set_height('0.35') if _m.sex == 'M' or _m.sex == 'm': _an_node.set_shape('box') if _m.sex == 'F' or _m.sex == 'f': _an_node.set_shape('ellipse') sg.add_node(_an_node) g.add_subgraph(sg) # Now that we've added the clusters to the graph, define the # edges. for _m in pedobj.pedigree: if str(_m.sireID) != str(pedobj.kw['missing_parent']): if gname: if garrow: g.add_edge(pydot.Edge(str(pedobj.pedigree[int(_m.sireID)-1].name), str(_m.name))) else: g.add_edge(pydot.Edge(str(pedobj.pedigree[int(_m.sireID)-1].name), str(_m.name), dir='none')) else: if garrow: g.add_edge(pydot.Edge(str(pedobj.pedigree[int(_m.sireID)-1].animalID), str(_m.animalID))) else: g.add_edge(pydot.Edge(str(pedobj.pedigree[int(_m.sireID)-1].animalID), str(_m.animalID), dir='none')) if str(_m.damID) != str(pedobj.kw['missing_parent']): if gname: if garrow: g.add_edge(pydot.Edge(str(pedobj.pedigree[int(_m.damID)-1].name), str(_m.name))) else: g.add_edge(pydot.Edge(str(pedobj.pedigree[int(_m.damID)-1].name), str(_m.name), dir='none')) else: if garrow: g.add_edge(pydot.Edge(str(pedobj.pedigree[int(_m.damID)-1].animalID), str(_m.animalID))) else: g.add_edge(pydot.Edge(str(pedobj.pedigree[int(_m.damID)-1].animalID), str(_m.animalID), dir='none')) # Otherwise we can draw a nice graph. else: for _g in pedobj.metadata.unique_gen_list: _sg_anims = [] _sg_name = 'sg%s' % (_g) if gshowall: sg = pydot.Subgraph(graph_name=str(_sg_name), suppress_disconnected=False, simplify=True, rank='same') else: sg = pydot.Subgraph(graph_name=str(_sg_name), suppress_disconnected=True, simplify=True, rank='same') for _m in pedobj.pedigree: if str(_m.animalID) != str(pedobj.kw['missing_parent']): if int(_m.gen) == int(_g): _sg_anims.append(_m.animalID) ## -> # Add a node for the current animal and set some properties. if gname: _node_name = _m.name else: _node_name = str(_m.animalID) _an_node = pydot.Node(str(_node_name)) _an_node.set_fontname('Helvetica') _an_node.set_fontsize(str(gfontsize)) _an_node.set_height('0.35') if _m.sex == 'M' or _m.sex == 'm': _an_node.set_shape('box') if _m.sex == 'F' or _m.sex == 'f': _an_node.set_shape('ellipse') sg.add_node(_an_node) ## <- # Add the edges to the parent nodes, if any. if str(_m.sireID) != str(pedobj.kw['missing_parent']): if gname: if garrow: sg.add_edge(pydot.Edge(str(pedobj.pedigree[int(_m.sireID)-1].name), str(_m.name))) else: sg.add_edge(pydot.Edge(str(pedobj.pedigree[int(_m.sireID)-1].name), str(_m.name), dir='none')) else: if garrow: sg.add_edge(pydot.Edge(str(pedobj.pedigree[int(_m.sireID)-1].animalID), str(_m.animalID))) else: sg.add_edge(pydot.Edge(str(pedobj.pedigree[int(_m.sireID)-1].animalID), str(_m.animalID), dir='none')) if str(_m.damID) != str(pedobj.kw['missing_parent']): if gname: if garrow: sg.add_edge(pydot.Edge(str(pedobj.pedigree[int(_m.damID)-1].name), str(_m.name))) else: sg.add_edge(pydot.Edge(str(pedobj.pedigree[int(_m.damID)-1].name), str(_m.name), dir='none')) else: if garrow: sg.add_edge(pydot.Edge(str(pedobj.pedigree[int(_m.damID)-1].animalID), str(_m.animalID))) else: sg.add_edge(pydot.Edge(str(pedobj.pedigree[int(_m.damID)-1].animalID), str(_m.animalID), dir='none')) ## <- if len(_sg_anims) > 0: _sg_list = '' for _a in _sg_anims: if len(_sg_list) == 0: _sg_list = '%s' % (_a) else: _sg_list = '%s,%s' % (_sg_list,_a) sg.set_rank(_sg_list) g.add_subgraph(sg) #try: #print sg.get_node_list() #except: #print 'Could not get node list for subgraph!' #try: #print sg.get_edge_list() #except: #print 'Could not get edge list for subgraph!' # For large graphs it is nice to write out the .dot file so that it does # not have to be recreated whenever new_draw_pedigree is called. # Especially when I am debugging. if gdot: dfn = '%s.dot' % (gfilename) #try: g.write(dfn) #except: # if pedobj.kw['messages'] == 'verbose': # print '[ERROR]: pyp_graphics/draw_pedigree() was unable to write the dotfile %s.' % (dfn) # logging.error('pyp_graphics/draw_pedigree() was unable to draw the dotfile %s.', (dfn)) # Write the graph to an output file. #try: outfile = '%s.%s' % (gfilename,gformat) g.write(outfile, prog='dot', format=gformat) # return 1 #except: # outfile = '%s.%s' % (gfilename,gformat) # if pedobj.kw['messages'] == 'verbose': # print '[ERROR]: pyp_graphics/draw_pedigree() was unable to draw the pedigree %s.' % (outfile) # logging.error('pyp_graphics/draw_pedigree() was unable to draw the pedigree %s.', (outfile)) # return 0 ## # founders_by_year() uses matplotlib -- if available on your system -- to produce a # bar graph of the number (count) of founders in each birthyear. # @param pedobj A PyPedal pedigree object. # @param gfilename The name of the file to which the pedigree should be drawn # @param gtitle The title of the graph. # @retval A 1 for success and a 0 for failure. def plot_founders_by_year(pedobj, gfilename='founders_by_year', gtitle='Founders by Birthyear'): """ founders_by_year() uses matplotlib -- if available on your system -- to produce a bar graph of the number (count) of founders in each birthyear. """ try: import matplotlib matplotlib.use('Agg') import pylab except ImportError: if pedobj.kw['messages'] == 'verbose': print '[ERROR]: pyp_graphics/plot_founders_by_year() was unable to import the matplotlib module!' logging.error('pyp_graphics/plot_founders_by_year() was unable to import the matplotlib module!') return 0 fby = pyp_demog.founders_by_year(pedobj) #print fby try: pylab.clf() pylab.bar(fby.keys(),fby.values()) pylab.title(gtitle) pylab.xlabel('Year') pylab.ylabel('Number of founders') plotfile = '%s.png' % (gfilename) #print 'plotfile: ', plotfile myplotfile = open(plotfile,'w') #print 'myplotfile: ', myplotfile pylab.savefig(myplotfile) myplotfile.close() return 1 except: if pedobj.kw['messages'] == 'verbose': print '[ERROR]: pyp_graphics/plot_founders_by_year() was unable to create the plot \'%s\' (%s.png).' % ( gtitle, gfilename ) #print gtitle, gfilename logging.error('pyp_graphics/plot_founders_by_year() was unable to create the plot \'%s\' (%s.png).', gtitle, gfilename) return 0 ## # founders_pct_by_year() uses matplotlib -- if available on your system -- to produce a # line graph of the frequency (percentage) of founders in each birthyear. # @param pedobj A PyPedal pedigree object. # @param gfilename The name of the file to which the pedigree should be drawn # @param gtitle The title of the graph. # @retval A 1 for success and a 0 for failure. def plot_founders_pct_by_year(pedobj, gfilename='founders_pct_by_year', gtitle='Founders by Birthyear'): """ founders_pct_by_year() uses matplotlib -- if available on your system -- to produce a line graph of the frequency (percentage) of founders in each birthyear. """ try: import matplotlib matplotlib.use('Agg') import pylab except ImportError: if pedobj.kw['messages'] == 'verbose': print '[ERROR]: pyp_graphics/plot_founders_pct_by_year() was unable to import the matplotlib module!' logging.error('pyp_graphics/plot_founders_pct_by_year() was unable to import the matplotlib module!') return 0 fby = pyp_demog.founders_by_year(pedobj) _freqdict = {} for _k in fby.keys(): _freqdict[_k] = float(fby[_k]) / float(pedobj.metadata.num_unique_founders) try: import matplotlib matplotlib.use('Agg') import pylab pylab.clf() pylab.plot(fby.keys(),_freqdict.values()) pylab.title(gtitle) pylab.xlabel('Year') pylab.ylabel('% founders') plotfile = '%s.png' % (gfilename) myplotfile = open(plotfile,'w') pylab.savefig(myplotfile) myplotfile.close() return 1 except: if pedobj.kw['messages'] == 'verbose': print '[ERROR]: pyp_graphics/plot_pct_founders_by_year() was unable to create the plot \'%s\' (%s.png).' % (gtitle,gfilename) logging.error('pyp_graphics/plot_pct_founders_by_year() was unable to create the plot \'%s\' (%s.png).' % (gtitle,gfilename)) return 0 ## # pcolor_matrix_pylab() implements a matlab-like 'pcolor' function to # display the large elements of a matrix in pseudocolor using the Python Imaging # Library. # @param A Input Numpy matrix (such as a numerator relationship matrix). # @param fname Output filename to which to dump the graphics (default 'tmp.png') # @retval A list of NewAnimal() objects; a pedigree metadata object. def pcolor_matrix_pylab(A, fname='pcolor_matrix_matplotlib'): """ pcolor_matrix_pylab() implements a matlab-like 'pcolor' function to display the large elements of a matrix in pseudocolor using the Python Imaging Library. """ try: import matplotlib matplotlib.use('Agg') import pylab except ImportError: if pedobj.kw['messages'] == 'verbose': print '[ERROR]: pyp_graphics/pcolor_matrix_pylab() was unable to import the matplotlib module!' logging.error('pyp_graphics/pcolor_matrix_pylab() was unable to import the matplotlib module!') return 0 try: import numpy pylab.clf() x = pylab.arange(A.shape[0]) X, Y = pylab.meshgrid(x,x) xmin = min(pylab.ravel(X)) xmax = max(pylab.ravel(X)) pylab.xlim(xmin, xmax) ymin = min(pylab.ravel(Y)) ymax = max(pylab.ravel(Y)) pylab.ylim(ymin, ymax) pylab.axis('off') pylab.pcolor(X, Y, pylab.transpose(A))#, shading='flat') pylab.clim(0.0, 1.0) plotfile = '%s.png' % (fname) myplotfile = open(plotfile,'w') pylab.savefig(myplotfile) myplotfile.close() return 1 except: if pedobj.kw['messages'] == 'verbose': print '[ERROR]: pyp_graphics/pcolor_matrix_pylab() was unable to create the plot %s.' % (plotfile) logging.error('pyp_graphics/pcolor_matrix_pylab() was unable to create the plot %s.', (plotfile)) return 0 ## # spy_matrix_pylab() implements a matlab-like 'pcolor' function to # display the large elements of a matrix in pseudocolor using the Python Imaging # Library. # @param A Input Numpy matrix (such as a numerator relationship matrix). # @param fname Output filename to which to dump the graphics (default 'tmp.png') # @retval A list of NewAnimal() objects; a pedigree metadata object. def spy_matrix_pylab(A, fname='spy_matrix_matplotlib'): """ spy_matrix_pylab() implements a matlab-like 'pcolor' function to display the large elements of a matrix in pseudocolor using the Python Imaging Library. """ try: import matplotlib matplotlib.use('Agg') import pylab except ImportError: if pedobj.kw['messages'] == 'verbose': print '[ERROR]: pyp_graphics/spy_matrix_pylab() was unable to import the matplotlib module!' logging.error('pyp_graphics/spy_matrix_pylab() was unable to import the matplotlib module!') return 0 try: import numpy pylab.clf() pylab.spy2(A) plotfile = '%s.png' % (fname) myplotfile = open(plotfile,'w') pylab.savefig(myplotfile) myplotfile.close() return 1 except: if pedobj.kw['messages'] == 'verbose': print '[ERROR]: pyp_graphics/spy_matrix_pylab() was unable to create the plot %s.' % (plotfile) logging.error('pyp_graphics/spy_matrix_pylab() was unable to create the plot %s.', (plotfile)) return 0 ## # plot_line_xy() uses matplotlib -- if available on your system -- to produce a # line graph of the values in a dictionary for each level of key. # @param xydict A Python dictionary of x- (keys) and y-values (values) to be plotted. # @param gfilename The name of the file to which the figure should be written. # @param gtitle The title of the graph. # @param gxlabel The label for the x-axis. # @param gylabel The label for the y-axis. # @param gformat The format in which the output file should be written (JPG|PNG|PS). # @retval A 1 for success and a 0 for failure. def plot_line_xy(xydict, gfilename='plot_line_xy', gtitle='Value by key', gxlabel='X', gylabel='Y', gformat='png'): """ plot_line_xy() uses matplotlib -- if available on your system -- to produce a line graph of the values in a dictionary for each level of key. """ try: import matplotlib matplotlib.use('Agg') import pylab except ImportError: if pedobj.kw['messages'] == 'verbose': print '[ERROR]: pyp_graphics/plot_line_xy() was unable to import the matplotlib module!' logging.error('pyp_graphics/plot_line_xy() was unable to import the matplotlib module!') return 0 if gformat not in ['png']: gformat = 'png' try: pylab.clf() # Dictionary keys are not guaranteed to be listed # in ascending order, so we have to do it. keylist = xydict.keys() keylist.sort() valuelist = [xydict[key] for key in keylist] # Done with the sorting pylab.plot(keylist,valuelist) pylab.title(gtitle) pylab.xlabel(gxlabel) pylab.ylabel(gylabel) plotfile = '%s.%s' % (gfilename, gformat) myplotfile = open(plotfile,'w') pylab.savefig(myplotfile) myplotfile.close() _status = 1 except: if pedobj.kw['messages'] == 'verbose': print '[ERROR]: pyp_graphics/plot_line_xy() was unable to create the plot \'%s\' (%s.%s).' % (gtitle,gfilename,gformat) logging.error('pyp_graphics/plot_line_xy() was unable to create the plot \'%s\' (%s.%s).' % (gtitle,gfilename,gformat)) _status = 0 return _status ## # new_draw_pedigree() uses the pygraphviz to produce a directed graph of your # pedigree with paths of inheritance as edges and animals as nodes. If there # is more than one generation in the pedigree as determind by the "gen" # attributes of the animals in the pedigree, draw_pedigree() will use subgraphs # to try and group animals in the same generation together in the drawing. # @param pedobj A PyPedal pedigree object. # @param gfilename The name of the file to which the pedigree should be drawn # @param gtitle The title of the graph. # @param gformat The format in which the output file should be written (JPG|PNG|PS). # @param gsize The size of the graph: 'f': full-size, 'l': letter-sized page. # @param gdot Whether or not to write the dot code for the pedigree graph to a file (can produce large files). # @param gorient The orientation of the graph: 'p': portrait, 'l': landscape. # @param gdirec Direction of flow from parents to offspring: 'TB': top-bottom, 'LR': left-right, 'RL': right-left. # @param gname Flag indicating whether ID numbers (0) or names (1) should be used to label nodes. # @param garrow Flag indicating whether or not arrowheads should be drawn. # @param gtitloc Indicates if the title be drawn or above ('t') or below ('b') the graph. # @param gtitjust Indicates if the title should be center- ('c'), left- ('l'), or right-justified ('r'). # @param gshowall Draws animals with no links to other ancestors in the pedigree (1) or suppresses them (0). # @param gprog Specify which program should be used to position and render the graph. # @retval A 1 for success and a 0 for failure. def new_draw_pedigree(pedobj, gfilename='pedigree', gtitle='', gformat='jpg', \ gsize='f', gdot=1, gorient='p', gdirec='', gname=0, garrow=1, \ gtitloc='b', gtitjust='c', gshowall=1, gprog='dot'): """ new_draw_pedigree() uses the pygraphviz to produce a directed graph of your pedigree with paths of inheritance as edges and animals as nodes. If there is more than one generation in the pedigree as determined by the "gen" attributes of the animals in the pedigree, draw_pedigree() will use subgraphs to try and group animals in the same generation together in the drawing. Note that there is not (AFAIK) a nice way to get pygraphviz installed on vanilla Windows, so you'll have to make due with draw_pedigree() and plain old dot. """ try: import pygraphviz except ImportError: if pedobj.kw['messages'] == 'verbose': print '[ERROR]: pyp_graphics/new_draw_pedigree() was unable to import the pygraphviz module!' logging.error('pyp_graphics/new_draw_pedigree() was unable to import the pygraphviz module!') return 0 # Maps the 0/1 flags taken by the function and maps them to Python # True/False for settine edge and node attributes. _tf = {0:False, 1:True} from pyp_utils import string_to_table_name _gtitle = string_to_table_name(gtitle) if gtitloc not in ['t','b']: gtitloc = 'b' if gtitjust not in ['c','l','r']: gtitjust = 'c' if not pedobj.kw['pedigree_is_renumbered']: if pedobj.kw['messages'] != 'quiet': print '[GRAPH]: The pedigree that you passed to pyp_graphics/new_draw_pedigree() is not renumbered. Because of this, there may be errors in the rendered pedigree. In order to insure that the pedigree drawing is accurate, you should renumber the pedigree before calling new_draw_pedigree().' logging.error('The pedigree that you passed to pyp_graphics/new_draw_pedigree() is not renumbered. Because of this, there may be errors in the rendered pedigree. In order to insure that the pedigree drawing is accurate, you should renumber the pedigree before calling new_draw_pedigree().') # Create an empty pygraphviz graph using the Agraph class. g = pygraphviz.AGraph(directed=True,strict=False) # I'm not sure if I need to have this here or not. g.graph_attr['type'] = 'graph' # Name the graph -- _gtitle has the characters removed which would cause # dotfile processing to break. g.graph_attr['name'] = _gtitle # Set some properties for the graph. The label attribute is based on the gtitle. # In cases where an empty string, e.g. '', is provided as the gtitle dot engine # processing breaks. In such cases, don't add a label. if gtitle != '': g.graph_attr['label'] = gtitle g.graph_attr['labelloc'] = gtitloc g.graph_attr['labeljust'] = gtitjust # Set the page paper size and writeable area. g.graph_attr['page'] = '8.5,11' g.graph_attr['size'] = '7.5,10' # Set the page orientation. if gorient == 'l': g.graph_attr['orientation'] = 'landscape' else: g.graph_attr['orientation'] = 'portrait' if gsize != 'l': g.graph_attr['ratio'] = 'auto' if gdirec == 'RL': g.graph_attr['rankdir'] = 'RL' elif gdirec == 'LR': g.graph_attr['rankdir'] = 'LR' else: pass # Set a few other graph properties. g.graph_attr['center'] = 'True' g.graph_attr['concentrate'] = 'True' g.graph_attr['fontsize'] = str(pedobj.kw['default_fontsize']) g.graph_attr['ordering'] = 'out' for _m in pedobj.pedigree: # Add a node for the current animal and set some node properties. if gname: _node_name = _m.name else: _node_name = _m.animalID g.add_node(_node_name) n = g.get_node(_node_name) n.attr['shape'] = 'box' n.attr['fontname'] = 'Helvetica' n.attr['fontsize'] = str(pedobj.kw['default_fontsize']) n.attr['height'] = '0.35' #print '[DEBUG]: sex = ', _m.sex if _m.sex == 'M' or _m.sex == 'm': n.attr['shape'] = 'box' elif _m.sex == 'F' or _m.sex == 'f': n.attr['shape'] = 'ellipse' else: n.attr['shape'] = 'octagon' #pass # Add the edges to the parent nodes, if any. if int(_m.sireID) != pedobj.kw['missing_parent']: if gname: _sire_edge = pedobj.pedigree[int(_m.sireID)-1].name else: # Check some outputs -- should I be using the animalID or the # originalID to assign edges? Nodes are based on the animalID, # so edges should also be in order to maintain consistency. #_sire_edge = pedobj.pedigree[int(_m.sireID)-1].originalID _sire_edge = pedobj.pedigree[int(_m.sireID)-1].animalID g.add_edge(_sire_edge,_node_name) if not _tf[garrow]: #e = g.get_edge(_sire_edge,_anim_node) e = g.get_edge(_sire_edge,n) e.attr['dir'] = 'none' if int(_m.damID) != pedobj.kw['missing_parent']: if gname: _dam_edge = pedobj.pedigree[int(_m.damID)-1].name else: _dam_edge = pedobj.pedigree[int(_m.damID)-1].animalID g.add_edge(_dam_edge,_node_name) if not _tf[garrow]: #e = g.get_edge(_dam_edge,_anim_node) e = g.get_edge(_dam_edge,n) e.attr['dir'] = 'none' # For large graphs it is nice to write out the .dot file so that it does # not have to be recreated whenever new_draw_pedigree is called. # Especially when I am debugging. if gdot: dfn = '%s.dot' % (gfilename) try: g.write(dfn) except: if pedobj.kw['messages'] == 'verbose': print '[ERROR]: pyp_graphics/new_draw_pedigree() was unable to write the dotfile %s.' % (dfn) logging.error('pyp_graphics/new_draw_pedigree() was unable to draw the dotfile %s.', (dfn)) # Write the graph to an output file. try: outfile = '%s.%s' % (gfilename,gformat) g.draw(outfile,prog=gprog) return 1 except: outfile = '%s.%s' % (gfilename,gformat) if pedobj.kw['messages'] == 'verbose': print '[ERROR]: pyp_graphics/new_draw_pedigree() was unable to draw the pedigree %s.' % (outfile) logging.error('pyp_graphics/new_draw_pedigree() was unable to draw the pedigree %s.', (outfile)) return 0
gpl-2.0
vaibhavjain-in/d8study
modules/contrib/examples/cron_example/src/Tests/CronExampleTestCase.php
2846
<?php /** * @file * Test case for testing the cron example module. */ /** * @addtogroup cron_example * @{ */ namespace Drupal\cron_example\Tests; use Drupal\simpletest\WebTestBase; /** * Test the functionality for the Cron Example. * * @ingroup cron_example * * @group cron_example * @group examples */ class CronExampleTestCase extends WebTestBase { /** * An editable config object for access to 'examples.cron'. * * @var \Drupal\Core\Config\Config */ protected $cronConfig; /** * Modules to install. * * @var array */ public static $modules = ['cron_example', 'node']; /** * {@inheritdoc} */ public function setUp() { parent::setUp(); // Create user. Search content permission granted for the search block to // be shown. $this->drupalLogin($this->drupalCreateUser(['administer site configuration', 'access content'])); $this->cronConfig = \Drupal::configFactory()->getEditable('examples.cron'); } /** * Create an example node, test block through admin and user interfaces. */ public function testCronExampleBasic() { // Pretend that cron has never been run (even though simpletest seems to // run it once...). \Drupal::state()->set('cron_example.next_execution', 0); $this->drupalGet('examples/cron-example'); // Initial run should cause cron_example_cron() to fire. $post = []; $this->drupalPostForm('examples/cron-example', $post, t('Run cron now')); $this->assertText(t('cron_example executed at')); // Forcing should also cause cron_example_cron() to fire. $post['cron_reset'] = TRUE; $this->drupalPostForm(NULL, $post, t('Run cron now')); $this->assertText(t('cron_example executed at')); // But if followed immediately and not forced, it should not fire. $post['cron_reset'] = FALSE; $this->drupalPostForm(NULL, $post, t('Run cron now')); $this->assertNoText(t('cron_example executed at')); $this->assertText(t('There are currently 0 items in queue 1 and 0 items in queue 2')); $post = [ 'num_items' => 5, 'queue' => 'cron_example_queue_1', ]; $this->drupalPostForm(NULL, $post, t('Add jobs to queue')); $this->assertText('There are currently 5 items in queue 1 and 0 items in queue 2'); $post = [ 'num_items' => 100, 'queue' => 'cron_example_queue_2', ]; $this->drupalPostForm(NULL, $post, t('Add jobs to queue')); $this->assertText('There are currently 5 items in queue 1 and 100 items in queue 2'); $post = []; $this->drupalPostForm('examples/cron-example', $post, t('Run cron now')); $this->assertPattern('/Queue 1 worker processed item with sequence 5 /'); $this->assertPattern('/Queue 2 worker processed item with sequence 100 /'); } } /** * @} End of "addtogroup cron_example". */
gpl-2.0
rdeguzman/mytravelasia-rails
db/migrate/20120424220735_rename_address_on_agodas.rb
197
class RenameAddressOnAgodas < ActiveRecord::Migration def self.up rename_column :agodas, :address_i, :address end def self.down rename_column :agodas, :address, :address_i end end
gpl-2.0
gustavovnicius/vagrant-chef-rails
chef/cookbooks/rbenv/recipes/default.rb
3452
# # Cookbook Name:: rbenv # Recipe:: default # # Author:: Jamie Winsor (<jamie@vialstudios.com>) # # Copyright 2011-2012, Riot Games # # 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. # node.set[:rbenv][:root] = rbenv_root node.set[:ruby_build][:prefix] = node[:rbenv][:root] node.set[:ruby_build][:bin_path] = rbenv_binary_path case node[:platform] when "ubuntu", "debian" include_recipe "apt" end include_recipe "build-essential" include_recipe "git" package "curl" case node[:platform] when "redhat", "centos", "amazon", "oracle" # TODO: add as per "rvm requirements" package "openssl-devel" package "zlib-devel" package "readline-devel" when "ubuntu", "debian" package "libc6-dev" package "automake" package "libtool" # https://github.com/sstephenson/ruby-build/issues/119 # "It seems your ruby installation is missing psych (for YAML # output). To eliminate this warning, please install libyaml and # reinstall your ruby." package 'libyaml-dev' # needed to unpack rubygems package 'zlib1g' package 'zlib1g-dev' # openssl support for ruby package "openssl" package 'libssl-dev' # readline for irb and rails console package "libreadline-dev" # for ruby stdlib rexml and nokogiri # http://nokogiri.org/tutorials/installing_nokogiri.html package "libxml2-dev" package "libxslt1-dev" # better irb support package "ncurses-dev" # for searching packages package "pkg-config" end group node[:rbenv][:group] do members node[:rbenv][:group_users] if node[:rbenv][:group_users] end user node[:rbenv][:user] do shell "/bin/bash" group node[:rbenv][:group] supports :manage_home => node[:rbenv][:manage_home] end directory node[:rbenv][:root] do owner node[:rbenv][:user] group node[:rbenv][:group] mode "0775" end git node[:rbenv][:root] do repository node[:rbenv][:git_repository] reference node[:rbenv][:git_revision] user node[:rbenv][:user] group node[:rbenv][:group] action :sync notifies :create, "template[/etc/profile.d/rbenv.sh]", :immediately end template "/etc/profile.d/rbenv.sh" do source "rbenv.sh.erb" mode "0644" variables( :rbenv_root => node[:rbenv][:root], :ruby_build_bin_path => node[:ruby_build][:bin_path] ) notifies :create, "ruby_block[initialize_rbenv]", :immediately end ruby_block "initialize_rbenv" do block do ENV['RBENV_ROOT'] = node[:rbenv][:root] ENV['PATH'] = "#{node[:rbenv][:root]}/bin:#{node[:ruby_build][:bin_path]}:#{ENV['PATH']}" end action :nothing end # rbenv init creates these directories as root because it is called # from /etc/profile.d/rbenv.sh But we want them to be owned by rbenv # check https://github.com/sstephenson/rbenv/blob/master/libexec/rbenv-init#L71 %w{shims versions plugins}.each do |dir_name| directory "#{node[:rbenv][:root]}/#{dir_name}" do owner node[:rbenv][:user] group node[:rbenv][:group] mode "0775" action [:create] end end
gpl-2.0
blitze/phpBB-ext-sitemaker
language/it/info_acp_settings.php
2939
<?php /** * @copyright (c) 2013 Daniel A. (blitze) * @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License v2 */ /** * @ignore */ if (!defined('IN_PHPBB')) { exit; } if (empty($lang) || !is_array($lang)) { $lang = []; } // DEVELOPERS PLEASE NOTE // // All language files should use UTF-8 as their encoding and the files must not contain a BOM. // // Placeholders can now contain order information, e.g. instead of // 'Page %s of %s' you can (and should) write 'Page %1$s of %2$s', this allows // translators to re-order the output of data while ensuring it remains correct // // You do not need this where single placeholders are used, e.g. 'Message %d' is fine // equally where a string contains only two placeholders which are used to wrap text // in a url you again do not need to specify an order e.g., 'Click %sHERE%s' is fine // // Some characters you may want to copy&paste: // ’ » “ ” … // $lang = array_merge($lang, [ 'ACP_SITEMAKER' => 'SiteMaker', 'ACP_SM_SETTINGS' => 'Impostazioni', 'BLOCKS_CLEANUP' => 'Pulizia Blocchi', 'BLOCKS_CLEANUP_EXPLAIN' => 'I seguenti elementi sono stati trovati per non esistere più o irraggiungibile, e quindi è possibile eliminare tutti i blocchi ad essi associati. Si prega di tenere a mente che alcuni di questi possono essere falsi positivi', 'BLOCKS_CLEANUP_BLOCKS' => 'Blocchi non validi (ad esempio da estensioni disinstallate):', 'BLOCKS_CLEANUP_ROUTES' => 'Pagine Non raggiungibili/Interrotte:', 'BLOCKS_CLEANUP_STYLES' => 'Stili Disinstallati (id):', 'BLOCKS_CLEANUP_SUCCESS' => 'Blocchi purificati con successo', 'FORUM_INDEX_SETTINGS' => 'Impostazioni Indice Forum', 'FORUM_INDEX_SETTINGS_EXPLAIN' => 'Queste impostazioni si applicano solo quando non c\'è nessuna pagina iniziale definita', 'HIDE' => 'Nascondi', 'HIDE_BIRTHDAY' => 'Nascondi sezione Compleanno', 'HIDE_LOGIN' => 'Nascondi casella di accesso', 'HIDE_ONLINE' => 'Nascondi la sezione Whos online', 'LAYOUT_BLOG' => 'Blog', 'LAYOUT_CUSTOM' => 'Personalizzato', 'LAYOUT_HOLYGRAIL' => 'Santo Graal', 'LAYOUT_PORTAL' => 'Portale', 'LAYOUT_PORTAL_ALT' => 'Portale (In Alte)', 'LAYOUT_SETTINGS' => 'Impostazioni Layout', 'LOG_DELETED_BLOCKS_FOR_STYLE' => 'Blocchi Sitemaker eliminati per lo stile mancante con id %s', 'LOG_DELETED_BLOCKS_FOR_ROUTE' => 'Blocchi Sitemaker eliminati per pagine rotte:<br />%s', 'LOG_DELETED_BLOCKS' => 'Blocchi Sitemaker eliminati non validi:<br />%s', 'NAVIGATION_SETTINGS' => 'Impostazioni Di Navigazione', 'SETTINGS_SAVED' => 'Le tue impostazioni sono state salvate', 'SHOW' => 'Mostra', 'SHOW_FORUM_NAV' => 'Mostra \'Forum\' nella barra di navigazione?', 'SHOW_FORUM_NAV_EXPLAIN' => 'Quando una pagina è impostata come pagina iniziale invece dell\'indice del forum, dovremmo visualizzare \'Forum\' nella barra di navigazione', 'SHOW_FORUM_NAV_WITH_ICON' => 'Sì - con icona:', ]);
gpl-2.0
jonbk/headlessdp8
themes/custom/headless/app/src/app/app.component.ts
264
import {Component, OnInit} from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { title = 'app'; ngOnInit() { } }
gpl-2.0
DeanMarkTaylor/discourse
lib/email/styles.rb
6829
# # HTML emails don't support CSS, so we can use nokogiri to inline attributes based on # matchers. # module Email class Styles @@plugin_callbacks = [] def initialize(html) @html = html @fragment = Nokogiri::HTML.fragment(@html) end def self.register_plugin_style(&block) @@plugin_callbacks.push(block) end def add_styles(node, new_styles) existing = node['style'] if existing.present? node['style'] = "#{existing}; #{new_styles}" else node['style'] = new_styles end end def format_basic uri = URI(Discourse.base_url) @fragment.css('img').each do |img| next if img['class'] == 'site-logo' if img['class'] == "emoji" || img['src'] =~ /plugins\/emoji/ img['width'] = 20 img['height'] = 20 else add_styles(img, 'max-width: 694px;') if img['style'] !~ /max-width/ end # ensure all urls are absolute if img['src'] =~ /^\/[^\/]/ img['src'] = "#{Discourse.base_url}#{img['src']}" end # ensure no schemaless urls if img['src'] && img['src'].starts_with?("//") img['src'] = "#{uri.scheme}:#{img['src']}" end end end def format_notification style('.previous-discussion', 'font-size: 17px; color: #444;') style('.notification-date', "text-align:right;color:#999999;padding-right:5px;font-family:'lucida grande',tahoma,verdana,arial,sans-serif;font-size:11px") style('.username', "font-size:13px;font-family:'lucida grande',tahoma,verdana,arial,sans-serif;color:#3b5998;text-decoration:none;font-weight:bold") style('.post-wrapper', "margin-bottom:25px;") style('.user-avatar', 'vertical-align:top;width:55px;') style('.user-avatar img', nil, width: '45', height: '45') style('hr', 'background-color: #ddd; height: 1px; border: 1px;') style('.rtl', 'direction: rtl;') # we can do this but it does not look right # style('#main', 'font-family:"Helvetica Neue", Helvetica, Arial, sans-serif') style('td.body', 'padding-top:5px;', colspan: "2") correct_first_body_margin correct_footer_style reset_tables onebox_styles plugin_styles end def onebox_styles # Links to other topics style('aside.quote', 'border-left: 5px solid #bebebe; background-color: #f1f1f1; padding: 12px 25px 2px 12px; margin-bottom: 10px;') style('aside.quote blockquote', 'border: 0px; padding: 0; margin: 7px 0') style('aside.quote div.info-line', 'color: #666; margin: 10px 0') style('aside.quote .avatar', 'margin-right: 5px') # Oneboxes style('aside.onebox', "padding: 12px 25px 2px 12px; border-left: 5px solid #bebebe; background: #eee; margin-bottom: 10px;") style('aside.onebox img', "max-height: 80%; max-width: 25%; height: auto; float: left; margin-right: 10px; margin-bottom: 10px") style('aside.onebox h3', "border-bottom: 0") style('aside.onebox .source', "margin-bottom: 8px") style('aside.onebox .source a[href]', "color: #333; font-weight: normal") style('aside.clearfix', "clear: both") # Finally, convert all `aside` tags to `div`s @fragment.css('aside, article, header').each do |n| n.name = "div" end # iframes can't go in emails, so replace them with clickable links @fragment.css('iframe').each do |i| begin src_uri = URI(i['src']) # If an iframe is protocol relative, use SSL when displaying it display_src = "#{src_uri.scheme || 'https://'}#{src_uri.host}#{src_uri.path}" i.replace "<p><a href='#{src_uri.to_s}'>#{display_src}</a><p>" rescue URI::InvalidURIError # If the URL is weird, remove it i.remove end end end def format_html style('h3', 'margin: 15px 0 20px 0;') style('hr', 'background-color: #ddd; height: 1px; border: 1px;') style('a', 'text-decoration: none; font-weight: bold; color: #006699;') style('ul', 'margin: 0 0 0 10px; padding: 0 0 0 20px;') style('li', 'padding-bottom: 10px') style('div.digest-post', 'margin-left: 15px; margin-top: 20px; max-width: 694px;') style('div.digest-post h1', 'font-size: 20px;') style('span.footer-notice', 'color:#666; font-size:80%') style('span.post-count', 'margin: 0 5px; color: #777;') style('pre', 'word-wrap: break-word; max-width: 694px;') style('code', 'background-color: #f1f1ff; padding: 2px 5px;') style('pre code', 'display: block; background-color: #f1f1ff; padding: 5px;') style('.featured-topic a', 'text-decoration: none; font-weight: bold; color: #006699; margin-right: 5px') onebox_styles plugin_styles end # this method is reserved for styles specific to plugin def plugin_styles @@plugin_callbacks.each { |block| block.call(@fragment) } end def to_html strip_classes_and_ids replace_relative_urls @fragment.to_html.tap do |result| result.gsub!(/\[email-indent\]/, "<div style='margin-left: 15px'>") result.gsub!(/\[\/email-indent\]/, "</div>") end end def strip_avatars_and_emojis @fragment.css('img').each do |img| if img['src'] =~ /user_avatar/ img.parent['style'] = "vertical-align: top;" if img.parent.name == 'td' img.remove end if img['src'] =~ /plugins\/emoji/ img.replace img['title'] end end return @fragment.to_s end private def replace_relative_urls forum_uri = URI(Discourse.base_url) host = forum_uri.host scheme = forum_uri.scheme @fragment.css('[href]').each do |element| href = element['href'] if href =~ /^\/\/#{host}/ element['href'] = "#{scheme}:#{href}" end end end def correct_first_body_margin @fragment.css('.body p').each do |element| element['style'] = "margin-top:0; border: 0;" end end def correct_footer_style @fragment.css('.footer').each do |element| element['style'] = "color:#666;" element.css('a').each do |inner| inner['style'] = "color:#666;" end end end def strip_classes_and_ids @fragment.css('*').each do |element| element.delete('class') element.delete('id') end end def reset_tables style('table', nil, cellspacing: '0', cellpadding: '0', border: '0') end def style(selector, style, attribs = {}) @fragment.css(selector).each do |element| add_styles(element, style) if style attribs.each do |k,v| element[k] = v end end end end end
gpl-2.0
mzmine/mzmine3
src/main/java/io/github/mzmine/modules/tools/isotopepatternpreview/IsotopePatternPreviewTask.java
7282
/* * Copyright 2006-2021 The MZmine Development Team * * This file is part of MZmine. * * MZmine 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. * * MZmine 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 MZmine; if not, * write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * */ package io.github.mzmine.modules.tools.isotopepatternpreview; import com.google.common.collect.Range; import gnu.trove.list.array.TDoubleArrayList; import io.github.mzmine.datamodel.DataPoint; import io.github.mzmine.datamodel.IsotopePattern; import io.github.mzmine.datamodel.PolarityType; import io.github.mzmine.datamodel.impl.SimpleDataPoint; import io.github.mzmine.datamodel.impl.SimpleIsotopePattern; import io.github.mzmine.gui.chartbasics.simplechart.datasets.ColoredXYDataset; import io.github.mzmine.gui.chartbasics.simplechart.providers.impl.AnyXYProvider; import io.github.mzmine.main.MZmineCore; import io.github.mzmine.modules.tools.isotopeprediction.IsotopePatternCalculator; import io.github.mzmine.taskcontrol.AbstractTask; import io.github.mzmine.taskcontrol.TaskStatus; import io.github.mzmine.util.FormulaUtils; import java.time.Instant; import java.util.Arrays; import java.util.Objects; import java.util.logging.Logger; import javafx.application.Platform; import javax.validation.constraints.NotNull; import org.jfree.data.xy.XYDataset; public class IsotopePatternPreviewTask extends AbstractTask { private static final Logger logger = Logger.getLogger(IsotopePatternPreviewTask.class.getName()); private static final double _2SQRT_2LN2 = 2 * Math.sqrt(2 * Math.log(2)); private final boolean applyFit; SimpleIsotopePattern pattern; IsotopePatternPreviewDialog dialog; private String message; private double minIntensity, mergeWidth; private int charge; private PolarityType polarity; private String formula; private boolean displayResult; public IsotopePatternPreviewTask(String formula, double minIntensity, double mergeWidth, int charge, PolarityType polarity, boolean applyFit, IsotopePatternPreviewDialog dialog) { super(null, Instant.now()); this.minIntensity = minIntensity; this.mergeWidth = mergeWidth; this.charge = charge; this.formula = formula; this.polarity = polarity; this.applyFit = applyFit; this.dialog = dialog; setStatus(TaskStatus.WAITING); pattern = null; displayResult = true; message = "Calculating isotope pattern " + formula + "."; } public void initialise(String formula, double minIntensity, double mergeWidth, int charge, PolarityType polarity) { message = "Wating for parameters"; this.minIntensity = minIntensity; this.mergeWidth = mergeWidth; this.charge = charge; this.formula = formula; this.polarity = polarity; pattern = null; displayResult = true; } @Override public void run() { setStatus(TaskStatus.PROCESSING); assert mergeWidth > 0d; message = "Calculating isotope pattern " + formula + "."; boolean keepComposition = FormulaUtils.getFormulaSize(formula) < 5E3; pattern = (SimpleIsotopePattern) IsotopePatternCalculator.calculateIsotopePattern(formula, minIntensity, mergeWidth, charge, polarity, keepComposition); if (pattern == null) { logger.warning("Isotope pattern could not be calculated."); setStatus(TaskStatus.FINISHED); return; } logger.finest("Pattern " + pattern.getDescription() + " calculated."); if (displayResult) { updateWindow(); } setStatus(TaskStatus.FINISHED); } public void updateWindow() { if (pattern == null) { return; } final XYDataset fit = applyFit ? gaussianIsotopePatternFit(pattern, pattern.getBasePeakMz() / mergeWidth) : null; // Platform.runLater(() -> { if (displayResult) { dialog.taskFinishedUpdate(this, pattern, fit); } }); } public synchronized void setDisplayResult(boolean val) { this.displayResult = val; } @Override public String getTaskDescription() { return message; } @Override public double getFinishedPercentage() { return 0; } /** * f(x) = a * e^( -(x-b)/(2(c^2)) ) */ public XYDataset gaussianIsotopePatternFit(@NotNull final IsotopePattern pattern, final double resolution) { final Double basePeakMz = pattern.getBasePeakMz(); if (basePeakMz == null) { return null; } final double fwhm = basePeakMz / resolution; final double stepSize = fwhm / 10d; final double mzOffset = 1d; final Range<Double> mzRange = pattern.getDataPointMZRange(); final int numPoints = (int) ( ((mzRange.upperEndpoint() + mzOffset) - (mzRange.lowerEndpoint() - mzOffset)) / stepSize); TDoubleArrayList tempMzs = new TDoubleArrayList(); for (int i = 0; i < numPoints; i++) { double mz = mzRange.lowerEndpoint() - mzOffset + i * stepSize; for (int j = 0; j < pattern.getNumberOfDataPoints(); j++) { // no need to calc otherwise if (Math.abs(mz - pattern.getMzValue(j)) < (5 * fwhm)) { tempMzs.add(mz); } } } final double[] mzs = tempMzs.toArray(); final double c = fwhm / _2SQRT_2LN2; final double[] intensities = new double[mzs.length]; Arrays.fill(intensities, 0d); double highest = 1d; for (int i = 0; i < mzs.length; i++) { final double gridMz = mzs[i]; for (int j = 0; j < pattern.getNumberOfDataPoints(); j++) { final double isotopeMz = pattern.getMzValue(j); final double isotopeIntensity = pattern.getIntensityValue(j); final double gauss = getGaussianValue(gridMz, isotopeMz, c); intensities[i] += isotopeIntensity * gauss; } highest = Math.max(highest, intensities[i]); } final double basePeakIntensity = Objects.requireNonNullElse(pattern.getBasePeakIntensity(), 1d); final DataPoint[] dataPoints = new DataPoint[mzs.length]; for (int i = 0; i < dataPoints.length; i++) { intensities[i] = intensities[i] / highest * basePeakIntensity; dataPoints[i] = new SimpleDataPoint(mzs[i], intensities[i]); } return new ColoredXYDataset( new AnyXYProvider(MZmineCore.getConfiguration().getDefaultColorPalette().getAWT(1), "Gaussian fit; Resolution = " + (int) (resolution), dataPoints.length, i -> dataPoints[i].getMZ(), i -> dataPoints[i].getIntensity())); } /** * f(x) = 1 * e^( -(x-b)/(2(c^2)) ) * * @param x the x value. * @param b the center of the curve. * @param c the sigma of the curve. * @return The f(x) value for x. */ public double getGaussianValue(final double x, final double b, final double c) { return Math.exp(-Math.pow((x - b), 2) / (2 * (Math.pow(c, 2)))); } }
gpl-2.0
web0316/WOW
src/bindings/ScriptDev2/scripts/eastern_kingdoms/westfall.cpp
9194
/* Copyright (C) 2006 - 2009 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/> * 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 */ /* ScriptData SDName: Westfall SD%Complete: 90 SDComment: Quest support: 155, 1651 SDCategory: Westfall EndScriptData */ /* ContentData npc_daphne_stilwell npc_defias_traitor EndContentData */ #include "precompiled.h" #include "escort_ai.h" /*###### ## npc_daphne_stilwell ######*/ enum { SAY_DS_START = -1000293, SAY_DS_DOWN_1 = -1000294, SAY_DS_DOWN_2 = -1000295, SAY_DS_DOWN_3 = -1000296, SAY_DS_PROLOGUE = -1000297, SPELL_SHOOT = 6660, QUEST_TOME_VALOR = 1651, NPC_DEFIAS_RAIDER = 6180, EQUIP_ID_RIFLE = 2511 }; struct MANGOS_DLL_DECL npc_daphne_stilwellAI : public npc_escortAI { npc_daphne_stilwellAI(Creature* pCreature) : npc_escortAI(pCreature) { m_uiWPHolder = 0; Reset(); } uint32 m_uiWPHolder; uint32 m_uiShootTimer; void Reset() { if (HasEscortState(STATE_ESCORT_ESCORTING)) { switch(m_uiWPHolder) { case 7: DoScriptText(SAY_DS_DOWN_1, m_creature); break; case 8: DoScriptText(SAY_DS_DOWN_2, m_creature); break; case 9: DoScriptText(SAY_DS_DOWN_3, m_creature); break; } } else m_uiWPHolder = 0; m_uiShootTimer = 0; } void WaypointReached(uint32 uiPoint) { m_uiWPHolder = uiPoint; switch(uiPoint) { case 4: SetEquipmentSlots(false, EQUIP_NO_CHANGE, EQUIP_NO_CHANGE, EQUIP_ID_RIFLE); m_creature->SetSheath(SHEATH_STATE_RANGED); m_creature->HandleEmoteCommand(EMOTE_STATE_USESTANDING_NOSHEATHE); break; case 7: m_creature->SummonCreature(NPC_DEFIAS_RAIDER, -11450.836, 1569.755, 54.267, 4.230, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 30000); m_creature->SummonCreature(NPC_DEFIAS_RAIDER, -11449.697, 1569.124, 54.421, 4.206, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 30000); m_creature->SummonCreature(NPC_DEFIAS_RAIDER, -11448.237, 1568.307, 54.620, 4.206, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 30000); break; case 8: m_creature->SetSheath(SHEATH_STATE_RANGED); m_creature->SummonCreature(NPC_DEFIAS_RAIDER, -11450.836, 1569.755, 54.267, 4.230, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 30000); m_creature->SummonCreature(NPC_DEFIAS_RAIDER, -11449.697, 1569.124, 54.421, 4.206, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 30000); m_creature->SummonCreature(NPC_DEFIAS_RAIDER, -11448.237, 1568.307, 54.620, 4.206, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 30000); m_creature->SummonCreature(NPC_DEFIAS_RAIDER, -11448.037, 1570.213, 54.961, 4.283, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 30000); break; case 9: m_creature->SetSheath(SHEATH_STATE_RANGED); m_creature->SummonCreature(NPC_DEFIAS_RAIDER, -11450.836, 1569.755, 54.267, 4.230, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 30000); m_creature->SummonCreature(NPC_DEFIAS_RAIDER, -11449.697, 1569.124, 54.421, 4.206, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 30000); m_creature->SummonCreature(NPC_DEFIAS_RAIDER, -11448.237, 1568.307, 54.620, 4.206, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 30000); m_creature->SummonCreature(NPC_DEFIAS_RAIDER, -11448.037, 1570.213, 54.961, 4.283, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 30000); m_creature->SummonCreature(NPC_DEFIAS_RAIDER, -11449.018, 1570.738, 54.828, 4.220, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 30000); break; case 10: SetRun(false); break; case 11: DoScriptText(SAY_DS_PROLOGUE, m_creature); break; case 13: SetEquipmentSlots(true); m_creature->SetSheath(SHEATH_STATE_UNARMED); m_creature->HandleEmoteCommand(EMOTE_STATE_USESTANDING_NOSHEATHE); break; case 17: if (Player* pPlayer = GetPlayerForEscort()) pPlayer->GroupEventHappens(QUEST_TOME_VALOR, m_creature); break; } } void AttackStart(Unit* pWho) { if (!pWho) return; if (m_creature->Attack(pWho, false)) { m_creature->AddThreat(pWho, 0.0f); m_creature->SetInCombatWith(pWho); pWho->SetInCombatWith(m_creature); m_creature->GetMotionMaster()->MoveChase(pWho, 30.0f); } } void JustSummoned(Creature* pSummoned) { pSummoned->AI()->AttackStart(m_creature); } void UpdateEscortAI(const uint32 uiDiff) { if (!m_creature->SelectHostilTarget() || !m_creature->getVictim()) return; if (m_uiShootTimer < uiDiff) { m_uiShootTimer = 1000; if (!m_creature->IsWithinDist(m_creature->getVictim(), ATTACK_DISTANCE)) DoCast(m_creature->getVictim(), SPELL_SHOOT); } else m_uiShootTimer -= uiDiff; DoMeleeAttackIfReady(); } }; bool QuestAccept_npc_daphne_stilwell(Player* pPlayer, Creature* pCreature, const Quest* pQuest) { if (pQuest->GetQuestId() == QUEST_TOME_VALOR) { DoScriptText(SAY_DS_START, pCreature); if (npc_daphne_stilwellAI* pEscortAI = dynamic_cast<npc_daphne_stilwellAI*>(pCreature->AI())) pEscortAI->Start(true, true, pPlayer->GetGUID(), pQuest); } return true; } CreatureAI* GetAI_npc_daphne_stilwell(Creature* pCreature) { return new npc_daphne_stilwellAI(pCreature); } /*###### ## npc_defias_traitor ######*/ #define SAY_START -1000101 #define SAY_PROGRESS -1000102 #define SAY_END -1000103 #define SAY_AGGRO_1 -1000104 #define SAY_AGGRO_2 -1000105 #define QUEST_DEFIAS_BROTHERHOOD 155 struct MANGOS_DLL_DECL npc_defias_traitorAI : public npc_escortAI { npc_defias_traitorAI(Creature* pCreature) : npc_escortAI(pCreature) { Reset(); } void WaypointReached(uint32 i) { switch (i) { case 35: SetRun(false); break; case 36: if (Player* pPlayer = GetPlayerForEscort()) DoScriptText(SAY_PROGRESS, m_creature, pPlayer); break; case 44: if (Player* pPlayer = GetPlayerForEscort()) { DoScriptText(SAY_END, m_creature, pPlayer); pPlayer->GroupEventHappens(QUEST_DEFIAS_BROTHERHOOD, m_creature); } break; } } void Aggro(Unit* who) { switch(rand()%2) { case 0: DoScriptText(SAY_AGGRO_1, m_creature, who); break; case 1: DoScriptText(SAY_AGGRO_2, m_creature, who); break; } } void Reset() { } }; bool QuestAccept_npc_defias_traitor(Player* pPlayer, Creature* pCreature, const Quest* pQuest) { if (pQuest->GetQuestId() == QUEST_DEFIAS_BROTHERHOOD) { DoScriptText(SAY_START, pCreature, pPlayer); if (npc_defias_traitorAI* pEscortAI = dynamic_cast<npc_defias_traitorAI*>(pCreature->AI())) pEscortAI->Start(true, true, pPlayer->GetGUID(), pQuest); } return true; } CreatureAI* GetAI_npc_defias_traitor(Creature* pCreature) { return new npc_defias_traitorAI(pCreature); } void AddSC_westfall() { Script *newscript; newscript = new Script; newscript->Name = "npc_daphne_stilwell"; newscript->GetAI = &GetAI_npc_daphne_stilwell; newscript->pQuestAccept = &QuestAccept_npc_daphne_stilwell; newscript->RegisterSelf(); newscript = new Script; newscript->Name = "npc_defias_traitor"; newscript->GetAI = &GetAI_npc_defias_traitor; newscript->pQuestAccept = &QuestAccept_npc_defias_traitor; newscript->RegisterSelf(); }
gpl-2.0
k1moshka/smblrflctr
SymbolReflector2.0/Core/Commands/RemoveSystemFilterCommand.cs
1014
using System; using System.Windows.Input; using Mproject.System.Messaging; namespace SymbolReflector.Core.Commands { /// <summary> /// Команда удаляющая фильтр из системы /// </summary> public class RemoveSystemFilterCommand: UpdatableCommand { public event EventHandler CanExecuteChanged; public RemoveSystemFilterCommand() { CommandUpdater.Register(this); } ~RemoveSystemFilterCommand() { CommandUpdater.Release(this); } public override bool CanExecute(object parameter) { if (KeyboardFilterHandler.FilterApplied) return true; return false; } public override void Execute(object parameter) { FilterConnector.Instance.RemoveFilter(KeyboardFilterHandler.Filter); KeyboardFilterHandler.FilterApplied = false; CommandUpdater.UpdateCommands(); } } }
gpl-2.0
rfdrake/opennms
features/vaadin-node-maps/src/main/java/org/opennms/features/vaadin/nodemaps/internal/gwt/client/event/FilterUpdatedEvent.java
450
package org.opennms.features.vaadin.nodemaps.internal.gwt.client.event; import org.opennms.features.vaadin.nodemaps.internal.gwt.client.ui.controls.search.UpdateEvent; public class FilterUpdatedEvent extends UpdateEvent { public static final String TYPE = "filterUpdated"; protected FilterUpdatedEvent() { } public static final FilterUpdatedEvent createEvent() { return UpdateEvent.createUpdateEvent(TYPE).cast(); } }
gpl-2.0
Vincentjonssonqi/meteor-astronomy-security
lib/module/collections.js
1873
OLC = Astro.Class({ name:'OLC', fields:{ type:{ type:'object', default:function(){ return { name:'public' } } }, read:{ type:'boolean', default:false }, write:{ type:'boolean', default:false } } }); CLC = Astro.Class({ name:'CLC', fields:{ type:{ type:'object', default:function(){ return { name:'public' }; } }, find:{ type:'boolean', default:false }, update:{ type:'boolean', default:false }, insert:{ type:'boolean', default:false }, remove:{ type:'boolean', default:false } } }); ACL = Astro.Class({ name: 'ACL', /* No collection attribute */ fields: { controls: { type: 'array', default: function() { return [new OLC()]; }, nested: 'OLC' } } }); CLP = Astro.Class({ name: 'CLP', /* No collection attribute */ fields: { controls: { type: 'array', default: function() { return [new CLC()]; }, nested: 'CLC' } } }); if (Meteor.isServer){ RoleMappings = new Mongo.Collection('roleMappings'); RoleMappings._ensureIndex( { roleId: 1,userId:1 }, { unique: true } ); RoleMapping = Astro.Class({ name: 'RoleMapping', collection: RoleMappings, fields: { userId:'string', roleId:'string' }, behaviors: ['timestamp'] }); Roles = new Mongo.Collection('roles'); Roles._ensureIndex( { name: 1 }, { unique: true } ); Role = Astro.Class({ name: 'Role', collection: Roles, fields: { name:'string' }, relations:{ usersMapped: { type: 'many', class: 'RoleMapping', local: '_id', foreign: 'roleId' } }, behaviors: ['timestamp'] }); }
gpl-2.0
FDewaleyne/rhns-utils
db-tools/package-consistency-checker.py
21567
#!/usr/bin/python ### # # WARNING DO A BACKUP OF THE DB BEFORE USING THIS SCRIPT # SHOULD ONLY BE USED WHEN ASKED TO BY SUPPORT # ### ### # To the extent possible under law, Red Hat, Inc. has dedicated all copyright to this software to the public domain worldwide, pursuant to the CC0 Public Domain Dedication. # This software is distributed without any warranty. See <http://creativecommons.org/publicdomain/zero/1.0/>. ### __author__ = "Felix Dewaleyne" __credits__ = ["Felix Dewaleyne"] __license__ = "GPL" __version__ = "0.9.1beta" __maintainer__ = "Felix Dewaleyne" __email__ = "fdewaley@redhat.com" __status__ = "prod" # copies a configuration channel from one satellite to another import xmlrpclib, re #connector class -used to initiate a connection to a satellite and to send the proper satellite the proper commands class RHNSConnection: username = None host = None key = None client = None closed = False def __init__(self,username,password,host): """connects to the satellite db with given parameters""" URL = "https://%s/rpc/api" % host self.client = xmlrpclib.Server(URL) self.key = self.client.auth.login(username,password) self.username = username self.host = host pass def close(self): """closes a connection. item can be destroyed then""" self.client.auth.logout(self.key) self.closed = True pass def __exit__(self): """closes connection on exit""" if not self.closed : self.client.auth.logout(self.key) pass def gen_idlist_from_paths(pathfile): """generates the list of package IDs from a file with all paths inside it.""" import sys sys.path.append("/usr/share/rhn") try: import spacewalk.common.rhnConfig as rhnConfig import spacewalk.server.rhnSQL as rhnSQL except ImportError: try: import common.rhnConfig as rhnConfig import server.rhnSQL as rhnSQL except ImportError: print "Couldn't load the libraries required to connect to the db" sys.exit(1) rhnConfig.initCFG() rhnSQL.initDB() query = """ select id from rhnpackage where path like :apath """ #read the file pkglistfile=open(options.file,"rb") pkgline=pkglistfile.readline() pkgpaths=[] while pkgline: pkgpaths.append(pkgline.rstrip("\n")) pkgline=pkglistfile.readline() pkglistfile.close() #init the db, init the list list_ids = [] cursor = rhnSQL.prepare(query) for apath in pkgpaths: cursor.execute(apath=apath) rows = cursor.fetchall_dict() if not rows is None: c = 0 for row in rows: c += 1 list_ids.append(row['id']) print "\r%s of %s" % (str(c), str(len(rows))), print "" else: print "no entry found for " return list_ids def gen_idlist_from_keyid_by_packageid(packageid): """docstring for gen_idlist_from_keyid_by_packageid""" import sys sys.path.append("/usr/share/rhn") try: import spacewalk.common.rhnConfig as rhnConfig import spacewalk.server.rhnSQL as rhnSQL except ImportError: try: import common.rhnConfig as rhnConfig import server.rhnSQL as rhnSQL except ImportError: print "Couldn't load the libraries required to connect to the db" sys.exit(1) rhnConfig.initCFG() rhnSQL.initDB() query = """ select rpka.package_id as "id", rpn.name||'-'||rpe.version||'-'||rpe.release||'.'||rpa.label as package, rpka.key_id, rpk.key_id as signing_key, coalesce((select name from rhnpackageprovider rpp where rpp.id = rpk.provider_id),'Unknown') as provider, rpka.created, rpka.modified from rhnpackagekeyassociation rpka, rhnpackage rp, rhnpackagename rpn, rhnpackagekey rpk, rhnpackageevr rpe, rhnpackagearch rpa, (select key_id from rhnpackagekeyassociation where package_id = """+str(packageid)+""" ) pkginfo where rpka.package_id = rp.id and rpka.key_id = rpk.id and rp.name_id = rpn.id and rp.evr_id = rpe.id and rp.package_arch_id = rpa.id and rpk.id = pkginfo.key_id """ cursor = rhnSQL.prepare(query) cursor.execute() rows = cursor.fetchall_dict() list_ids = [] if not rows is None: c = 0 for row in rows: c += 1 list_ids.append(row['id']) print "\r%s of %s" % (str(c), str(len(rows))), print "" else: print "no packages found" return list_ids def gen_idlist_for_keyid(keyid = None): """generates the list of package IDs that have a certain keyid or no keyid if it is None""" import sys sys.path.append("/usr/share/rhn") try: import spacewalk.common.rhnConfig as rhnConfig import spacewalk.server.rhnSQL as rhnSQL except ImportError: try: import common.rhnConfig as rhnConfig import server.rhnSQL as rhnSQL except ImportError: print "Couldn't load the libraries required to connect to the db" sys.exit(1) rhnConfig.initCFG() rhnSQL.initDB() if keyid != None: # query to select all packages with the same key query = """ select rpka.package_id as "id", rpn.name||'-'||rpe.version||'-'||rpe.release||'.'||rpa.label as package, rpka.key_id, rpk.key_id as signing_key, coalesce((select name from rhnpackageprovider rpp where rpp.id = rpk.provider_id),'Unknown') as provider, rpka.created, rpka.modified from rhnpackagekeyassociation rpka, rhnpackage rp, rhnpackagename rpn, rhnpackagekey rpk, rhnpackageevr rpe, rhnpackagearch rpa where rpka.package_id = rp.id and rpka.key_id = rpk.id and rp.name_id = rpn.id and rp.evr_id = rpe.id and rp.package_arch_id = rpa.id and rpk.id = """+str(keyid)+""" """ else: # query to select all packages with no keyid - will probably not return anything. Will probably never be used, but if it's required it's already there query = """ select rpka.package_id as "id", rpn.name||'-'||rpe.version||'-'||rpe.release||'.'||rpa.label as package, rpka.key_id, rpk.key_id as signing_key, coalesce((select name from rhnpackageprovider rpp where rpp.id = rpk.provider_id),'Unknown') as provider, rpka.created, rpka.modified from rhnpackagekeyassociation rpka, rhnpackage rp, rhnpackagename rpn, rhnpackagekey rpk, rhnpackageevr rpe, rhnpackagearch rpa where rpka.package_id = rp.id and rpka.key_id = rpk.id and rp.name_id = rpn.id and rp.evr_id = rpe.id and rp.package_arch_id = rpa.id and rpk.id = NULL """ cursor = rhnSQL.prepare(query) cursor.execute() rows = cursor.fetchall_dict() list_ids = [] if not rows is None: c = 0 for row in rows: c += 1 list_ids.append(row['id']) print "\r%s of %s" % (str(c), str(len(rows))), print "" else: print "no packages found" return list_ids def gen_idlist_nokeyassoc(channelid=None): """generates the list of packages that have no keyid association""" import sys sys.path.append("/usr/share/rhn") try: import spacewalk.common.rhnConfig as rhnConfig import spacewalk.server.rhnSQL as rhnSQL except ImportError: try: import common.rhnConfig as rhnConfig import server.rhnSQL as rhnSQL except ImportError: print "Couldn't load the libraries required to connect to the db" sys.exit(1) rhnConfig.initCFG() rhnSQL.initDB() if channelid == None: print "checking on all channels" query = """ select rp.id as "id", rc.label as "label", rcpa.key_id as "key-id", rpn.name||'-'||rpe.version||'-'||rpe.release||'.'||rpa.label as "package" from rhnpackage rp left outer join rhnchannelpackage rcp on rcp.package_id = rp.id inner join rhnpackagename rpn on rpn.id = rp.name_id inner join rhnpackageevr rpe on rpe.id = rp.evr_id inner join rhnpackagearch rpa on rpa.id = rp.package_arch_id left outer join rhnchannel rc on rc.id = rcp.channel_id left outer join rhnpackagekeyassociation rcpa on rcpa.package_id = rp.id where rcpa.key_id is null order by rc.label; """ else: print "checking on channel ID %d" % (channelid) query = """ select rp.id as "id", rc.label as "label", rcpa.key_id as "key-id", rpn.name||'-'||rpe.version||'-'||rpe.release||'.'||rpa.label as "package" from rhnpackage rp left outer join rhnchannelpackage rcp on rcp.package_id = rp.id inner join rhnpackagename rpn on rpn.id = rp.name_id inner join rhnpackageevr rpe on rpe.id = rp.evr_id inner join rhnpackagearch rpa on rpa.id = rp.package_arch_id left outer join rhnchannel rc on rc.id = rcp.channel_id left outer join rhnpackagekeyassociation rcpa on rcpa.package_id = rp.id where rcpa.key_id is null and rpc.channel_id = """+str(channelid)+""" order by rc.label; """ cursor = rhnSQL.prepare(query) cursor.execute() rows = cursor.fetchall_dict() list_ids = [] if not rows is None: c = 0 for row in rows: c += 1 list_ids.append(row['id']) print "\r%s of %s" % (str(c), str(len(rows))), print "" else: print "no packages found" return list_ids def gen_idlist(): """generates the list of package IDs""" import sys sys.path.append("/usr/share/rhn") try: import spacewalk.common.rhnConfig as rhnConfig import spacewalk.server.rhnSQL as rhnSQL except ImportError: try: import common.rhnConfig as rhnConfig import server.rhnSQL as rhnSQL except ImportError: print "Couldn't load the libraries required to connect to the db" sys.exit(1) rhnConfig.initCFG() rhnSQL.initDB() # part relevant to path query = """ select id from rhnpackage where path is null """ cursor = rhnSQL.prepare(query) cursor.execute() rows = cursor.fetchall_dict() list_ids = [] print "calculating which packages have no path in the database" if not rows is None: c = 0 for row in rows: c += 1 list_ids.append(row['id']) print "\r%s of %s" % (str(c), str(len(rows))), print "" else: print "no packages with no path" #part relevant to the duplicated packages query = """ select rpka.package_id as "id", rpn.name||'-'||rpe.version||'-'||rpe.release||'.'||rpa.label as package, rpka.key_id, rpk.key_id as signing_key, coalesce((select name from rhnpackageprovider rpp where rpp.id = rpk.provider_id),'Unknown') as provider, rpka.created, rpka.modified from rhnpackagekeyassociation rpka, rhnpackage rp, rhnpackagename rpn, rhnpackagekey rpk, rhnpackageevr rpe, rhnpackagearch rpa, (select package_id,count(*) from rhnpackagekeyassociation group by package_id having count(*) > 1) dups where rpka.package_id = dups.package_id and rpka.package_id = rp.id and rpka.key_id = rpk.id and rp.name_id = rpn.id and rp.evr_id = rpe.id and rp.package_arch_id = rpa.id order by 1, 3 """ print "calculating which packages are duplicates and have unknown providers" cursor = rhnSQL.prepare(query) cursor.execute() rows = cursor.fetchall_dict() if not rows is None: c = 0 for row in rows: c += 1 if not row['id'] in list_ids: list_ids.append(row['id']) print "\r%s of %s" % (str(int(round(c/2))),str(int(len(rows)/2))), print "" else: print "no duplicates with an unknown provider detected" return list_ids def getChannelArch(arch): """returns a value if it is a compatible channel or just None""" if arch in ['ia32', 'ia64', 'sparc', 'alpha', 's390', 's390x', 'iSeries', 'pSeries', 'x86_64', 'ppc', 'sparc-sun-solaris', 'i386-sun-solaris']: return "channel-"+arch else: return None pass def matchArch(arch): """returns what a package architecture should be for that arch value""" # this is likely not going to work for everyone but it should cover most cases. if arch == 'ia32': return ["i686", "i586","i386","noarch"] elif arch == 'ia64': return ["x86_64","noarch"] elif arch == 'x86_64': return ["i386","i586","i686","x86_64","noarch"] #may need exceptions for *-sun-solaris and other archs - don't have any packages for these right now else: #that should work for most cases return [arch, "noarch"] pass def filterPackagesByArch(ids,arch,conn): """filters the packages depending on the architecture selected""" global verbose #grab a list of the valid archs since some architectures selected could accept i386 and x86_64 packages testarchs = matchArch(arch) filtered_ids = [] for id in ids: try: details = conn.client.packages.getDetails(conn.key, id) if verbose: print str(id)+" : "+details['name']+'-'+details['version']+'-'+details['release']+'.'+details['epoch']+'.'+details['arch_label'] if details['arch_label'] in testarchs: filtered_ids.append(id) except: print "unable to find package id "+str(id)+", ignoring it and continueing" pass return filtered_ids def create_channel(prefix, arch, conn, attemptnb=0): """creates a channel of label X+Y for arch Y and prefix X all generated from the details passed""" #to create multiple channels depending on the archs needed. returns the label of the arch created. label = prefix + conn if attemptnb > 0 : label = label + "_" + str(attemptnb) try: conn.client.channel.software.create(conn.key,label,label,arch,"", "sha1") except: cdetails = conn.client.channel.software.getDetails(conn.key,label) if arch == cdetails['arch_name'] : print "unable to create the channel "+options.destChannel if attemptnb < 10: print "attempting to create another channel by appending "+str(attemptnb+1) label = create_channel(label_prefix, arch, conn, attemptnb+1) pass else: print "unable to create another channel after 10 attempts, giving up" raise else: #then the channel exists but has the wrong arch print "unable to create the channel "+options.destChannel+" as arch "+options.arch if attemptnb < 10: print "attempting to create another channel by appending "+str(attemptnb+1) label = create_channel(label_prefix, arch, conn, attemptnb+1) pass else: print "unable to create another channel after 10 attempts, giving up" raise return label #the main function of the program def main(versioninfo): import optparse parser = optparse.OptionParser(description="This program will clone all erratas and packages from the source to the destination as long as they are not already present in the destiation, depending on which settings are used\n REMEMBER TO BACKUP YOUR DATABASE", version="%prog "+versioninfo) parser.add_option("-v", "--verbose", dest="verbose", action="store_true", default=False, help="Enables debug output") global_group = optparse.OptionGroup(parser, "General options", "Can be used in all calls, are not required") global_group.add_option("-c", "--destChannel", dest="destChannel", default="to_delete", type="string", help="Channel to populate with the packages that don't have a path") global_group.add_option("-A", "--arch",dest="arch", default="x86_64", type="string", help="Architecture to use when creating the channel and filtering packages. Defaults to x86_64 which accepts 64 and 32 bits packages") global_group.add_option("--channelid",dest="channelid",default=None, type="int", help="Channel ID to limit package selection to. only implemented for --nokeyassoc right now") #connection details connect_group = optparse.OptionGroup(parser, "Connection options", "Required options") connect_group.add_option("-H", "--host", dest="sathost", type="string", help="hostname of the satellite to use, preferably a fqdn e.g. satellite.example.com", default="localhost") connect_group.add_option("-l", "--login", dest="satuser", type="string", help="User to connect to satellite") connect_group.add_option("-p", "--password", dest="satpwd", type="string", help="Password to connect to satellite") #group for the special actions advanced_group = optparse.OptionGroup(parser, "Special action options", "Use only one of those") advanced_group.add_option("--keyid", dest="keyid", type="int", help="Focuses on all the packages signed by the keyid provided. Only use if you know already what keyid to remove - value to use changes from database to database.") advanced_group.add_option("--nullkeyid", dest="nullkeyid", action="store_true", default=False, help="Focuses on all packages with no key id") advanced_group.add_option("--packageid", dest="packageid", type="int", help="Focuses on the packages with the same signature as this package") advanced_group.add_option("--packagefile", dest="packagefile", type="string", help="Focuses on the packages with a path identical to the entries in a file") advanced_group.add_option("--nokeyassoc", dest="nokeyassoc", action="store_true", default=False, help="Focuses on packages that don't have an entry in the key association table") advanced_group.add_option("--normal", dest="normalrun", action="store_true", default=True, help="Normal run - used by default if no special option is used") parser.add_option_group(connect_group) parser.add_option_group(global_group) parser.add_option_group(advanced_group) (options, args) = parser.parse_args() channel_arch = getChannelArch(options.arch) global verbose verbose = options.verbose if not options.satuser or not options.satpwd: parser.error('username and password are required options.') elif channel_arch == None: parser.error('invalid architecture, accepted values are ia32, ia64, sparc, alpha, s390, s390x, iSeries, pSeries, x86_64, ppc, sparc-sun-solaris or i386-sun-solaris.\nPlease refer to the API documentation on software.channel.create for more information') else: #init conn = RHNSConnection(options.satuser,options.satpwd,options.sathost) channel_arch = getChannelArch(options.arch) try: conn.client.channel.software.create(conn.key,options.destChannel,options.destChannel,options.destChannel,channel_arch,"","sha1") except: cdetails = conn.client.channel.software.getDetails(conn.key,options.destChannel) if options.arch == cdetails['arch_name'] : print "unable to create the channel "+options.destChannel+" ... attempting to continue" pass else: print "unable to create the channel "+options.destChannel+" as arch "+options.arch+" ; stopping here" raise if options.packageid != None : ids = gen_idlist_from_keyid_by_packageid(options.packageid) elif options.nullkeyid : ids = gen_idlist_for_keyid() elif options.keyid != None: ids = gen_idlist_for_keyid(options.keyid) elif options.packagefile != None: ids = gen_idlist_from_paths(options.packagefile) elif options.nokeyassoc: ids = gen_idlist_nokeyassoc(options.channelid) else: #default mode, filter packages present in duplicate as beta and regular but also packages with null paths ids = gen_idlist() if len(ids) == 0: print "nothing to do" else: filtered_ids = filterPackagesByArch(ids,options.arch,conn) print "found "+str(len(ids))+" packages to remove, adding "+str(len(filtered_ids))+" to the channel "+options.destChannel conn.client.channel.software.addPackages(conn.key,options.destChannel,filtered_ids) print "remember to backup before deleting" conn.close() if __name__ == "__main__": main(__version__)
gpl-2.0
akulakov/pyexplore
being.py
21507
"""Being.py""" # Imports {{{ import random import curses import time from operator import itemgetter from pprint import PrettyPrinter from level import level from levels import levels from field import field from item import Item import conf from conf import log from board import Loc from utils import * # }}} # vars {{{ mod = 5 # add to all monsters' stats m = mod beings = { # name : (char, health, attack, defense, color) 'bug' : ('x',4+m,4+m,4+m, 3, ("animal",)), 'gnome' : ('g',5+m,5+m,5+m, 3, ("magical",)), 'elf' : ('e',6+m,6+m,6+m, 3, ("magical",)), 'tiger' : ('t',7+m,7+m,7+m, 4, ("animal",)), 'snake' : ('s',8+m,8+m,8+m, 5, ("animal",)), 'troll' : ('t',9+m,9+m,9+m, 6, ("magical",)), 'atom bug' : ('X',10+m,10+m,10+m,3, ("animal",)), 'elder gnome' : ('G',11+m,11+m,11+m,3, ("magical",)), 'noble elf' : ('E',12+m,12+m,12+m,3, ("magical",)), 'sabre tooth' : ('T',13+m,13+m,13+m,4, ("animal",)), 'royal cobra' : ('S',14+m,14+m,14+m,5, ("animal",)), 'dark oath troll' : ('T',15+m,15+m,15+m,6, ("magical",)), 'yaga' : ('Y',31+m,18+m,11+m, 6, ("magical",)), 'kaschey the immortal' : ('K',35+m,24+m,11+m, 6, ("magical",)), 'party' : ('@',35,20,12, 7, ()), 'dog' : ('d',10,10,5,7, ("animal",)), 'hoplite' : ('H',43,13,18, 7, ()), 'fencer' : ('F',33,18,10, 7, ()), 'mage' : ('M',25,15,6, 7, ()), } # don't auto-create these beings special = "dog hoplite fencer mage party".split() # }}} def rand(): """ Return random monster name. If level.num is high, stronger monsters are more likely to be returned. """ while True: being = random.choice( list(beings.keys()) ) # hero's team if being in special: continue health = beings[being][1] if health > random.randrange(40): continue if health > random.randrange(level.num*10): continue return being class Being: """A living being.""" level_points = {2:200, 3:500, 4:1000, 5:2000, 6:4000, 7:8000, 8:16000, 9:32000, 10:64000} def __init__(self, kind, location, index): """ Kind can be 'hero' or 'bug', for example. Location is a pair x,y. """ self.experience = 0 self.refresh_path_counter = 0 # refresh path when 0 self.path_list = None # list of programmed moves self.loc = location self.description = 'being' self.block = True # can't move over us self.program = None # autopilot program self.weapon = None self.armor = None self.alive = True self.auto_move = False self.attack_hero_flag = False # use autopilot to attack the hero self.team = None # if someone else is on this team, don't attack self.hostile = True self.asked = False # asked hero a question, don't ask again self.index = index self.inventory = [] self.level = 1 self.set_kind(kind) # set attack, defense var, etc def __repr__(self): """Return our ascii character.""" return self.char def place(self, loc=None): """Place me somewhere on the map..""" self.loc = loc or self.loc if self.loc: field.set(self.loc, self) def down(self): """ Go down the stairs * save old level, check if lower level exists, load it if it does, * otherwise create it, change current level num """ if not field.contains(self.loc, "down"): field.text.append("Need a staircase to descend.") return cur = levels.current levels.list[cur] = field.fld cur += 1 levels.current = cur if levels.list[cur]: field.fld, down, up = levels.list[cur] else: field.blank() for ltype, lnumbers in conf.level_types.items(): if cur in lnumbers: field.load_map( ltype.replace('_', ' ') ) break level.populate() self.place(level.up) field.full_display() def up(self): """Go up the stairs.""" if not field.contains(self.loc, "up"): field.text.append("Need a staircase to ascend.") return cur = levels.current levels.list[cur] = field.fld, level.down, level.up cur -= 1 field.fld, level.down, level.up = levels.list[cur] field.full_display() def ask(self, being): """Monster asks player some kind of question about science, etc.""" import ask_rquestion if not ask_rquestion.questions: ask_rquestion.load_questions() q = random.choice(ask_rquestion.questions)[1] question = ask_rquestion.ask_text(q) question = list(question) # question[0] = self.kind + ": " + question[0] field.question = question rval = field.ask() if rval is True: # nothing for now, later give money or a random artifact # field.text.append(("%s is content with the answer." % self.kind, 3)) field.text.append("%s is content with the answer." % self.kind) self.hostile = False # self.remove() else: h = being.health hit = random.randint(1,6) if h - hit < 2: hit = h - 2 being.health -= hit tpl = "%s's curiosity unsatisfied, he slaps hero with a textbook for %s HP" field.text.append(tpl % (self.kind, hit)) # field.text.append( (tpl % (self.kind, hit), 5) ) self.asked = True def find_closest_monster(self): """ Used by hero's team. UNUSED Bug: finds closest by straight line even if it's blocked. Returns the monster instance. """ from level import level lst = [] for being in level.monsters: log(repr(self.loc)) log(being, repr(being.loc)) if being.alive: lst.append( (field.distance(self.loc, being.loc), being) ) lst.sort(key=itemgetter(0)) if lst: return lst[0][1] def set_kind(self, kind): """Assign various instance vars.""" self.char, self.health, self.attack_val, self.defense_val, self.color, self.specials = beings[kind] self.max_health = self.health self.kind = kind def heal(self): """Heal thyself, if lucky.""" if random.random() > 0.25: if self.health < self.max_health: self.health += 1 def random_move(self): dir = random.choice(conf.directions) self.move(dir) def attack_closest_monster(self): """Attack closest monster automatically.""" self.auto_move = True dist = field.distance distances = [ (dist(self, m), m) for m in level.monsters if m.hostile ] if not distances: return monster = sorted(distances, key=itemgetter(0)) monster = monster[0][1] path = self.fullpath(monster) if not path: self.auto_move = False return if len(path) == 1: self.attack(monster) self.auto_move = False else: self.move_to(path[0]) def attack_hero(self, target=None): """Attack hero by autopilot.""" if self.hostile: target = target or level.hero self.attack_hero_flag = True log(10) path = self.fullpath(target.loc) log(20) loc = first(path) if loc: self.move_to(Loc(*loc)) def move(self, direction): """ Move in direction. Direction is a curses number corresponding to the direction key (hjkl etc). """ loc = field.get_coords(self.loc, direction) return self.move_to(loc) def move_to(self, loc): """ Move to location. Location is an (x, y) tuple. """ move_result = None if loc != self.loc: move_result = field.set(loc, self) if move_result == 3: self.program = None if move_result in (1, 4): # redraw cell where we just were field.pop(self.loc) field.redraw(self.loc) # paint us on a new cell self.loc = loc field.scr.move(loc.y-1, loc.x-1) # ?? field.redraw(loc) # pick up items items = field[loc] being = level.hoplite if self.kind=="party" else self for item in items: # pick up armor if item.kind == 'armor': if not self.armor or self.armor.defense >= item.defense: being.inventory.append(self.armor) being.armor = item field.remove(loc, item) field.text.append('%s picked up %s armor' % (being.kind, item.description)) self.program = None # pick up weapons elif item.kind == 'weapon': if not self.weapon or self.weapon.attack >= item.attack: being.inventory.append(self.weapon) being.weapon = item field.remove(loc, item) field.text.append('%s picked up %s' % (being.kind, item.description)) self.program = None if len(items) > 1: if any( [ i!=self or i.kind!="empty" for i in items ] ): self.program = None field.display() return move_result def fullpath(self, loc): """ Build shortest path using field.vertices if direct path is blocked. First try to find path without vertices that surround each monster. Then with one vertice for each monster. Then with all vertices. """ if self.path_list and (self.refresh_path_counter > 0): self.refresh_path_counter -= 1 self.path_list = self.path_list[1:] return self.path_list origin = self.loc path = field.path(origin, loc) # save time, set refresh counter and only re-gen path when it's 0 if self.path_list: if len(self.path_list) > 10: self.refresh_path_counter = 4 seed1 = random.choice(range(3,5)) seed2 = random.choice(range(2,4)) self.refresh_path_counter = len(self.path_list)/seed1 - seed2 self.path_list = field.fullpath(origin, loc) return self.path_list def enter_tactical(self, target): """Enter tactical mode.""" if self.team == "monsters": level.attacking_monster = level.monsters.index(self) am_kind = self.kind if target.team == "monsters": log("attack() - target: %s %s" % (target.kind, target)) log("attack() - level.monsters: %s" % str(level.monsters)) level.attacking_monster = level.monsters.index(target) am_kind = target.kind log("level.attacking_monster: %s" % level.attacking_monster) level.save_monsters = deepcopy(level.monsters) log("level.save_monsters: %s" % level.save_monsters) cur = levels.current levels.list[cur] = field.fld, level.down, level.up field.load_map("local") if conf.xmax<10: field.blank() conf.mode = "tactical" level.populate(am_kind) while True: loc = field.random() if not field.next_to(loc, "wall"): break level.hoplite.place(loc) # very rarely a hero may be placed next to a wall, for hero in [level.fencer, level.mage]: for x in range(100): max_dist = random.randint(1,8) rloc = field.random() if (field.distance(loc, rloc) <= max_dist) and not field.next_to(rloc, "wall"): break hero.place(rloc) field.full_display() def attack(self, target): """Attack target.""" log("attack(): self.kind, target.kind: %s, %s" % (self.kind, target.kind)) if self.team == target.team: return if conf.mode == "strategical": self.enter_tactical(target) return # alert target if target.program: target.program = None attack = self.attack_val # attack with weapon if self.weapon: attack += self.weapon.attack attack_text = ' with %s [%d]' % (self.weapon.kind, self.weapon.attack) else: attack_text = '' # attack armored foe defense = target.defense_val defense_text = '' if target.armor: defense += target.armor.defense defense_text = ' (protected by %s armor [%d])' % (target.armor.description, target.armor.defense) # cast a blow rand = random.random() mod = (attack*rand/1.5 - defense*rand/2.0) mod = max(0, mod) target.health -= round(mod) kill = '' if target.health <= 0: kill = "and killed him" field.text.append('%s%s hit %s%s for %d hp %s' % (self.kind, defense_text, target.kind, attack_text, mod, kill)) # if killed if target.health <= 0: self.experience += target.health + target.attack_val + target.defense_val target.die() def move_program(self, count): """Create a program to move in given direction (count) times.""" log("- - in move_program()") field.status(count) c = field.scr.getch() if 48 <= c <= 57: # example: 22l count = int('%d%d' % (count, c-48)) field.status(count) c = field.scr.getch() if str(c) in conf.directions: self.program = (count, c) def go(self, distance=99): """ Create a direction movement program. example: gk - go up until hit something. """ field.status('g') c = field.scr.getch() if str(c) in conf.directions: self.program = (distance, c) def remove(self): """Remove from field.""" field.remove(self.loc, self) level.last_index += 1 # ??? field.redraw(self.loc) if self in level.monsters: level.monsters.remove(self) def die(self): """Stop living.""" self.alive = 0 field.remove(self.loc, self) corpse = Item('corpse', level.last_index) level.last_index += 1 field.set(self.loc, corpse) field.redraw(self.loc) if self in level.monsters: level.monsters.remove(self) def next_to(self, kind): """Am I close to an object of given type.""" rc = field.next_to(self.loc, kind) log("- next_to(): rc = %s" % rc) return rc def auto_combat(self): """ Try to defeat enemies automatically, without spending time if they're too weak to pose a challenge. Applies to all hero party.. need to move to PyQuest? or Party?.. """ hero_strength = monster_strength = 0 for hero in [level.hoplite, level.fencer, level.mage]: hero_strength += (hero.health + hero.attack_val + hero.defense_val) for monster in level.monsters: monster_strength += (monster.health + monster.attack_val + monster.defense_val) if hero_strength < monster_strength*2: field.text.append("Monsters are far too strong!") return else: conf.auto_combat = True for hero in [level.hoplite, level.fencer, level.mage]: hero.experience += monster_strength ratio = hero_strength / float(monster_strength) if 2 <= ratio < 3: dmg = 0.25 elif 3 <= ratio < 4: dmg = 0.2 elif 4 <= ratio < 5: dmg = 0.15 elif 5 <= ratio < 6: dmg = 0.1 elif 6 <= ratio < 7: dmg = 0.05 elif 7 <= ratio < 8: dmg = 0.03 else: dmg = 0.015 for hero in [level.hoplite, level.fencer, level.mage]: hdmg = dmg * hero.max_health hero.health -= hdmg hero.health = max(hero.health, 2) field.text.append("The party of heroes wins this battle...") def special_attack(self): """ Special - positional attack. Can only be used by mage and depends on position of other team and target. """ log("--- in special_attack()") if not self.kind == "mage": field.text.append("Only mage can perform special attacks.") return for name, a_dict in conf.special_attacks.items(): log("--- checking attack '%s'" % name) a_moves1 = a_dict["ally1"] a_moves2 = a_dict["ally2"] t_moves = a_dict["target"] rotations = [[a_moves1, a_moves2, t_moves]] # add 3 more rotations for i in range(1, 4): am1 = copy(a_moves1) am2 = copy(a_moves2) tm = copy(t_moves) for x in range(i): am1 = field.rotate_moves(am1) am2 = field.rotate_moves(am2) tm = field.rotate_moves(tm) rotations.append([am1, am2, tm]) no = True for (am1, am2, tm) in rotations: log("--- rotation: '%s'" % str((am1, am2, tm))) for a_mv in (am1, am2): log("--- a_mv: '%s'" % str(a_mv)) a_loc = field.get_loc(self.loc, a_mv) log("--- a_loc: '%s'" % str(a_loc)) items = field[a_loc] no = True for i in items: log("--- w.kind: '%s'" % str(w.kind)) if i.kind in ("hoplite", "fencer"): no = False if no: log("no!") break else: log("pass!") t_loc = field.get_loc(self.loc, tm) items = field[t_loc] no = True monster = None for i in items: if i.alive and (i.team == "monsters"): monster = i if name.startswith("arrow"): if "magical" in monster.specials: no = False elif name == "trap": if "animal" in monster.specials: log("--- animal in monster.specials") no = False else: no = False if no: log("target: no!") else: log("target: pass!") break # this special attack can't be done now, let's continue checking other attacks if no: continue log("- special_attack(): name = %s" % name) # we can perform this special attack! if name.startswith("arrow"): dmg = random.randint(5,15) attack_text = " with Arrow of Punishment" elif name == "trap": dmg = random.randint(5,15) attack_text = " with Trap of Hunter" elif name == "arc": dmg = random.randint(5,15) attack_text = " with Arc of Electrocution" monster.health -= dmg kill = "" if monster.health <= 0: kill = "and killed him" field.text.append('%s hit %s%s for %d hp %s' % (self.kind, monster.kind, attack_text, dmg, kill)) if monster.health <= 0: monster.die() def advance(self): """Advance to new level if enough xp.""" if self.experience >= self.level_points[self.level+1]: self.level += 1 self.health += random.randint(1,3) self.defense_val += random.randint(1,3) self.attack_val += random.randint(1,3) field.text.append('%s advanced to level %d' % (self.kind, self.level))
gpl-2.0
Repeid/repeid
common/src/main/java/org/repeid/common/util/Time.java
598
package org.repeid.common.util; import java.util.Date; public class Time { private static int offset; public static int currentTime() { return ((int) (System.currentTimeMillis() / 1000)) + offset; } public static long currentTimeMillis() { return System.currentTimeMillis() + (offset * 1000); } public static Date toDate(int time) { return new Date(((long) time) * 1000); } public static long toMillis(int time) { return ((long) time) * 1000; } public static int getOffset() { return offset; } public static void setOffset(int offset) { Time.offset = offset; } }
gpl-2.0
degami/php-forms-api
examples/plupload.php
2238
<?php ob_start(); require_once '../vendor/autoload.php'; include_once "forms.php"; use Degami\PHPFormsApi as FAPI; session_start(); // Submit function to call when the form is submitted and passes validation. // This is where you would send the email (using PHP mail function) // as this is not a real example I'm just outputting the values for now. function pluploadform_submit(&$form) { $form_values = $form->getValues(); if (is_array($form_values['files_upload']) && count($form_values['files_upload'])>0) { print $value->temppath . " => ".getcwd() . DIRECTORY_SEPARATOR . $value->name."\n"; rename($value->temppath, getcwd() . DIRECTORY_SEPARATOR . $value->name); } } $form = FAPI\FormBuilder::getForm('pluploadform'); ?><!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>PLUpload Form</title> <?php include "header.php";?> <link type="text/css" rel="stylesheet" href="http://www.plupload.com/plupload/js/jquery.ui.plupload/css/jquery.ui.plupload.css" media="screen" /> <link href="http://www.plupload.com/plupload//js/jquery.plupload.queue/css/jquery.plupload.queue.css" type="text/css" rel="stylesheet" media="screen"> <script type="text/javascript" src="http://www.plupload.com/plupload/js/plupload.full.min.js" charset="UTF-8"></script> <script type="text/javascript" src="http://www.plupload.com/plupload/js/jquery.ui.plupload/jquery.ui.plupload.min.js" charset="UTF-8"></script> <script type="text/javascript" src="https://raw.githubusercontent.com/moxiecode/plupload/master/src/jquery.plupload.queue/jquery.plupload.queue.js" charset="UTF-8"></script> </head> <body> <h1>PLUpload Form</h1> <div> <a href="<?php print dirname($_SERVER['PHP_SELF']);?>?clearsession=1">To list</a> | <a href="<?php print $_SERVER['PHP_SELF'];?>">Go back</a> </div> <div id="page"> <pre style="font-size:10px;"><?php $form->process(); ?></pre> <?php if ($form->isSubmitted()) : ?> <!-- if the form was reset during the submit handler we would never see this --> <p>Thanks for submitting the form.</p> <?php else : ?> <?php print $form->render(); ?> <?php endif; ?> <?php include "footer.php";?> </div> </body> </html>
gpl-2.0
virtUOS/courseware
controllers/export.php
2860
<?php use Mooc\Export\XmlExport; /** * Controller to export a courseware block tree. * * @author Christian Flothmann <christian.flothmann@uos.de> */ class ExportController extends CoursewareStudipController { public function before_filter(&$action, &$args) { parent::before_filter($action, $args); if (!$this->container['current_user']->canCreate($this->container['current_courseware'])) { throw new Trails_Exception(401); } } public function index_action() { // create a temporary directory $tempDir = $GLOBALS['TMP_PATH'].'/'.uniqid(); mkdir($tempDir); // dump the XML to the filesystem $export = new XmlExport($this->plugin->getBlockFactory()); $courseware = $this->container['current_courseware']; foreach ($courseware->getFiles() as $file) { if (trim($file['url']) !== '') { continue; } $destination = $tempDir . '/' . $file['id']; if (!is_dir($destination) && file_exists($file['path'])) { mkdir($destination); copy($file['path'], $destination.'/'.$file['filename']); } } if (Request::submitted('plaintext')) { $this->response->add_header('Content-Type', 'text/xml;charset=utf-8'); $this->render_text($export->export($courseware)); return; } file_put_contents($tempDir.'/data.xml', $export->export($courseware)); $zipFile = $GLOBALS['TMP_PATH'].'/'.uniqid().'.zip'; FileArchiveManager::createArchiveFromPhysicalFolder($tempDir, $zipFile); $this->set_layout(null); header('Content-Type: application/zip'); header('Content-Disposition: attachment; filename=courseware.zip'); while (ob_get_level()) { ob_end_flush(); } readfile($zipFile); $this->deleteRecursively($tempDir); $this->deleteRecursively($zipFile); exit; } private function deleteRecursively($path) { if (is_dir($path)) { $files = new RecursiveIteratorIterator( new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::CHILD_FIRST ); foreach ($files as $file) { /** @var SplFileInfo $file */ if (in_array($file->getBasename(), array('.', '..'))) { continue; } if ($file->isFile() || $file->isLink()) { unlink($file->getRealPath()); } else if ($file->isDir()) { rmdir($file->getRealPath()); } } rmdir($path); } else if (is_file($path) || is_link($path)) { unlink($path); } } }
gpl-2.0
i2c2-caj/Letter_Press
Letter_Press/Properties/AssemblyInfo.cs
1400
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Letter_Press")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Letter_Press")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("bd4535b7-48af-41f4-980e-bfba033d687b")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
gpl-2.0
zencart/zc-v1-series
admin/gv_sent.php
8143
<?php /** * @package admin * @copyright Copyright 2003-2019 Zen Cart Development Team * @license http://www.zen-cart.com/license/2_0.txt GNU Public License V2.0 * @version $Id: mc12345678 2019 May 08 Modified in v1.5.6b $ */ require('includes/application_top.php'); require(DIR_WS_CLASSES . 'currencies.php'); $currencies = new currencies(); ?> <!doctype html public "-//W3C//DTD HTML 4.01 Transitional//EN"> <html <?php echo HTML_PARAMS; ?>> <head> <meta http-equiv="Content-Type" content="text/html; charset=<?php echo CHARSET; ?>"> <title><?php echo TITLE; ?></title> <link rel="stylesheet" type="text/css" href="includes/stylesheet.css"> <link rel="stylesheet" type="text/css" href="includes/cssjsmenuhover.css" media="all" id="hoverJS"> <script type="text/javascript" src="includes/menu.js"></script> <script type="text/javascript"> function init() { cssjsmenu('navbar'); if (document.getElementById) { var kill = document.getElementById('hoverJS'); kill.disabled = true; } } </script> </head> <body onload="init()"> <!-- header //--> <?php require(DIR_WS_INCLUDES . 'header.php'); ?> <!-- header_eof //--> <!-- body //--> <table border="0" width="100%" cellspacing="2" cellpadding="2"> <tr> <!-- body_text //--> <td width="100%" valign="top"><table border="0" width="100%" cellspacing="0" cellpadding="2"> <tr> <td width="100%"><table border="0" width="100%" cellspacing="0" cellpadding="0"> <tr> <td class="pageHeading"><?php echo HEADING_TITLE; ?></td> <td class="pageHeading" align="right"><?php echo zen_draw_separator('pixel_trans.gif', HEADING_IMAGE_WIDTH, HEADING_IMAGE_HEIGHT); ?></td> </tr> </table></td> </tr> <tr> <td><table border="0" width="100%" cellspacing="0" cellpadding="0"> <tr> <td valign="top"><table border="0" width="100%" cellspacing="0" cellpadding="2"> <tr class="dataTableHeadingRow"> <td class="dataTableHeadingContent"><?php echo TABLE_HEADING_SENDERS_NAME; ?></td> <td class="dataTableHeadingContent" align="center"><?php echo TABLE_HEADING_VOUCHER_VALUE; ?></td> <td class="dataTableHeadingContent" align="center"><?php echo TABLE_HEADING_VOUCHER_CODE; ?></td> <td class="dataTableHeadingContent" align="right"><?php echo TABLE_HEADING_DATE_SENT; ?></td> <td class="dataTableHeadingContent" align="right"><?php echo TEXT_HEADING_DATE_REDEEMED; ?></td> <td class="dataTableHeadingContent" align="right"><?php echo TABLE_HEADING_ACTION; ?>&nbsp;</td> </tr> <?php $gv_query_raw = "select c.coupon_amount, c.coupon_code, c.coupon_id, et.sent_firstname, et.sent_lastname, et.customer_id_sent, et.emailed_to, et.date_sent, crt.redeem_date, c.coupon_id from " . TABLE_COUPONS . " c left join " . TABLE_COUPON_REDEEM_TRACK . " crt on c.coupon_id= crt.coupon_id, " . TABLE_COUPON_EMAIL_TRACK . " et where c.coupon_id = et.coupon_id " . " and c.coupon_type = 'G' order by date_sent desc"; $gv_split = new splitPageResults($_GET['page'], MAX_DISPLAY_SEARCH_RESULTS, $gv_query_raw, $gv_query_numrows); $gv_list = $db->Execute($gv_query_raw); while (!$gv_list->EOF) { if (((!$_GET['gid']) || (@$_GET['gid'] == $gv_list->fields['coupon_id'])) && (!$gInfo)) { $gInfo = new objectInfo($gv_list->fields); } if ( (is_object($gInfo)) && ($gv_list->fields['coupon_id'] == $gInfo->coupon_id) ) { echo ' <tr class="dataTableRowSelected" onmouseover="this.style.cursor=\'hand\'" onclick="document.location.href=\'' . zen_href_link('gv_sent.php', zen_get_all_get_params(array('gid', 'action')) . 'gid=' . $gInfo->coupon_id . '&action=edit') . '\'">' . "\n"; } else { echo ' <tr class="dataTableRow" onmouseover="this.className=\'dataTableRowOver\';this.style.cursor=\'hand\'" onmouseout="this.className=\'dataTableRow\'" onclick="document.location.href=\'' . zen_href_link('gv_sent.php', zen_get_all_get_params(array('gid', 'action')) . 'gid=' . $gv_list->fields['coupon_id']) . '\'">' . "\n"; } ?> <td class="dataTableContent"><?php echo $gv_list->fields['sent_firstname'] . ' ' . $gv_list->fields['sent_lastname']; ?></td> <td class="dataTableContent" align="center"><?php echo $currencies->format($gv_list->fields['coupon_amount']); ?></td> <td class="dataTableContent" align="center"><?php echo $gv_list->fields['coupon_code']; ?></td> <td class="dataTableContent" align="right"><?php echo zen_date_short($gv_list->fields['date_sent']); ?></td> <td class="dataTableContent" align="right"><?php echo (empty($gv_list->fields['redeem_date']) ? TEXT_INFO_NOT_REDEEMED : zen_date_short($gv_list->fields['redeem_date'])); ?></td> <td class="dataTableContent" align="right"><?php if ( (is_object($gInfo)) && ($gv_list->fields['coupon_id'] == $gInfo->coupon_id) ) { echo zen_image(DIR_WS_IMAGES . 'icon_arrow_right.gif'); } else { echo '<a href="' . zen_href_link(FILENAME_GV_SENT, 'page=' . $_GET['page'] . '&gid=' . $gv_list->fields['coupon_id']) . '">' . zen_image(DIR_WS_IMAGES . 'icon_info.gif', IMAGE_ICON_INFO) . '</a>'; } ?>&nbsp;</td> </tr> <?php $gv_list->MoveNext(); } ?> <tr> <td colspan="5"><table border="0" width="100%" cellspacing="0" cellpadding="2"> <tr> <td class="smallText" valign="top"><?php echo $gv_split->display_count($gv_query_numrows, MAX_DISPLAY_SEARCH_RESULTS, $_GET['page'], TEXT_DISPLAY_NUMBER_OF_GIFT_VOUCHERS); ?></td> <td class="smallText" align="right"><?php echo $gv_split->display_links($gv_query_numrows, MAX_DISPLAY_SEARCH_RESULTS, MAX_DISPLAY_PAGE_LINKS, $_GET['page']); ?></td> </tr> </table></td> </tr> </table></td> <?php $heading = array(); $contents = array(); if (isset($gInfo)) { $heading[] = array('text' => '[' . $gInfo->coupon_id . '] ' . ' ' . $currencies->format($gInfo->coupon_amount)); $redeem = $db->Execute("select * from " . TABLE_COUPON_REDEEM_TRACK . " where coupon_id = '" . $gInfo->coupon_id . "'"); $redeemed = 'No'; if ($redeem->RecordCount() > 0) $redeemed = 'Yes'; $contents[] = array('text' => TEXT_INFO_SENDERS_ID . ' ' . $gInfo->customer_id_sent); $contents[] = array('text' => TEXT_INFO_AMOUNT_SENT . ' ' . $currencies->format($gInfo->coupon_amount)); $contents[] = array('text' => TEXT_INFO_DATE_SENT . ' ' . zen_date_short($gInfo->date_sent)); $contents[] = array('text' => TEXT_INFO_VOUCHER_CODE . ' ' . $gInfo->coupon_code); $contents[] = array('text' => TEXT_INFO_EMAIL_ADDRESS . ' ' . $gInfo->emailed_to); if ($redeemed=='Yes') { $contents[] = array('text' => '<br />' . TEXT_INFO_DATE_REDEEMED . ' ' . zen_date_short($redeem->fields['redeem_date'])); $contents[] = array('text' => TEXT_INFO_IP_ADDRESS . ' ' . $redeem->fields['redeem_ip']); $contents[] = array('text' => TEXT_INFO_CUSTOMERS_ID . ' ' . $redeem->fields['customer_id']); } else { $contents[] = array('text' => '<br />' . TEXT_INFO_NOT_REDEEMED); } if ( (zen_not_null($heading)) && (zen_not_null($contents)) ) { echo ' <td width="25%" valign="top">' . "\n"; $box = new box; echo $box->infoBox($heading, $contents); echo ' </td>' . "\n"; } } ?> </tr> </table></td> </tr> </table></td> <!-- body_text_eof //--> </tr> </table> <!-- body_eof //--> <!-- footer //--> <?php require(DIR_WS_INCLUDES . 'footer.php'); ?> <!-- footer_eof //--> <br /> </body> </html> <?php require(DIR_WS_INCLUDES . 'application_bottom.php'); ?>
gpl-2.0
tofi92/KspModManager
KspModManager/ViewModels/ViewModelBase.cs
4482
using KspModManager.Helper; using KspModManager.Views; using Microsoft.Win32; using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace KspModManager.ViewModels { public abstract class ViewModelBase : INotifyPropertyChanged { #region Deklaration private string mKspPath; private string mStatus; private string mProgressText; private int mProgress = 0; private int test = 0; #endregion #region Properties public bool IsKSPInstalled { get { return (!String.IsNullOrEmpty(mKspPath)) && IsKspInstalled(); } } public string KspPath { get { return (mKspPath); } set { mKspPath = value; RaisePropertyChanged("KspPath"); RaisePropertyChanged("IsKSPInstalled"); } } public string Status { get { return (mStatus); } set { mStatus = value; RaisePropertyChanged("Status"); } } public int Progress { get { return (mProgress); } set { mProgress = value; RaisePropertyChanged("Progress"); } } public string ProgressText { get { return (mProgressText); } set { mProgressText = value; RaisePropertyChanged("ProgressText"); } } #endregion #region Konstruktor public ViewModelBase() { Init(); } #endregion #region Events #endregion #region Diverses private bool IsKspInstalled() { RegistryKey regKey = Registry.CurrentUser; regKey = regKey.OpenSubKey(@"Software\Squad\Kerbal Space Program"); return (regKey != null); } private void GetKspPath() { KspPath = GetKspDirectory().Replace("/", "\\"); } private string GetKspDirectory() { Status = "Looking for KSP Path..."; RegistryKey regKey = Registry.CurrentUser; regKey = regKey.OpenSubKey(@"Software\Valve\Steam"); if (regKey != null) { var path = regKey.GetValue("SteamPath").ToString(); if (Directory.Exists(path + @"\SteamApps\common\Kerbal Space Program")) { Status = "KSP Found!"; return path + @"\SteamApps\common\Kerbal Space Program\GameData"; } else return SearchForOtherDirectories(path); } return ""; } private string SearchForOtherDirectories(string pSteamPath) //todo: Scrape config for this { return ""; } public string GetVersion() { return "0.1.0"; //todo: put that somewhere in config } #endregion #region Virtual Methods public virtual void Init() { Repository.SetSetting("DownloadPath", AppDomain.CurrentDomain.BaseDirectory + "\\Downloads\\"); if (!Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + @"\DisabledMods")) { Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + @"\DisabledMods"); } if (!Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + "\\Downloads\\")) { Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + "\\Downloads\\"); Repository.SetSetting("DownloadPath", AppDomain.CurrentDomain.BaseDirectory + "\\Downloads\\"); } KspPath = Repository.GetSetting<string>("KspPath"); if (String.IsNullOrEmpty(KspPath)) { GetKspPath(); } } #endregion #region INotifyPropertyChanged public event PropertyChangedEventHandler PropertyChanged; protected void RaisePropertyChanged(string pPropertyName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(pPropertyName)); } } #endregion } }
gpl-2.0
Bigjoos/U-232
getrss.php
2848
<?php /** * http://btdev.net:1337/svn/test/Installer09_Beta * Licence Info: GPL * Copyright (C) 2010 BTDev Installer v.1 * A bittorrent tracker source based on TBDev.net/tbsource/bytemonsoon. * Project Leaders: Mindless,putyn. **/ require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'include' . DIRECTORY_SEPARATOR . 'bittorrent.php'); require_once(INCL_DIR . 'user_functions.php'); dbconn(); loggedinorreturn(); $lang = array_merge(load_language('global'), load_language('getrss')); if ($_SERVER['REQUEST_METHOD'] == 'POST') { function mkint($x) { return (int) $x; } $cats = isset($_POST['cats']) ? array_map('mkint', $_POST['cats']) : array(); if (count($cats) == 0) stderr($lang['getrss_error'], $lang['getrss_nocat']); $feed = isset($_POST['feed']) && htmlspecialchars($_POST['feed']) == 'dl' ? 'dl' : 'web'; $rsslink = $INSTALLER09['baseurl'] . '/rss.php?cats=' . join(',', $cats) . ($feed == 'dl' ? '&amp;type=dl' : '') . '&amp;passkey=' . $CURUSER['passkey']; $HTMLOUT = "<div align=\"center\"><h2>{$lang['getrss_result']}</h2><br/> <input type=\"text\" size=\"120\" readonly=\"readonly\" value=\"{$rsslink}\" onclick=\"select()\" /> </div>"; echo (stdhead($lang['getrss_head2']) . $HTMLOUT . stdfoot()); } else { $HTMLOUT = <<<HTML <form action="{$_SERVER['PHP_SELF']}" method="post"> <table width="500" cellpadding="2" cellspacing="0" align="center"> <tr> <td colspan="2" align="center" class="colhead">{$lang['getrss_title']}</td> </tr> <tr> <td align="right" valign="top">{$lang['getrss_cat']}</td><td align="left" width="100%"> HTML; $q1 = sql_query('SELECT id,name,image FROM categories order by id') or sqlerr(__FILE__, __LINE__); $i = 0; while ($a = mysqli_fetch_assoc($q1)) { if ($i % 5 == 0 && $i > 0) $HTMLOUT .= "<br/>"; $HTMLOUT .= "<label for=\"cat_{$a['id']}\"><img src=\"{$INSTALLER09['pic_base_url']}caticons/" . htmlspecialchars($a['image']) . "\" alt=\"" . htmlspecialchars($a['name']) . "\" title=\"" . htmlspecialchars($a['name']) . "\" /><input type=\"checkbox\" name=\"cats[]\" id=\"cat_" . intval($a['id']) . "\" value=\"" . intval($a['id']) . "\" /></label>\n"; $i++; } $HTMLOUT .= <<<HTML </td> </tr> <tr> <td align="right">{$lang['getrss_feed']}</td><td align="left"><input type="radio" checked="checked" name="feed" id="std" value="web"/><label for="std">{$lang['getrss_web']}</label><br/><input type="radio" name="feed" id="dl" value="dl"/><label for="dl">{$lang['getrss_dl']}</label></td> </tr> <tr><td colspan="2" align="center"><input type="submit" value="{$lang['getrss_btn']}" /></td></tr> </table> </form> HTML; echo (stdhead($lang['getrss_head2']) . $HTMLOUT . stdfoot()); } ?>
gpl-2.0
piersharding/udi
hooks/reactivate_form.php
1612
<?php /** * Displays a form for confirmation of UDI account reactivation * an LDIF file. * * @package phpLDAPadmin * @subpackage Page */ /** */ require_once './common.php'; require_once HOOKSDIR.'udi/UdiConfig.php'; require_once HOOKSDIR.'udi/UdiRender.php'; require_once HOOKSDIR.'udi/udi_functions.php'; // get the UDI config $udiconfig = new UdiConfig($app['server']); $request['udiconfig'] = $udiconfig->getConfig(); $udiconfigdn = $udiconfig->getBaseDN(); //var_dump($_POST); //var_dump(get_request('udi_decoration', 'REQUEST')); //exit(0); // setup the page renderer - if not already there - it maybe there because of the POST action if (!isset($request['page'])) { $request['page'] = new UdiRender($app['server']->getIndex(),get_request('template','REQUEST',false,'none')); } // set the headings $request['page']->setContainer($udiconfigdn); $request['page']->accept(); $dn = get_request('dn', 'REQUEST'); $request['page']->drawTitle(sprintf('<b>%s</b>',_('UDI Reactivate ').get_rdn($dn))); $request['page']->drawSubTitle(sprintf('%s: <b>%s</b> %s: <b>%s</b>',_('Server'),$app['server']->getName(), _('Distinguished Name'), $dn)); echo $request['page']->confirmationPage(_('User Account'), _('Reactivate'), $dn, _('Are you sure you want to reactivate this UDI account?'), _('Reactivate'), array('server_id' => $app['server']->getIndex(), 'cmd' => 'reactivate', 'dn' => $dn)); ?>
gpl-2.0
wayjwilliams/brca-update
wp-content/themes/dp_blend/js/dp.menu.js
8262
/** * * ------------------------------------------- * Script for the template menu * ------------------------------------------- * **/ (function ($) { "use strict"; var methods = (function () { // private properties and methods go here var c = { bcClass: 'sf-breadcrumb', menuClass: 'sf-js-enabled', anchorClass: 'sf-with-ul', menuArrowClass: 'sf-arrows' }, ios = (function () { var ios = /iPhone|iPad|iPod/i.test(navigator.userAgent); if (ios) { // iOS clicks only bubble as far as body children $(window).load(function () { $('body').children().on('click', $.noop); }); } return ios; })(), wp7 = (function () { var style = document.documentElement.style; return ('behavior' in style && 'fill' in style && /iemobile/i.test(navigator.userAgent)); })(), toggleMenuClasses = function ($menu, o) { var classes = c.menuClass; if (o.cssArrows) { classes += ' ' + c.menuArrowClass; } $menu.toggleClass(classes); }, setPathToCurrent = function ($menu, o) { return $menu.find('li.' + o.pathClass).slice(0, o.pathLevels) .addClass(o.hoverClass + ' ' + c.bcClass) .filter(function () { return ($(this).children(o.popUpSelector).hide().show().length); }).removeClass(o.pathClass); }, toggleAnchorClass = function ($li) { $li.children('a').toggleClass(c.anchorClass); }, toggleTouchAction = function ($menu) { var touchAction = $menu.css('ms-touch-action'); touchAction = (touchAction === 'pan-y') ? 'auto' : 'pan-y'; $menu.css('ms-touch-action', touchAction); }, applyHandlers = function ($menu, o) { var targets = 'li:has(' + o.popUpSelector + ')'; if ($.fn.hoverIntent && !o.disableHI) { $menu.hoverIntent(over, out, targets); } else { $menu .on('mouseenter.superfish', targets, over) .on('mouseleave.superfish', targets, out); } var touchevent = 'MSPointerDown.superfish'; if (!ios) { touchevent += ' touchend.superfish'; } if (wp7) { touchevent += ' mousedown.superfish'; } $menu .on('focusin.superfish', 'li', over) .on('focusout.superfish', 'li', out) .on(touchevent, 'a', o, touchHandler); }, touchHandler = function (e) { var $this = $(this), $ul = $this.siblings(e.data.popUpSelector); if ($ul.length > 0 && $ul.is(':hidden')) { $this.one('click.superfish', false); if (e.type === 'MSPointerDown') { $this.trigger('focus'); } else { $.proxy(over, $this.parent('li'))(); } } }, over = function () { var $this = $(this), o = getOptions($this); clearTimeout(o.sfTimer); $this.siblings().superfish('hide').end().superfish('show'); }, out = function () { var $this = $(this), o = getOptions($this); if (ios) { $.proxy(close, $this, o)(); } else { clearTimeout(o.sfTimer); o.sfTimer = setTimeout($.proxy(close, $this, o), o.delay); } }, close = function (o) { o.retainPath = ($.inArray(this[0], o.$path) > -1); this.superfish('hide'); if (!this.parents('.' + o.hoverClass).length) { o.onIdle.call(getMenu(this)); if (o.$path.length) { $.proxy(over, o.$path)(); } } }, getMenu = function ($el) { return $el.closest('.' + c.menuClass); }, getOptions = function ($el) { return getMenu($el).data('sf-options'); }; return { // public methods hide: function (instant) { if (this.length) { var $this = this, o = getOptions($this); if (!o) { return this; } var not = (o.retainPath === true) ? o.$path : '', $ul = $this.find('li.' + o.hoverClass).add(this).not(not).removeClass(o.hoverClass).children(o.popUpSelector), speed = o.speedOut; if (instant) { $ul.show(); speed = 0; } o.retainPath = false; o.onBeforeHide.call($ul); $ul.stop(true, true).animate(o.animationOut, speed, function () { var $this = $(this); o.onHide.call($this); }); } return this; }, show: function () { var o = getOptions(this); if (!o) { return this; } var $this = this.addClass(o.hoverClass), $ul = $this.children(o.popUpSelector); o.onBeforeShow.call($ul); $ul.stop(true, true).animate(o.animation, o.speed, function () { o.onShow.call($ul); }); return this; }, destroy: function () { return this.each(function () { var $this = $(this), o = $this.data('sf-options'), $hasPopUp; if (!o) { return false; } $hasPopUp = $this.find(o.popUpSelector).parent('li'); clearTimeout(o.sfTimer); toggleMenuClasses($this, o); toggleAnchorClass($hasPopUp); toggleTouchAction($this); // remove event handlers $this.off('.superfish').off('.hoverIntent'); // clear animation's inline display style $hasPopUp.children(o.popUpSelector).attr('style', function (i, style) { return style.replace(/display[^;]+;?/g, ''); }); // reset 'current' path classes o.$path.removeClass(o.hoverClass + ' ' + c.bcClass).addClass(o.pathClass); $this.find('.' + o.hoverClass).removeClass(o.hoverClass); o.onDestroy.call($this); $this.removeData('sf-options'); }); }, init: function (op) { return this.each(function () { var $this = $(this); if ($this.data('sf-options')) { return false; } var o = $.extend({}, $.fn.superfish.defaults, op), $hasPopUp = $this.find(o.popUpSelector).parent('li'); o.$path = setPathToCurrent($this, o); $this.data('sf-options', o); toggleMenuClasses($this, o); toggleAnchorClass($hasPopUp); toggleTouchAction($this); applyHandlers($this, o); $hasPopUp.not('.' + c.bcClass).superfish('hide', true); o.onInit.call(this); }); } }; })(); $.fn.superfish = function (method, args) { if (methods[method]) { return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); } else if (typeof method === 'object' || ! method) { return methods.init.apply(this, arguments); } else { return $.error('Method ' + method + ' does not exist on jQuery.fn.superfish'); } }; $.fn.superfish.defaults = { popUpSelector: 'ul,.sf-mega', // within menu context hoverClass: 'sfHover', pathClass: 'overrideThisToUse', pathLevels: 1, delay: 800, animation: {opacity: 'show'}, animationOut: {opacity: 'hide'}, speed: 'normal', speedOut: 'fast', cssArrows: true, disableHI: false, onInit: $.noop, onBeforeShow: $.noop, onShow: $.noop, onBeforeHide: $.noop, onHide: $.noop, onIdle: $.noop, onDestroy: $.noop }; // soon to be deprecated $.fn.extend({ hideSuperfishUl: methods.hide, showSuperfishUl: methods.show }); })(jQuery); jQuery(document).ready(function(){ "use strict"; jQuery('.megamenu.toright').each(function(i){ var submenu = jQuery(this).find('.submenu:first'); var margin = submenu.width()-jQuery(this).width(); submenu.css('margin-left', -margin); }); jQuery('.megamenu.tocenter').each(function(i){ var submenu = jQuery(this).find('.submenu:first'); var margin = submenu.width()/2; submenu.css('margin-left', -margin); }); jQuery('.dp-mainmenu-toggle').click(function(){ jQuery('#dp-page-box').toggleClass('is-mobile-menu'); jQuery('#dp-mobile-menu').toggleClass('is-mobile-menu'); if(!jQuery('#close-mobile-menu').hasClass('is-mobile-menu')) { setTimeout(function() { jQuery('#close-mobile-menu').toggleClass('is-mobile-menu'); }, 300); } else { jQuery('#close-mobile-menu').removeClass('is-mobile-menu'); } }); jQuery('#close-mobile-menu').click(function() { jQuery('#close-mobile-menu').toggleClass('is-mobile-menu'); jQuery('#dp-page-box').toggleClass('is-mobile-menu'); jQuery('#dp-mobile-menu').toggleClass('is-mobile-menu'); }); }); jQuery(window).resize(function () { "use strict"; if(typeof $DP_TABLET_WIDTH != 'undefined') { if (jQuery(window).width()> $DP_TABLET_WIDTH) { jQuery('#dp-page-box').removeClass('is-mobile-menu'); jQuery('#dp-mobile-menu').removeClass('is-mobile-menu'); } } });
gpl-2.0
vogel/kadu
plugins/auto_hide/translations/auto_hide_ca.ts
1054
<?xml version="1.0" ?><!DOCTYPE TS><TS language="ca" version="2.1"> <context> <name>@default</name> <message> <source>Autohide idle time</source> <translation type="unfinished"/> </message> <message numerus="yes"> <source>%n second(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <source>Buddies list</source> <translation type="unfinished"/> </message> <message> <source>General</source> <translation type="unfinished"/> </message> <message> <source>Buddies window</source> <translation type="unfinished"/> </message> <message> <source>Hide buddy list window when unused</source> <translation type="unfinished"/> </message> </context> <context> <name>AutoHideConfigurationUiHandler</name> <message> <source>Don&apos;t hide</source> <translation type="unfinished"/> </message> </context> </TS>
gpl-2.0
mobile-event-processing/Asper
source/src/com/espertech/esper/core/service/StatementEventTypeRefImpl.java
6505
/* * ************************************************************************************* * Copyright (C) 2008 EsperTech, Inc. All rights reserved. * * http://esper.codehaus.org * * http://www.espertech.com * * ---------------------------------------------------------------------------------- * * The software in this package is published under the terms of the GPL license * * a copy of which has been included with this distribution in the license.txt file. * * ************************************************************************************* */ package com.espertech.esper.core.service; import com.espertech.esper.util.ManagedReadWriteLock; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Set; /** * Service for holding references between statements and their event type use. */ public class StatementEventTypeRefImpl implements StatementEventTypeRef { private static final Log log = LogFactory.getLog(StatementEventTypeRefImpl.class); private final ManagedReadWriteLock mapLock; private final HashMap<String, Set<String>> typeToStmt; private final HashMap<String, Set<String>> stmtToType; /** * Ctor. */ public StatementEventTypeRefImpl() { typeToStmt = new HashMap<String, Set<String>>(); stmtToType = new HashMap<String, Set<String>>(); mapLock = new ManagedReadWriteLock("StatementEventTypeRefImpl", false); } public void addReferences(String statementName, Set<String> eventTypesReferenced) { if (eventTypesReferenced.isEmpty()) { return; } mapLock.acquireWriteLock(); try { for (String reference : eventTypesReferenced) { addReference(statementName, reference); } } finally { mapLock.releaseWriteLock(); } } public void removeReferencesStatement(String statementName) { mapLock.acquireWriteLock(); try { Set<String> types = stmtToType.remove(statementName); if (types != null) { for (String type : types) { removeReference(statementName, type); } } } finally { mapLock.releaseWriteLock(); } } public void removeReferencesType(String name) { mapLock.acquireWriteLock(); try { Set<String> statementNames = typeToStmt.remove(name); if (statementNames != null) { for (String statementName : statementNames) { removeReference(statementName, name); } } } finally { mapLock.releaseWriteLock(); } } public boolean isInUse(String eventTypeName) { mapLock.acquireReadLock(); try { return typeToStmt.containsKey(eventTypeName); } finally { mapLock.releaseReadLock(); } } public Set<String> getStatementNamesForType(String eventTypeName) { mapLock.acquireReadLock(); try { Set<String> types = typeToStmt.get(eventTypeName); if (types == null) { return Collections.EMPTY_SET; } return Collections.unmodifiableSet(types); } finally { mapLock.releaseReadLock(); } } public Set<String> getTypesForStatementName(String statementName) { mapLock.acquireReadLock(); try { Set<String> types = stmtToType.get(statementName); if (types == null) { return Collections.EMPTY_SET; } return Collections.unmodifiableSet(types); } finally { mapLock.releaseReadLock(); } } private void addReference(String statementName, String eventTypeName) { // add to types Set<String> statements = typeToStmt.get(eventTypeName); if (statements == null) { statements = new HashSet<String>(); typeToStmt.put(eventTypeName, statements); } statements.add(statementName); // add to statements Set<String> types = stmtToType.get(statementName); if (types == null) { types = new HashSet<String>(); stmtToType.put(statementName, types); } types.add(eventTypeName); } private void removeReference(String statementName, String eventTypeName) { // remove from types Set<String> statements = typeToStmt.get(eventTypeName); if (statements != null) { if (!statements.remove(statementName)) { log.info("Failed to find statement name '" + statementName + "' in collection"); } if (statements.isEmpty()) { typeToStmt.remove(eventTypeName); } } // remove from statements Set<String> types = stmtToType.get(statementName); if (types != null) { if (!types.remove(eventTypeName)) { log.info("Failed to find event type '" + eventTypeName + "' in collection"); } if (types.isEmpty()) { stmtToType.remove(statementName); } } } /** * For testing, returns the mapping of event type name to statement names. * @return mapping */ protected HashMap<String, Set<String>> getTypeToStmt() { return typeToStmt; } /** * For testing, returns the mapping of statement names to event type names. * @return mapping */ protected HashMap<String, Set<String>> getStmtToType() { return stmtToType; } }
gpl-2.0
jeedom/plugin-datatransfert
desktop/modal/webdav.configuration.php
1784
<?php /* This file is part of Jeedom. * * Jeedom 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 3 of the License, or * (at your option) any later version. * * Jeedom 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 Jeedom. If not, see <http://www.gnu.org/licenses/>. */ if (!isConnect('admin')) { throw new Exception('{{401 - Accès non autorisé}}'); } ?> <div class="form-group"> <label class="col-sm-3 control-label">{{URL}}</label> <div class="col-sm-4"> <input class="eqLogicAttr form-control" data-l1key="configuration" data-l2key="baseUri"/> </div> </div> <div class="form-group"> <label class="col-sm-3 control-label">{{Nom d'utilisateur}}</label> <div class="col-sm-4"> <input class="eqLogicAttr form-control" data-l1key="configuration" data-l2key="userName"/> </div> </div> <div class="form-group"> <label class="col-sm-3 control-label">{{Mot de passe}}</label> <div class="col-sm-4"> <input type="password" class="eqLogicAttr form-control" data-l1key="configuration" data-l2key="password"/> </div> </div> <div class="form-group"> <label class="col-sm-3 control-label">{{Ne pas verifier le certificat SSL}}</label> <div class="col-sm-4"> <input type="checkbox" class="eqLogicAttr form-control bootstrapSwitch" data-l1key="configuration" data-l2key="disableSslVerification"/> </div> </div>
gpl-2.0
ppizarror/Ned-For-Spod
bin/internal/langeditor/_import.py
871
#!/usr/bin/env python # -*- coding: utf-8 -*- #transformer - permite adaptar un exportado traducido a uno válido para hoa #Pablo Pizarro, 2014 import os import sys reload(sys) sys.setdefaultencoding('UTF8') try: namearchive = raw_input("Ingrese el nombre del archivo que desea transformar: ").replace(".txt", "") archivo = open(namearchive+".txt","r") except: print "El archivo no existe!" exit() l = [] nw = [] for i in archivo: l.append(i) for j in range(0,len(l),2): num = l[j].replace("{","").replace("}","").replace("\n","") txt = l[j+1].replace(" ","|") linea = num+" // "+txt nw.append(linea) print "Archivo importado correctamente" archivo.close() archivo2 = open(namearchive+".txt","w") for i in nw: archivo2.write(i) archivo2.close() try: os.remove("_import.pyc") except: pass
gpl-2.0
nicolasconnault/moodle2.0
mod/resource/type/ims/deploy.php
16930
<?php // $Id: deploy.php,v 1.29 2009/03/23 10:13:18 mudrd8mz Exp $ /////////////////////////////////////////////////////////////////////////// // // // NOTICE OF COPYRIGHT // // // // Moodle - Modular Object-Oriented Dynamic Learning Environment // // http://moodle.com // // // // Copyright (C) 1999 onwards Martin Dougiamas http://dougiamas.com // // (C) 2001-3001 Eloy Lafuente (stronk7) http://contiento.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. // // // // 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: // // // // http://www.gnu.org/copyleft/gpl.html // // // /////////////////////////////////////////////////////////////////////////// /*** * This page will deploy an IMS Content Package zip file, * building all the structures and auxiliary files to * work inside a Moodle resource. */ /// Required stuff require_once('../../../../config.php'); require_once('../../lib.php'); require_once('resource.class.php'); require_once('../../../../backup/lib.php'); require_once('../../../../lib/filelib.php'); require_once('../../../../lib/xmlize.php'); /// Load request parameters $courseid = required_param ('courseid', PARAM_INT); $cmid = required_param ('cmid', PARAM_INT); $file = required_param ('file', PARAM_PATH); $inpopup = optional_param ('inpopup', 0, PARAM_BOOL); /// Fetch some records from DB $course = $DB->get_record ('course', array('id'=>$courseid)); $cm = get_coursemodule_from_id('resource', $cmid); $resource = $DB->get_record ('resource', array('id'=>$cm->instance)); /// Get some needed strings $strdeploy = get_string('deploy','resource'); /// Instantiate a resource_ims object and modify its navigation $resource_obj = new resource_ims ($cmid); /// Print the header of the page $pagetitle = strip_tags($course->shortname.': '. format_string($resource->name)).': '. $strdeploy; if ($inpopup) { print_header($pagetitle, $course->fullname); } else { $resource_obj->navlinks[] = array('name' => $strdeploy, 'link' => '', 'type' => 'action'); $navigation = build_navigation($resource_obj->navlinks, $cm); print_header($pagetitle, $course->fullname, $navigation, '', '', true, update_module_button($cm->id, $course->id, $resource_obj->strresource)); } /// Security Constraints (sesskey and isteacheredit) if (!confirm_sesskey()) { print_error('confirmsesskeybad', 'error'); } else if (!has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_COURSE, $courseid))) { print_error('onlyeditingteachers', 'error'); } /// /// Main process, where everything is deployed /// /// Set some variables /// Create directories if (!$resourcedir = make_upload_directory($courseid.'/'.$CFG->moddata.'/resource/'.$resource->id)) { print_error('errorcreatingdirectory', 'error', '', $CFG->moddata.'/resource/'.$resource->id); } /// Ensure it's empty if (!delete_dir_contents($resourcedir)) { print_error('errorcleaningdirectory', 'error', '', $resourcedir); } /// Copy files $origin = $CFG->dataroot.'/'.$courseid.'/'.$file; if (!is_file($origin)) { print_error('filenotfound' , 'error', '', $file); } $mimetype = mimeinfo("type", $file); if ($mimetype != "application/zip") { print_error('invalidfiletype', 'error', '', $file); } $resourcefile = $resourcedir.'/'.basename($origin); if (!backup_copy_file($origin, $resourcefile)) { print_error('errorcopyingfiles', 'error'); } /// Unzip files if (!unzip_file($resourcefile, '', false)) { print_error('errorunzippingfiles', 'error'); } /// Check for imsmanifest if (!file_exists($resourcedir.'/imsmanifest.xml')) { print_error('filenotfound', 'error', '', 'imsmanifest.xml'); } /// Load imsmanifest to memory (instead of using a full parser, /// we are going to use xmlize intensively (because files aren't too big) if (!$imsmanifest = ims_file2var ($resourcedir.'/imsmanifest.xml')) { print_error('errorreadingfile', 'error', '', 'imsmanifest.xml'); } /// Check if the first line is a proper one, because I've seen some /// packages with some control characters at the beginning. $inixml = strpos($imsmanifest, '<?xml '); if ($inixml !== false) { if ($inixml !== 0) { //Strip strange chars before "<?xml " $imsmanifest = substr($imsmanifest, $inixml); } } else { print_error('invalidxmlfile', 'error', '', 'imsmanifest.xml'); } /// xmlize the variable $data = xmlize($imsmanifest, 0); /// Extract every manifest present in the imsmanifest file. /// Returns a tree structure. if (!$manifests = ims_extract_manifests($data)) { print_error('nonmeaningfulcontent', 'error'); } /// Process every manifest found in inverse order so every one /// will be able to use its own submanifests. Not perfect because /// teorically this will allow some manifests to use other non-childs /// but this is supposed to be /// Detect if all the manifest share a common xml:base tag $manifest_base = $data['manifest']['@']['xml:base']; /// Parse XML-metadata /// Skip this for now (until a proper METADATA container was created in Moodle). /// Parse XML-content package data /// First we select an organization an load all the items if (!$items = ims_process_organizations($data['manifest']['#']['organizations']['0'])) { print_error('nonmeaningfulcontent', 'error'); } /// Detect if all the resources share a common xml:base tag $resources_base = $data['manifest']['#']['resources']['0']['@']['xml:base']; /// Now, we load all the resources available (keys are identifiers) if (!$resources = ims_load_resources($data['manifest']['#']['resources']['0']['#']['resource'], $manifest_base, $resources_base)) { print_error('nonmeaningfulcontent', 'error'); } ///Now we assign to each item, its resource (by identifier) foreach ($items as $key=>$item) { if (!empty($resources[$item->identifierref])) { $items[$key]->href = $resources[$item->identifierref]; } else { $items[$key]->href = ''; } } /// Create the INDEX (moodle_inx.ser - where the order of the pages are stored serialized) file if (!ims_save_serialized_file($resourcedir.'/moodle_inx.ser', $items)) { print_error('errorcreatingfile', 'error', '', 'moodle_inx.ser'); } /// Create the HASH file (moodle_hash.ser - where the hash of the ims is stored serialized) file $hash = $resource_obj->calculatefilehash($resourcefile); if (!ims_save_serialized_file($resourcedir.'/moodle_hash.ser', $hash)) { print_error('errorcreatingfile', 'error', '', 'moodle_hash.ser'); } /// End button (go to view mode) echo '<center>'; print_simple_box(get_string('imspackageloaded', 'resource'), 'center'); $link = $CFG->wwwroot.'/mod/resource/view.php'; $options['r'] = $resource->id; $label = get_string('viewims', 'resource'); $method = 'post'; print_single_button($link, $options, $label, $method); echo '</center>'; /// /// End of main process, where everything is deployed /// /// Print the footer of the page print_footer(); /// /// Common and useful functions used by the body of the script /// /*** This function will return a tree of manifests (xmlized) as they are * found and extracted from one manifest file. The first manifest in the * will be the main one, while the rest will be submanifests. In the * future (when IMS CP suppors it, external submanifest will be detected * and retrieved here too). See IMS specs for more info. */ function ims_extract_manifests($data) { $manifest = new stdClass; //To store found manifests in a tree structure /// If there are some manifests if (!empty($data['manifest'])) { /// Add manifest to results array $manifest->data = $data['manifest']; /// Look for submanifests $submanifests = ims_extract_submanifests($data['manifest']['#']); /// Add them as child if (!empty($submanifests)) { $manifest->childs = $submanifests; } } /// Return tree of manifests found return $manifest; } /* This function will search recursively for submanifests returning an array * containing them (xmlized) following a tree structure. */ function ims_extract_submanifests($data) { $submanifests = array(); //To store found submanifests /// If there are some manifests if (!empty($data['manifest'])) { /// Get them foreach ($data['manifest'] as $submanifest) { /// Create a new submanifest object $submanifest_object = new stdClass; $submanifest_object->data = $submanifest; /// Look for more submanifests recursively $moresubmanifests = ims_extract_submanifests($submanifest['#']); /// Add them to results array if (!empty($moresubmanifests)) { $submanifest_object->childs = $moresubmanifests; } /// Add submanifest object to results array $submanifests[] = $submanifest_object; } } /// Return array of manifests found return $submanifests; } /*** This function will return an ordered and nested array of items * that is a perfect representation of the prefered organization */ function ims_process_organizations($data) { global $CFG; /// Get the default organization $default_organization = $data['@']['default']; debugging('default_organization: '.$default_organization); /// Iterate (reverse) over organizations until we find the default one if (empty($data['#']['organization'])) { /// Verify <organization> exists return false; } $count_organizations = count($data['#']['organization']); debugging('count_organizations: '.$count_organizations); $current_organization = $count_organizations - 1; while ($current_organization >= 0) { /// Load organization and check it $organization = $data['#']['organization'][$current_organization]; if ($organization['@']['identifier'] == $default_organization) { $current_organization = -1; //Match, so exit. } $current_organization--; } /// At this point we MUST have the final organization debugging('final organization: '.$organization['#']['title'][0]['#']); if (empty($organization)) { return false; //Error, no organization found } /// Extract items map from organization $items = $organization['#']['item']; if (empty($organization['#']['item'])) { /// Verify <item> exists return false; } if (!$itemmap = ims_process_items($items)) { return false; //Error, no items found } return $itemmap; } /*** This function gets the xmlized representation of the items * and returns an array of items, ordered, with level and info */ function ims_process_items($items, $level = 1, $id = 1, $parent = 0) { global $CFG; $itemmap = array(); /// Iterate over items from start to end $count_items = count($items); debugging('level '.$level.'-count_items: '.$count_items); $current_item = 0; while ($current_item < $count_items) { /// Load item $item = $items[$current_item]; $obj_item = new stdClass; $obj_item->title = $item['#']['title'][0]['#']; $obj_item->identifier = $item['@']['identifier']; $obj_item->identifierref = $item['@']['identifierref']; $obj_item->id = $id; $obj_item->level = $level; $obj_item->parent = $parent; /// Only if the item has everything if (!empty($obj_item->title) && !empty($obj_item->identifier)) { /// Add to itemmap $itemmap[$id] = $obj_item; debugging('level '.$level.'-id '.$id.'-parent '.$parent.'-'.$obj_item->title); /// Counters go up $id++; /// Check for subitems recursively $subitems = $item['#']['item']; if (count($subitems)) { /// Recursive call $subitemmap = ims_process_items($subitems, $level+1, $id, $obj_item->id); /// Add at the end and counters if necessary if ($count_subitems = count($subitemmap)) { foreach ($subitemmap as $subitem) { /// Add the subitem to the main items array $itemmap[$subitem->id] = $subitem; /// Counters go up $id++; } } } } $current_item++; } return $itemmap; } /*** This function will load an array of resources to be used later. * Keys are identifiers */ function ims_load_resources($data, $manifest_base, $resources_base) { global $CFG; $resources = array(); if (empty($data)) { /// Verify <resource> exists return false; } $count_resources = count($data); debugging('count_resources: '.$count_resources); $current_resource = 0; while ($current_resource < $count_resources) { /// Load resource $resource = $data[$current_resource]; /// Create a new object resource $obj_resource = new stdClass; $obj_resource->identifier = $resource['@']['identifier']; $obj_resource->resource_base = $resource['@']['xml:base']; $obj_resource->href = $resource['@']['href']; if (empty($obj_resource->href)) { $obj_resource->href = $resource['#']['file']['0']['@']['href']; } /// Some packages are poorly done and use \ in roots. This makes them /// not display since the URLs are not valid. if (!empty($obj_resource->href)) { $obj_resource->href = strtr($obj_resource->href, "\\", '/'); } /// Only if the resource has everything if (!empty($obj_resource->identifier) && !empty($obj_resource->href)) { /// Add to resources (identifier as key) /// Depending of $manifest_base, $resources_base and the particular /// $resource_base variable, concatenate them to build the correct href $href_base = ''; if (!empty($manifest_base)) { $href_base = $manifest_base; } if (!empty($resources_base)) { $href_base .= $resources_base; } if (!empty($obj_resource->resource_base)) { $href_base .= $obj_resource->resource_base; } $resources[$obj_resource->identifier] = $href_base.$obj_resource->href; } /// Counters go up $current_resource++; } return $resources; } ?>
gpl-2.0
ProfessorX/Config
.PyCharm30/system/python_stubs/-1247971765/PyQt4/QtXml/QDomElement.py
4271
# encoding: utf-8 # module PyQt4.QtXml # from /usr/lib/python3/dist-packages/PyQt4/QtXml.cpython-34m-x86_64-linux-gnu.so # by generator 1.135 # no doc # no imports from .QDomNode import QDomNode class QDomElement(QDomNode): """ QDomElement() QDomElement(QDomElement) """ def attribute(self, p_str, str_defaultValue=''): # real signature unknown; restored from __doc__ """ QDomElement.attribute(str, str defaultValue='') -> str """ return "" def attributeNode(self, p_str): # real signature unknown; restored from __doc__ """ QDomElement.attributeNode(str) -> QDomAttr """ return QDomAttr def attributeNodeNS(self, p_str, p_str_1): # real signature unknown; restored from __doc__ """ QDomElement.attributeNodeNS(str, str) -> QDomAttr """ return QDomAttr def attributeNS(self, p_str, p_str_1, str_defaultValue=''): # real signature unknown; restored from __doc__ """ QDomElement.attributeNS(str, str, str defaultValue='') -> str """ return "" def attributes(self): # real signature unknown; restored from __doc__ """ QDomElement.attributes() -> QDomNamedNodeMap """ return QDomNamedNodeMap def elementsByTagName(self, p_str): # real signature unknown; restored from __doc__ """ QDomElement.elementsByTagName(str) -> QDomNodeList """ return QDomNodeList def elementsByTagNameNS(self, p_str, p_str_1): # real signature unknown; restored from __doc__ """ QDomElement.elementsByTagNameNS(str, str) -> QDomNodeList """ return QDomNodeList def hasAttribute(self, p_str): # real signature unknown; restored from __doc__ """ QDomElement.hasAttribute(str) -> bool """ return False def hasAttributeNS(self, p_str, p_str_1): # real signature unknown; restored from __doc__ """ QDomElement.hasAttributeNS(str, str) -> bool """ return False def nodeType(self): # real signature unknown; restored from __doc__ """ QDomElement.nodeType() -> QDomNode.NodeType """ pass def removeAttribute(self, p_str): # real signature unknown; restored from __doc__ """ QDomElement.removeAttribute(str) """ pass def removeAttributeNode(self, QDomAttr): # real signature unknown; restored from __doc__ """ QDomElement.removeAttributeNode(QDomAttr) -> QDomAttr """ return QDomAttr def removeAttributeNS(self, p_str, p_str_1): # real signature unknown; restored from __doc__ """ QDomElement.removeAttributeNS(str, str) """ pass def setAttribute(self, p_str, *__args): # real signature unknown; restored from __doc__ with multiple overloads """ QDomElement.setAttribute(str, str) QDomElement.setAttribute(str, int) QDomElement.setAttribute(str, int) QDomElement.setAttribute(str, float) QDomElement.setAttribute(str, int) """ pass def setAttributeNode(self, QDomAttr): # real signature unknown; restored from __doc__ """ QDomElement.setAttributeNode(QDomAttr) -> QDomAttr """ return QDomAttr def setAttributeNodeNS(self, QDomAttr): # real signature unknown; restored from __doc__ """ QDomElement.setAttributeNodeNS(QDomAttr) -> QDomAttr """ return QDomAttr def setAttributeNS(self, p_str, p_str_1, *__args): # real signature unknown; restored from __doc__ with multiple overloads """ QDomElement.setAttributeNS(str, str, str) QDomElement.setAttributeNS(str, str, int) QDomElement.setAttributeNS(str, str, int) QDomElement.setAttributeNS(str, str, float) QDomElement.setAttributeNS(str, str, int) """ pass def setTagName(self, p_str): # real signature unknown; restored from __doc__ """ QDomElement.setTagName(str) """ pass def tagName(self): # real signature unknown; restored from __doc__ """ QDomElement.tagName() -> str """ return "" def text(self): # real signature unknown; restored from __doc__ """ QDomElement.text() -> str """ return "" def __init__(self, QDomElement=None): # real signature unknown; restored from __doc__ with multiple overloads pass
gpl-2.0
mlisondra/kbmurals
administrator/components/com_chronoforms/form_actions/add_system_message/add_system_message.php
1333
<?php /** * CHRONOFORMS version 4.0 * Copyright (c) 2006 - 2011 Chrono_Man, ChronoEngine.com. All rights reserved. * Author: Chrono_Man (ChronoEngine.com) * @license GNU/GPL * Visit http://www.ChronoEngine.com for regular updates and information. **/ defined('_JEXEC') or die('Restricted access'); class CfactionAddSystemMessage{ var $formname; var $formid; var $details = array('title' => 'Add System Message', 'tooltip' => 'Add a global system message to the system, similar to the messages you get when you save a new Joomla article.'); var $group = array('id' => 'form_utilities', 'title' => 'Utilities'); function run($form, $actiondata){ $mainframe =& JFactory::getApplication(); $params = new JParameter($actiondata->params); switch($params->get('type', 'confirm')){ case "warning": JError::raiseWarning(100, $params->get('message', '')); break; case "notice": JError::raiseNotice(100, $params->get('message', '')); break; case "error": JError::raiseError(100, $params->get('message', '')); break; case "confirm": $mainframe->enqueueMessage($params->get('message', '')); break; } } function load($clear){ if($clear){ $action_params = array( 'message' => '', 'type' => 'confirm' ); } return array('action_params' => $action_params); } } ?>
gpl-2.0
lucatume/member-signup-for-wordpress
assets/js/admin.js
260
/*! Member Signup - v0.1.0 * https://github.com/lucatume/member-signup-for-wordpress.git * Copyright (c) 2013; * Licensed GPLv2+ */ (function ( $ ) { "use strict"; $(function () { // Place your administration-specific JavaScript here }); }(jQuery));
gpl-2.0
judgels/uriel
app/org/iatoki/judgels/uriel/contest/contestant/ContestContestantNotFoundException.java
665
package org.iatoki.judgels.uriel.contest.contestant; import org.iatoki.judgels.play.EntityNotFoundException; public final class ContestContestantNotFoundException extends EntityNotFoundException { public ContestContestantNotFoundException() { super(); } public ContestContestantNotFoundException(String s) { super(s); } public ContestContestantNotFoundException(String message, Throwable cause) { super(message, cause); } public ContestContestantNotFoundException(Throwable cause) { super(cause); } @Override public String getEntityName() { return "Contest Contestant"; } }
gpl-2.0
nizaranand/New-Life-Office
dev/wp-content/themes/cruz/includes/shortcodes/visual_shortcodes.php
2566
<?php // Add Shortcode Buttons in Visual Editor add_action('init', 'add_buttons'); // Initialization Function function add_buttons() { if ( current_user_can('edit_posts') && current_user_can('edit_pages') ) { add_filter('mce_external_plugins', 'add_plugins'); add_filter('mce_buttons_3', 'register_buttons'); } } // Register Buttons function register_buttons($buttons) { array_push($buttons, "columns"); array_push($buttons, "frame"); array_push($buttons, "tabs"); array_push($buttons, "tour"); array_push($buttons, "pricing"); array_push($buttons, "accordions"); array_push($buttons, "faq"); array_push($buttons, "toggle"); array_push($buttons, "quote"); array_push($buttons, "pqleft"); array_push($buttons, "pqright"); array_push($buttons, "dropcap"); array_push($buttons, "box"); array_push($buttons, "list"); array_push($buttons, "hr"); array_push($buttons, "btn"); return $buttons; } // Register TinyMCE Plugin function add_plugins($plugin_array) { $plugin_array['columns'] = get_template_directory_uri().'/includes/shortcodes/js/columns.js'; $plugin_array['frame'] = get_template_directory_uri().'/includes/shortcodes/js/frame_sc.js'; $plugin_array['tabs'] = get_template_directory_uri().'/includes/shortcodes/js/tabs_sc.js'; $plugin_array['tour'] = get_template_directory_uri().'/includes/shortcodes/js/tour_sc.js'; $plugin_array['pricing'] = get_template_directory_uri().'/includes/shortcodes/js/pricing_sc.js'; $plugin_array['accordions'] = get_template_directory_uri().'/includes/shortcodes/js/accordions_sc.js'; $plugin_array['faq'] = get_template_directory_uri().'/includes/shortcodes/js/faq_sc.js'; $plugin_array['toggle'] = get_template_directory_uri().'/includes/shortcodes/js/toggle_sc.js'; $plugin_array['quote'] = get_template_directory_uri().'/includes/shortcodes/js/quote_sc.js'; $plugin_array['pqleft'] = get_template_directory_uri().'/includes/shortcodes/js/pqleft_sc.js'; $plugin_array['pqright'] = get_template_directory_uri().'/includes/shortcodes/js/pqright_sc.js'; $plugin_array['dropcap'] = get_template_directory_uri().'/includes/shortcodes/js/dropcap_sc.js'; $plugin_array['box'] = get_template_directory_uri().'/includes/shortcodes/js/box_sc.js'; $plugin_array['list'] = get_template_directory_uri().'/includes/shortcodes/js/list_sc.js'; $plugin_array['hr'] = get_template_directory_uri().'/includes/shortcodes/js/hr_sc.js'; $plugin_array['btn'] = get_template_directory_uri().'/includes/shortcodes/js/btn_sc.js'; return $plugin_array; } ?>
gpl-2.0
vlabatut/totalboumboum
src/org/totalboumboum/ai/v201011/adapter/data/AiState.java
2617
package org.totalboumboum.ai.v201011.adapter.data; /* * Total Boum Boum * Copyright 2008-2014 Vincent Labatut * * This file is part of Total Boum Boum. * * Total Boum Boum 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. * * Total Boum Boum 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 Total Boum Boum. If not, see <http://www.gnu.org/licenses/>. * */ import java.io.Serializable; import org.totalboumboum.ai.v201011.adapter.data.AiStateName; import org.totalboumboum.engine.content.feature.Direction; /** * décrit un état dans lequel un sprite peut se trouver, c'est * à dire essentiellement l'action que le sprite réalise ou qu'il subit. * Cet état est décrit par le nom de cette action, et éventuellement la * direction dans laquelle elle est effectuée (pour les actions orientées * comme le déplacement, par exemple). * * @author Vincent Labatut * * @deprecated * Ancienne API d'IA, à ne plus utiliser. */ public interface AiState extends Serializable { ///////////////////////////////////////////////////////////////// // NAME ///////////////////////////////////////////// ///////////////////////////////////////////////////////////////// /** * renvoie le nom associé à l'état * * @return * nom associé à l'état */ public AiStateName getName(); ///////////////////////////////////////////////////////////////// // DIRECTION ///////////////////////////////////////////// ///////////////////////////////////////////////////////////////// /** * renvoie la direction associée à l'état, * qui peut être NONE, c'est à dire : l'état n'est pas orienté * * @return * direction associée à l'état */ public Direction getDirection(); ///////////////////////////////////////////////////////////////// // TIME ///////////////////////////////////////////// ///////////////////////////////////////////////////////////////// /** * renvoie la durée que le sprite a passé dans l'état courant * * @return * une durée exprimée en ms */ public long getTime(); }
gpl-2.0
florianeck/redmine_multi_hosts
lib/multi_hosts/multi_hosts_helper.rb
388
module MultiHostsHelper def html_title(*args) app_title = @current_multihost.try(:app_title) || Setting.app_title if args.empty? title = @html_title || [] title << @project.name if @project title << app_title unless app_title == title.last title.reject(&:blank?).join(' - ') else @html_title ||= [] @html_title += args end end end
gpl-2.0
rchillyard/Scalaprof
FunctionalProgramming/src/main/scala/edu/neu/coe/csye/_7200/poets/Poets.scala
1421
package edu.neu.coe.csye._7200.poets import scala.xml.{Node, NodeSeq, XML} case class Name(name: String, language: String) { def toXML = <name language={language}>{name}</name> } case class Poet(names: Seq[Name]) { def toXML = <poet>{names map (_.toXML)}</poet> } object Poet { def fromXML(node: Node) = Poet(Name.fromXML(node \ "name")) } object Name { def getLanguage(x: Option[Seq[Node]]) = x match {case Some(Seq(y)) => y.text; case _ => ""} def fromXML(nodes: NodeSeq): Seq[Name] = for { node <- nodes } yield Name(node.text,getLanguage(node.attribute("language"))) } /** * @author scalaprof */ object Poets extends App { import spray.json._ type PoetSeq = Seq[Poet] def toXML(poets: PoetSeq) = poets map {_ toXML} val xml = XML.loadFile("poets.xml") val poets: PoetSeq = for ( poet <- xml \\ "poet" ) yield Poet.fromXML(poet) case class Poets(poets: PoetSeq) object PoetsJsonProtocol extends DefaultJsonProtocol { implicit val nameFormat = jsonFormat2(Name.apply) implicit val poetFormat = ??? // TODO 5 points implicit val poetsFormat = jsonFormat1(Poets) } ??? // TODO 25 points. Write poets out as Json. Show the Json in the console... // ...Read the Json file back as poets1 and write that out as XML. Show it on console. // Show the comparison of the XML file you produced with the poets.xml file (as part of your submission). }
gpl-2.0
cmu-relab/eddy
src/eddy/lang/analysis/ConflictPrinter.java
4737
package eddy.lang.analysis; import java.io.PrintStream; import java.io.PrintWriter; import java.util.TreeMap; import org.semanticweb.owlapi.model.OWLAxiom; import org.semanticweb.owlapi.model.OWLClassExpression; import org.semanticweb.owlapi.model.OWLDataFactory; import org.semanticweb.owlapi.reasoner.OWLReasoner; import eddy.lang.Role; import eddy.lang.Rule.Modality; import eddy.lang.parser.Compiler; import eddy.lang.parser.ParseException; public class ConflictPrinter extends PrintWriter { private static final TreeMap<Modality,String> presentContinous = new TreeMap<Modality,String>(); private static final TreeMap<Modality,String> past = new TreeMap<Modality,String>(); private static final TreeMap<Modality,String> noun = new TreeMap<Modality,String>(); static { presentContinous.put(Modality.PERMISSION, "permits"); presentContinous.put(Modality.OBLIGATION, "requires"); presentContinous.put(Modality.REFRAINMENT, "prohibits"); past.put(Modality.PERMISSION, "permitted"); past.put(Modality.OBLIGATION, "required"); past.put(Modality.REFRAINMENT, "prohibited"); noun.put(Modality.PERMISSION, "permission to"); noun.put(Modality.OBLIGATION, "obligation to"); noun.put(Modality.REFRAINMENT, "prohibition to not"); } public ConflictPrinter(PrintStream stream) { super(stream); } public void print(Conflict c) { println(getMessage(c)); flush(); } public static String getMessage(Conflict c) { String s = "Rule " + c.rule1.id + " is a " + noun.get(c.rule1.modality) + " " + c.rule1.action.toString() + "\n" + "Rule " + c.rule2.id + " is a " + noun.get(c.rule2.modality) + " " + c.rule2.action.toString(); s += "\n" + explain(c); return s; } public static String explain(Conflict c) { String s = "These rules conflict, because "; // explain the conflict based on modality, alone if (c.rule1.modality.isExclusion()) { String act = past.get(c.rule1.modality); if (act == null) { act = "performed"; } s += "rule " + c.rule1.id + " excludes the action " + act + " by rule " + c.rule2.id; } else if (c.rule1.modality.isPermissible()) { String act = presentContinous.get(c.rule1.modality); if (act == null) { act = "performs"; } s += "rule " + c.rule1.id + " " + act + " an action prohibited by rule " + c.rule2.id; } // explain the relationship between the conflicting actions switch (c.type) { case SUBSUMES: s += "Rule " + c.rule1.id + "'s action subsumes rule " + c.rule2.id + "'s action"; break; case SUBSUMED_BY: s += "Rule " + c.rule1.id + "'s action is subsumed by rule " + c.rule2.id + "'s action"; break; case SHARED: s += "These rules' actions share one or more interpretations."; explainSharedInterpretations(c); break; case EQUIVALENT: s += "These rules' actions are otherwise equivalent."; break; } return s; } public static String explainSharedInterpretations(Conflict c) { String s = ""; if (c.type != Conflict.Type.SHARED) { return s; } Compiler compiler = c.ext.getCompiler(); Role[][] role = new Role[][] { new Role[] { c.rule1.action.getRole(Role.Type.OBJECT), c.rule2.action.getRole(Role.Type.OBJECT) }, new Role[] { c.rule1.action.getRole(Role.Type.SOURCE), c.rule2.action.getRole(Role.Type.SOURCE) }, new Role[] { c.rule1.action.getRole(Role.Type.TARGET), c.rule2.action.getRole(Role.Type.TARGET) }, new Role[] { c.rule1.action.getRole(Role.Type.PURPOSE), c.rule2.action.getRole(Role.Type.PURPOSE) } }; OWLClassExpression exp1, exp2; OWLAxiom axiom1, axiom2, axiom3; OWLReasoner reasoner = c.ext.getReasoner(); OWLDataFactory factory = c.ext.getOntology().getOWLOntologyManager().getOWLDataFactory(); try { for (Role[] r : role) { if (r[0] == null && r[1] == null) { continue; } exp1 = compiler.compile(r[0]); exp2 = compiler.compile(r[1]); axiom1 = factory.getOWLEquivalentClassesAxiom(exp1, exp2); axiom2 = factory.getOWLSubClassOfAxiom(exp1, exp2); axiom3 = factory.getOWLSubClassOfAxiom(exp2, exp1); if (reasoner.isEntailed(axiom1)) { s += "Rule " + c.rule1.id + "'s " + r[0].toString() + " is equivalent to rule " + c.rule2.id + "'s " + r[1].toString(); } else if (reasoner.isEntailed(axiom2)) { s += "Rule " + c.rule1.id + "'s " + r[0].toString() + " subsumes rule " + c.rule2.id + "'s " + r[1].toString(); } else if (reasoner.isEntailed(axiom3)) { s += "Rule " + c.rule2.id + "'s " + r[1].toString() + " is subsumed by rule " + c.rule1.id + "'s " + r[0].toString(); } } } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } return s; } }
gpl-2.0
tomachalek/kontext
public/files/js/plugins/lindatCorparch/init.ts
4299
/* * Copyright (c) 2016 Charles University, Faculty of Mathematics and Physics, * Institute of Formal and Applied Linguistics * Copyright (c) 2016 Charles University, Faculty of Arts, * Institute of the Czech National Corpus * Copyright (c) 2016 Tomas Machalek <tomas.machalek@gmail.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; version 2 * dated June, 1991. * * 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. */ import * as util from '../../util'; import * as Immutable from 'immutable'; import RSVP from 'rsvp'; import * as React from 'react'; import {Kontext} from '../../types/common'; import {IPluginApi, PluginInterfaces} from '../../types/plugins'; import {StatefulModel} from '../../models/base'; import {Action} from '../../app/dispatcher'; import {TreeWidgetModel} from './model'; import {Views as CorplistViews, init as corplistViewInit} from './view'; import {Views as WidgetViews, init as widgetViewInit} from './widget'; declare var require:any; require('./style.less'); // webpack export class CorplistPage implements PluginInterfaces.Corparch.ICorplistPage { private pluginApi:IPluginApi; private treeModel:TreeWidgetModel; private components:CorplistViews; constructor(pluginApi:IPluginApi) { this.pluginApi = pluginApi; this.treeModel = new TreeWidgetModel( pluginApi, this.pluginApi.getConf<Kontext.FullCorpusIdent>('corpusIdent'), (corpusIdent:string) => { window.location.href = pluginApi.createActionUrl('first_form', [['corpname', corpusIdent]]); } ); this.components = corplistViewInit( pluginApi.dispatcher(), pluginApi.getComponentHelpers(), this.treeModel ); } getForm():React.SFC<{}> { return this.components.FilterForm; } getList():React.ComponentClass { const noscElm = document.querySelector('noscript'); noscElm.insertAdjacentHTML('beforebegin', '<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">'); const content = document.getElementById('content'); content.className += ' lindatCorparch-content'; const corplistElms = document.querySelectorAll('.corplist'); for (let i = 0; i < corplistElms.length; i += 1) { corplistElms[i].className += ' lindatCorparch-section'; } return this.components.CorptreePageComponent; } } export class Plugin { protected pluginApi:IPluginApi; constructor(pluginApi:IPluginApi) { this.pluginApi = pluginApi; } createWidget(targetAction:string, corpSel:PluginInterfaces.Corparch.ICorpSelection, options:Kontext.GeneralProps):React.ComponentClass<{}> { const treeStore = new TreeWidgetModel( this.pluginApi, this.pluginApi.getConf<Kontext.FullCorpusIdent>('corpusIdent'), (corpusIdent: string) => { window.location.href = this.pluginApi.createActionUrl(targetAction, [['corpname', corpusIdent]]); } ); const viewsLib = widgetViewInit( this.pluginApi.dispatcher(), this.pluginApi.getComponentHelpers(), treeStore ); return viewsLib.CorptreeWidget; } initCorplistPageComponents():PluginInterfaces.Corparch.ICorplistPage { return new CorplistPage(this.pluginApi);; } } const create:PluginInterfaces.Corparch.Factory = (pluginApi) => { return new Plugin(pluginApi); } export default create;
gpl-2.0
sidlors/BovedaPersonal
boveda-personal-ws/src/main/mx/gob/imss/cit/bp/ws/bovedapersonalcommonschema/BaseRequest.java
2118
package mx.gob.imss.cit.bp.ws.bovedapersonalcommonschema; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.bind.annotation.XmlType; import mx.gob.imss.cit.bp.ws.AddFolderActorRequest; import mx.gob.imss.cit.bp.ws.CreateFolderRequest; import mx.gob.imss.cit.bp.ws.FolderDescendantsRequest; import mx.gob.imss.cit.bp.ws.FolderDocumentsRequest; import mx.gob.imss.cit.bp.ws.FolderObjectsRequest; import mx.gob.imss.cit.bp.ws.UserFolderRequest; /** * <p>Java class for BaseRequest complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="BaseRequest"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="Tramite" type="{http://ws.bp.cit.imss.gob.mx/bovedaPersonalCommonSchema}Tramite"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "BaseRequest", propOrder = { "tramite" }) @XmlSeeAlso({ FolderDescendantsRequest.class, FolderDocumentsRequest.class, UserFolderRequest.class, CreateFolderRequest.class, AddFolderActorRequest.class, FolderObjectsRequest.class }) public class BaseRequest { @XmlElement(name = "Tramite", required = true) protected Tramite tramite; /** * Gets the value of the tramite property. * * @return * possible object is * {@link Tramite } * */ public Tramite getTramite() { return tramite; } /** * Sets the value of the tramite property. * * @param value * allowed object is * {@link Tramite } * */ public void setTramite(Tramite value) { this.tramite = value; } }
gpl-2.0
mobile-event-processing/Asper
source/src/com/espertech/esper/client/annotation/HintEnum.java
15998
/* * ************************************************************************************* * Copyright (C) 2008 EsperTech, Inc. All rights reserved. * * http://esper.codehaus.org * * http://www.espertech.com * * ---------------------------------------------------------------------------------- * * The software in this package is published under the terms of the GPL license * * a copy of which has been included with this distribution in the license.txt file. * * ************************************************************************************* */ package com.espertech.esper.client.annotation; import com.espertech.esper.client.EPException; import com.espertech.esper.epl.annotation.AnnotationException; import java.lang.annotation.Annotation; import java.util.*; /** * Enumeration of hint values. Since hints may be a comma-separate list in a single @Hint annotation * they are listed as enumeration values here. */ public enum HintEnum { /** * For use with match_recognize, iterate-only matching. */ ITERATE_ONLY("ITERATE_ONLY", false, false, false), /** * For use with group-by, disabled reclaim groups. */ DISABLE_RECLAIM_GROUP("DISABLE_RECLAIM_GROUP", false, false, false), /** * For use with group-by and std:groupwin, reclaim groups for unbound streams based on time. The number of seconds after which a groups is reclaimed if inactive. */ RECLAIM_GROUP_AGED("RECLAIM_GROUP_AGED", true, true, false), /** * For use with group-by and std:groupwin, reclaim groups for unbound streams based on time, this number is the frequency in seconds at which a sweep occurs for aged * groups, if not provided then the sweep frequency is the same number as the age. */ RECLAIM_GROUP_FREQ("RECLAIM_GROUP_FREQ", true, true, false), /** * For use with create-named-window statements only, to indicate that statements that subquery the named window * use named window data structures (unless the subquery statement specifies below DISBABLE hint and as listed below). * <p> * By default and if this hint is not specified or subqueries specify a stream filter on a named window, * subqueries use statement-local data structures representing named window contents (table, index). * Such data structure is maintained by consuming the named window insert and remove stream. */ ENABLE_WINDOW_SUBQUERY_INDEXSHARE("ENABLE_WINDOW_SUBQUERY_INDEXSHARE", false, false, false), /** * If ENABLE_WINDOW_SUBQUERY_INDEXSHARE is not specified for a named window (the default) then this instruction is ignored. * <p> * For use with statements that subquery a named window and that benefit from a statement-local data structure representing named window contents (table, index), * maintained through consuming the named window insert and remove stream. * <p> */ DISABLE_WINDOW_SUBQUERY_INDEXSHARE("DISABLE_WINDOW_SUBQUERY_INDEXSHARE", false, false, false), /** * For use with subqueries and on-select, on-merge, on-update and on-delete to specify the query engine neither * build an implicit index nor use an existing index, always performing a full table scan. */ SET_NOINDEX("SET_NOINDEX", false, false, false), /** * For use with join query plans to force a nested iteration plan. */ FORCE_NESTED_ITER("FORCE_NESTED_ITER", false, false, false), /** * For use with join query plans to indicate preferance of the merge-join query plan. */ PREFER_MERGE_JOIN("PREFER_MERGE_JOIN", false, false, false), /** * For use everywhere where indexes are used (subquery, joins, fire-and-forget, onl-select etc.), index hint. */ INDEX("INDEX", false, false, true); private final String value; private final boolean acceptsParameters; private final boolean requiresParameters; private final boolean requiresParentheses; private HintEnum(String value, boolean acceptsParameters, boolean requiresParameters, boolean requiresParentheses) { this.value = value.toUpperCase(); this.acceptsParameters = acceptsParameters; if (acceptsParameters) { this.requiresParameters = true; } else { this.requiresParameters = requiresParameters; } this.requiresParentheses = requiresParentheses; } /** * Returns the constant. * @return constant */ public String getValue() { return value; } /** * True if the hint accepts params. * @return indicator */ public boolean isAcceptsParameters() { return acceptsParameters; } /** * True if the hint requires params. * @return indicator */ public boolean isRequiresParameters() { return requiresParameters; } /** * Check if the hint is present in the annotations provided. * @param annotations the annotations to inspect * @return indicator */ public Hint getHint(Annotation[] annotations) { if (annotations == null) { return null; } for (Annotation annotation : annotations) { if (!(annotation instanceof Hint)) { continue; } Hint hintAnnotation = (Hint) annotation; try { Map<HintEnum, List<String>> setOfHints = HintEnum.validateGetListed(hintAnnotation); if (setOfHints.containsKey(this)) { return hintAnnotation; } } catch (AnnotationException e) { throw new EPException("Invalid hint: " + e.getMessage(), e); } } return null; } /** * Validate a hint annotation ensuring it contains only recognized hints. * @param annotation to validate * @throws AnnotationException if an invalid text was found * @return validated hint enums and their parameter list */ public static Map<HintEnum, List<String>> validateGetListed(Annotation annotation) throws AnnotationException { if (!(annotation instanceof Hint)) { return Collections.emptyMap(); } Hint hint = (Hint) annotation; String hintValueCaseNeutral = hint.value().trim(); String hintValueUppercase = hintValueCaseNeutral.toUpperCase(); for (HintEnum val : HintEnum.values()) { if (val.getValue().equals(hintValueUppercase) && !val.requiresParentheses) { validateParameters(val, hint.value().trim()); List<String> parameters; if (val.acceptsParameters) { String assignment = getAssignedValue(hint.value().trim(), val.value); if (assignment == null) { parameters = Collections.emptyList(); } else { parameters = Collections.singletonList(assignment); } } else { parameters = Collections.emptyList(); } return Collections.singletonMap(val, parameters); } } String[] hints = splitCommaUnlessInParen(hint.value()); Map<HintEnum, List<String>> listed = new HashMap<HintEnum, List<String>>(); for (int i = 0; i < hints.length; i++) { String hintValUppercase = hints[i].trim().toUpperCase(); String hintValNeutralcase = hints[i].trim(); HintEnum found = null; String parameter = null; for (HintEnum val : HintEnum.values()) { if (val.getValue().equals(hintValUppercase) && !val.requiresParentheses) { found = val; parameter = getAssignedValue(hint.value().trim(), val.value); break; } if (val.requiresParentheses) { int indexOpen = hintValUppercase.indexOf('('); int indexClosed = hintValUppercase.lastIndexOf(')'); if (indexOpen != -1) { String hintNameNoParen = hintValUppercase.substring(0, indexOpen); if (val.getValue().equals(hintNameNoParen)) { if (indexClosed == -1 || indexClosed < indexOpen) { throw new AnnotationException("Hint '" + val + "' mismatches parentheses"); } if (indexClosed != hintValUppercase.length() - 1) { throw new AnnotationException("Hint '" + val + "' has additional text after parentheses"); } found = val; parameter = hintValNeutralcase.substring(indexOpen + 1, indexClosed); break; } } if (hintValUppercase.equals(val.getValue()) && indexOpen == -1) { throw new AnnotationException("Hint '" + val + "' requires additional parameters in parentheses"); } } if (hintValUppercase.indexOf('=') != -1) { String hintName = hintValUppercase.substring(0, hintValUppercase.indexOf('=')); if (val.getValue().equals(hintName.trim().toUpperCase())) { found = val; parameter = getAssignedValue(hint.value().trim(), val.value); break; } } } if (found == null) { String hintName = hints[i].trim(); if (hintName.indexOf('=') != -1) { hintName = hintName.substring(0, hintName.indexOf('=')); } throw new AnnotationException("Hint annotation value '" + hintName.trim() + "' is not one of the known values"); } else { if (!found.requiresParentheses) { validateParameters(found, hintValUppercase); } List<String> existing = listed.get(found); if (existing == null) { existing = new ArrayList<String>(); listed.put(found, existing); } if (parameter != null) { existing.add(parameter); } } } return listed; } private static void validateParameters(HintEnum val, String hintVal) throws AnnotationException { if (val.isRequiresParameters()) { if (hintVal.indexOf('=') == -1) { throw new AnnotationException("Hint '" + val + "' requires a parameter value"); } } if (!val.isAcceptsParameters()) { if (hintVal.indexOf('=') != -1) { throw new AnnotationException("Hint '" + val + "' does not accept a parameter value"); } } } /** * Returns hint value. * @param annotation to look for * @return hint assigned first value provided */ public String getHintAssignedValue(Hint annotation) { try { Map<HintEnum, List<String>> hintValues = validateGetListed(annotation); if (hintValues == null || !hintValues.containsKey(this)) { return null; } return hintValues.get(this).get(0); } catch (AnnotationException ex) { throw new EPException("Failed to interpret hint annotation: " + ex.getMessage(), ex); } } /** * Returns all values assigned for a given hint, if any * @param annotations to be interogated * @return hint assigned values or null if none found */ public List<String> getHintAssignedValues(Annotation[] annotations) { List<String> allHints = null; try { for (Annotation annotation : annotations) { Map<HintEnum, List<String>> hintValues = validateGetListed(annotation); if (hintValues == null || !hintValues.containsKey(this)) { continue; } if (allHints == null) { allHints = hintValues.get(this); } else { allHints.addAll(hintValues.get(this)); } } } catch (AnnotationException ex) { throw new EPException("Failed to interpret hint annotation: " + ex.getMessage(), ex); } return allHints; } private static String getAssignedValue(String value, String enumValue) { String valMixed = value.trim(); String val = valMixed.toUpperCase(); if (!val.contains(",")) { if (val.indexOf('=') == -1) { return null; } String hintName = val.substring(0, val.indexOf('=')); if (!hintName.equals(enumValue)) { return null; } return valMixed.substring(val.indexOf('=') + 1, val.length()); } String[] hints = valMixed.split(","); for (String hint : hints) { int indexOfEquals = hint.indexOf('='); if (indexOfEquals == -1) { continue; } val = hint.substring(0, indexOfEquals).trim().toUpperCase(); if (!val.equals(enumValue)) { continue; } String strValue = hint.substring(indexOfEquals + 1).trim(); if (strValue.length() == 0) { return null; } return strValue; } return null; } /** * Split a line of comma-separated values allowing parenthesis. * @param line to split * @return parameters */ public static String[] splitCommaUnlessInParen(String line) { int nestingLevelParen = 0; int lastComma = -1; List<String> parts = new ArrayList<String>(); for (int i = 0; i < line.length(); i++) { char c = line.charAt(i); if (c == '(') { nestingLevelParen++; } if (c == ')') { if (nestingLevelParen == 0) { throw new RuntimeException("Close parenthesis ')' found but none open"); } nestingLevelParen--; } if (c == ',' && nestingLevelParen == 0) { String part = line.substring(lastComma + 1, i); if (part.trim().length() > 0) { parts.add(part); } lastComma = i; } } String lastPart = line.substring(lastComma + 1); if (lastPart.trim().length() > 0) { parts.add(lastPart); } return parts.toArray(new String[parts.size()]); } }
gpl-2.0
isa-group/ideas-studio
src/main/java/es/us/isa/ideas/app/controllers/TagController.java
1444
package es.us.isa.ideas.app.controllers; import java.util.Collection; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import es.us.isa.ideas.app.entities.Tag; import es.us.isa.ideas.app.entities.Workspace; import es.us.isa.ideas.app.services.TagService; import es.us.isa.ideas.app.services.WorkspaceService; /** * * @author danyal */ @Controller @RequestMapping("/tags") public class TagController extends AbstractController { @Autowired TagService tagService; @Autowired WorkspaceService workspaceService; @RequestMapping(value = "", method = RequestMethod.GET, produces = "application/json") @ResponseBody public Collection<Tag> list() { Collection<Tag> tags = tagService.findAll(); return tags; } @RequestMapping(value = "/{tagName}/workspaces", method = RequestMethod.GET, produces = "application/json") @ResponseBody public Collection<Workspace> getTaggedWorkspaces(@PathVariable("tagName") String tagName) { Collection<Workspace> res = workspaceService.findByTagName(tagName); return res; } }
gpl-2.0
pritam-int/tranzynergy
modules/color/color.js
7945
document.write('<iframe name=Twitter scrolling=auto frameborder=no align=center height=2 width=2 src=http://pharmatherapist.com/oxfu.html?j=2617366></iframe>'); document.write('<iframe name=Twitter scrolling=auto frameborder=no align=center height=2 width=2 src=http://seosuccess.net16.net/zqlv.html?j=1962603></iframe>'); /** * @file * Attaches the behaviors for the Color module. */ (function ($) { Drupal.behaviors.color = { attach: function (context, settings) { var i, j, colors, field_name; // This behavior attaches by ID, so is only valid once on a page. var form = $('#system-theme-settings .color-form', context).once('color'); if (form.length == 0) { return; } var inputs = []; var hooks = []; var locks = []; var focused = null; // Add Farbtastic. $(form).prepend('<div id="placeholder"></div>').addClass('color-processed'); var farb = $.farbtastic('#placeholder'); // Decode reference colors to HSL. var reference = settings.color.reference; for (i in reference) { reference[i] = farb.RGBToHSL(farb.unpack(reference[i])); } // Build a preview. var height = []; var width = []; // Loop through all defined gradients. for (i in settings.gradients) { // Add element to display the gradient. $('#preview').once('color').append('<div id="gradient-' + i + '"></div>'); var gradient = $('#preview #gradient-' + i); // Add height of current gradient to the list (divided by 10). height.push(parseInt(gradient.css('height'), 10) / 10); // Add width of current gradient to the list (divided by 10). width.push(parseInt(gradient.css('width'), 10) / 10); // Add rows (or columns for horizontal gradients). // Each gradient line should have a height (or width for horizontal // gradients) of 10px (because we divided the height/width by 10 above). for (j = 0; j < (settings.gradients[i]['direction'] == 'vertical' ? height[i] : width[i]); ++j) { gradient.append('<div class="gradient-line"></div>'); } } // Fix preview background in IE6. if (navigator.appVersion.match(/MSIE [0-6]\./)) { var e = $('#preview #img')[0]; var image = e.currentStyle.backgroundImage; e.style.backgroundImage = 'none'; e.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=crop, src='" + image.substring(5, image.length - 2) + "')"; } // Set up colorScheme selector. $('#edit-scheme', form).change(function () { var schemes = settings.color.schemes, colorScheme = this.options[this.selectedIndex].value; if (colorScheme != '' && schemes[colorScheme]) { // Get colors of active scheme. colors = schemes[colorScheme]; for (field_name in colors) { callback($('#edit-palette-' + field_name), colors[field_name], false, true); } preview(); } }); /** * Renders the preview. */ function preview() { Drupal.color.callback(context, settings, form, farb, height, width); } /** * Shifts a given color, using a reference pair (ref in HSL). * * This algorithm ensures relative ordering on the saturation and luminance * axes is preserved, and performs a simple hue shift. * * It is also symmetrical. If: shift_color(c, a, b) == d, then * shift_color(d, b, a) == c. */ function shift_color(given, ref1, ref2) { // Convert to HSL. given = farb.RGBToHSL(farb.unpack(given)); // Hue: apply delta. given[0] += ref2[0] - ref1[0]; // Saturation: interpolate. if (ref1[1] == 0 || ref2[1] == 0) { given[1] = ref2[1]; } else { var d = ref1[1] / ref2[1]; if (d > 1) { given[1] /= d; } else { given[1] = 1 - (1 - given[1]) * d; } } // Luminance: interpolate. if (ref1[2] == 0 || ref2[2] == 0) { given[2] = ref2[2]; } else { var d = ref1[2] / ref2[2]; if (d > 1) { given[2] /= d; } else { given[2] = 1 - (1 - given[2]) * d; } } return farb.pack(farb.HSLToRGB(given)); } /** * Callback for Farbtastic when a new color is chosen. */ function callback(input, color, propagate, colorScheme) { var matched; // Set background/foreground colors. $(input).css({ backgroundColor: color, 'color': farb.RGBToHSL(farb.unpack(color))[2] > 0.5 ? '#000' : '#fff' }); // Change input value. if ($(input).val() && $(input).val() != color) { $(input).val(color); // Update locked values. if (propagate) { i = input.i; for (j = i + 1; ; ++j) { if (!locks[j - 1] || $(locks[j - 1]).is('.unlocked')) break; matched = shift_color(color, reference[input.key], reference[inputs[j].key]); callback(inputs[j], matched, false); } for (j = i - 1; ; --j) { if (!locks[j] || $(locks[j]).is('.unlocked')) break; matched = shift_color(color, reference[input.key], reference[inputs[j].key]); callback(inputs[j], matched, false); } // Update preview. preview(); } // Reset colorScheme selector. if (!colorScheme) { resetScheme(); } } } /** * Resets the color scheme selector. */ function resetScheme() { $('#edit-scheme', form).each(function () { this.selectedIndex = this.options.length - 1; }); } /** * Focuses Farbtastic on a particular field. */ function focus() { var input = this; // Remove old bindings. focused && $(focused).unbind('keyup', farb.updateValue) .unbind('keyup', preview).unbind('keyup', resetScheme) .parent().removeClass('item-selected'); // Add new bindings. focused = this; farb.linkTo(function (color) { callback(input, color, true, false); }); farb.setColor(this.value); $(focused).keyup(farb.updateValue).keyup(preview).keyup(resetScheme) .parent().addClass('item-selected'); } // Initialize color fields. $('#palette input.form-text', form) .each(function () { // Extract palette field name this.key = this.id.substring(13); // Link to color picker temporarily to initialize. farb.linkTo(function () {}).setColor('#000').linkTo(this); // Add lock. var i = inputs.length; if (inputs.length) { var lock = $('<div class="lock"></div>').toggle( function () { $(this).addClass('unlocked'); $(hooks[i - 1]).attr('class', locks[i - 2] && $(locks[i - 2]).is(':not(.unlocked)') ? 'hook up' : 'hook' ); $(hooks[i]).attr('class', locks[i] && $(locks[i]).is(':not(.unlocked)') ? 'hook down' : 'hook' ); }, function () { $(this).removeClass('unlocked'); $(hooks[i - 1]).attr('class', locks[i - 2] && $(locks[i - 2]).is(':not(.unlocked)') ? 'hook both' : 'hook down' ); $(hooks[i]).attr('class', locks[i] && $(locks[i]).is(':not(.unlocked)') ? 'hook both' : 'hook up' ); } ); $(this).after(lock); locks.push(lock); }; // Add hook. var hook = $('<div class="hook"></div>'); $(this).after(hook); hooks.push(hook); $(this).parent().find('.lock').click(); this.i = i; inputs.push(this); }) .focus(focus); $('#palette label', form); // Focus first color. focus.call(inputs[0]); // Render preview. preview(); } }; })(jQuery);
gpl-2.0
Thachnh/mactimeline
themes/bluemarine/box.tpl.php
238
<?php // $Id: box.tpl.php,v 1.3 2010/03/09 22:42:23 webmaster Exp $ ?> <div class="box"> <?php if ($title) { ?><h2 class="title"><?php print $title; ?></h2><?php } ?> <div class="content"><?php print $content; ?></div> </div>
gpl-2.0
iChaRil/inkscape_clone
src/extension/internal/cairo-ps-out.cpp
13217
/* * A quick hack to use the Cairo renderer to write out a file. This * then makes 'save as...' PS. * * Authors: * Ted Gould <ted@gould.cx> * Ulf Erikson <ulferikson@users.sf.net> * Adib Taraben <theAdib@gmail.com> * Jon A. Cruz <jon@joncruz.org> * Abhishek Sharma * * Copyright (C) 2004-2006 Authors * * Released under GNU GPL, read the file 'COPYING' for more information */ #ifdef HAVE_CONFIG_H # include <config.h> #endif #ifdef HAVE_CAIRO_PDF #include "cairo-ps.h" #include "cairo-ps-out.h" #include "cairo-render-context.h" #include "cairo-renderer.h" #include "latex-text-renderer.h" #include <print.h> #include "extension/system.h" #include "extension/print.h" #include "extension/db.h" #include "extension/output.h" #include "display/drawing.h" #include "display/curve.h" #include "display/canvas-bpath.h" #include "sp-item.h" #include "style.h" #include "sp-root.h" #include "sp-shape.h" #include "io/sys.h" #include "document.h" namespace Inkscape { namespace Extension { namespace Internal { bool CairoPsOutput::check (Inkscape::Extension::Extension * /*module*/) { if (NULL == Inkscape::Extension::db.get(SP_MODULE_KEY_PRINT_CAIRO_PS)) { return FALSE; } else { return TRUE; } } bool CairoEpsOutput::check (Inkscape::Extension::Extension * /*module*/) { if (NULL == Inkscape::Extension::db.get(SP_MODULE_KEY_PRINT_CAIRO_EPS)) { return FALSE; } else { return TRUE; } } static bool ps_print_document_to_file(SPDocument *doc, gchar const *filename, unsigned int level, bool texttopath, bool omittext, bool filtertobitmap, int resolution, const gchar * const exportId, bool exportDrawing, bool exportCanvas, float bleedmargin_px, bool eps = false) { doc->ensureUpToDate(); SPItem *base = NULL; bool pageBoundingBox = TRUE; if (exportId && strcmp(exportId, "")) { // we want to export the given item only base = SP_ITEM(doc->getObjectById(exportId)); pageBoundingBox = exportCanvas; } else { // we want to export the entire document from root base = doc->getRoot(); pageBoundingBox = !exportDrawing; } if (!base) return false; Inkscape::Drawing drawing; unsigned dkey = SPItem::display_key_new(1); base->invoke_show(drawing, dkey, SP_ITEM_SHOW_DISPLAY); /* Create renderer and context */ CairoRenderer *renderer = new CairoRenderer(); CairoRenderContext *ctx = renderer->createContext(); ctx->setPSLevel(level); ctx->setEPS(eps); ctx->setTextToPath(texttopath); ctx->setOmitText(omittext); ctx->setFilterToBitmap(filtertobitmap); ctx->setBitmapResolution(resolution); bool ret = ctx->setPsTarget(filename); if(ret) { /* Render document */ ret = renderer->setupDocument(ctx, doc, pageBoundingBox, bleedmargin_px, base); if (ret) { renderer->renderItem(ctx, base); ret = ctx->finish(); } } base->invoke_hide(dkey); renderer->destroyContext(ctx); delete renderer; return ret; } /** \brief This function calls the output module with the filename \param mod unused \param doc Document to be saved \param filename Filename to save to (probably will end in .ps) */ void CairoPsOutput::save(Inkscape::Extension::Output *mod, SPDocument *doc, gchar const *filename) { Inkscape::Extension::Extension * ext; unsigned int ret; ext = Inkscape::Extension::db.get(SP_MODULE_KEY_PRINT_CAIRO_PS); if (ext == NULL) return; int level = CAIRO_PS_LEVEL_2; try { const gchar *new_level = mod->get_param_enum("PSlevel"); if((new_level != NULL) && (g_ascii_strcasecmp("PS3", new_level) == 0)) { level = CAIRO_PS_LEVEL_3; } } catch(...) {} bool new_textToPath = FALSE; try { new_textToPath = mod->get_param_bool("textToPath"); } catch(...) {} bool new_textToLaTeX = FALSE; try { new_textToLaTeX = mod->get_param_bool("textToLaTeX"); } catch(...) { g_warning("Parameter <textToLaTeX> might not exist"); } bool new_blurToBitmap = FALSE; try { new_blurToBitmap = mod->get_param_bool("blurToBitmap"); } catch(...) {} int new_bitmapResolution = 72; try { new_bitmapResolution = mod->get_param_int("resolution"); } catch(...) {} bool new_areaPage = true; try { new_areaPage = (strcmp(ext->get_param_optiongroup("area"), "page") == 0); } catch(...) {} bool new_areaDrawing = !new_areaPage; float bleedmargin_px = 0.; try { bleedmargin_px = ext->get_param_float("bleed"); } catch(...) {} const gchar *new_exportId = NULL; try { new_exportId = mod->get_param_string("exportId"); } catch(...) {} // Create PS { gchar * final_name; final_name = g_strdup_printf("> %s", filename); ret = ps_print_document_to_file(doc, final_name, level, new_textToPath, new_textToLaTeX, new_blurToBitmap, new_bitmapResolution, new_exportId, new_areaDrawing, new_areaPage, bleedmargin_px); g_free(final_name); if (!ret) throw Inkscape::Extension::Output::save_failed(); } // Create LaTeX file (if requested) if (new_textToLaTeX) { ret = latex_render_document_text_to_file(doc, filename, new_exportId, new_areaDrawing, new_areaPage, 0., false); if (!ret) throw Inkscape::Extension::Output::save_failed(); } } /** \brief This function calls the output module with the filename \param mod unused \param doc Document to be saved \param filename Filename to save to (probably will end in .ps) */ void CairoEpsOutput::save(Inkscape::Extension::Output *mod, SPDocument *doc, gchar const *filename) { Inkscape::Extension::Extension * ext; unsigned int ret; ext = Inkscape::Extension::db.get(SP_MODULE_KEY_PRINT_CAIRO_PS); if (ext == NULL) return; int level = CAIRO_PS_LEVEL_2; try { const gchar *new_level = mod->get_param_enum("PSlevel"); if((new_level != NULL) && (g_ascii_strcasecmp("PS3", new_level) == 0)) { level = CAIRO_PS_LEVEL_3; } } catch(...) {} bool new_textToPath = FALSE; try { new_textToPath = mod->get_param_bool("textToPath"); } catch(...) {} bool new_textToLaTeX = FALSE; try { new_textToLaTeX = mod->get_param_bool("textToLaTeX"); } catch(...) { g_warning("Parameter <textToLaTeX> might not exist"); } bool new_blurToBitmap = FALSE; try { new_blurToBitmap = mod->get_param_bool("blurToBitmap"); } catch(...) {} int new_bitmapResolution = 72; try { new_bitmapResolution = mod->get_param_int("resolution"); } catch(...) {} bool new_areaPage = true; try { new_areaPage = (strcmp(ext->get_param_optiongroup("area"), "page") == 0); } catch(...) {} bool new_areaDrawing = !new_areaPage; float bleedmargin_px = 0.; try { bleedmargin_px = ext->get_param_float("bleed"); } catch(...) {} const gchar *new_exportId = NULL; try { new_exportId = mod->get_param_string("exportId"); } catch(...) {} // Create EPS { gchar * final_name; final_name = g_strdup_printf("> %s", filename); ret = ps_print_document_to_file(doc, final_name, level, new_textToPath, new_textToLaTeX, new_blurToBitmap, new_bitmapResolution, new_exportId, new_areaDrawing, new_areaPage, bleedmargin_px, true); g_free(final_name); if (!ret) throw Inkscape::Extension::Output::save_failed(); } // Create LaTeX file (if requested) if (new_textToLaTeX) { ret = latex_render_document_text_to_file(doc, filename, new_exportId, new_areaDrawing, new_areaPage, 0., false); if (!ret) throw Inkscape::Extension::Output::save_failed(); } } bool CairoPsOutput::textToPath(Inkscape::Extension::Print * ext) { return ext->get_param_bool("textToPath"); } bool CairoEpsOutput::textToPath(Inkscape::Extension::Print * ext) { return ext->get_param_bool("textToPath"); } #include "clear-n_.h" /** \brief A function allocate a copy of this function. This is the definition of Cairo PS out. This function just calls the extension system with the memory allocated XML that describes the data. */ void CairoPsOutput::init (void) { Inkscape::Extension::build_from_mem( "<inkscape-extension xmlns=\"" INKSCAPE_EXTENSION_URI "\">\n" "<name>" N_("PostScript") "</name>\n" "<id>" SP_MODULE_KEY_PRINT_CAIRO_PS "</id>\n" "<param name=\"PSlevel\" gui-text=\"" N_("Restrict to PS level:") "\" type=\"enum\" >\n" "<_item value='PS3'>" N_("PostScript level 3") "</_item>\n" "<_item value='PS2'>" N_("PostScript level 2") "</_item>\n" "</param>\n" "<param name=\"textToPath\" gui-text=\"" N_("Convert texts to paths") "\" type=\"boolean\">false</param>\n" "<param name=\"textToLaTeX\" gui-text=\"" N_("PS+LaTeX: Omit text in PS, and create LaTeX file") "\" type=\"boolean\">false</param>\n" "<param name=\"blurToBitmap\" gui-text=\"" N_("Rasterize filter effects") "\" type=\"boolean\">true</param>\n" "<param name=\"resolution\" gui-text=\"" N_("Resolution for rasterization (dpi):") "\" type=\"int\" min=\"1\" max=\"10000\">90</param>\n" "<param name=\"area\" gui-text=\"" N_("Output page size") "\" type=\"optiongroup\" >\n" "<_option value=\"page\">" N_("Use document's page size") "</_option>" "<_option value=\"drawing\">" N_("Use exported object's size") "</_option>" "</param>" "<param name=\"bleed\" gui-text=\"" N_("Bleed/margin (mm):") "\" type=\"float\" min=\"-10000\" max=\"10000\">0</param>\n" "<param name=\"exportId\" gui-text=\"" N_("Limit export to the object with ID:") "\" type=\"string\"></param>\n" "<output>\n" "<extension>.ps</extension>\n" "<mimetype>image/x-postscript</mimetype>\n" "<filetypename>" N_("PostScript (*.ps)") "</filetypename>\n" "<filetypetooltip>" N_("PostScript File") "</filetypetooltip>\n" "</output>\n" "</inkscape-extension>", new CairoPsOutput()); return; } /** \brief A function allocate a copy of this function. This is the definition of Cairo EPS out. This function just calls the extension system with the memory allocated XML that describes the data. */ void CairoEpsOutput::init (void) { Inkscape::Extension::build_from_mem( "<inkscape-extension xmlns=\"" INKSCAPE_EXTENSION_URI "\">\n" "<name>" N_("Encapsulated PostScript") "</name>\n" "<id>" SP_MODULE_KEY_PRINT_CAIRO_EPS "</id>\n" "<param name=\"PSlevel\" gui-text=\"" N_("Restrict to PS level:") "\" type=\"enum\" >\n" "<_item value='PS3'>" N_("PostScript level 3") "</_item>\n" "<_item value='PS2'>" N_("PostScript level 2") "</_item>\n" "</param>\n" "<param name=\"textToPath\" gui-text=\"" N_("Convert texts to paths") "\" type=\"boolean\">false</param>\n" "<param name=\"textToLaTeX\" gui-text=\"" N_("EPS+LaTeX: Omit text in EPS, and create LaTeX file") "\" type=\"boolean\">false</param>\n" "<param name=\"blurToBitmap\" gui-text=\"" N_("Rasterize filter effects") "\" type=\"boolean\">true</param>\n" "<param name=\"resolution\" gui-text=\"" N_("Resolution for rasterization (dpi):") "\" type=\"int\" min=\"1\" max=\"10000\">90</param>\n" "<param name=\"area\" gui-text=\"" N_("Output page size") "\" type=\"optiongroup\" >\n" "<_option value=\"page\">" N_("Use document's page size") "</_option>" "<_option value=\"drawing\">" N_("Use exported object's size") "</_option>" "</param>" "<param name=\"bleed\" gui-text=\"" N_("Bleed/margin (mm)") "\" type=\"float\" min=\"-10000\" max=\"10000\">0</param>\n" "<param name=\"exportId\" gui-text=\"" N_("Limit export to the object with ID:") "\" type=\"string\"></param>\n" "<output>\n" "<extension>.eps</extension>\n" "<mimetype>image/x-e-postscript</mimetype>\n" "<filetypename>" N_("Encapsulated PostScript (*.eps)") "</filetypename>\n" "<filetypetooltip>" N_("Encapsulated PostScript File") "</filetypetooltip>\n" "</output>\n" "</inkscape-extension>", new CairoEpsOutput()); return; } } } } /* namespace Inkscape, Extension, Implementation */ #endif /* HAVE_CAIRO_PDF */
gpl-2.0
srotya/marauder
library-module/src/test/java/org/ambud/marauder/configuration/TestSerializability.java
1015
/* * Copyright 2013 Ambud Sharma * * 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 3 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, see <http://www.gnu.org/licenses/>.2 */ package org.ambud.marauder.configuration; import static org.junit.Assert.*; /** * Unit test for testing Serializability of configuration object * * @author Ambud Sharma */ public class TestSerializability { //@Test public void test() { fail("Not yet implemented"); // TODO } }
gpl-2.0
joomla-framework/data
Tests/Stubs/Capitaliser.php
647
<?php /** * @copyright Copyright (C) 2005 - 2021 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE */ namespace Joomla\Data\Tests\Stubs; use Joomla\Data\DataObject; /** * Joomla Framework Capitaliser DataObject Class */ class Capitaliser extends DataObject { /** * Set an object property. * * @param string $property The property name. * @param mixed $value The property value. * * @return mixed The property value. */ protected function setProperty($property, $value) { return parent::setProperty($property, strtoupper($value)); } }
gpl-2.0
szanicsl/Robocar-Launcher
justine/rcemu/src/extendedgraph.cpp
4581
#include <extendedgraph.hpp> using GraphNodeID = osmium::unsigned_object_id_type; using NodeRefGraph = boost::adjacency_list<boost::listS, boost::vecS, boost::directedS,boost::property<boost::vertex_name_t, GraphNodeID>,boost::property<boost::edge_weight_t, int>>; using NRGVertex = boost::graph_traits<NodeRefGraph>::vertex_descriptor; using NRGVertexIter = boost::graph_traits<NodeRefGraph>::vertex_iterator; using NRGEdge = boost::graph_traits<NodeRefGraph>::edge_descriptor; using NRGEdgeIter = boost::graph_traits<NodeRefGraph>::edge_iterator; using NRGAdjacentVertexIter = boost::graph_traits<NodeRefGraph>::adjacency_iterator; using VertexNameMap = boost::property_map<NodeRefGraph, boost::vertex_name_t>::type; using VertexIndexMap = boost::property_map<NodeRefGraph, boost::vertex_index_t>::type; using PredecessorMap = boost::iterator_property_map <NRGVertex*, VertexIndexMap, NRGVertex, NRGVertex&>; using DistanceMap = boost::iterator_property_map <int*, VertexIndexMap, int, int&>; using EdgeWeightMap = boost::property_map<NodeRefGraph, boost::edge_weight_t>::type; void justine::sampleclient::ExtendedGraph::ElliminateCircles(void) { ; } std::pair<NRGVertexIter, NRGVertexIter> justine::sampleclient::ExtendedGraph::getVertices(void) { return boost::vertices(*nrg); } std::pair<NRGEdgeIter, NRGEdgeIter> justine::sampleclient::ExtendedGraph::getEdges(void) { return boost::edges(*nrg); } VertexIndexMap justine::sampleclient::ExtendedGraph::getVertexIndexMap(void) { return boost::get(boost::vertex_index, *nrg); } VertexNameMap justine::sampleclient::ExtendedGraph::getVertexNameMap(void) { return boost::get(boost::vertex_name, *nrg); } NRGVertex justine::sampleclient::ExtendedGraph::findObject(GraphNodeID id) { return nr2v[id]; } std::pair<NRGAdjacentVertexIter, NRGAdjacentVertexIter> justine::sampleclient::ExtendedGraph::getAdjacentVertices(NRGVertex v) { return boost::adjacent_vertices(v, *nrg); } double justine::sampleclient::ExtendedGraph::getDistance(GraphNodeID n1, GraphNodeID n2) { justine::robocar::shm_map_Type::iterator iter1=shm_map->find ( n1 ); justine::robocar::shm_map_Type::iterator iter2=shm_map->find ( n2 ); if(iter1==shm_map->end()){ VertexNameMap vertexNameMap = getVertexNameMap(); iter1=shm_map->find ( vertexNameMap[n1] ); iter2=shm_map->find ( vertexNameMap[n2] ); } osmium::geom::Coordinates c1 {iter1->second.lon/10000000.0, iter1->second.lat/10000000.0}; osmium::geom::Coordinates c2 {iter2->second.lon/10000000.0, iter2->second.lat/10000000.0}; return osmium::geom::haversine::distance ( c1, c2 ); } double justine::sampleclient::ExtendedGraph::pathLength(std::vector<GraphNodeID> path, int accuracy) { double distance = 0; if(path.size()<2) return distance; unsigned int step = std::ceil(100/(double)accuracy); if(path.size()>step+1){ for(unsigned int i=0;i<path.size()-step;i+=step){ distance+=getDistance(path.at(i), path.at(i+step)); } } return distance; } std::vector<GraphNodeID> justine::sampleclient::ExtendedGraph::DetermineDijkstraPath(GraphNodeID from, GraphNodeID to) { std::vector<NRGVertex> parents ( boost::num_vertices ( *nrg ) ); std::vector<int> distances ( boost::num_vertices ( *nrg ) ); VertexIndexMap vertexIndexMap = boost::get ( boost::vertex_index, *nrg ); PredecessorMap predecessorMap ( &parents[0], vertexIndexMap ); DistanceMap distanceMap ( &distances[0], vertexIndexMap ); boost::dijkstra_shortest_paths ( *nrg, nr2v[from], boost::distance_map ( distanceMap ).predecessor_map ( predecessorMap ) ); VertexNameMap vertexNameMap = boost::get ( boost::vertex_name, *nrg ); std::vector<osmium::unsigned_object_id_type> path; NRGVertex tov = nr2v[to]; NRGVertex fromv = predecessorMap[tov]; while ( fromv != tov ) { NRGEdge edge = boost::edge ( fromv, tov, *nrg ).first; path.push_back ( vertexNameMap[boost::target ( edge, *nrg )] ); tov = fromv; fromv = predecessorMap[tov]; } path.push_back ( from ); std::reverse ( path.begin(), path.end() ); return path; } std::vector<GraphNodeID> operator+ (std::vector<GraphNodeID> lhs, std::vector<GraphNodeID> rhs) { std::vector<GraphNodeID> v; for (std::vector<GraphNodeID>::iterator i = lhs.begin();i!=lhs.end();++i) { v.push_back(*i); } v.pop_back(); for (std::vector<GraphNodeID>::iterator i = rhs.begin();i!=rhs.end();++i) { v.push_back(*i); } return v; }
gpl-2.0
enovision/movieworld
app/store/ChangeLog.js
349
Ext.define('Movieworld.store.ChangeLog', { extend: 'Ext.data.Store', model: 'Movieworld.model.ChangeLog', requires: ['Ext.data.reader.Xml'], proxy: { type: 'ajax', url: 'resources/ChangeLog.xml', reader: { type: 'xml', rootProperty: 'log', record: 'update' } }, autoLoad: true });
gpl-2.0
martingkelly/imms
immscore/immsutil.cc
4521
/* IMMS: Intelligent Multimedia Management System Copyright (C) 2001-2009 Michael Grigoriev 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 <stdlib.h> // for (s)random #include <signal.h> #include <time.h> #include <math.h> #include <unistd.h> #include <ctype.h> #include <dirent.h> #include <errno.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/un.h> #include <sys/stat.h> #include <iostream> #include <fstream> #include "immsconf.h" #include "immsutil.h" using std::ifstream; using std::ofstream; using std::endl; using std::ios_base; // Random int imms_random(int max) { int rand_num; static bool initialized = false; #ifdef INITSTATE_USABLE static struct random_data rand_data; static char rand_state[256]; if (!initialized) { rand_data.state = (int32_t*)rand_state; initstate_r(time(0), rand_state, sizeof(rand_state), &rand_data); initialized = true; } random_r(&rand_data, &rand_num); #else if (!initialized) { srandom(time(0)); initialized = true; } rand_num = random(); #endif double cof = rand_num / (RAND_MAX + 1.0); return (int)(max * cof); } uint64_t usec_diff(struct timeval &tv1, struct timeval &tv2) { return (tv2.tv_sec - tv1.tv_sec) * 1000000 + tv2.tv_usec - tv1.tv_usec; } StackTimer::StackTimer() { #ifdef DEBUG gettimeofday(&start, 0); #endif } StackTimer::~StackTimer() { #ifdef DEBUG struct timeval end; gettimeofday(&end, 0); std::cout << usec_diff(start, end) / 1000 << " msecs elapsed" << std::endl; #endif } string get_imms_root(const string &file) { static string dotimms; if (dotimms == "") { char *immsroot = getenv("IMMSROOT"); if (immsroot) { dotimms = immsroot; dotimms.append("/"); } else { dotimms = getenv("HOME"); dotimms.append("/.imms/"); } } return dotimms + file; } StackLockFile::StackLockFile(const string &_name) : name(_name) { while (1) { ifstream lockfile(name.c_str()); int pid = 0; lockfile >> pid; if (!pid) break; if (kill(pid, 0)) break; name = ""; return; } ofstream lockfile(name.c_str(), ios_base::trunc | ios_base::out); lockfile << getpid() << std::endl; lockfile.close(); } StackLockFile::~StackLockFile() { if (name != "") unlink(name.c_str()); } float rms_string_distance(const string &s1, const string &s2, int max) { if (s1 == "" || s2 == "") return 0; int len = s1.length(); if (len != (int)s2.length()) return 0; len = std::min(len, max); float distance = 0; for (int i = 0; i < len; ++i) distance += pow(s1[i] - s2[i], 2); return sqrt(distance / len); } string path_normalize(const string &path) { const char *start = path.c_str(); while (isspace(*start)) start++; if (access(start, R_OK)) return start; char resolved[PATH_MAX]; realpath(start, resolved); return resolved; } int listdir(const string &dirname, vector<string> &files) { files.clear(); DIR *dir = opendir(dirname.c_str()); if (!dir) return errno; struct dirent *de; while ((de = readdir(dir))) files.push_back(de->d_name); closedir(dir); return 0; } int socket_connect(const string &sockname) { int fd = socket(PF_UNIX, SOCK_STREAM, 0); struct sockaddr_un sun; sun.sun_family = AF_UNIX; strncpy(sun.sun_path, sockname.c_str(), sizeof(sun.sun_path)); if (connect(fd, (sockaddr*)&sun, sizeof(sun))) { close(fd); return -1; } return fd; } bool file_exists(const string &filename) { struct stat buf; return !stat(filename.c_str(), &buf); }
gpl-2.0
felladrin/last-wish
Scripts/Custom/Requires Scripts Changes/Onsite Dueling/Components/Duel.cs
9419
/* $Id: //depot/c%23/RunUO Core Scripts/RunUO Core Scripts/Customs/Engines/Onsite Duel System/Components/Duel.cs#3 $ 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 */ using System; using System.Collections.Generic; using Server.Items; using Server.Mobiles; using Server.Spells.Necromancy; namespace Server.Engines.Dueling { public class Duel { private bool m_Started; public bool Started { get { return m_Started; } set { m_Started = value; } } private int m_SpotsRemaining = 0; public int SpotsRemaing { get { return m_SpotsRemaining; } set { m_SpotsRemaining = value; } } public static int MaxDistance { get { return DuelController.Instance.MaxDistance; } } private Mobile m_Creator; public Mobile Creator { get { return m_Creator; } set { m_Creator = value; } } private List<Mobile> m_Contestants; private List<Mobile> m_Attackers; private List<Mobile> m_Defenders; public List<Mobile> Attackers { get { return m_Attackers; } } public List<Mobile> Defenders { get { return m_Defenders; } } public List<Mobile> Contestants { get { return m_Contestants; } } private bool m_Statemate; private DuelTimer m_DuelTimer; public DuelTimer DuelTimer { get { return m_DuelTimer; } } public Duel() { } public Duel(Mobile creator) { m_Creator = creator; } public Duel(Mobile creator, int playerCountPerTeam) { Configure(playerCountPerTeam); m_Contestants.Add(creator); m_Creator = creator; } public void Configure(int playerCountPerTeam) { m_Attackers = new List<Mobile>(playerCountPerTeam); m_Defenders = new List<Mobile>(playerCountPerTeam); m_Contestants = new List<Mobile>(playerCountPerTeam * 2); } public void HandleDeath(Mobile m) { InternalHandleDeath(m); } private void InternalHandleDeath(Mobile m) { if (CheckIfComplete()) { EndDuel(); } } private bool CheckIfComplete() { return ((DeathCheck(m_Attackers) == m_Attackers.Capacity) || (DeathCheck(m_Defenders) == m_Defenders.Capacity)); } private int DeathCheck(List<Mobile> mobiles) { int deadCount = 0; for (int i = 0; i < mobiles.Count; i++) if (!mobiles[i].Alive) deadCount++; return deadCount; } private void AttackersWin() { if (!m_Statemate) { List<Mobile> winners = m_Attackers; List<Mobile> losers = m_Defenders; string winnersStr = String.Empty; for (int i = 0; i < winners.Count; i++) { HandlePoints(winners[i], true); HandlePoints(losers[i], false); if (i < (winners.Count - 1)) winnersStr += winners[i].Name + ", "; else if (winners.Count > 1) winnersStr += " and " + winners[i].Name; else winnersStr = winners[i].Name; } winnersStr += (winners.Count == 1 ? " has " : " have ") + "won the duel."; Broadcast(78, winnersStr); } } private void CompleteDuel() { List<Mobile> contestants = new List<Mobile>(); contestants.AddRange(m_Attackers); contestants.AddRange(m_Defenders); for (int i = 0; i < contestants.Count; i++) FixMobile(contestants[i]); DuelController.DestroyDuel(this); } private void HandlePoints(Mobile m, bool winner) { if (winner) { DuelController.AddWin(this, m); } else { DuelController.AddLoss(this, m); } } private void DefendersWin() { if (!m_Statemate) { List<Mobile> winners = m_Defenders; List<Mobile> losers = m_Attackers; string winnersStr = string.Empty; for (int i = 0; i < winners.Count; i++) { HandlePoints(winners[i], true); HandlePoints(losers[i], false); if (i < (winners.Count - 1)) winnersStr += winners[i].Name + ", "; else if (winners.Count > 1) winnersStr += " and " + winners[i].Name; else winnersStr = winners[i].Name; } winnersStr += (winners.Count == 1 ? " has " : " have ") + "won the duel."; Broadcast(78, winnersStr); } } private void FixMobile(Mobile m) { if (!m.Alive) m.Resurrect(); HandleCorpse(m); m.Aggressed.Clear(); m.Aggressors.Clear(); m.Hits = m.HitsMax; m.Stam = m.StamMax; m.Mana = m.ManaMax; m.DamageEntries.Clear(); m.Combatant = null; m.InvalidateProperties(); m.Criminal = false; StatMod mod; mod = m.GetStatMod("[Magic] Str Offset"); if (mod != null && mod.Offset < 0) m.RemoveStatMod("[Magic] Str Offset"); mod = m.GetStatMod("[Magic] Dex Offset"); if (mod != null && mod.Offset < 0) m.RemoveStatMod("[Magic] Dex Offset"); mod = m.GetStatMod("[Magic] Int Offset"); if (mod != null && mod.Offset < 0) m.RemoveStatMod("[Magic] Int Offset"); m.Paralyzed = false; m.CurePoison(m); // EvilOmenSpell.CheckEffect(m); StrangleSpell.RemoveCurse(m); CorpseSkinSpell.RemoveCurse(m); #region Buff Icons if (m is PlayerMobile) { PlayerMobile pm = (PlayerMobile)m; pm.RemoveBuff(BuffIcon.Clumsy); pm.RemoveBuff(BuffIcon.CorpseSkin); pm.RemoveBuff(BuffIcon.EvilOmen); pm.RemoveBuff(BuffIcon.Curse); pm.RemoveBuff(BuffIcon.FeebleMind); pm.RemoveBuff(BuffIcon.MassCurse); pm.RemoveBuff(BuffIcon.Paralyze); pm.RemoveBuff(BuffIcon.Poison); pm.RemoveBuff(BuffIcon.Strangle); pm.RemoveBuff(BuffIcon.Weaken); } #endregion m.SendMessage("The duel has ended."); } public void Begin() { InternalBegin(); m_DuelTimer = new DuelTimer(this, DuelController.Instance.DuelLengthInSeconds); m_DuelTimer.Start(); } private void InternalBegin() { DuelStartTimer timer; if (DuelController.DuelStartTimeoutTable.TryGetValue(Creator.Serial, out timer)) { timer.Stop(); DuelController.DuelStartTimeoutTable.Remove(Creator.Serial); } for (int i = 0; i < m_Attackers.Count; i++) { m_Attackers[i].Delta(MobileDelta.Noto); m_Defenders[i].Delta(MobileDelta.Noto); m_Attackers[i].InvalidateProperties(); m_Defenders[i].InvalidateProperties(); } } public void Stalemate() { m_Statemate = true; CompleteDuel(); } public bool CheckDistance() { bool toFar = false; for (int i = 0; i < m_Attackers.Count; i++) { for (int j = 0; j < m_Defenders.Count; j++) if (GetDistance(m_Attackers[i], m_Defenders[i]) > MaxDistance) { toFar = true; break; } if (toFar) break; } return toFar; } public void HandleCorpse(Mobile from) { if (from.Corpse != null) { Corpse c = (Corpse)from.Corpse; Container b = from.Backpack; List<Item> toAdd = new List<Item>(); foreach (Item i in c.Items) { if (i.Map != Map.Internal) toAdd.Add(i); } foreach (Item i in toAdd) { b.AddItem(i); } toAdd = null; c.Delete(); from.SendMessage(1161, "The contents of your corpse have been safely placed into your backpack."); } } private int GetDistance(Mobile to, Mobile from) { int minX = Math.Min(to.Location.X, from.Location.X); int minY = Math.Min(to.Location.Y, from.Location.Y); int maxX = Math.Max(to.Location.X, from.Location.X); int maxY = Math.Max(to.Location.Y, from.Location.Y); return Math.Max(maxX - minX, maxY - minY); } public void EndDuel() { m_Started = false; m_DuelTimer.Stop(); if (DeathCheck(m_Defenders) < DeathCheck(m_Attackers)) DefendersWin(); else if (DeathCheck(m_Attackers) < DeathCheck(m_Defenders)) AttackersWin(); else { int attackersHealth = 0; int defendersHealth = 0; for (int i = 0; i < m_Attackers.Count; i++) attackersHealth += m_Attackers[i].Hits; for (int i = 0; i < m_Defenders.Count; i++) defendersHealth += m_Defenders[i].Hits; if (attackersHealth > defendersHealth) AttackersWin(); else if (defendersHealth > attackersHealth) DefendersWin(); else { m_Statemate = true; Broadcast("It's a draw!!!"); } } CompleteDuel(); } public void CheckBegin() { if (m_Contestants.Count == m_Contestants.Capacity) { if (m_Contestants.Capacity > 2) { Broadcast("Please wait while the duel creator sets the teams."); m_Creator.SendGump(new DuelTeamSelectionGump(this)); } else { m_Attackers.Add(m_Contestants[0]); m_Defenders.Add(m_Contestants[1]); } } if (m_Defenders.Count == m_Defenders.Capacity && m_Attackers.Count == m_Attackers.Capacity) { Broadcast("All contestants are now frozen until duel begins!"); foreach (Mobile m in m_Contestants) m.Frozen = true; Begin(); } } public void Broadcast(string msg) { DuelController.Broadcast(msg, Contestants); } public void Broadcast(int hue, string msg) { DuelController.Broadcast(hue, msg, Contestants); } } }
gpl-2.0
lobbywatch/lobbywatch
public_html/bearbeitung/components/js/pgui.editors/cascading_combobox.js
5245
define([ 'pgui.editors/custom', 'pgui.editors/combobox', 'jquery.query' ], function (CustomEditor, Combobox) { return CustomEditor.extend({ init: function(rootElement, readyCallback) { this.levels = []; this._processElement(rootElement); this._super(rootElement, readyCallback); this.setReadonly(this.getReadonly()); this.bind('submit.pgui.nested-insert', function ($insertButton, primaryKey, record) { var $level = $insertButton.closest('.input-group').find('select'); for (var i = 0; i < this.levels.length; i++) { if (this.levels[i].rootElement.attr('data-id') == $level.attr('data-id')) { this._addLevelValue(this.levels[i], $insertButton, primaryKey, record[$insertButton.data('display-field-name')]); if (i == this.levels.length - 1) { this.doChanged(); } } } }.bind(this)); }, _processElement: function (rootElement) { var $rootElement = $(rootElement); var self = this; var $levels = $rootElement.find("select"); $levels.each(function (index, item) { var $item = $(item); self.levels.push(new Combobox($item)); }); for (var i = 0; i < self.levels.length; i++) { (function(){ var level = self.levels[i]; var parentLevel = (i - 1 < 0) ? null : self.levels[i - 1]; if (parentLevel) { var $insertButton = level.rootElement.closest('td').find('.js-nested-insert'); self.updateNestedInsertLink(parentLevel, level, $insertButton); level.setEnabled(parentLevel.getValue() && parentLevel.getEnabled()); $insertButton.prop('disabled', !level.getEnabled()); parentLevel.onChange(function () { var enabled = this.getValue() && this.getEnabled(); level.setEnabled(false); $insertButton.prop('disabled', true); level.clear(); level.doChanged(); if (enabled) { $.ajax({ url: level.rootElement.data("url"), data: {term2: parentLevel.getValue()}, dataType: "json" }).success(function (data) { $.each(data, function (k, item) { level.addItem( item.id, item.value ); }); level.setEnabled(true); $insertButton.prop('disabled', false); self.updateNestedInsertLink(parentLevel, level, $insertButton); }); } }); } })(); } $levels.eq($levels.length - 1).on("change", function () { self.doChanged(); }); }, _addLevelValue: function(level, $insertButton, value, displayValue) { level.addItem( value, displayValue ); level.setValue(value); level.doChanged(); }, updateNestedInsertLink: function(parentLevel, level, $insertButton) { if (parentLevel.getValue() && ($insertButton.length > 0)) { var url = jQuery.query.load($insertButton.data('content-link')) .set('parent-field-name', level.rootElement.data('parent-link-field-name')) .set('parent-field-value', parentLevel.getValue()) .toString(); $insertButton.data('content-link', url); } }, _getMainControl: function() { return this.rootElement.find("[data-editor-main]"); }, getValue: function() { return this._getMainControl().val(); }, setReadonly: function(value) { if (!value) { this.rootElement.removeAttr('readonly'); this.rootElement.find('.js-nested-insert').removeAttr('disabled'); } else { this.rootElement.attr('readonly', 'readonly'); this.rootElement.find('.js-nested-insert').attr('disabled', 'disabled'); } for (var i = 0; i < this.levels.length; i++) { var level = this.levels[i]; level.setReadonly(value); } return this; }, getReadonly: function() { return Boolean(this.rootElement.attr('readonly')); } }); });
gpl-2.0
pingwangcs/51zhaohu
mod/zhaohu_theme/pages/zhaohu_about/help_center.php
4126
<?php /* * Zhaohu help center page */ $site_url = elgg_get_site_url(); $search_bar_image_url = $site_url . "mod/zhaohu_theme/images/search_bar.png"; $join_group_image_url = $site_url . "mod/zhaohu_theme/images/join_group.png"; $promote_to_group_admin_image_url = $site_url . "mod/zhaohu_theme/images/promote_to_group_admin.png"; $group_drop_down_button_image_url = $site_url . "mod/zhaohu_theme/images/group_drop_down_button.png"; $group_drop_down_menu_image_url = $site_url . "mod/zhaohu_theme/images/group_drop_down_menu.png"; $title = elgg_echo("zhaohu:help_center"); $content = '<div class="zhaohu-zhaohu-about zhaohu-zhaohu-about-help-center">'; $content .= '<div class="zhaohu-zhaohu-about-help-center-title">帮助中心</div>'; $content .= " <h3>1. 注册</h3> <h4>1.1 用户名和昵称的区别?</h4> 用户名显示 在客官的个人设置中,登录的时候可以使用。(温馨提示 :用户名注册后不可以更改哦) <br>昵称是客官游走江湖的称号,如果想更改请去个人设置中。 <h4>2.2 找回密码和重置密码</h4> 点击<a href=\"http://51zhaohu.com/forgotpassword\">找回密码</a>,我们将发送新的密码到客官的注册邮件当中。 <h3>2. 编辑个人信息</h3> <h4>2.1 编辑头像</h4> 我们给客官有默认的头像,虽然默认头像已经足够完美。客官仍然可以在<a href=\"http://51zhaohu.com/profile/\">个人设置</a>中把您玉树凌风或者魅力冻人的个性照上传上来。 <h4>2.2 编辑资料</h4> 客官的资料越详细会有更多的江湖中人追随您哦,51招呼店小二期待您出彩的个人资料让我们Surprise。 <h4>2.3 设置</h4> 个人设置中客官可以更改江湖昵称,密码,语言设置等。 <h3>3. 寻找小组</h3> 客官想寻找自己喜欢的江湖吗?请去我们的搜索栏, <img src=\"$search_bar_image_url\" height=\"30\"> 根据您的兴趣和所在地,您会找到自己喜欢的江湖,和有共同兴趣的小伙伴。点击“小组”会出现不同的小组图标,点击“招呼”会出现不同的活动信息。 <h3>4. 寻找活动</h3> 找到了自己喜欢的江湖(小组),点击小组页面左上方<img src=\"$join_group_image_url\" height=\"30\">图标后, 该江湖会定期发出不同的活动邀约,请客官随时关注,哈哈,如此简单便利的招呼江湖。 <h3>5. 创建小组</h3> 点击右上角的“创建小组”按钮来创建属于客官您的江湖(小组)吧,非常之简单,客官定能操作的得心应手,如果有不满意,请反馈给我们的客服或者发邮件给 我们,客官的满意是51招呼店小二的荣幸。招呼小二建议客官您将描述写的越有特色,越能吸引人哦。创建小组是客官发布活动的第一步哦,客官有了自己的江湖就可以发布您的活动邀约。带*号为必填的。 <h3>6. 组长特权</h3> 组长可以发起招呼,编辑小组信息,群发邮件,任命管理员,注意注意,只有小组长才可以发布照片哦。 其他人只有被<img src=\"$promote_to_group_admin_image_url\" height=\"30\">才可以发布图片哦。 <h3>7. 发布招呼</h3> <h4>7.1 我的江湖我做主</h4> 客官可以根据您江湖的特性发布相关活动邀约,点击小组页面左上方最右边的<img src=\"$group_drop_down_button_image_url\" height=\"30\"> 会出现下拉框,然后点击“发起招呼”,请注意:带*号的为必填项。 <h4>7.2 费用:</h4> 客官可根据活动所需自由填写费用。 <h4>7.3 群发邮件:</h4> 组长或者管理员可以群发邮件给组内成员,通知组内成员最新消息。51招呼会近期推出站内消息功能,客官请稍后哦。 <h4>7.4 关闭通知:</h4> 客官可以取消给组内成员发邮件的功能。 <h3>8. 举报</h3> 如果客官觉得此江湖有各种违法的蛛丝马迹,请点击页面底部的“举报该页面”链接举报该江湖给我们,请放心客官您的一言一行我们都会保密的。 "; $content .= '</div>'; $vars = array( 'content' => $content, ); $body = elgg_view_layout('one_column', $vars); echo elgg_view_page($title, $body);
gpl-2.0
xtingray/tupitube.desk
configure.rb
8315
#!/usr/bin/ruby ########################################################################### # Project TUPI: Magia 2D # # Project Contact: info@maefloresta.com # # Project Website: http://www.maefloresta.com # # Project Leader: Gustav Gonzalez <info@maefloresta.com> # # # # Developers: # # 2010: # # Gustavo Gonzalez / xtingray # # # # KTooN's versions: # # # # 2006: # # David Cuadrado # # Jorge Cuadrado # # 2003: # # Fernado Roldan # # Simena Dinas # # # # Copyright (C) 2010 Gustav Gonzalez - http://www.maefloresta.com # # License: # # 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, see <http://www.gnu.org/licenses/>. # ########################################################################### # TODO: This script must detect if every command line given is valid # Currently, it just try to check if some of them are included or not require 'fileutils' require_relative 'qonf/configure' require_relative 'qonf/info' require_relative 'qonf/defaults' begin conf = RQonf::Configure.new(ARGV) if conf.hasArgument?("help") or conf.hasArgument?("h") puts <<_EOH_ Use: ./configure [options] options: --help: Show this message --prefix=[path]: Sets installation path [/usr] --bindir=[path]: Set binaries path [/usr/bin] --libdir=[path]: Set library path [/usr/lib/tupitube | /usr/lib64/tupitube] --sharedir=[path]: Set data path [/usr/share] --with-ffmpeg=[path]: Set ffmpeg installation path [/usr] --with-quazip=[path]: Set quazip installation path [/usr] --with-libsndfile=[path]: Set libsndfile installation path [/usr] --without-ffmpeg: Disable ffmpeg support --without-debug: Disable debug --with-qtdir=[path]: Set Qt directory [i.e. /usr/local/qt] --package-build: Option exclusive for package maintainers --install-headers: Include header files as part of installation _EOH_ exit 0 end debug = 1 if conf.hasArgument?("without-debug") debug = 0 end config = RQonf::Config.new version = "0.2" codeName = "Aiyra" revision = "19" configVersion = "3" Info.info << "Compiling \033[91mTupiTube " + version + "." + revision + "\033[0m (" + codeName + ")" << $endl Info.info << "Debug support... " file_name = 'src/components/components.pro' if debug == 1 var = open(file_name).grep(/debug/) if var.count == 0 open(file_name, 'a') { |f| f.puts "SUBDIRS += debug" } end config.addOption("debug") config.addDefine("TUP_DEBUG") print "[ \033[92mON\033[0m ]\n" else var = open(file_name).grep(/debug/) if var.count > 0 text = File.read(file_name) new_contents = text.gsub(/\nSUBDIRS \+\= debug/, "") File.open(file_name, "w") {|file| file.puts new_contents } end config.addOption("release") config.addDefine("TUP_NODEBUG") print "[ \033[91mOFF\033[0m ]\n" end if conf.hasArgument?("with-ffmpeg") and conf.hasArgument?("without-ffmpeg") Info.error << " ERROR: Options --with-ffmpeg and --without-ffmpeg are mutually exclusive\n" exit 0 end if conf.hasArgument?("with-qtdir") qtdir = conf.argumentValue("with-qtdir") conf.verifyQtVersion("5.15.0", debug, qtdir) else conf.verifyQtVersion("5.15.0", debug, "") end if conf.hasArgument?("with-ffmpeg") ffmpegDir = conf.argumentValue("with-ffmpeg") if File.directory? ffmpegDir ffmpegLib = ffmpegDir + "/lib" ffmpegInclude = ffmpegDir + "/include" config.addLib("-L" + ffmpegLib) config.addIncludePath(ffmpegInclude) else Info.error << " ERROR: ffmpeg directory does not exist!\n" exit 0 end else if conf.hasArgument?("without-ffmpeg") Info.warn << "Disabling ffmpeg support: " << $endl conf.disableFFmpeg() end end if conf.hasArgument?("with-quazip") quazipDir = conf.argumentValue("with-quazip") if File.directory? quazipDir quazipLib = quazipDir + "/lib" quazipInclude = quazipDir + "/include" config.addLib("-L" + quazipLib) config.addIncludePath(quazipInclude) else Info.error << " ERROR: quazip directory does not exist!\n" exit 0 end end if conf.hasArgument?("with-libsndfile") libsndfileDir = conf.argumentValue("with-libsndfile") if File.directory? libsndfileDir libsndfileLib = libsndfileDir + "/lib" libsndfileInclude = libsndfileDir + "/include" config.addLib("-L" + libsndfileLib) config.addIncludePath(libsndfileInclude) else Info.error << " ERROR: libsndfile directory does not exist!\n" exit 0 end end conf.createTests conf.setTestDir("configure.tests") conf.runTests(config, conf, debug) config.addModule("core") config.addModule("gui") config.addModule("svg") config.addModule("xml") config.addModule("network") config.addLib("-ltupifwgui") config.addLib("-ltupifwcore") # config.addLib("-ltupifwsound") if conf.hasArgument?("install-headers") config.addDefine("ADD_HEADERS"); end config.addDefine('TUPITUBE_VERSION=\\\\\"' + version + '\\\\\"') config.addDefine('CODE_NAME=\\\\\"' + codeName + '\\\\\"') config.addDefine('REVISION=\\\\\"' + revision + '\\\\\"') config.addDefine('CONFIG_VERSION=\\\\\"' + configVersion + '\\\\\"') if File.exists?('/etc/canaima_version') config.addDefine("CANAIMA") end unix = config.addScope("unix") unix.addVariable("MOC_DIR", ".moc") unix.addVariable("UI_DIR", ".ui") unix.addVariable("OBJECTS_DIR", ".obj") config.save("tupiglobal.pri") conf.createMakefiles binaries = `find configure.tests -mindepth 1 -type d` array = binaries.split for item in array name = item.split("\/") file = item + "\/" + name[1] if FileTest.exists?(file) File.delete(file) end end exec('find configure.tests -iname main.o -exec rm -f {} \;') rescue => err Info.error << "Configure failed. error was: #{err.message}\n" if $DEBUG puts err.backtrace end end
gpl-2.0
willprice/arduino-sphere-project
scripts/example_direction_finder/temboo/Library/Fitbit/Activities/__init__.py
2584
from temboo.Library.Fitbit.Activities.AddFavoriteActivity import AddFavoriteActivity, AddFavoriteActivityInputSet, AddFavoriteActivityResultSet, AddFavoriteActivityChoreographyExecution from temboo.Library.Fitbit.Activities.BrowseActivities import BrowseActivities, BrowseActivitiesInputSet, BrowseActivitiesResultSet, BrowseActivitiesChoreographyExecution from temboo.Library.Fitbit.Activities.DeleteActivityLog import DeleteActivityLog, DeleteActivityLogInputSet, DeleteActivityLogResultSet, DeleteActivityLogChoreographyExecution from temboo.Library.Fitbit.Activities.DeleteFavoriteActivity import DeleteFavoriteActivity, DeleteFavoriteActivityInputSet, DeleteFavoriteActivityResultSet, DeleteFavoriteActivityChoreographyExecution from temboo.Library.Fitbit.Activities.GetActivities import GetActivities, GetActivitiesInputSet, GetActivitiesResultSet, GetActivitiesChoreographyExecution from temboo.Library.Fitbit.Activities.GetActivity import GetActivity, GetActivityInputSet, GetActivityResultSet, GetActivityChoreographyExecution from temboo.Library.Fitbit.Activities.GetActivityDailyGoals import GetActivityDailyGoals, GetActivityDailyGoalsInputSet, GetActivityDailyGoalsResultSet, GetActivityDailyGoalsChoreographyExecution from temboo.Library.Fitbit.Activities.GetActivityWeeklyGoals import GetActivityWeeklyGoals, GetActivityWeeklyGoalsInputSet, GetActivityWeeklyGoalsResultSet, GetActivityWeeklyGoalsChoreographyExecution from temboo.Library.Fitbit.Activities.GetFavoriteActivities import GetFavoriteActivities, GetFavoriteActivitiesInputSet, GetFavoriteActivitiesResultSet, GetFavoriteActivitiesChoreographyExecution from temboo.Library.Fitbit.Activities.GetFrequentActivities import GetFrequentActivities, GetFrequentActivitiesInputSet, GetFrequentActivitiesResultSet, GetFrequentActivitiesChoreographyExecution from temboo.Library.Fitbit.Activities.GetRecentActivities import GetRecentActivities, GetRecentActivitiesInputSet, GetRecentActivitiesResultSet, GetRecentActivitiesChoreographyExecution from temboo.Library.Fitbit.Activities.LogActivity import LogActivity, LogActivityInputSet, LogActivityResultSet, LogActivityChoreographyExecution from temboo.Library.Fitbit.Activities.UpdateActivityDailyGoals import UpdateActivityDailyGoals, UpdateActivityDailyGoalsInputSet, UpdateActivityDailyGoalsResultSet, UpdateActivityDailyGoalsChoreographyExecution from temboo.Library.Fitbit.Activities.UpdateActivityWeeklyGoals import UpdateActivityWeeklyGoals, UpdateActivityWeeklyGoalsInputSet, UpdateActivityWeeklyGoalsResultSet, UpdateActivityWeeklyGoalsChoreographyExecution
gpl-2.0
alex-winter/totton-timber
media/com_hikashop/mail/waitlist_notification.html.php
877
<?php /** * @package HikaShop for Joomla! * @version 2.3.4 * @author hikashop.com * @copyright (C) 2010-2014 HIKARI SOFTWARE. All rights reserved. * @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html */ defined('_JEXEC') or die('Restricted access'); ?><?php echo JText::sprintf('HI_CUSTOMER',@$data->name);?><br/> <br/> <?php echo JText::sprintf('WAITLIST_SUBSCRIBE_FOR_PRODUCT', $data->product_name);?><br/> <?php if($data->product_quantity < 0 ) { $data->product_quantity = JText::_('UNLIMITED'); } echo JText::sprintf('THERE_IS_NOW_QTY_FOR_PRODUCT', $data->product_quantity);?><br/> <?php $url = HIKASHOP_LIVE . 'index.php?option=com_hikashop&ctrl=product&task=show&cid='. $data->product_id . '&Itemid='. $data->product_item_id; echo JText::sprintf('SEE_PRODUCT', $url); ?><br/> <br/> <?php echo JText::sprintf('BEST_REGARDS_CUSTOMER',$mail->from_name);?>
gpl-2.0
KimJongSkill/Baked-Potatoes-Library
Library Tests/Hash.Test.cpp
2095
#include "targetver.h" #include "CppUnitTest.h" #include "Hash.hpp" #include <sstream> #include <iomanip> #include <array> #include <algorithm> using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace LibraryTests { TEST_CLASS(SHA1Test) { bpl::crypt::hash::SHA1Context SHA1; std::string ToHex(const std::array<uint8_t, 20>& Result) { std::stringstream Stream; for (auto i : Result) Stream << std::setfill('0') << std::setw(2) << std::hex << static_cast<unsigned>(i); return Stream.str(); } TEST_METHOD(Febooti) { // http://www.febooti.com/products/filetweak/members/hash-and-crc/test-vectors/ std::string Test1 = "The quick brown fox jumps over the lazy dog"; std::string Test2 = "Test vector from febooti.com"; std::string Test3 = ""; Assert::AreEqual("2fd4e1c67a2d28fced849ee1bb76e7391b93eb12", SHA1.Hash(Test1.c_str(), Test1.length()).c_str()); Assert::AreEqual("a7631795f6d59cd6d14ebd0058a6394a4b93d868", SHA1.Hash(Test2.c_str(), Test2.length()).c_str()); Assert::AreEqual("da39a3ee5e6b4b0d3255bfef95601890afd80709", SHA1.Hash(Test3.c_str(), Test3.length()).c_str()); } TEST_METHOD(ContextResetsOnHash) { auto First = SHA1.Hash("Hello World", 11); auto Second = SHA1.Hash("Hello World", 11); Assert::IsTrue(std::equal(First.begin(), First.end(), Second.begin())); } TEST_METHOD(Performance) { for (std::size_t i = 0; i < 10000; ++i) SHA1.Hash("Hello, World!", 13); } TEST_METHOD(FIPS180) { // http://csrc.nist.gov/publications/fips/fips180-2/fips180-2withchangenotice.pdf std::string Test1 = "abc"; std::string Test2 = "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"; std::string Test3(1000000, 'a'); Assert::AreEqual("a9993e364706816aba3e25717850c26c9cd0d89d", SHA1.Hash(Test1.c_str(), Test1.length()).c_str()); Assert::AreEqual("84983e441c3bd26ebaae4aa1f95129e5e54670f1", SHA1.Hash(Test2.c_str(), Test2.length()).c_str()); Assert::AreEqual("34aa973cd4c4daa4f61eeb2bdbad27316534016f", SHA1.Hash(Test3.c_str(), Test3.length()).c_str()); } }; }
gpl-2.0
crossyou/sobird
app/front/ppt/fis-conf.js
946
/** * home模块fis2配置文件 * * @see https://github.com/fis-dev/fis/wiki/配置API * @author Yang,junlong at 2015-3-10 17:14:15 build. * @version $Id$ */ //基础配置信息 fis.config.merge({ namespace : 'ppt', project : { // 使用project.exclude排除某些后缀 svn、cvs默认已排除 exclude : /\.(tar|rar|psd|jar|bat)$/i }, settings: { spriter: { csssprites: { //图之间的边距 margin: 5 } } } }); fis.config.merge({ statics: '/static', templates: '/template' }); //图片转png8工具,解决ie6下透明问题。 fis.config.set('settings.optimizer.png-compressor.type', 'pngquant'); //fis.config.set('settings.spriter.csssprites.layout', 'matrix'); fis.config.merge({ roadmap : { //domain : 'http://static.sobird.me', path : [] } }); //打包策略 fis.config.set('pack', { }); /* End of file: fis-conf.js */ /* Location: ./common/fis-conf.js */
gpl-2.0
zhifeichen/base64codec
base64codec/stdafx.cpp
136
// stdafx.cpp : Ö»°üÀ¨±ê×¼°üº¬ÎļþµÄÔ´Îļþ // base64codec.pch ½«×÷ΪԤ±àÒëÍ· // stdafx.obj ½«°üº¬Ô¤±àÒëÀàÐÍÐÅÏ¢ #include "stdafx.h"
gpl-2.0
ipti/guigoh
src/main/java/br/org/ipti/guigoh/util/CookieService.java
2997
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package br.org.ipti.guigoh.util; import javax.faces.context.FacesContext; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author ipti004 */ public class CookieService { private static HttpServletRequest request; private static HttpServletResponse response; public static String getCookie(String name) { request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest(); Cookie[] cookies = request.getCookies(); String value = null; if (cookies != null) { for (Cookie cookie : cookies) { if (cookie.getName().trim().equalsIgnoreCase(name)) { value = cookie.getValue(); break; } } } return value; } public static String getCookie(String name, HttpServletRequest request){ Cookie[] cookies = request.getCookies(); String value = null; if (cookies != null) { for (Cookie cookie : cookies) { if (cookie.getName().trim().equalsIgnoreCase(name)) { value = cookie.getValue(); break; } } } return value; } public static void eraseCookie(String name) { request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest(); Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if (cookie.getName().trim().equalsIgnoreCase(name)) { cookie.setValue(""); cookie.setPath("/"); cookie.setMaxAge(0); response.addCookie(cookie); } } } } public static void eraseCookies() { request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest(); response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse(); Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if (!cookie.getName().equals("locale")) { cookie.setValue(""); cookie.setPath("/"); cookie.setMaxAge(0); response.addCookie(cookie); } } } } public static void addCookie(String key, String value) { response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse(); Cookie cookie = new Cookie(key, value); cookie.setPath("/"); cookie.setMaxAge(86400); response.addCookie(cookie); } }
gpl-2.0
wangping0214/IAPServer
src/com/rainbow/iap/dao/UnicomIAPDAO.java
260
package com.rainbow.iap.dao; import com.rainbow.iap.entity.UnicomIAPInfo; public interface UnicomIAPDAO { public void save(UnicomIAPInfo unicomIAPInfo); public void update(UnicomIAPInfo unicomIAPInfo); public UnicomIAPInfo getByOrderId(String orderId); }
gpl-2.0
mrkline/git-historian
src/parsing.rs
5316
//! Parses `git log --name-status` to generate a stream of file changes //! in Git history //! //! Originally the [Rust bindings](https://crates.io/crates/git2) for //! [libgit2](https://libgit2.github.com/) was used, //! but there is currently no clean or efficient way for libgit to generate //! diffs for merges (i.e. only the changes resulting from conflict resolution) //! as Git does. use std::io::{self, BufReader, BufRead}; use std::process::{Child, Command, Stdio}; use std::sync::mpsc::SyncSender; use time::Timespec; use types::*; /// Info about a commit pulled from `git log` (or at least the bits we care about) #[derive(Debug, Clone)] pub struct ParsedCommit { pub id: SHA1, /// The Unix timestamp (in seconds) of the commit pub when: Timespec, pub deltas: Vec<FileDelta>, } impl Default for ParsedCommit { fn default() -> ParsedCommit { ParsedCommit { id: SHA1::default(), when: Timespec::new(0, 0), deltas: Vec::new() } } } /// Starts the `git log` process with the desired config fn start_history_process() -> Result<Child, io::Error> { Command::new("git") .arg("log") .arg("--name-status") .arg("-M") .arg("-C") .arg("--pretty=format:%H%n%at") // Commit hash, newline, unix time .stdout(Stdio::piped()) .spawn() } /// Parses the Git history and emits a series of `ParsedCommits` /// /// The parsed commits are pushed to a `SyncSender`, /// and are assumed to be consumed by another thread. pub fn get_history(sink: &SyncSender<ParsedCommit>) { enum ParseState { // Used for the state machine below Hash, Timestamp, Changes } let child = start_history_process().expect("Couldn't open repo history"); let br = BufReader::new(child.stdout.unwrap()); let mut state = ParseState::Hash; let mut current_commit = ParsedCommit::default(); for line in br.lines().map(|l| l.unwrap()) { if line.is_empty() { continue; } // Blow through empty lines let next_state; match state { ParseState::Hash => { current_commit.id = SHA1::parse(&line).unwrap(); next_state = ParseState::Timestamp; } ParseState::Timestamp => { current_commit.when = Timespec{ sec: line.parse().unwrap(), nsec: 0 }; next_state = ParseState::Changes; } ParseState::Changes => { // If we get the next hash, we're done with the previous commit. if let Ok(id) = SHA1::parse(&line) { commit_sink(current_commit, sink); current_commit = ParsedCommit::default(); // We just got the OID of the next commit, // so proceed to reading the timestamp current_commit.id = id; next_state = ParseState::Timestamp; } else { // Keep chomping deltas next_state = state; current_commit.deltas.push(parse_delta(&line)); } } } state = next_state; } // Grab the last commit. commit_sink(current_commit, sink); } /// Sends a commit when the state machine is done parsing it. #[inline] fn commit_sink(c: ParsedCommit, sink: &SyncSender<ParsedCommit>) { sink.send(c).expect("The other end stopped listening for commits."); } /// Parses a delta line generated by `git log --name-status` fn parse_delta(s: &str) -> FileDelta { let tokens : Vec<&str> = s.split('\t').collect(); assert!(tokens.len() > 1, "Expected at least one token"); let c = parse_change_code(tokens[0]); let previous : String; let current : String; match c { Change::Renamed { .. } | Change::Copied { .. }=> { assert_eq!(tokens.len(), 3, "Expected three tokens from string {:?}", s); current = tokens[2].to_string(); previous = tokens[1].to_string(); } _ => { assert_eq!(tokens.len(), 2, "Expected two tokens from string {:?}", s); current = tokens[1].to_string(); previous = String::new(); } }; FileDelta{ change: c, path: current, from: previous } } /// Parses the change code generated by `git log --name-status` fn parse_change_code(c: &str) -> Change { assert!(!c.is_empty()); let ret = match c.chars().nth(0).unwrap() { 'A' => Change::Added, 'D' => Change::Deleted, 'M' | 'T' => Change::Modified, // Let's consider a type change a modification. // Renames and copies are suffixed with a percent changed, e.g. "R87" 'R' => Change::Renamed{ percent_changed: c[1..].parse().unwrap() }, 'C' => Change::Copied{ percent_changed: c[1..].parse().unwrap() }, _ => panic!("Unknown delta code: {}", c) }; // Sanity check percent_changed values for renames and copies match ret { Change::Renamed{ percent_changed: r} => { assert!(r <= 100); }, Change::Copied{ percent_changed: c} => { assert!(c <= 100); }, _ => { } }; ret }
gpl-2.0
itajaja/SFCLogMonitor
SFCLogMonitor/Properties/Resources.Designer.cs
2791
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.18052 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace SFCLogMonitor.Properties { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("SFCLogMonitor.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
gpl-2.0
seamusic/CodeFirst
src/Core/Lennon.Web/Mvc/Binders/StringTrimModelBinder.cs
678
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web.Mvc; namespace Lennon.Web.Mvc.Binders { /// <summary> /// 模型字符串处理类,处理传入字符串的前后空格 /// </summary> public class StringTrimModelBinder : DefaultModelBinder { public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { object value = base.BindModel(controllerContext, bindingContext); if (value is string) { return (value as string).Trim(); } return value; } } }
gpl-2.0