repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
rdunlop/unicycling-registration
app/actions/importers/parsers/lif.rb
1251
class Importers::Parsers::Lif < Importers::Parsers::Base def extract_file data = Importers::CsvExtractor.new(file).extract_csv data.drop(1) # drop header row end def validate_contents if file_contents.first.count < 7 @errors << "Not enough columns. Are you sure this is a comma-separated file?" end end def process_row(raw) lif_hash = convert_lif_to_hash(raw) { lane: lif_hash[:lane], minutes: lif_hash[:minutes], seconds: lif_hash[:seconds], thousands: lif_hash[:thousands], status: (lif_hash[:disqualified] ? "DQ" : "active") } end def convert_lif_to_hash(arr) results = {} results[:lane] = arr[2] full_time = arr[6].to_s # TODO: Extract this into a StatusTranslation if full_time == "DQ" || arr[0] == "DQ" || arr[0] == "DNS" || arr[0] == "DNF" results[:disqualified] = true results[:minutes] = 0 results[:seconds] = 0 results[:thousands] = 0 else results[:disqualified] = false time_result = TimeParser.new(full_time).result results[:minutes] = time_result[:minutes] results[:seconds] = time_result[:seconds] results[:thousands] = time_result[:thousands] end results end end
mit
darul75/starter-aws
Gruntfile.js
890
module.exports = function(grunt) { 'use strict'; // Project configuration. grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), jshint: { files: ['src/**/*.js', 'test/**/*.js'] }, // UGLIFY TASK uglify: { task1: { options: { preserveComments: 'some', report: 'min', banner: '/** \n* @license <%= pkg.name %> - v<%= pkg.version %>\n' + '* (c) 2013 Julien VALERY https://github.com/darul75/starter-aws\n' + '* License: MIT \n**/\n' }, files: { 'lib/starter-aws.js': ['src/starter-aws.js'], 'lib/config.js': ['src/config.js'] } } } }); // LOAD PLUGINS grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-uglify'); // TASK REGISTER grunt.registerTask('default', ['jshint', 'uglify:task1']); };
mit
mikebluestein/learning_monotouch_code
ch7/LMT7-3/LMT7-3/LocationTableViewController.xib.cs
3575
using System; using System.Collections.Generic; using System.Linq; using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreLocation; namespace LMT73 { public partial class LocationTableViewController : UIViewController { LocationTableSource _source; List<CLLocation> _locations; CLRegion _testRegion; #region Constructors // The IntPtr and initWithCoder constructors are required for items that need // to be able to be created from a xib rather than from managed code public LocationTableViewController (IntPtr handle) : base(handle) { Initialize (); } [Export("initWithCoder:")] public LocationTableViewController (NSCoder coder) : base(coder) { Initialize (); } public LocationTableViewController () : base("LocationTableViewController", null) { Initialize (); } void Initialize () { } #endregion public override void ViewDidLoad () { base.ViewDidLoad (); _locations = LocationHelper.Instance.Locations; LocationHelper.Instance.LocationAdded += delegate { locationTable.ReloadData (); }; startLocation.Clicked += delegate { LocationHelper.Instance.StartLocationUpdates (); // creating and arbitrary region for now // we'll make this interactive when we introduce mapkit in the next chapter _testRegion = new CLRegion (new CLLocationCoordinate2D (41.79554472, -72.62135916), 1000, "testRegion"); LocationHelper.Instance.StartRegionUpdates (_testRegion); }; stopLocation.Clicked += delegate { LocationHelper.Instance.StopLocationUpdates (); LocationHelper.Instance.StartRegionUpdates (_testRegion); }; _source = new LocationTableSource (this); locationTable.Source = _source; } class LocationTableSource : UITableViewSource { static string cellId = "locationCell"; LocationTableViewController _controller; public LocationTableSource (LocationTableViewController controller) { _controller = controller; } public override int RowsInSection (UITableView tableview, int section) { return _controller._locations.Count (); } public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) { UITableViewCell cell = tableView.DequeueReusableCell (cellId); if (cell == null) cell = new UITableViewCell (UITableViewCellStyle.Subtitle, cellId); cell.TextLabel.Text = String.Format ("(lat/lon) {0}, {1}", _controller._locations[indexPath.Row].Coordinate.Latitude, _controller._locations[indexPath.Row].Coordinate.Longitude); cell.DetailTextLabel.Text = String.Format ("(timestamp) {0}", _controller._locations[indexPath.Row].Timestamp.ToString ()); return cell; } } } }
mit
arslanoguzhan/NeoniumFramework
NeoniumFramework/vendor/Neonium/Core/Types/StringType.php
113
<?php namespace Neonium\Core\Types; use Neonium\Core\Object; abstract class StringType extends Object { } ?>
mit
ChiragKalia/AlgorithmsAndDataStructures
DataStructures/Helpers/SwapVars.cs
343
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DataStructures.Helpers { public static class SwapVars { public static void Swap(ref int a, ref int b) { int temp = a; a = b; b = temp; } } }
mit
andymeneely/dev-fortress-server
app/routes/user.js
4913
const userController = require('../controllers/user'); const authenticationController = require('../controllers/authentication'); const authenticationMiddleware = require('../middleware/authentication'); const express = require('express'); const router = express.Router(); /** * @api {get} /user Get Users * @apiName GetUsers * @apiGroup User * * @apiDescription * Retrieve all Users. Requires authentication. * * @apiHeader {String} Authorization Bearer [JWT_TOKEN] * * @apiSuccess {Object[]} users List of Users. * @apiSuccess {Number} users.id Primary key. * @apiSuccess {String} users.username Username; unique. * @apiSuccess {Boolean} users.is_admin Indicates whether or not the User is an Administrator. * @apiSuccess {String} users.created_at ISO String timestamp of when the User was created. */ router.get( '/', // route authenticationMiddleware.validateAuthentication, // isAuthenticated middleware userController.getUsers // the controller ); /** * @api {get} /user/:id Get User by ID * @apiName GetUser * @apiGroup User * * @apiDescription * Retrieve a User by ID. Requires authentication. * * @apiHeader {String} Authorization Bearer [JWT_TOKEN] * * @apiParam {Number} :id User's primary key * * @apiSuccess {Number} id Primary key. * @apiSuccess {String} username Username; unique. * @apiSuccess {Boolean} is_admin Indicates whether or not the User is an Administrator. * @apiSuccess {String} created_at ISO String timestamp of when the User was created. */ router.get( '/:id', authenticationMiddleware.validateAuthentication, // isAuthenticated middleware userController.getUserById ); /** * @api {post} /user Create New User * @apiName CreateUser * @apiGroup User * * @apiDescription * Create a new User. Requires Administrator authentication. * * @apiHeader {String} Authorization Bearer [JWT_TOKEN] * * @apiParam {String} username Unique username for the User. * @apiParam {String} password Password for the User. * @apiParam {String} email Unique email address of the User. * @apiParam {Boolean} [is_admin] Set `true` for Admin account. * * @apiSuccess {Number} id Primary key of the new User. * @apiSuccess {String} username Username of the new User. */ router.post( '/', authenticationMiddleware.validateAuthenticationAttachEntity, authenticationMiddleware.verifyAdministrator, userController.registerNewUser ); /** * @api {delete} /user/:id Delete User by ID * @apiName DeleteUser * @apiGroup User * * @apiDescription * Delete an existing User. Requires administrator authentication. * * @apiHeader {String} Authorization Bearer [JWT_TOKEN] * * @apiParam {String} :id ID of the User to be deleted. */ router.delete( '/:id', authenticationMiddleware.validateAuthenticationAttachEntity, authenticationMiddleware.verifyAdministrator, userController.deleteUserById ); /** * @api {patch} /user/:id/roles Set User Role * @apiName AttachUserRole * @apiGroup User * * @apiDescription * Attach an existing User to a Role. Requires Administrator authentication. * * @apiHeader {String} Authorization Bearer [JWT_TOKEN] * * @apiParam {String} :id Primary key for the existing User. * @apiParam {Number} [add] The Role ID to add the User to. * @apiParam {Number} [remove] The Role ID to remove the User from. */ router.patch( '/:id/roles', authenticationMiddleware.validateAuthenticationAttachEntity, authenticationMiddleware.verifyAdministrator, userController.setRoles ); /** * @api {post} /user/login Login to User Account * @apiName UserLogin * @apiGroup User * * @apiDescription * Login to an existing User account. * * @apiParam {String} username The username for the User. * @apiParam {String} password The password for the User. * * @apiSuccess {String} token The JWT token with which to send authenticated requests. */ router.post( '/login', authenticationController.login ); /** * @api {post} /user/refresh Refresh JWT Token * @apiName UserRefreshToken * @apiGroup User * * @apiDescription * Refresh the JWT token of the User making the request. Requires authentication. * * @apiHeader {String} Authorization Bearer [JWT_TOKEN] * * @apiSuccess {String} token A new JWT token with which * to send authenticated requests. */ router.post( '/refresh', authenticationMiddleware.validateAuthenticationAttachEntity, authenticationController.refreshToken ); /** * Generate 404s. * Only use this at the bottom of custom route handlers. */ router.use((req, res) => { res.status(404).json({ error: 'Not Found', request: req.body, }); }); module.exports = router;
mit
ccclayton/DataWar
static/js/threejs.r65/editor/js/Viewport.js
10571
var Viewport = function ( editor ) { var signals = editor.signals; var container = new UI.Panel(); container.setPosition( 'absolute' ); var info = new UI.Text(); info.setPosition( 'absolute' ); info.setRight( '5px' ); info.setBottom( '5px' ); info.setFontSize( '12px' ); info.setColor( '#ffffff' ); info.setValue( 'objects: 0, vertices: 0, faces: 0' ); container.add( info ); var scene = editor.scene; var sceneHelpers = editor.sceneHelpers; var objects = []; // helpers var grid = new THREE.GridHelper( 500, 25 ); sceneHelpers.add( grid ); // var camera = new THREE.PerspectiveCamera( 50, container.dom.offsetWidth / container.dom.offsetHeight, 1, 5000 ); camera.position.fromArray( editor.config.getKey( 'camera' ).position ); camera.lookAt( new THREE.Vector3().fromArray( editor.config.getKey( 'camera' ).target ) ); // var selectionBox = new THREE.BoxHelper(); selectionBox.material.depthTest = false; selectionBox.material.transparent = true; selectionBox.visible = false; sceneHelpers.add( selectionBox ); var transformControls = new THREE.TransformControls( camera, container.dom ); transformControls.addEventListener( 'change', function () { controls.enabled = true; if ( transformControls.axis !== undefined ) { controls.enabled = false; } if ( editor.selected !== null ) { signals.objectChanged.dispatch( editor.selected ); } } ); sceneHelpers.add( transformControls ); // fog var oldFogType = "None"; var oldFogColor = 0xaaaaaa; var oldFogNear = 1; var oldFogFar = 5000; var oldFogDensity = 0.00025; // object picking var ray = new THREE.Raycaster(); var projector = new THREE.Projector(); // events var getIntersects = function ( event, object ) { var rect = container.dom.getBoundingClientRect(); x = ( event.clientX - rect.left ) / rect.width; y = ( event.clientY - rect.top ) / rect.height; var vector = new THREE.Vector3( ( x ) * 2 - 1, - ( y ) * 2 + 1, 0.5 ); projector.unprojectVector( vector, camera ); ray.set( camera.position, vector.sub( camera.position ).normalize() ); if ( object instanceof Array ) { return ray.intersectObjects( object ); } return ray.intersectObject( object ); }; var onMouseDownPosition = new THREE.Vector2(); var onMouseUpPosition = new THREE.Vector2(); var onMouseDown = function ( event ) { event.preventDefault(); var rect = container.dom.getBoundingClientRect(); x = (event.clientX - rect.left) / rect.width; y = (event.clientY - rect.top) / rect.height; onMouseDownPosition.set( x, y ); document.addEventListener( 'mouseup', onMouseUp, false ); }; var onMouseUp = function ( event ) { var rect = container.dom.getBoundingClientRect(); x = (event.clientX - rect.left) / rect.width; y = (event.clientY - rect.top) / rect.height; onMouseUpPosition.set( x, y ); if ( onMouseDownPosition.distanceTo( onMouseUpPosition ) == 0 ) { var intersects = getIntersects( event, objects ); if ( intersects.length > 0 ) { var object = intersects[ 0 ].object; if ( object.userData.object !== undefined ) { // helper editor.select( object.userData.object ); } else { editor.select( object ); } } else { editor.select( null ); } render(); } document.removeEventListener( 'mouseup', onMouseUp ); }; var onDoubleClick = function ( event ) { var intersects = getIntersects( event, objects ); if ( intersects.length > 0 && intersects[ 0 ].object === editor.selected ) { controls.focus( editor.selected ); } }; container.dom.addEventListener( 'mousedown', onMouseDown, false ); container.dom.addEventListener( 'dblclick', onDoubleClick, false ); // controls need to be added *after* main logic, // otherwise controls.enabled doesn't work. var controls = new THREE.EditorControls( camera, container.dom ); controls.center.fromArray( editor.config.getKey( 'camera' ).target ) controls.addEventListener( 'change', function () { transformControls.update(); signals.cameraChanged.dispatch( camera ); } ); // signals signals.themeChanged.add( function ( value ) { switch ( value ) { case 'css/light.css': grid.setColors( 0x444444, 0x888888 ); clearColor = 0xaaaaaa; break; case 'css/dark.css': grid.setColors( 0xbbbbbb, 0x888888 ); clearColor = 0x333333; break; } renderer.setClearColor( clearColor ); render(); } ); signals.transformModeChanged.add( function ( mode ) { transformControls.setMode( mode ); } ); signals.snapChanged.add( function ( dist ) { transformControls.setSnap( dist ); } ); signals.spaceChanged.add( function ( space ) { transformControls.setSpace( space ); } ); signals.rendererChanged.add( function ( type ) { container.dom.removeChild( renderer.domElement ); renderer = new THREE[ type ]( { antialias: true } ); renderer.autoClear = false; renderer.autoUpdateScene = false; renderer.setClearColor( clearColor ); renderer.setSize( container.dom.offsetWidth, container.dom.offsetHeight ); container.dom.appendChild( renderer.domElement ); render(); } ); signals.sceneGraphChanged.add( function () { render(); updateInfo(); } ); signals.cameraChanged.add( function () { editor.config.setKey( 'camera', { position: camera.position.toArray(), target: controls.center.toArray() } ); render(); } ); signals.objectSelected.add( function ( object ) { selectionBox.visible = false; transformControls.detach(); if ( object !== null ) { if ( object.geometry !== undefined ) { selectionBox.update( object ); selectionBox.visible = true; } if ( object instanceof THREE.PerspectiveCamera === false ) { transformControls.attach( object ); } } render(); } ); signals.objectAdded.add( function ( object ) { var materialsNeedUpdate = false; object.traverse( function ( child ) { if ( child instanceof THREE.Light ) materialsNeedUpdate = true; objects.push( child ); } ); if ( materialsNeedUpdate === true ) updateMaterials(); } ); signals.objectChanged.add( function ( object ) { transformControls.update(); if ( object !== camera ) { if ( object.geometry !== undefined ) { selectionBox.update( object ); } if ( editor.helpers[ object.id ] !== undefined ) { editor.helpers[ object.id ].update(); } updateInfo(); } render(); } ); signals.objectRemoved.add( function ( object ) { var materialsNeedUpdate = false; object.traverse( function ( child ) { if ( child instanceof THREE.Light ) materialsNeedUpdate = true; objects.splice( objects.indexOf( child ), 1 ); } ); if ( materialsNeedUpdate === true ) updateMaterials(); } ); signals.helperAdded.add( function ( object ) { objects.push( object.getObjectByName( 'picker' ) ); } ); signals.helperRemoved.add( function ( object ) { objects.splice( objects.indexOf( object.getObjectByName( 'picker' ) ), 1 ); } ); signals.materialChanged.add( function ( material ) { render(); } ); signals.fogTypeChanged.add( function ( fogType ) { if ( fogType !== oldFogType ) { if ( fogType === "None" ) { scene.fog = null; } else if ( fogType === "Fog" ) { scene.fog = new THREE.Fog( oldFogColor, oldFogNear, oldFogFar ); } else if ( fogType === "FogExp2" ) { scene.fog = new THREE.FogExp2( oldFogColor, oldFogDensity ); } updateMaterials(); oldFogType = fogType; } render(); } ); signals.fogColorChanged.add( function ( fogColor ) { oldFogColor = fogColor; updateFog( scene ); render(); } ); signals.fogParametersChanged.add( function ( near, far, density ) { oldFogNear = near; oldFogFar = far; oldFogDensity = density; updateFog( scene ); render(); } ); signals.windowResize.add( function () { camera.aspect = container.dom.offsetWidth / container.dom.offsetHeight; camera.updateProjectionMatrix(); renderer.setSize( container.dom.offsetWidth, container.dom.offsetHeight ); render(); } ); signals.playAnimations.add( function (animations) { function animate() { requestAnimationFrame( animate ); for ( var i = 0; i < animations.length ; i ++ ) { animations[i].update(0.016); } render(); } animate(); } ); // var clearColor, renderer; if ( editor.config.getKey( 'renderer' ) !== undefined ) { renderer = new THREE[ editor.config.getKey( 'renderer' ) ]( { antialias: true } ); } else { if ( System.support.webgl === true ) { renderer = new THREE.WebGLRenderer( { antialias: true } ); } else { renderer = new THREE.CanvasRenderer(); } } renderer.autoClear = false; renderer.autoUpdateScene = false; container.dom.appendChild( renderer.domElement ); animate(); // function updateInfo() { var objects = 0; var vertices = 0; var faces = 0; scene.traverse( function ( object ) { if ( object instanceof THREE.Mesh ) { objects ++; var geometry = object.geometry; if ( geometry instanceof THREE.Geometry ) { vertices += geometry.vertices.length; faces += geometry.faces.length; } else if ( geometry instanceof THREE.BufferGeometry ) { vertices += geometry.attributes.position.array.length / 3; if ( geometry.attributes.index !== undefined ) { faces += geometry.attributes.index.array.length / 3; } else { faces += vertices / 3; } } } } ); info.setValue( 'objects: ' + objects + ', vertices: ' + vertices + ', faces: ' + faces ); } function updateMaterials() { editor.scene.traverse( function ( node ) { if ( node.material ) { node.material.needsUpdate = true; if ( node.material instanceof THREE.MeshFaceMaterial ) { for ( var i = 0; i < node.material.materials.length; i ++ ) { node.material.materials[ i ].needsUpdate = true; } } } } ); } function updateFog( root ) { if ( root.fog ) { root.fog.color.setHex( oldFogColor ); if ( root.fog.near !== undefined ) root.fog.near = oldFogNear; if ( root.fog.far !== undefined ) root.fog.far = oldFogFar; if ( root.fog.density !== undefined ) root.fog.density = oldFogDensity; } } function animate() { requestAnimationFrame( animate ); } function render() { sceneHelpers.updateMatrixWorld(); scene.updateMatrixWorld(); renderer.clear(); renderer.render( scene, camera ); renderer.render( sceneHelpers, camera ); //console.trace(); } return container; }
mit
zeageorge/Project01_8PD
protected/views/header.php
4273
<?php \defined('_JEXEC') or die('Restricted access'); $cfg = \Project\libs\Project::getConfig(); $isGuest = Project\libs\Tools::getUserIsGuest(); $strAuthor = $cfg->systemAdminName." <".$cfg->systemAdminEmailAddress.">"; $cssUrl = $cfg->cssUrl; $jsUrl = $cfg->jsUrl; $imagesUrl = $cfg->imagesUrl; ?> <!doctype html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content=""> <meta name="author" content="<?php echo $strAuthor;?>"> <meta http-equiv="Content-Type" content="text/html;"> <meta http-equiv="cache-control" content="max-age=0" /> <meta http-equiv="cache-control" content="no-cache" /> <meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT" /> <meta http-equiv="pragma" content="no-cache" /> <?php /** Global css */?> <link href="<?php echo $cssUrl;?>global.css" rel="stylesheet" media="screen"> <!--[if IE 6]> <link href="<?php echo $cssUrl;?>ie6.css" rel="stylesheet" type="text/css"> <![endif]--> <!--[if IE 7]> <link href="<?php echo $cssUrl;?>ie7.css" rel="stylesheet" type="text/css"> <![endif]--> <?php /** Per requested page css */?> <?php $f = $cfg->cssFolderPath . $this->controllerName . \DS . $this->actionName . ".css"; if (\is_readable($f)) { echo "<link href=\"".$cssUrl.$this->controllerName . "/" . $this->actionName . ".css\" rel=\"stylesheet\" media=\"screen\">"; } ?> <?php /** Global scripts */?> <script src="<?php echo $jsUrl;?>jquery-1.10.2.min.js"></script> <script src="<?php echo $jsUrl;?>core.js"></script> <?php /** Per requested page scripts */?> <?php $f = $cfg->jsFolderPath . $this->controllerName . \DS . $this->actionName . ".js"; if (\is_readable($f)) { echo "<script src=\"" . $jsUrl . $this->controllerName . "/" . $this->actionName . ".js\"></script>"; } ?> <title><?php echo $cfg->siteTitle ."::". $this->pageTitle ?></title> </head> <body> <div id="background"> <div <?php echo $this->controllerName!==$cfg->http_request_defaultControllerName?'class="page"':'id="page"';?>> <div id="header"> <a id="logo" href="index.php?url=index"> <img src="<?php echo $imagesUrl;?>logo.jpg" width="276" height="203" alt="Steak House" title="Steak House"> </a> <div id="social_icons"> <span>Follow us:</span> <a href="http://www.facebook.com/zeageorge" class="facebook">&nbsp;</a> <a href="https://twitter.com/zeageorge" class="twitter">&nbsp;</a> <a href="https://plus.google.com/u/0/102990311574823512033/posts" class="googleplus">&nbsp;</a> <?php if (!Project\libs\Tools::getUserIsGuest()){ echo '<br><br><br><br><br><a id="dashboard_link" href="index.php?url=user/dashboard">Dashboard</a>'; } ?> </div> <ul class="navigation"> <li><a href="index.php?url=food">Το Φαγητό μας</a></li> <li><a href="index.php?url=photo_gallery">Ο χώρος μας</a></li> <li><a href="index.php?url=order">Παραγγελιά </a></li> <li><a href="index.php?url=user/<?php echo $isGuest?'login':'logout'; ?>"><?php echo $isGuest?'Είσοδος':'Έξοδος'; ?></a></li> <li> <a href="index.php?url=news" id="menuItem01">Ανακοινώσεις</a> <!-- <ul class="subMenu displayNone"> <li><a href="index.php?url=news">Προβολή</a></li> <li><a href="index.php?url=news">Αποθήκευση</a></li> </ul>--> </li> <li><a href="index.php?url=contact">Επικοινωνία</a></li> </ul> </div>
mit
pianoman373/crucible
include/crucible/Scene.hpp
1153
#pragma once #include <crucible/GameObject.hpp> #include <vector> class CrucibleBulletDebugDraw; class btDefaultCollisionConfiguration; class btCollisionDispatcher; class btBroadphaseInterface; class btSequentialImpulseConstraintSolver; class btDiscreteDynamicsWorld; class Scene { private: std::vector<GameObject*> objects; btDefaultCollisionConfiguration* collisionConfiguration; btCollisionDispatcher* dispatcher; btBroadphaseInterface* overlappingPairCache; btSequentialImpulseConstraintSolver* solver; btDiscreteDynamicsWorld* dynamicsWorld; CrucibleBulletDebugDraw* debugDrawer; bool physicsEnabled = false; public: ~Scene(); GameObject &createObject(const Transform &transform, const std::string &name); GameObject &createMeshObject(Mesh &mesh, Material &material, const Transform &transform, const std::string &name); void render(); void update(float delta); void setupPhysicsWorld(); btDiscreteDynamicsWorld *getBulletWorld(); bool isPhysicsEnabled() const; int numObjects(); GameObject &getObject(int index); };
mit
InnovateUKGitHub/innovation-funding-service
ifs-web-service/ifs-competition-mgt-service/src/test/java/org/innovateuk/ifs/management/review/controller/ReviewInviteAssessorsOverviewControllerTest.java
10414
package org.innovateuk.ifs.management.review.controller; import org.apache.commons.lang3.StringUtils; import org.innovateuk.ifs.BaseControllerMockMVCTest; import org.innovateuk.ifs.category.resource.CategoryResource; import org.innovateuk.ifs.category.resource.InnovationAreaResource; import org.innovateuk.ifs.competition.resource.CompetitionResource; import org.innovateuk.ifs.competition.service.CompetitionKeyApplicationStatisticsRestService; import org.innovateuk.ifs.competition.service.CompetitionRestService; import org.innovateuk.ifs.invite.resource.AssessorInviteOverviewPageResource; import org.innovateuk.ifs.invite.resource.AssessorInviteOverviewResource; import org.innovateuk.ifs.management.assessor.viewmodel.InviteAssessorsViewModel; import org.innovateuk.ifs.management.assessor.viewmodel.OverviewAssessorRowViewModel; import org.innovateuk.ifs.management.review.model.ReviewInviteAssessorsOverviewModelPopulator; import org.innovateuk.ifs.management.review.viewmodel.ReviewInviteAssessorsOverviewViewModel; import org.innovateuk.ifs.review.resource.ReviewInviteStatisticsResource; import org.innovateuk.ifs.review.service.ReviewInviteRestService; import org.innovateuk.ifs.util.CompressedCookieService; import org.junit.Before; import org.junit.Test; import org.mockito.InOrder; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.springframework.test.web.servlet.MvcResult; import java.util.List; import static java.lang.Boolean.FALSE; import static java.lang.Boolean.TRUE; import static java.util.Arrays.asList; import static java.util.stream.Collectors.joining; import static org.apache.commons.lang3.StringUtils.EMPTY; import static org.innovateuk.ifs.category.builder.InnovationAreaResourceBuilder.newInnovationAreaResource; import static org.innovateuk.ifs.commons.rest.RestResult.restSuccess; import static org.innovateuk.ifs.competition.builder.CompetitionResourceBuilder.newCompetitionResource; import static org.innovateuk.ifs.competition.resource.CompetitionStatus.IN_ASSESSMENT; import static org.innovateuk.ifs.invite.builder.AssessorInviteOverviewPageResourceBuilder.newAssessorInviteOverviewPageResource; import static org.innovateuk.ifs.invite.builder.AssessorInviteOverviewResourceBuilder.newAssessorInviteOverviewResource; import static org.innovateuk.ifs.invite.resource.ParticipantStatusResource.PENDING; import static org.innovateuk.ifs.invite.resource.ParticipantStatusResource.REJECTED; import static org.innovateuk.ifs.review.builder.ReviewInviteStatisticsResourceBuilder.newReviewInviteStatisticsResource; import static org.innovateuk.ifs.user.resource.BusinessType.ACADEMIC; import static org.innovateuk.ifs.user.resource.BusinessType.BUSINESS; import static org.innovateuk.ifs.util.CollectionFunctions.asLinkedSet; import static org.innovateuk.ifs.util.CollectionFunctions.forEachWithIndex; import static org.innovateuk.ifs.util.CookieTestUtil.setupCompressedCookieService; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; public class ReviewInviteAssessorsOverviewControllerTest extends BaseControllerMockMVCTest<ReviewInviteAssessorsOverviewController> { @Spy @InjectMocks private ReviewInviteAssessorsOverviewModelPopulator panelInviteAssessorsOverviewModelPopulator; @Mock private CompressedCookieService cookieUtil; @Mock private CompetitionRestService competitionRestService; @Mock private CompetitionKeyApplicationStatisticsRestService competitionKeyApplicationStatisticsRestService; @Mock private ReviewInviteRestService reviewInviteRestService; @Override protected ReviewInviteAssessorsOverviewController supplyControllerUnderTest() { return new ReviewInviteAssessorsOverviewController(); } private CompetitionResource competition; private ReviewInviteStatisticsResource inviteStatistics; @Before public void setUp() { setupCompressedCookieService(cookieUtil); competition = newCompetitionResource() .withCompetitionStatus(IN_ASSESSMENT) .withName("Technology inspired") .withInnovationSectorName("Infrastructure systems") .withInnovationAreaNames(asLinkedSet("Transport Systems", "Urban living")) .build(); inviteStatistics = newReviewInviteStatisticsResource() .withAssessorsInvited(5) .withAssessorsAccepted(1) .withAssessorsRejected(1) .build(); when(competitionRestService.getCompetitionById(competition.getId())).thenReturn(restSuccess(competition)); when(competitionKeyApplicationStatisticsRestService.getReviewInviteStatisticsByCompetition(competition.getId())).thenReturn(restSuccess(inviteStatistics)); } @Test public void overview() throws Exception { int page = 1; List<Long> inviteIds = asList(1L, 2L); List<AssessorInviteOverviewResource> assessorInviteOverviewResources = setUpAssessorInviteOverviewResources(); AssessorInviteOverviewPageResource pageResource = newAssessorInviteOverviewPageResource() .withContent(assessorInviteOverviewResources) .build(); when(reviewInviteRestService.getInvitationOverview(competition.getId(), page, asList(REJECTED, PENDING))) .thenReturn(restSuccess(pageResource)); when(reviewInviteRestService.getNonAcceptedAssessorInviteIds(competition.getId())).thenReturn(restSuccess(inviteIds)); MvcResult result = mockMvc.perform(get("/assessment/panel/competition/{competitionId}/assessors/pending-and-declined", competition.getId()) .param("page", "1")) .andExpect(status().isOk()) .andExpect(model().attributeExists("model")) .andExpect(view().name("assessors/panel-overview")) .andReturn(); assertCompetitionDetails(competition, result); assertInviteOverviews(assessorInviteOverviewResources, result); InOrder inOrder = inOrder(competitionRestService, reviewInviteRestService); inOrder.verify(reviewInviteRestService).getNonAcceptedAssessorInviteIds(competition.getId()); inOrder.verify(competitionRestService).getCompetitionById(competition.getId()); inOrder.verify(reviewInviteRestService).getInvitationOverview(competition.getId(), page, asList(REJECTED, PENDING)); inOrder.verifyNoMoreInteractions(); } private List<AssessorInviteOverviewResource> setUpAssessorInviteOverviewResources() { return newAssessorInviteOverviewResource() .withId(1L, 2L) .withInviteId(3L, 4L) .withName("Dave Smith", "John Barnes") .withInnovationAreas(asList(newInnovationAreaResource() .withName("Earth Observation", "Healthcare, Analytical science") .buildArray(2, InnovationAreaResource.class))) .withCompliant(TRUE, FALSE) .withBusinessType(BUSINESS, ACADEMIC) .withStatus(PENDING, REJECTED) .withDetails("", "Invite declined: person is too busy") .build(2); } private void assertCompetitionDetails(CompetitionResource expectedCompetition, MvcResult result) { InviteAssessorsViewModel model = (InviteAssessorsViewModel) result.getModelAndView().getModel().get("model"); assertEquals(expectedCompetition.getId(), model.getCompetitionId()); assertEquals(expectedCompetition.getName(), model.getCompetitionName()); assertInnovationSectorAndArea(expectedCompetition, model); assertStatistics(model); } private void assertInnovationSectorAndArea(CompetitionResource expectedCompetition, InviteAssessorsViewModel model) { assertEquals(expectedCompetition.getInnovationSectorName(), model.getInnovationSector()); assertEquals(StringUtils.join(expectedCompetition.getInnovationAreaNames(), ", "), model.getInnovationArea()); } private void assertStatistics(InviteAssessorsViewModel model) { assertEquals(inviteStatistics.getInvited(), model.getAssessorsInvited()); assertEquals(inviteStatistics.getAccepted(), model.getAssessorsAccepted()); assertEquals(inviteStatistics.getDeclined(), model.getAssessorsDeclined()); } private void assertInviteOverviews(List<AssessorInviteOverviewResource> expectedInviteOverviews, MvcResult result) { assertTrue(result.getModelAndView().getModel().get("model") instanceof ReviewInviteAssessorsOverviewViewModel); ReviewInviteAssessorsOverviewViewModel model = (ReviewInviteAssessorsOverviewViewModel) result.getModelAndView().getModel().get("model"); assertEquals(expectedInviteOverviews.size(), model.getAssessors().size()); forEachWithIndex(expectedInviteOverviews, (i, inviteOverviewResource) -> { OverviewAssessorRowViewModel overviewAssessorRowViewModel = model.getAssessors().get(i); assertEquals(inviteOverviewResource.getName(), overviewAssessorRowViewModel.getName()); assertEquals(formatInnovationAreas(inviteOverviewResource.getInnovationAreas()), overviewAssessorRowViewModel.getInnovationAreas()); assertEquals(inviteOverviewResource.isCompliant(), overviewAssessorRowViewModel.isCompliant()); assertEquals(inviteOverviewResource.getBusinessType(), overviewAssessorRowViewModel.getBusinessType()); assertEquals(inviteOverviewResource.getStatus(), overviewAssessorRowViewModel.getStatus()); assertEquals(inviteOverviewResource.getDetails(), overviewAssessorRowViewModel.getDetails()); assertEquals(inviteOverviewResource.getInviteId(), overviewAssessorRowViewModel.getInviteId()); }); } private String formatInnovationAreas(List<InnovationAreaResource> innovationAreas) { return innovationAreas == null ? EMPTY : innovationAreas.stream() .map(CategoryResource::getName) .collect(joining(", ")); } }
mit
amishiro/AmiTemplate-PHP
public/lib/components/gobals/main/conts/sample.php
133
<?php include($inc_comps."/gobals/main/conts/element/template.php"); include($inc_comps."/gobals/main/conts/form/template.php"); ?>
mit
GurudathReddy/stock-market-game
src/main/java/com/vsm/stockmarket/security/CsrfTokenGeneratorFilter.java
1189
package com.vsm.stockmarket.security; import java.io.IOException; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.security.web.csrf.CsrfToken; import org.springframework.web.filter.OncePerRequestFilter; public class CsrfTokenGeneratorFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { CsrfToken token = (CsrfToken) request.getAttribute("_csrf"); // Spring Security will allow the Token to be included in this header name response.setHeader("X-CSRF-HEADER", token.getHeaderName()); // Spring Security will allow the token to be included in this parameter name response.setHeader("X-CSRF-PARAM", token.getParameterName()); // this is the value of the token to be included as either a header or an HTTP parameter response.setHeader("X-CSRF-TOKEN", token.getToken()); filterChain.doFilter(request, response); } }
mit
SaiAshirwadInformatia/TaskTracker
application/controllers/Profile.php
2230
<?php class Profile extends TT_Controller{ protected $currentUser; public function __construct(){ parent::__construct(); $this->load->model([ 'users_model', 'projects_model', 'tasks_model', 'releases_model' ]); $this->load->library('pagination'); loadProjectsSession(); if($this->session->userdata('user')){ $this->currentUser = $this->session->userdata('user'); } } public function index(){ $this->load->view('header'); $user = $this->users_model->get_by_id($this->currentUser['id']); $tasks = $this->tasks_model->get_by_user_id($this->currentUser['id']); $projects = $this->projects_model->get_by_team_member($this->currentUser['id']); $data = [ 'user' => $user ]; $this->load->view('profile',$data); $this->load->view('footer'); } public function update(){ $this->load->view('header'); $user = $this->users_model->get_by_id($this->currentUser['id']); $data = [ 'user' => $user ]; $this->load->view('update_profile',$data); $this->load->view('footer'); } public function update_action(){ $data = [ //Personal Information 'fname' => $this->input->post('fname'), 'lname' => $this->input->post('lname'), 'mname' => $this->input->post('mname'), 'dob' => $this->input->post('dob'), 'gender' => $this->input->post('gender'), 'designation' => $this->input->post('designation'), //Contact Details 'email' => $this->input->post('email'), 'phone' => $this->input->post('phone'), 'github' => $this->input->post('github'), 'facebook' => $this->input->post('facebook'), //Residential Information 'address1' => $this->input->post('address1'), 'address2' => $this->input->post('address2'), 'city' => $this->input->post('city'), 'district' => $this->input->post('district'), 'state' => $this->input->post('state'), 'pincode' => $this->input->post('pincode'), 'country' => $this->input->post('country'), //Edicational Details 'college' => $this->input->post('college'), 'board' => $this->input->post('board'), 'exam' => $this->input->post('exam'), ]; $ret = $this->users_model->update($this->currentUser['id'] ,$data); if($ret['id']){ redirect(base_url('Profile')); } } }
mit
Azure/azure-sdk-for-java
sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/ServiceNowAuthenticationType.java
1383
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.analytics.synapse.artifacts.models; import com.azure.core.util.ExpandableStringEnum; import com.fasterxml.jackson.annotation.JsonCreator; import java.util.Collection; /** Defines values for ServiceNowAuthenticationType. */ public final class ServiceNowAuthenticationType extends ExpandableStringEnum<ServiceNowAuthenticationType> { /** Static value Basic for ServiceNowAuthenticationType. */ public static final ServiceNowAuthenticationType BASIC = fromString("Basic"); /** Static value OAuth2 for ServiceNowAuthenticationType. */ public static final ServiceNowAuthenticationType OAUTH2 = fromString("OAuth2"); /** * Creates or finds a ServiceNowAuthenticationType from its string representation. * * @param name a name to look for. * @return the corresponding ServiceNowAuthenticationType. */ @JsonCreator public static ServiceNowAuthenticationType fromString(String name) { return fromString(name, ServiceNowAuthenticationType.class); } /** @return known ServiceNowAuthenticationType values. */ public static Collection<ServiceNowAuthenticationType> values() { return values(ServiceNowAuthenticationType.class); } }
mit
madmaw/mvp.ts
mvp-jquery-handlebars-example.ts/src/main/ts/DecoratedStack/DecoratedStackModel.ts
2911
// Module module TS.IJQuery.MVP.HB.Example.DecoratedStack { // Class export class DecoratedStackModel extends TS.MVP.Composite.Stack.AbstractStackPresenterModel<TS.MVP.IPresenter> implements TS.IJQuery.MVP.HB.Example.TextInput.ITextInputModel { // Constructor constructor( private _topLevelController: TS.MVP.IPresenter, private _labelViewFactory: TS.IJQuery.MVP.IJQueryViewFactory, private _inputViewFactory: TS.IJQuery.MVP.IJQueryViewFactory, private _toolbarDecoratorFactory: (presenters: TS.MVP.IPresenter[], commandModel: TS.MVP.Command.ICommandModel) => TS.MVP.IPresenter ) { super(false); } getValue(): string { return ""; } requestSubmit(value: string) { // push a new controller if (value != null && value.length > 0) { // create the label var decoratorController = this._createPresenter(value); this._push(decoratorController, value); } } public _createPresenter(value: string): TS.MVP.IPresenter { var labelController = new TS.IJQuery.MVP.HB.Example.Label.LabelPresenter(this._labelViewFactory); labelController.setModel(new TS.IJQuery.MVP.HB.Example.Label.ImmutableLabelModel(value)); // create an input controller var inputController = new TS.IJQuery.MVP.HB.Example.TextInput.TextInputPresenter(this._inputViewFactory); inputController.setModel(this); var presenters: TS.MVP.IPresenter[] = [labelController, inputController]; var commandModel = new TS.MVP.Command.SimpleCommandModel(); // TODO back button handling return this._toolbarDecoratorFactory(presenters, commandModel); } public _importEntry(description: any, importCompletionCallback: TS.MVP.IModelImportStateCallback): TS.MVP.Composite.Stack.AbstractStackPresenterModelEntry<TS.MVP.IPresenter> { var presenter = this._createPresenter(description); return new TS.MVP.Composite.Stack.AbstractStackPresenterModelEntry(presenter, description); } public _exportEntry(entry: TS.MVP.Composite.Stack.AbstractStackPresenterModelEntry<TS.MVP.IPresenter>, models: TS.MVP.IModel[]): any { return entry.data; } /* public _entryToDescription(entry: templa.mvc.composite.IAbstractStackControllerModelEntry): any { return entry.data; } public _createEntryFromDescription(description: string): templa.mvc.composite.IAbstractStackControllerModelEntry { var controller = this._createController(description); return { controller: controller, data: description }; } */ } }
mit
danielwertheim/routemeister
src/tests/Routemeister.UnitTests/UnitTestsOf.cs
680
using System; namespace Routemeister.UnitTests { public abstract class UnitTestsOf<T> : UnitTests { protected T UnitUnderTest { get; set; } protected override void OnDisposing() => (UnitUnderTest as IDisposable)?.Dispose(); } public abstract class UnitTests : IDisposable { public UnitTests() { OnBeforeEachTest(); } public void Dispose() { OnAfterEachTest(); OnDisposing(); } protected virtual void OnBeforeEachTest() { } protected virtual void OnAfterEachTest() { } protected virtual void OnDisposing() { } } }
mit
basharal/passport-duo
test/index.test.js
273
var duo = require('index'); describe('passport-duo', function() { it('should export version', function() { expect(duo.version).to.be.a('string'); }); it('should export Strategy', function() { expect(duo.Strategy).to.be.a('function'); }); });
mit
baccigalupi/c8ke
lib/c8ke/envjs/connection.js
4193
/* Stores of connections */ Envjs.connections = []; Envjs.connections.addConnection = function(xhr){ log.debug('registering connection.'); Envjs.connections.push(xhr); }; Envjs.connections.removeConnection = function(xhr){ log.debug('unregistering connection.'); var i; for(i = 0; i < Envjs.connections.length; i++){ if(Envjs.connections[i] === xhr){ Envjs.connections.splice(i,1); break; } } }; Envjs.localXHR = function(url, xhr, data){ try{ // make the fake file level request if ( "PUT" == xhr.method.toUpperCase() || "POST" == xhr.method.toUpperCase() ) { log.debug('writing to file %s', url); data = data || "" ; Envjs.writeToFile(data, url); } else if ( xhr.method == "DELETE" ) { log.debug('not deleting file %s, because delete file not implemented yet', url); // Envjs.deleteFile(url); } else { log.debug('reading from file %s', url); xhr.responseText = Envjs.readFromFile(url); } // process the response try { xhr.readyState = 4; xhr.status = 200; xhr.statusText = ""; if(url.match(/html$/)){ xhr.responseHeaders["Content-Type"] = 'text/html'; }else if(url.match(/.xml$/)){ xhr.responseHeaders["Content-Type"] = 'text/xml'; }else if(url.match(/.js$/)){ xhr.responseHeaders["Content-Type"] = 'text/javascript'; }else if(url.match(/.json$/)){ xhr.responseHeaders["Content-Type"] = 'application/json'; }else{ xhr.responseHeaders["Content-Type"] = 'text/plain'; } } catch(ee) { log.error('failed to load response headers', ee); } } catch(e) { log.error('failed to open file %s %s', url, e); xhr.readyState = 4; xhr.statusText = "Local File Protocol Error"; xhr.responseText = "<html><head/><body><p>"+ e+ "</p></body></html>"; } }; Envjs.HTTPConnection = { get : function(url){ return RestClient.get(url); }, post : function(url, data){ return RestClient.get(url, data); }, put : function(url, data){ return RestClient.put(url, data); }, delete : function(url){ return RestClient.delete(url); } }; /* requires XHR (in xhr.js), Document (in dom.js), XMLSerializer (in dom.js) */ /** * establishes connection and calls responsehandler * @param {Object} xhr * @param {Object} responseHandler * @param {Object} data */ Envjs.connection = function(xhr, responseHandler, data) { var url = xhr.url; if (/^file\:/.test(url)) { log.debug('establishing file connection'); Envjs.localXHR(url, xhr, data); } else { // repackage data if (data instanceof Document) { log.debug('about to initialize serializer') var serializer = new XMLSerializer(); log.debug('gonna serialize to string') data = serializer.serializeToString(data); } else if ( data && (!data.length || data.length == 0) ) { data = null; } // making the request var requester = Envjs.HTTPConnection[xhr.method.toLowerCase()]; var response; try { if ( data ) { response = requester(url, data); } else { response = requester(url); } } catch(e) { log.error('could not connect to url: %s\n%s', url, e); } // process the response var headers = response.raw_headers; try { for (var header in headers ) { log.debug('response header [%s] = %s', header, headers[header]); xhr.responseHeaders[header] = headers[header]; } } catch(e) { log.error('failed to load response headers \n%s', e); } xhr.readyState = 4; xhr.status = response.code(); xhr.statusText = response.description() || ""; log.debug('%s %s %s %s', xhr.method, xhr.status, xhr.url, xhr.statusText); xhr.responseText = response.body() + ''; } if (responseHandler) { log.debug('calling ajax response handler'); if (!xhr.async) { log.debug('calling sync response handler directly'); responseHandler(); } else { log.debug('using setTimeout for async response handler'); setTimeout(responseHandler, 1); } } };
mit
rojassergio/Aprendiendo-a-programar-en-Python-con-mi-computador
Programas_Capitulo_05/Cap05_pagina_105.py
736
''' @author: Sergio Rojas @contact: rr.sergio@gmail.com -------------------------- Contenido bajo Atribución-NoComercial-CompartirIgual 3.0 Venezuela (CC BY-NC-SA 3.0 VE) http://creativecommons.org/licenses/by-nc-sa/3.0/ve/ Creado en abril 21, 2016 ''' import numpy as np def f(x, a=2.5, b = np.sqrt(3), c = 3.2): return a*x**2 + b*x + c print(f(0)) print(f(1)) print(f(np.sqrt(7))) print(f(0, c = 9)) print(f(1, c=9, a=0, b=1)) print(f(1, c=9, a=0)) print(f(c=9, a=0, x=1)) print(f(c=9, a=0, x=1, b=6.5)) print("\t EJECUTAR LAS SIGUIENTES 2 instrucciones desde Ipython") print("\t despues de ejecutar: %run Cap05_pagina_105.py") print("\t f(9, a=0, 1, b=6.5)") print("\t f(9, a=0, 1, 6.5)") print(f(9, 0, 1, 6.5))
mit
laborautonomo/poedit
deps/boost/boost/thread/future.hpp
135901
// (C) Copyright 2008-10 Anthony Williams // (C) Copyright 2011-2013 Vicente J. Botet Escriba // // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_THREAD_FUTURE_HPP #define BOOST_THREAD_FUTURE_HPP #include <boost/thread/detail/config.hpp> // boost::thread::future requires exception handling // due to boost::exception::exception_ptr dependency #ifndef BOOST_NO_EXCEPTIONS //#include <boost/thread/detail/log.hpp> #include <boost/detail/scoped_enum_emulation.hpp> #include <stdexcept> #include <boost/thread/detail/move.hpp> #include <boost/thread/detail/async_func.hpp> #include <boost/thread/thread_time.hpp> #include <boost/thread/mutex.hpp> #include <boost/thread/condition_variable.hpp> #include <boost/thread/lock_algorithms.hpp> #include <boost/thread/lock_types.hpp> #include <boost/exception_ptr.hpp> #include <boost/shared_ptr.hpp> #include <boost/scoped_ptr.hpp> #include <boost/type_traits/is_fundamental.hpp> #include <boost/thread/detail/is_convertible.hpp> #include <boost/type_traits/remove_reference.hpp> #include <boost/type_traits/remove_cv.hpp> #include <boost/type_traits/is_void.hpp> #include <boost/mpl/if.hpp> #include <boost/config.hpp> #include <boost/throw_exception.hpp> #include <algorithm> #include <boost/function.hpp> #include <boost/bind.hpp> #include <boost/ref.hpp> #include <boost/scoped_array.hpp> #include <boost/enable_shared_from_this.hpp> #include <boost/utility/enable_if.hpp> #include <list> #include <boost/next_prior.hpp> #include <vector> #include <boost/thread/future_error_code.hpp> #ifdef BOOST_THREAD_USES_CHRONO #include <boost/chrono/system_clocks.hpp> #endif #if defined BOOST_THREAD_PROVIDES_FUTURE_CTOR_ALLOCATORS #include <boost/thread/detail/memory.hpp> #endif #include <boost/utility/result_of.hpp> #include <boost/thread/thread_only.hpp> #if defined BOOST_THREAD_PROVIDES_FUTURE #define BOOST_THREAD_FUTURE future #else #define BOOST_THREAD_FUTURE unique_future #endif namespace boost { //enum class launch BOOST_SCOPED_ENUM_DECLARE_BEGIN(launch) { none = 0, async = 1, deferred = 2, any = async | deferred } BOOST_SCOPED_ENUM_DECLARE_END(launch) //enum class future_status BOOST_SCOPED_ENUM_DECLARE_BEGIN(future_status) { ready, timeout, deferred } BOOST_SCOPED_ENUM_DECLARE_END(future_status) class BOOST_SYMBOL_VISIBLE future_error : public std::logic_error { system::error_code ec_; public: future_error(system::error_code ec) : logic_error(ec.message()), ec_(ec) { } const system::error_code& code() const BOOST_NOEXCEPT { return ec_; } }; class BOOST_SYMBOL_VISIBLE future_uninitialized: public future_error { public: future_uninitialized() : future_error(system::make_error_code(future_errc::no_state)) {} }; class BOOST_SYMBOL_VISIBLE broken_promise: public future_error { public: broken_promise(): future_error(system::make_error_code(future_errc::broken_promise)) {} }; class BOOST_SYMBOL_VISIBLE future_already_retrieved: public future_error { public: future_already_retrieved(): future_error(system::make_error_code(future_errc::future_already_retrieved)) {} }; class BOOST_SYMBOL_VISIBLE promise_already_satisfied: public future_error { public: promise_already_satisfied(): future_error(system::make_error_code(future_errc::promise_already_satisfied)) {} }; class BOOST_SYMBOL_VISIBLE task_already_started: public future_error { public: task_already_started(): future_error(system::make_error_code(future_errc::promise_already_satisfied)) {} }; class BOOST_SYMBOL_VISIBLE task_moved: public future_error { public: task_moved(): future_error(system::make_error_code(future_errc::no_state)) {} }; class promise_moved: public future_error { public: promise_moved(): future_error(system::make_error_code(future_errc::no_state)) {} }; namespace future_state { enum state { uninitialized, waiting, ready, moved, deferred }; } namespace detail { struct relocker { boost::unique_lock<boost::mutex>& lock_; bool unlocked_; relocker(boost::unique_lock<boost::mutex>& lk): lock_(lk) { lock_.unlock(); unlocked_=true; } ~relocker() { if (unlocked_) { lock_.lock(); } } void lock() { if (unlocked_) { lock_.lock(); unlocked_=false; } } private: relocker& operator=(relocker const&); }; struct shared_state_base : enable_shared_from_this<shared_state_base> { typedef std::list<boost::condition_variable_any*> waiter_list; #if defined BOOST_THREAD_PROVIDES_FUTURE_CONTINUATION typedef shared_ptr<shared_state_base> continuation_ptr_type; #else // This type shouldn't be included, but is included to maintain the same layout. typedef shared_ptr<void> continuation_ptr_type; #endif boost::exception_ptr exception; bool done; bool is_deferred_; launch policy_; bool is_constructed; mutable boost::mutex mutex; boost::condition_variable waiters; waiter_list external_waiters; boost::function<void()> callback; // This declaration should be only included conditionally, but is included to maintain the same layout. bool thread_was_interrupted; // This declaration should be only included conditionally, but is included to maintain the same layout. continuation_ptr_type continuation_ptr; // This declaration should be only included conditionally, but is included to maintain the same layout. virtual void launch_continuation(boost::unique_lock<boost::mutex>&) { } shared_state_base(): done(false), is_deferred_(false), policy_(launch::none), is_constructed(false), thread_was_interrupted(false), continuation_ptr() {} virtual ~shared_state_base() {} void set_deferred() { is_deferred_ = true; policy_ = launch::deferred; } void set_async() { is_deferred_ = false; policy_ = launch::async; } waiter_list::iterator register_external_waiter(boost::condition_variable_any& cv) { boost::unique_lock<boost::mutex> lock(mutex); do_callback(lock); return external_waiters.insert(external_waiters.end(),&cv); } void remove_external_waiter(waiter_list::iterator it) { boost::lock_guard<boost::mutex> lock(mutex); external_waiters.erase(it); } #if defined BOOST_THREAD_PROVIDES_FUTURE_CONTINUATION void do_continuation(boost::unique_lock<boost::mutex>& lock) { if (continuation_ptr) { continuation_ptr->launch_continuation(lock); if (! lock.owns_lock()) lock.lock(); continuation_ptr.reset(); } } #else void do_continuation(boost::unique_lock<boost::mutex>&) { } #endif #if defined BOOST_THREAD_PROVIDES_FUTURE_CONTINUATION void set_continuation_ptr(continuation_ptr_type continuation, boost::unique_lock<boost::mutex>& lock) { continuation_ptr= continuation; if (done) { do_continuation(lock); } } #endif void mark_finished_internal(boost::unique_lock<boost::mutex>& lock) { done=true; waiters.notify_all(); for(waiter_list::const_iterator it=external_waiters.begin(), end=external_waiters.end();it!=end;++it) { (*it)->notify_all(); } do_continuation(lock); } void make_ready() { boost::unique_lock<boost::mutex> lock(mutex); mark_finished_internal(lock); } void do_callback(boost::unique_lock<boost::mutex>& lock) { if(callback && !done) { boost::function<void()> local_callback=callback; relocker relock(lock); local_callback(); } } void wait_internal(boost::unique_lock<boost::mutex> &lk, bool rethrow=true) { do_callback(lk); //if (!done) // fixme why this doesn't work? { if (is_deferred_) { is_deferred_=false; execute(lk); //lk.unlock(); } else { while(!done) { waiters.wait(lk); } #if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS if(rethrow && thread_was_interrupted) { throw boost::thread_interrupted(); } #endif if(rethrow && exception) { boost::rethrow_exception(exception); } } } } virtual void wait(bool rethrow=true) { boost::unique_lock<boost::mutex> lock(mutex); wait_internal(lock, rethrow); } #if defined BOOST_THREAD_USES_DATETIME bool timed_wait_until(boost::system_time const& target_time) { boost::unique_lock<boost::mutex> lock(mutex); if (is_deferred_) return false; do_callback(lock); while(!done) { bool const success=waiters.timed_wait(lock,target_time); if(!success && !done) { return false; } } return true; } #endif #ifdef BOOST_THREAD_USES_CHRONO template <class Clock, class Duration> future_status wait_until(const chrono::time_point<Clock, Duration>& abs_time) { boost::unique_lock<boost::mutex> lock(mutex); if (is_deferred_) return future_status::deferred; do_callback(lock); while(!done) { cv_status const st=waiters.wait_until(lock,abs_time); if(st==cv_status::timeout && !done) { return future_status::timeout; } } return future_status::ready; } #endif void mark_exceptional_finish_internal(boost::exception_ptr const& e, boost::unique_lock<boost::mutex>& lock) { exception=e; mark_finished_internal(lock); } void mark_exceptional_finish() { boost::unique_lock<boost::mutex> lock(mutex); mark_exceptional_finish_internal(boost::current_exception(), lock); } #if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS void mark_interrupted_finish() { boost::unique_lock<boost::mutex> lock(mutex); thread_was_interrupted=true; mark_finished_internal(lock); } void set_interrupted_at_thread_exit() { unique_lock<boost::mutex> lk(mutex); thread_was_interrupted=true; if (has_value(lk)) { throw_exception(promise_already_satisfied()); } detail::make_ready_at_thread_exit(shared_from_this()); } #endif void set_exception_at_thread_exit(exception_ptr e) { unique_lock<boost::mutex> lk(mutex); if (has_value(lk)) { throw_exception(promise_already_satisfied()); } exception=e; this->is_constructed = true; detail::make_ready_at_thread_exit(shared_from_this()); } bool has_value() const { boost::lock_guard<boost::mutex> lock(mutex); return done && !(exception #if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS || thread_was_interrupted #endif ); } bool has_value(unique_lock<boost::mutex>& ) const { return done && !(exception #if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS || thread_was_interrupted #endif ); } bool has_exception() const { boost::lock_guard<boost::mutex> lock(mutex); return done && (exception #if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS || thread_was_interrupted #endif ); } bool has_exception(unique_lock<boost::mutex>&) const { return done && (exception #if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS || thread_was_interrupted #endif ); } bool is_deferred(boost::lock_guard<boost::mutex>&) const { return is_deferred_; } launch launch_policy(boost::unique_lock<boost::mutex>&) const { return policy_; } future_state::state get_state() const { boost::lock_guard<boost::mutex> guard(mutex); if(!done) { return future_state::waiting; } else { return future_state::ready; } } exception_ptr get_exception_ptr() { boost::unique_lock<boost::mutex> lock(mutex); return get_exception_ptr(lock); } exception_ptr get_exception_ptr(boost::unique_lock<boost::mutex>& lock) { wait_internal(lock, false); #if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS if(thread_was_interrupted) { return copy_exception(boost::thread_interrupted()); } #endif return exception; } template<typename F,typename U> void set_wait_callback(F f,U* u) { boost::lock_guard<boost::mutex> lock(mutex); callback=boost::bind(f,boost::ref(*u)); } virtual void execute(boost::unique_lock<boost::mutex>&) {} private: shared_state_base(shared_state_base const&); shared_state_base& operator=(shared_state_base const&); }; template<typename T> struct future_traits { typedef boost::scoped_ptr<T> storage_type; struct dummy; #ifndef BOOST_NO_CXX11_RVALUE_REFERENCES typedef T const& source_reference_type; //typedef typename boost::mpl::if_<boost::is_fundamental<T>,dummy&,BOOST_THREAD_RV_REF(T)>::type rvalue_source_type; typedef BOOST_THREAD_RV_REF(T) rvalue_source_type; //typedef typename boost::mpl::if_<boost::is_fundamental<T>,T,BOOST_THREAD_RV_REF(T)>::type move_dest_type; typedef T move_dest_type; #elif defined BOOST_THREAD_USES_MOVE typedef typename boost::mpl::if_c<boost::is_fundamental<T>::value,T,T&>::type source_reference_type; //typedef typename boost::mpl::if_c<boost::is_fundamental<T>::value,T,BOOST_THREAD_RV_REF(T)>::type rvalue_source_type; //typedef typename boost::mpl::if_c<boost::enable_move_utility_emulation<T>::value,BOOST_THREAD_RV_REF(T),T>::type move_dest_type; typedef BOOST_THREAD_RV_REF(T) rvalue_source_type; typedef T move_dest_type; #else typedef T& source_reference_type; typedef typename boost::mpl::if_<boost::thread_detail::is_convertible<T&,BOOST_THREAD_RV_REF(T) >,BOOST_THREAD_RV_REF(T),T const&>::type rvalue_source_type; typedef typename boost::mpl::if_<boost::thread_detail::is_convertible<T&,BOOST_THREAD_RV_REF(T) >,BOOST_THREAD_RV_REF(T),T>::type move_dest_type; #endif typedef const T& shared_future_get_result_type; static void init(storage_type& storage,source_reference_type t) { storage.reset(new T(t)); } static void init(storage_type& storage,rvalue_source_type t) { #if ! defined BOOST_NO_CXX11_RVALUE_REFERENCES storage.reset(new T(boost::forward<T>(t))); #else storage.reset(new T(static_cast<rvalue_source_type>(t))); #endif } static void cleanup(storage_type& storage) { storage.reset(); } }; template<typename T> struct future_traits<T&> { typedef T* storage_type; typedef T& source_reference_type; //struct rvalue_source_type //{}; typedef T& move_dest_type; typedef T& shared_future_get_result_type; static void init(storage_type& storage,T& t) { storage=&t; } static void cleanup(storage_type& storage) { storage=0; } }; template<> struct future_traits<void> { typedef bool storage_type; typedef void move_dest_type; typedef void shared_future_get_result_type; static void init(storage_type& storage) { storage=true; } static void cleanup(storage_type& storage) { storage=false; } }; // Used to create stand-alone futures template<typename T> struct shared_state: detail::shared_state_base { typedef typename future_traits<T>::storage_type storage_type; typedef typename future_traits<T>::source_reference_type source_reference_type; typedef typename future_traits<T>::rvalue_source_type rvalue_source_type; typedef typename future_traits<T>::move_dest_type move_dest_type; typedef typename future_traits<T>::shared_future_get_result_type shared_future_get_result_type; storage_type result; shared_state(): result(0) {} ~shared_state() {} void mark_finished_with_result_internal(source_reference_type result_, boost::unique_lock<boost::mutex>& lock) { future_traits<T>::init(result,result_); this->mark_finished_internal(lock); } void mark_finished_with_result_internal(rvalue_source_type result_, boost::unique_lock<boost::mutex>& lock) { #if ! defined BOOST_NO_CXX11_RVALUE_REFERENCES future_traits<T>::init(result,boost::forward<T>(result_)); #else future_traits<T>::init(result,static_cast<rvalue_source_type>(result_)); #endif this->mark_finished_internal(lock); } void mark_finished_with_result(source_reference_type result_) { boost::unique_lock<boost::mutex> lock(mutex); this->mark_finished_with_result_internal(result_, lock); } void mark_finished_with_result(rvalue_source_type result_) { boost::unique_lock<boost::mutex> lock(mutex); #if ! defined BOOST_NO_CXX11_RVALUE_REFERENCES mark_finished_with_result_internal(boost::forward<T>(result_), lock); #else mark_finished_with_result_internal(static_cast<rvalue_source_type>(result_), lock); #endif } virtual move_dest_type get() { wait(); return boost::move(*result); } virtual shared_future_get_result_type get_sh() { wait(); return *result; } //void set_value_at_thread_exit(const T & result_) void set_value_at_thread_exit(source_reference_type result_) { unique_lock<boost::mutex> lk(this->mutex); if (this->has_value(lk)) { throw_exception(promise_already_satisfied()); } //future_traits<T>::init(result,result_); result.reset(new T(result_)); this->is_constructed = true; detail::make_ready_at_thread_exit(shared_from_this()); } //void set_value_at_thread_exit(BOOST_THREAD_RV_REF(T) result_) void set_value_at_thread_exit(rvalue_source_type result_) { unique_lock<boost::mutex> lk(this->mutex); if (this->has_value(lk)) throw_exception(promise_already_satisfied()); result.reset(new T(boost::move(result_))); //future_traits<T>::init(result,static_cast<rvalue_source_type>(result_)); this->is_constructed = true; detail::make_ready_at_thread_exit(shared_from_this()); } private: shared_state(shared_state const&); shared_state& operator=(shared_state const&); }; template<typename T> struct shared_state<T&>: detail::shared_state_base { typedef typename future_traits<T&>::storage_type storage_type; typedef typename future_traits<T&>::source_reference_type source_reference_type; typedef typename future_traits<T&>::move_dest_type move_dest_type; typedef typename future_traits<T&>::shared_future_get_result_type shared_future_get_result_type; T* result; shared_state(): result(0) {} ~shared_state() { } void mark_finished_with_result_internal(source_reference_type result_, boost::unique_lock<boost::mutex>& lock) { //future_traits<T>::init(result,result_); result= &result_; mark_finished_internal(lock); } void mark_finished_with_result(source_reference_type result_) { boost::unique_lock<boost::mutex> lock(mutex); mark_finished_with_result_internal(result_, lock); } virtual T& get() { wait(); return *result; } virtual T& get_sh() { wait(); return *result; } void set_value_at_thread_exit(T& result_) { unique_lock<boost::mutex> lk(this->mutex); if (this->has_value(lk)) throw_exception(promise_already_satisfied()); //future_traits<T>::init(result,result_); result= &result_; this->is_constructed = true; detail::make_ready_at_thread_exit(shared_from_this()); } private: shared_state(shared_state const&); shared_state& operator=(shared_state const&); }; template<> struct shared_state<void>: detail::shared_state_base { typedef void shared_future_get_result_type; shared_state() {} void mark_finished_with_result_internal(boost::unique_lock<boost::mutex>& lock) { mark_finished_internal(lock); } void mark_finished_with_result() { boost::unique_lock<boost::mutex> lock(mutex); mark_finished_with_result_internal(lock); } virtual void get() { this->wait(); } virtual void get_sh() { wait(); } void set_value_at_thread_exit() { unique_lock<boost::mutex> lk(this->mutex); if (this->has_value(lk)) { throw_exception(promise_already_satisfied()); } this->is_constructed = true; detail::make_ready_at_thread_exit(shared_from_this()); } private: shared_state(shared_state const&); shared_state& operator=(shared_state const&); }; ///////////////////////// /// future_async_shared_state_base ///////////////////////// template<typename Rp> struct future_async_shared_state_base: shared_state<Rp> { typedef shared_state<Rp> base_type; protected: boost::thread thr_; void join() { if (thr_.joinable()) thr_.join(); } public: future_async_shared_state_base() { this->set_async(); } explicit future_async_shared_state_base(BOOST_THREAD_RV_REF(boost::thread) th) : thr_(boost::move(th)) { this->set_async(); } ~future_async_shared_state_base() { join(); } virtual void wait(bool rethrow) { join(); this->base_type::wait(rethrow); } }; ///////////////////////// /// future_async_shared_state ///////////////////////// template<typename Rp, typename Fp> struct future_async_shared_state: future_async_shared_state_base<Rp> { typedef future_async_shared_state_base<Rp> base_type; public: explicit future_async_shared_state(BOOST_THREAD_FWD_REF(Fp) f) : base_type(thread(&future_async_shared_state::run, this, boost::forward<Fp>(f))) { } static void run(future_async_shared_state* that, BOOST_THREAD_FWD_REF(Fp) f) { try { that->mark_finished_with_result(f()); } #if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS catch(thread_interrupted& ) { that->mark_interrupted_finish(); } #endif catch(...) { that->mark_exceptional_finish(); } } }; template<typename Fp> struct future_async_shared_state<void, Fp>: public future_async_shared_state_base<void> { typedef future_async_shared_state_base<void> base_type; public: explicit future_async_shared_state(BOOST_THREAD_FWD_REF(Fp) f) : base_type(thread(&future_async_shared_state::run, this, boost::forward<Fp>(f))) { } static void run(future_async_shared_state* that, BOOST_THREAD_FWD_REF(Fp) f) { try { f(); that->mark_finished_with_result(); } #if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS catch(thread_interrupted& ) { that->mark_interrupted_finish(); } #endif catch(...) { that->mark_exceptional_finish(); } } }; template<typename Rp, typename Fp> struct future_async_shared_state<Rp&, Fp>: future_async_shared_state_base<Rp&> { typedef future_async_shared_state_base<Rp&> base_type; public: explicit future_async_shared_state(BOOST_THREAD_FWD_REF(Fp) f) : base_type(thread(&future_async_shared_state::run, this, boost::forward<Fp>(f))) { } static void run(future_async_shared_state* that, BOOST_THREAD_FWD_REF(Fp) f) { try { that->mark_finished_with_result(f()); } #if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS catch(thread_interrupted& ) { that->mark_interrupted_finish(); } #endif catch(...) { that->mark_exceptional_finish(); } } }; ////////////////////////// /// future_deferred_shared_state ////////////////////////// template<typename Rp, typename Fp> struct future_deferred_shared_state: shared_state<Rp> { typedef shared_state<Rp> base_type; Fp func_; public: explicit future_deferred_shared_state(BOOST_THREAD_FWD_REF(Fp) f) : func_(boost::forward<Fp>(f)) { this->set_deferred(); } virtual void execute(boost::unique_lock<boost::mutex>& lck) { try { this->mark_finished_with_result_internal(func_(), lck); } catch (...) { this->mark_exceptional_finish_internal(current_exception(), lck); } } }; template<typename Rp, typename Fp> struct future_deferred_shared_state<Rp&,Fp>: shared_state<Rp&> { typedef shared_state<Rp&> base_type; Fp func_; public: explicit future_deferred_shared_state(BOOST_THREAD_FWD_REF(Fp) f) : func_(boost::forward<Fp>(f)) { this->set_deferred(); } virtual void execute(boost::unique_lock<boost::mutex>& lck) { try { this->mark_finished_with_result_internal(func_(), lck); } catch (...) { this->mark_exceptional_finish_internal(current_exception(), lck); } } }; template<typename Fp> struct future_deferred_shared_state<void,Fp>: shared_state<void> { typedef shared_state<void> base_type; Fp func_; public: explicit future_deferred_shared_state(BOOST_THREAD_FWD_REF(Fp) f) : func_(boost::forward<Fp>(f)) { this->set_deferred(); } virtual void execute(boost::unique_lock<boost::mutex>& lck) { try { func_(); this->mark_finished_with_result_internal(lck); } catch (...) { this->mark_exceptional_finish_internal(current_exception(), lck); } } }; // template<typename T, typename Allocator> // struct shared_state_alloc: public shared_state<T> // { // typedef shared_state<T> base; // Allocator alloc_; // // public: // explicit shared_state_alloc(const Allocator& a) // : alloc_(a) {} // // }; class future_waiter { struct registered_waiter; typedef std::vector<int>::size_type count_type; struct registered_waiter { boost::shared_ptr<detail::shared_state_base> future_; detail::shared_state_base::waiter_list::iterator wait_iterator; count_type index; registered_waiter(boost::shared_ptr<detail::shared_state_base> const& a_future, detail::shared_state_base::waiter_list::iterator wait_iterator_, count_type index_): future_(a_future),wait_iterator(wait_iterator_),index(index_) {} }; struct all_futures_lock { #ifdef _MANAGED typedef std::ptrdiff_t count_type_portable; #else typedef count_type count_type_portable; #endif count_type_portable count; boost::scoped_array<boost::unique_lock<boost::mutex> > locks; all_futures_lock(std::vector<registered_waiter>& futures): count(futures.size()),locks(new boost::unique_lock<boost::mutex>[count]) { for(count_type_portable i=0;i<count;++i) { #if defined __DECCXX || defined __SUNPRO_CC || defined __hpux locks[i]=boost::unique_lock<boost::mutex>(futures[i].future_->mutex).move(); #else locks[i]=boost::unique_lock<boost::mutex>(futures[i].future_->mutex); #endif } } void lock() { boost::lock(locks.get(),locks.get()+count); } void unlock() { for(count_type_portable i=0;i<count;++i) { locks[i].unlock(); } } }; boost::condition_variable_any cv; std::vector<registered_waiter> futures; count_type future_count; public: future_waiter(): future_count(0) {} template<typename F> void add(F& f) { if(f.future_) { futures.push_back(registered_waiter(f.future_,f.future_->register_external_waiter(cv),future_count)); } ++future_count; } count_type wait() { all_futures_lock lk(futures); for(;;) { for(count_type i=0;i<futures.size();++i) { if(futures[i].future_->done) { return futures[i].index; } } cv.wait(lk); } } ~future_waiter() { for(count_type i=0;i<futures.size();++i) { futures[i].future_->remove_external_waiter(futures[i].wait_iterator); } } }; } template <typename R> class BOOST_THREAD_FUTURE; template <typename R> class shared_future; template<typename T> struct is_future_type { BOOST_STATIC_CONSTANT(bool, value=false); typedef void type; }; template<typename T> struct is_future_type<BOOST_THREAD_FUTURE<T> > { BOOST_STATIC_CONSTANT(bool, value=true); typedef T type; }; template<typename T> struct is_future_type<shared_future<T> > { BOOST_STATIC_CONSTANT(bool, value=true); typedef T type; }; template<typename Iterator> typename boost::disable_if<is_future_type<Iterator>,void>::type wait_for_all(Iterator begin,Iterator end) { for(Iterator current=begin;current!=end;++current) { current->wait(); } } template<typename F1,typename F2> typename boost::enable_if<is_future_type<F1>,void>::type wait_for_all(F1& f1,F2& f2) { f1.wait(); f2.wait(); } template<typename F1,typename F2,typename F3> void wait_for_all(F1& f1,F2& f2,F3& f3) { f1.wait(); f2.wait(); f3.wait(); } template<typename F1,typename F2,typename F3,typename F4> void wait_for_all(F1& f1,F2& f2,F3& f3,F4& f4) { f1.wait(); f2.wait(); f3.wait(); f4.wait(); } template<typename F1,typename F2,typename F3,typename F4,typename F5> void wait_for_all(F1& f1,F2& f2,F3& f3,F4& f4,F5& f5) { f1.wait(); f2.wait(); f3.wait(); f4.wait(); f5.wait(); } template<typename Iterator> typename boost::disable_if<is_future_type<Iterator>,Iterator>::type wait_for_any(Iterator begin,Iterator end) { if(begin==end) return end; detail::future_waiter waiter; for(Iterator current=begin;current!=end;++current) { waiter.add(*current); } return boost::next(begin,waiter.wait()); } template<typename F1,typename F2> typename boost::enable_if<is_future_type<F1>,unsigned>::type wait_for_any(F1& f1,F2& f2) { detail::future_waiter waiter; waiter.add(f1); waiter.add(f2); return waiter.wait(); } template<typename F1,typename F2,typename F3> unsigned wait_for_any(F1& f1,F2& f2,F3& f3) { detail::future_waiter waiter; waiter.add(f1); waiter.add(f2); waiter.add(f3); return waiter.wait(); } template<typename F1,typename F2,typename F3,typename F4> unsigned wait_for_any(F1& f1,F2& f2,F3& f3,F4& f4) { detail::future_waiter waiter; waiter.add(f1); waiter.add(f2); waiter.add(f3); waiter.add(f4); return waiter.wait(); } template<typename F1,typename F2,typename F3,typename F4,typename F5> unsigned wait_for_any(F1& f1,F2& f2,F3& f3,F4& f4,F5& f5) { detail::future_waiter waiter; waiter.add(f1); waiter.add(f2); waiter.add(f3); waiter.add(f4); waiter.add(f5); return waiter.wait(); } template <typename R> class promise; template <typename R> class packaged_task; namespace detail { /// Common implementation for all the futures independently of the return type class base_future { //BOOST_THREAD_MOVABLE(base_future) }; /// Common implementation for future and shared_future. template <typename R> class basic_future : public base_future { protected: public: typedef boost::shared_ptr<detail::shared_state<R> > future_ptr; future_ptr future_; basic_future(future_ptr a_future): future_(a_future) { } // Copy construction from a shared_future explicit basic_future(const shared_future<R>&) BOOST_NOEXCEPT; public: typedef future_state::state state; BOOST_THREAD_MOVABLE(basic_future) basic_future(): future_() {} ~basic_future() {} basic_future(BOOST_THREAD_RV_REF(basic_future) other) BOOST_NOEXCEPT: future_(BOOST_THREAD_RV(other).future_) { BOOST_THREAD_RV(other).future_.reset(); } basic_future& operator=(BOOST_THREAD_RV_REF(basic_future) other) BOOST_NOEXCEPT { future_=BOOST_THREAD_RV(other).future_; BOOST_THREAD_RV(other).future_.reset(); return *this; } void swap(basic_future& that) BOOST_NOEXCEPT { future_.swap(that.future_); } // functions to check state, and wait for ready state get_state() const { if(!future_) { return future_state::uninitialized; } return future_->get_state(); } bool is_ready() const { return get_state()==future_state::ready; } bool has_exception() const { return future_ && future_->has_exception(); } bool has_value() const { return future_ && future_->has_value(); } launch launch_policy(boost::unique_lock<boost::mutex>& lk) const { if ( future_ ) return future_->launch_policy(lk); else return launch(launch::none); } exception_ptr get_exception_ptr() { return future_ ? future_->get_exception_ptr() : exception_ptr(); } bool valid() const BOOST_NOEXCEPT { return future_ != 0; } void wait() const { if(!future_) { boost::throw_exception(future_uninitialized()); } future_->wait(false); } #if defined BOOST_THREAD_USES_DATETIME template<typename Duration> bool timed_wait(Duration const& rel_time) const { return timed_wait_until(boost::get_system_time()+rel_time); } bool timed_wait_until(boost::system_time const& abs_time) const { if(!future_) { boost::throw_exception(future_uninitialized()); } return future_->timed_wait_until(abs_time); } #endif #ifdef BOOST_THREAD_USES_CHRONO template <class Rep, class Period> future_status wait_for(const chrono::duration<Rep, Period>& rel_time) const { return wait_until(chrono::steady_clock::now() + rel_time); } template <class Clock, class Duration> future_status wait_until(const chrono::time_point<Clock, Duration>& abs_time) const { if(!future_) { boost::throw_exception(future_uninitialized()); } return future_->wait_until(abs_time); } #endif }; } // detail BOOST_THREAD_DCL_MOVABLE_BEG(R) detail::basic_future<R> BOOST_THREAD_DCL_MOVABLE_END namespace detail { #if (!defined _MSC_VER || _MSC_VER >= 1400) // _MSC_VER == 1400 on MSVC 2005 template <class Rp, class Fp> BOOST_THREAD_FUTURE<Rp> make_future_async_shared_state(BOOST_THREAD_FWD_REF(Fp) f); template <class Rp, class Fp> BOOST_THREAD_FUTURE<Rp> make_future_deferred_shared_state(BOOST_THREAD_FWD_REF(Fp) f); #endif // #if (!defined _MSC_VER || _MSC_VER >= 1400) #if defined BOOST_THREAD_PROVIDES_FUTURE_CONTINUATION template<typename F, typename Rp, typename Fp> struct future_deferred_continuation_shared_state; template<typename F, typename Rp, typename Fp> struct future_async_continuation_shared_state; template <class F, class Rp, class Fp> BOOST_THREAD_FUTURE<Rp> make_future_async_continuation_shared_state(boost::unique_lock<boost::mutex> &lock, BOOST_THREAD_RV_REF(F) f, BOOST_THREAD_FWD_REF(Fp) c); template <class F, class Rp, class Fp> BOOST_THREAD_FUTURE<Rp> make_future_deferred_continuation_shared_state(boost::unique_lock<boost::mutex> &lock, BOOST_THREAD_RV_REF(F) f, BOOST_THREAD_FWD_REF(Fp) c); #endif #if defined BOOST_THREAD_PROVIDES_FUTURE_UNWRAP template<typename F, typename Rp> struct future_unwrap_shared_state; template <class F, class Rp> inline BOOST_THREAD_FUTURE<Rp> make_future_unwrap_shared_state(boost::unique_lock<boost::mutex> &lock, BOOST_THREAD_RV_REF(F) f); #endif } template <typename R> class BOOST_THREAD_FUTURE : public detail::basic_future<R> { private: typedef detail::basic_future<R> base_type; typedef typename base_type::future_ptr future_ptr; friend class shared_future<R>; friend class promise<R>; #if defined BOOST_THREAD_PROVIDES_FUTURE_CONTINUATION template <typename, typename, typename> friend struct detail::future_async_continuation_shared_state; template <typename, typename, typename> friend struct detail::future_deferred_continuation_shared_state; template <class F, class Rp, class Fp> friend BOOST_THREAD_FUTURE<Rp> detail::make_future_async_continuation_shared_state(boost::unique_lock<boost::mutex> &lock, BOOST_THREAD_RV_REF(F) f, BOOST_THREAD_FWD_REF(Fp) c); template <class F, class Rp, class Fp> friend BOOST_THREAD_FUTURE<Rp> detail::make_future_deferred_continuation_shared_state(boost::unique_lock<boost::mutex> &lock, BOOST_THREAD_RV_REF(F) f, BOOST_THREAD_FWD_REF(Fp) c); #endif #if defined BOOST_THREAD_PROVIDES_FUTURE_UNWRAP template<typename F, typename Rp> friend struct detail::future_unwrap_shared_state; template <class F, class Rp> friend BOOST_THREAD_FUTURE<Rp> detail::make_future_unwrap_shared_state(boost::unique_lock<boost::mutex> &lock, BOOST_THREAD_RV_REF(F) f); #endif #if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK template <class> friend class packaged_task; // todo check if this works in windows #else friend class packaged_task<R>; #endif friend class detail::future_waiter; template <class Rp, class Fp> friend BOOST_THREAD_FUTURE<Rp> detail::make_future_async_shared_state(BOOST_THREAD_FWD_REF(Fp) f); template <class Rp, class Fp> friend BOOST_THREAD_FUTURE<Rp> detail::make_future_deferred_shared_state(BOOST_THREAD_FWD_REF(Fp) f); typedef typename detail::future_traits<R>::move_dest_type move_dest_type; BOOST_THREAD_FUTURE(future_ptr a_future): base_type(a_future) { } public: BOOST_THREAD_MOVABLE_ONLY(BOOST_THREAD_FUTURE) typedef future_state::state state; typedef R value_type; // EXTENSION BOOST_CONSTEXPR BOOST_THREAD_FUTURE() {} ~BOOST_THREAD_FUTURE() {} BOOST_THREAD_FUTURE(BOOST_THREAD_RV_REF(BOOST_THREAD_FUTURE) other) BOOST_NOEXCEPT: base_type(boost::move(static_cast<base_type&>(BOOST_THREAD_RV(other)))) { } inline BOOST_THREAD_FUTURE(BOOST_THREAD_RV_REF(BOOST_THREAD_FUTURE<BOOST_THREAD_FUTURE<R> >) other); // EXTENSION BOOST_THREAD_FUTURE& operator=(BOOST_THREAD_RV_REF(BOOST_THREAD_FUTURE) other) BOOST_NOEXCEPT { this->base_type::operator=(boost::move(static_cast<base_type&>(BOOST_THREAD_RV(other)))); return *this; } shared_future<R> share() { return shared_future<R>(::boost::move(*this)); } void swap(BOOST_THREAD_FUTURE& other) { static_cast<base_type*>(this)->swap(other); } // todo this function must be private and friendship provided to the internal users. void set_async() { this->future_->set_async(); } // todo this function must be private and friendship provided to the internal users. void set_deferred() { this->future_->set_deferred(); } // retrieving the value move_dest_type get() { if(!this->future_) { boost::throw_exception(future_uninitialized()); } future_ptr fut_=this->future_; #ifdef BOOST_THREAD_PROVIDES_FUTURE_INVALID_AFTER_GET this->future_.reset(); #endif return fut_->get(); } template <typename R2> typename disable_if< is_void<R2>, move_dest_type>::type get_or(BOOST_THREAD_RV_REF(R2) v) { if(!this->future_) { boost::throw_exception(future_uninitialized()); } this->future_->wait(false); future_ptr fut_=this->future_; #ifdef BOOST_THREAD_PROVIDES_FUTURE_INVALID_AFTER_GET this->future_.reset(); #endif if (fut_->has_value()) { return fut_->get(); } else { return boost::move(v); } } template <typename R2> typename disable_if< is_void<R2>, move_dest_type>::type get_or(R2 const& v) // EXTENSION { if(!this->future_) { boost::throw_exception(future_uninitialized()); } this->future_->wait(false); future_ptr fut_=this->future_; #ifdef BOOST_THREAD_PROVIDES_FUTURE_INVALID_AFTER_GET this->future_.reset(); #endif if (fut_->has_value()) { return fut_->get(); } else { return v; } } #if defined BOOST_THREAD_PROVIDES_FUTURE_CONTINUATION // template<typename F> // auto then(F&& func) -> BOOST_THREAD_FUTURE<decltype(func(*this))>; //#if defined(BOOST_THREAD_RVALUE_REFERENCES_DONT_MATCH_FUNTION_PTR) // template<typename RF> // inline BOOST_THREAD_FUTURE<RF> then(RF(*func)(BOOST_THREAD_FUTURE&)); // template<typename RF> // inline BOOST_THREAD_FUTURE<RF> then(launch policy, RF(*func)(BOOST_THREAD_FUTURE&)); //#endif template<typename F> inline BOOST_THREAD_FUTURE<typename boost::result_of<F(BOOST_THREAD_FUTURE)>::type> then(BOOST_THREAD_FWD_REF(F) func); // EXTENSION template<typename F> inline BOOST_THREAD_FUTURE<typename boost::result_of<F(BOOST_THREAD_FUTURE)>::type> then(launch policy, BOOST_THREAD_FWD_REF(F) func); // EXTENSION template <typename R2> inline typename disable_if< is_void<R2>, BOOST_THREAD_FUTURE<R> >::type fallback_to(BOOST_THREAD_RV_REF(R2) v); // EXTENSION template <typename R2> inline typename disable_if< is_void<R2>, BOOST_THREAD_FUTURE<R> >::type fallback_to(R2 const& v); // EXTENSION #endif //#if defined BOOST_THREAD_PROVIDES_FUTURE_UNWRAP // inline // typename enable_if< // is_future_type<value_type>, // value_type // //BOOST_THREAD_FUTURE<typename is_future_type<value_type>::type> // >::type // unwrap(); //#endif }; BOOST_THREAD_DCL_MOVABLE_BEG(T) BOOST_THREAD_FUTURE<T> BOOST_THREAD_DCL_MOVABLE_END template <typename R2> class BOOST_THREAD_FUTURE<BOOST_THREAD_FUTURE<R2> > : public detail::basic_future<BOOST_THREAD_FUTURE<R2> > { typedef BOOST_THREAD_FUTURE<R2> R; private: typedef detail::basic_future<R> base_type; typedef typename base_type::future_ptr future_ptr; friend class shared_future<R>; friend class promise<R>; #if defined BOOST_THREAD_PROVIDES_FUTURE_CONTINUATION template <typename, typename, typename> friend struct detail::future_async_continuation_shared_state; template <typename, typename, typename> friend struct detail::future_deferred_continuation_shared_state; template <class F, class Rp, class Fp> friend BOOST_THREAD_FUTURE<Rp> detail::make_future_async_continuation_shared_state(boost::unique_lock<boost::mutex> &lock, BOOST_THREAD_RV_REF(F) f, BOOST_THREAD_FWD_REF(Fp) c); template <class F, class Rp, class Fp> friend BOOST_THREAD_FUTURE<Rp> detail::make_future_deferred_continuation_shared_state(boost::unique_lock<boost::mutex> &lock, BOOST_THREAD_RV_REF(F) f, BOOST_THREAD_FWD_REF(Fp) c); #endif #if defined BOOST_THREAD_PROVIDES_FUTURE_UNWRAP template<typename F, typename Rp> friend struct detail::future_unwrap_shared_state; template <class F, class Rp> friend BOOST_THREAD_FUTURE<Rp> detail::make_future_unwrap_shared_state(boost::unique_lock<boost::mutex> &lock, BOOST_THREAD_RV_REF(F) f); #endif #if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK template <class> friend class packaged_task; // todo check if this works in windows #else friend class packaged_task<R>; #endif friend class detail::future_waiter; template <class Rp, class Fp> friend BOOST_THREAD_FUTURE<Rp> detail::make_future_async_shared_state(BOOST_THREAD_FWD_REF(Fp) f); template <class Rp, class Fp> friend BOOST_THREAD_FUTURE<Rp> detail::make_future_deferred_shared_state(BOOST_THREAD_FWD_REF(Fp) f); typedef typename detail::future_traits<R>::move_dest_type move_dest_type; BOOST_THREAD_FUTURE(future_ptr a_future): base_type(a_future) { } public: BOOST_THREAD_MOVABLE_ONLY(BOOST_THREAD_FUTURE) typedef future_state::state state; typedef R value_type; // EXTENSION BOOST_CONSTEXPR BOOST_THREAD_FUTURE() {} ~BOOST_THREAD_FUTURE() {} BOOST_THREAD_FUTURE(BOOST_THREAD_RV_REF(BOOST_THREAD_FUTURE) other) BOOST_NOEXCEPT: base_type(boost::move(static_cast<base_type&>(BOOST_THREAD_RV(other)))) { } BOOST_THREAD_FUTURE& operator=(BOOST_THREAD_RV_REF(BOOST_THREAD_FUTURE) other) BOOST_NOEXCEPT { this->base_type::operator=(boost::move(static_cast<base_type&>(BOOST_THREAD_RV(other)))); return *this; } shared_future<R> share() { return shared_future<R>(::boost::move(*this)); } void swap(BOOST_THREAD_FUTURE& other) { static_cast<base_type*>(this)->swap(other); } // todo this function must be private and friendship provided to the internal users. void set_async() { this->future_->set_async(); } // todo this function must be private and friendship provided to the internal users. void set_deferred() { this->future_->set_deferred(); } // retrieving the value move_dest_type get() { if(!this->future_) { boost::throw_exception(future_uninitialized()); } future_ptr fut_=this->future_; #ifdef BOOST_THREAD_PROVIDES_FUTURE_INVALID_AFTER_GET this->future_.reset(); #endif return fut_->get(); } move_dest_type get_or(BOOST_THREAD_RV_REF(R) v) // EXTENSION { if(!this->future_) { boost::throw_exception(future_uninitialized()); } this->future_->wait(false); future_ptr fut_=this->future_; #ifdef BOOST_THREAD_PROVIDES_FUTURE_INVALID_AFTER_GET this->future_.reset(); #endif if (fut_->has_value()) return fut_->get(); else return boost::move(v); } move_dest_type get_or(R const& v) // EXTENSION { if(!this->future_) { boost::throw_exception(future_uninitialized()); } this->future_->wait(false); future_ptr fut_=this->future_; #ifdef BOOST_THREAD_PROVIDES_FUTURE_INVALID_AFTER_GET this->future_.reset(); #endif if (fut_->has_value()) return fut_->get(); else return v; } #if defined BOOST_THREAD_PROVIDES_FUTURE_CONTINUATION // template<typename F> // auto then(F&& func) -> BOOST_THREAD_FUTURE<decltype(func(*this))>; //#if defined(BOOST_THREAD_RVALUE_REFERENCES_DONT_MATCH_FUNTION_PTR) // template<typename RF> // inline BOOST_THREAD_FUTURE<RF> then(RF(*func)(BOOST_THREAD_FUTURE&)); // template<typename RF> // inline BOOST_THREAD_FUTURE<RF> then(launch policy, RF(*func)(BOOST_THREAD_FUTURE&)); //#endif template<typename F> inline BOOST_THREAD_FUTURE<typename boost::result_of<F(BOOST_THREAD_FUTURE)>::type> then(BOOST_THREAD_FWD_REF(F) func); // EXTENSION template<typename F> inline BOOST_THREAD_FUTURE<typename boost::result_of<F(BOOST_THREAD_FUTURE)>::type> then(launch policy, BOOST_THREAD_FWD_REF(F) func); // EXTENSION #endif #if defined BOOST_THREAD_PROVIDES_FUTURE_UNWRAP inline BOOST_THREAD_FUTURE<R2> unwrap(); // EXTENSION #endif }; template <typename R> class shared_future : public detail::basic_future<R> { typedef detail::basic_future<R> base_type; typedef typename base_type::future_ptr future_ptr; friend class detail::future_waiter; friend class promise<R>; #if defined BOOST_THREAD_PROVIDES_FUTURE_CONTINUATION template <typename, typename, typename> friend struct detail::future_async_continuation_shared_state; template <typename, typename, typename> friend struct detail::future_deferred_continuation_shared_state; template <class F, class Rp, class Fp> friend BOOST_THREAD_FUTURE<Rp> detail::make_future_async_continuation_shared_state(boost::unique_lock<boost::mutex> &lock, BOOST_THREAD_RV_REF(F) f, BOOST_THREAD_FWD_REF(Fp) c); template <class F, class Rp, class Fp> friend BOOST_THREAD_FUTURE<Rp> detail::make_future_deferred_continuation_shared_state(boost::unique_lock<boost::mutex> &lock, BOOST_THREAD_RV_REF(F) f, BOOST_THREAD_FWD_REF(Fp) c); #endif #if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK template <class> friend class packaged_task;// todo check if this works in windows #else friend class packaged_task<R>; #endif shared_future(future_ptr a_future): base_type(a_future) {} public: BOOST_THREAD_MOVABLE(shared_future) typedef R value_type; // EXTENSION shared_future(shared_future const& other): base_type(other) {} typedef future_state::state state; BOOST_CONSTEXPR shared_future() {} ~shared_future() {} shared_future& operator=(shared_future const& other) { shared_future(other).swap(*this); return *this; } shared_future(BOOST_THREAD_RV_REF(shared_future) other) BOOST_NOEXCEPT : base_type(boost::move(static_cast<base_type&>(BOOST_THREAD_RV(other)))) { BOOST_THREAD_RV(other).future_.reset(); } shared_future(BOOST_THREAD_RV_REF( BOOST_THREAD_FUTURE<R> ) other) BOOST_NOEXCEPT : base_type(boost::move(static_cast<base_type&>(BOOST_THREAD_RV(other)))) { } shared_future& operator=(BOOST_THREAD_RV_REF(shared_future) other) BOOST_NOEXCEPT { base_type::operator=(boost::move(static_cast<base_type&>(BOOST_THREAD_RV(other)))); return *this; } shared_future& operator=(BOOST_THREAD_RV_REF( BOOST_THREAD_FUTURE<R> ) other) BOOST_NOEXCEPT { base_type::operator=(boost::move(static_cast<base_type&>(BOOST_THREAD_RV(other)))); return *this; } void swap(shared_future& other) BOOST_NOEXCEPT { static_cast<base_type*>(this)->swap(other); } // retrieving the value typename detail::shared_state<R>::shared_future_get_result_type get() { if(!this->future_) { boost::throw_exception(future_uninitialized()); } return this->future_->get_sh(); } template <typename R2> typename disable_if< is_void<R2>, typename detail::shared_state<R>::shared_future_get_result_type>::type get_or(BOOST_THREAD_RV_REF(R2) v) // EXTENSION { if(!this->future_) { boost::throw_exception(future_uninitialized()); } future_ptr fut_=this->future_; fut_->wait(); if (fut_->has_value()) return fut_->get_sh(); else return boost::move(v); } #if defined BOOST_THREAD_PROVIDES_FUTURE_CONTINUATION // template<typename F> // auto then(F&& func) -> BOOST_THREAD_FUTURE<decltype(func(*this))>; // template<typename F> // auto then(launch, F&& func) -> BOOST_THREAD_FUTURE<decltype(func(*this))>; //#if defined(BOOST_THREAD_RVALUE_REFERENCES_DONT_MATCH_FUNTION_PTR) // template<typename RF> // inline BOOST_THREAD_FUTURE<RF> then(RF(*func)(shared_future&)); // template<typename RF> // inline BOOST_THREAD_FUTURE<RF> then(launch policy, RF(*func)(shared_future&)); //#endif template<typename F> inline BOOST_THREAD_FUTURE<typename boost::result_of<F(shared_future)>::type> then(BOOST_THREAD_FWD_REF(F) func); // EXTENSION template<typename F> inline BOOST_THREAD_FUTURE<typename boost::result_of<F(shared_future)>::type> then(launch policy, BOOST_THREAD_FWD_REF(F) func); // EXTENSION #endif //#if defined BOOST_THREAD_PROVIDES_FUTURE_UNWRAP // inline // typename enable_if_c< // is_future_type<value_type>::value, // BOOST_THREAD_FUTURE<typename is_future_type<value_type>::type> // >::type // unwrap(); //#endif }; BOOST_THREAD_DCL_MOVABLE_BEG(T) shared_future<T> BOOST_THREAD_DCL_MOVABLE_END namespace detail { /// Copy construction from a shared_future template <typename R> inline basic_future<R>::basic_future(const shared_future<R>& other) BOOST_NOEXCEPT : future_(other.future_) { } } template <typename R> class promise { typedef boost::shared_ptr<detail::shared_state<R> > future_ptr; future_ptr future_; bool future_obtained; void lazy_init() { #if defined BOOST_THREAD_PROVIDES_PROMISE_LAZY #include <boost/detail/atomic_undef_macros.hpp> if(!atomic_load(&future_)) { future_ptr blank; atomic_compare_exchange(&future_,&blank,future_ptr(new detail::shared_state<R>)); } #include <boost/detail/atomic_redef_macros.hpp> #endif } public: BOOST_THREAD_MOVABLE_ONLY(promise) #if defined BOOST_THREAD_PROVIDES_FUTURE_CTOR_ALLOCATORS template <class Allocator> promise(boost::allocator_arg_t, Allocator a) { typedef typename Allocator::template rebind<detail::shared_state<R> >::other A2; A2 a2(a); typedef thread_detail::allocator_destructor<A2> D; future_ = future_ptr(::new(a2.allocate(1)) detail::shared_state<R>(), D(a2, 1) ); future_obtained = false; } #endif promise(): #if defined BOOST_THREAD_PROVIDES_PROMISE_LAZY future_(), #else future_(new detail::shared_state<R>()), #endif future_obtained(false) {} ~promise() { if(future_) { boost::unique_lock<boost::mutex> lock(future_->mutex); if(!future_->done && !future_->is_constructed) { future_->mark_exceptional_finish_internal(boost::copy_exception(broken_promise()), lock); } } } // Assignment promise(BOOST_THREAD_RV_REF(promise) rhs) BOOST_NOEXCEPT : future_(BOOST_THREAD_RV(rhs).future_),future_obtained(BOOST_THREAD_RV(rhs).future_obtained) { BOOST_THREAD_RV(rhs).future_.reset(); BOOST_THREAD_RV(rhs).future_obtained=false; } promise & operator=(BOOST_THREAD_RV_REF(promise) rhs) BOOST_NOEXCEPT { future_=BOOST_THREAD_RV(rhs).future_; future_obtained=BOOST_THREAD_RV(rhs).future_obtained; BOOST_THREAD_RV(rhs).future_.reset(); BOOST_THREAD_RV(rhs).future_obtained=false; return *this; } void swap(promise& other) { future_.swap(other.future_); std::swap(future_obtained,other.future_obtained); } // Result retrieval BOOST_THREAD_FUTURE<R> get_future() { lazy_init(); if (future_.get()==0) { boost::throw_exception(promise_moved()); } if (future_obtained) { boost::throw_exception(future_already_retrieved()); } future_obtained=true; return BOOST_THREAD_FUTURE<R>(future_); } void set_value(typename detail::future_traits<R>::source_reference_type r) { lazy_init(); boost::unique_lock<boost::mutex> lock(future_->mutex); if(future_->done) { boost::throw_exception(promise_already_satisfied()); } future_->mark_finished_with_result_internal(r, lock); } // void set_value(R && r); void set_value(typename detail::future_traits<R>::rvalue_source_type r) { lazy_init(); boost::unique_lock<boost::mutex> lock(future_->mutex); if(future_->done) { boost::throw_exception(promise_already_satisfied()); } #if ! defined BOOST_NO_CXX11_RVALUE_REFERENCES future_->mark_finished_with_result_internal(boost::forward<R>(r), lock); #else future_->mark_finished_with_result_internal(static_cast<typename detail::future_traits<R>::rvalue_source_type>(r), lock); #endif } void set_exception(boost::exception_ptr p) { lazy_init(); boost::unique_lock<boost::mutex> lock(future_->mutex); if(future_->done) { boost::throw_exception(promise_already_satisfied()); } future_->mark_exceptional_finish_internal(p, lock); } template <typename E> void set_exception(E ex) { set_exception(copy_exception(ex)); } // setting the result with deferred notification void set_value_at_thread_exit(const R& r) { if (future_.get()==0) { boost::throw_exception(promise_moved()); } future_->set_value_at_thread_exit(r); } void set_value_at_thread_exit(BOOST_THREAD_RV_REF(R) r) { if (future_.get()==0) { boost::throw_exception(promise_moved()); } future_->set_value_at_thread_exit(boost::move(r)); } void set_exception_at_thread_exit(exception_ptr e) { if (future_.get()==0) { boost::throw_exception(promise_moved()); } future_->set_exception_at_thread_exit(e); } template <typename E> void set_exception_at_thread_exit(E ex) { set_exception_at_thread_exit(copy_exception(ex)); } template<typename F> void set_wait_callback(F f) { lazy_init(); future_->set_wait_callback(f,this); } }; template <typename R> class promise<R&> { typedef boost::shared_ptr<detail::shared_state<R&> > future_ptr; future_ptr future_; bool future_obtained; void lazy_init() { #if defined BOOST_THREAD_PROVIDES_PROMISE_LAZY #include <boost/detail/atomic_undef_macros.hpp> if(!atomic_load(&future_)) { future_ptr blank; atomic_compare_exchange(&future_,&blank,future_ptr(new detail::shared_state<R&>)); } #include <boost/detail/atomic_redef_macros.hpp> #endif } public: BOOST_THREAD_MOVABLE_ONLY(promise) #if defined BOOST_THREAD_PROVIDES_FUTURE_CTOR_ALLOCATORS template <class Allocator> promise(boost::allocator_arg_t, Allocator a) { typedef typename Allocator::template rebind<detail::shared_state<R&> >::other A2; A2 a2(a); typedef thread_detail::allocator_destructor<A2> D; future_ = future_ptr(::new(a2.allocate(1)) detail::shared_state<R&>(), D(a2, 1) ); future_obtained = false; } #endif promise(): #if defined BOOST_THREAD_PROVIDES_PROMISE_LAZY future_(), #else future_(new detail::shared_state<R&>()), #endif future_obtained(false) {} ~promise() { if(future_) { boost::unique_lock<boost::mutex> lock(future_->mutex); if(!future_->done && !future_->is_constructed) { future_->mark_exceptional_finish_internal(boost::copy_exception(broken_promise()), lock); } } } // Assignment promise(BOOST_THREAD_RV_REF(promise) rhs) BOOST_NOEXCEPT : future_(BOOST_THREAD_RV(rhs).future_),future_obtained(BOOST_THREAD_RV(rhs).future_obtained) { BOOST_THREAD_RV(rhs).future_.reset(); BOOST_THREAD_RV(rhs).future_obtained=false; } promise & operator=(BOOST_THREAD_RV_REF(promise) rhs) BOOST_NOEXCEPT { future_=BOOST_THREAD_RV(rhs).future_; future_obtained=BOOST_THREAD_RV(rhs).future_obtained; BOOST_THREAD_RV(rhs).future_.reset(); BOOST_THREAD_RV(rhs).future_obtained=false; return *this; } void swap(promise& other) { future_.swap(other.future_); std::swap(future_obtained,other.future_obtained); } // Result retrieval BOOST_THREAD_FUTURE<R&> get_future() { lazy_init(); if (future_.get()==0) { boost::throw_exception(promise_moved()); } if (future_obtained) { boost::throw_exception(future_already_retrieved()); } future_obtained=true; return BOOST_THREAD_FUTURE<R&>(future_); } void set_value(R& r) { lazy_init(); boost::unique_lock<boost::mutex> lock(future_->mutex); if(future_->done) { boost::throw_exception(promise_already_satisfied()); } future_->mark_finished_with_result_internal(r, lock); } void set_exception(boost::exception_ptr p) { lazy_init(); boost::unique_lock<boost::mutex> lock(future_->mutex); if(future_->done) { boost::throw_exception(promise_already_satisfied()); } future_->mark_exceptional_finish_internal(p, lock); } template <typename E> void set_exception(E ex) { set_exception(copy_exception(ex)); } // setting the result with deferred notification void set_value_at_thread_exit(R& r) { if (future_.get()==0) { boost::throw_exception(promise_moved()); } future_->set_value_at_thread_exit(r); } void set_exception_at_thread_exit(exception_ptr e) { if (future_.get()==0) { boost::throw_exception(promise_moved()); } future_->set_exception_at_thread_exit(e); } template <typename E> void set_exception_at_thread_exit(E ex) { set_exception_at_thread_exit(copy_exception(ex)); } template<typename F> void set_wait_callback(F f) { lazy_init(); future_->set_wait_callback(f,this); } }; template <> class promise<void> { typedef boost::shared_ptr<detail::shared_state<void> > future_ptr; future_ptr future_; bool future_obtained; void lazy_init() { #if defined BOOST_THREAD_PROVIDES_PROMISE_LAZY if(!atomic_load(&future_)) { future_ptr blank; atomic_compare_exchange(&future_,&blank,future_ptr(new detail::shared_state<void>)); } #endif } public: BOOST_THREAD_MOVABLE_ONLY(promise) #if defined BOOST_THREAD_PROVIDES_FUTURE_CTOR_ALLOCATORS template <class Allocator> promise(boost::allocator_arg_t, Allocator a) { typedef typename Allocator::template rebind<detail::shared_state<void> >::other A2; A2 a2(a); typedef thread_detail::allocator_destructor<A2> D; future_ = future_ptr(::new(a2.allocate(1)) detail::shared_state<void>(), D(a2, 1) ); future_obtained = false; } #endif promise(): #if defined BOOST_THREAD_PROVIDES_PROMISE_LAZY future_(), #else future_(new detail::shared_state<void>), #endif future_obtained(false) {} ~promise() { if(future_) { boost::unique_lock<boost::mutex> lock(future_->mutex); if(!future_->done && !future_->is_constructed) { future_->mark_exceptional_finish_internal(boost::copy_exception(broken_promise()), lock); } } } // Assignment promise(BOOST_THREAD_RV_REF(promise) rhs) BOOST_NOEXCEPT : future_(BOOST_THREAD_RV(rhs).future_),future_obtained(BOOST_THREAD_RV(rhs).future_obtained) { // we need to release the future as shared_ptr doesn't implements move semantics BOOST_THREAD_RV(rhs).future_.reset(); BOOST_THREAD_RV(rhs).future_obtained=false; } promise & operator=(BOOST_THREAD_RV_REF(promise) rhs) BOOST_NOEXCEPT { future_=BOOST_THREAD_RV(rhs).future_; future_obtained=BOOST_THREAD_RV(rhs).future_obtained; BOOST_THREAD_RV(rhs).future_.reset(); BOOST_THREAD_RV(rhs).future_obtained=false; return *this; } void swap(promise& other) { future_.swap(other.future_); std::swap(future_obtained,other.future_obtained); } // Result retrieval BOOST_THREAD_FUTURE<void> get_future() { lazy_init(); if (future_.get()==0) { boost::throw_exception(promise_moved()); } if(future_obtained) { boost::throw_exception(future_already_retrieved()); } future_obtained=true; return BOOST_THREAD_FUTURE<void>(future_); } void set_value() { lazy_init(); boost::unique_lock<boost::mutex> lock(future_->mutex); if(future_->done) { boost::throw_exception(promise_already_satisfied()); } future_->mark_finished_with_result_internal(lock); } void set_exception(boost::exception_ptr p) { lazy_init(); boost::unique_lock<boost::mutex> lock(future_->mutex); if(future_->done) { boost::throw_exception(promise_already_satisfied()); } future_->mark_exceptional_finish_internal(p,lock); } template <typename E> void set_exception(E ex) { set_exception(copy_exception(ex)); } // setting the result with deferred notification void set_value_at_thread_exit() { if (future_.get()==0) { boost::throw_exception(promise_moved()); } future_->set_value_at_thread_exit(); } void set_exception_at_thread_exit(exception_ptr e) { if (future_.get()==0) { boost::throw_exception(promise_moved()); } future_->set_exception_at_thread_exit(e); } template <typename E> void set_exception_at_thread_exit(E ex) { set_exception_at_thread_exit(copy_exception(ex)); } template<typename F> void set_wait_callback(F f) { lazy_init(); future_->set_wait_callback(f,this); } }; #if defined BOOST_THREAD_PROVIDES_FUTURE_CTOR_ALLOCATORS namespace container { template <class R, class Alloc> struct uses_allocator<promise<R> , Alloc> : true_type { }; } #endif BOOST_THREAD_DCL_MOVABLE_BEG(T) promise<T> BOOST_THREAD_DCL_MOVABLE_END namespace detail { #if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK template<typename R> struct task_base_shared_state; #if defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD) template<typename R, typename ...ArgTypes> struct task_base_shared_state<R(ArgTypes...)>: #else template<typename R> struct task_base_shared_state<R()>: #endif #else template<typename R> struct task_base_shared_state: #endif detail::shared_state<R> { bool started; task_base_shared_state(): started(false) {} void reset() { started=false; } #if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK && defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD) virtual void do_run(BOOST_THREAD_RV_REF(ArgTypes) ... args)=0; void run(BOOST_THREAD_RV_REF(ArgTypes) ... args) #else virtual void do_run()=0; void run() #endif { { boost::lock_guard<boost::mutex> lk(this->mutex); if(started) { boost::throw_exception(task_already_started()); } started=true; } #if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK && defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD) do_run(boost::forward<ArgTypes>(args)...); #else do_run(); #endif } #if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK && defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD) virtual void do_apply(BOOST_THREAD_RV_REF(ArgTypes) ... args)=0; void apply(BOOST_THREAD_RV_REF(ArgTypes) ... args) #else virtual void do_apply()=0; void apply() #endif { { boost::lock_guard<boost::mutex> lk(this->mutex); if(started) { boost::throw_exception(task_already_started()); } started=true; } #if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK && defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD) do_apply(boost::forward<ArgTypes>(args)...); #else do_apply(); #endif } void owner_destroyed() { boost::unique_lock<boost::mutex> lk(this->mutex); if(!started) { started=true; this->mark_exceptional_finish_internal(boost::copy_exception(boost::broken_promise()), lk); } } }; #if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK template<typename F, typename R> struct task_shared_state; #if defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD) template<typename F, typename R, typename ...ArgTypes> struct task_shared_state<F, R(ArgTypes...)>: task_base_shared_state<R(ArgTypes...)> #else template<typename F, typename R> struct task_shared_state<F, R()>: task_base_shared_state<R()> #endif #else template<typename F, typename R> struct task_shared_state: task_base_shared_state<R> #endif { private: task_shared_state(task_shared_state&); public: F f; task_shared_state(F const& f_): f(f_) {} task_shared_state(BOOST_THREAD_RV_REF(F) f_): f(boost::move(f_)) {} #if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK && defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD) void do_apply(BOOST_THREAD_RV_REF(ArgTypes) ... args) { try { this->set_value_at_thread_exit(f(boost::forward<ArgTypes>(args)...)); } #else void do_apply() { try { this->set_value_at_thread_exit(f()); } #endif #if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS catch(thread_interrupted& ) { this->set_interrupted_at_thread_exit(); } #endif catch(...) { this->set_exception_at_thread_exit(current_exception()); } } #if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK && defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD) void do_run(BOOST_THREAD_RV_REF(ArgTypes) ... args) { try { this->mark_finished_with_result(f(boost::forward<ArgTypes>(args)...)); } #else void do_run() { try { #if ! defined BOOST_NO_CXX11_RVALUE_REFERENCES R res((f())); this->mark_finished_with_result(boost::move(res)); #else this->mark_finished_with_result(f()); #endif } #endif #if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS catch(thread_interrupted& ) { this->mark_interrupted_finish(); } #endif catch(...) { this->mark_exceptional_finish(); } } }; #if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK #if defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD) template<typename F, typename R, typename ...ArgTypes> struct task_shared_state<F, R&(ArgTypes...)>: task_base_shared_state<R&(ArgTypes...)> #else template<typename F, typename R> struct task_shared_state<F, R&()>: task_base_shared_state<R&()> #endif #else template<typename F, typename R> struct task_shared_state<F,R&>: task_base_shared_state<R&> #endif { private: task_shared_state(task_shared_state&); public: F f; task_shared_state(F const& f_): f(f_) {} task_shared_state(BOOST_THREAD_RV_REF(F) f_): f(boost::move(f_)) {} #if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK && defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD) void do_apply(BOOST_THREAD_RV_REF(ArgTypes) ... args) { try { this->set_value_at_thread_exit(f(boost::forward<ArgTypes>(args)...)); } #else void do_apply() { try { this->set_value_at_thread_exit(f()); } #endif #if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS catch(thread_interrupted& ) { this->set_interrupted_at_thread_exit(); } #endif catch(...) { this->set_exception_at_thread_exit(current_exception()); } } #if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK && defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD) void do_run(BOOST_THREAD_RV_REF(ArgTypes) ... args) { try { this->mark_finished_with_result(f(boost::forward<ArgTypes>(args)...)); } #else void do_run() { try { R& res((f())); this->mark_finished_with_result(res); } #endif #if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS catch(thread_interrupted& ) { this->mark_interrupted_finish(); } #endif catch(...) { this->mark_exceptional_finish(); } } }; #if defined(BOOST_THREAD_RVALUE_REFERENCES_DONT_MATCH_FUNTION_PTR) #if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK #if defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD) template<typename R, typename ...ArgTypes> struct task_shared_state<R (*)(ArgTypes...), R(ArgTypes...)>: task_base_shared_state<R(ArgTypes...)> #else template<typename R> struct task_shared_state<R (*)(), R()>: task_base_shared_state<R()> #endif #else template<typename R> struct task_shared_state<R (*)(), R> : task_base_shared_state<R> #endif { private: task_shared_state(task_shared_state&); public: R (*f)(); task_shared_state(R (*f_)()): f(f_) {} #if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK && defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD) void do_apply(BOOST_THREAD_RV_REF(ArgTypes) ... args) { try { this->set_value_at_thread_exit(f(boost::forward<ArgTypes>(args)...)); } #else void do_apply() { try { R r((f())); this->set_value_at_thread_exit(boost::move(r)); } #endif #if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS catch(thread_interrupted& ) { this->set_interrupted_at_thread_exit(); } #endif catch(...) { this->set_exception_at_thread_exit(current_exception()); } } #if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK && defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD) void do_run(BOOST_THREAD_RV_REF(ArgTypes) ... args) { try { this->mark_finished_with_result(f(boost::forward<ArgTypes>(args)...)); } #else void do_run() { try { R res((f())); this->mark_finished_with_result(boost::move(res)); } #endif #if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS catch(thread_interrupted& ) { this->mark_interrupted_finish(); } #endif catch(...) { this->mark_exceptional_finish(); } } }; #if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK #if defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD) template<typename R, typename ...ArgTypes> struct task_shared_state<R& (*)(ArgTypes...), R&(ArgTypes...)>: task_base_shared_state<R&(ArgTypes...)> #else template<typename R> struct task_shared_state<R& (*)(), R&()>: task_base_shared_state<R&()> #endif #else template<typename R> struct task_shared_state<R& (*)(), R&> : task_base_shared_state<R&> #endif { private: task_shared_state(task_shared_state&); public: R& (*f)(); task_shared_state(R& (*f_)()): f(f_) {} #if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK && defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD) void do_apply(BOOST_THREAD_RV_REF(ArgTypes) ... args) { try { this->set_value_at_thread_exit(f(boost::forward<ArgTypes>(args)...)); } #else void do_apply() { try { this->set_value_at_thread_exit(f()); } #endif #if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS catch(thread_interrupted& ) { this->set_interrupted_at_thread_exit(); } #endif catch(...) { this->set_exception_at_thread_exit(current_exception()); } } #if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK && defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD) void do_run(BOOST_THREAD_RV_REF(ArgTypes) ... args) { try { this->mark_finished_with_result(f(boost::forward<ArgTypes>(args)...)); } #else void do_run() { try { this->mark_finished_with_result(f()); } #endif #if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS catch(thread_interrupted& ) { this->mark_interrupted_finish(); } #endif catch(...) { this->mark_exceptional_finish(); } } }; #endif #if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK #if defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD) template<typename F, typename ...ArgTypes> struct task_shared_state<F, void(ArgTypes...)>: task_base_shared_state<void(ArgTypes...)> #else template<typename F> struct task_shared_state<F, void()>: task_base_shared_state<void()> #endif #else template<typename F> struct task_shared_state<F,void>: task_base_shared_state<void> #endif { private: task_shared_state(task_shared_state&); public: F f; task_shared_state(F const& f_): f(f_) {} task_shared_state(BOOST_THREAD_RV_REF(F) f_): f(boost::move(f_)) {} #if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK && defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD) void do_apply(BOOST_THREAD_RV_REF(ArgTypes) ... args) { try { f(boost::forward<ArgTypes>(args)...); #else void do_apply() { try { f(); #endif this->set_value_at_thread_exit(); } #if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS catch(thread_interrupted& ) { this->set_interrupted_at_thread_exit(); } #endif catch(...) { this->set_exception_at_thread_exit(current_exception()); } } #if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK && defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD) void do_run(BOOST_THREAD_RV_REF(ArgTypes) ... args) { try { f(boost::forward<ArgTypes>(args)...); #else void do_run() { try { f(); #endif this->mark_finished_with_result(); } #if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS catch(thread_interrupted& ) { this->mark_interrupted_finish(); } #endif catch(...) { this->mark_exceptional_finish(); } } }; #if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK #if defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD) template<typename ...ArgTypes> struct task_shared_state<void (*)(ArgTypes...), void(ArgTypes...)>: task_base_shared_state<void(ArgTypes...)> #else template<> struct task_shared_state<void (*)(), void()>: task_base_shared_state<void()> #endif #else template<> struct task_shared_state<void (*)(),void>: task_base_shared_state<void> #endif { private: task_shared_state(task_shared_state&); public: void (*f)(); task_shared_state(void (*f_)()): f(f_) {} #if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK && defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD) void do_apply(BOOST_THREAD_RV_REF(ArgTypes) ... args) { try { f(boost::forward<ArgTypes>(args)...); #else void do_apply() { try { f(); #endif this->set_value_at_thread_exit(); } #if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS catch(thread_interrupted& ) { this->set_interrupted_at_thread_exit(); } #endif catch(...) { this->set_exception_at_thread_exit(current_exception()); } } #if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK && defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD) void do_run(BOOST_THREAD_RV_REF(ArgTypes) ... args) { try { f(boost::forward<ArgTypes>(args)...); #else void do_run() { try { f(); #endif this->mark_finished_with_result(); } #if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS catch(thread_interrupted& ) { this->mark_interrupted_finish(); } #endif catch(...) { this->mark_exceptional_finish(); } } }; } #if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK #if defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD) template<typename R, typename ...ArgTypes> class packaged_task<R(ArgTypes...)> { typedef boost::shared_ptr<detail::task_base_shared_state<R(ArgTypes...)> > task_ptr; boost::shared_ptr<detail::task_base_shared_state<R(ArgTypes...)> > task; #else template<typename R> class packaged_task<R()> { typedef boost::shared_ptr<detail::task_base_shared_state<R()> > task_ptr; boost::shared_ptr<detail::task_base_shared_state<R()> > task; #endif #else template<typename R> class packaged_task { typedef boost::shared_ptr<detail::task_base_shared_state<R> > task_ptr; boost::shared_ptr<detail::task_base_shared_state<R> > task; #endif bool future_obtained; struct dummy; public: typedef R result_type; BOOST_THREAD_MOVABLE_ONLY(packaged_task) packaged_task(): future_obtained(false) {} // construction and destruction #if defined(BOOST_THREAD_RVALUE_REFERENCES_DONT_MATCH_FUNTION_PTR) #if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK #if defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD) explicit packaged_task(R(*f)(), BOOST_THREAD_FWD_REF(ArgTypes)... args) { typedef R(*FR)(BOOST_THREAD_FWD_REF(ArgTypes)...); typedef detail::task_shared_state<FR,R(ArgTypes...)> task_shared_state_type; task= task_ptr(new task_shared_state_type(f, boost::forward<ArgTypes>(args)...)); future_obtained=false; } #else explicit packaged_task(R(*f)()) { typedef R(*FR)(); typedef detail::task_shared_state<FR,R()> task_shared_state_type; task= task_ptr(new task_shared_state_type(f)); future_obtained=false; } #endif #else explicit packaged_task(R(*f)()) { typedef R(*FR)(); typedef detail::task_shared_state<FR,R> task_shared_state_type; task= task_ptr(new task_shared_state_type(f)); future_obtained=false; } #endif #endif #ifndef BOOST_NO_CXX11_RVALUE_REFERENCES template <class F> explicit packaged_task(BOOST_THREAD_FWD_REF(F) f , typename disable_if<is_same<typename decay<F>::type, packaged_task>, dummy* >::type=0 ) { typedef typename remove_cv<typename remove_reference<F>::type>::type FR; #if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK #if defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD) typedef detail::task_shared_state<FR,R(ArgTypes...)> task_shared_state_type; #else typedef detail::task_shared_state<FR,R()> task_shared_state_type; #endif #else typedef detail::task_shared_state<FR,R> task_shared_state_type; #endif task = task_ptr(new task_shared_state_type(boost::forward<F>(f))); future_obtained = false; } #else template <class F> explicit packaged_task(F const& f , typename disable_if<is_same<typename decay<F>::type, packaged_task>, dummy* >::type=0 ) { #if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK #if defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD) typedef detail::task_shared_state<F,R(ArgTypes...)> task_shared_state_type; #else typedef detail::task_shared_state<F,R()> task_shared_state_type; #endif #else typedef detail::task_shared_state<F,R> task_shared_state_type; #endif task = task_ptr(new task_shared_state_type(f)); future_obtained=false; } template <class F> explicit packaged_task(BOOST_THREAD_RV_REF(F) f) { #if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK #if defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD) typedef detail::task_shared_state<F,R(ArgTypes...)> task_shared_state_type; task = task_ptr(new task_shared_state_type(boost::forward<F>(f))); #else typedef detail::task_shared_state<F,R()> task_shared_state_type; task = task_ptr(new task_shared_state_type(boost::move(f))); // TODO forward #endif #else typedef detail::task_shared_state<F,R> task_shared_state_type; task = task_ptr(new task_shared_state_type(boost::forward<F>(f))); #endif future_obtained=false; } #endif #if defined BOOST_THREAD_PROVIDES_FUTURE_CTOR_ALLOCATORS #if defined(BOOST_THREAD_RVALUE_REFERENCES_DONT_MATCH_FUNTION_PTR) template <class Allocator> packaged_task(boost::allocator_arg_t, Allocator a, R(*f)()) { typedef R(*FR)(); #if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK #if defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD) typedef detail::task_shared_state<FR,R(ArgTypes...)> task_shared_state_type; #else typedef detail::task_shared_state<FR,R()> task_shared_state_type; #endif #else typedef detail::task_shared_state<FR,R> task_shared_state_type; #endif typedef typename Allocator::template rebind<task_shared_state_type>::other A2; A2 a2(a); typedef thread_detail::allocator_destructor<A2> D; task = task_ptr(::new(a2.allocate(1)) task_shared_state_type(f), D(a2, 1) ); future_obtained = false; } #endif // BOOST_THREAD_RVALUE_REFERENCES_DONT_MATCH_FUNTION_PTR #if ! defined BOOST_NO_CXX11_RVALUE_REFERENCES template <class F, class Allocator> packaged_task(boost::allocator_arg_t, Allocator a, BOOST_THREAD_FWD_REF(F) f) { typedef typename remove_cv<typename remove_reference<F>::type>::type FR; #if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK #if defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD) typedef detail::task_shared_state<FR,R(ArgTypes...)> task_shared_state_type; #else typedef detail::task_shared_state<FR,R()> task_shared_state_type; #endif #else typedef detail::task_shared_state<FR,R> task_shared_state_type; #endif typedef typename Allocator::template rebind<task_shared_state_type>::other A2; A2 a2(a); typedef thread_detail::allocator_destructor<A2> D; task = task_ptr(::new(a2.allocate(1)) task_shared_state_type(boost::forward<F>(f)), D(a2, 1) ); future_obtained = false; } #else // ! defined BOOST_NO_CXX11_RVALUE_REFERENCES template <class F, class Allocator> packaged_task(boost::allocator_arg_t, Allocator a, const F& f) { #if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK #if defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD) typedef detail::task_shared_state<F,R(ArgTypes...)> task_shared_state_type; #else typedef detail::task_shared_state<F,R()> task_shared_state_type; #endif #else typedef detail::task_shared_state<F,R> task_shared_state_type; #endif typedef typename Allocator::template rebind<task_shared_state_type>::other A2; A2 a2(a); typedef thread_detail::allocator_destructor<A2> D; task = task_ptr(::new(a2.allocate(1)) task_shared_state_type(f), D(a2, 1) ); future_obtained = false; } template <class F, class Allocator> packaged_task(boost::allocator_arg_t, Allocator a, BOOST_THREAD_RV_REF(F) f) { #if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK #if defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD) typedef detail::task_shared_state<F,R(ArgTypes...)> task_shared_state_type; #else typedef detail::task_shared_state<F,R()> task_shared_state_type; #endif #else typedef detail::task_shared_state<F,R> task_shared_state_type; #endif typedef typename Allocator::template rebind<task_shared_state_type>::other A2; A2 a2(a); typedef thread_detail::allocator_destructor<A2> D; #if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK && defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD) task = task_ptr(::new(a2.allocate(1)) task_shared_state_type(boost::forward<F>(f)), D(a2, 1) ); #else task = task_ptr(::new(a2.allocate(1)) task_shared_state_type(boost::move(f)), D(a2, 1) ); // TODO forward #endif future_obtained = false; } #endif //BOOST_NO_CXX11_RVALUE_REFERENCES #endif // BOOST_THREAD_PROVIDES_FUTURE_CTOR_ALLOCATORS ~packaged_task() { if(task) { task->owner_destroyed(); } } // assignment packaged_task(BOOST_THREAD_RV_REF(packaged_task) other) BOOST_NOEXCEPT : future_obtained(BOOST_THREAD_RV(other).future_obtained) { task.swap(BOOST_THREAD_RV(other).task); BOOST_THREAD_RV(other).future_obtained=false; } packaged_task& operator=(BOOST_THREAD_RV_REF(packaged_task) other) BOOST_NOEXCEPT { // todo use forward #if ! defined BOOST_NO_CXX11_RVALUE_REFERENCES packaged_task temp(boost::move(other)); #else packaged_task temp(static_cast<BOOST_THREAD_RV_REF(packaged_task)>(other)); #endif swap(temp); return *this; } void reset() { if (!valid()) throw future_error(system::make_error_code(future_errc::no_state)); task->reset(); future_obtained=false; } void swap(packaged_task& other) BOOST_NOEXCEPT { task.swap(other.task); std::swap(future_obtained,other.future_obtained); } bool valid() const BOOST_NOEXCEPT { return task.get()!=0; } // result retrieval BOOST_THREAD_FUTURE<R> get_future() { if(!task) { boost::throw_exception(task_moved()); } else if(!future_obtained) { future_obtained=true; return BOOST_THREAD_FUTURE<R>(task); } else { boost::throw_exception(future_already_retrieved()); } //return BOOST_THREAD_FUTURE<R>(); } // execution #if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK && defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD) void operator()(BOOST_THREAD_RV_REF(ArgTypes)... args) { if(!task) { boost::throw_exception(task_moved()); } task->run(boost::forward<ArgTypes>(args)...); } void make_ready_at_thread_exit(ArgTypes... args) { if(!task) { boost::throw_exception(task_moved()); } if (task->has_value()) { boost::throw_exception(promise_already_satisfied()); } task->apply(boost::forward<ArgTypes>(args)...); } #else void operator()() { if(!task) { boost::throw_exception(task_moved()); } task->run(); } void make_ready_at_thread_exit() { if(!task) { boost::throw_exception(task_moved()); } if (task->has_value()) boost::throw_exception(promise_already_satisfied()); task->apply(); } #endif template<typename F> void set_wait_callback(F f) { task->set_wait_callback(f,this); } }; #if defined BOOST_THREAD_PROVIDES_FUTURE_CTOR_ALLOCATORS namespace container { template <class R, class Alloc> struct uses_allocator<packaged_task<R>, Alloc> : public true_type {}; } #endif BOOST_THREAD_DCL_MOVABLE_BEG(T) packaged_task<T> BOOST_THREAD_DCL_MOVABLE_END namespace detail { //////////////////////////////// // make_future_deferred_shared_state //////////////////////////////// template <class Rp, class Fp> BOOST_THREAD_FUTURE<Rp> make_future_deferred_shared_state(BOOST_THREAD_FWD_REF(Fp) f) { shared_ptr<future_deferred_shared_state<Rp, Fp> > h(new future_deferred_shared_state<Rp, Fp>(boost::forward<Fp>(f))); return BOOST_THREAD_FUTURE<Rp>(h); } //////////////////////////////// // make_future_async_shared_state //////////////////////////////// template <class Rp, class Fp> BOOST_THREAD_FUTURE<Rp> make_future_async_shared_state(BOOST_THREAD_FWD_REF(Fp) f) { shared_ptr<future_async_shared_state<Rp, Fp> > h(new future_async_shared_state<Rp, Fp>(boost::forward<Fp>(f))); return BOOST_THREAD_FUTURE<Rp>(h); } } //////////////////////////////// // template <class F, class... ArgTypes> // future<R> async(launch policy, F&&, ArgTypes&&...); //////////////////////////////// #if defined BOOST_THREAD_RVALUE_REFERENCES_DONT_MATCH_FUNTION_PTR #if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK #if defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD) template <class R, class... ArgTypes> BOOST_THREAD_FUTURE<R> async(launch policy, R(*f)(BOOST_THREAD_FWD_REF(ArgTypes)...), BOOST_THREAD_FWD_REF(ArgTypes)... args) { typedef R(*F)(BOOST_THREAD_FWD_REF(ArgTypes)...); typedef detail::async_func<typename decay<F>::type, typename decay<ArgTypes>::type...> BF; typedef typename BF::result_type Rp; #else template <class R> BOOST_THREAD_FUTURE<R> async(launch policy, R(*f)()) { typedef packaged_task<R()> packaged_task_type; #endif #else template <class R> BOOST_THREAD_FUTURE<R> async(launch policy, R(*f)()) { typedef packaged_task<R> packaged_task_type; #endif if (int(policy) & int(launch::async)) { #if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK && defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD) return BOOST_THREAD_MAKE_RV_REF(boost::detail::make_future_async_shared_state<Rp>( BF( thread_detail::decay_copy(boost::forward<F>(f)) , thread_detail::decay_copy(boost::forward<ArgTypes>(args))... ) )); #else packaged_task_type pt( f ); BOOST_THREAD_FUTURE<R> ret = BOOST_THREAD_MAKE_RV_REF(pt.get_future()); ret.set_async(); boost::thread( boost::move(pt) ).detach(); return ::boost::move(ret); #endif } else if (int(policy) & int(launch::deferred)) { #if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK && defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD) return BOOST_THREAD_MAKE_RV_REF(boost::detail::make_future_deferred_shared_state<Rp>( BF( thread_detail::decay_copy(boost::forward<F>(f)) , thread_detail::decay_copy(boost::forward<ArgTypes>(args))... ) )); #else std::terminate(); BOOST_THREAD_FUTURE<R> ret; return ::boost::move(ret); #endif } else { std::terminate(); BOOST_THREAD_FUTURE<R> ret; return ::boost::move(ret); } } #endif #if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK #if defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD) template <class F, class ...ArgTypes> BOOST_THREAD_FUTURE<typename boost::result_of<typename decay<F>::type( typename decay<ArgTypes>::type... )>::type> async(launch policy, BOOST_THREAD_FWD_REF(F) f, BOOST_THREAD_FWD_REF(ArgTypes)... args) { typedef typename boost::result_of<typename decay<F>::type( typename decay<ArgTypes>::type... )>::type R; typedef detail::async_func<typename decay<F>::type, typename decay<ArgTypes>::type...> BF; typedef typename BF::result_type Rp; #else template <class F> BOOST_THREAD_FUTURE<typename boost::result_of<typename decay<F>::type()>::type> async(launch policy, BOOST_THREAD_FWD_REF(F) f) { typedef typename boost::result_of<typename decay<F>::type()>::type R; typedef packaged_task<R()> packaged_task_type; #endif #else template <class F> BOOST_THREAD_FUTURE<typename boost::result_of<typename decay<F>::type()>::type> async(launch policy, BOOST_THREAD_FWD_REF(F) f) { typedef typename boost::result_of<typename decay<F>::type()>::type R; typedef packaged_task<R> packaged_task_type; #endif if (int(policy) & int(launch::async)) { #if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK && defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD) return BOOST_THREAD_MAKE_RV_REF(boost::detail::make_future_async_shared_state<Rp>( BF( thread_detail::decay_copy(boost::forward<F>(f)) , thread_detail::decay_copy(boost::forward<ArgTypes>(args))... ) )); #else packaged_task_type pt( boost::forward<F>(f) ); BOOST_THREAD_FUTURE<R> ret = pt.get_future(); ret.set_async(); boost::thread( boost::move(pt) ).detach(); return ::boost::move(ret); #endif } else if (int(policy) & int(launch::deferred)) { #if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK && defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD) return BOOST_THREAD_MAKE_RV_REF(boost::detail::make_future_deferred_shared_state<Rp>( BF( thread_detail::decay_copy(boost::forward<F>(f)) , thread_detail::decay_copy(boost::forward<ArgTypes>(args))... ) )); #else std::terminate(); BOOST_THREAD_FUTURE<R> ret; return ::boost::move(ret); // return boost::detail::make_future_deferred_shared_state<Rp>( // BF( // thread_detail::decay_copy(boost::forward<F>(f)) // ) // ); #endif } else { std::terminate(); BOOST_THREAD_FUTURE<R> ret; return ::boost::move(ret); } } //////////////////////////////// // template <class F, class... ArgTypes> // future<R> async(F&&, ArgTypes&&...); //////////////////////////////// #if defined BOOST_THREAD_RVALUE_REFERENCES_DONT_MATCH_FUNTION_PTR #if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK && defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD) template <class R, class... ArgTypes> BOOST_THREAD_FUTURE<R> async(R(*f)(BOOST_THREAD_FWD_REF(ArgTypes)...), BOOST_THREAD_FWD_REF(ArgTypes)... args) { return BOOST_THREAD_MAKE_RV_REF(async(launch(launch::any), f, boost::forward<ArgTypes>(args)...)); } #else template <class R> BOOST_THREAD_FUTURE<R> async(R(*f)()) { return BOOST_THREAD_MAKE_RV_REF(async(launch(launch::any), f)); } #endif #endif #if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK && defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD) template <class F, class ...ArgTypes> BOOST_THREAD_FUTURE<typename boost::result_of<typename decay<F>::type( typename decay<ArgTypes>::type... )>::type> async(BOOST_THREAD_FWD_REF(F) f, BOOST_THREAD_FWD_REF(ArgTypes)... args) { return BOOST_THREAD_MAKE_RV_REF(async(launch(launch::any), boost::forward<F>(f), boost::forward<ArgTypes>(args)...)); } #else template <class F> BOOST_THREAD_FUTURE<typename boost::result_of<F()>::type> async(BOOST_THREAD_RV_REF(F) f) { return BOOST_THREAD_MAKE_RV_REF(async(launch(launch::any), boost::forward<F>(f))); } #endif //////////////////////////////// // make_future deprecated //////////////////////////////// template <typename T> BOOST_THREAD_FUTURE<typename decay<T>::type> make_future(BOOST_THREAD_FWD_REF(T) value) { typedef typename decay<T>::type future_value_type; promise<future_value_type> p; p.set_value(boost::forward<future_value_type>(value)); return BOOST_THREAD_MAKE_RV_REF(p.get_future()); } #if defined BOOST_THREAD_USES_MOVE inline BOOST_THREAD_FUTURE<void> make_future() { promise<void> p; p.set_value(); return BOOST_THREAD_MAKE_RV_REF(p.get_future()); } #endif //////////////////////////////// // make_ready_future //////////////////////////////// template <typename T> BOOST_THREAD_FUTURE<typename decay<T>::type> make_ready_future(BOOST_THREAD_FWD_REF(T) value) { typedef typename decay<T>::type future_value_type; promise<future_value_type> p; p.set_value(boost::forward<future_value_type>(value)); return BOOST_THREAD_MAKE_RV_REF(p.get_future()); } #if defined BOOST_THREAD_USES_MOVE inline BOOST_THREAD_FUTURE<void> make_ready_future() { promise<void> p; p.set_value(); return BOOST_THREAD_MAKE_RV_REF(p.get_future()); } #endif template <typename T> BOOST_THREAD_FUTURE<T> make_ready_future(exception_ptr ex) { promise<T> p; p.set_exception(ex); return BOOST_THREAD_MAKE_RV_REF(p.get_future()); } template <typename T, typename E> BOOST_THREAD_FUTURE<T> make_ready_future(E ex) { promise<T> p; p.set_exception(boost::copy_exception(ex)); return BOOST_THREAD_MAKE_RV_REF(p.get_future()); } #if 0 template<typename CLOSURE> make_future(CLOSURE closure) -> BOOST_THREAD_FUTURE<decltype(closure())> { typedef decltype(closure()) T; promise<T> p; try { p.set_value(closure()); } catch(...) { p.set_exception(std::current_exception()); } return BOOST_THREAD_MAKE_RV_REF(p.get_future()); } #endif //////////////////////////////// // make_shared_future deprecated //////////////////////////////// template <typename T> shared_future<typename decay<T>::type> make_shared_future(BOOST_THREAD_FWD_REF(T) value) { typedef typename decay<T>::type future_type; promise<future_type> p; p.set_value(boost::forward<T>(value)); return BOOST_THREAD_MAKE_RV_REF(p.get_future().share()); } inline shared_future<void> make_shared_future() { promise<void> p; return BOOST_THREAD_MAKE_RV_REF(p.get_future().share()); } // //////////////////////////////// // // make_ready_shared_future // //////////////////////////////// // template <typename T> // shared_future<typename decay<T>::type> make_ready_shared_future(BOOST_THREAD_FWD_REF(T) value) // { // typedef typename decay<T>::type future_type; // promise<future_type> p; // p.set_value(boost::forward<T>(value)); // return p.get_future().share(); // } // // // inline shared_future<void> make_ready_shared_future() // { // promise<void> p; // return BOOST_THREAD_MAKE_RV_REF(p.get_future().share()); // // } // // //////////////////////////////// // // make_exceptional_shared_future // //////////////////////////////// // template <typename T> // shared_future<T> make_exceptional_shared_future(exception_ptr ex) // { // promise<T> p; // p.set_exception(ex); // return p.get_future().share(); // } //////////////////////////////// // detail::future_async_continuation_shared_state //////////////////////////////// #if defined BOOST_THREAD_PROVIDES_FUTURE_CONTINUATION namespace detail { ///////////////////////// /// future_async_continuation_shared_state ///////////////////////// template<typename F, typename Rp, typename Fp> struct future_async_continuation_shared_state: future_async_shared_state_base<Rp> { F parent; Fp continuation; public: future_async_continuation_shared_state( BOOST_THREAD_RV_REF(F) f, BOOST_THREAD_FWD_REF(Fp) c ) : parent(boost::move(f)), continuation(boost::move(c)) { } void launch_continuation(boost::unique_lock<boost::mutex>& lock) { lock.unlock(); this->thr_ = thread(&future_async_continuation_shared_state::run, this); } static void run(future_async_continuation_shared_state* that) { try { that->mark_finished_with_result(that->continuation(boost::move(that->parent))); } #if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS catch(thread_interrupted& ) { that->mark_interrupted_finish(); } #endif catch(...) { that->mark_exceptional_finish(); } } ~future_async_continuation_shared_state() { this->join(); } }; template<typename F, typename Fp> struct future_async_continuation_shared_state<F, void, Fp>: public future_async_shared_state_base<void> { F parent; Fp continuation; public: future_async_continuation_shared_state( BOOST_THREAD_RV_REF(F) f, BOOST_THREAD_FWD_REF(Fp) c ) : parent(boost::move(f)), continuation(boost::move(c)) { } void launch_continuation(boost::unique_lock<boost::mutex>& lk) { lk.unlock(); this->thr_ = thread(&future_async_continuation_shared_state::run, this); } static void run(future_async_continuation_shared_state* that) { try { that->continuation(boost::move(that->parent)); that->mark_finished_with_result(); } #if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS catch(thread_interrupted& ) { that->mark_interrupted_finish(); } #endif catch(...) { that->mark_exceptional_finish(); } } ~future_async_continuation_shared_state() { this->join(); } }; ////////////////////////// /// future_deferred_continuation_shared_state ////////////////////////// template<typename F, typename Rp, typename Fp> struct future_deferred_continuation_shared_state: shared_state<Rp> { F parent; Fp continuation; public: future_deferred_continuation_shared_state( BOOST_THREAD_RV_REF(F) f, BOOST_THREAD_FWD_REF(Fp) c ) : parent(boost::move(f)), continuation(boost::move(c)) { this->set_deferred(); } virtual void launch_continuation(boost::unique_lock<boost::mutex>& lk) { execute(lk); } virtual void execute(boost::unique_lock<boost::mutex>& lck) { try { this->mark_finished_with_result_internal(continuation(boost::move(parent)), lck); } catch (...) { this->mark_exceptional_finish_internal(current_exception(), lck); } } }; template<typename F, typename Fp> struct future_deferred_continuation_shared_state<F,void,Fp>: shared_state<void> { F parent; Fp continuation; public: future_deferred_continuation_shared_state( BOOST_THREAD_RV_REF(F) f, BOOST_THREAD_FWD_REF(Fp) c ): parent(boost::move(f)), continuation(boost::move(c)) { this->set_deferred(); } virtual void launch_continuation(boost::unique_lock<boost::mutex>& lk) { execute(lk); } virtual void execute(boost::unique_lock<boost::mutex>& lck) { try { continuation(boost::move(parent)); this->mark_finished_with_result_internal(lck); } catch (...) { this->mark_exceptional_finish_internal(current_exception(), lck); } } }; //////////////////////////////// // make_future_deferred_continuation_shared_state //////////////////////////////// template<typename F, typename Rp, typename Fp> BOOST_THREAD_FUTURE<Rp> make_future_deferred_continuation_shared_state( boost::unique_lock<boost::mutex> &lock, BOOST_THREAD_RV_REF(F) f, BOOST_THREAD_FWD_REF(Fp) c ) { shared_ptr<future_deferred_continuation_shared_state<F, Rp, Fp> > h(new future_deferred_continuation_shared_state<F, Rp, Fp>(boost::move(f), boost::forward<Fp>(c))); h->parent.future_->set_continuation_ptr(h, lock); return BOOST_THREAD_FUTURE<Rp>(h); } //////////////////////////////// // make_future_async_continuation_shared_state //////////////////////////////// template<typename F, typename Rp, typename Fp> BOOST_THREAD_FUTURE<Rp> make_future_async_continuation_shared_state( boost::unique_lock<boost::mutex> &lock, BOOST_THREAD_RV_REF(F) f, BOOST_THREAD_FWD_REF(Fp) c ) { shared_ptr<future_async_continuation_shared_state<F,Rp, Fp> > h(new future_async_continuation_shared_state<F,Rp, Fp>(boost::move(f), boost::forward<Fp>(c))); h->parent.future_->set_continuation_ptr(h, lock); return BOOST_THREAD_FUTURE<Rp>(h); } } //////////////////////////////// // template<typename F> // auto future<R>::then(F&& func) -> BOOST_THREAD_FUTURE<decltype(func(*this))>; //////////////////////////////// template <typename R> template <typename F> inline BOOST_THREAD_FUTURE<typename boost::result_of<F(BOOST_THREAD_FUTURE<R>)>::type> BOOST_THREAD_FUTURE<R>::then(launch policy, BOOST_THREAD_FWD_REF(F) func) { typedef typename boost::result_of<F(BOOST_THREAD_FUTURE<R>)>::type future_type; BOOST_THREAD_ASSERT_PRECONDITION(this->future_!=0, future_uninitialized()); boost::unique_lock<boost::mutex> lock(this->future_->mutex); if (int(policy) & int(launch::async)) { return BOOST_THREAD_MAKE_RV_REF((boost::detail::make_future_async_continuation_shared_state<BOOST_THREAD_FUTURE<R>, future_type, F>( lock, boost::move(*this), boost::forward<F>(func) ))); } else if (int(policy) & int(launch::deferred)) { return BOOST_THREAD_MAKE_RV_REF((boost::detail::make_future_deferred_continuation_shared_state<BOOST_THREAD_FUTURE<R>, future_type, F>( lock, boost::move(*this), boost::forward<F>(func) ))); } else { //BOOST_THREAD_ASSERT_PRECONDITION(false && "invalid launch parameter", std::logic_error("invalid launch parameter")); return BOOST_THREAD_MAKE_RV_REF((boost::detail::make_future_async_continuation_shared_state<BOOST_THREAD_FUTURE<R>, future_type, F>( lock, boost::move(*this), boost::forward<F>(func) ))); } } template <typename R> template <typename F> inline BOOST_THREAD_FUTURE<typename boost::result_of<F(BOOST_THREAD_FUTURE<R>)>::type> BOOST_THREAD_FUTURE<R>::then(BOOST_THREAD_FWD_REF(F) func) { typedef typename boost::result_of<F(BOOST_THREAD_FUTURE<R>)>::type future_type; BOOST_THREAD_ASSERT_PRECONDITION(this->future_!=0, future_uninitialized()); boost::unique_lock<boost::mutex> lock(this->future_->mutex); if (int(this->launch_policy(lock)) & int(launch::async)) { return boost::detail::make_future_async_continuation_shared_state<BOOST_THREAD_FUTURE<R>, future_type, F>( lock, boost::move(*this), boost::forward<F>(func) ); } else if (int(this->launch_policy(lock)) & int(launch::deferred)) { this->future_->wait_internal(lock); return boost::detail::make_future_deferred_continuation_shared_state<BOOST_THREAD_FUTURE<R>, future_type, F>( lock, boost::move(*this), boost::forward<F>(func) ); } else { //BOOST_THREAD_ASSERT_PRECONDITION(false && "invalid launch parameter", std::logic_error("invalid launch parameter")); return boost::detail::make_future_async_continuation_shared_state<BOOST_THREAD_FUTURE<R>, future_type, F>( lock, boost::move(*this), boost::forward<F>(func) ); } } //#if 0 && defined(BOOST_THREAD_RVALUE_REFERENCES_DONT_MATCH_FUNTION_PTR) // template <typename R> // template<typename RF> // BOOST_THREAD_FUTURE<RF> // BOOST_THREAD_FUTURE<R>::then(RF(*func)(BOOST_THREAD_FUTURE<R>&)) // { // // typedef RF future_type; // // if (this->future_) // { // boost::unique_lock<boost::mutex> lock(this->future_->mutex); // detail::future_continuation<BOOST_THREAD_FUTURE<R>, future_type, RF(*)(BOOST_THREAD_FUTURE&) > *ptr = // new detail::future_continuation<BOOST_THREAD_FUTURE<R>, future_type, RF(*)(BOOST_THREAD_FUTURE&)>(*this, func); // if (ptr==0) // { // return BOOST_THREAD_MAKE_RV_REF(BOOST_THREAD_FUTURE<future_type>()); // } // this->future_->set_continuation_ptr(ptr, lock); // return ptr->get_future(); // } else { // // fixme what to do when the future has no associated state? // return BOOST_THREAD_MAKE_RV_REF(BOOST_THREAD_FUTURE<future_type>()); // } // // } // template <typename R> // template<typename RF> // BOOST_THREAD_FUTURE<RF> // BOOST_THREAD_FUTURE<R>::then(launch policy, RF(*func)(BOOST_THREAD_FUTURE<R>&)) // { // // typedef RF future_type; // // if (this->future_) // { // boost::unique_lock<boost::mutex> lock(this->future_->mutex); // detail::future_continuation<BOOST_THREAD_FUTURE<R>, future_type, RF(*)(BOOST_THREAD_FUTURE&) > *ptr = // new detail::future_continuation<BOOST_THREAD_FUTURE<R>, future_type, RF(*)(BOOST_THREAD_FUTURE&)>(*this, func, policy); // if (ptr==0) // { // return BOOST_THREAD_MAKE_RV_REF(BOOST_THREAD_FUTURE<future_type>()); // } // this->future_->set_continuation_ptr(ptr, lock); // return ptr->get_future(); // } else { // // fixme what to do when the future has no associated state? // return BOOST_THREAD_MAKE_RV_REF(BOOST_THREAD_FUTURE<future_type>()); // } // // } //#endif template <typename R> template <typename F> inline BOOST_THREAD_FUTURE<typename boost::result_of<F(shared_future<R>)>::type> shared_future<R>::then(launch policy, BOOST_THREAD_FWD_REF(F) func) { typedef typename boost::result_of<F(shared_future<R>)>::type future_type; BOOST_THREAD_ASSERT_PRECONDITION(this->future_!=0, future_uninitialized()); boost::unique_lock<boost::mutex> lock(this->future_->mutex); if (int(policy) & int(launch::async)) { return BOOST_THREAD_MAKE_RV_REF((boost::detail::make_future_async_continuation_shared_state<shared_future<R>, future_type, F>( lock, boost::move(*this), boost::forward<F>(func) ))); } else if (int(policy) & int(launch::deferred)) { return BOOST_THREAD_MAKE_RV_REF((boost::detail::make_future_deferred_continuation_shared_state<shared_future<R>, future_type, F>( lock, boost::move(*this), boost::forward<F>(func) ))); } else { //BOOST_THREAD_ASSERT_PRECONDITION(false && "invalid launch parameter", std::logic_error("invalid launch parameter")); return BOOST_THREAD_MAKE_RV_REF((boost::detail::make_future_async_continuation_shared_state<shared_future<R>, future_type, F>( lock, boost::move(*this), boost::forward<F>(func) ))); } } template <typename R> template <typename F> inline BOOST_THREAD_FUTURE<typename boost::result_of<F(shared_future<R>)>::type> shared_future<R>::then(BOOST_THREAD_FWD_REF(F) func) { typedef typename boost::result_of<F(shared_future<R>)>::type future_type; BOOST_THREAD_ASSERT_PRECONDITION(this->future_!=0, future_uninitialized()); boost::unique_lock<boost::mutex> lock(this->future_->mutex); if (int(this->launch_policy(lock)) & int(launch::async)) { return boost::detail::make_future_async_continuation_shared_state<shared_future<R>, future_type, F>( lock, boost::move(*this), boost::forward<F>(func) ); } else if (int(this->launch_policy(lock)) & int(launch::deferred)) { this->future_->wait_internal(lock); return boost::detail::make_future_deferred_continuation_shared_state<shared_future<R>, future_type, F>( lock, boost::move(*this), boost::forward<F>(func) ); } else { //BOOST_THREAD_ASSERT_PRECONDITION(false && "invalid launch parameter", std::logic_error("invalid launch parameter")); return boost::detail::make_future_async_continuation_shared_state<shared_future<R>, future_type, F>( lock, boost::move(*this), boost::forward<F>(func) ); } } namespace detail { template <typename T> struct mfallbacker_to { T value_; typedef T result_type; mfallbacker_to(BOOST_THREAD_RV_REF(T) v) : value_(boost::move(v)) {} T operator()(BOOST_THREAD_FUTURE<T> fut) { return fut.get_or(boost::move(value_)); } }; template <typename T> struct cfallbacker_to { T value_; typedef T result_type; cfallbacker_to(T const& v) : value_(v) {} T operator()(BOOST_THREAD_FUTURE<T> fut) { return fut.get_or(value_); } }; } //////////////////////////////// // future<R> future<R>::fallback_to(R&& v); //////////////////////////////// template <typename R> template <typename R2> inline typename disable_if< is_void<R2>, BOOST_THREAD_FUTURE<R> >::type BOOST_THREAD_FUTURE<R>::fallback_to(BOOST_THREAD_RV_REF(R2) v) { return then(detail::mfallbacker_to<R>(boost::move(v))); } template <typename R> template <typename R2> inline typename disable_if< is_void<R2>, BOOST_THREAD_FUTURE<R> >::type BOOST_THREAD_FUTURE<R>::fallback_to(R2 const& v) { return then(detail::cfallbacker_to<R>(v)); } #endif #if defined BOOST_THREAD_PROVIDES_FUTURE_UNWRAP namespace detail { ///////////////////////// /// future_unwrap_shared_state ///////////////////////// template<typename F, typename Rp> struct future_unwrap_shared_state: shared_state<Rp> { F parent; public: explicit future_unwrap_shared_state( BOOST_THREAD_RV_REF(F) f ) : parent(boost::move(f)) { } virtual void wait(bool ) // todo see if rethrow must be used { boost::unique_lock<boost::mutex> lock(mutex); parent.get().wait(); } virtual Rp get() { boost::unique_lock<boost::mutex> lock(mutex); return parent.get().get(); } }; template <class F, class Rp> BOOST_THREAD_FUTURE<Rp> make_future_unwrap_shared_state(boost::unique_lock<boost::mutex> &lock, BOOST_THREAD_RV_REF(F) f) { shared_ptr<future_unwrap_shared_state<F, Rp> > //shared_ptr<basic_future<Rp> > //typename boost::detail::basic_future<Rp>::future_ptr h(new future_unwrap_shared_state<F, Rp>(boost::move(f))); h->parent.future_->set_continuation_ptr(h, lock); return BOOST_THREAD_FUTURE<Rp>(h); } } template <typename R> inline BOOST_THREAD_FUTURE<R>::BOOST_THREAD_FUTURE(BOOST_THREAD_RV_REF(BOOST_THREAD_FUTURE<BOOST_THREAD_FUTURE<R> >) other): base_type(other.unwrap()) { } template <typename R2> BOOST_THREAD_FUTURE<R2> BOOST_THREAD_FUTURE<BOOST_THREAD_FUTURE<R2> >::unwrap() { BOOST_THREAD_ASSERT_PRECONDITION(this->future_!=0, future_uninitialized()); boost::unique_lock<boost::mutex> lock(this->future_->mutex); return boost::detail::make_future_unwrap_shared_state<BOOST_THREAD_FUTURE<BOOST_THREAD_FUTURE<R2> >, R2>(lock, boost::move(*this)); } #endif } #endif // BOOST_NO_EXCEPTION #endif // header
mit
mbasso/refraction
examples/buildAll.js
783
import fs from 'fs'; import path from 'path'; import { spawnSync } from 'child_process'; const exampleDirs = fs.readdirSync(__dirname).filter((file) => ( fs.statSync(path.join(__dirname, file)).isDirectory() )); const cmdArgs = [ { cmd: 'npm', args: ['install'] }, { cmd: 'webpack', args: ['index.js'] }, ]; for (const dir of exampleDirs) { for (const cmdArg of cmdArgs) { const opts = { cwd: path.join(__dirname, dir), stdio: 'inherit', }; let result = {}; if (process.platform === 'win32') { result = spawnSync(`${cmdArg.cmd}.cmd`, cmdArg.args, opts); } else { result = spawnSync(cmdArg.cmd, cmdArg.args, opts); } if (result.status !== 0) { throw new Error('Building examples exited with non-zero'); } } }
mit
vntarasov/openpilot
selfdrive/modeld/constants.py
91
MAX_DISTANCE = 140. LANE_OFFSET = 1.8 MAX_REL_V = 10. LEAD_X_SCALE = 10 LEAD_Y_SCALE = 10
mit
fgrid/iso20022
RejectionOrRepairReason9.go
689
package iso20022 // Reason for the rejection or repair status. type RejectionOrRepairReason9 struct { // Specifies the reason why the instruction/request has a rejected or repair status. Code *RejectionAndRepairReason9Choice `xml:"Cd"` // Provides additional reason information that cannot be provided in a structured field. AdditionalReasonInformation *Max210Text `xml:"AddtlRsnInf,omitempty"` } func (r *RejectionOrRepairReason9) AddCode() *RejectionAndRepairReason9Choice { r.Code = new(RejectionAndRepairReason9Choice) return r.Code } func (r *RejectionOrRepairReason9) SetAdditionalReasonInformation(value string) { r.AdditionalReasonInformation = (*Max210Text)(&value) }
mit
shpuld/ShpuldAdventure
main_english.py
39004
#Tuomas Kaukoranta - 233733 #TIE-02100 - Johdatus ohjelmointiin #Harjoitustyö 2 #4.6.2014 #Shpuld's Adventure #Ohjeet: #Tehtävänäsi on päästä niin syvälle kuin mahdollista luolastossa ja kerätä #paljon pisteitä. #Liikuta hahmoasi klikkaamalla siihen suuntaan ruudulla, minne haluat liikkua. #Voit myös käyttää nuolinäppäimiä liikkumiseen ja välilyöntiä odottamiseen. #Taistele vihollisten kanssa liikkumalla niitä kohti ollessasi niiden #viereisellä ruudulla. Huomaa, että vihollinen voi myös lyödä sinua tällöin. #Kun elämäpisteesi loppuvat, peli päättyy ja voit aloittaa uuden pelin #uudessa luolastossa. #Löydät hyödyllisiä esineitä luolasta, kuten kilpiä, miekkoja ja taikajuomia. #Poimimalla kilven tai miekan, puolustus- tai hyökkäysarvosi nousee. #Taikajuoma taas nostaa elämäpisteesi takaisin maksimiin. #Tuhoamalla vihollisia kartutat kokemusta, joka taas nostattaa tasoasi. Kun #tasosi nousee, elämäpisteiden maksimi ja hyökkäys- sekä puolustusarvot #nousevat. #Melkein kaikista näistä toiminnoista, sekä seuraavaan kerrokseen #siirtymisestä (tikkaat alas) kartutat pisteitä, joilla voit päästä pelin #top-10-listalle. from tkinter import * from random import randint canvas_width = 480 canvas_height = 480 map_size_x = 32 map_size_y = 32 view_size_x = 7 view_size_y = 7 turn = 0 waiting = 0 floor = 1 drawprompt = 0 gameoverprompt = 0 class room: def __init__(self, x, y, w, h): self.x = x self.y = y self.w = w self.h = h #rooms.append(self) class player: def __init__(self): self.x = 0 self.y = 0 self.dead = 0 self.lvl = 1 self.hp = 20 self.maxhp = 20 self.xp = 0 self.nextlvl = 25 self.attack = 5 self.defense = 5 self.classname = "Player" self.isplayer = 1 self.points = 0 self.rank = -1 self.text = "" self.textcolor = "white" class mob: def __init__(self, x, y, type): self.x = x self.y = y self.dead = 0 self.isplayer = 0 self.alerted = 0 self.text = "" self.textcolor = "white" if type == "slime": self.img = img_slime self.hp = 10 self.attack = 4 self.defense = 4 self.target = 0 self.classname = "Slime" elif type == "skeleton": self.img = img_skeleton self.hp = 15 self.attack = 9 self.defense = 9 self.target = 0 self.classname = "Skeleton" elif type == "troll": self.img = img_troll self.hp = 20 self.attack = 15 self.defense = 15 self.target = 0 self.classname = "Troll" elif type == "demon": self.img = img_demon self.hp = 25 self.attack = 20 self.defense = 20 self.target = 0 self.classname = "Demon" else: print("invalid monster type") return def think(self): if self.alerted == 0: if randint(0,4) == 0: #wander dir = randint(0,3) if dir == 0: dir = "N" elif dir == 1: dir = "E" elif dir == 2: dir = "S" else: dir = "W" move(self,dir) if abs(self.x - player.x) > 3 or abs(self.y - player.y) > 3: return vis = isvisible(self.x,self.y,player.x,player.y) if vis == 1: self.alerted = 1 self.text = "!" self.textcolor = "white" else: ignorex = ignorey = 0 if player.x == self.x: ignorex = 1 elif player.y == self.y: ignorey = 1 asd = randint(0,1) moved = 0 if asd == 0 or ignorex == 1 and ignorey != 1: triedx = 0 if player.y < self.y: moved = move(self, "N") else: moved = move(self, "S") else: triedx = 1 if player.x < self.x: moved = move(self, "W") else: moved = move(self, "E") if moved == 0: if triedx == 1: if player.y < self.y: move(self, "N") else: move(self, "S") else: if player.x < self.x: move(self, "W") else: move(self, "E") class entity: def __init__(self,x,y,type): self.x = x self.y = y self.type = type if type == "ladder_up": self.img = img_ladder_up elif type == "ladder_down": self.img = img_ladder_down elif type == "shield": self.img = img_shield elif type == "sword": self.img = img_sword elif type == "potion": self.img = img_potion def touch(self, toucher): if self.type == "ladder_down": prompt_new_floor() elif self.type == "shield": ents.remove(self) toucher.defense += 1 toucher.points += 20 elif self.type == "sword": ents.remove(self) toucher.attack += 1 toucher.points += 20 elif self.type == "potion": ents.remove(self) toucher.hp = toucher.maxhp toucher.points += 20 def isvisible(xs,ys,xe,ye): dx = abs(xs - xe) dy = abs(ys - ye) if xs < xe: sx = 1 else: sx = -1 if ys < ye: sy = 1 else: sy = -1 err = dx-dy end = 0 while end == 0: cell = get_cell(xs,ys) #set_cell(xs,ys,"debug") if cell == "wall" or cell == "empty": return 0 if xs == xe and ys == ye: end = 1 return 1 e2 = 2 * err if e2 > dy * -1: err = err - dy xs = xs + sx if e2 < dx: err = err + dx ys = ys + sy def get_cell( x, y): if x < 0 or x >= map_size_x or y < 0 or y >= map_size_y: return "empty" return dmap[x + (y * map_size_y)] def set_cell( x, y, type): global dmap dmap[x + (y * map_size_y)] = type def make_room( x, y, w, h): #testaa pystyykö kaivamaan huoneen for tempx in range(x-1, x+w+1): if tempx < 0 or tempx >= map_size_x: return -1 for tempy in range(y-1, y+h+1): if tempy < 0 or tempy >= map_size_y: return -1 if get_cell(tempx, tempy) == "ground" or \ get_cell(tempx, tempy) == "floor" or \ get_cell(tempx, tempy) == "empty": return -1 #pystyy: kaivetaan huone for tempx in range(x,x+w): for tempy in range(y,y+h): set_cell(tempx,tempy,"floor") rooms.append(room(x,y,w,h)) return len(rooms) def make_tunnelroom(index): #tarkista voiko rakentaa tunnelin, jos y, kokeile rakentaa huone #jos molemmat onnistuu, toteutetaan #print(index) dira = randint(0,3) dirb = 1 - randint(0,1) #dira = 3 if dirb == 0: dirb = -1 xlen = randint(2,3) ylen = randint(2,3) rh = randint(3,5) rw = randint(3,5) if dira == 0: #tunneli lähtee ylös y = rooms[index].y x = rooms[index].x + randint(0,rooms[index].w-1) for ytemp in range(y-ylen-1, y+1): for xtemp in range(x-1,x+2): if get_cell(xtemp, ytemp) == "floor" and ytemp != y or \ get_cell(xtemp, ytemp) == "empty": #print("1") return 0 if dirb == -1: #kääntyy vasemmalle for xtemp in range(x-xlen+1, x+1): for ytemp in range(y-ylen-1,y-ylen+1): if get_cell(xtemp,ytemp) == "floor" or \ get_cell(xtemp,ytemp) == "ground" or \ get_cell(xtemp,ytemp) == "empty": #print("2:" + str(xtemp) + "," + str(ytemp)) #print(ylen) return 0 rx = x-xlen+1-rw else: #kääntyy oikealle for xtemp in range(x,x+xlen): for ytemp in range(y-ylen-1,y-ylen+1): if get_cell(xtemp,ytemp) == "floor" or \ get_cell(xtemp,ytemp) == "ground" or \ get_cell(xtemp,ytemp) == "empty": #set_cell(xtemp,ytemp,"debug") #set_cell(xtemp,y-ylen-1,"debug") #print("3:" + str(xtemp) + "," + str(ytemp)) #print(ylen) return 0 rx = x+xlen ry = y-ylen-randint(0,rh-1) #yritä rakentaa huone tunnelin päähän if make_room(rx,ry,rw,rh) != -1: for ytemp in range(y-ylen+1,y): set_cell(x,ytemp,"ground") if dirb == -1: for xtemp in range(x-xlen+1,x+1): set_cell(xtemp,y-ylen,"ground") else: for xtemp in range(x,x+xlen): set_cell(xtemp,y-ylen,"ground") elif dira == 1: #tunneli lähtee oikealle y = rooms[index].y + randint(0,rooms[index].h-1) x = rooms[index].x + rooms[index].w-1 for xtemp in range(x, x+xlen+2): for ytemp in range(y-1,y+2): if get_cell(xtemp, ytemp) == "floor" and xtemp != x: #print("1") return 0 if dirb == -1: #kääntyy ylös for ytemp in range(y-ylen+1, y+1): #set_cell(x,y,"debug") for ytemp in range(x-xlen-1,x-xlen+1): if get_cell(xtemp,ytemp) == "floor" or \ get_cell(xtemp,ytemp) == "ground" or \ get_cell(xtemp,ytemp) == "empty": #print("2:" + str(xtemp) + "," + str(ytemp)) #print(ylen) return 0 ry = y-ylen+1-rh else: #kääntyy alas for ytemp in range(y,y+ylen): #set_cell(x,y,"debug") for xtemp in range(x+xlen-1,x-xlen+1): if get_cell(xtemp,ytemp) == "floor" or \ get_cell(xtemp,ytemp) == "ground" or \ get_cell(xtemp,ytemp) == "empty": #set_cell(xtemp,ytemp,"debug") #set_cell(x,y,"debug") #print("3:" + str(xtemp) + "," + str(ytemp)) #print(ylen) return 0 ry = y+ylen rx = x+xlen-randint(0,rw-1) #yritä rakentaa huone tunnelin päähän if make_room(rx,ry,rw,rh) != -1: for xtemp in range(x+1,x+xlen): set_cell(xtemp,y,"ground") if dirb == -1: for ytemp in range(y-ylen+1,y+1): set_cell(x+xlen,ytemp,"ground") else: for ytemp in range(y,y+ylen): set_cell(x+xlen,ytemp,"ground") #else: # print("room failed") if dira == 2: #tunneli lähtee alas y = rooms[index].y + rooms[index].h-1 x = rooms[index].x + randint(0,rooms[index].w-1) for ytemp in range(y, y+ylen+2): for xtemp in range(x-1,x+2): if get_cell(xtemp, ytemp) == "floor" and ytemp != y: #print("1") return 0 if dirb == -1: #kääntyy vasemmalle for xtemp in range(x-xlen+1, x+1): for ytemp in range(y+ylen-1,y+ylen+2): if get_cell(xtemp,ytemp) == "floor" or \ get_cell(xtemp,ytemp) == "ground" or \ get_cell(xtemp,ytemp) == "empty": #print("2:" + str(xtemp) + "," + str(ytemp)) #print(ylen) return 0 rx = x-xlen+1-rw else: #kääntyy oikealle for xtemp in range(x,x+xlen): for ytemp in range(y+ylen-1,y+ylen+2): if get_cell(xtemp,ytemp) == "floor" or \ get_cell(xtemp,ytemp) == "ground" or \ get_cell(xtemp,ytemp) == "empty": #set_cell(xtemp,ytemp,"debug") #set_cell(xtemp,y-ylen-1,"debug") #print("3:" + str(xtemp) + "," + str(ytemp)) #print(ylen) return 0 rx = x+xlen ry = y+ylen-randint(0,rh-1) #yritä rakentaa huone tunnelin päähän if make_room(rx,ry,rw,rh) != -1: for ytemp in range(y+1,y+ylen): set_cell(x,ytemp,"ground") if dirb == -1: for xtemp in range(x-xlen+1,x+1): set_cell(xtemp,y+ylen,"ground") else: for xtemp in range(x,x+xlen): set_cell(xtemp,y+ylen,"ground") elif dira == 3: #tunneli lähtee vasemmalle y = rooms[index].y + randint(0,rooms[index].h-1) x = rooms[index].x for xtemp in range(x-xlen-1, x+1): for ytemp in range(y-1,y+2): if get_cell(xtemp, ytemp) == "floor" and xtemp != x: #print("1") return 0 if dirb == -1: #kääntyy ylös for ytemp in range(y, y-ylen+1): #set_cell(x,y,"debug") for ytemp in range(x-xlen-1,x-xlen+1): if get_cell(xtemp,ytemp) == "floor" or \ get_cell(xtemp,ytemp) == "ground" or \ get_cell(xtemp,ytemp) == "empty": #print("2:" + str(xtemp) + "," + str(ytemp)) #print(ylen) return 0 ry = y-ylen+1-rh else: #kääntyy alas for ytemp in range(y,y+ylen): #set_cell(x,y,"debug") for xtemp in range(x+xlen-1,x-xlen+1): if get_cell(xtemp,ytemp) == "floor" or \ get_cell(xtemp,ytemp) == "ground" or \ get_cell(xtemp,ytemp) == "empty": #set_cell(xtemp,ytemp,"debug") #set_cell(x,y,"debug") #print("3:" + str(xtemp) + "," + str(ytemp)) #print(ylen) return 0 ry = y+ylen rx = x-xlen-randint(0,rw-1) #yritä rakentaa huone tunnelin päähän if make_room(rx,ry,rw,rh) != -1: for xtemp in range(x-xlen+1,x): set_cell(xtemp,y,"ground") if dirb == -1: for ytemp in range(y-ylen+1,y+1): set_cell(x-xlen,ytemp,"ground") else: for ytemp in range(y,y+ylen): set_cell(x-xlen,ytemp,"ground") def random_carve(): x = randint(0,map_size_x-1) y = randint(0,map_size_y-1) while get_cell(x,y) != "ground": x = randint(0,map_size_x-1) y = randint(0,map_size_y-1) dir = randint(0,3) len = 1 + randint(1,6) while len > 0: if x < 1 or x >= map_size_x - 1 or y < 1 or y >= map_size_y-1: return if dir == 0: if get_cell(x,y-1) == "floor": return else: set_cell(x,y,"ground") y -= 1 if randint(0,4) == 4: dir = randint(0,3) elif dir == 1: if get_cell(x+1,y) == "floor": return else: set_cell(x,y,"ground") x += 1 if randint(0,4) == 4: dir = randint(0,3) elif dir == 2: if get_cell(x,y+1) == "floor": return else: set_cell(x,y,"ground") y += 1 if randint(0,4) == 4: dir = randint(0,3) elif dir == 3: if get_cell(x-1,y) == "floor": return else: set_cell(x,y,"ground") x -= 1 if randint(0,4) == 4: dir = randint(0,3) len -= 1 def generate_dungeon(): global dmap for x in range(0,map_size_x): for y in range(0,map_size_y): dmap.append("wall") make_room(12,12,4,4) count = 0 while count < 200: count += 1 make_tunnelroom(randint(0,len(rooms) - 1)) count = 0 while count < 0: count += 1 random_carve() def place_entities(): #place ladders downroom = randint(0,len(rooms) - 1) uproom = randint(0,len(rooms) - 1) while uproom == downroom: uproom = randint(0,len(rooms) - 1) x = randint(rooms[uproom].x, rooms[uproom].x + rooms[uproom].w-1) y = randint(rooms[uproom].y, rooms[uproom].y + rooms[uproom].h-1) ents.append(entity(x,y,"ladder_up")) x = randint(rooms[downroom].x, rooms[downroom].x + rooms[downroom].w-1) y = randint(rooms[downroom].y, rooms[downroom].y + rooms[downroom].h-1) ents.append(entity(x,y,"ladder_down")) for inst in rooms: rand = randint(0,8) type = "" if rand == 0: type = "shield" elif rand == 1: type = "sword" elif rand == 2: type = "potion" if type != "": x = randint(inst.x, inst.x + inst.w-1) y = randint(inst.y, inst.y + inst.h-1) while x == ents[0].x and y == ents[0].y: x = randint(inst.x, inst.x + inst.w-1) y = randint(inst.y, inst.y + inst.h-1) ents.append(entity(x,y,type)) def place_mobs(): global floor if floor < 3: maxmobs = 6 elif floor < 6: maxmobs = 10 else: maxmobs = 15 while len(mobs) < maxmobs: cancel = 0 x = randint(1,map_size_x-1) y = randint(1,map_size_y-1) if get_cell(x,y) == "ground": if abs(ents[0].x - x) > 4 and abs(ents[0].y - y) > 4: for other in mobs: if other.x == x and other.y == y: cancel = 1 if cancel == 0: if floor <= 1: mobs.append(mob(x,y,"slime")) elif floor <= 3: rand = randint(0,9) if rand > 5: mobs.append(mob(x,y,"skeleton")) else: mobs.append(mob(x,y,"slime")) elif floor <= 6: rand = randint(0,9) if rand > 7: mobs.append(mob(x,y,"troll")) elif rand > 3: mobs.append(mob(x,y,"skeleton")) else: mobs.append(mob(x,y,"slime")) elif floor <= 9: rand = randint(0,9) if rand > 7: mobs.append(mob(x,y,"demon")) elif rand > 5: mobs.append(mob(x,y,"troll")) elif rand > 2: mobs.append(mob(x,y,"skeleton")) else: mobs.append(mob(x,y,"slime")) else: rand = randint(0,9) if rand > 6: mobs.append(mob(x,y,"demon")) elif rand > 4: mobs.append(mob(x,y,"troll")) elif rand > 1: mobs.append(mob(x,y,"skeleton")) else: mobs.append(mob(x,y,"slime")) def disableprompt(): global drawprompt drawprompt = 0 nextfloorbutton.destroy() cancelnextbutton.destroy() draw_screen() def prompt_new_floor(): global drawprompt global nextfloorbutton global cancelnextbutton drawprompt = 1 nextfloorbutton = Button(text="Kyllä",command=new_floor) cancelnextbutton = Button(text="Ei",command=disableprompt) nextfloorbutton.place(x=184,y=216,width=100,anchor=CENTER) cancelnextbutton.place(x=296,y=216,width=100,anchor=CENTER) def new_floor(): global floor global drawprompt drawprompt = 0 nextfloorbutton.destroy() cancelnextbutton.destroy() dmap.clear() rooms.clear() ents.clear() mobs.clear() generate_dungeon() place_entities() player.x = ents[0].x player.y = ents[0].y place_mobs() draw_screen() player.points += floor*100 floor += 1 def move(obj, dir): oldx = obj.x oldy = obj.y if dir == "E": obj.x += 1 elif dir == "W": obj.x -= 1 elif dir == "S": obj.y += 1 else: obj.y -= 1 if get_cell(obj.x,obj.y) == "wall" or get_cell(obj.x,obj.y) == "empty": obj.x = oldx obj.y = oldy return 0 else: if obj.isplayer == 1: for dude in mobs: if dude.x == obj.x and dude.y == obj.y: combat(obj, dude) obj.x = oldx obj.y = oldy return 2 for ent in ents: if ent.x == obj.x and ent.y == obj.y: ent.touch(obj) return 1 else: for dude in mobs: if dude.x == obj.x and dude.y == obj.y and dude != obj: obj.x = oldx obj.y = oldy return 0 if obj.x == player.x and obj.y == player.y: obj.x = oldx obj.y = oldy combat(obj, player) return 2 return 1 def clean_up(): global healthlabel global lvllabel global xplabel global atklabel global deflabel global timerlabel global ptslabel global waitbutton global canvas global player global ents global mobs global dmap global rooms healthlabel.destroy() lvllabel.destroy() xplabel.destroy() atklabel.destroy() deflabel.destroy() timerlabel.destroy() ptslabel.destroy() waitbutton.destroy() canvas.destroy() del ents del mobs del dmap del rooms def submit_highscore(): global nameentry global hiscores global floor global okbutton name = nameentry.get() hiscores.insert(player.rank-1,score(name,str(player.lvl),str(floor), str(player.points) + "\n", str(player .rank))) del hiscores[10] fo = open("hiscores.txt", "w") string = "" for line in hiscores: string += line.name+" "+line.level+" "+line.floor+" "+line.points #print(string) fo.write(string) nameentry.destroy() okbutton.destroy() clean_up() main_menu() def gametomain_menu(): global okbutton clean_up() okbutton.destroy() main_menu() def kill(victim): victim.dead = 1 if victim.isplayer == 1: global okbutton global gameoverprompt global nameentry global hiscores global drawprompt drawprompt = 0 read_highscores() rank = 1 for hs in hiscores: if victim.points > int(hs.points): gameoverprompt = 2 #print("2") nameentry = Entry(master) nameentry.place(x=240,y=210,width=200,anchor=CENTER) okbutton = Button(text="Ok",command=submit_highscore) okbutton.place(x=240,y=240,width=100,anchor=CENTER) player.rank = rank return rank += 1 #print("1") gameoverprompt = 1 okbutton = Button(text="Ok",command=gametomain_menu) okbutton.place(x=240,y=216,width=100,anchor=CENTER) def combat(attacker, victim): dmg = attacker.attack - randint(0,victim.defense) if dmg <= 0: dmg = 0 victim.text = "Miss" victim.textcolor = "white" else: victim.hp -= dmg victim.text = dmg victim.textcolor = "red" if victim.hp <= 0: if attacker.isplayer == 1: attacker.xp += randint(victim.defense - 2, victim.defense + 2) attacker.points += victim.defense * 3 if attacker.xp > attacker.nextlvl: attacker.xp = 0 attacker.lvl += 1 attacker.maxhp += randint(2,4) attacker.hp = attacker.maxhp attacker.nextlvl += 25 attacker.attack += 1 attacker.defense += 1 attacker.points += attacker.lvl * 25 kill(victim) def click(event): absx = abs(event.x - 240) absy = abs(event.y - 240) if absx > absy: if event.x > 240: dir = "E" else: dir = "W" else: if event.y > 240: dir = "S" else: dir = "N" action(dir) def up_key(event): action("N") def down_key(event): action("S") def left_key(event): action("W") def right_key(event): action("E") def action(dir): global player global turn if player.dead == 1: return incturn = 0 player.collider = 0 if waiting == 1: return else: delay_label(timerlabel) asd = move(player,dir) if asd == 1: incturn = 1 elif asd == 2: incturn = 1 if incturn == 1: turn += 1 for inst in mobs: if inst.dead == 1: mobs.remove(inst) else: inst.think() draw_screen() def spacebar(event): wait_turn() def wait_turn(): global turn if player.dead == 1: return turn += 1 if waiting == 1: return else: delay_label(timerlabel) for inst in mobs: if inst.dead == 1: mobs.remove(inst) else: inst.think() draw_screen() def draw_screen(): global player canvas.delete(ALL) scr_x = 0 for x in range(player.x - view_size_x, player.x + view_size_x+1): scr_y = 0 for y in range(player.y - view_size_y,player.y + view_size_y+1): if (x >= 0) and (y >= 0) and x < map_size_x and y < map_size_y: if get_cell(x, y) == "ground": img = img_ground elif get_cell(x, y) == "floor": img = img_floor elif get_cell(x, y) == "debug": img = img_debug elif get_cell(x, y) == "wall": if y + 1 < map_size_y: if get_cell(x, y + 1) != "wall": img = img_wall_bottom else: img = img_wall else: img = img_wall else: img = img_wall #if scr_x == view_size_x and scr_y == view_size_y : # img = img_player canvas.create_image(scr_x*32, scr_y*32,anchor=NW, image=img) else: canvas.create_image(scr_x*32, scr_y*32,anchor=NW, image=img_wall) scr_y += 1 scr_x += 1 for ent in ents: if abs(ent.x - player.x) < view_size_x+1: if abs(ent.y - player.y) < view_size_y+1: canvas.create_image((ent.x - player.x + view_size_x)*32, (ent.y - player.y + view_size_y)*32, anchor=NW, image=ent.img) for dude in mobs: if abs(dude.x - player.x) < view_size_x+1: if abs(dude.y - player.y) < view_size_y+1: canvas.create_image((dude.x - player.x + view_size_x)*32, (dude.y - player.y + view_size_y)*32, anchor=NW, image=dude.img) if dude.text != "": canvas.create_text((dude.x - player.x + view_size_x)*32 + 17, (dude.y - player.y + view_size_y)*32 + 7, text=dude.text,fill = "black") canvas.create_text((dude.x - player.x + view_size_x)*32 + 16, (dude.y - player.y + view_size_y)*32 + 6, text=dude.text,fill = dude.textcolor) dude.text = "" canvas.create_image(view_size_x*32, view_size_y*32, anchor=NW, image=img_player) if player.text != "": canvas.create_text(view_size_x*32 + 17, view_size_y*32 + 7, text=player.text,fill = "black") canvas.create_text(view_size_x*32 + 16, view_size_y*32 + 6, text=player.text,fill = player.textcolor) player.text = "" if drawprompt == 1: canvas.create_rectangle(120,180,360,240,fill="gray") canvas.create_text(240,188,text="Do you want to progress to the next " "floor?",anchor=CENTER) elif gameoverprompt == 1: canvas.create_rectangle(120,180,360,236,fill="gray") canvas.create_text(240,188,text="Game over, you didn't make it to" "top-10.",anchor=CENTER) elif gameoverprompt == 2: canvas.create_rectangle(110,180,370,260,fill="gray") canvas.create_text(240,188,text="Game over, you made it to top-10!" "Enter your name:",anchor=CENTER) lvllabel.config(text="LVL: " + str(player.lvl)) healthlabel.config(text="HP: " + str(player.hp) + "/" + str(player.maxhp)) xplabel.config(text="EXP: " + str(player.xp) + "/" + str(player.nextlvl)) atklabel.config(text="ATK: " + str(player.attack)) deflabel.config(text="DEF: " + str(player.defense)) ptslabel.config(text="Score: " + str(player.points)) def delay_label(label): def done(): global waiting label.config(text="") waiting = 0 def wait(): global waiting waiting = 1 label.config(text="") label.after(100, done) wait() master = Tk() master.title("Shpuld's Adventure") master.minsize(640,480) master.maxsize(640,480) img_wall = PhotoImage(file="assets/wall.gif") img_wall_bottom = PhotoImage(file="assets/wall_bottom.gif") img_ground = PhotoImage(file="assets/ground.gif") img_floor = PhotoImage(file="assets/floor.gif") img_player = PhotoImage(file="assets/player.gif") img_debug = PhotoImage(file="assets/wall_debug.gif") img_slime = PhotoImage(file="assets/slime.gif") img_skeleton = PhotoImage(file="assets/skeleton.gif") img_troll = PhotoImage(file="assets/troll.gif") img_demon = PhotoImage(file="assets/demon.gif") img_ladder_down = PhotoImage(file="assets/ladder_down.gif") img_ladder_up = PhotoImage(file="assets/ladder_up.gif") img_shield = PhotoImage(file="assets/shield.gif") img_sword = PhotoImage(file="assets/sword.gif") img_potion = PhotoImage(file="assets/potion.gif") img_bg = PhotoImage(file="assets/bg.gif") def scorestomain_menu(): menubutton.destroy() hslabel.destroy() main_menu() def display_scores(): menucanv.destroy() startbutton.destroy() hsbutton.destroy() infobutton.destroy() quitbutton.destroy() read_highscores() string = "Name/Level/Floor/Score\n\n" for scores in hiscores: #print(scores.name) #print(scores.level) string += str(scores.rank) + ". " + str(scores.name) + " / " + \ str(scores.level) + " / " + str(scores.floor) + " / " + \ str(scores.points) + "\n" global hslabel hslabel = Label(master, text=string) hslabel.place(x=320, y=240, anchor=CENTER) global menubutton menubutton = Button(master, text="Back", command=scorestomain_menu) menubutton.place(x=320, y=460, anchor=CENTER) def display_info(): menucanv.destroy() startbutton.destroy() hsbutton.destroy() infobutton.destroy() quitbutton.destroy() string = "Ohjeet:\n\n" \ "Tehtävänäsi on päästä niin syvälle kuin " \ "mahdollista luolastossa ja kerätä paljon " \ "pisteitä.\n\n" \ "Liikuta hahmoasi klikkaamalla siihen suuntaan ruudulla, " \ "minne haluat liikkua.\n" \ "Voit myös käyttää nuolinäppäimiä liikkumiseen ja välilyöntiä " \ "odottamiseen.\n\n" \ "Taistele vihollisten kanssa liikkumalla niitä kohti ollessasi " \ "niiden viereisellä ruudulla.\n" \ "Huomaa, että vihollinen voi myös lyödä sinua tällöin. Kun " \ "elämäpisteesi loppuvat, \n" \ "peli päättyy ja voit aloittaa uuden pelin uudessa luolastossa" \ ".\n\n" \ "Löydät hyödyllisiä esineitä luolasta, kuten kilpiä, miekkoja " \ "ja taikajuomia. \n" \ "Poimimalla kilven tai miekan, puolustus- tai hyökkäysarvosi " \ "nousee. \n" \ "Taikajuoma taas nostaa elämäpisteesi takaisin maksimiin. \n\n" \ "Tuhoamalla vihollisia kartutat kokemusta, joka taas nostattaa " \ "tasoasi.\n" \ "Kun tasosi nousee, elämäpisteiden maksimi ja hyökkäys- sekä " \ "puolustusarvot nousevat. \n\n" \ "Melkein kaikista näistä toiminnoista, sekä seuraavaan " \ "kerrokseen " \ "siirtymisestä (tikkaat alas)\n" \ "kartutat pisteitä, joilla voit päästä pelin top-10-listalle." global hslabel hslabel = Label(master, text=string) hslabel.place(x=320, y=240, anchor=CENTER) global menubutton menubutton = Button(master, text="Back", command=scorestomain_menu) menubutton.place(x=320, y=460, anchor=CENTER) def quit(): master.destroy() def main_menu(): global menucanv global startbutton global hsbutton global infobutton global quitbutton global drawprompt global gameoverprompt drawprompt = 0 gameoverprompt = 0 menucanv = Canvas(master, width=640, height=480) menucanv.create_image(0,0,anchor=NW,image=img_bg) menucanv.place(x=0,y=0,width=640,height=480) startbutton = Button(master, text="New game", command=start_game) startbutton.place(x=80,y=280,width=120,height=24,anchor=CENTER) hsbutton = Button(master, text="Highscores", command=display_scores) hsbutton.place(x=80,y=306,width=120,height=24,anchor=CENTER) infobutton = Button(master, text="Info (finnish)", command=display_info) infobutton.place(x=80,y=332,width=120,height=24,anchor=CENTER) quitbutton = Button(master, text="Quit", command=quit) quitbutton.place(x=80,y=358,width=120,height=24,anchor=CENTER) def start_game(): global player global healthlabel global lvllabel global xplabel global atklabel global deflabel global canvas global timerlabel global ptslabel global waitbutton global dmap global rooms global mobs global ents dmap = [] rooms = [] mobs = [] ents = [] menucanv.destroy() startbutton.destroy() hsbutton.destroy() infobutton.destroy() quitbutton.destroy() generate_dungeon() place_entities() player.x = ents[0].x player.y = ents[0].y player.dead = 0 player.lvl = 1 player.hp = 20 player.maxhp = 20 player.xp = 0 player.nextlvl = 25 player.attack = 5 player.defense = 5 player.classname = "Player" player.isplayer = 1 player.points = 0 player.rank = -1 player.text = "" player.textcolor = "white" canvas = Canvas(master, width=canvas_width, height=canvas_height) canvas.place(x=0, y=0, width=480, height=480, anchor=NW) master.bind("<Left>", left_key) master.bind("<Right>", right_key) master.bind("<Up>", up_key) master.bind("<Down>", down_key) master.bind("<space>", spacebar) canvas.bind("<Button-1>", click) healthlabel = Label(master, text="HP: " + str(player.hp) + "/" + str(player.maxhp)) healthlabel.place(x=480, y=0) lvllabel = Label(master, text="LVL: " + str(player.lvl)) lvllabel.place(x=480, y=36) xplabel = Label(master, text="EXP: " + str(player.xp) + "/" + str(player.nextlvl)) xplabel.place(x=480, y=54) atklabel = Label(master, text="ATK: " + str(player.attack)) atklabel.place(x=480, y=90) deflabel = Label(master, text="DEF: " + str(player.defense)) deflabel.place(x=480, y=108) ptslabel = Label(master, text="Score: " + str(player.points)) ptslabel.place(x=480, y=144) timerlabel = Label(master, fg="black") timerlabel.place(x=640, y=480) waitbutton = Button(master, text="Wait a turn", command=wait_turn) waitbutton.place(x=560, y=464, width=158, anchor=CENTER) place_mobs() scr_x = 0 scr_y = 0 draw_screen() class score: def __init__(self, name, level, floor, points, rank): self.name = name self.level = level self.floor = floor self.points = points self.rank = rank def read_highscores(): global hiscores hsfile = open("hiscores.txt","r") hiscores = [] tmp = [] rank = 1 for line in hsfile: #print(line) tmp = line.split(" ") #print(tmp[0]) hiscores.append(score(tmp[0],tmp[1],tmp[2],tmp[3],rank)) rank += 1 main_menu() player = player() mainloop()
mit
djforth/ajax-es6-fp
src/destroy.js
866
import add_id from './add_id'; import addMethod from './add_method'; import addHeaders from './manage_headers'; import getCSRF from './get_CSRF'; import createPromise from './create_promise'; import xhrRequest from './set_request'; export default function(url, rails = true){ // let csrf, data_set, headers, promise, xhr, url_id; const csrf = getCSRF(); const headers = addHeaders(); headers.addCSRF(csrf.token); const url_id = add_id(url); const data_set = addMethod(csrf, 'delete'); if (rails){ headers.addRails(); } const promise = createPromise(); const xhr = xhrRequest(promise.resolve, promise.reject); return function(id, data){ let api = (id) ? url_id(id) : url; xhr.open('DELETE', api); // data[csrf.param] = csrf.token; headers.set(xhr.get()); xhr.send(data_set(data)); return promise.promise; }; };
mit
chrisclarke1977/nuclear-js
docs/grunt/build-site.js
3313
var mkdirp = require("mkdirp") var path = require('path'); var glob = require('glob') var async = require('async') var fm = require('front-matter') var fs = require('fs') var marked = require('marked') require('babel/register')({ only: [ 'src/', 'node_modules/highlight.js', 'node_modules/react-highlight', ] }) var React = require('react') var OUT = path.join(process.cwd(), 'dist/') module.exports = function(grunt) { grunt.registerTask('build-site', function() { var done = this.async() async.parallel([ buildPages.bind(null, '**/*.js', { cwd: 'src/pages' }), buildDocs.bind(null, 'docs/**/*.md', { cwd: 'src/' }) ], done) }); } /** * @param {glob} pagesGlob * @param {Object} opts * @param {String} opts.cwd * @param {Function} cb */ function buildPages(pagesGlob, opts, cb) { var cwd = path.join(process.cwd(), opts.cwd) console.log('buildPages, cwd=%s', cwd) glob(pagesGlob, opts, function(err, files) { async.each(files, function(item, cb) { var componentPath = path.relative(__dirname, path.join(cwd, item)) var destFilepath = changeExtension(path.join(OUT, item), '.html') var Component = require(componentPath) var html = React.renderToStaticMarkup(React.createElement(Component)); writeFile(destFilepath, html, cb) }, cb) }) } /** * @param {glob} globPattern * @param {Object} opts * @param {String} opts.cwd * @param {Function} cb */ function buildDocs(globPattern, opts, cb) { var DocWrapper = require('../src/layouts/doc-wrapper') parseDocs(globPattern, opts, function(err, docs) { var navData = docs.map(function(doc) { return { title: doc.attributes.title, relative: doc.relative, } }) console.log('navdata', navData) async.each(docs, function(doc, cb) { fs.readFile(doc.src, 'utf8') var props = { title: doc.attributes.title, contents: doc.body, navData: navData, } var html = React.renderToStaticMarkup(React.createElement(DocWrapper, props)); writeFile(path.join(OUT, doc.relative), html, cb) }, cb) }) } /** * @param {glob} globPattern * @param {Object} opts * @param {String} opts.cwd * @param {Function} cb */ function parseDocs(globPattern, opts, cb) { var cwd = path.join(process.cwd(), opts.cwd) glob(globPattern, opts, function(err, files) { async.map(files, function(item, cb) { var filepath = path.join(cwd, item) var relativeFilepath = changeExtension(item, '.html') fs.readFile(filepath, 'utf8', function(err, data) { if (err) { cb(err) } var fmData = fm(data) fmData.body = marked(fmData.body) fmData.src = filepath fmData.relative = relativeFilepath cb(null, fmData) }) }, cb) }) } // Util Functions function filenameOnly(filepath) { return path.basename(filepath, path.extname(filepath)) } function changeExtension(filepath, newExt) { var newFilename = filenameOnly(filepath) + newExt; return path.join(path.dirname(filepath), newFilename) } function writeFile (p, contents, cb) { mkdirp(path.dirname(p), function (err) { console.log('writing file: [%s]', p) if (err) return cb(err) fs.writeFile(p, contents, cb) }) }
mit
Apkawa/react-query-builder
karma.conf.js
793
'use strict'; var webpack = require('webpack'); var webpack_config = require('./webpack.config'); module.exports = function (config) { config.set({ browsers: [ 'Chrome' ], //run in Chrome singleRun: false, //just run once by default autoWatch: true, frameworks: [ 'mocha' ], //use the mocha test framework files: [ 'tests/webpack.js' //just load this file ], preprocessors: { 'tests/webpack.js': [ 'webpack', 'sourcemap' ] //preprocess with webpack and our sourcemap loader }, reporters: [ 'dots' ], //report results in this format webpack: webpack_config, webpackServer: { noInfo: true //please don't spam the console when running in karma! } }); };
mit
jahvi/generator-magento-extension-installer
gulpfile.js
1515
'use strict'; var path = require('path'); var gulp = require('gulp'); var eslint = require('gulp-eslint'); var excludeGitignore = require('gulp-exclude-gitignore'); var mocha = require('gulp-mocha'); var istanbul = require('gulp-istanbul'); var nsp = require('gulp-nsp'); var plumber = require('gulp-plumber'); var coveralls = require('gulp-coveralls'); gulp.task('static', function () { return gulp.src('**/*.js') .pipe(excludeGitignore()) .pipe(eslint()) .pipe(eslint.format()) .pipe(eslint.failAfterError()); }); gulp.task('nsp', function (cb) { nsp({package: path.resolve('package.json')}, cb); }); gulp.task('pre-test', function () { return gulp.src('generators/**/*.js') .pipe(excludeGitignore()) .pipe(istanbul({ includeUntested: true })) .pipe(istanbul.hookRequire()); }); gulp.task('test', ['pre-test'], function (cb) { var mochaErr; gulp.src('test/**/*.js') .pipe(plumber()) .pipe(mocha({reporter: 'spec'})) .on('error', function (err) { mochaErr = err; }) .pipe(istanbul.writeReports()) .on('end', function () { cb(mochaErr); }); }); gulp.task('watch', function () { gulp.watch(['generators/**/*.js', 'test/**'], ['test']); }); gulp.task('coveralls', ['test'], function () { if (!process.env.CI) { return undefined; } return gulp.src(path.join(__dirname, 'coverage/lcov.info')) .pipe(coveralls()); }); gulp.task('prepublish', ['nsp']); gulp.task('default', ['static', 'test', 'coveralls']);
mit
nwolber/xCUTEr
cmd/xValidate/main.go
1237
// Copyright (c) 2016 Niklas Wolber // This file is licensed under the MIT license. // See the LICENSE file for more information. package main import ( "flag" "fmt" "log" "os" "github.com/nwolber/xCUTEr/job" ) func main() { file, all, raw, full, json := flags() config, err := job.ReadConfig(file) if err != nil { log.Fatalln(err) } if json { fmt.Println(config.JSON()) return } maxHosts := 0 if !all { maxHosts = 1 } tree, err := config.Tree(full, raw, maxHosts, 0) if err != nil { fmt.Println("error building execution tree:", err) return } fmt.Printf("Execution tree:\n%s\n", tree) } func flags() (file string, all, raw, full, json bool) { const ( allDefault = false rawDefault = false fullDefault = false jsonDefault = false ) flag.BoolVar(&all, "all", allDefault, "Display all hosts.") flag.BoolVar(&raw, "raw", rawDefault, "Display without templating.") flag.BoolVar(&full, "full", fullDefault, "Display all directives, including infrastructure.") flag.BoolVar(&json, "json", jsonDefault, "Display json representation.") help := flag.Bool("help", false, "Display this help.") flag.Parse() if *help { flag.PrintDefaults() os.Exit(0) } file = flag.Arg(0) return }
mit
Rowandish/serviceREST
db/migrate/20140709003709_change_name.rb
114
class ChangeName < ActiveRecord::Migration def change rename_table :user_buildings, :userbuildings end end
mit
arnaudroger/SimpleFlatMapper
sfm-jooq/src/test/java/org/simpleflatmapper/jooq/test/books/Author.java
4442
/* * This file is generated by jOOQ. */ package org.simpleflatmapper.jooq.test.books; import java.sql.Date; import java.time.LocalDate; import java.util.Arrays; import java.util.List; import javax.annotation.Generated; import org.jooq.Field; import org.jooq.ForeignKey; import org.jooq.Index; import org.jooq.Name; import org.jooq.Record; import org.jooq.Row4; import org.jooq.Row5; import org.jooq.Schema; import org.jooq.Table; import org.jooq.TableField; import org.jooq.UniqueKey; import org.jooq.impl.DSL; import org.jooq.impl.TableImpl; /** * This class is generated by jOOQ. */ @Generated( value = { "http://www.jooq.org", "jOOQ version:3.12.0" }, comments = "This class is generated by jOOQ" ) @SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class Author extends TableImpl<AuthorRecord> { private static final long serialVersionUID = 1283506805; /** * The reference instance of <code>PUBLIC.AUTHOR</code> */ public static final Author AUTHOR = new Author(); /** * The class holding records for this type */ @Override public Class<AuthorRecord> getRecordType() { return AuthorRecord.class; } /** * The column <code>PUBLIC.AUTHOR.ID</code>. */ public final TableField<AuthorRecord, Integer> ID = createField(DSL.name("ID"), org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, ""); /** * The column <code>PUBLIC.AUTHOR.FIRST_NAME</code>. */ public final TableField<AuthorRecord, String> FIRST_NAME = createField(DSL.name("FIRST_NAME"), org.jooq.impl.SQLDataType.VARCHAR(50), this, ""); /** * The column <code>PUBLIC.AUTHOR.LAST_NAME</code>. */ public final TableField<AuthorRecord, String> LAST_NAME = createField(DSL.name("LAST_NAME"), org.jooq.impl.SQLDataType.VARCHAR(50).nullable(false), this, ""); /** * The column <code>PUBLIC.AUTHOR.DATE_OF_BIRTH</code>. */ public final TableField<AuthorRecord, Date> DATE_OF_BIRTH = createField(DSL.name("DATE_OF_BIRTH"), org.jooq.impl.SQLDataType.DATE, this, ""); /** * The column <code>PUBLIC.AUTHOR.DATE_OF_DEATH</code>. */ public final TableField<AuthorRecord, LocalDate> DATE_OF_DEATH = createField(DSL.name("DATE_OF_DEATH"), org.jooq.impl.SQLDataType.LOCALDATE, this, ""); /** * Create a <code>PUBLIC.AUTHOR</code> table reference */ public Author() { this(DSL.name("AUTHOR"), null); } /** * Create an aliased <code>PUBLIC.AUTHOR</code> table reference */ public Author(String alias) { this(DSL.name(alias), AUTHOR); } /** * Create an aliased <code>PUBLIC.AUTHOR</code> table reference */ public Author(Name alias) { this(alias, AUTHOR); } private Author(Name alias, Table<AuthorRecord> aliased) { this(alias, aliased, null); } private Author(Name alias, Table<AuthorRecord> aliased, Field<?>[] parameters) { super(alias, null, aliased, parameters, DSL.comment("")); } public <O extends Record> Author(Table<O> child, ForeignKey<O, AuthorRecord> key) { super(child, key, AUTHOR); } @Override public Schema getSchema() { return Public.PUBLIC; } @Override public List<Index> getIndexes() { return Arrays.<Index>asList(); } @Override public UniqueKey<AuthorRecord> getPrimaryKey() { return Keys.PK_T_AUTHOR; } @Override public List<UniqueKey<AuthorRecord>> getKeys() { return Arrays.<UniqueKey<AuthorRecord>>asList(Keys.PK_T_AUTHOR); } @Override public Author as(String alias) { return new Author(DSL.name(alias), this); } @Override public Author as(Name alias) { return new Author(alias, this); } /** * Rename this table */ @Override public Author rename(String name) { return new Author(DSL.name(name), null); } /** * Rename this table */ @Override public Author rename(Name name) { return new Author(name, null); } // ------------------------------------------------------------------------- // Row4 type methods // ------------------------------------------------------------------------- @Override public Row5<Integer, String, String, Date, LocalDate> fieldsRow() { return (Row5) super.fieldsRow(); } }
mit
FR-CO2/kyt
src/main/resources/public/scripts/app/project/task/comment/reply.controller.js
443
var listController = function (scope) { var vm = this; scope.$watch("commentListCtrl.selectedComment", function (newVal, oldVal) { var currentcomment = newVal; currentcomment.$promise.then(function (data) { vm.replies = data; }); }); }; listController.$inject = ["$scope"]; module.exports = listController;
mit
mjeldres/Gesen
app/cache/dev/twig/6c/e1/85e6e7abb245990c7eb93bfd43862ecc65b23ec27e34e7540a163c2a10c8.php
15720
<?php /* CosacoGesenBundle:Horario:new.html.twig */ class __TwigTemplate_6ce185e6e7abb245990c7eb93bfd43862ecc65b23ec27e34e7540a163c2a10c8 extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); $this->parent = false; $this->blocks = array( 'body' => array($this, 'block_body'), ); } protected function doDisplay(array $context, array $blocks = array()) { // line 1 echo " "; // line 3 $this->env->getExtension('form')->renderer->setTheme((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), array(0 => "bootstrap_3_horizontal_layout.html.twig")); echo " "; // line 5 $this->displayBlock('body', $context, $blocks); } public function block_body($context, array $blocks = array()) { // line 6 echo " <!-- Modal --> <div class=\"modal fade\" id=\"detalleReserva\" tabindex=\"-1\" role=\"dialog\" aria-labelledby=\"myModalLabel\" aria-hidden=\"true\"> <div class=\"modal-dialog\"> <div class=\"modal-content\"> <div class=\"modal-header bg-danger\" style=\"border-radius: 5px 5px 0 0;\"> <button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-label=\"Close\"><span aria-hidden=\"true\">&times;</span></button> <h4 class=\"modal-title\" id=\"myModalLabel\">Editar Reserva</h4> </div> <div class=\"modal-body\" style=\"min-height: 200px;\"> <div role=\"tabpanel\"> <!-- Nav tabs --> <ul class=\"nav nav-tabs\" role=\"tablist\"> <li role=\"presentation\" class=\"active\"><a href=\"#home\" aria-controls=\"home\" role=\"tab\" data-toggle=\"tab\">Día</a></li> <li role=\"presentation\"><a href=\"#profile\" aria-controls=\"profile\" role=\"tab\" data-toggle=\"tab\">Lote</a></li> </ul> <!-- Tab panes --> <div class=\"tab-content\" style=\"margin-top:20px;\"> <div role=\"tabpanel\" class=\"tab-pane active\" id=\"home\"> <!-- comienzo del formulario --> "; // line 31 echo $this->env->getExtension('form')->renderer->renderBlock((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), 'form_start', array("attr" => array("id" => "gsn-form-editar-reserva"))); echo $this->env->getExtension('form')->renderer->searchAndRenderBlock((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), 'errors'); echo " <!-- select tipo reservas --> <div class=\"form-group gsn-tipo-reserva-cmb\">"; // line 34 echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "tipoReserva", array()), 'label', array("label" => "Reserva: ")); echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "tipoReserva", array()), 'errors'); echo "<div class=\"col-sm-10\">"; echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "tipoReserva", array()), 'widget', array("attr" => array("class" => "gsn-cmb-tipo-reserva"))); echo "</div><div class=\"clearfix\"></div></div> "; // line 36 if ($this->getAttribute((isset($context["form"]) ? $context["form"] : null), "asignatura", array(), "any", true, true)) { // line 37 echo " <!-- select asignatura --> <div class=\"form-group\">"; // line 38 echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "asignatura", array()), 'label'); echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "asignatura", array()), 'errors'); echo "<div class=\"col-sm-10\">"; echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "asignatura", array()), 'widget'); echo "</div><div class=\"clearfix\"></div></div> <!-- select curso --> <div class=\"form-group\">"; // line 41 echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "curso", array()), 'label'); echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "curso", array()), 'errors'); echo "<div class=\"col-sm-10\">"; echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "curso", array()), 'widget'); echo "</div><div class=\"clearfix\"></div></div> "; } // line 43 echo " "; // line 44 if ($this->getAttribute((isset($context["form"]) ? $context["form"] : null), "taller", array(), "any", true, true)) { // line 45 echo " <!-- select taller --> <div class=\"form-group gsn-option gsn-taller-cmb\">"; // line 46 echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "taller", array()), 'label'); echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "taller", array()), 'errors'); echo "<div class=\"col-sm-10\">"; echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "taller", array()), 'widget'); echo "</div><div class=\"clearfix\"></div></div> "; } // line 47 echo " "; // line 48 if ($this->getAttribute($this->getAttribute((isset($context["form"]) ? $context["form"] : null), "dias", array(), "any", false, true), 0, array(), "array", true, true)) { // line 49 echo " <!-- ingreso actividad --> <div class=\"form-group\">"; // line 50 echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute($this->getAttribute($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "dias", array()), 0, array(), "array"), "actividadReserva", array()), 'label'); echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute($this->getAttribute($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "dias", array()), 0, array(), "array"), "actividadReserva", array()), 'errors'); echo "<div class=\"col-sm-10\">"; echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute($this->getAttribute($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "dias", array()), 0, array(), "array"), "actividadReserva", array()), 'widget'); echo "</div><div class=\"clearfix\"></div></div> <!-- ingreso observación --> <div class=\"form-group\">"; // line 53 echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute($this->getAttribute($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "dias", array()), 0, array(), "array"), "observacionReserva", array()), 'label'); echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute($this->getAttribute($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "dias", array()), 0, array(), "array"), "observacionReserva", array()), 'errors'); echo "<div class=\"col-sm-10\">"; echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute($this->getAttribute($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "dias", array()), 0, array(), "array"), "observacionReserva", array()), 'widget'); echo "</div><div class=\"clearfix\"></div></div> "; } // line 55 echo " <!-- submit --> <div style=\"border-bottom: 1px solid #ddd; margin-bottom: 15px;\"></div> <div class=\"form-group\" style=\"margin-bottom:0;\"><div class=\"col-sm-2\"><button class=\"gsn-prevent-validation btn btn-primary pull-left\"><span class=\"glyphicon glyphicon-print\"></span></button></div><div class=\"col-sm-10\"><button type=\"submit\" class=\"btn btn-success pull-right\" id=\""; // line 57 echo twig_escape_filter($this->env, $this->getAttribute($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "vars", array()), "id", array()), "html", null, true); echo "_submit\" name=\""; echo twig_escape_filter($this->env, $this->getAttribute($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "vars", array()), "name", array()), "html", null, true); echo "[submit]\"><span class=\"glyphicon glyphicon-floppy-save\"></span> Guardar</button><button id=\"gsn-close-editar-reserva\" class=\"gsn-prevent-validation btn btn-default pull-right\" style=\"margin-right: 5px;\">Cerrar</button></div></div> "; // line 59 echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "dias", array()), 'widget', array("attr" => array("style" => "display:none !important; margin:0 !important;"))); echo " "; // line 60 echo $this->env->getExtension('form')->renderer->renderBlock((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), 'form_end'); echo " </div> <div role=\"tabpanel\" class=\"tab-pane\" id=\"profile\"></div> </div> </div> </div> </div> </div> <script> \$('document').ready(function(){ \$('body').on('click', '.gsn-prevent-validation', function(ev){ ev.preventDefault(); }); \$('#gsn-form-editar-reserva').submit(function(ev){ ev.preventDefault(); var form = \$(this); \$.ajax({ type: form.attr('method'), url: form.attr('action'), data: form.serializeArray(), dataType: 'json', success: function(data) { // console.log(data); } }); }); /* * Cargamos dinamicamente los combos al seleccionar el tipo de reserva */ var cmb=\$('.gsn-cmb-tipo-reserva'); cmb.change(function(){ var form=\$(this).closest('form'); var form_name=form.attr('name'); //console.log(form_name); var data = {}; data[cmb.attr('name')]=cmb.val(); \$('select[name=\"'+form_name+'[asignatura]\"]').closest('.form-group').remove(); \$('select[name=\"'+form_name+'[curso]\"]').closest('.form-group').remove(); \$('select[name=\"'+form_name+'[taller]\"]').closest('.form-group').remove(); \$.ajax({ url: form.attr('action'), type: form.attr('method'), data: data, success: function(html) { if(cmb.prop('selectedIndex')===0) { var asignatura = \$(html).find('select[name=\"'+form_name+'[asignatura]\"]').closest('.form-group'); var curso = \$(html).find('select[name=\"'+form_name+'[curso]\"]').closest('.form-group'); curso.insertAfter('.gsn-tipo-reserva-cmb'); asignatura.insertAfter('.gsn-tipo-reserva-cmb'); } if(cmb.prop('selectedIndex')===1) { var taller = \$(html).find('select[name=\"'+form_name+'[taller]\"]').closest('.form-group'); taller.insertAfter('.gsn-tipo-reserva-cmb'); } } }) }); }); </script> </div> "; } public function getTemplateName() { return "CosacoGesenBundle:Horario:new.html.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 154 => 60, 150 => 59, 143 => 57, 139 => 55, 131 => 53, 122 => 50, 119 => 49, 117 => 48, 114 => 47, 106 => 46, 103 => 45, 101 => 44, 98 => 43, 90 => 41, 81 => 38, 78 => 37, 76 => 36, 68 => 34, 61 => 31, 34 => 6, 28 => 5, 23 => 3, 20 => 1,); } }
mit
arnaudroger/SimpleFlatMapper
lightningcsv/src/main/java/org/simpleflatmapper/lightningcsv/Row.java
6123
package org.simpleflatmapper.lightningcsv; import java.util.AbstractMap; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.Map; import java.util.Set; public class Row implements Map<String, String> { public static final int SORTED_HEADERS_THRESHOLD = 10; private final Headers headers; private final String[] values; private Set<Entry<String, String>> entrySetCache; private Collection<String> valuesCollectionCache; public Row(Headers headers, String[] values) { this.headers = headers; this.values = values; } @Override public int size() { return headers.size(); } @Override public boolean isEmpty() { return headers.isEmpty(); } @Override public boolean containsKey(Object key) { if (key instanceof String) { return headers.containsKey((String) key); } return false; } @Override public boolean containsValue(Object value) { for(int i = 0; i < values.length; i++) { if (value == null ? values[i] == null : value.equals(values[i])) { return true; } } return false; } @Override public String get(Object key) { if (!(key instanceof String)) { return null; } int i = headers.indexOf((String)key); if (i != -1) { return values[i]; } return null; } @Override public String put(String key, String value) { throw new UnsupportedOperationException(); } @Override public String remove(Object key) { throw new UnsupportedOperationException(); } @Override public void putAll(Map<? extends String, ? extends String> m) { throw new UnsupportedOperationException(); } @Override public void clear() { throw new UnsupportedOperationException(); } @Override public Set<String> keySet() { return headers.keySet(); } @Override public Collection<String> values() { if (valuesCollectionCache == null) { valuesCollectionCache = Collections.unmodifiableList(Arrays.asList(values)); } return valuesCollectionCache; } @Override public Set<Entry<String, String>> entrySet() { if (entrySetCache == null) { HashSet<Entry<String, String>> set = new HashSet<Entry<String, String>>(); for(int i = 0; i < headers.headers.length; i++) { set.add(new AbstractMap.SimpleImmutableEntry<String, String>(headers.headers[i], values[i])); } entrySetCache = Collections.unmodifiableSet(set); } return entrySetCache; } public static Headers headers(String[] headers) { if (headers.length > SORTED_HEADERS_THRESHOLD) { return new SortedHeaders(headers); } return new DefaultHeaders(headers); } static abstract class Headers { protected final String[] headers; private Set<String> keySet; protected Headers(String[] headers) { this.headers = headers; } public final boolean containsKey(String key) { return indexOf(key) != -1; } public final int size() { return headers.length; } public final boolean isEmpty() { return headers.length == 0; } public final Set<String> keySet() { if (keySet == null) { keySet = new HashSet<String>(); Collections.addAll(keySet, headers); } return keySet; } public abstract int indexOf(String key); } public static class DefaultHeaders extends Headers { protected DefaultHeaders(String[] headers) { super(headers); } @Override public final int indexOf(String key) { for(int i = 0; i < headers.length; i++) { if (Row.equals(key, headers[i])) { return i; } } return -1; } } public static class SortedHeaders extends Headers { private final String[] sortedHeader; private final int[] sortedHeaderIndex; protected SortedHeaders(String[] headers) { super(headers); sortedHeader = new String[headers.length]; sortedHeaderIndex = new int[headers.length]; IndexedHeader[] indexedHeaders = new IndexedHeader[headers.length]; for(int i = 0; i < indexedHeaders.length; i++) { indexedHeaders[i] = new IndexedHeader(headers[i], i); } Arrays.sort(indexedHeaders, IndexedHeader.NAME_COMPARATOR); for(int i = 0; i < indexedHeaders.length; i++) { IndexedHeader ih = indexedHeaders[i]; sortedHeader[i] = ih.name; sortedHeaderIndex[i] = ih.index; } } @Override public final int indexOf(String key) { int i = Arrays.binarySearch(sortedHeader, key); if (i < 0) return -1; return sortedHeaderIndex[i]; } private static class IndexedHeader { public static final Comparator<IndexedHeader> NAME_COMPARATOR = new Comparator<IndexedHeader>() { @Override public int compare(IndexedHeader o1, IndexedHeader o2) { return o1.name.compareTo(o2.name); } }; public final String name; public final int index; IndexedHeader(String name, int index) { this.name = name == null ? "" : name; this.index = index; } } } private static boolean equals(Object a, Object b) { return (a == b) || (a != null && a.equals(b)); } }
mit
gongyicoin/gongyicoin
src/qt/locale/bitcoin_pt_PT.ts
127644
<TS language="pt_PT" version="2.1"> <context> <name>AddressBookPage</name> <message> <source>Right-click to edit address or label</source> <translation>Clique á direita para editar endereço ou rótulo</translation> </message> <message> <source>Create a new address</source> <translation>Criar um novo endereço</translation> </message> <message> <source>&amp;New</source> <translation>&amp;Novo</translation> </message> <message> <source>Copy the currently selected address to the system clipboard</source> <translation>Copiar o endereço selecionado para a área de transferência</translation> </message> <message> <source>&amp;Copy</source> <translation>&amp;Copiar</translation> </message> <message> <source>C&amp;lose</source> <translation>F&amp;echar</translation> </message> <message> <source>&amp;Copy Address</source> <translation>&amp;Copiar Endereço</translation> </message> <message> <source>Delete the currently selected address from the list</source> <translation>Apagar o endereço selecionado da lista</translation> </message> <message> <source>Export the data in the current tab to a file</source> <translation>Exportar os dados no separador actual para um ficheiro</translation> </message> <message> <source>&amp;Export</source> <translation>&amp;Exportar</translation> </message> <message> <source>&amp;Delete</source> <translation>&amp;Eliminar\</translation> </message> <message> <source>Choose the address to send coins to</source> <translation>Escolha o endereço para o qual pretende enviar moedas</translation> </message> <message> <source>Choose the address to receive coins with</source> <translation>Escolha o endereço com o qual pretende receber moedas</translation> </message> <message> <source>C&amp;hoose</source> <translation>Escol&amp;her</translation> </message> <message> <source>Sending addresses</source> <translation>Endereços de envio</translation> </message> <message> <source>Receiving addresses</source> <translation>Endereços de depósito</translation> </message> <message> <source>These are your GongYiCoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation>Estes são os seus endereços GongYiCoin para enviar pagamentos. Verifique sempre o valor e o endereço de envio antes de enviar moedas.</translation> </message> <message> <source>These are your GongYiCoin addresses for receiving payments. It is recommended to use a new receiving address for each transaction.</source> <translation>Estes são os seus endereços GongYiCoin para receber pagamentos. É recomendado que utilize um endereço novo para cada transacção.</translation> </message> <message> <source>Copy &amp;Label</source> <translation>Copiar &amp;Rótulo</translation> </message> <message> <source>&amp;Edit</source> <translation>&amp;Editar</translation> </message> <message> <source>Export Address List</source> <translation>Exportar Lista de Endereços</translation> </message> <message> <source>Comma separated file (*.csv)</source> <translation>Ficheiro separado por vírgulas (*.csv)</translation> </message> <message> <source>Exporting Failed</source> <translation>A Exportação Falhou</translation> </message> <message> <source>There was an error trying to save the address list to %1. Please try again.</source> <translation>Houve um erro ao tentar a guardar a lista de endereços em %1. Por favor tente novamente.</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <source>Label</source> <translation>Rótulo</translation> </message> <message> <source>Address</source> <translation>Endereço</translation> </message> <message> <source>(no label)</source> <translation>(sem rótulo)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <source>Passphrase Dialog</source> <translation>Diálogo de frase de segurança</translation> </message> <message> <source>Enter passphrase</source> <translation>Insira a frase de segurança</translation> </message> <message> <source>New passphrase</source> <translation>Nova frase de segurança</translation> </message> <message> <source>Repeat new passphrase</source> <translation>Repita a nova frase de segurança</translation> </message> <message> <source>Encrypt wallet</source> <translation>Encriptar carteira</translation> </message> <message> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>A sua frase de segurança é necessária para desbloquear a carteira.</translation> </message> <message> <source>Unlock wallet</source> <translation>Desbloquear carteira</translation> </message> <message> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>A sua frase de segurança é necessária para desencriptar a carteira.</translation> </message> <message> <source>Decrypt wallet</source> <translation>Desencriptar carteira</translation> </message> <message> <source>Change passphrase</source> <translation>Alterar frase de segurança</translation> </message> <message> <source>Enter the old and new passphrase to the wallet.</source> <translation>Escreva a antiga frase de segurança da carteira, seguida da nova.</translation> </message> <message> <source>Confirm wallet encryption</source> <translation>Confirmar encriptação da carteira</translation> </message> <message> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR LITECOINS&lt;/b&gt;!</source> <translation>Atenção: Se encriptar a carteira e perder a sua senha irá &lt;b&gt;PERDER TODOS OS SEUS LITECOINS&lt;/b&gt;!</translation> </message> <message> <source>Are you sure you wish to encrypt your wallet?</source> <translation>Tem a certeza que deseja encriptar a carteira?</translation> </message> <message> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation>IMPORTANTE: Qualquer cópia de segurança da carteira anterior deverá ser substituída com o novo ficheiro de carteira, agora encriptado. Por razões de segurança, cópias de segurança não encriptadas tornar-se-ão inúteis assim que começar a usar a nova carteira encriptada.</translation> </message> <message> <source>Warning: The Caps Lock key is on!</source> <translation>Atenção: A tecla Caps Lock está activa!</translation> </message> <message> <source>Wallet encrypted</source> <translation>Carteira encriptada</translation> </message> <message> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;ten or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation>Escreva a nova frase de seguraça da sua carteira. &lt;br/&gt; Por favor, use uma frase de &lt;b&gt;10 ou mais caracteres aleatórios,&lt;/b&gt; ou &lt;b&gt;oito ou mais palavras&lt;/b&gt;.</translation> </message> <message> <source>GongYiCoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your gongyicoins from being stolen by malware infecting your computer.</source> <translation>O cliente GongYiCoin irá agora ser fechado para terminar o processo de encriptação. Recorde que a encriptação da sua carteira não protegerá totalmente os seus gongyicoins de serem roubados por programas maliciosos que infectem o seu computador.</translation> </message> <message> <source>Wallet encryption failed</source> <translation>A encriptação da carteira falhou</translation> </message> <message> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>A encriptação da carteira falhou devido a um erro interno. A carteira não foi encriptada.</translation> </message> <message> <source>The supplied passphrases do not match.</source> <translation>As frases de segurança fornecidas não coincidem.</translation> </message> <message> <source>Wallet unlock failed</source> <translation>O desbloqueio da carteira falhou</translation> </message> <message> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>A frase de segurança introduzida para a desencriptação da carteira estava incorreta.</translation> </message> <message> <source>Wallet decryption failed</source> <translation>A desencriptação da carteira falhou</translation> </message> <message> <source>Wallet passphrase was successfully changed.</source> <translation>A frase de segurança da carteira foi alterada com êxito.</translation> </message> </context> <context> <name>BitcoinGUI</name> <message> <source>Sign &amp;message...</source> <translation>Assinar &amp;mensagem...</translation> </message> <message> <source>Synchronizing with network...</source> <translation>A sincronizar com a rede...</translation> </message> <message> <source>&amp;Overview</source> <translation>Visã&amp;o geral</translation> </message> <message> <source>Node</source> <translation>Nó</translation> </message> <message> <source>Show general overview of wallet</source> <translation>Mostrar visão geral da carteira</translation> </message> <message> <source>&amp;Transactions</source> <translation>&amp;Transações</translation> </message> <message> <source>Browse transaction history</source> <translation>Navegar pelo histórico de transações</translation> </message> <message> <source>E&amp;xit</source> <translation>Fec&amp;har</translation> </message> <message> <source>Quit application</source> <translation>Sair da aplicação</translation> </message> <message> <source>About &amp;Qt</source> <translation>Sobre &amp;Qt</translation> </message> <message> <source>Show information about Qt</source> <translation>Mostrar informação sobre Qt</translation> </message> <message> <source>&amp;Options...</source> <translation>&amp;Opções...</translation> </message> <message> <source>&amp;Encrypt Wallet...</source> <translation>E&amp;ncriptar Carteira...</translation> </message> <message> <source>&amp;Backup Wallet...</source> <translation>&amp;Guardar Carteira...</translation> </message> <message> <source>&amp;Change Passphrase...</source> <translation>Mudar &amp;Palavra-passe...</translation> </message> <message> <source>&amp;Sending addresses...</source> <translation>A &amp;enviar endereços...</translation> </message> <message> <source>&amp;Receiving addresses...</source> <translation>A &amp;receber endereços...</translation> </message> <message> <source>Open &amp;URI...</source> <translation>Abrir &amp;URI...</translation> </message> <message> <source>GongYiCoin Core client</source> <translation>Cliente GongYiCoin Core</translation> </message> <message> <source>Importing blocks from disk...</source> <translation>A importar blocos do disco...</translation> </message> <message> <source>Reindexing blocks on disk...</source> <translation>A reindexar blocos no disco...</translation> </message> <message> <source>Send coins to a GongYiCoin address</source> <translation>Enviar moedas para um endereço gongyicoin</translation> </message> <message> <source>Modify configuration options for GongYiCoin</source> <translation>Modificar opções de configuração para gongyicoin</translation> </message> <message> <source>Backup wallet to another location</source> <translation>Faça uma cópia de segurança da carteira para outra localização</translation> </message> <message> <source>Change the passphrase used for wallet encryption</source> <translation>Mudar a frase de segurança utilizada na encriptação da carteira</translation> </message> <message> <source>&amp;Debug window</source> <translation>Janela de &amp;depuração</translation> </message> <message> <source>Open debugging and diagnostic console</source> <translation>Abrir consola de diagnóstico e depuração</translation> </message> <message> <source>&amp;Verify message...</source> <translation>&amp;Verificar mensagem...</translation> </message> <message> <source>GongYiCoin</source> <translation>GongYiCoin</translation> </message> <message> <source>Wallet</source> <translation>Carteira</translation> </message> <message> <source>&amp;Send</source> <translation>&amp;Enviar</translation> </message> <message> <source>&amp;Receive</source> <translation>&amp;Receber</translation> </message> <message> <source>Show information about GongYiCoin Core</source> <translation>Mostrar informação sobre GongYiCoin Core</translation> </message> <message> <source>&amp;Show / Hide</source> <translation>Mo&amp;strar / Ocultar</translation> </message> <message> <source>Show or hide the main Window</source> <translation>Mostrar ou esconder a janela principal</translation> </message> <message> <source>Encrypt the private keys that belong to your wallet</source> <translation>Encriptar as chaves privadas que pertencem à sua carteira</translation> </message> <message> <source>Sign messages with your GongYiCoin addresses to prove you own them</source> <translation>Assine mensagens com os seus endereços GongYiCoin para provar que os controla</translation> </message> <message> <source>Verify messages to ensure they were signed with specified GongYiCoin addresses</source> <translation>Verifique mensagens para assegurar que foram assinadas com o endereço GongYiCoin especificado</translation> </message> <message> <source>&amp;File</source> <translation>&amp;Ficheiro</translation> </message> <message> <source>&amp;Settings</source> <translation>&amp;Configurações</translation> </message> <message> <source>&amp;Help</source> <translation>&amp;Ajuda</translation> </message> <message> <source>Tabs toolbar</source> <translation>Barra de separadores</translation> </message> <message> <source>GongYiCoin Core</source> <translation>GongYiCoin Core</translation> </message> <message> <source>Request payments (generates QR codes and gongyicoin: URIs)</source> <translation>Solicitar pagamentos (gera códigos QR e URIs gongyicoin:)</translation> </message> <message> <source>&amp;About GongYiCoin Core</source> <translation>&amp;Sobre o GongYiCoin Core</translation> </message> <message> <source>Show the list of used sending addresses and labels</source> <translation>Mostrar a lista de rótulos e endereços de envio usados</translation> </message> <message> <source>Show the list of used receiving addresses and labels</source> <translation>Mostrar a lista de rótulos e endereços de receção usados</translation> </message> <message> <source>Open a gongyicoin: URI or payment request</source> <translation>Abrir URI gongyicoin: ou pedido de pagamento</translation> </message> <message> <source>&amp;Command-line options</source> <translation>&amp;Opções da linha de &amp;comandos</translation> </message> <message> <source>Show the GongYiCoin Core help message to get a list with possible GongYiCoin command-line options</source> <translation>Mostrar a mensagem de ajuda do GongYiCoin Core para obter uma lista com possíveis opções de linha de comandos</translation> </message> <message numerus="yes"> <source>%n active connection(s) to GongYiCoin network</source> <translation><numerusform>%n ligação ativa à rede GongYiCoin</numerusform><numerusform>%n ligações ativas à rede GongYiCoin</numerusform></translation> </message> <message> <source>No block source available...</source> <translation>Nenhuma fonte de blocos disponível...</translation> </message> <message numerus="yes"> <source>%n hour(s)</source> <translation><numerusform>%n hora</numerusform><numerusform>%n horas</numerusform></translation> </message> <message numerus="yes"> <source>%n day(s)</source> <translation><numerusform>%n dia</numerusform><numerusform>%n dias</numerusform></translation> </message> <message numerus="yes"> <source>%n week(s)</source> <translation><numerusform>%n semana</numerusform><numerusform>%n semanas</numerusform></translation> </message> <message> <source>%1 and %2</source> <translation>%1 e %2</translation> </message> <message numerus="yes"> <source>%n year(s)</source> <translation><numerusform>%n ano</numerusform><numerusform>%n anos</numerusform></translation> </message> <message> <source>%1 behind</source> <translation>%1 em atraso</translation> </message> <message> <source>Last received block was generated %1 ago.</source> <translation>O último bloco recebido foi gerado %1 atrás.</translation> </message> <message> <source>Transactions after this will not yet be visible.</source> <translation>Transações posteriores não serão visíveis por enquanto.</translation> </message> <message> <source>Error</source> <translation>Erro</translation> </message> <message> <source>Warning</source> <translation>Aviso</translation> </message> <message> <source>Information</source> <translation>Informação</translation> </message> <message> <source>Up to date</source> <translation>Atualizado</translation> </message> <message> <source>Catching up...</source> <translation>Recuperando o atraso...</translation> </message> <message> <source>Sent transaction</source> <translation>Transação enviada</translation> </message> <message> <source>Incoming transaction</source> <translation>Transação recebida</translation> </message> <message> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>Data: %1 Quantia: %2 Tipo: %3 Endereço: %4</translation> </message> <message> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>A carteira está &lt;b&gt;encriptada&lt;/b&gt; e atualmente &lt;b&gt;desbloqueada&lt;/b&gt;</translation> </message> <message> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>A carteira está &lt;b&gt;encriptada&lt;/b&gt; e atualmente &lt;b&gt;bloqueada&lt;/b&gt;</translation> </message> </context> <context> <name>ClientModel</name> <message> <source>Network Alert</source> <translation>Alerta da Rede</translation> </message> </context> <context> <name>CoinControlDialog</name> <message> <source>Coin Selection</source> <translation>Seleção de moeda</translation> </message> <message> <source>Quantity:</source> <translation>Quantidade:</translation> </message> <message> <source>Bytes:</source> <translation>Bytes:</translation> </message> <message> <source>Amount:</source> <translation>Quantia:</translation> </message> <message> <source>Priority:</source> <translation>Prioridade:</translation> </message> <message> <source>Fee:</source> <translation>Taxa:</translation> </message> <message> <source>Dust:</source> <translation>Lixo:</translation> </message> <message> <source>After Fee:</source> <translation>Depois da Taxa:</translation> </message> <message> <source>Change:</source> <translation>Troco:</translation> </message> <message> <source>(un)select all</source> <translation>(des)seleccionar todos</translation> </message> <message> <source>Tree mode</source> <translation>Modo árvore</translation> </message> <message> <source>List mode</source> <translation>Modo lista</translation> </message> <message> <source>Amount</source> <translation>Quantia</translation> </message> <message> <source>Received with label</source> <translation>Recebido com rótulo</translation> </message> <message> <source>Received with address</source> <translation>Recebido com endereço</translation> </message> <message> <source>Date</source> <translation>Data</translation> </message> <message> <source>Confirmations</source> <translation>Confirmados</translation> </message> <message> <source>Confirmed</source> <translation>Confirmada</translation> </message> <message> <source>Priority</source> <translation>Prioridade</translation> </message> <message> <source>Copy address</source> <translation>Copiar endereço</translation> </message> <message> <source>Copy label</source> <translation>Copiar rótulo</translation> </message> <message> <source>Copy amount</source> <translation>Copiar quantia</translation> </message> <message> <source>Copy transaction ID</source> <translation>Copiar ID da transação</translation> </message> <message> <source>Lock unspent</source> <translation>Bloquear não gastos</translation> </message> <message> <source>Unlock unspent</source> <translation>Desbloquear não gastos</translation> </message> <message> <source>Copy quantity</source> <translation>Copiar quantidade</translation> </message> <message> <source>Copy fee</source> <translation>Copiar taxa</translation> </message> <message> <source>Copy after fee</source> <translation>Copiar valor após taxa</translation> </message> <message> <source>Copy bytes</source> <translation>Copiar bytes</translation> </message> <message> <source>Copy priority</source> <translation>Copiar prioridade</translation> </message> <message> <source>Copy dust</source> <translation>Copiar lixo</translation> </message> <message> <source>Copy change</source> <translation>Copiar alteração</translation> </message> <message> <source>highest</source> <translation>muito alta</translation> </message> <message> <source>higher</source> <translation>mais alta</translation> </message> <message> <source>high</source> <translation>alta</translation> </message> <message> <source>medium-high</source> <translation>média-alta</translation> </message> <message> <source>medium</source> <translation>média</translation> </message> <message> <source>low-medium</source> <translation>média-baixa</translation> </message> <message> <source>low</source> <translation>baixa</translation> </message> <message> <source>lower</source> <translation>mais baixa</translation> </message> <message> <source>lowest</source> <translation>muito alta</translation> </message> <message> <source>(%1 locked)</source> <translation>(%1 bloqueados)</translation> </message> <message> <source>none</source> <translation>nenhum</translation> </message> <message> <source>Can vary +/- %1 satoshi(s) per input.</source> <translation>Pode variar +/- %1 satoshi(s) por entrada</translation> </message> <message> <source>yes</source> <translation>sim</translation> </message> <message> <source>no</source> <translation>não</translation> </message> <message> <source>This label turns red, if the transaction size is greater than 1000 bytes.</source> <translation>Este rótulo fica vermelha se o tamanho da transacção exceder os 1000 bytes.</translation> </message> <message> <source>This means a fee of at least %1 per kB is required.</source> <translation>Isto significa que uma taxa de pelo menos %1 por kB é necessária.</translation> </message> <message> <source>Can vary +/- 1 byte per input.</source> <translation>Pode variar +/- 1 byte por input.</translation> </message> <message> <source>Transactions with higher priority are more likely to get included into a block.</source> <translation>Transacções com uma prioridade mais alta têm uma maior probabilidade de serem incluídas num bloco.</translation> </message> <message> <source>This label turns red, if the priority is smaller than "medium".</source> <translation>Esta legenda fica vermelha, se a prioridade for menor que "média".</translation> </message> <message> <source>This label turns red, if any recipient receives an amount smaller than %1.</source> <translation>Este rótulo fica vermelho se algum recipiente receber uma quantia menor que %1.</translation> </message> <message> <source>(no label)</source> <translation>(sem rótulo)</translation> </message> <message> <source>change from %1 (%2)</source> <translation>troco de %1 (%2)</translation> </message> <message> <source>(change)</source> <translation>(troco)</translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <source>Edit Address</source> <translation>Editar Endereço</translation> </message> <message> <source>&amp;Label</source> <translation>&amp;Rótulo</translation> </message> <message> <source>The label associated with this address list entry</source> <translation>O rótulo associado com esta entrada no livro de endereços</translation> </message> <message> <source>The address associated with this address list entry. This can only be modified for sending addresses.</source> <translation>O endereço associado com o esta entrada no livro de endereços. Isto só pode ser modificado para endereços de saída.</translation> </message> <message> <source>&amp;Address</source> <translation>E&amp;ndereço</translation> </message> <message> <source>New receiving address</source> <translation>Novo endereço de entrada</translation> </message> <message> <source>New sending address</source> <translation>Novo endereço de saída</translation> </message> <message> <source>Edit receiving address</source> <translation>Editar endereço de entrada</translation> </message> <message> <source>Edit sending address</source> <translation>Editar endereço de saída</translation> </message> <message> <source>The entered address "%1" is already in the address book.</source> <translation>O endereço introduzido "%1" já se encontra no livro de endereços.</translation> </message> <message> <source>The entered address "%1" is not a valid GongYiCoin address.</source> <translation>O endereço introduzido "%1" não é um endereço gongyicoin válido.</translation> </message> <message> <source>Could not unlock wallet.</source> <translation>Impossível desbloquear carteira.</translation> </message> <message> <source>New key generation failed.</source> <translation>Falha ao gerar nova chave.</translation> </message> </context> <context> <name>FreespaceChecker</name> <message> <source>A new data directory will be created.</source> <translation>Uma nova pasta de dados será criada.</translation> </message> <message> <source>name</source> <translation>nome</translation> </message> <message> <source>Directory already exists. Add %1 if you intend to create a new directory here.</source> <translation>A pasta já existe. Adicione %1 se pretender criar aqui uma nova pasta.</translation> </message> <message> <source>Path already exists, and is not a directory.</source> <translation>Caminho já existe, e não é uma pasta.</translation> </message> <message> <source>Cannot create data directory here.</source> <translation>Não pode ser criada uma pasta de dados aqui.</translation> </message> </context> <context> <name>HelpMessageDialog</name> <message> <source>GongYiCoin Core</source> <translation>GongYiCoin Core</translation> </message> <message> <source>version</source> <translation>versão</translation> </message> <message> <source>(%1-bit)</source> <translation>(%1-bit)</translation> </message> <message> <source>About GongYiCoin Core</source> <translation>Sobre o GongYiCoin Core</translation> </message> <message> <source>Command-line options</source> <translation>Opções de linha de comandos</translation> </message> <message> <source>Usage:</source> <translation>Utilização:</translation> </message> <message> <source>command-line options</source> <translation>opções da linha de comandos</translation> </message> <message> <source>UI options</source> <translation>Opções de Interface</translation> </message> <message> <source>Set language, for example "de_DE" (default: system locale)</source> <translation>Definir linguagem, por exemplo "pt_PT" (por defeito: linguagem do sistema)</translation> </message> <message> <source>Start minimized</source> <translation>Iniciar minimizado</translation> </message> <message> <source>Set SSL root certificates for payment request (default: -system-)</source> <translation>Configurar certificados SSL root para pedido de pagamento (default: -system-)</translation> </message> <message> <source>Show splash screen on startup (default: 1)</source> <translation>Mostrar imagem ao iniciar (por defeito: 1)</translation> </message> <message> <source>Choose data directory on startup (default: 0)</source> <translation>Escolha a pasta de dados ao iniciar (por defeito: 0)</translation> </message> </context> <context> <name>Intro</name> <message> <source>Welcome</source> <translation>Bem-vindo</translation> </message> <message> <source>Welcome to GongYiCoin Core.</source> <translation>Bem-vindo ao GongYiCoin Core.</translation> </message> <message> <source>As this is the first time the program is launched, you can choose where GongYiCoin Core will store its data.</source> <translation>Sendo esta a primeira vez que o programa é iniciado, poderá escolher onde o GongYiCoin Core irá guardar os seus dados.</translation> </message> <message> <source>GongYiCoin Core will download and store a copy of the GongYiCoin block chain. At least %1GB of data will be stored in this directory, and it will grow over time. The wallet will also be stored in this directory.</source> <translation>O GongYiCoin Core vai transferir e armazenar uma cópia do "block chain" (cadeia de blocos). Pelo menos %1GB de dados serão armazenados nesta pasta, e vão crescer ao longo do tempo. A sua carteira também irá ser armazenada nesta pasta.</translation> </message> <message> <source>Use the default data directory</source> <translation>Utilizar a pasta de dados padrão</translation> </message> <message> <source>Use a custom data directory:</source> <translation>Utilizar uma pasta de dados personalizada:</translation> </message> <message> <source>GongYiCoin Core</source> <translation>GongYiCoin Core</translation> </message> <message> <source>Error: Specified data directory "%1" cannot be created.</source> <translation>Erro: Pasta de dados especificada como "%1, não pode ser criada.</translation> </message> <message> <source>Error</source> <translation>Erro</translation> </message> <message numerus="yes"> <source>%n GB of free space available</source> <translation><numerusform>%n GB de espaço livre disponível </numerusform><numerusform>%n GB de espaço livre disponível </numerusform></translation> </message> <message numerus="yes"> <source>(of %n GB needed)</source> <translation><numerusform>(de %n GB necessários)</numerusform><numerusform>(de %n GB necessário)</numerusform></translation> </message> </context> <context> <name>OpenURIDialog</name> <message> <source>Open URI</source> <translation>Abir URI</translation> </message> <message> <source>Open payment request from URI or file</source> <translation>Abrir pedido de pagamento de um URI ou ficheiro</translation> </message> <message> <source>URI:</source> <translation>URI:</translation> </message> <message> <source>Select payment request file</source> <translation>Seleccione o ficheiro de pedido de pagamento</translation> </message> <message> <source>Select payment request file to open</source> <translation>Seleccione o ficheiro de pedido de pagamento a abrir</translation> </message> </context> <context> <name>OptionsDialog</name> <message> <source>Options</source> <translation>Opções</translation> </message> <message> <source>&amp;Main</source> <translation>&amp;Principal</translation> </message> <message> <source>Automatically start GongYiCoin after logging in to the system.</source> <translation>Começar o GongYiCoin automaticamente ao iniciar sessão no sistema.</translation> </message> <message> <source>&amp;Start GongYiCoin on system login</source> <translation>&amp;Começar o GongYiCoin ao iniciar o sistema</translation> </message> <message> <source>Size of &amp;database cache</source> <translation>Tamanho da cache da base de &amp;dados</translation> </message> <message> <source>MB</source> <translation>MB</translation> </message> <message> <source>Number of script &amp;verification threads</source> <translation>Número de processos de &amp;verificação de scripts</translation> </message> <message> <source>Accept connections from outside</source> <translation>Aceitar conceções externas</translation> </message> <message> <source>Allow incoming connections</source> <translation>Permitir conexão</translation> </message> <message> <source>IP address of the proxy (e.g. IPv4: 127.0.0.1 / IPv6: ::1)</source> <translation>Endereço IP do proxy (p.ex. IPv4: 127.0.0.1 / IPv6: ::1)</translation> </message> <message> <source>Third party URLs (e.g. a block explorer) that appear in the transactions tab as context menu items. %s in the URL is replaced by transaction hash. Multiple URLs are separated by vertical bar |.</source> <translation>URLs de outrem (ex. um explorador de blocos) que aparece no separador de transações como itens do menu de contexto. %s do URL é substituído por hash de transação. Vários URLs são separados por barra vertical |.</translation> </message> <message> <source>Third party transaction URLs</source> <translation>URLs de transação de outrem</translation> </message> <message> <source>Active command-line options that override above options:</source> <translation>Opções de linha de comandos ativas que se sobrepõem ás opções anteriores:</translation> </message> <message> <source>Reset all client options to default.</source> <translation>Repor todas as opções do cliente.</translation> </message> <message> <source>&amp;Reset Options</source> <translation>&amp;Repor Opções</translation> </message> <message> <source>&amp;Network</source> <translation>&amp;Rede</translation> </message> <message> <source>(0 = auto, &lt;0 = leave that many cores free)</source> <translation>(0 = auto, &lt;0 = Deixar essa quantidade de núcleos livre)</translation> </message> <message> <source>W&amp;allet</source> <translation>C&amp;arteira</translation> </message> <message> <source>Expert</source> <translation>Especialista</translation> </message> <message> <source>Enable coin &amp;control features</source> <translation>Ativar funcionalidades de controlo de transação.</translation> </message> <message> <source>If you disable the spending of unconfirmed change, the change from a transaction cannot be used until that transaction has at least one confirmation. This also affects how your balance is computed.</source> <translation>No caso de desativar o gasto de troco não confirmado, o troco de uma transação não poderá ser utilizado até que essa transação tenha pelo menos uma confirmação. Isto também afeta o cálculo do seu saldo.</translation> </message> <message> <source>&amp;Spend unconfirmed change</source> <translation>&amp;Gastar troco não confirmado</translation> </message> <message> <source>Automatically open the GongYiCoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation>Abrir a porta do cliente gongyicoin automaticamente no seu router. Isto apenas funciona se o seu router suportar UPnP e este se encontrar ligado.</translation> </message> <message> <source>Map port using &amp;UPnP</source> <translation>Mapear porta usando &amp;UPnP</translation> </message> <message> <source>Connect to the GongYiCoin network through a SOCKS5 proxy.</source> <translation>Conectar à rede da GongYiCoin através dum proxy SOCLS5.</translation> </message> <message> <source>&amp;Connect through SOCKS5 proxy (default proxy):</source> <translation>&amp;Ligar através dum proxy SOCKS5 (proxy por defeito):</translation> </message> <message> <source>Proxy &amp;IP:</source> <translation>&amp;IP do proxy:</translation> </message> <message> <source>&amp;Port:</source> <translation>&amp;Porto:</translation> </message> <message> <source>Port of the proxy (e.g. 9050)</source> <translation>Porto do proxy (p.ex. 9050)</translation> </message> <message> <source>&amp;Window</source> <translation>&amp;Janela</translation> </message> <message> <source>Show only a tray icon after minimizing the window.</source> <translation>Apenas mostrar o ícone da bandeja de sistema após minimizar a janela.</translation> </message> <message> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation>&amp;Minimizar para a bandeja de sistema e não para a barra de ferramentas</translation> </message> <message> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation>Minimize ao invés de sair da aplicação quando a janela é fechada. Com esta opção selecionada, a aplicação apenas será encerrada só quando escolher Sair da aplicação no menu.</translation> </message> <message> <source>M&amp;inimize on close</source> <translation>M&amp;inimizar ao fechar</translation> </message> <message> <source>&amp;Display</source> <translation>&amp;Visualização</translation> </message> <message> <source>User Interface &amp;language:</source> <translation>&amp;Linguagem da interface de utilizador:</translation> </message> <message> <source>The user interface language can be set here. This setting will take effect after restarting GongYiCoin.</source> <translation>A linguagem da interface do utilizador pode ser definida aqui. Esta definição entrará em efeito após reiniciar o GongYiCoin.</translation> </message> <message> <source>&amp;Unit to show amounts in:</source> <translation>&amp;Unidade para mostrar quantias:</translation> </message> <message> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation>Escolha a subdivisão unitária a ser mostrada por defeito na aplicação e ao enviar moedas.</translation> </message> <message> <source>Whether to show coin control features or not.</source> <translation>Escolha para mostrar funcionalidades de Coin Control ou não.</translation> </message> <message> <source>&amp;OK</source> <translation>&amp;OK</translation> </message> <message> <source>&amp;Cancel</source> <translation>&amp;Cancelar</translation> </message> <message> <source>default</source> <translation>padrão</translation> </message> <message> <source>none</source> <translation>nenhum</translation> </message> <message> <source>Confirm options reset</source> <translation>Confirme a reposição de opções</translation> </message> <message> <source>Client restart required to activate changes.</source> <translation>É necessário reiniciar o cliente para ativar as alterações.</translation> </message> <message> <source>Client will be shutdown, do you want to proceed?</source> <translation>O cliente será desligado, deseja continuar?</translation> </message> <message> <source>This change would require a client restart.</source> <translation>Esta alteração requer um reinício do cliente.</translation> </message> <message> <source>The supplied proxy address is invalid.</source> <translation>O endereço de proxy introduzido é inválido. </translation> </message> </context> <context> <name>OverviewPage</name> <message> <source>Form</source> <translation>Formulário</translation> </message> <message> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the GongYiCoin network after a connection is established, but this process has not completed yet.</source> <translation>A informação mostrada poderá estar desatualizada. A sua carteira sincroniza automaticamente com a rede GongYiCoin depois de estabelecer ligação, mas este processo ainda não está completo.</translation> </message> <message> <source>Watch-only:</source> <translation>Modo-verificação:</translation> </message> <message> <source>Available:</source> <translation>Disponível:</translation> </message> <message> <source>Your current spendable balance</source> <translation>O seu saldo (gastável) disponível</translation> </message> <message> <source>Pending:</source> <translation>Pendente:</translation> </message> <message> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the spendable balance</source> <translation>Total de transações por confirmar, que ainda não estão contabilizadas no seu saldo gastável</translation> </message> <message> <source>Immature:</source> <translation>Imaturo:</translation> </message> <message> <source>Mined balance that has not yet matured</source> <translation>O saldo minado ainda não amadureceu</translation> </message> <message> <source>Balances</source> <translation>Balanços</translation> </message> <message> <source>Total:</source> <translation>Total:</translation> </message> <message> <source>Your current total balance</source> <translation>O seu saldo total actual</translation> </message> <message> <source>Your current balance in watch-only addresses</source> <translation>O seu balanço atual em endereços de apenas observação</translation> </message> <message> <source>Spendable:</source> <translation>Dispensável:</translation> </message> <message> <source>Recent transactions</source> <translation>transações recentes</translation> </message> <message> <source>Unconfirmed transactions to watch-only addresses</source> <translation>Transações não confirmadas para endereços modo-verificação</translation> </message> <message> <source>Mined balance in watch-only addresses that has not yet matured</source> <translation>Saldo minado ainda não disponivél de endereços modo-verificação</translation> </message> <message> <source>Current total balance in watch-only addresses</source> <translation>Saldo disponivél em enderços modo-verificação</translation> </message> <message> <source>out of sync</source> <translation>fora de sincronia</translation> </message> </context> <context> <name>PaymentServer</name> <message> <source>URI handling</source> <translation>Manuseamento de URI</translation> </message> <message> <source>Invalid payment address %1</source> <translation>Endereço de pagamento inválido %1</translation> </message> <message> <source>Payment request rejected</source> <translation>Pedido de pagamento rejeitado</translation> </message> <message> <source>Payment request network doesn't match client network.</source> <translation>Rede de requisição de pagamento não corresponde com a rede do cliente.</translation> </message> <message> <source>Payment request has expired.</source> <translation>Pedido de pagamento expirado.</translation> </message> <message> <source>Payment request is not initialized.</source> <translation>Requisição de pagamento não iniciou.</translation> </message> <message> <source>Requested payment amount of %1 is too small (considered dust).</source> <translation>Quantia solicitada para pagamento de %1 é muito pequena (considerada "pó").</translation> </message> <message> <source>Payment request error</source> <translation>Erro de pedido de pagamento</translation> </message> <message> <source>Cannot start gongyicoin: click-to-pay handler</source> <translation>Impossível iniciar o controlador de gongyicoin: click-to-pay</translation> </message> <message> <source>Payment request fetch URL is invalid: %1</source> <translation>O URL de pedido de pagamento é inválido: %1</translation> </message> <message> <source>URI cannot be parsed! This can be caused by an invalid GongYiCoin address or malformed URI parameters.</source> <translation>URI não foi lido correctamente! Isto pode ser causado por um endereço GongYiCoin inválido ou por parâmetros URI malformados.</translation> </message> <message> <source>Payment request file handling</source> <translation>Controlo de pedidos de pagamento.</translation> </message> <message> <source>Payment request file cannot be read! This can be caused by an invalid payment request file.</source> <translation>O ficheiro de pedido de pagamento não pôde ser lido! Isto pode ter sido causado por um ficheiro de pedido de pagamento inválido.</translation> </message> <message> <source>Unverified payment requests to custom payment scripts are unsupported.</source> <translation>Pedidos de pagamento não-verificados para scripts de pagamento personalizados não são suportados.</translation> </message> <message> <source>Refund from %1</source> <translation>Reembolsar de %1</translation> </message> <message> <source>Payment request %1 is too large (%2 bytes, allowed %3 bytes).</source> <translation>Pedido de pagamento %1 excede o tamanho (%2 bytes, permitido %3 bytes).</translation> </message> <message> <source>Payment request DoS protection</source> <translation>Pedido de pagamento proteção DdS</translation> </message> <message> <source>Error communicating with %1: %2</source> <translation>Erro ao comunicar com %1: %2</translation> </message> <message> <source>Payment request cannot be parsed!</source> <translation>O pedido de pagamento não pode ser lido ou processado!</translation> </message> <message> <source>Bad response from server %1</source> <translation>Má resposta do servidor %1</translation> </message> <message> <source>Payment acknowledged</source> <translation>Pagamento confirmado</translation> </message> <message> <source>Network request error</source> <translation>Erro de pedido de rede</translation> </message> </context> <context> <name>PeerTableModel</name> <message> <source>User Agent</source> <translation>Agente Usuário</translation> </message> <message> <source>Address/Hostname</source> <translation>Endereço/Nome da Rede</translation> </message> <message> <source>Ping Time</source> <translation>Tempo de Latência</translation> </message> </context> <context> <name>QObject</name> <message> <source>Amount</source> <translation>Quantia</translation> </message> <message> <source>Enter a GongYiCoin address (e.g. %1)</source> <translation>Entre um endereço GongYiCoin (ex. %1)</translation> </message> <message> <source>%1 d</source> <translation>%1 d</translation> </message> <message> <source>%1 h</source> <translation>%1 h</translation> </message> <message> <source>%1 m</source> <translation>%1 m</translation> </message> <message> <source>%1 s</source> <translation>%1 s</translation> </message> <message> <source>NETWORK</source> <translation>REDE</translation> </message> <message> <source>UNKNOWN</source> <translation>DESCONHECIDO</translation> </message> <message> <source>None</source> <translation>Nenhum</translation> </message> <message> <source>N/A</source> <translation>N/D</translation> </message> <message> <source>%1 ms</source> <translation>%1 ms</translation> </message> </context> <context> <name>QRImageWidget</name> <message> <source>&amp;Save Image...</source> <translation>&amp;Salvar Imagem...</translation> </message> <message> <source>&amp;Copy Image</source> <translation>&amp;Copiar Imagem</translation> </message> <message> <source>Save QR Code</source> <translation>Guardar Código QR</translation> </message> <message> <source>PNG Image (*.png)</source> <translation>Imagem PNG (*.png)</translation> </message> </context> <context> <name>RPCConsole</name> <message> <source>Client name</source> <translation>Nome do Cliente</translation> </message> <message> <source>N/A</source> <translation>N/D</translation> </message> <message> <source>Client version</source> <translation>Versão do Cliente</translation> </message> <message> <source>&amp;Information</source> <translation>&amp;Informação</translation> </message> <message> <source>Debug window</source> <translation>Janela de depuração</translation> </message> <message> <source>General</source> <translation>Geral</translation> </message> <message> <source>Using OpenSSL version</source> <translation>Usando versão OpenSSL</translation> </message> <message> <source>Using BerkeleyDB version</source> <translation>Versão BerkeleyDB em uso</translation> </message> <message> <source>Startup time</source> <translation>Hora de inicialização</translation> </message> <message> <source>Network</source> <translation>Rede</translation> </message> <message> <source>Name</source> <translation>Nome</translation> </message> <message> <source>Number of connections</source> <translation>Número de ligações</translation> </message> <message> <source>Block chain</source> <translation>Cadeia de blocos</translation> </message> <message> <source>Current number of blocks</source> <translation>Número actual de blocos</translation> </message> <message> <source>Received</source> <translation>Recebido</translation> </message> <message> <source>Sent</source> <translation>Enviado</translation> </message> <message> <source>&amp;Peers</source> <translation>&amp;Conexção</translation> </message> <message> <source>Select a peer to view detailed information.</source> <translation>Selecione uma conexação para ver informação em detalhe.</translation> </message> <message> <source>Direction</source> <translation>Direcção</translation> </message> <message> <source>Version</source> <translation>Versão</translation> </message> <message> <source>User Agent</source> <translation>Agente Usuário</translation> </message> <message> <source>Services</source> <translation>Serviços</translation> </message> <message> <source>Starting Height</source> <translation>Iniciando Altura</translation> </message> <message> <source>Sync Height</source> <translation>Sincronização da Altura</translation> </message> <message> <source>Ban Score</source> <translation>Resultado da Suspensão</translation> </message> <message> <source>Connection Time</source> <translation>Tempo de Conexção</translation> </message> <message> <source>Last Send</source> <translation>Ultimo Envio</translation> </message> <message> <source>Last Receive</source> <translation>Ultimo Recebimento</translation> </message> <message> <source>Bytes Sent</source> <translation>Bytes Enviados</translation> </message> <message> <source>Bytes Received</source> <translation>Bytes Recebidos</translation> </message> <message> <source>Ping Time</source> <translation>Tempo de Latência</translation> </message> <message> <source>Last block time</source> <translation>Data do último bloco</translation> </message> <message> <source>&amp;Open</source> <translation>&amp;Abrir</translation> </message> <message> <source>&amp;Console</source> <translation>&amp;Consola</translation> </message> <message> <source>&amp;Network Traffic</source> <translation>&amp;Tráfego de Rede</translation> </message> <message> <source>&amp;Clear</source> <translation>&amp;Limpar</translation> </message> <message> <source>Totals</source> <translation>Totais</translation> </message> <message> <source>In:</source> <translation>Entrada:</translation> </message> <message> <source>Out:</source> <translation>Saída:</translation> </message> <message> <source>Build date</source> <translation>Data de compilação</translation> </message> <message> <source>Debug log file</source> <translation>Ficheiro de registo de depuração</translation> </message> <message> <source>Open the GongYiCoin debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation>Abrir o ficheiro de registo de depuração da pasta de dados actual. Isto pode demorar alguns segundos para ficheiros de registo maiores.</translation> </message> <message> <source>Clear console</source> <translation>Limpar consola</translation> </message> <message> <source>Welcome to the GongYiCoin RPC console.</source> <translation>Bem-vindo à consola RPC GongYiCoin.</translation> </message> <message> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation>Use as setas para cima e para baixo para navegar no histórico e &lt;b&gt;Ctrl-L&lt;/b&gt; para limpar o ecrã.</translation> </message> <message> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation>Insira &lt;b&gt;help&lt;/b&gt; para visualizar os comandos disponíveis.</translation> </message> <message> <source>%1 B</source> <translation>%1 B</translation> </message> <message> <source>%1 KB</source> <translation>%1 KB</translation> </message> <message> <source>%1 MB</source> <translation>%1 MB</translation> </message> <message> <source>%1 GB</source> <translation>%1 GB</translation> </message> <message> <source>via %1</source> <translation>via %1</translation> </message> <message> <source>never</source> <translation>nunca</translation> </message> <message> <source>Inbound</source> <translation>Entrada</translation> </message> <message> <source>Outbound</source> <translation>Saída</translation> </message> <message> <source>Unknown</source> <translation>Desconhecido</translation> </message> <message> <source>Fetching...</source> <translation>Em busca...</translation> </message> </context> <context> <name>ReceiveCoinsDialog</name> <message> <source>&amp;Amount:</source> <translation>&amp;Quantia:</translation> </message> <message> <source>&amp;Label:</source> <translation>&amp;Rótulo:</translation> </message> <message> <source>&amp;Message:</source> <translation>&amp;Mensagem:</translation> </message> <message> <source>Reuse one of the previously used receiving addresses. Reusing addresses has security and privacy issues. Do not use this unless re-generating a payment request made before.</source> <translation>Reutilize um dos endereços de entrada usados anteriormente. Reutilizar endereços pode levar a riscos de segurança e de privacidade. Não use esta função a não ser que esteja a gerar novamente uma requisição de pagamento feita anteriormente.</translation> </message> <message> <source>R&amp;euse an existing receiving address (not recommended)</source> <translation>Reutilizar um endereço de receção existente (não recomendado)</translation> </message> <message> <source>An optional message to attach to the payment request, which will be displayed when the request is opened. Note: The message will not be sent with the payment over the GongYiCoin network.</source> <translation>Uma mensagem opcional para anexar ao pedido de pagamento, que será exibida quando o pedido for aberto. Nota: A mensagem não será enviada com o pagamento através da rede GongYiCoin.</translation> </message> <message> <source>An optional label to associate with the new receiving address.</source> <translation>Um rótulo opcional a associar ao novo endereço de receção.</translation> </message> <message> <source>Use this form to request payments. All fields are &lt;b&gt;optional&lt;/b&gt;.</source> <translation>Utilize este formulário para solicitar pagamentos. Todos os campos são &lt;b&gt;opcionais&lt;/b&gt;.</translation> </message> <message> <source>An optional amount to request. Leave this empty or zero to not request a specific amount.</source> <translation>Uma quantia opcional a solicitar. Deixe em branco ou zero para não solicitar uma quantidade específica.</translation> </message> <message> <source>Clear all fields of the form.</source> <translation>Limpar todos os campos do formulário.</translation> </message> <message> <source>Clear</source> <translation>Limpar</translation> </message> <message> <source>Requested payments history</source> <translation>Histórico de pagamentos solicitados</translation> </message> <message> <source>&amp;Request payment</source> <translation>&amp;Requisitar Pagamento</translation> </message> <message> <source>Show the selected request (does the same as double clicking an entry)</source> <translation>Mostrar o pedido seleccionado (faz o mesmo que clicar 2 vezes numa entrada)</translation> </message> <message> <source>Show</source> <translation>Mostrar</translation> </message> <message> <source>Remove the selected entries from the list</source> <translation>Remover as entradas seleccionadas da lista</translation> </message> <message> <source>Remove</source> <translation>Remover</translation> </message> <message> <source>Copy label</source> <translation>Copiar rótulo</translation> </message> <message> <source>Copy message</source> <translation>Copiar mensagem</translation> </message> <message> <source>Copy amount</source> <translation>Copiar quantia</translation> </message> </context> <context> <name>ReceiveRequestDialog</name> <message> <source>QR Code</source> <translation>Código QR</translation> </message> <message> <source>Copy &amp;URI</source> <translation>Copiar &amp;URI</translation> </message> <message> <source>Copy &amp;Address</source> <translation>Copi&amp;ar Endereço</translation> </message> <message> <source>&amp;Save Image...</source> <translation>&amp;Salvar Imagem...</translation> </message> <message> <source>Request payment to %1</source> <translation>Requisitar Pagamento para %1</translation> </message> <message> <source>Payment information</source> <translation>Informação de Pagamento</translation> </message> <message> <source>URI</source> <translation>URI</translation> </message> <message> <source>Address</source> <translation>Endereço</translation> </message> <message> <source>Amount</source> <translation>Quantia</translation> </message> <message> <source>Label</source> <translation>Rótulo</translation> </message> <message> <source>Message</source> <translation>Mensagem</translation> </message> <message> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation>URI resultante muito longo. Tente reduzir o texto do rótulo / mensagem.</translation> </message> <message> <source>Error encoding URI into QR Code.</source> <translation>Erro ao codificar URI em Código QR.</translation> </message> </context> <context> <name>RecentRequestsTableModel</name> <message> <source>Date</source> <translation>Data</translation> </message> <message> <source>Label</source> <translation>Rótulo</translation> </message> <message> <source>Message</source> <translation>Mensagem</translation> </message> <message> <source>Amount</source> <translation>Quantia</translation> </message> <message> <source>(no label)</source> <translation>(sem rótulo)</translation> </message> <message> <source>(no message)</source> <translation>(sem mensagem)</translation> </message> <message> <source>(no amount)</source> <translation>(sem quantia)</translation> </message> </context> <context> <name>SendCoinsDialog</name> <message> <source>Send Coins</source> <translation>Enviar Moedas</translation> </message> <message> <source>Coin Control Features</source> <translation>Funcionalidades de Coin Control:</translation> </message> <message> <source>Inputs...</source> <translation>Entradas...</translation> </message> <message> <source>automatically selected</source> <translation>selecionadas automáticamente</translation> </message> <message> <source>Insufficient funds!</source> <translation>Fundos insuficientes!</translation> </message> <message> <source>Quantity:</source> <translation>Quantidade:</translation> </message> <message> <source>Bytes:</source> <translation>Bytes:</translation> </message> <message> <source>Amount:</source> <translation>Quantia:</translation> </message> <message> <source>Priority:</source> <translation>Prioridade:</translation> </message> <message> <source>Fee:</source> <translation>Taxa:</translation> </message> <message> <source>After Fee:</source> <translation>Depois da taxa:</translation> </message> <message> <source>Change:</source> <translation>Troco:</translation> </message> <message> <source>If this is activated, but the change address is empty or invalid, change will be sent to a newly generated address.</source> <translation>Se isto estiver ativo, mas o endereço de troco estiver vazio ou for inválido, o troco irá ser enviado para um novo endereço.</translation> </message> <message> <source>Custom change address</source> <translation>Endereço de troco personalizado</translation> </message> <message> <source>Transaction Fee:</source> <translation>Custo da Transação:</translation> </message> <message> <source>Choose...</source> <translation>Escolha...</translation> </message> <message> <source>collapse fee-settings</source> <translation>fechar definições-de custos</translation> </message> <message> <source>Minimize</source> <translation>Minimizar</translation> </message> <message> <source>If the custom fee is set to 1000 satoshis and the transaction is only 250 bytes, then "per kilobyte" only pays 250 satoshis in fee, while "at least" pays 1000 satoshis. For transactions bigger than a kilobyte both pay by kilobyte.</source> <translation>Se a taxa fixa for 1000 satoshis e a transação for somente 250 bytes, pagará somente 250 satoshis "por kilobyte" em custos se trasacionar "pelo menos" 1000 satoshis. Transações superiores a um kilobyte são cobradas por kilobyte.</translation> </message> <message> <source>per kilobyte</source> <translation>por kilobyte</translation> </message> <message> <source>If the custom fee is set to 1000 satoshis and the transaction is only 250 bytes, then "per kilobyte" only pays 250 satoshis in fee, while "total at least" pays 1000 satoshis. For transactions bigger than a kilobyte both pay by kilobyte.</source> <translation>Se a taxa fixa for 1000 satoshis e a transação for somente 250 bytes, pagará somente 250 satoshis "por kilobyte" em custos se trasacionar "pelo menos" 1000 satoshis. Transações superiores a um kilobyte são cobradas por kilobyte.</translation> </message> <message> <source>total at least</source> <translation>total minimo</translation> </message> <message> <source>Paying only the minimum fee is just fine as long as there is less transaction volume than space in the blocks. But be aware that this can end up in a never confirming transaction once there is more demand for gongyicoin transactions than the network can process.</source> <translation>Pode pagar somente a taxa minima desde que haja um volume de transações inferior ao espaço nos blocos. No entanto tenha em atenção que esta opção poderá acabar em uma transação nunca confirmada assim que os pedidos de transações excedam a capacidade de processamento da rede.</translation> </message> <message> <source>(read the tooltip)</source> <translation>(leia a dica)</translation> </message> <message> <source>Recommended:</source> <translation>Recomendado:</translation> </message> <message> <source>Custom:</source> <translation>Uso:</translation> </message> <message> <source>(Smart fee not initialized yet. This usually takes a few blocks...)</source> <translation>(Taxa inteligente ainda não foi acionada. Normalmente demora alguns blocos...)</translation> </message> <message> <source>Confirmation time:</source> <translation>Tempo de confirmação:</translation> </message> <message> <source>normal</source> <translation>normal</translation> </message> <message> <source>fast</source> <translation>rapido</translation> </message> <message> <source>Send as zero-fee transaction if possible</source> <translation>Enviar como uma transação a custo zero se possivél</translation> </message> <message> <source>(confirmation may take longer)</source> <translation>(confirmação poderá demorar mais)</translation> </message> <message> <source>Send to multiple recipients at once</source> <translation>Enviar para múltiplos destinatários de uma vez</translation> </message> <message> <source>Add &amp;Recipient</source> <translation>Adicionar &amp;Destinatário</translation> </message> <message> <source>Clear all fields of the form.</source> <translation>Limpar todos os campos do formulário.</translation> </message> <message> <source>Dust:</source> <translation>Lixo:</translation> </message> <message> <source>Clear &amp;All</source> <translation>Limpar &amp;Tudo</translation> </message> <message> <source>Balance:</source> <translation>Saldo:</translation> </message> <message> <source>Confirm the send action</source> <translation>Confirme ação de envio</translation> </message> <message> <source>S&amp;end</source> <translation>E&amp;nviar</translation> </message> <message> <source>Confirm send coins</source> <translation>Confirme envio de moedas</translation> </message> <message> <source>%1 to %2</source> <translation>%1 para %2</translation> </message> <message> <source>Copy quantity</source> <translation>Copiar quantidade</translation> </message> <message> <source>Copy amount</source> <translation>Copiar quantia</translation> </message> <message> <source>Copy fee</source> <translation>Copiar taxa</translation> </message> <message> <source>Copy after fee</source> <translation>Copiar valor após taxa</translation> </message> <message> <source>Copy bytes</source> <translation>Copiar bytes</translation> </message> <message> <source>Copy priority</source> <translation>Copiar prioridade</translation> </message> <message> <source>Copy change</source> <translation>Copiar alteração</translation> </message> <message> <source>Total Amount %1 (= %2)</source> <translation>Quantia Total %1 (= %2)</translation> </message> <message> <source>or</source> <translation>ou</translation> </message> <message> <source>The recipient address is not valid, please recheck.</source> <translation>O endereço de destino não é válido, por favor verifique.</translation> </message> <message> <source>The amount to pay must be larger than 0.</source> <translation>A quantia a pagar deverá ser maior que 0.</translation> </message> <message> <source>The amount exceeds your balance.</source> <translation>A quantia excede o seu saldo.</translation> </message> <message> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation>O total excede o seu saldo quando a taxa de transação de %1 for incluída.</translation> </message> <message> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation>Endereço duplicado encontrado, apenas poderá enviar uma vez para cada endereço por cada operação de envio.</translation> </message> <message> <source>Transaction creation failed!</source> <translation>Erro: A criação da transação falhou! </translation> </message> <message> <source>The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation>A transação foi rejeitada! Isto poderá acontecer se algumas das moedas na sua carteira já tiverem sido gastas, se por exemplo tiver usado uma cópia do ficheiro wallet.dat e as moedas tiverem sido gastas na cópia mas não tiverem sido marcadas como gastas aqui.</translation> </message> <message> <source>A fee higher than %1 is considered an insanely high fee.</source> <translation>Uma taxa superior a %1 é considerada muito alta.</translation> </message> <message> <source>Pay only the minimum fee of %1</source> <translation>Pagar somente a taxa minima de %1</translation> </message> <message> <source>Estimated to begin confirmation within %1 block(s).</source> <translation>Confirmação deverá começar dentro de %1 bloco(s).</translation> </message> <message> <source>Warning: Invalid GongYiCoin address</source> <translation>Aviso: Endereço GongYiCoin inválido</translation> </message> <message> <source>(no label)</source> <translation>(sem rótulo)</translation> </message> <message> <source>Warning: Unknown change address</source> <translation>Aviso: Endereço de troco desconhecido</translation> </message> <message> <source>Copy dust</source> <translation>Copiar lixo</translation> </message> <message> <source>Are you sure you want to send?</source> <translation>Tem a certeza que deseja enviar?</translation> </message> <message> <source>added as transaction fee</source> <translation>adicionados como taxa de transação</translation> </message> </context> <context> <name>SendCoinsEntry</name> <message> <source>A&amp;mount:</source> <translation>Qu&amp;antia:</translation> </message> <message> <source>Pay &amp;To:</source> <translation>&amp;Pagar A:</translation> </message> <message> <source>Enter a label for this address to add it to your address book</source> <translation>Escreva um rótulo para este endereço para o adicionar ao seu livro de endereços</translation> </message> <message> <source>&amp;Label:</source> <translation>Rótu&amp;lo:</translation> </message> <message> <source>Choose previously used address</source> <translation>Escolher endereço usado previamente</translation> </message> <message> <source>This is a normal payment.</source> <translation>Este é um pagamento normal.</translation> </message> <message> <source>The GongYiCoin address to send the payment to</source> <translation>O endereço GongYiCoin para enviar o pagamento</translation> </message> <message> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <source>Paste address from clipboard</source> <translation>Cole endereço da área de transferência</translation> </message> <message> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <source>Remove this entry</source> <translation>Remover esta entrada</translation> </message> <message> <source>Message:</source> <translation>Mensagem:</translation> </message> <message> <source>This is a verified payment request.</source> <translation>Este é um pedido de pagamento verificado.</translation> </message> <message> <source>Enter a label for this address to add it to the list of used addresses</source> <translation>Introduza um rótulo para este endereço para o adicionar à sua lista de endereços usados</translation> </message> <message> <source>A message that was attached to the gongyicoin: URI which will be stored with the transaction for your reference. Note: This message will not be sent over the GongYiCoin network.</source> <translation>Uma mensagem que estava anexada ao URI gongyicoin: que será armazenada com a transação para sua referência. Nota: Esta mensagem não será enviada através da rede GongYiCoin.</translation> </message> <message> <source>This is an unverified payment request.</source> <translation>Este é um pedido de pagamento não-verificado.</translation> </message> <message> <source>Pay To:</source> <translation>Pagar a:</translation> </message> <message> <source>Memo:</source> <translation>Memorando:</translation> </message> </context> <context> <name>ShutdownWindow</name> <message> <source>GongYiCoin Core is shutting down...</source> <translation>O GongYiCoin Core está a encerrar...</translation> </message> <message> <source>Do not shut down the computer until this window disappears.</source> <translation>Não desligue o computador enquanto esta janela não desaparecer.</translation> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <source>Signatures - Sign / Verify a Message</source> <translation>Assinaturas - Assinar / Verificar uma Mensagem</translation> </message> <message> <source>&amp;Sign Message</source> <translation>&amp;Assinar Mensagem</translation> </message> <message> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation>Pode assinar mensagens com os seus endereços para provar que são seus. Tenha atenção ao assinar mensagens ambíguas, pois ataques de phishing podem tentar enganá-lo de modo a assinar a sua identidade para os atacantes. Apenas assine declarações detalhadas com as quais concorde.</translation> </message> <message> <source>The GongYiCoin address to sign the message with</source> <translation>O endereço GongYiCoin para designar a mensagem</translation> </message> <message> <source>Choose previously used address</source> <translation>Escolher endereço usado previamente</translation> </message> <message> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <source>Paste address from clipboard</source> <translation>Colar endereço da área de transferência</translation> </message> <message> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <source>Enter the message you want to sign here</source> <translation>Escreva aqui a mensagem que deseja assinar</translation> </message> <message> <source>Signature</source> <translation>Assinatura</translation> </message> <message> <source>Copy the current signature to the system clipboard</source> <translation>Copiar a assinatura actual para a área de transferência</translation> </message> <message> <source>Sign the message to prove you own this GongYiCoin address</source> <translation>Assine uma mensagem para provar que é dono deste endereço GongYiCoin</translation> </message> <message> <source>Sign &amp;Message</source> <translation>Assinar &amp;Mensagem</translation> </message> <message> <source>Reset all sign message fields</source> <translation>Repor todos os campos de assinatura de mensagem</translation> </message> <message> <source>Clear &amp;All</source> <translation>Limpar &amp;Tudo</translation> </message> <message> <source>&amp;Verify Message</source> <translation>&amp;Verificar Mensagem</translation> </message> <message> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation>Introduza o endereço de assinatura, mensagem (assegure-se que copia quebras de linha, espaços, tabulações, etc. exactamente) e assinatura abaixo para verificar a mensagem. Tenha atenção para não ler mais na assinatura do que o que estiver na mensagem assinada, para evitar ser enganado por um atacante que se encontre entre si e quem assinou a mensagem.</translation> </message> <message> <source>The GongYiCoin address the message was signed with</source> <translation>O endereço GongYiCoin com que a mensagem foi designada</translation> </message> <message> <source>Verify the message to ensure it was signed with the specified GongYiCoin address</source> <translation>Verifique a mensagem para assegurar que foi assinada com o endereço GongYiCoin especificado</translation> </message> <message> <source>Verify &amp;Message</source> <translation>Verificar &amp;Mensagem</translation> </message> <message> <source>Reset all verify message fields</source> <translation>Repor todos os campos de verificação de mensagem</translation> </message> <message> <source>Click "Sign Message" to generate signature</source> <translation>Clique "Assinar mensagem" para gerar a assinatura</translation> </message> <message> <source>The entered address is invalid.</source> <translation>O endereço introduzido é inválido.</translation> </message> <message> <source>Please check the address and try again.</source> <translation>Por favor verifique o endereço e tente de novo.</translation> </message> <message> <source>The entered address does not refer to a key.</source> <translation>O endereço introduzido não refere a nenhuma chave.</translation> </message> <message> <source>Wallet unlock was cancelled.</source> <translation>O desbloqueio da carteira foi cancelado.</translation> </message> <message> <source>Private key for the entered address is not available.</source> <translation>A chave privada para o endereço introduzido não está disponível.</translation> </message> <message> <source>Message signing failed.</source> <translation>Assinatura de mensagem falhou.</translation> </message> <message> <source>Message signed.</source> <translation>Mensagem assinada.</translation> </message> <message> <source>The signature could not be decoded.</source> <translation>A assinatura não pôde ser descodificada.</translation> </message> <message> <source>Please check the signature and try again.</source> <translation>Por favor verifique a assinatura e tente de novo.</translation> </message> <message> <source>The signature did not match the message digest.</source> <translation>A assinatura não condiz com o conteúdo da mensagem.</translation> </message> <message> <source>Message verification failed.</source> <translation>Verificação da mensagem falhou.</translation> </message> <message> <source>Message verified.</source> <translation>Mensagem verificada.</translation> </message> </context> <context> <name>SplashScreen</name> <message> <source>GongYiCoin Core</source> <translation>GongYiCoin Core</translation> </message> <message> <source>The GongYiCoin Core developers</source> <translation>Os programadores do GongYiCoin Core</translation> </message> <message> <source>[testnet]</source> <translation>[rede de testes]</translation> </message> </context> <context> <name>TrafficGraphWidget</name> <message> <source>KB/s</source> <translation>KB/s</translation> </message> </context> <context> <name>TransactionDesc</name> <message> <source>Open until %1</source> <translation>Aberto até %1</translation> </message> <message> <source>conflicted</source> <translation>em conflito:</translation> </message> <message> <source>%1/offline</source> <translation>%1/desligado</translation> </message> <message> <source>%1/unconfirmed</source> <translation>%1/não confirmada</translation> </message> <message> <source>%1 confirmations</source> <translation>%1 confirmações</translation> </message> <message> <source>Status</source> <translation>Estado</translation> </message> <message numerus="yes"> <source>, broadcast through %n node(s)</source> <translation><numerusform>, transmitida através de %n nó</numerusform><numerusform>, transmitida através de %n nós</numerusform></translation> </message> <message> <source>Date</source> <translation>Data</translation> </message> <message> <source>Source</source> <translation>Origem</translation> </message> <message> <source>Generated</source> <translation>Gerado</translation> </message> <message> <source>From</source> <translation>De</translation> </message> <message> <source>To</source> <translation>Para</translation> </message> <message> <source>own address</source> <translation>endereço próprio</translation> </message> <message> <source>watch-only</source> <translation>modo-verificação</translation> </message> <message> <source>label</source> <translation>rótulo</translation> </message> <message> <source>Credit</source> <translation>Crédito</translation> </message> <message numerus="yes"> <source>matures in %n more block(s)</source> <translation><numerusform>matura em %n bloco</numerusform><numerusform>matura em %n blocos</numerusform></translation> </message> <message> <source>not accepted</source> <translation>não aceite</translation> </message> <message> <source>Debit</source> <translation>Débito</translation> </message> <message> <source>Total debit</source> <translation>Total a debitar</translation> </message> <message> <source>Total credit</source> <translation>Total a creditar</translation> </message> <message> <source>Transaction fee</source> <translation>Taxa de transação</translation> </message> <message> <source>Net amount</source> <translation>Valor líquido</translation> </message> <message> <source>Message</source> <translation>Mensagem</translation> </message> <message> <source>Comment</source> <translation>Comentário</translation> </message> <message> <source>Transaction ID</source> <translation>ID da Transação</translation> </message> <message> <source>Merchant</source> <translation>Comerciante</translation> </message> <message> <source>Generated coins must mature %1 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation>Moedas geradas deverão maturar por %1 blocos antes de poderem ser gastas. Quando gerou este bloco, ele foi transmitido para a rede para ser incluído na cadeia de blocos. Se a inclusão na cadeia de blocos falhar, o seu estado irá ser alterado para "não aceite" e as moedas não poderão ser gastas. Isto poderá acontecer ocasionalmente se outro nó da rede gerar um bloco a poucos segundos de diferença do seu.</translation> </message> <message> <source>Debug information</source> <translation>Informação de depuração</translation> </message> <message> <source>Transaction</source> <translation>Transação</translation> </message> <message> <source>Inputs</source> <translation>Entradas</translation> </message> <message> <source>Amount</source> <translation>Quantia</translation> </message> <message> <source>true</source> <translation>verdadeiro</translation> </message> <message> <source>false</source> <translation>falso</translation> </message> <message> <source>, has not been successfully broadcast yet</source> <translation>, ainda não foi transmitida com sucesso</translation> </message> <message numerus="yes"> <source>Open for %n more block(s)</source> <translation><numerusform>Aberta por mais %n bloco</numerusform><numerusform>Aberta por mais %n blocos</numerusform></translation> </message> <message> <source>unknown</source> <translation>desconhecido</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <source>Transaction details</source> <translation>Detalhes da transação</translation> </message> <message> <source>This pane shows a detailed description of the transaction</source> <translation>Esta janela mostra uma descrição detalhada da transação</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <source>Date</source> <translation>Data</translation> </message> <message> <source>Type</source> <translation>Tipo</translation> </message> <message> <source>Address</source> <translation>Endereço</translation> </message> <message> <source>Immature (%1 confirmations, will be available after %2)</source> <translation>Imaturo (%1 confirmações, estará disponível após %2)</translation> </message> <message numerus="yes"> <source>Open for %n more block(s)</source> <translation><numerusform>Aberta por mais %n bloco</numerusform><numerusform>Aberta por mais %n blocos</numerusform></translation> </message> <message> <source>Open until %1</source> <translation>Aberto até %1</translation> </message> <message> <source>Confirmed (%1 confirmations)</source> <translation>Confirmada (%1 confirmações)</translation> </message> <message> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>Este bloco não foi recebido por outros nós e provavelmente não será aceite pela rede!</translation> </message> <message> <source>Generated but not accepted</source> <translation>Gerado mas não aceite</translation> </message> <message> <source>Offline</source> <translation>Offline</translation> </message> <message> <source>Unconfirmed</source> <translation>Não confirmado:</translation> </message> <message> <source>Confirming (%1 of %2 recommended confirmations)</source> <translation>A confirmar (%1 de %2 confirmações recomendadas)</translation> </message> <message> <source>Conflicted</source> <translation>Em Conflito:</translation> </message> <message> <source>Received with</source> <translation>Recebido com</translation> </message> <message> <source>Received from</source> <translation>Recebido de</translation> </message> <message> <source>Sent to</source> <translation>Enviado para</translation> </message> <message> <source>Payment to yourself</source> <translation>Pagamento a si mesmo</translation> </message> <message> <source>Mined</source> <translation>Minadas</translation> </message> <message> <source>watch-only</source> <translation>modo-verificação</translation> </message> <message> <source>(n/a)</source> <translation>(n/d)</translation> </message> <message> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>Estado da transação. Passar o cursor por cima deste campo para mostrar o número de confirmações.</translation> </message> <message> <source>Date and time that the transaction was received.</source> <translation>Data e hora em que a transação foi recebida.</translation> </message> <message> <source>Type of transaction.</source> <translation>Tipo de transação.</translation> </message> <message> <source>Whether or not a watch-only address is involved in this transaction.</source> <translation>Desde que um endereço de modo-verificação faça parte ou não desta transação</translation> </message> <message> <source>Destination address of transaction.</source> <translation>Endereço de destino da transação.</translation> </message> <message> <source>Amount removed from or added to balance.</source> <translation>Quantia retirada ou adicionada ao saldo.</translation> </message> </context> <context> <name>TransactionView</name> <message> <source>All</source> <translation>Todas</translation> </message> <message> <source>Today</source> <translation>Hoje</translation> </message> <message> <source>This week</source> <translation>Esta semana</translation> </message> <message> <source>This month</source> <translation>Este mês</translation> </message> <message> <source>Last month</source> <translation>Mês passado</translation> </message> <message> <source>This year</source> <translation>Este ano</translation> </message> <message> <source>Range...</source> <translation>Período...</translation> </message> <message> <source>Received with</source> <translation>Recebida com</translation> </message> <message> <source>Sent to</source> <translation>Enviada para</translation> </message> <message> <source>To yourself</source> <translation>Para si mesmo</translation> </message> <message> <source>Mined</source> <translation>Minadas</translation> </message> <message> <source>Other</source> <translation>Outras</translation> </message> <message> <source>Enter address or label to search</source> <translation>Escreva endereço ou rótulo a procurar</translation> </message> <message> <source>Min amount</source> <translation>Quantia mínima</translation> </message> <message> <source>Copy address</source> <translation>Copiar endereço</translation> </message> <message> <source>Copy label</source> <translation>Copiar rótulo</translation> </message> <message> <source>Copy amount</source> <translation>Copiar quantia</translation> </message> <message> <source>Copy transaction ID</source> <translation>Copiar ID da Transação</translation> </message> <message> <source>Edit label</source> <translation>Editar rótulo</translation> </message> <message> <source>Show transaction details</source> <translation>Mostrar detalhes da transação</translation> </message> <message> <source>Export Transaction History</source> <translation>Exportar Histórico de Transacções</translation> </message> <message> <source>Watch-only</source> <translation>Modo-verificação</translation> </message> <message> <source>Exporting Failed</source> <translation>A Exportação Falhou</translation> </message> <message> <source>There was an error trying to save the transaction history to %1.</source> <translation>Ocorreu um erro ao tentar guardar o histórico de transações em %1.</translation> </message> <message> <source>Exporting Successful</source> <translation>Exportação Bem Sucedida</translation> </message> <message> <source>The transaction history was successfully saved to %1.</source> <translation>O histórico de transacções foi com guardado com sucesso em %1.</translation> </message> <message> <source>Comma separated file (*.csv)</source> <translation>Ficheiro separado por vírgulas (*.csv)</translation> </message> <message> <source>Confirmed</source> <translation>Confirmada</translation> </message> <message> <source>Date</source> <translation>Data</translation> </message> <message> <source>Type</source> <translation>Tipo</translation> </message> <message> <source>Label</source> <translation>Rótulo</translation> </message> <message> <source>Address</source> <translation>Endereço</translation> </message> <message> <source>ID</source> <translation>ID</translation> </message> <message> <source>Range:</source> <translation>Período:</translation> </message> <message> <source>to</source> <translation>até</translation> </message> </context> <context> <name>UnitDisplayStatusBarControl</name> <message> <source>Unit to show amounts in. Click to select another unit.</source> <translation>Unidade de valores recebidos. Clique para selecionar outra unidade.</translation> </message> </context> <context> <name>WalletFrame</name> <message> <source>No wallet has been loaded.</source> <translation>Nenhuma carteira foi carregada.</translation> </message> </context> <context> <name>WalletModel</name> <message> <source>Send Coins</source> <translation>Enviar Moedas</translation> </message> </context> <context> <name>WalletView</name> <message> <source>&amp;Export</source> <translation>&amp;Exportar</translation> </message> <message> <source>Export the data in the current tab to a file</source> <translation>Exportar os dados no separador actual para um ficheiro</translation> </message> <message> <source>Backup Wallet</source> <translation>Cópia de Segurança da Carteira</translation> </message> <message> <source>Wallet Data (*.dat)</source> <translation>Dados da Carteira (*.dat)</translation> </message> <message> <source>Backup Failed</source> <translation>Cópia de Segurança Falhou</translation> </message> <message> <source>There was an error trying to save the wallet data to %1.</source> <translation>Ocorreu um erro ao tentar guardar os dados da carteira em %1.</translation> </message> <message> <source>The wallet data was successfully saved to %1.</source> <translation>Os dados da carteira foram guardados com sucesso em %1.</translation> </message> <message> <source>Backup Successful</source> <translation>Cópia de Segurança Bem Sucedida</translation> </message> </context> <context> <name>bitcoin-core</name> <message> <source>Options:</source> <translation>Opções:</translation> </message> <message> <source>Specify data directory</source> <translation>Especificar pasta de dados</translation> </message> <message> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation>Ligar a um nó para recuperar endereços de pares, e desligar</translation> </message> <message> <source>Specify your own public address</source> <translation>Especifique o seu endereço público</translation> </message> <message> <source>Accept command line and JSON-RPC commands</source> <translation>Aceitar comandos de linha de comandos e JSON-RPC</translation> </message> <message> <source>Run in the background as a daemon and accept commands</source> <translation>Correr o processo em segundo plano e aceitar comandos</translation> </message> <message> <source>Use the test network</source> <translation>Utilizar a rede de testes</translation> </message> <message> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation>Aceitar ligações externas (padrão: 1 sem -proxy ou -connect)</translation> </message> <message> <source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source> <translation>Associar a endereço específico e escutar sempre nele. Use a notação [anfitrião]:porta para IPv6</translation> </message> <message> <source>Delete all wallet transactions and only recover those parts of the blockchain through -rescan on startup</source> <translation>Apague todas as transações da carteira e somente restore aquelas que façam parte do blockchain através de re-scan ao reiniciar o programa</translation> </message> <message> <source>Distributed under the MIT software license, see the accompanying file COPYING or &lt;http://www.opensource.org/licenses/mit-license.php&gt;.</source> <translation>Distribuido através da licença de software MIT, verifique o ficheiro anexado COPYING ou &lt;http://www.opensource.org/licenses/mit-license.php&gt;.</translation> </message> <message> <source>Enter regression test mode, which uses a special chain in which blocks can be solved instantly.</source> <translation>Entre no modo de teste de regressão, que usa uma cadeia especial cujos blocos podem ser resolvidos instantaneamente.</translation> </message> <message> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation>Executar comando quando uma das transações na carteira mudar (no comando, %s é substituído pelo ID da Transação)</translation> </message> <message> <source>In this mode -genproclimit controls how many blocks are generated immediately.</source> <translation>O modo -genproclimit controla quantos blocos são generados imediatamente.</translation> </message> <message> <source>Set the number of script verification threads (%u to %d, 0 = auto, &lt;0 = leave that many cores free, default: %d)</source> <translation>Defina o número de processos de verificação (%u até %d, 0 = automático, &lt;0 = ldisponibiliza esse número de núcleos livres, por defeito: %d)</translation> </message> <message> <source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source> <translation>Esta é uma versão de testes pré-lançamento - use à sua responsabilidade - não usar para minar ou aplicações comerciais</translation> </message> <message> <source>Unable to bind to %s on this computer. GongYiCoin Core is probably already running.</source> <translation>Incapaz de vincular à porta %s neste computador. O GongYiCoin Core provavelmente já está a correr.</translation> </message> <message> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation>Atenção: -paytxfee está definida com um valor muito alto! Esta é a taxa que irá pagar se enviar uma transação.</translation> </message> <message> <source>Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.</source> <translation>Aviso: A rede não parece estar completamente de acordo! Parece que alguns mineiros estão com dificuldades técnicas.</translation> </message> <message> <source>Warning: We do not appear to fully agree with our peers! You may need to upgrade, or other nodes may need to upgrade.</source> <translation>Atenção: Parecemos não estar de acordo com os nossos pares! Poderá ter que atualizar o seu cliente, ou outros nós poderão ter que atualizar os seus clientes.</translation> </message> <message> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation>Atenção: erro ao ler wallet.dat! Todas as chaves foram lidas correctamente, mas dados de transação ou do livro de endereços podem estar em falta ou incorrectos.</translation> </message> <message> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation>Atenção: wallet.dat corrompido, dados recuperados! wallet.dat original salvo como wallet.{timestamp}.bak em %s; se o seu saldo ou transações estiverem incorrectos deverá recuperar uma cópia de segurança.</translation> </message> <message> <source>Whitelist peers connecting from the given netmask or IP address. Can be specified multiple times.</source> <translation>Ligações na lista branca conectam desde a seguinte netmask ou endereço IP. Posse ser especificado varias vezes.</translation> </message> <message> <source>(default: 1)</source> <translation>(padrão: 1)</translation> </message> <message> <source>&lt;category&gt; can be:</source> <translation>&lt;categoria&gt; pode ser:</translation> </message> <message> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation>Tentar recuperar chaves privadas de um wallet.dat corrupto</translation> </message> <message> <source>Block creation options:</source> <translation>Opções de criação de bloco:</translation> </message> <message> <source>Connect only to the specified node(s)</source> <translation>Apenas ligar ao(s) nó(s) especificado(s)</translation> </message> <message> <source>Connection options:</source> <translation>Opcões de conexção:</translation> </message> <message> <source>Corrupted block database detected</source> <translation>Cadeia de blocos corrompida detectada</translation> </message> <message> <source>Debugging/Testing options:</source> <translation>Depuração/Opções teste:</translation> </message> <message> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation>Descobrir endereço IP próprio (padrão: 1 ao escutar sem -externalip)</translation> </message> <message> <source>Do not load the wallet and disable wallet RPC calls</source> <translation>Não carregar a carteira e desativar chamadas RPC de carteira.</translation> </message> <message> <source>Do you want to rebuild the block database now?</source> <translation>Deseja reconstruir agora a base de dados de blocos.</translation> </message> <message> <source>Error initializing block database</source> <translation>Erro ao inicializar a cadeia de blocos</translation> </message> <message> <source>Error initializing wallet database environment %s!</source> <translation>Erro ao inicializar o ambiente %s da base de dados da carteira</translation> </message> <message> <source>Error loading block database</source> <translation>Erro ao carregar base de dados de blocos</translation> </message> <message> <source>Error opening block database</source> <translation>Erro ao abrir a base de dados de blocos</translation> </message> <message> <source>Error: A fatal internal error occured, see debug.log for details</source> <translation>Erro: Um erro fatal interno ocorreu, verificar debug.log para mais informação</translation> </message> <message> <source>Error: Disk space is low!</source> <translation>Erro: Pouco espaço em disco!</translation> </message> <message> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation>Falhou a escutar em qualquer porta. Use -listen=0 se quiser isto.</translation> </message> <message> <source>If &lt;category&gt; is not supplied, output all debugging information.</source> <translation>Se uma &lt;categoria&gt; não é fornecida, imprimir toda a informação de depuração.</translation> </message> <message> <source>Importing...</source> <translation>A importar...</translation> </message> <message> <source>Incorrect or no genesis block found. Wrong datadir for network?</source> <translation>Bloco génese incorreto ou nenhum bloco génese encontrado. Pasta de dados errada para a rede?</translation> </message> <message> <source>Invalid -onion address: '%s'</source> <translation>Endereço -onion inválido: '%s'</translation> </message> <message> <source>Not enough file descriptors available.</source> <translation>Os descritores de ficheiros disponíveis são insuficientes.</translation> </message> <message> <source>Only connect to nodes in network &lt;net&gt; (ipv4, ipv6 or onion)</source> <translation>Somente conectar aos nodes na rede &lt;net&gt; (ipv4, ipv6 ou onion)</translation> </message> <message> <source>Rebuild block chain index from current blk000??.dat files</source> <translation>Reconstruir a cadeia de blocos a partir dos ficheiros blk000??.dat atuais</translation> </message> <message> <source>Set database cache size in megabytes (%d to %d, default: %d)</source> <translation>Definir o tamanho da cache de base de dados em megabytes (%d a %d, padrão: %d)</translation> </message> <message> <source>Set maximum block size in bytes (default: %d)</source> <translation>Definir tamanho máximo por bloco em bytes (por defeito: %d)</translation> </message> <message> <source>Specify wallet file (within data directory)</source> <translation>Especifique ficheiro de carteira (dentro da pasta de dados)</translation> </message> <message> <source>This is intended for regression testing tools and app development.</source> <translation>Isto têm como fim a realização de testes de regressão para pools e desenvolvimento de aplicações.</translation> </message> <message> <source>Use UPnP to map the listening port (default: %u)</source> <translation>Use UPnP para mapear a porto de escuta (default: %u)</translation> </message> <message> <source>Verifying blocks...</source> <translation>A verificar blocos...</translation> </message> <message> <source>Verifying wallet...</source> <translation>A verificar carteira...</translation> </message> <message> <source>Wallet %s resides outside data directory %s</source> <translation>A carteira %s reside fora da pasta de dados %s</translation> </message> <message> <source>Wallet options:</source> <translation>Opções da carteira:</translation> </message> <message> <source>You need to rebuild the database using -reindex to change -txindex</source> <translation>É necessário reconstruir as bases de dados usando -reindex para mudar o -txindex</translation> </message> <message> <source>Imports blocks from external blk000??.dat file</source> <translation>Importar blocos de um ficheiro blk000??.dat externo</translation> </message> <message> <source>Allow JSON-RPC connections from specified source. Valid for &lt;ip&gt; are a single IP (e.g. 1.2.3.4), a network/netmask (e.g. 1.2.3.4/255.255.255.0) or a network/CIDR (e.g. 1.2.3.4/24). This option can be specified multiple times</source> <translation>Permitir conexções JSON-RPC de fontes especificas. Valido para &lt;ip&gt; um unico IP (ex. 1.2.3.4), uma rede/netmask (ex. 1.2.3.4/255.255.255.0) ou uma rede/CIDR (ex. 1.2.3.4/24). Esta opção pode ser especificada varias vezes</translation> </message> <message> <source>An error occurred while setting up the RPC address %s port %u for listening: %s</source> <translation>Um erro ocorreu durante a definição do endereço RPC %s porto %u para escutar: %s</translation> </message> <message> <source>Bind to given address and whitelist peers connecting to it. Use [host]:port notation for IPv6</source> <translation>Vincualar o endereço dado e listar as ligações conectadas ao mesmo na lista branca. Use a notação [anfitrião]:porta para IPv6</translation> </message> <message> <source>Cannot obtain a lock on data directory %s. GongYiCoin Core is probably already running.</source> <translation>Impossível trancar a pasta de dados %s. Provavelmente o GongYiCoin Core já está a ser executado.</translation> </message> <message> <source>Execute command when a relevant alert is received or we see a really long fork (%s in cmd is replaced by message)</source> <translation>Executar comando quando um alerta relevante for recebido ou em caso de uma divisão longa da cadeia de blocos (no comando, %s é substituído pela mensagem)</translation> </message> <message> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: %d)</source> <translation>Definir tamanho máximo de transações com alta-prioridade/baixa-taxa em bytes (por defeito: %d)</translation> </message> <message> <source>Information</source> <translation>Informação</translation> </message> <message> <source>Invalid amount for -minrelaytxfee=&lt;amount&gt;: '%s'</source> <translation>Quantia inválida para -minrelaytxfee=&lt;quantidade&gt;: '%s'</translation> </message> <message> <source>Invalid amount for -mintxfee=&lt;amount&gt;: '%s'</source> <translation>Quantia inválida para -mintxfee=&lt;quantidade&gt;: '%s'</translation> </message> <message> <source>Send trace/debug info to console instead of debug.log file</source> <translation>Enviar informação de rastreio/depuração para a consola e não para o ficheiro debug.log</translation> </message> <message> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation>Encolher ficheiro debug.log ao iniciar o cliente (por defeito: 1 sem -debug definido)</translation> </message> <message> <source>Signing transaction failed</source> <translation>Falhou assinatura da transação</translation> </message> <message> <source>Transaction amount too small</source> <translation>Quantia da transação é muito baixa</translation> </message> <message> <source>Transaction amounts must be positive</source> <translation>Quantia da transação deverá ser positiva</translation> </message> <message> <source>Transaction too large</source> <translation>Transação grande demais</translation> </message> <message> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation>Usar UPnP para mapear a porta de escuta (padrão: 1 ao escutar)</translation> </message> <message> <source>Username for JSON-RPC connections</source> <translation>Nome de utilizador para ligações JSON-RPC</translation> </message> <message> <source>Warning</source> <translation>Aviso</translation> </message> <message> <source>Warning: This version is obsolete, upgrade required!</source> <translation>Atenção: Esta versão está obsoleta, é necessário actualizar!</translation> </message> <message> <source>Zapping all transactions from wallet...</source> <translation>A limpar todas as transações da carteira...</translation> </message> <message> <source>wallet.dat corrupt, salvage failed</source> <translation>wallet.dat corrompido, recuperação falhou</translation> </message> <message> <source>Password for JSON-RPC connections</source> <translation>Palavra-passe para ligações JSON-RPC</translation> </message> <message> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation>Executar comando quando o melhor bloco mudar (no comando, %s é substituído pela hash do bloco)</translation> </message> <message> <source>Upgrade wallet to latest format</source> <translation>Atualize a carteira para o formato mais recente</translation> </message> <message> <source>Rescan the block chain for missing wallet transactions</source> <translation>Procurar transações em falta na cadeia de blocos</translation> </message> <message> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>Usar OpenSSL (https) para ligações JSON-RPC</translation> </message> <message> <source>This help message</source> <translation>Esta mensagem de ajuda</translation> </message> <message> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation>Permitir procuras DNS para -addnode, -seednode e -connect</translation> </message> <message> <source>Loading addresses...</source> <translation>A carregar endereços...</translation> </message> <message> <source>Error loading wallet.dat: Wallet corrupted</source> <translation>Erro ao carregar wallet.dat: Carteira danificada</translation> </message> <message> <source>Error loading wallet.dat</source> <translation>Erro ao carregar wallet.dat</translation> </message> <message> <source>Invalid -proxy address: '%s'</source> <translation>Endereço -proxy inválido: '%s'</translation> </message> <message> <source>Unknown network specified in -onlynet: '%s'</source> <translation>Rede desconhecida especificada em -onlynet: '%s'</translation> </message> <message> <source>Cannot resolve -bind address: '%s'</source> <translation>Não foi possível resolver o endereço -bind: '%s'</translation> </message> <message> <source>Cannot resolve -externalip address: '%s'</source> <translation>Não foi possível resolver o endereço -externalip: '%s'</translation> </message> <message> <source>Invalid amount for -paytxfee=&lt;amount&gt;: '%s'</source> <translation>Quantia inválida para -paytxfee=&lt;amount&gt;: '%s'</translation> </message> <message> <source>Insufficient funds</source> <translation>Fundos insuficientes</translation> </message> <message> <source>Loading block index...</source> <translation>A carregar índice de blocos...</translation> </message> <message> <source>Add a node to connect to and attempt to keep the connection open</source> <translation>Adicionar um nó para se ligar e tentar manter a ligação aberta</translation> </message> <message> <source>Loading wallet...</source> <translation>A carregar carteira...</translation> </message> <message> <source>Cannot downgrade wallet</source> <translation>Impossível mudar a carteira para uma versão anterior</translation> </message> <message> <source>Cannot write default address</source> <translation>Impossível escrever endereço por defeito</translation> </message> <message> <source>Rescanning...</source> <translation>Reexaminando...</translation> </message> <message> <source>Done loading</source> <translation>Carregamento completo</translation> </message> <message> <source>Error</source> <translation>Erro</translation> </message> </context> </TS>
mit
twilio/twilio-csharp
src/Twilio/Rest/Chat/V2/Service/User/UserBindingResource.cs
19306
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / /// <summary> /// UserBindingResource /// </summary> using Newtonsoft.Json; using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Clients; using Twilio.Converters; using Twilio.Exceptions; using Twilio.Http; using Twilio.Types; namespace Twilio.Rest.Chat.V2.Service.User { public class UserBindingResource : Resource { public sealed class BindingTypeEnum : StringEnum { private BindingTypeEnum(string value) : base(value) {} public BindingTypeEnum() {} public static implicit operator BindingTypeEnum(string value) { return new BindingTypeEnum(value); } public static readonly BindingTypeEnum Gcm = new BindingTypeEnum("gcm"); public static readonly BindingTypeEnum Apn = new BindingTypeEnum("apn"); public static readonly BindingTypeEnum Fcm = new BindingTypeEnum("fcm"); } private static Request BuildReadRequest(ReadUserBindingOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Chat, "/v2/Services/" + options.PathServiceSid + "/Users/" + options.PathUserSid + "/Bindings", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// read /// </summary> /// <param name="options"> Read UserBinding parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of UserBinding </returns> public static ResourceSet<UserBindingResource> Read(ReadUserBindingOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildReadRequest(options, client)); var page = Page<UserBindingResource>.FromJson("bindings", response.Content); return new ResourceSet<UserBindingResource>(page, options, client); } #if !NET35 /// <summary> /// read /// </summary> /// <param name="options"> Read UserBinding parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of UserBinding </returns> public static async System.Threading.Tasks.Task<ResourceSet<UserBindingResource>> ReadAsync(ReadUserBindingOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildReadRequest(options, client)); var page = Page<UserBindingResource>.FromJson("bindings", response.Content); return new ResourceSet<UserBindingResource>(page, options, client); } #endif /// <summary> /// read /// </summary> /// <param name="pathServiceSid"> The SID of the Service to read the resource from </param> /// <param name="pathUserSid"> The SID of the User with the User Bindings to read </param> /// <param name="bindingType"> The push technology used by the User Binding resources to read </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of UserBinding </returns> public static ResourceSet<UserBindingResource> Read(string pathServiceSid, string pathUserSid, List<UserBindingResource.BindingTypeEnum> bindingType = null, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadUserBindingOptions(pathServiceSid, pathUserSid){BindingType = bindingType, PageSize = pageSize, Limit = limit}; return Read(options, client); } #if !NET35 /// <summary> /// read /// </summary> /// <param name="pathServiceSid"> The SID of the Service to read the resource from </param> /// <param name="pathUserSid"> The SID of the User with the User Bindings to read </param> /// <param name="bindingType"> The push technology used by the User Binding resources to read </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of UserBinding </returns> public static async System.Threading.Tasks.Task<ResourceSet<UserBindingResource>> ReadAsync(string pathServiceSid, string pathUserSid, List<UserBindingResource.BindingTypeEnum> bindingType = null, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadUserBindingOptions(pathServiceSid, pathUserSid){BindingType = bindingType, PageSize = pageSize, Limit = limit}; return await ReadAsync(options, client); } #endif /// <summary> /// Fetch the target page of records /// </summary> /// <param name="targetUrl"> API-generated URL for the requested results page </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The target page of records </returns> public static Page<UserBindingResource> GetPage(string targetUrl, ITwilioRestClient client) { client = client ?? TwilioClient.GetRestClient(); var request = new Request( HttpMethod.Get, targetUrl ); var response = client.Request(request); return Page<UserBindingResource>.FromJson("bindings", response.Content); } /// <summary> /// Fetch the next page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The next page of records </returns> public static Page<UserBindingResource> NextPage(Page<UserBindingResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetNextPageUrl(Rest.Domain.Chat) ); var response = client.Request(request); return Page<UserBindingResource>.FromJson("bindings", response.Content); } /// <summary> /// Fetch the previous page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The previous page of records </returns> public static Page<UserBindingResource> PreviousPage(Page<UserBindingResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetPreviousPageUrl(Rest.Domain.Chat) ); var response = client.Request(request); return Page<UserBindingResource>.FromJson("bindings", response.Content); } private static Request BuildFetchRequest(FetchUserBindingOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Chat, "/v2/Services/" + options.PathServiceSid + "/Users/" + options.PathUserSid + "/Bindings/" + options.PathSid + "", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// fetch /// </summary> /// <param name="options"> Fetch UserBinding parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of UserBinding </returns> public static UserBindingResource Fetch(FetchUserBindingOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildFetchRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// fetch /// </summary> /// <param name="options"> Fetch UserBinding parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of UserBinding </returns> public static async System.Threading.Tasks.Task<UserBindingResource> FetchAsync(FetchUserBindingOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildFetchRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// fetch /// </summary> /// <param name="pathServiceSid"> The SID of the Service to fetch the resource from </param> /// <param name="pathUserSid"> The SID of the User with the binding </param> /// <param name="pathSid"> The SID of the User Binding resource to fetch </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of UserBinding </returns> public static UserBindingResource Fetch(string pathServiceSid, string pathUserSid, string pathSid, ITwilioRestClient client = null) { var options = new FetchUserBindingOptions(pathServiceSid, pathUserSid, pathSid); return Fetch(options, client); } #if !NET35 /// <summary> /// fetch /// </summary> /// <param name="pathServiceSid"> The SID of the Service to fetch the resource from </param> /// <param name="pathUserSid"> The SID of the User with the binding </param> /// <param name="pathSid"> The SID of the User Binding resource to fetch </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of UserBinding </returns> public static async System.Threading.Tasks.Task<UserBindingResource> FetchAsync(string pathServiceSid, string pathUserSid, string pathSid, ITwilioRestClient client = null) { var options = new FetchUserBindingOptions(pathServiceSid, pathUserSid, pathSid); return await FetchAsync(options, client); } #endif private static Request BuildDeleteRequest(DeleteUserBindingOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Delete, Rest.Domain.Chat, "/v2/Services/" + options.PathServiceSid + "/Users/" + options.PathUserSid + "/Bindings/" + options.PathSid + "", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// delete /// </summary> /// <param name="options"> Delete UserBinding parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of UserBinding </returns> public static bool Delete(DeleteUserBindingOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildDeleteRequest(options, client)); return response.StatusCode == System.Net.HttpStatusCode.NoContent; } #if !NET35 /// <summary> /// delete /// </summary> /// <param name="options"> Delete UserBinding parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of UserBinding </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(DeleteUserBindingOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildDeleteRequest(options, client)); return response.StatusCode == System.Net.HttpStatusCode.NoContent; } #endif /// <summary> /// delete /// </summary> /// <param name="pathServiceSid"> The SID of the Service to delete the resource from </param> /// <param name="pathUserSid"> The SID of the User of the User Bindings to delete </param> /// <param name="pathSid"> The SID of the User Binding resource to delete </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of UserBinding </returns> public static bool Delete(string pathServiceSid, string pathUserSid, string pathSid, ITwilioRestClient client = null) { var options = new DeleteUserBindingOptions(pathServiceSid, pathUserSid, pathSid); return Delete(options, client); } #if !NET35 /// <summary> /// delete /// </summary> /// <param name="pathServiceSid"> The SID of the Service to delete the resource from </param> /// <param name="pathUserSid"> The SID of the User of the User Bindings to delete </param> /// <param name="pathSid"> The SID of the User Binding resource to delete </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of UserBinding </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(string pathServiceSid, string pathUserSid, string pathSid, ITwilioRestClient client = null) { var options = new DeleteUserBindingOptions(pathServiceSid, pathUserSid, pathSid); return await DeleteAsync(options, client); } #endif /// <summary> /// Converts a JSON string into a UserBindingResource object /// </summary> /// <param name="json"> Raw JSON string </param> /// <returns> UserBindingResource object represented by the provided JSON </returns> public static UserBindingResource FromJson(string json) { // Convert all checked exceptions to Runtime try { return JsonConvert.DeserializeObject<UserBindingResource>(json); } catch (JsonException e) { throw new ApiException(e.Message, e); } } /// <summary> /// The unique string that identifies the resource /// </summary> [JsonProperty("sid")] public string Sid { get; private set; } /// <summary> /// The SID of the Account that created the resource /// </summary> [JsonProperty("account_sid")] public string AccountSid { get; private set; } /// <summary> /// The SID of the Service that the resource is associated with /// </summary> [JsonProperty("service_sid")] public string ServiceSid { get; private set; } /// <summary> /// The ISO 8601 date and time in GMT when the resource was created /// </summary> [JsonProperty("date_created")] public DateTime? DateCreated { get; private set; } /// <summary> /// The ISO 8601 date and time in GMT when the resource was last updated /// </summary> [JsonProperty("date_updated")] public DateTime? DateUpdated { get; private set; } /// <summary> /// The unique endpoint identifier for the User Binding /// </summary> [JsonProperty("endpoint")] public string Endpoint { get; private set; } /// <summary> /// The string that identifies the resource's User /// </summary> [JsonProperty("identity")] public string Identity { get; private set; } /// <summary> /// The SID of the User with the binding /// </summary> [JsonProperty("user_sid")] public string UserSid { get; private set; } /// <summary> /// The SID of the Credential for the binding /// </summary> [JsonProperty("credential_sid")] public string CredentialSid { get; private set; } /// <summary> /// The push technology to use for the binding /// </summary> [JsonProperty("binding_type")] [JsonConverter(typeof(StringEnumConverter))] public UserBindingResource.BindingTypeEnum BindingType { get; private set; } /// <summary> /// The Programmable Chat message types the binding is subscribed to /// </summary> [JsonProperty("message_types")] public List<string> MessageTypes { get; private set; } /// <summary> /// The absolute URL of the User Binding resource /// </summary> [JsonProperty("url")] public Uri Url { get; private set; } private UserBindingResource() { } } }
mit
ddollar/foreman
lib/foreman/vendor/thor/lib/thor/util.rb
8706
require "rbconfig" class Foreman::Thor module Sandbox #:nodoc: end # This module holds several utilities: # # 1) Methods to convert thor namespaces to constants and vice-versa. # # Foreman::Thor::Util.namespace_from_thor_class(Foo::Bar::Baz) #=> "foo:bar:baz" # # 2) Loading thor files and sandboxing: # # Foreman::Thor::Util.load_thorfile("~/.thor/foo") # module Util class << self # Receives a namespace and search for it in the Foreman::Thor::Base subclasses. # # ==== Parameters # namespace<String>:: The namespace to search for. # def find_by_namespace(namespace) namespace = "default#{namespace}" if namespace.empty? || namespace =~ /^:/ Foreman::Thor::Base.subclasses.detect { |klass| klass.namespace == namespace } end # Receives a constant and converts it to a Foreman::Thor namespace. Since Foreman::Thor # commands can be added to a sandbox, this method is also responsable for # removing the sandbox namespace. # # This method should not be used in general because it's used to deal with # older versions of Foreman::Thor. On current versions, if you need to get the # namespace from a class, just call namespace on it. # # ==== Parameters # constant<Object>:: The constant to be converted to the thor path. # # ==== Returns # String:: If we receive Foo::Bar::Baz it returns "foo:bar:baz" # def namespace_from_thor_class(constant) constant = constant.to_s.gsub(/^Foreman::Thor::Sandbox::/, "") constant = snake_case(constant).squeeze(":") constant end # Given the contents, evaluate it inside the sandbox and returns the # namespaces defined in the sandbox. # # ==== Parameters # contents<String> # # ==== Returns # Array[Object] # def namespaces_in_content(contents, file = __FILE__) old_constants = Foreman::Thor::Base.subclasses.dup Foreman::Thor::Base.subclasses.clear load_thorfile(file, contents) new_constants = Foreman::Thor::Base.subclasses.dup Foreman::Thor::Base.subclasses.replace(old_constants) new_constants.map!(&:namespace) new_constants.compact! new_constants end # Returns the thor classes declared inside the given class. # def thor_classes_in(klass) stringfied_constants = klass.constants.map(&:to_s) Foreman::Thor::Base.subclasses.select do |subclass| next unless subclass.name stringfied_constants.include?(subclass.name.gsub("#{klass.name}::", "")) end end # Receives a string and convert it to snake case. SnakeCase returns snake_case. # # ==== Parameters # String # # ==== Returns # String # def snake_case(str) return str.downcase if str =~ /^[A-Z_]+$/ str.gsub(/\B[A-Z]/, '_\&').squeeze("_") =~ /_*(.*)/ $+.downcase end # Receives a string and convert it to camel case. camel_case returns CamelCase. # # ==== Parameters # String # # ==== Returns # String # def camel_case(str) return str if str !~ /_/ && str =~ /[A-Z]+.*/ str.split("_").map(&:capitalize).join end # Receives a namespace and tries to retrieve a Foreman::Thor or Foreman::Thor::Group class # from it. It first searches for a class using the all the given namespace, # if it's not found, removes the highest entry and searches for the class # again. If found, returns the highest entry as the class name. # # ==== Examples # # class Foo::Bar < Foreman::Thor # def baz # end # end # # class Baz::Foo < Foreman::Thor::Group # end # # Foreman::Thor::Util.namespace_to_thor_class("foo:bar") #=> Foo::Bar, nil # will invoke default command # Foreman::Thor::Util.namespace_to_thor_class("baz:foo") #=> Baz::Foo, nil # Foreman::Thor::Util.namespace_to_thor_class("foo:bar:baz") #=> Foo::Bar, "baz" # # ==== Parameters # namespace<String> # def find_class_and_command_by_namespace(namespace, fallback = true) if namespace.include?(":") # look for a namespaced command pieces = namespace.split(":") command = pieces.pop klass = Foreman::Thor::Util.find_by_namespace(pieces.join(":")) end unless klass # look for a Foreman::Thor::Group with the right name klass = Foreman::Thor::Util.find_by_namespace(namespace) command = nil end if !klass && fallback # try a command in the default namespace command = namespace klass = Foreman::Thor::Util.find_by_namespace("") end [klass, command] end alias_method :find_class_and_task_by_namespace, :find_class_and_command_by_namespace # Receives a path and load the thor file in the path. The file is evaluated # inside the sandbox to avoid namespacing conflicts. # def load_thorfile(path, content = nil, debug = false) content ||= File.binread(path) begin Foreman::Thor::Sandbox.class_eval(content, path) rescue StandardError => e $stderr.puts("WARNING: unable to load thorfile #{path.inspect}: #{e.message}") if debug $stderr.puts(*e.backtrace) else $stderr.puts(e.backtrace.first) end end end def user_home @@user_home ||= if ENV["HOME"] ENV["HOME"] elsif ENV["USERPROFILE"] ENV["USERPROFILE"] elsif ENV["HOMEDRIVE"] && ENV["HOMEPATH"] File.join(ENV["HOMEDRIVE"], ENV["HOMEPATH"]) elsif ENV["APPDATA"] ENV["APPDATA"] else begin File.expand_path("~") rescue if File::ALT_SEPARATOR "C:/" else "/" end end end end # Returns the root where thor files are located, depending on the OS. # def thor_root File.join(user_home, ".thor").tr('\\', "/") end # Returns the files in the thor root. On Windows thor_root will be something # like this: # # C:\Documents and Settings\james\.thor # # If we don't #gsub the \ character, Dir.glob will fail. # def thor_root_glob files = Dir["#{escape_globs(thor_root)}/*"] files.map! do |file| File.directory?(file) ? File.join(file, "main.thor") : file end end # Where to look for Foreman::Thor files. # def globs_for(path) path = escape_globs(path) ["#{path}/Foreman::Thorfile", "#{path}/*.thor", "#{path}/tasks/*.thor", "#{path}/lib/tasks/*.thor"] end # Return the path to the ruby interpreter taking into account multiple # installations and windows extensions. # def ruby_command @ruby_command ||= begin ruby_name = RbConfig::CONFIG["ruby_install_name"] ruby = File.join(RbConfig::CONFIG["bindir"], ruby_name) ruby << RbConfig::CONFIG["EXEEXT"] # avoid using different name than ruby (on platforms supporting links) if ruby_name != "ruby" && File.respond_to?(:readlink) begin alternate_ruby = File.join(RbConfig::CONFIG["bindir"], "ruby") alternate_ruby << RbConfig::CONFIG["EXEEXT"] # ruby is a symlink if File.symlink? alternate_ruby linked_ruby = File.readlink alternate_ruby # symlink points to 'ruby_install_name' ruby = alternate_ruby if linked_ruby == ruby_name || linked_ruby == ruby end rescue NotImplementedError # rubocop:disable HandleExceptions # just ignore on windows end end # escape string in case path to ruby executable contain spaces. ruby.sub!(/.*\s.*/m, '"\&"') ruby end end # Returns a string that has had any glob characters escaped. # The glob characters are `* ? { } [ ]`. # # ==== Examples # # Foreman::Thor::Util.escape_globs('[apps]') # => '\[apps\]' # # ==== Parameters # String # # ==== Returns # String # def escape_globs(path) path.to_s.gsub(/[*?{}\[\]]/, '\\\\\\&') end end end end
mit
dibayendu/flickr_photo_search
app/controllers/photos_controller.rb
1914
require_relative '../../lib/errors/exceptions' class PhotosController < ApplicationController PHOTOS_PER_PAGE = 112 def search @searched_query = params[:query] @current_page = (params[:page_number] && !params[:page_number].empty?) ? params[:page_number].to_i : 1 @photos = [] @capacity = 8 if @searched_query && !@searched_query.empty? begin @last_page = @total_pages = get_total_number_of_pages(ENV['FLICKR_API_KEY'], @searched_query, PHOTOS_PER_PAGE) @photos = flickr.photos.search(text: @searched_query, per_page: PHOTOS_PER_PAGE, page: @current_page) flash.now[:warn] = "Sorry, could not find photos for text: #{@searched_query}" unless @photos.any? rescue => e flash.now[:error] = "Something went wrong! Either you don't have internet connection of Flickr is down!" end end end def get_total_number_of_pages(api_key, text, photos_per_page) url = get_default_flickr_photo_search_url(api_key, text, photos_per_page) data = get_data_from_flickr(url) data = filter_received_data(data) if data.has_key? "photos" data["photos"]["pages"].to_i else raise ::Exceptions::FlickrApiError.new(data) end end private def get_default_flickr_photo_search_url(api_key, text, photos_per_page) text = URI.escape(text) "https://api.flickr.com/services/rest/?method=flickr.photos.search" + "&api_key=#{api_key}" + "&text=#{text}&per_page=#{photos_per_page}" + "&format=json" end def get_data_from_flickr(url) url = URI.parse(url) http = Net::HTTP.new(url.host, url.port) http.use_ssl = url.scheme == "https" request = Net::HTTP::Get.new(url) response= http.request(request) response.body end def filter_received_data(data) data = data.sub("jsonFlickrApi(", "") data = data.chomp(')') JSON.parse(data) end end
mit
Michayal/michayal.github.io
node_modules/mathjs/lib/entry/dependenciesNumber/dependenciesCompareText.generated.js
526
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.compareTextDependencies = void 0; var _dependenciesTyped = require("./dependenciesTyped.generated"); var _factoriesNumber = require("../../factoriesNumber.js"); /** * THIS FILE IS AUTO-GENERATED * DON'T MAKE CHANGES HERE */ var compareTextDependencies = { typedDependencies: _dependenciesTyped.typedDependencies, createCompareText: _factoriesNumber.createCompareText }; exports.compareTextDependencies = compareTextDependencies;
mit
glenngillen/s3backup-manager
lib/adapters/postgres_adapter.rb
1799
module S3BackupManager module PostgresAdapter def dump_database_to_file(username, database, directory) directory = "#{directory}/s3postgresbackup/#{database}" FileUtils.mkdir_p(directory) FileUtils.chmod_R 0770, directory FileUtils.chown_R nil, username, directory system "cd #{directory} && sudo -u #{username} vacuumdb -z #{database} >/dev/null 2>&1" exit(1) unless $?.success? dump_file = "#{directory}/#{database}.pgsql" system "cd #{directory} && sudo -u #{username} pg_dump --blobs --format=t #{database} > #{dump_file}" exit(1) unless $?.success? user_file = "#{directory}/globals.pgsql" system "cd #{directory} && sudo -u #{username} pg_dumpall -v -f #{user_file} --globals-only >/dev/null 2>&1" exit(1) unless $?.success? [directory] end def restore_database_from_file(username, database, directory) system "chown -R #{username} #{config[:temp_dir]}/#{database}" user_file = "#{directory}/globals.pgsql" system "cd #{config[:temp_dir]} && sudo -u #{username} psql -f #{user_file} >/dev/null 2>&1" unless $?.success? puts "Unable to load in the users" exit(1) end dump_file = "#{directory}/#{database}.pgsql" recreate_database!(username, database) system "cd #{config[:temp_dir]} && sudo -u #{username} pg_restore --format=t -d #{database} #{dump_file} >/dev/null 2>&1" unless $?.success? puts "Unable to restore database. Did you provide a username that has permission?" exit(1) end end private def recreate_database!(username, database) system "cd #{config[:temp_dir]} && sudo -u #{username} createdb --encoding=UNICODE #{database} > /dev/null 2>&1" end end end
mit
json-api-dotnet/JsonApiDotNetCore
test/JsonApiDotNetCoreTests/IntegrationTests/IdObfuscation/ObfuscatedIdentifiable.cs
488
using JsonApiDotNetCore.Resources; namespace JsonApiDotNetCoreTests.IntegrationTests.IdObfuscation; public abstract class ObfuscatedIdentifiable : Identifiable<int> { private static readonly HexadecimalCodec Codec = new(); protected override string? GetStringId(int value) { return value == default ? null : Codec.Encode(value); } protected override int GetTypedId(string? value) { return value == null ? default : Codec.Decode(value); } }
mit
hs634/algorithms
python/arrays/3sum-zero.py
955
__author__ = 'hs634' class Solution(): def __init__(self): pass def three_sum_zero(self, arr): arr, solution, i = sorted(arr), [], 0 while i < len(arr) - 2: j, k = i + 1, len(arr) - 1 while j < k: three_sum = arr[i] + arr[j] + arr[k] if three_sum < 0: j += 1 elif three_sum > 0: k -= 1 else: solution.append([arr[i], arr[j], arr[k]]) j, k = j + 1, k - 1 while j < k and arr[j] == arr[j - 1]: j += 1 while j < k and arr[k] == arr[k + 1]: k -= 1 i += 1 while i < len(arr) - 2 and arr[i] == arr[i - 1]: i += 1 return solution if __name__ == "__main__": solution = Solution().three_sum_zero([-1, 0, 1, 2, -1, -4])
mit
sinsoku/oauth_adapter
spec/spec_helper.rb
526
require 'simplecov' SimpleCov.start 'test_frameworks' if ENV['CI'] == 'true' require 'codecov' SimpleCov.formatter = SimpleCov::Formatter::Codecov end $LOAD_PATH.unshift File.expand_path('../../lib', __FILE__) require 'oauth' require 'oauth2' require 'oauth_adapter' # omniauth require 'omniauth' require 'oauth_adapter/omniauth' module OmniAuth module Strategies class Twitter include OmniAuth::Strategy option :client_options, { site: 'https://api.twitter.com', } end end end
mit
rstgroup/oauth2-client
src/Grant/ResourceOwnerPasswordCredentials/AccessTokenRequest.php
2703
<?php /** * @license http://opensource.org/licenses/BSD-3-Clause BSD-3-Clause * @copyright Copyright (c) 2015 Michał Kopacz. * @author Michał Kopacz <michalkopacz.mk@gmail.com> */ namespace MostSignificantBit\OAuth2\Client\Grant\ResourceOwnerPasswordCredentials; use MostSignificantBit\OAuth2\Client\AccessToken\AbstractRequest as AbstractAccessTokenRequest; use MostSignificantBit\OAuth2\Client\Parameter\GrantType; use MostSignificantBit\OAuth2\Client\Parameter\Password; use MostSignificantBit\OAuth2\Client\Parameter\Scope; use MostSignificantBit\OAuth2\Client\Parameter\Username; class AccessTokenRequest extends AbstractAccessTokenRequest { /** * OAuth2: REQUIRED * * @var Username */ protected $username; /** * OAuth2: REQUIRED * * @var Password */ protected $password; /** * OAuth2: OPTIONAL * * @var Scope */ protected $scope; public function __construct(Username $username, Password $password) { $this->setUsername($username); $this->setPassword($password); } /** * @return GrantType */ public function getGrantType() { return GrantType::PASSWORD(); } /** * @param \MostSignificantBit\OAuth2\Client\Parameter\Username $username */ public function setUsername($username) { $this->username = $username; } /** * @return \MostSignificantBit\OAuth2\Client\Parameter\Username */ public function getUsername() { return $this->username; } /** * @param \MostSignificantBit\OAuth2\Client\Parameter\Password $password */ public function setPassword($password) { $this->password = $password; } /** * @return \MostSignificantBit\OAuth2\Client\Parameter\Password */ public function getPassword() { return $this->password; } /** * @param \MostSignificantBit\OAuth2\Client\Parameter\Scope $scope */ public function setScope($scope) { $this->scope = $scope; } /** * @return \MostSignificantBit\OAuth2\Client\Parameter\Scope */ public function getScope() { return $this->scope; } /** * @return array */ public function getBodyParameters() { $params = array( 'grant_type' => $this->getGrantType()->getValue(), 'username' => $this->getUsername()->getValue(), 'password' => $this->getPassword()->getValue(), ); if ($this->getScope() !== null) { $params['scope'] = $this->getScope()->getScopeParameter(); } return $params; } }
mit
dbisUnibas/cineast
cineast-core/src/main/java/org/vitrivr/cineast/core/data/providers/AvgImgProvider.java
382
package org.vitrivr.cineast.core.data.providers; import org.vitrivr.cineast.core.data.raw.images.MultiImage; public interface AvgImgProvider { /** * * @return the aggregated pixel-wise average of multiple images. By default, the {@link MultiImage}.EMPTY_MULTIIMAGE is returned. */ public default MultiImage getAvgImg(){ return MultiImage.EMPTY_MULTIIMAGE; } }
mit
react-cosmos/fs-playground
src/__tests__/fileMocks/componentNamespace/Header/Hello.js
91
// @flow import React from 'react'; const Hello = () => <span />; export default Hello;
mit
cdaguerre/Sylius
src/Sylius/Behat/Context/Ui/Admin/ManagingProductVariantsContext.php
16603
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sylius\Behat\Context\Ui\Admin; use Behat\Behat\Context\Context; use Sylius\Behat\NotificationType; use Sylius\Behat\Page\Admin\ProductVariant\CreatePageInterface; use Sylius\Behat\Page\Admin\ProductVariant\GeneratePageInterface; use Sylius\Behat\Page\Admin\ProductVariant\IndexPageInterface; use Sylius\Behat\Page\Admin\ProductVariant\UpdatePageInterface; use Sylius\Behat\Service\NotificationCheckerInterface; use Sylius\Behat\Service\Resolver\CurrentPageResolverInterface; use Sylius\Behat\Service\SharedStorageInterface; use Sylius\Component\Core\Model\ProductInterface; use Sylius\Component\Core\Model\ProductVariantInterface; use Webmozart\Assert\Assert; /** * @author Łukasz Chruściel <lukasz.chrusciel@lakion.com> * @author Gorka Laucirica <gorka.lauzirika@gmail.com> */ final class ManagingProductVariantsContext implements Context { /** * @var SharedStorageInterface */ private $sharedStorage; /** * @var CreatePageInterface */ private $createPage; /** * @var IndexPageInterface */ private $indexPage; /** * @var UpdatePageInterface */ private $updatePage; /** * @var GeneratePageInterface */ private $generatePage; /** * @var CurrentPageResolverInterface */ private $currentPageResolver; /** * @var NotificationCheckerInterface */ private $notificationChecker; /** * @param SharedStorageInterface $sharedStorage * @param CreatePageInterface $createPage * @param IndexPageInterface $indexPage * @param UpdatePageInterface $updatePage * @param GeneratePageInterface $generatePage * @param CurrentPageResolverInterface $currentPageResolver * @param NotificationCheckerInterface $notificationChecker */ public function __construct( SharedStorageInterface $sharedStorage, CreatePageInterface $createPage, IndexPageInterface $indexPage, UpdatePageInterface $updatePage, GeneratePageInterface $generatePage, CurrentPageResolverInterface $currentPageResolver, NotificationCheckerInterface $notificationChecker ) { $this->sharedStorage = $sharedStorage; $this->createPage = $createPage; $this->indexPage = $indexPage; $this->updatePage = $updatePage; $this->generatePage = $generatePage; $this->currentPageResolver = $currentPageResolver; $this->notificationChecker = $notificationChecker; } /** * @Given /^I want to create a new variant of (this product)$/ */ public function iWantToCreateANewProduct(ProductInterface $product) { $this->createPage->open(['productId' => $product->getId()]); } /** * @When I specify its code as :code * @When I do not specify its code */ public function iSpecifyItsCodeAs($code = null) { $this->createPage->specifyCode($code); } /** * @When I name it :name in :language */ public function iNameItIn($name, $language) { $this->createPage->nameItIn($name, $language); } /** * @When I rename it to :name */ public function iRenameItTo($name) { $this->updatePage->nameIt($name); } /** * @When I add it * @When I try to add it */ public function iAddIt() { $this->createPage->create(); } /** * @When I disable its inventory tracking */ public function iDisableItsTracking() { $this->updatePage->disableTracking(); } /** * @When I enable its inventory tracking */ public function iEnableItsTracking() { $this->updatePage->enableTracking(); } /** * @When /^I set its(?:| default) price to "(?:€|£|\$)([^"]+)" for "([^"]+)" channel$/ * @When I do not set its price */ public function iSetItsPriceTo($price = null, $channelName = null) { $this->createPage->specifyPrice($price, (null === $channelName) ? $this->sharedStorage->get('channel') :$channelName); } /** * @When /^I set its original price to "(?:€|£|\$)([^"]+)" for "([^"]+)" channel$/ */ public function iSetItsOriginalPriceTo($originalPrice, $channelName) { $this->createPage->specifyOriginalPrice($originalPrice, $channelName); } /** * @When I set its height, width, depth and weight to :number */ public function iSetItsDimensionsTo($value) { $this->createPage->specifyHeightWidthDepthAndWeight($value, $value, $value, $value); } /** * @When I do not specify its current stock */ public function iDoNetSetItsCurrentStockTo() { $this->createPage->specifyCurrentStock(''); } /** * @When I choose :calculatorName calculator */ public function iChooseCalculator($calculatorName) { $this->createPage->choosePricingCalculator($calculatorName); } /** * @When I set its :optionName option to :optionValue */ public function iSetItsOptionAs($optionName, $optionValue) { $this->createPage->selectOption($optionName, $optionValue); } /** * @When I set the position of :name to :position */ public function iSetThePositionOfTo($name, $position) { $this->indexPage->setPosition($name, (int) $position); } /** * @When I save my new configuration */ public function iSaveMyNewConfiguration() { $this->indexPage->savePositions(); } /** * @Then /^the (variant with code "[^"]+") should be priced at (?:€|£|\$)([^"]+) for channel "([^"]+)"$/ */ public function theVariantWithCodeShouldBePricedAtForChannel(ProductVariantInterface $productVariant, $price, $channelName) { $this->updatePage->open(['id' => $productVariant->getId(), 'productId' => $productVariant->getProduct()->getId()]); Assert::same($this->updatePage->getPriceForChannel($channelName), $price); } /** * @Then /^the (variant with code "[^"]+") should be named "([^"]+)" in ("([^"]+)" locale)$/ */ public function theVariantWithCodeShouldBeNamedIn(ProductVariantInterface $productVariant, $name, $language) { $this->updatePage->open(['id' => $productVariant->getId(), 'productId' => $productVariant->getProduct()->getId()]); Assert::same($this->updatePage->getNameInLanguage($language), $name); } /** * @Then /^the (variant with code "[^"]+") should have an original price of (?:€|£|\$)([^"]+) for channel "([^"]+)"$/ */ public function theVariantWithCodeShouldHaveAnOriginalPriceOfForChannel(ProductVariantInterface $productVariant, $originalPrice, $channelName) { $this->updatePage->open(['id' => $productVariant->getId(), 'productId' => $productVariant->getProduct()->getId()]); Assert::same( $this->updatePage->getOriginalPriceForChannel($channelName), $originalPrice ); } /** * @When /^I delete the ("[^"]+" variant of product "[^"]+")$/ * @When /^I try to delete the ("[^"]+" variant of product "[^"]+")$/ */ public function iDeleteTheVariantOfProduct(ProductVariantInterface $productVariant) { $this->indexPage->open(['productId' => $productVariant->getProduct()->getId()]); $this->indexPage->deleteResourceOnPage(['code' => $productVariant->getCode()]); } /** * @Then I should be notified that this variant is in use and cannot be deleted */ public function iShouldBeNotifiedOfFailure() { $this->notificationChecker->checkNotification( 'Cannot delete, the product variant is in use.', NotificationType::failure() ); } /** * @When /^I want to modify the ("[^"]+" product variant)$/ */ public function iWantToModifyAProduct(ProductVariantInterface $productVariant) { $this->updatePage->open(['id' => $productVariant->getId(), 'productId' => $productVariant->getProduct()->getId()]); } /** * @Then the code field should be disabled */ public function theCodeFieldShouldBeDisabled() { Assert::true($this->updatePage->isCodeDisabled()); } /** * @Then I should be notified that :element is required */ public function iShouldBeNotifiedThatIsRequired($element) { $this->assertValidationMessage($element, sprintf('Please enter the %s.', $element)); } /** * @Then I should be notified that code has to be unique */ public function iShouldBeNotifiedThatCodeHasToBeUnique() { $this->assertValidationMessage('code', 'Product variant code must be unique.'); } /** * @Then I should be notified that current stock is required */ public function iShouldBeNotifiedThatOnHandIsRequired() { $this->assertValidationMessage('on_hand', 'Please enter on hand.'); } /** * @Then I should be notified that height, width, depth and weight cannot be lower than 0 */ public function iShouldBeNotifiedThatIsHeightWidthDepthWeightCannotBeLowerThan() { $this->assertValidationMessage('height', 'Height cannot be negative.'); $this->assertValidationMessage('width', 'Width cannot be negative.'); $this->assertValidationMessage('depth', 'Depth cannot be negative.'); $this->assertValidationMessage('weight', 'Weight cannot be negative.'); } /** * @Then I should be notified that price cannot be lower than 0.01 */ public function iShouldBeNotifiedThatPriceCannotBeLowerThen() { /** @var CreatePageInterface|UpdatePageInterface $currentPage */ $currentPage = $this->currentPageResolver->getCurrentPageWithForm([$this->createPage, $this->updatePage]); Assert::contains($currentPage->getPricesValidationMessage(), 'Price must be at least 0.01.'); } /** * @Then I should be notified that this variant already exists */ public function iShouldBeNotifiedThatThisVariantAlreadyExists() { /** @var CreatePageInterface|UpdatePageInterface $currentPage */ $currentPage = $this->currentPageResolver->getCurrentPageWithForm([$this->createPage, $this->updatePage]); Assert::same($currentPage->getValidationMessageForForm(), 'Variant with this option set already exists.'); } /** * @Then /^I should be notified that code is required for the (\d)(?:st|nd|rd|th) variant$/ */ public function iShouldBeNotifiedThatCodeIsRequiredForVariant($position) { Assert::same( $this->generatePage->getValidationMessage('code', $position - 1), 'Please enter the code.' ); } /** * @Then /^I should be notified that prices in all channels must be defined for the (\d)(?:st|nd|rd|th) variant$/ */ public function iShouldBeNotifiedThatPricesInAllChannelsMustBeDefinedForTheVariant($position) { Assert::same( $this->generatePage->getPricesValidationMessage($position - 1), 'You must define price for every channel.' ); } /** * @Then /^I should be notified that variant code must be unique within this product for the (\d)(?:st|nd|rd|th) variant$/ */ public function iShouldBeNotifiedThatVariantCodeMustBeUniqueWithinThisProductForYheVariant($position) { Assert::same( $this->generatePage->getValidationMessage('code', $position - 1), 'This code must be unique within this product.' ); } /** * @Then I should be notified that prices in all channels must be defined */ public function iShouldBeNotifiedThatPricesInAllChannelsMustBeDefined() { Assert::contains( $this->createPage->getPricesValidationMessage(), 'You must define price for every channel.' ); } /** * @When I save my changes * @When I try to save my changes */ public function iSaveMyChanges() { $this->updatePage->saveChanges(); } /** * @When I remove its name */ public function iRemoveItsNameFromTranslation() { $this->updatePage->nameIt(''); } /** * @Then /^inventory of (this variant) should not be tracked$/ */ public function thisProductVariantShouldNotBeTracked(ProductVariantInterface $productVariant) { $this->iWantToModifyAProduct($productVariant); Assert::false($this->updatePage->isTracked()); } /** * @Then /^inventory of (this variant) should be tracked$/ */ public function thisProductVariantShouldBeTracked(ProductVariantInterface $productVariant) { $this->iWantToModifyAProduct($productVariant); Assert::true($this->updatePage->isTracked()); } /** * @When /^I want to generate new variants for (this product)$/ */ public function iWantToGenerateNewVariantsForThisProduct(ProductInterface $product) { $this->generatePage->open(['productId' => $product->getId()]); } /** * @When I generate it * @When I try to generate it */ public function iClickGenerate() { $this->generatePage->generate(); } /** * @When /^I specify that the (\d)(?:st|nd|rd|th) variant is identified by "([^"]+)" code and costs "(?:€|£|\$)([^"]+)" in ("[^"]+") channel$/ */ public function iSpecifyThereAreVariantsIdentifiedByCodeWithCost($nthVariant, $code, $price, $channelName) { $this->generatePage->specifyCode($nthVariant - 1, $code); $this->generatePage->specifyPrice($nthVariant - 1, $price, $channelName); } /** * @When /^I specify that the (\d)(?:st|nd|rd|th) variant is identified by "([^"]+)" code$/ */ public function iSpecifyThereAreVariantsIdentifiedByCode($nthVariant, $code) { $this->generatePage->specifyCode($nthVariant - 1, $code); } /** * @When /^I specify that the (\d)(?:st|nd|rd|th) variant costs "(?:€|£|\$)([^"]+)" in ("[^"]+") channel$/ */ public function iSpecifyThereAreVariantsWithCost($nthVariant, $price, $channelName) { $this->generatePage->specifyPrice($nthVariant - 1, $price, $channelName); } /** * @When /^I remove (\d)(?:st|nd|rd|th) variant from the list$/ */ public function iRemoveVariantFromTheList($nthVariant) { $this->generatePage->removeVariant($nthVariant - 1); } /** * @Then I should be notified that it has been successfully generated */ public function iShouldBeNotifiedThatItHasBeenSuccessfullyGenerated() { $this->notificationChecker->checkNotification('Success Product variants have been successfully generated.', NotificationType::success()); } /** * @When I set its shipping category as :shippingCategoryName */ public function iSetItsShippingCategoryAs($shippingCategoryName) { $this->createPage->selectShippingCategory($shippingCategoryName); } /** * @When I do not specify any information about variants */ public function iDoNotSpecifyAnyInformationAboutVariants() { // Intentionally left blank to fulfill context expectation } /** * @When I change its quantity of inventory to :amount */ public function iChangeItsQuantityOfInventoryTo($amount) { $this->updatePage->specifyCurrentStock($amount); } /** * @Then I should be notified that on hand quantity must be greater than the number of on hold units */ public function iShouldBeNotifiedThatOnHandQuantityMustBeGreaterThanTheNumberOfOnHoldUnits() { Assert::same( $this->updatePage->getValidationMessage('on_hand'), 'On hand must be greater than the number of on hold units' ); } /** * @param string $element * @param $message */ private function assertValidationMessage($element, $message) { /** @var CreatePageInterface|UpdatePageInterface $currentPage */ $currentPage = $this->currentPageResolver->getCurrentPageWithForm([$this->createPage, $this->updatePage]); Assert::same($currentPage->getValidationMessage($element), $message); } }
mit
Heufneutje/RE_HeufyBot
src/heufybot/core/Logger.java
2052
package heufybot.core; import heufybot.utils.FileUtils; import heufybot.utils.StringUtils; import java.nio.file.Path; import java.nio.file.Paths; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; public class Logger { public static void log(String line, String target, String network) { String baseLogPath = HeufyBot.getInstance().getGlobalConfig() .getSettingWithDefault("logPath", "logs"); // Timestamp line DateFormat dateFormat = new SimpleDateFormat("[HH:mm]"); Date date = new Date(); // Output to console String consoleLogLine = ""; if (target == null) { consoleLogLine = dateFormat.format(date) + " " + line; } else { consoleLogLine = dateFormat.format(date) + " " + target + "@" + network + " - " + line; } consoleLogLine = StringUtils.toValid3ByteUTF8String(consoleLogLine); System.out.println(consoleLogLine); // Output to logfile Path path = Paths.get(baseLogPath).toAbsolutePath(); if (network == null) { FileUtils.writeFileAppend(path.resolve("server.log").toString(), consoleLogLine + "\n"); } else { FileUtils.touchDir(path.resolve(network + "/" + target).toString()); line = dateFormat.format(date) + " " + line; dateFormat = new SimpleDateFormat("yyyy-MM-dd"); FileUtils.writeFileAppend( path.resolve(network + "/" + target + "/" + dateFormat.format(date) + ".log") .toString(), line + "\n"); } } public static void log(String line) { log(line, null, null); } public static void error(String errorSource, String line) { DateFormat dateFormat = new SimpleDateFormat("[HH:mm]"); Date date = new Date(); System.err.println(dateFormat.format(date) + " " + errorSource + " - ERROR: " + line); } }
mit
DigitalMachinist/ConcurrentBinaryMinHeap
docs/html/search/properties_0.js
436
var searchData= [ ['capacity',['Capacity',['../classca_1_1axoninteractive_1_1_collections_1_1_concurrent_binary_min_heap.html#a7eed25e728d4a4706008f3a14ef12a76',1,'ca::axoninteractive::Collections::ConcurrentBinaryMinHeap']]], ['count',['Count',['../classca_1_1axoninteractive_1_1_collections_1_1_concurrent_binary_min_heap.html#a5e16fd3fa2df28a4756a800aa797e241',1,'ca::axoninteractive::Collections::ConcurrentBinaryMinHeap']]] ];
mit
firelizzard18/Tea-Service
server/DBusServer.go
2871
package server import ( "errors" "log" "github.com/godbus/dbus" "github.com/firelizzard18/Tea-Service/common" ) type DBusServer struct { proc *Process path dbus.ObjectPath bus *dbus.Conn closed bool } func ExportToDBus(proc *Process, bus string) error { s := new(DBusServer) s.closed = false s.proc = proc proc.exported = s var err error switch bus { case "session": s.bus, err = dbus.SessionBus() case "system": s.bus, err = dbus.SystemBus() default: s.bus, err = dbus.Dial(bus) } if err != nil { return err } if !s.bus.SupportsUnixFDs() { return errors.New("DBus connection does not support file descriptors") } s.path = dbus.ObjectPath("/com/firelizzard/teasvc/Server") go s.handleSignals() err = s.bus.Export(s, s.path, "com.firelizzard.teasvc.Server") if err != nil { return err } c := s.bus.BusObject().Call("org.freedesktop.DBus.AddMatch", 0, "type='signal',interface='com.firelizzard.teasvc',member='Ping'") if c.Err != nil { return c.Err } return nil } func (s *DBusServer) Close() error { if s.closed { return nil } s.closed = true return s.bus.Close() } func (s *DBusServer) handleSignals() { ch := make(chan *dbus.Signal, 50) s.bus.Signal(ch) for sig := range ch { if sig.Name == "com.firelizzard.teasvc.Ping" { err := s.bus.Emit(s.path, "com.firelizzard.teasvc.Pong", s.proc.Description) if err != nil { log.Print(err) } } } } func newError(name string, body ...interface{}) *dbus.Error { return dbus.NewError(name, body) } func (s *DBusServer) RequestOutput(sender dbus.Sender, otype byte) (output dbus.UnixFD, derr *dbus.Error) { if s.closed { panic("closed") } output = -1 outPipe, err := s.proc.RequestOutput(common.OutputType(otype)) if err != nil { derr = newError("com.firelizzard.teasvc.Server.RequestOutputFailure", err.Error()) return } if outPipe != nil { output = dbus.UnixFD(outPipe.Fd()) } return } func (s *DBusServer) RequestCommand(sender dbus.Sender, otype byte) (input, output dbus.UnixFD, derr *dbus.Error) { if s.closed { panic("closed") } input = -1 output = -1 inPipe, outPipe, err := s.proc.RequestCommand(common.OutputType(otype)) if err != nil { derr = newError("com.firelizzard.teasvc.Server.RequestCommandFailure", err.Error()) return } if inPipe != nil { input = dbus.UnixFD(inPipe.Fd()) } if outPipe != nil { output = dbus.UnixFD(outPipe.Fd()) } return } func (s *DBusServer) SendCommand(sender dbus.Sender, otype byte, command string) (output dbus.UnixFD, derr *dbus.Error) { if s.closed { panic("closed") } output = -1 outPipe, err := s.proc.SendCommand(common.OutputType(otype), command) if err != nil { derr = newError("com.firelizzard.teasvc.Server.SendCommandFailure", err.Error()) return } if outPipe != nil { output = dbus.UnixFD(outPipe.Fd()) } return }
mit
auth0/webtask-widget
src/widgets/editor.js
605
import Editor from 'components/editor'; import AuthenticatedWidget from 'lib/authenticatedWidget'; export default class EditorWidget extends AuthenticatedWidget { constructor(options) { super(Editor, { events: { save: 'onSave', run: 'onRun', }, hotkeys: { 'Mod-Enter': e => this.run(), 'Mod-s': e => this.save(), }, ...options }); } run() { return this._enqueue('run'); } save() { return this._enqueue('save'); } }
mit
IMAMBAKS/data_viz_pa
tasks/build.js
2454
var gulp = require('gulp'); var runSequence = require('run-sequence'); var config = require('../gulp.config')(); var inject = require('gulp-inject'); var useref = require('gulp-useref'); var gulpif = require('gulp-if'); var rev = require('gulp-rev'); var revReplace = require('gulp-rev-replace'); var uglify = require('gulp-uglify'); var cssnano = require('gulp-cssnano'); var Builder = require('systemjs-builder'); /* Prepare build using SystemJS Builder */ gulp.task('build', function (done) { runSequence('test', 'build-sjs', done); }); gulp.task('build-sjs', function (done) { runSequence('build-assets', 'tsc-app', buildSJS); function buildSJS () { var builder = new Builder(); builder.loadConfig('./systemjs.conf.js') .then(function() { return builder .bundle(config.app + 'main.js', config.build.path + config.app + 'main.js', config.systemJs.builder); }) .then(function() { console.log('Build complete'); done(); }) .catch(function (ex) { console.log('error', ex); done('Build failed.'); }); } }); /* Concat and minify/uglify all css, js, and copy fonts */ gulp.task('build-assets', function (done) { runSequence('clean-build', ['sass', 'fonts'], function () { done(); gulp.src(config.app + '**/*.html', { base: config.app }) .pipe(gulp.dest(config.build.app)); gulp.src(config.app + '**/*.css', { base: config.app }) .pipe(cssnano()) .pipe(gulp.dest(config.build.app)); gulp.src(config.assetsPath.images + '**/*.*', { base: config.assetsPath.images }) .pipe(gulp.dest(config.build.assetPath + 'images')); return gulp.src(config.index) .pipe(useref()) .pipe(gulpif('*.js', uglify())) .pipe(gulpif('*.css', cssnano())) .pipe(gulpif('!*.html', rev())) .pipe(revReplace()) .pipe(gulp.dest(config.build.path)); }); }); /* Copy fonts in packages */ gulp.task('fonts', function () { gulp.src(config.assetsPath.fonts + '**/*.*', { base: config.assetsPath.fonts }) .pipe(gulp.dest(config.build.fonts)); gulp.src([ 'node_modules/font-awesome/fonts/*.*' ]) .pipe(gulp.dest(config.build.fonts)); });
mit
bruceadams/isthereacapsgame
test/test_day_name.rb
3346
require_relative './helper' require_relative '../helpers' class TestDayNames < TestCapsApp def test_monday get '/monday' assert_equal 200, last_response.status end def test_tuesday get '/tuesday' assert_equal 200, last_response.status end def test_wednesday get '/wednesday' assert_equal 200, last_response.status end def test_thursday get '/thursday' assert_equal 200, last_response.status end def test_friday get '/friday' assert_equal 200, last_response.status end def test_saturday get '/saturday' assert_equal 200, last_response.status end def test_sunday get '/sunday' assert_equal 200, last_response.status end end class TestDayNamesFunkyCaps < TestCapsApp def test_monday get '/MoNdAY' assert_equal 200, last_response.status end def test_tuesday get '/TUESDAY' assert_equal 200, last_response.status end def test_wednesday get '/WEDnesDAY' assert_equal 200, last_response.status end def test_thursday get '/THurSDay' assert_equal 200, last_response.status end def test_friday get '/FRIday' assert_equal 200, last_response.status end def test_saturday get '/SATurdAy' assert_equal 200, last_response.status end def test_sunday get '/SUNDAy' assert_equal 200, last_response.status end end class TestDynamicDayResponse < TestCapsApp def test_monday get '/monday' doc = Nokogiri::HTML(last_response.body) body = doc.xpath('//p//text()').text assert body.include?('Monday?'), body end def test_tuesday get '/tuesday' doc = Nokogiri::HTML(last_response.body) body = doc.xpath('//p//text()').text assert body.include?('Tuesday?'), body end def test_wednesday get '/wednesday' doc = Nokogiri::HTML(last_response.body) body = doc.xpath('//p//text()').text assert body.include?('Wednesday?'), body end def test_thursday get '/thursday' doc = Nokogiri::HTML(last_response.body) body = doc.xpath('//p//text()').text assert body.include?('Thursday?'), body end def test_friday get '/friday' doc = Nokogiri::HTML(last_response.body) body = doc.xpath('//p//text()').text assert body.include?('Friday?'), body end def test_saturday get '/saturday' doc = Nokogiri::HTML(last_response.body) body = doc.xpath('//p//text()').text assert body.include?('Saturday?'), body end def test_sunday get '/sunday' doc = Nokogiri::HTML(last_response.body) body = doc.xpath('//p//text()').text assert body.include?('Sunday?'), body end end class TestDayJumpsOverToday < TestCapsApp def test_today_is_skipped_over today = DateTime.now # in order to get at the helper method, I need some sleight-of-hand next_today = Caps.new!.get_named_day(today.strftime("%A")) assert today != next_today end def test_next_week_this_day require 'date' today = DateTime.strptime(DateTime.now.strftime("%Y%m%d"), fmt="%Y%m%d") # in order to get at the helper method, I need some sleight-of-hand next_today = Caps.new!.get_named_day(today.strftime("%A")) 7.times do today = today.next_day end assert today.eql?(next_today), "#{today.strftime("%Y%m%d")} #{next_today.strftime("%Y%m%d")}" end end
mit
vpopolitov/api_caller
lib/api_caller/service.rb
2230
module ApiCaller class Service class << self def decorate_request(route_name = :all, with: ApiCaller::Decorator) request_decorators << with.new(route_name) end def remove_request_decorators(route_name = :all) request_decorators.delete_if { |d| [d.route_name, :all].include? route_name } end def decorate_response(route_name = :all, with: ApiCaller::Decorator) response_decorators << with.new(route_name) end def remove_response_decorators(route_name = :all) response_decorators.delete_if { |d| [d.route_name, :all].include? route_name } end def use_base_url(url) @base_url = url end def use_http_adapter(http_adapter) @http_adapter = http_adapter end def get(url_template, params = {}) route_name = params[:as] raise ApiCaller::Error::MissingRouteName, route_name unless route_name routes[route_name] = Route.new template: url_template, http_verb: :get end def call(route_name, params = {}, message_http_adapter = nil) route = routes[route_name] raise ApiCaller::Error::MissingRoute, route_name unless route params = request_decorators.inject(params) { |req, decorator| decorator.execute(req, route_name) } context = ApiCaller::Context.new(base_url: base_url, raw_params: params) req = route.build_request(context) res = ApiCaller::Client.new(message_http_adapter || http_adapter).build_response(req) res = response_decorators.inject(res) { |res, decorator| decorator.execute(res, route_name) } res end def configure(&block) class_eval &block if block_given? end private def routes @routes ||= {} end def base_url @base_url ||= '' end def http_adapter @http_adapter ||= ApiCaller::http_adapter || Faraday.new do |builder| builder.response :logger builder.adapter Faraday.default_adapter end end def request_decorators @request_decorators ||= [] end def response_decorators @response_decorators ||= [] end end end end
mit
Invizible/Catdogtion
src/main/java/com/github/invizible/catdogtion/config/WebSocketConfig.java
921
package com.github.invizible.catdogtion.config; import org.springframework.context.annotation.Configuration; import org.springframework.messaging.simp.config.MessageBrokerRegistry; import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer; import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; import org.springframework.web.socket.config.annotation.StompEndpointRegistry; @Configuration @EnableWebSocketMessageBroker public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer { @Override public void registerStompEndpoints(StompEndpointRegistry registry) { registry.addEndpoint("/ws") .setAllowedOrigins("*"); } @Override public void configureMessageBroker(MessageBrokerRegistry registry) { registry.setApplicationDestinationPrefixes("/app"); registry.enableSimpleBroker("/topic", "/queue"); } }
mit
mixer/interactive-java
src/test/java/com/mixer/interactive/test/integration/resource/InteractiveResourceIntegrationTest.java
9016
package com.mixer.interactive.test.integration.resource; import com.google.gson.JsonObject; import com.mixer.interactive.GameClient; import com.mixer.interactive.resources.group.InteractiveGroup; import com.mixer.interactive.test.util.TestEventHandler; import com.mixer.interactive.test.util.TestUtils; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.stream.Collectors; import static com.mixer.interactive.GameClient.GROUP_SERVICE_PROVIDER; import static com.mixer.interactive.test.util.TestUtils.*; /** * Tests <code>InteractiveResource</code> changes to meta properties. * * @author Microsoft Corporation * * @since 2.0.0 */ public class InteractiveResourceIntegrationTest { /** * <code>GameClient</code> that connects to an Interactive integration that contains multiple scenes that all * contain controls */ private static GameClient gameClient; @Before public void setupGameClient() { gameClient = new GameClient(INTERACTIVE_PROJECT_ID, TestUtils.CLIENT_ID); gameClient.getEventBus().register(TestEventHandler.HANDLER); } @After public void teardownGameClient() { TestEventHandler.HANDLER.clear(); gameClient.disconnect(); gameClient = null; } @Test public void can_create_with_meta_properties() { try { InteractiveGroup group = new InteractiveGroup("awesome-group") .addMetaProperty("awesome-property", "awesome-value"); Set<InteractiveGroup> groups = gameClient.connectTo(OAUTH_BEARER_TOKEN, INTERACTIVE_SERVICE_URI) .thenCompose(connected -> gameClient.using(GROUP_SERVICE_PROVIDER).create(group)) .thenCompose(created -> gameClient.using(GROUP_SERVICE_PROVIDER).getGroups()) .get(); Assert.assertEquals("The resource was created", new HashSet<>(Collections.singletonList(group.getGroupID())), groups.stream().filter(group1 -> !"default".equals(group1.getGroupID())).map(InteractiveGroup::getGroupID).collect(Collectors.toSet())); Assert.assertEquals("The resource has the expected meta properties", true, groups.stream().anyMatch(interactiveGroup -> group.getGroupID().equals(interactiveGroup.getGroupID()) && ((JsonObject) group.getMeta().get("awesome-property")).get("value").getAsString().equals("awesome-value"))); } catch (InterruptedException | ExecutionException e) { Assert.fail(e.getMessage()); } } @Test public void can_add_a_meta_property() { try { InteractiveGroup group = new InteractiveGroup("awesome-group"); Set<InteractiveGroup> updatedGroups = gameClient.connectTo(OAUTH_BEARER_TOKEN, INTERACTIVE_SERVICE_URI) .thenCompose(connected -> gameClient.using(GROUP_SERVICE_PROVIDER).create(group)) .thenCompose(created -> { group.addMetaProperty("awesome-property", "awesome-value"); return gameClient.using(GROUP_SERVICE_PROVIDER).update(group); }) .get(); Assert.assertEquals("Only the expected resource was updated", new HashSet<>(Collections.singletonList(group.getGroupID())), updatedGroups.stream().map(InteractiveGroup::getGroupID).collect(Collectors.toSet())); Assert.assertEquals("The resource has the expected meta properties", true, updatedGroups.stream().anyMatch(interactiveGroup -> group.getGroupID().equals(interactiveGroup.getGroupID()) && ((JsonObject) group.getMeta().get("awesome-property")).get("value").getAsString().equals("awesome-value"))); } catch (InterruptedException | ExecutionException e) { Assert.fail(e.getMessage()); } } @Test public void can_change_a_meta_property() { try { InteractiveGroup group = new InteractiveGroup("awesome-group") .addMetaProperty("awesome-property", "awesome-value") .addMetaProperty("other-property", "other-value"); Set<InteractiveGroup> groups = gameClient.connectTo(OAUTH_BEARER_TOKEN, INTERACTIVE_SERVICE_URI) .thenCompose(connected -> gameClient.using(GROUP_SERVICE_PROVIDER).create(group)) .thenCompose(created -> { JsonObject metaObject = group.getMeta(); metaObject.addProperty("other-property", 4); group.setMeta(metaObject); return gameClient.using(GROUP_SERVICE_PROVIDER).update(group); }) .thenCompose(created -> gameClient.using(GROUP_SERVICE_PROVIDER).getGroups()) .get(); Assert.assertEquals("The resource was updated", new HashSet<>(Collections.singletonList(group.getGroupID())), groups.stream().filter(group1 -> !"default".equals(group1.getGroupID())).map(InteractiveGroup::getGroupID).collect(Collectors.toSet())); Assert.assertEquals("The resource has the expected meta properties", true, groups.stream().anyMatch(updatedGroup -> group.getGroupID().equals(updatedGroup.getGroupID()) && group.getMeta().get("other-property").getAsNumber().equals(4))); } catch (InterruptedException | ExecutionException e) { Assert.fail(e.getMessage()); } } @Test public void can_remove_a_meta_property() { try { InteractiveGroup group = new InteractiveGroup("awesome-group") .addMetaProperty("awesome-property", "awesome-value") .addMetaProperty("other-property", "other-value"); Set<InteractiveGroup> groups = gameClient.connectTo(OAUTH_BEARER_TOKEN, INTERACTIVE_SERVICE_URI) .thenCompose(connected -> gameClient.using(GROUP_SERVICE_PROVIDER).create(group)) .thenCompose(created -> { JsonObject metaObject = group.getMeta(); metaObject.remove("other-property"); group.setMeta(metaObject); return gameClient.using(GROUP_SERVICE_PROVIDER).update(group); }) .thenCompose(created -> gameClient.using(GROUP_SERVICE_PROVIDER).getGroups()) .get(); Assert.assertEquals("The resource was updated", new HashSet<>(Collections.singletonList(group.getGroupID())), groups.stream().filter(group1 -> !"default".equals(group1.getGroupID())).map(InteractiveGroup::getGroupID).collect(Collectors.toSet())); Assert.assertEquals("The resource has the expected meta properties", true, groups.stream().anyMatch(updatedGroup -> group.getGroupID().equals(updatedGroup.getGroupID()) && ((JsonObject) group.getMeta().get("awesome-property")).get("value").getAsString().equals("awesome-value"))); } catch (InterruptedException | ExecutionException e) { Assert.fail(e.getMessage()); } } @Test public void can_remove_all_meta_properties() { try { InteractiveGroup group = new InteractiveGroup("awesome-group") .addMetaProperty("awesome-property", "awesome-value"); Set<InteractiveGroup> groups = gameClient.connectTo(OAUTH_BEARER_TOKEN, INTERACTIVE_SERVICE_URI) .thenCompose(connected -> gameClient.using(GROUP_SERVICE_PROVIDER).create(group)) .thenCompose(created -> { group.setMeta(null); return gameClient.using(GROUP_SERVICE_PROVIDER).update(group); }) .thenCompose(created -> gameClient.using(GROUP_SERVICE_PROVIDER).getGroups()) .get(); Assert.assertEquals("The resource was updated", new HashSet<>(Collections.singletonList(group.getGroupID())), groups.stream().filter(group1 -> !"default".equals(group1.getGroupID())).map(InteractiveGroup::getGroupID).collect(Collectors.toSet())); Assert.assertEquals("The resource has the expected meta properties", true, groups.stream().anyMatch(updatedGroup -> group.getGroupID().equals(updatedGroup.getGroupID()) && group.getMeta() == null)); } catch (InterruptedException | ExecutionException e) { Assert.fail(e.getMessage()); } } }
mit
hpsanampudi/Ducksoft.Soa.Common
DataContracts/BatchTaskResult.cs
859
using System; using System.Runtime.Serialization; using System.Threading.Tasks; namespace Ducksoft.SOA.Common.DataContracts { /// <summary> /// Data class which is used to store async task result related information. /// </summary> [DataContract(Name = "BatchTaskResult", Namespace = "http://ducksoftware.co.uk/SOA/WCF/DataContracts")] public class BatchTaskResult { /// <summary> /// Gets or sets the status. /// </summary> /// <value> /// The status. /// </value> [DataMember] public TaskStatus Status { get; set; } /// <summary> /// Gets or sets the exception. /// </summary> /// <value> /// The exception. /// </value> [DataMember] public AggregateException Exception { get; set; } } }
mit
lizconlan/indextank-demo
models/hansard_page.rb
1431
require 'nokogiri' require 'rest-client' class HansardPage attr_reader :html, :doc, :url, :next_url, :start_column, :end_column, :volume, :part, :title def initialize(url) @url = url response = RestClient.get(url) @html = response.body @doc = Nokogiri::HTML(@html) next_link = [] if @doc.xpath("//div[@class='navLinks']").empty? next_link = @doc.xpath("//table").last.xpath("tr/td/a[text()='Next Section']") elsif @doc.xpath("//div[@class='navLinks'][2]").empty? next_link = @doc.xpath("//div[@class='navLinks'][1]/div[@class='navLeft']/a") else next_link = @doc.xpath("//div[@class='navLinks'][2]/div[@class='navLeft']/a") end unless next_link.empty? prefix = url[0..url.rindex("/")] @next_url = prefix + next_link.attr("href").value.to_s else @next_url = nil end scrape_metadata() end private def scrape_metadata subject = doc.xpath("//meta[@name='Subject']").attr("content").value.to_s column_range = doc.xpath("//meta[@name='Columns']").attr("content").value.to_s cols = column_range.gsub("Columns: ", "").split(" to ") @start_column = cols[0] @end_column = cols[1] @volume = subject[subject.index("Volume:")+8..subject.rindex(",")-1] @part = subject[subject.index("Part:")+5..subject.length].gsub("\302\240", "") @title = doc.xpath("//head/title").text.strip end end
mit
dhpm/dhpm-go-spidermonkey
ErrorReport.cpp
711
#include "ErrorReport.h" ErrorReport::ErrorReport(JSContext *cx, const char *message, JSErrorReport *report) { this->context = context; this->message = message; this->report = report; } const char* ErrorReport::GetStackTrace() { jsval v; if (!this->IsException() || !JS_GetPendingException(this->context, &v)) { return ""; } JSString *jsStackTrace; JS_ClearPendingException(this->context); JS_GetProperty(this->context, JSVAL_TO_OBJECT(v), "stack", &v); jsStackTrace = JS_ValueToString(this->context, v); return JS_EncodeString(this->context, jsStackTrace); } bool ErrorReport::IsException() { return JSREPORT_IS_EXCEPTION(this->report->flags); }
mit
hiro4bbh/hako.rb
lib/hako/libc.rb
725
require 'ffi' module LibC extend FFI::Library ffi_lib FFI::Library::LIBC # int memcmp(const void *s1, const void *s2, size_t n); attach_function :memcmp, [:pointer, :pointer, :size_t], :int # void *memset(void *b, int c, size_t len); attach_function :memset, [:pointer, :pointer, :size_t], :void # void memset_pattern4(void *b, const void *c4, size_t len); attach_function :memset_pattern4, [:pointer, :pointer, :size_t], :void # void memset_pattern8(void *b, const void *c8, size_t len); attach_function :memset_pattern8, [:pointer, :pointer, :size_t], :void # void memset_pattern16(void *b, const void *c16, size_t len); attach_function :memset_pattern16, [:pointer, :pointer, :size_t], :void end
mit
efgm1024/SysPGPP
migrations/m151211_122625_create_campus.php
519
<?php use yii\db\Schema; use yii\db\Migration; class m151211_122625_create_campus extends Migration { public function up() { $this->createTable('campus', [ 'id' => $this->primaryKey(), 'name' => $this->string()->notNull(), ]); } public function down() { $this->dropTable('campus'); } /* // Use safeUp/safeDown to run migration code within a transaction public function safeUp() { } public function safeDown() { } */ }
mit
kentor/notejs-react
webpack.prod.js
144
const common = require('./webpack.common'); const merge = require('webpack-merge'); module.exports = merge(common, { mode: 'production', });
mit
nooproblem/influxdb
pkg/csv2lp/csv2lp_test.go
5361
package csv2lp import ( "bytes" "errors" "io" "io/ioutil" "log" "os" "strconv" "strings" "testing" "github.com/stretchr/testify/require" ) // Test_CsvToLineProtocol tests conversion of annotated CSV data to line protocol data func Test_CsvToLineProtocol(t *testing.T) { var tests = []struct { name string csv string lines string err string }{ { "simple1", "_measurement,a,b\ncpu,1,1\ncpu,b2\n", "cpu a=1,b=1\ncpu a=b2\n", "", }, { "simple1_withSep", "sep=;\n_measurement;a;b\ncpu;1;1\ncpu;b2\n", "cpu a=1,b=1\ncpu a=b2\n", "", }, { "simple2", "_measurement,a,b\ncpu,1,1\ncpu,\n", "", "no field data", }, { "simple3", "_measurement,a,_time\ncpu,1,1\ncpu,2,invalidTime\n", "", "_time", // error in _time column }, { "constant_annotations", "#constant,measurement,,cpu\n" + "#constant,tag,xpu,xpu1\n" + "#constant,tag,cpu,cpu1\n" + "#constant,long,of,100\n" + "#constant,dateTime,,2\n" + "x,y\n" + "1,2\n" + "3,4\n", "cpu,cpu=cpu1,xpu=xpu1 x=1,y=2,of=100i 2\n" + "cpu,cpu=cpu1,xpu=xpu1 x=3,y=4,of=100i 2\n", "", // no error }, { "timezone_annotation-0100", "#timezone,-0100\n" + "#constant,measurement,cpu\n" + "#constant,dateTime:2006-01-02,1970-01-01\n" + "x,y\n" + "1,2\n", "cpu x=1,y=2 3600000000000\n", "", // no error }, { "timezone_annotation_EST", "#timezone,EST\n" + "#constant,measurement,cpu\n" + "#constant,dateTime:2006-01-02,1970-01-01\n" + "x,y\n" + "1,2\n", "cpu x=1,y=2 18000000000000\n", "", // no error }, } bufferSizes := []int{40, 7, 3, 1} for _, test := range tests { for _, bufferSize := range bufferSizes { t.Run(test.name+"_"+strconv.Itoa(bufferSize), func(t *testing.T) { reader := CsvToLineProtocol(strings.NewReader(test.csv)) buffer := make([]byte, bufferSize) lines := make([]byte, 0, 100) for { n, err := reader.Read(buffer) if err != nil { if err == io.EOF { break } if test.err != "" { // fmt.Println(err) if err := err.Error(); !strings.Contains(err, test.err) { require.Equal(t, err, test.err) } return } require.Nil(t, err.Error()) break } lines = append(lines, buffer[:n]...) } if test.err == "" { require.Equal(t, test.lines, string(lines)) } else { require.Fail(t, "error message with '"+test.err+"' expected") } }) } } } // Test_CsvToLineProtocol_LogTableColumns checks correct logging of table columns func Test_CsvToLineProtocol_LogTableColumns(t *testing.T) { var buf bytes.Buffer log.SetOutput(&buf) oldFlags := log.Flags() log.SetFlags(0) oldPrefix := log.Prefix() prefix := "::PREFIX::" log.SetPrefix(prefix) defer func() { log.SetOutput(os.Stderr) log.SetFlags(oldFlags) log.SetPrefix(oldPrefix) }() csv := "_measurement,a,b\ncpu,1,1\ncpu,b2\n" reader := CsvToLineProtocol(strings.NewReader(csv)).LogTableColumns(true) require.False(t, reader.skipRowOnError) require.True(t, reader.logTableDataColumns) // read all the data ioutil.ReadAll(reader) out := buf.String() // fmt.Println(out) messages := strings.Count(out, prefix) require.Equal(t, messages, 1) } // Test_CsvToLineProtocol_LogTimeZoneWarning checks correct logging of timezone warning func Test_CsvToLineProtocol_LogTimeZoneWarning(t *testing.T) { var buf bytes.Buffer log.SetOutput(&buf) oldFlags := log.Flags() log.SetFlags(0) oldPrefix := log.Prefix() prefix := "::PREFIX::" log.SetPrefix(prefix) defer func() { log.SetOutput(os.Stderr) log.SetFlags(oldFlags) log.SetPrefix(oldPrefix) }() csv := "#timezone 1\n" + "#constant,dateTime:2006-01-02,1970-01-01\n" + "_measurement,a,b\ncpu,1,1" reader := CsvToLineProtocol(strings.NewReader(csv)) bytes, _ := ioutil.ReadAll(reader) out := buf.String() // fmt.Println(out) // "::PREFIX::WARNING: #timezone annotation: unknown time zone 1 messages := strings.Count(out, prefix) require.Equal(t, messages, 1) require.Equal(t, string(bytes), "cpu a=1,b=1 0\n") } // Test_CsvToLineProtocol_SkipRowOnError tests that error rows are skipped func Test_CsvToLineProtocol_SkipRowOnError(t *testing.T) { var buf bytes.Buffer log.SetOutput(&buf) oldFlags := log.Flags() log.SetFlags(0) oldPrefix := log.Prefix() prefix := "::PREFIX::" log.SetPrefix(prefix) defer func() { log.SetOutput(os.Stderr) log.SetFlags(oldFlags) log.SetPrefix(oldPrefix) }() csv := "_measurement,a,_time\n,1,1\ncpu,2,2\ncpu,3,3a\n" reader := CsvToLineProtocol(strings.NewReader(csv)).SkipRowOnError(true) require.Equal(t, reader.skipRowOnError, true) require.Equal(t, reader.logTableDataColumns, false) // read all the data ioutil.ReadAll(reader) out := buf.String() // fmt.Println(out) messages := strings.Count(out, prefix) require.Equal(t, messages, 2) } // Test_CsvLineError tests CsvLineError error format func Test_CsvLineError(t *testing.T) { var tests = []struct { err CsvLineError value string }{ { CsvLineError{Line: 1, Err: errors.New("cause")}, "line 1: cause", }, { CsvLineError{Line: 2, Err: CsvColumnError{"a", errors.New("cause")}}, "line 2: column 'a': cause", }, } for _, test := range tests { require.Equal(t, test.value, test.err.Error()) } }
mit
wnadeau/descendants_describable
lib/descendants_describable/version.rb
54
module DescendantsDescribable VERSION = "1.0.0" end
mit
MiguelCastillo/config-grunt-tasks
index.js
1214
var glob = require("glob"); var path = require("path"); var defaultOptions = { path: "./tasks", pattern: "*.js" }; function normalizeOptions(options) { if (options) { if (typeof options === "string") { options = { path: options }; } } if (!options || !options.path) { options = { path: defaultOptions.path }; } if (!options.pattern) { options.pattern = defaultOptions.pattern; } return options; } function configGruntTask(grunt, options, taskOptions) { if (!grunt) { throw new TypeError("Must provide a valid instance of Grunt"); } taskOptions = taskOptions || {}; options = normalizeOptions(options); return glob .sync(options.pattern, { cwd: options.path, realpath: true }) .map(function(item) { return { name: path.parse(item).name, config: require(item) }; }) .map(function(item) { if (typeof item.config === "function") { item.config = item.config(grunt, taskOptions[item]); } return item; }) .reduce(function(container, item) { container[item.name] = item.config; return container; }, {}); } module.exports = configGruntTask;
mit
ebertech/outsourced
lib/outsourced/engine.rb
613
require 'rails/engine' require File.expand_path('../rack_filter.rb', __FILE__) module Outsourced class Engine < Rails::Engine middleware.use Outsourced::RackFilter config.autoload_paths.delete(File.expand_path("../../../app/controllers", __FILE__)) config.autoload_paths.delete(File.expand_path("../../../app/models", __FILE__)) config.autoload_once_paths << File.expand_path("../../../app/commands", __FILE__) config.autoload_once_paths << File.expand_path("../../../app/models", __FILE__) config.autoload_once_paths << File.expand_path("../../../app/controllers", __FILE__) end end
mit
youngastronauts/SecondScreen
demos/classic-controller/index.php
2838
<?php include("../../config.php"); $title = "Classic Controller"; $fullTitle = BASE_TITLE . " - " . $title; ?> <!DOCTYPE HTML> <html> <head> <meta charset="UTF-8"> <title><?php echo $fullTitle;?></title> <link rel="stylesheet" href="/shared/css/global.css" type="text/css"/> <?php if(MOBILE): ?> <meta name="viewport" content="width=device-width, minimum-scale=1, maximum-scale=1, initial-scale=1.0, user-scalable=no"> <link rel="stylesheet" href="/shared/css/normalize.css" type="text/css"/> <link rel="stylesheet" href="/shared/css/mobile.css" type="text/css"/> <link rel="stylesheet" href="mobile.css" type="text/css"/> <?php else: ?> <link rel="stylesheet" href="/shared/css/reset.css" type="text/css"/> <link rel="stylesheet" href="/shared/css/desktop.css" type="text/css"/> <link rel="stylesheet" href="desktop.css" type="text/css"/> <?php endif; ?> <script type="text/javascript"> var Settings = {}; Settings.socketScriptUrl = '<?php echo SOCKET_SCRIPT_URL; ?>'; Settings.socketServer = '<?php echo SOCKET_SERVER; ?>'; </script> </head> <body> <?php if(MOBILE):?> <a href="/" id="mobile-back">Back</a> <div id="c"> <div id="f"> <h2>Nintendo <em>&#174;</em></h2> <ul id="dpad"> <li id="d-up"><a href="#up" data-arrow="" title="Up"></a></li> <li id="d-right"><a href="#right" data-arrow="" title="Right"></a></li> <li id="d-down"><a href="#down" data-arrow="" title="Down"></a></li> <li id="d-left"><a href="#left" data-arrow="" title="Left"></a></li> </ul> <dl id="selectstart"> <dt>Select</dt> <dd><a href="#select">Select</a></dd> <dt>Start</dt> <dd><a href="#start">Start</a></dd> </dl> <dl id="ba"> <dt>B</dt> <dd><a href="#b">B</a></dd> <dt>A</dt> <dd><a href="#a">A</a></dd> </dl> </div> </div> <?php include(AUTH_PAGE); ?> <?php else: ?> <?php include(HEADER); ?> <div class="container"> <div id="passcodeLabel">Passcode: <span></span></div> <h1><?php echo $title; ?></h1> <div class="nes">Loading...</div> </div> <?php endif;?> <!-- FOOT --> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script> <script type="text/javascript" src="<?php echo SOCKET_SCRIPT_URL;?>"></script> <?php if(MOBILE):?> <script type="text/javascript" src="/shared/js/mobile.js" id="script-mobile-shared"></script> <script type="text/javascript" src="mobile.js" id="script-mobile"></script> <?php else: ?> <script type="text/javascript" src="dynamicaudio.min.js"></script> <script type="text/javascript" src="jnes.js"></script> <script type="text/javascript" src="/shared/js/desktop.js" id="script-desktop-shared"></script> <script type="text/javascript" src="desktop.js" id="script-desktop"></script> <?php endif; ?> </body> </html>
mit
neohunter/NubeFact
lib/nube_fact/invoice.rb
456
class NubeFact::Invoice < NubeFact::Document TIPO_DE_COMPROBANTE = 1 DEFAULT_DATA = { operacion: 'generar_comprobante', tipo_de_comprobante: TIPO_DE_COMPROBANTE, serie: 'F', sunat_transaction: 1, fecha_de_emision: ->(_i) { Date.today }, porcentaje_de_igv: 18, moneda: 1, tipo_de_cambio: ->(invoice) { invoice.set_tipo_de_cambio } } end
mit
nebulab/pulsar
spec/support/dummies/conf/dir/apps/blog/staging.rb
119
# Staging config server 'staging.blog.com', user: 'deploy', roles: %w{web app db}, primary: true set :stage, :staging
mit
armynante/battle-api
models/boardModel.js
10898
belt = { cols: "A B C D E F G H I J", rows: "1 2 3 4 5 6 7 8 9 10", spacers: "# 1 2 3 4 5 6 7 8 9 X", directions: ["up", "down", "left", "right"], charMap: "A B C D E F G H I J".split(" ") .reduce(function(obj, key, i) { obj[key] = i + 1; return obj; }, {}), randNum: function(maxInt) { return Math.floor(Math.random() * maxInt) + 1 } } ships = { carrier: { width: 5, callSign: "C", possibleNames: ["carrier", "c", "Carrier", "C"] }, battleship: { width: 4, callSign: "B", possibleNames: ["battle", "b", "battleship", "battle ship", "Battleship", "Battle", "B"] }, destroyer: { width: 3, callSign: "D", possibleNames: ["d", "destroyer", "Destroyer", "D"] }, submarine: { width: 3, callSign: "S", possibleNames: ["sub", "submarine", "s", "Sub", "Submarine"] }, patrolBoat: { width: 2, callSign: "P", possibleNames: ["pb", "patrol", "patrol boat", "patrolboat", "Patrol Boat", "PB", "P", "p"] } }; module.exports = function(){ var _this = this; this.renderedBoard = [ [], [], [], [], [], [], [], [], [], [] ]; this.state = null; this.availableTiles = {}; this.buildBoard = function() { for (var r = 0; r < belt.cols.split(" ").length; r++) { for (var c = 0; c < belt.rows.split(" ").length; c++) { var tile = new Tile(r, c); _this.state[r][c] = tile; stringKey = r.toString() + c.toString() _this.availableTiles[stringKey] = tile; } } _this.state; }; this.randomKey = function() { var result; var count = 0; for (var prop in _this.availableTiles) { if (Math.random() < 1 / ++count) { result = prop; } }; return _this.availableTiles[result] } // visiblity allows diferent render states // 'VISIBLE' allows for board to show ship class // this.render = function(visibility) { // // for (var r = 0; r < _this.state.length; r++) { // for (var c = 0; c < _this.state.length; c++) { // var state = _this.state[r][c]; // _this.renderedBoard[r][c] = clc.blackBright("0") // if (r % 2 === 0) { // _this.renderedBoard[r][c] = clc.blackBright("0") // } // if (state.hit) { // _this.renderedBoard[r][c] = clc.redBright("!"); // } // if (state.hit === false) { // _this.renderedBoard[r][c] = clc.magenta("X"); // } // // if (visibility === 'visible') { // // state.vacant ? _this.renderedBoard[r][c] = clc.blackBright("0") : _this.renderedBoard[r][c] = clc.whiteBright(ships[state.shipClass].callSign); // // if (state.hit) { // _this.renderedBoard[r][c] = clc.redBright("!"); // } // if (state.hit === false) { // _this.renderedBoard[r][c] = clc.magenta("X"); // } // // } // // // } // } // _this.renderedBoard.splice(0, 0, belt.cols.split(" ")); // // for (var i = 0; i < _this.renderedBoard.length; i++) { // _this.renderedBoard[i].splice(0, 0, belt.spacers.split(" ")[i]); // } // // for (var n = 0; n < _this.renderedBoard.length; n++) { // var line = _this.renderedBoard[n].join(" "); // if (n === 0) { // console.log(clc.yellow(line)); // } else { // var row = _this.renderedBoard[n].splice(0, 1); // var rest = _this.renderedBoard[n].join(" "); // // console.log(clc.green(row[0]) + " " + rest); // } // }; // _this.renderedBoard.splice(0, 1); // console.log("\n"); // }; // startRow and startCol are form input // remember to add a 1; this.placeBoat = function(shipClass, orientation, startRow, startCol, live, densityTest) { //refactor var validity = [0]; switch (orientation) { case "up": if (ships[shipClass] === undefined){ validity.push(1); break; } for (var i = 0; i < ships[shipClass].width; i++) { var row = startRow - i ; var col = startCol; if (densityTest) { val = _this.densityTest(row, col, shipClass); } else { val = _this.runPlacements(row, col, live, shipClass); } validity.push(val); } break; case "down": if (ships[shipClass] === undefined){ validity.push(1); break; } for (var i = 0; i < ships[shipClass].width; i++) { var row = startRow + i; var col = startCol; if (densityTest) { val = _this.densityTest(row, col, shipClass); } else { val = _this.runPlacements(row, col, live, shipClass); } validity.push(val); } break; case "left": if (ships[shipClass] === undefined){ validity.push(1); break; } for (var i = 0; i < ships[shipClass].width; i++) { var row = startRow var col = startCol - i; if (densityTest) { val = _this.densityTest(row, col, shipClass); } else { val = _this.runPlacements(row, col, live, shipClass); } validity.push(val); } break; case "right": if (ships[shipClass] === undefined){ validity.push(1); break; } for (var i = 0; i < ships[shipClass].width; i++) { var row = startRow; var col = startCol + i; if (densityTest) { val = _this.densityTest(row, col, shipClass); } else { val = _this.runPlacements(row, col, live, shipClass); } validity.push(val); } break; default: validity.push(1) } sum = validity.reduce(function(a, b) { return a + b; }) return sum === 0; }; // 1 is added to the index on row and col this.calculateDensity = function(shipsArray) { var orientations = ['up','down','left','right']; var highestDensity = 0; var bestGuess = null; for (var i = 0; i < _this.state.length; i++) { for (var c = 0; c < _this.state[i].length; c++) { _this.state[i][c].density = 0; }; }; for (var s = 0; s < shipsArray.length; s++) { for (var o = 0; o < orientations.length; o++) { for (var r = 0; r < _this.state.length; r++) { for (var c = 0; c < _this.state[r].length; c++) { valid = _this.placeBoat(shipsArray[s], orientations[o], r, c, false, true); if (valid) { _this.state[r][c].density += 1; } }; }; }; } //density is calculated by all ship locations that are open or hit for (var r = 0; r < _this.state.length; r++) { for (var c = 0; c < _this.state[r].length; c++) { if ( _this.state[r][c].density >= highestDensity && _this.state[r][c].hit === null) { highestDensity = _this.state[r][c].density; bestGuess = _this.state[r][c]; }; } } return bestGuess; } this.runPlacements = function(row, col, live, shipClass) { if (col >= 0 && row >= 0 && col <= 9 && row <= 9) { var position = _this.state[row][col]; if (position.vacant) { if (live) { _this.state[row][col].shipClass = shipClass; _this.state[row][col].vacant = false; } else { return 0; } } else { return 1; } } else { return 1; } }; this.densityTest = function(row, col, shipClass) { if (col >= 0 && row >= 0 && col <= 9 && row <= 9) { var position = _this.state[row][col]; if (position.hit === null || position.hit === true) { return 0 } else { return 1; } } else { return 1; } }; this.surroundingTiles = function(r, c) { var boxArray = [ [0, 1], [0, -1], [1, 0], [-1, 0], ] var tiles = []; for (var i = 0; i < boxArray.length; i++) { var row = boxArray[i][0] + r; var col = boxArray[i][1] + c; if (col >= 0 && row >= 0 && col <= 9 && row <= 9 && _this.state[row][col].hit === null) {; tiles.push(_this.state[row][col]); }; }; return tiles; } this.fire = function(r, c) { tile = _this.state[r][c]; if (!tile.vacant && tile.hit === null) { _this.state[r][c].hit = true; return true; } else { _this.state[r][c].hit = false; return false } } this.initialiaze = function() { _this.buildBoard(); }; }
mit
pokemon4e/terminate
MilenaSapunova.TerminateContracts/MilenaSapunova.TerminateContracts.Services/Contracts/ICountryService.cs
275
using MilenaSapunova.TerminateContracts.Model; using System.Linq; namespace MilenaSapunova.TerminateContracts.Services.Contracts { public interface ICountryService { IQueryable<Country> GetAll(); void Update(Country company); } }
mit
discountry/larawechat
config/app.php
8525
<?php return [ /* |-------------------------------------------------------------------------- | Application Environment |-------------------------------------------------------------------------- | | This value determines the "environment" your application is currently | running in. This may determine how you prefer to configure various | services your application utilizes. Set this in your ".env" file. | */ 'env' => env('APP_ENV', 'production'), /* |-------------------------------------------------------------------------- | Application Debug Mode |-------------------------------------------------------------------------- | | When your application is in debug mode, detailed error messages with | stack traces will be shown on every error that occurs within your | application. If disabled, a simple generic error page is shown. | */ 'debug' => env('APP_DEBUG', false), /* |-------------------------------------------------------------------------- | Application URL |-------------------------------------------------------------------------- | | This URL is used by the console to properly generate URLs when using | the Artisan command line tool. You should set this to the root of | your application so that it is used when running Artisan tasks. | */ 'url' => env('APP_URL', 'http://localhost'), /* |-------------------------------------------------------------------------- | Application Timezone |-------------------------------------------------------------------------- | | Here you may specify the default timezone for your application, which | will be used by the PHP date and date-time functions. We have gone | ahead and set this to a sensible default for you out of the box. | */ 'timezone' => 'UTC', /* |-------------------------------------------------------------------------- | Application Locale Configuration |-------------------------------------------------------------------------- | | The application locale determines the default locale that will be used | by the translation service provider. You are free to set this value | to any of the locales which will be supported by the application. | */ 'locale' => 'en', /* |-------------------------------------------------------------------------- | Application Fallback Locale |-------------------------------------------------------------------------- | | The fallback locale determines the locale to use when the current one | is not available. You may change the value to correspond to any of | the language folders that are provided through your application. | */ 'fallback_locale' => 'en', /* |-------------------------------------------------------------------------- | Encryption Key |-------------------------------------------------------------------------- | | This key is used by the Illuminate encrypter service and should be set | to a random, 32 character string, otherwise these encrypted strings | will not be safe. Please do this before deploying an application! | */ 'key' => env('APP_KEY'), 'cipher' => 'AES-256-CBC', /* |-------------------------------------------------------------------------- | Logging Configuration |-------------------------------------------------------------------------- | | Here you may configure the log settings for your application. Out of | the box, Laravel uses the Monolog PHP logging library. This gives | you a variety of powerful log handlers / formatters to utilize. | | Available Settings: "single", "daily", "syslog", "errorlog" | */ 'log' => 'errorlog', /* |-------------------------------------------------------------------------- | Autoloaded Service Providers |-------------------------------------------------------------------------- | | The service providers listed here will be automatically loaded on the | request to your application. Feel free to add your own services to | this array to grant expanded functionality to your applications. | */ 'providers' => [ /* * Laravel Framework Service Providers... */ Illuminate\Auth\AuthServiceProvider::class, Illuminate\Broadcasting\BroadcastServiceProvider::class, Illuminate\Bus\BusServiceProvider::class, Illuminate\Cache\CacheServiceProvider::class, Illuminate\Foundation\Providers\ConsoleSupportServiceProvider::class, Illuminate\Cookie\CookieServiceProvider::class, Illuminate\Database\DatabaseServiceProvider::class, Illuminate\Encryption\EncryptionServiceProvider::class, Illuminate\Filesystem\FilesystemServiceProvider::class, Illuminate\Foundation\Providers\FoundationServiceProvider::class, Illuminate\Hashing\HashServiceProvider::class, Illuminate\Mail\MailServiceProvider::class, Illuminate\Pagination\PaginationServiceProvider::class, Illuminate\Pipeline\PipelineServiceProvider::class, Illuminate\Queue\QueueServiceProvider::class, Illuminate\Redis\RedisServiceProvider::class, Illuminate\Auth\Passwords\PasswordResetServiceProvider::class, Illuminate\Session\SessionServiceProvider::class, Illuminate\Translation\TranslationServiceProvider::class, Illuminate\Validation\ValidationServiceProvider::class, Illuminate\View\ViewServiceProvider::class, /* * Application Service Providers... */ App\Providers\AppServiceProvider::class, App\Providers\AuthServiceProvider::class, App\Providers\EventServiceProvider::class, App\Providers\RouteServiceProvider::class, /** * Wechat Service Providers... */ Overtrue\LaravelWechat\ServiceProvider::class, ], /* |-------------------------------------------------------------------------- | Class Aliases |-------------------------------------------------------------------------- | | This array of class aliases will be registered when this application | is started. However, feel free to register as many as you wish as | the aliases are "lazy" loaded so they don't hinder performance. | */ 'aliases' => [ 'App' => Illuminate\Support\Facades\App::class, 'Artisan' => Illuminate\Support\Facades\Artisan::class, 'Auth' => Illuminate\Support\Facades\Auth::class, 'Blade' => Illuminate\Support\Facades\Blade::class, 'Cache' => Illuminate\Support\Facades\Cache::class, 'Config' => Illuminate\Support\Facades\Config::class, 'Cookie' => Illuminate\Support\Facades\Cookie::class, 'Crypt' => Illuminate\Support\Facades\Crypt::class, 'DB' => Illuminate\Support\Facades\DB::class, 'Eloquent' => Illuminate\Database\Eloquent\Model::class, 'Event' => Illuminate\Support\Facades\Event::class, 'File' => Illuminate\Support\Facades\File::class, 'Gate' => Illuminate\Support\Facades\Gate::class, 'Hash' => Illuminate\Support\Facades\Hash::class, 'Lang' => Illuminate\Support\Facades\Lang::class, 'Log' => Illuminate\Support\Facades\Log::class, 'Mail' => Illuminate\Support\Facades\Mail::class, 'Password' => Illuminate\Support\Facades\Password::class, 'Queue' => Illuminate\Support\Facades\Queue::class, 'Redirect' => Illuminate\Support\Facades\Redirect::class, 'Redis' => Illuminate\Support\Facades\Redis::class, 'Request' => Illuminate\Support\Facades\Request::class, 'Response' => Illuminate\Support\Facades\Response::class, 'Route' => Illuminate\Support\Facades\Route::class, 'Schema' => Illuminate\Support\Facades\Schema::class, 'Session' => Illuminate\Support\Facades\Session::class, 'Storage' => Illuminate\Support\Facades\Storage::class, 'URL' => Illuminate\Support\Facades\URL::class, 'Validator' => Illuminate\Support\Facades\Validator::class, 'View' => Illuminate\Support\Facades\View::class, 'Wechat' => Overtrue\LaravelWechat\Facade::class, ], ];
mit
portojs/angular-project-6
app/js/services/worlds.js
191
/** * Created by Peter on 15.12.2015. */ 'use strict'; angular.module('worldsApp') .service('WorldsService', function($resource) { return $resource('json/worlds.json', {}, {}); });
mit
shijiema/JavaXmlTabulator
src/main/java/person/developer/shijiema/XMLUtils/MyNode.java
1400
package person.developer.shijiema.XMLUtils; import org.w3c.dom.Node; import java.util.LinkedHashMap; import java.util.Map; import java.util.Objects; public class MyNode implements Comparable<MyNode>{ private String key; private String value; private Map<String,String> properties = null; private MyNode(String key, String value) { this.key = key; this.value = value; } public void setValue(String v){ this.value = "".equals(v)?null:v; } public String getKey() { return key; } public String getValue() { return value; } public Map<String,String> getProperties(){ return properties; } public void addProperty(String k,String v){ Objects.requireNonNull(k); Objects.requireNonNull(v); if(properties==null){ properties = new LinkedHashMap<>(); } properties.put(k, v); } public String toString(){ StringBuffer sb = new StringBuffer(); sb.append(key+"="+value); if(this.properties!=null) { for (Map.Entry<String, String> p : this.properties.entrySet()) { sb.append(p.getKey() + "=" + p.getValue()).append(" "); } } return sb.toString(); } public int hashCode(){ return getKey().hashCode(); } public static MyNode newStringKeyValuePair(String key, String value) { return new MyNode(key, value); } @Override public int compareTo(MyNode o) { Objects.requireNonNull(o); return o.toString().compareTo(this.toString()); } }
mit
victorli/cms
concrete/controllers/single_page/dashboard/system/backup/update.php
5843
<?php namespace Concrete\Controller\SinglePage\Dashboard\System\Backup; use Concrete\Controller\Upgrade; use Concrete\Core\Page\Controller\DashboardPageController; use Concrete\Core\Updater\ApplicationUpdate; use Concrete\Core\Updater\Archive; use Config; use Exception; use Loader; class UpdateArchive extends Archive { public function __construct() { parent::__construct(); $this->targetDirectory = DIR_CORE_UPDATES; } public function install($file) { parent::install($file, true); } } if (!ini_get('safe_mode')) { @set_time_limit(0); ini_set('max_execution_time', 0); } class Update extends DashboardPageController { public function check_for_updates() { Config::clear('APP_VERSION_LATEST', false); \Concrete\Core\Updater\Update::getLatestAvailableVersionNumber(); $this->redirect('/dashboard/system/backup/update'); } public function on_start() { parent::on_start(); $this->error = Loader::helper('validation/error'); id(new Upgrade())->checkSecurity(); } public function download_update() { $p = new \Permissions(); if (!$p->canUpgrade()) { return false; } $vt = Loader::helper('validation/token'); if (!$vt->validate('download_update')) { $this->error->add($vt->getErrorMessage()); } if (!is_dir(DIR_CORE_UPDATES)) { $this->error->add(t('The directory %s does not exist.', DIR_CORE_UPDATES)); } else { if (!is_writable(DIR_CORE_UPDATES)) { $this->error->add(t('The directory %s must be writable by the web server.', DIR_CORE_UPDATES)); } } if (!$this->error->has()) { $remote = \Concrete\Core\Updater\Update::getApplicationUpdateInformation(); if (is_object($remote)) { // try to download $r = \Marketplace::downloadRemoteFile($remote->url); if (empty($r) || $r == \Package::E_PACKAGE_DOWNLOAD) { $response = array(\Package::E_PACKAGE_DOWNLOAD); } else { if ($r == \Package::E_PACKAGE_SAVE) { $response = array($r); } } if (isset($response)) { $errors = \Package::mapError($response); foreach ($errors as $e) { $this->error->add($e); } } if (!$this->error->has()) { // the file exists in the right spot $ar = new UpdateArchive(); try { $ar->install($r); } catch (Exception $e) { $this->error->add($e->getMessage()); } } } else { $this->error->add(t('Unable to retrieve software from update server.')); } } $this->view(); } function view() { $p = new \Permissions(); if ($p->canUpgrade()) { $upd = new \Concrete\Core\Updater\Update(); $updates = $upd->getLocalAvailableUpdates(); $remote = $upd->getApplicationUpdateInformation(); $this->set('updates', $updates); if (is_object($remote) && version_compare($remote->version, APP_VERSION, '>')) { // loop through local updates $downloadableUpgradeAvailable = true; foreach ($updates as $upd) { if ($upd->getUpdateVersion() == $remote->version) { // we have a LOCAL version ready to install that is the same, so we abort $downloadableUpgradeAvailable = false; $this->set('showDownloadBox', false); break; } } $this->set('downloadableUpgradeAvailable', $downloadableUpgradeAvailable); $this->set('update', $remote); } else { $this->set('downloadableUpgradeAvailable', false); } $this->set('canUpgrade', true); } } public function do_update() { $p = new \Permissions(); if (!$p->canUpgrade()) { return false; } $updateVersion = $this->post('updateVersion'); if (!$updateVersion) { $this->error->add(t('Invalid version')); } else { $upd = ApplicationUpdate::getByVersionNumber($updateVersion); } if (!is_object($upd)) { $this->error->add(t('Invalid version')); } else { if (version_compare($upd->getUpdateVersion(), APP_VERSION, '<=')) { $this->error->add( t( 'You may only apply updates with a greater version number than the version you are currently running.')); } } if (!$this->error->has()) { $resp = $upd->apply(); if ($resp !== true) { switch ($resp) { case ApplicationUpdate::E_UPDATE_WRITE_CONFIG: $this->error->add( t( 'Unable to write to config/site.php. You must make config/site.php writable in order to upgrade in this manner.')); break; } } else { $token = Loader::helper("validation/token"); \Redirect::to('/ccm/system/upgrade/submit?ccm_token=' . $token->generate('Concrete\Controller\Upgrade'))->send(); exit; } } $this->view(); } }
mit
velmyk/mocha-test-async
config/load.js
303
'use strict'; const glob = require('glob'), path = require('path'); module.exports = (sourceDir) => { require('./testConfig'); require('babel-polyfill'); const SPECS_PATTERN = path.join(sourceDir, '/**/*.spec.js'); glob.sync(SPECS_PATTERN).forEach(spec => require(spec)); };
mit
andrew-carroll/watir-network-logging
db/migrate/20150611153006_create_responses.rb
496
class CreateResponses < ActiveRecord::Migration def change create_table :responses do |t| t.belongs_to :request, index: true, null: false, foreign_key: true t.string :proxy_connection t.string :connection t.string :date, null: false t.string :server, null: false t.string :vary t.string :content_encoding t.string :x_content_type_options t.string :content_type, null: false t.string :via t.string :body end end end
mit
Phonemetra/TurboCoin
contrib/devtools/test-security-check.py
3010
#!/usr/bin/env python3 # Copyright (c) 2015-2018 TurboCoin # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. ''' Test script for security-check.py ''' import subprocess import unittest def write_testcode(filename): with open(filename, 'w', encoding="utf8") as f: f.write(''' #include <stdio.h> int main() { printf("the quick brown fox jumps over the lazy god\\n"); return 0; } ''') def call_security_check(cc, source, executable, options): subprocess.check_call([cc,source,'-o',executable] + options) p = subprocess.Popen(['./security-check.py',executable], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, universal_newlines=True) (stdout, stderr) = p.communicate() return (p.returncode, stdout.rstrip()) class TestSecurityChecks(unittest.TestCase): def test_ELF(self): source = 'test1.c' executable = 'test1' cc = 'gcc' write_testcode(source) self.assertEqual(call_security_check(cc, source, executable, ['-Wl,-zexecstack','-fno-stack-protector','-Wl,-znorelro','-no-pie','-fno-PIE']), (1, executable+': failed PIE NX RELRO Canary')) self.assertEqual(call_security_check(cc, source, executable, ['-Wl,-znoexecstack','-fno-stack-protector','-Wl,-znorelro','-no-pie','-fno-PIE']), (1, executable+': failed PIE RELRO Canary')) self.assertEqual(call_security_check(cc, source, executable, ['-Wl,-znoexecstack','-fstack-protector-all','-Wl,-znorelro','-no-pie','-fno-PIE']), (1, executable+': failed PIE RELRO')) self.assertEqual(call_security_check(cc, source, executable, ['-Wl,-znoexecstack','-fstack-protector-all','-Wl,-znorelro','-pie','-fPIE']), (1, executable+': failed RELRO')) self.assertEqual(call_security_check(cc, source, executable, ['-Wl,-znoexecstack','-fstack-protector-all','-Wl,-zrelro','-Wl,-z,now','-pie','-fPIE']), (0, '')) def test_64bit_PE(self): source = 'test1.c' executable = 'test1.exe' cc = 'x86_64-w64-mingw32-gcc' write_testcode(source) self.assertEqual(call_security_check(cc, source, executable, ['-Wl,--no-nxcompat','-Wl,--no-dynamicbase','-Wl,--no-high-entropy-va']), (1, executable+': failed DYNAMIC_BASE HIGH_ENTROPY_VA NX')) self.assertEqual(call_security_check(cc, source, executable, ['-Wl,--nxcompat','-Wl,--no-dynamicbase','-Wl,--no-high-entropy-va']), (1, executable+': failed DYNAMIC_BASE HIGH_ENTROPY_VA')) self.assertEqual(call_security_check(cc, source, executable, ['-Wl,--nxcompat','-Wl,--dynamicbase','-Wl,--no-high-entropy-va']), (1, executable+': failed HIGH_ENTROPY_VA')) self.assertEqual(call_security_check(cc, source, executable, ['-Wl,--nxcompat','-Wl,--dynamicbase','-Wl,--high-entropy-va']), (0, '')) if __name__ == '__main__': unittest.main()
mit
devnull-tools/boteco
plugins/boteco-plugin-user/src/main/java/tools/devnull/boteco/plugins/user/LinkRequest.java
2063
/* * The MIT License * * Copyright (c) 2016 Marcelo "Ataxexe" Guimarães <ataxexe@devnull.tools> * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package tools.devnull.boteco.plugins.user; import tools.devnull.boteco.message.IncomeMessage; import tools.devnull.boteco.user.User; /** * A class that represents a request to link a destination * to an user. */ public class LinkRequest { private final String user; private final String channel; private final String target; public LinkRequest(User user, String channel, String target) { this.user = user.id(); this.channel = channel; this.target = target; } public LinkRequest(IncomeMessage message, String user) { this.user = user; this.channel = message.channel().id(); this.target = message.sender().id(); } public String userId() { return user; } public String channel() { return channel; } public String target() { return target; } }
mit
VanceKingSaxbeA/NYSE-Engine
App/LMT.php
10444
/*Owner & Copyrights: Vance King Saxbe. A.*//*Copyright (c) <2014> Author Vance King Saxbe. A, and contributors Power Dominion Enterprise, Precieux Consulting and other contributors. Modelled, Architected and designed by Vance King Saxbe. A. with the geeks from GoldSax Consulting and GoldSax Technologies email @vsaxbe@yahoo.com. Development teams from Power Dominion Enterprise, Precieux Consulting. Project sponsored by GoldSax Foundation, GoldSax Group and executed by GoldSax Manager.*/ /* $quote = file_get_contents('http://finance.google.co.uk/finance/info?client=ig&q=NYSE:LMT'); $avgp = "137.19"; $high = "138.84"; $low = "136.99"; $json = str_replace("\n", "", $quote); $data = substr($json, 4, strlen($json) -5); $json_output = json_decode($data, true); echo "&L=".$json_output['l']."&N=LMT&"; $temp = file_get_contents("LMTTEMP.txt", "r"); */ $json_output['l'] = file_get_contents('LMTLAST.txt'); $avgp = "137.19"; $high = "138.84"; $low = "136.99"; echo "&L=".$json_output['l']."&N=LMT&"; $temp = file_get_contents("LMTTEMP.txt", "r"); if ($json_output['l'] != $temp ) { $mhigh = ($avgp + $high)/2; $mlow = ($avgp + $low)/2; $llow = ($low - (($avgp - $low)/2)); $hhigh = ($high + (($high - $avgp)/2)); $diff = $json_output['l'] - $temp; $diff = number_format($diff, 2, '.', ''); $avgp = number_format($avgp, 2, '.', ''); if ( $json_output['l'] > $temp ) { if ( ($json_output['l'] > $mhigh ) && ($json_output['l'] < $high)) { echo "&sign=au" ; } if ( ($json_output['l'] < $mlow ) && ($json_output['l'] > $low)) { echo "&sign=ad" ; } if ( $json_output['l'] < $llow ) { echo "&sign=as" ; } if ( $json_output['l'] > $hhigh ) { echo "&sign=al" ; } if ( ($json_output['l'] < $hhigh) && ($json_output['l'] > $high)) { echo "&sign=auu" ; } if ( ($json_output['l'] > $llow) && ($json_output['l'] < $low)) { echo "&sign=add" ; } //else { echo "&sign=a" ; } $filedish = fopen("C:\wamp\www\malert.txt", "a+"); $write = fputs($filedish, "Lockheed Martin:".$json_output['l']. ":Moving up:".$diff.":".$high.":".$low.":".$avgp."\r\n"); fclose( $filedish );} if ( $json_output['l'] < $temp ) { if ( ($json_output['l'] >$mhigh) && ($json_output['l'] < $high)) { echo "&sign=bu" ; } if ( ($json_output['l'] < $mlow) && ($json_output['l'] > $low)) { echo "&sign=bd" ; } if ( $json_output['l'] < $llow ) { echo "&sign=bs" ; } if ( $json_output['l'] > $hhigh ) { echo "&sign=bl" ; } if ( ($json_output['l'] < $hhigh) && ($json_output['l'] > $high)) { echo "&sign=buu" ; } if ( ($json_output['l'] > $llow) && ($json_output['l'] < $low)) { echo "&sign=bdd" ; } // else { echo "&sign=b" ; } $filedish = fopen("C:\wamp\www\malert.txt", "a+"); $write = fputs($filedish, "Lockheed Martin:".$json_output['l']. ":Moving down:".$diff.":".$high.":".$low.":".$avgp."\r\n"); fclose( $filedish );} $my_time = date('h:i:s',time()); $seconds2add = 19800; $new_time= strtotime($my_time); $new_time+=$seconds2add; $index = file_get_contents("SNP500LAST.txt"); $time = date('h:i:s',$new_time); $filename= 'LMT.txt'; $file = fopen($filename, "a+" ); fwrite( $file, $json_output['l'].":".$index.":".$time."\r\n" ); fclose( $file ); if (($json_output['l'] > $mhigh ) && ($temp<= $mhigh )) {$my_time = date('h:i:s',time()); $seconds2add = 19800; $new_time= strtotime($my_time); $new_time+=$seconds2add; $time = date('h:i:s',$new_time); $risk = ($json_output['l'] - $low) * (200000/$json_output['l']); $risk = (int)$risk; $filedash = fopen("C:\wamp\www\alert.txt", "a+"); $wrote = fputs($filedash, "Lockheed Martin:".$json_output['l']. ":Approaching:PHIGH:".$high.":Buy Cost:".$risk."\r\n"); fclose( $filedash ); } if (($json_output['l'] < $mhigh ) && ($temp>= $mhigh )) {$my_time = date('h:i:s',time()); $seconds2add = 19800; $new_time= strtotime($my_time); $new_time+=$seconds2add; $risk = ($high - $json_output['l']) * (200000/$json_output['l']); $risk = (int)$risk; $time = date('h:i:s',$new_time); $filedash = fopen("C:\wamp\www\alert.txt", "a+"); $wrote = fputs($filedash, "Lockheed Martin:". $json_output['l'].":Moving Down:PHIGH:".$high.":short Cost:".$risk."\r\n"); fclose( $filedash ); } if (($json_output['l'] > $mlow ) && ($temp<= $mlow )) {$my_time = date('h:i:s',time()); $seconds2add = 19800; $new_time= strtotime($my_time); $new_time+=$seconds2add; $time = date('h:i:s',$new_time); $risk = ($json_output['l'] - $low) * (200000/$json_output['l']); $risk = (int)$risk; $filedash = fopen("C:\wamp\www\alert.txt", "a+"); $wrote = fputs($filedash, "Lockheed Martin:".$json_output['l']. ":Moving Up:PLOW:".$low.":Buy Cost:".$risk."\r\n"); fclose( $filedash ); } if (($json_output['l'] < $mlow ) && ($temp>= $mlow )) {$my_time = date('h:i:s',time()); $seconds2add = 19800; $new_time= strtotime($my_time); $new_time+=$seconds2add; $risk = ($high - $json_output['l']) * (200000/$json_output['l']); $risk = (int)$risk; $time = date('h:i:s',$new_time); $filedash = fopen("C:\wamp\www\alert.txt", "a+"); $wrote = fputs($filedash, "Lockheed Martin:". $json_output['l'].":Approaching:PLOW:".$low.":short Cost:".$risk."\r\n"); fclose( $filedash ); } if (($json_output['l'] > $high ) && ($temp<= $high )) {$my_time = date('h:i:s',time()); $seconds2add = 19800; $new_time= strtotime($my_time); $new_time+=$seconds2add; $time = date('h:i:s',$new_time); $risk = ($json_output['l'] - $low) * (200000/$json_output['l']); $risk = (int)$risk; $filedash = fopen("C:\wamp\www\alert.txt", "a+"); $wrote = fputs($filedash, "Lockheed Martin:".$json_output['l']. ":Breaking:PHIGH:".$high.":Buy Cost:".$risk."\r\n"); fclose( $filedash ); } if (($json_output['l'] > $hhigh ) && ($temp<= $hhigh )) {$my_time = date('h:i:s',time()); $seconds2add = 19800; $new_time= strtotime($my_time); $new_time+=$seconds2add; $time = date('h:i:s',$new_time); $risk = ($json_output['l'] - $low) * (200000/$json_output['l']); $risk = (int)$risk; $filedash = fopen("C:\wamp\www\alert.txt", "a+"); $wrote = fputs($filedash, "Lockheed Martin:".$json_output['l']. ":Moving Beyond:PHIGH:".$high.":Buy Cost:".$risk."\r\n"); fclose( $filedash ); } if (($json_output['l'] < $hhigh ) && ($temp>= $hhigh )) {$my_time = date('h:i:s',time()); $seconds2add = 19800; $new_time= strtotime($my_time); $new_time+=$seconds2add; $time = date('h:i:s',$new_time); $filedash = fopen("C:\wamp\www\alert.txt", "a+"); $wrote = fputs($filedash, "Lockheed Martin:". $json_output['l']. ":Coming near:PHIGH:".$high.":Buy Cost:".$risk."\r\n"); fclose( $filedash ); } if (($json_output['l'] < $high ) && ($temp>= $high )) {$my_time = date('h:i:s',time()); $seconds2add = 19800; $new_time= strtotime($my_time); $new_time+=$seconds2add; $time = date('h:i:s',$new_time); $filedash = fopen("C:\wamp\www\alert.txt", "a+"); $wrote = fputs($filedash, "Lockheed Martin:". $json_output['l']. ":Retracing:PHIGH:".$high."\r\n"); fclose( $filedash ); } if (($json_output['l'] < $llow ) && ($temp>= $llow )) {$my_time = date('h:i:s',time()); $seconds2add = 19800; $new_time= strtotime($my_time); $new_time+=$seconds2add; $risk = ($high - $json_output['l']) * (200000/$json_output['l']); $risk = (int)$risk; $time = date('h:i:s',$new_time); $filedash = fopen("C:\wamp\www\alert.txt", "a+"); $wrote = fputs($filedash, "Lockheed Martin:". $json_output['l'].":Breaking Beyond:PLOW:".$low.":short Cost:".$risk."\r\n"); fclose( $filedash ); } if (($json_output['l'] < $low ) && ($temp>= $low )) {$my_time = date('h:i:s',time()); $seconds2add = 19800; $new_time= strtotime($my_time); $new_time+=$seconds2add; $risk = ($high - $json_output['l']) * (200000/$json_output['l']); $risk = (int)$risk; $time = date('h:i:s',$new_time); $filedash = fopen("C:\wamp\www\alert.txt", "a+"); $wrote = fputs($filedash, "Lockheed Martin:". $json_output['l'].":Breaking:PLOW:".$low.":short Cost:".$risk."\r\n"); fclose( $filedash ); } if (($json_output['l'] > $llow ) && ($temp<= $llow )) {$my_time = date('h:i:s',time()); $seconds2add = 19800; $new_time= strtotime($my_time); $new_time+=$seconds2add; $time = date('h:i:s',$new_time); $filedash = fopen("C:\wamp\www\alert.txt", "a+"); $wrote = fputs($filedash, "Lockheed Martin:". $json_output['l'].":Coming near:PLOW:".$low.":short Cost:".$risk."\r\n"); fclose( $filedash ); } if (($json_output['l'] > $low ) && ($temp<= $low )) {$my_time = date('h:i:s',time()); $seconds2add = 19800; $new_time= strtotime($my_time); $new_time+=$seconds2add; $time = date('h:i:s',$new_time); $filedash = fopen("C:\wamp\www\alert.txt", "a+"); $wrote = fputs($filedash, "Lockheed Martin:". $json_output['l'].":Retracing:PLOW:".$low."\r\n"); fclose( $filedash ); } if (($json_output['l'] > $avgp ) && ($temp<= $avgp )) {$my_time = date('h:i:s',time()); $seconds2add = 19800; $new_time= strtotime($my_time); $new_time+=$seconds2add; $risk = ($json_output['l'] - $low) * (200000/$json_output['l']); $risk = (int)$risk; $avgp = number_format($avgp, 2, '.', ''); $time = date('h:i:s',$new_time); $filedash = fopen("C:\wamp\www\alert.txt", "a+"); $wrote = fputs($filedash, "Lockheed Martin:".$json_output['l']. ":Sliding up:PAVG:".$avgp.":Buy Cost:".$risk."\r\n"); fclose( $filedash ); } if (($json_output['l'] < $avgp ) && ($temp>= $avgp )) {$my_time = date('h:i:s',time()); $seconds2add = 19800; $new_time= strtotime($my_time); $new_time+=$seconds2add; $risk = ($high - $json_output['l']) * (200000/$json_output['l']); $risk = (int)$risk; $avgp = number_format($avgp, 2, '.', ''); $time = date('h:i:s',$new_time); $filedash = fopen("C:\wamp\www\alert.txt", "a+"); $wrote = fputs($filedash, "Lockheed Martin:".$json_output['l']. ":Sliding down:PAVG:".$avgp.":Short Cost:".$risk."\r\n"); fclose( $filedash ); } } $filedash = fopen("LMTTEMP.txt", "w"); $wrote = fputs($filedash, $json_output['l']); fclose( $filedash ); //echo "&chg=".$json_output['cp']."&"; ?> /*email to provide support at vancekingsaxbe@powerdominionenterprise.com, businessaffairs@powerdominionenterprise.com, For donations please write to fundraising@powerdominionenterprise.com*/
mit
csyhhu/L-OBS
PyTorch/ImageNet/models/resnet_layer_input.py
10119
import torch.nn as nn import math import torch.utils.model_zoo as model_zoo __all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101', 'resnet152'] model_urls = { 'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth', 'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth', 'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth', 'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth', 'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth', } def conv3x3(in_planes, out_planes, stride=1): """3x3 convolution with padding""" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False) class BasicBlock(nn.Module): expansion = 1 def __init__(self, inplanes, planes, layer_name, block_index, \ layer_input, layer_kernel, layer_stride, layer_padding, stride=1, downsample=None): super(BasicBlock, self).__init__() self.conv1 = conv3x3(inplanes, planes, stride) self.bn1 = nn.BatchNorm2d(planes) self.relu = nn.ReLU(inplace=True) self.conv2 = conv3x3(planes, planes) self.bn2 = nn.BatchNorm2d(planes) self.downsample = downsample self.stride = stride layer_kernel['layer%s.%s.conv1' %(layer_name, block_index)] = 3 layer_stride['layer%s.%s.conv1' %(layer_name, block_index)] = stride layer_padding['layer%s.%s.conv1' %(layer_name, block_index)] = 1 layer_kernel['layer%s.%s.conv2' %(layer_name, block_index)] = 3 layer_stride['layer%s.%s.conv2' %(layer_name, block_index)] = stride layer_padding['layer%s.%s.conv2' %(layer_name, block_index)] = 1 self.layer_input = layer_input self.layer_name = layer_name self.block_index = block_index # self.exist_downsample = False def forward(self, x): residual = x self.layer_input['layer%s.%s.conv1' %(self.layer_name, self.block_index)] = x.data out = self.conv1(x) out = self.bn1(out) out = self.relu(out) self.layer_input['layer%s.%s.conv2' %(self.layer_name, self.block_index)] = out.data out = self.conv2(out) out = self.bn2(out) if self.downsample is not None: self.layer_input['layer%s.%s.downsample.0' %(self.layer_name, self.block_index)] = x.data residual = self.downsample(x) out += residual out = self.relu(out) return out class Bottleneck(nn.Module): expansion = 4 def __init__(self, inplanes, planes, layer_name, block_index, \ layer_input, layer_kernel, layer_stride, layer_padding, stride=1, downsample=None): super(Bottleneck, self).__init__() self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False) self.bn1 = nn.BatchNorm2d(planes) self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False) self.bn2 = nn.BatchNorm2d(planes) self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False) self.bn3 = nn.BatchNorm2d(planes * 4) self.relu = nn.ReLU(inplace=True) self.downsample = downsample self.stride = stride layer_kernel['layer%s.%s.conv1' %(layer_name, block_index)] = 1 layer_stride['layer%s.%s.conv1' %(layer_name, block_index)] = 1 layer_padding['layer%s.%s.conv1' %(layer_name, block_index)] = 1 layer_kernel['layer%s.%s.conv2' %(layer_name, block_index)] = 3 layer_stride['layer%s.%s.conv2' %(layer_name, block_index)] = stride layer_padding['layer%s.%s.conv2' %(layer_name, block_index)] = 1 layer_kernel['layer%s.%s.conv3' %(layer_name, block_index)] = 1 layer_stride['layer%s.%s.conv3' %(layer_name, block_index)] = 1 layer_padding['layer%s.%s.conv3' %(layer_name, block_index)] = 1 self.layer_input = layer_input self.layer_name = layer_name self.block_index = block_index def forward(self, x): residual = x self.layer_input['layer%s.%s.conv1' %(self.layer_name, self.block_index)] = x.data out = self.conv1(x) out = self.bn1(out) out = self.relu(out) self.layer_input['layer%s.%s.conv2' %(self.layer_name, self.block_index)] = out.data out = self.conv2(out) out = self.bn2(out) out = self.relu(out) self.layer_input['layer%s.%s.conv3' %(self.layer_name, self.block_index)] = out.data out = self.conv3(out) out = self.bn3(out) if self.downsample is not None: self.layer_input['layer%s.%s.downsample.0' %(self.layer_name, self.block_index)] = x.data residual = self.downsample(x) out += residual out = self.relu(out) return out class ResNet(nn.Module): def __init__(self, block, layers, num_classes=1000): self.inplanes = 64 super(ResNet, self).__init__() # Modified by Chen Shangyu to get layer inputs self.layer_input = dict() self.layer_kernel = {'conv1': 7} self.layer_stride = {'conv1': 2} self.layer_padding = {'conv1': 3} self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False) self.bn1 = nn.BatchNorm2d(64) self.relu = nn.ReLU(inplace=True) self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) self.layer1 = self._make_layer(block, 64, layers[0], layer_name='1') self.layer2 = self._make_layer(block, 128, layers[1], layer_name='2', stride=2) self.layer3 = self._make_layer(block, 256, layers[2], layer_name='3', stride=2) self.layer4 = self._make_layer(block, 512, layers[3], layer_name='4', stride=2) self.avgpool = nn.AvgPool2d(7, stride=1) self.fc = nn.Linear(512 * block.expansion, num_classes) for m in self.modules(): if isinstance(m, nn.Conv2d): n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels m.weight.data.normal_(0, math.sqrt(2. / n)) elif isinstance(m, nn.BatchNorm2d): m.weight.data.fill_(1) m.bias.data.zero_() def _make_layer(self, block, planes, blocks, layer_name, stride=1): downsample = None if stride != 1 or self.inplanes != planes * block.expansion: self.layer_kernel['layer%s.0.downsample.0' %layer_name] = 1 self.layer_stride['layer%s.0.downsample.0' %layer_name] = stride self.layer_padding['layer%s.0.downsample.0' %layer_name] = 0 downsample = nn.Sequential( nn.Conv2d(self.inplanes, planes * block.expansion, kernel_size=1, stride=stride, bias=False), nn.BatchNorm2d(planes * block.expansion), ) # def __init__(self, inplanes, planes, layer_name, block_index, \ # layer_input, layer_kernel, layer_stride, layer_padding, stride=1, downsample=None): layers = [] layers.append(block(self.inplanes, planes, layer_name, block_index = 0, layer_input = self.layer_input, layer_kernel = self.layer_kernel, layer_stride = self.layer_stride, layer_padding = self.layer_padding, stride = stride, downsample = downsample)) self.inplanes = planes * block.expansion for i in range(1, blocks): layers.append(block(self.inplanes, planes, layer_name, block_index = i, layer_input = self.layer_input, layer_kernel = self.layer_kernel, layer_stride = self.layer_stride, layer_padding = self.layer_padding)) return nn.Sequential(*layers) def forward(self, x): self.layer_input['conv1'] = x.data x = self.conv1(x) x = self.bn1(x) x = self.relu(x) x = self.maxpool(x) x = self.layer1(x) x = self.layer2(x) x = self.layer3(x) x = self.layer4(x) x = self.avgpool(x) x = x.view(x.size(0), -1) self.layer_input['fc'] = x.data x = self.fc(x) return x def resnet18(pretrained=False, **kwargs): """Constructs a ResNet-18 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(BasicBlock, [2, 2, 2, 2], **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet18'])) return model def resnet34(pretrained=False, **kwargs): """Constructs a ResNet-34 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(BasicBlock, [3, 4, 6, 3], **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet34'])) return model def resnet50(pretrained=False, **kwargs): """Constructs a ResNet-50 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(Bottleneck, [3, 4, 6, 3], **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet50'])) return model def resnet101(pretrained=False, **kwargs): """Constructs a ResNet-101 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(Bottleneck, [3, 4, 23, 3], **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet101'])) return model def resnet152(pretrained=False, **kwargs): """Constructs a ResNet-152 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(Bottleneck, [3, 8, 36, 3], **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet152'])) return model
mit
havelessbemore/hackerrank
algorithms/warmup/staircase.java
536
//https://www.hackerrank.com/challenges/staircase import java.io.*; public class Solution { public static void main(String[] args) throws IOException { final BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); //Get size of staircase final int N = Integer.parseInt(br.readLine()); //Print stairs String stair = "#"; final String format = "%" + N + "s\n"; for(int i = 0; i < N; ++i){ System.out.print(String.format(format, stair)); stair += "#"; } } }
mit
Tyelpion/irony
Irony.GrammarExplorer/Highlighter/WavyLineStyle.cs
1134
// Written by Alexey Yakovlev <yallie@yandex.ru> // using System.Collections.Generic; using System.Drawing; using FastColoredTextBoxNS; namespace Irony.GrammarExplorer.Highlighter { /// <summary> /// This style draws a wavy line below a given text range. /// </summary> public class WavyLineStyle : Style { public WavyLineStyle(int alpha, Color color) { this.Pen = new Pen(Color.FromArgb(alpha, color)); } private Pen Pen { get; set; } public override void Draw(Graphics gr, Point pos, Range range) { var size = GetSizeOfRange(range); var start = new Point(pos.X, pos.Y + size.Height - 1); var end = new Point(pos.X + size.Width, pos.Y + size.Height - 1); this.DrawWavyLine(gr, start, end); } private void DrawWavyLine(Graphics graphics, Point start, Point end) { if (end.X - start.X < 2) { graphics.DrawLine(Pen, start, end); return; } var offset = -1; var points = new List<Point>(); for (int i = start.X; i <= end.X; i += 2) { points.Add(new Point(i, start.Y + offset)); offset = -offset; } graphics.DrawLines(Pen, points.ToArray()); } } }
mit
Huachao/vscode-restclient
src/models/configurationSettings.ts
16542
import { CharacterPair, Event, EventEmitter, languages, ViewColumn, window, workspace } from 'vscode'; import configuration from '../../language-configuration.json'; import { getCurrentTextDocument } from '../utils/workspaceUtility'; import { RequestHeaders } from './base'; import { FormParamEncodingStrategy, fromString as ParseFormParamEncodingStr } from './formParamEncodingStrategy'; import { fromString as ParseLogLevelStr, LogLevel } from './logLevel'; import { fromString as ParsePreviewOptionStr, PreviewOption } from './previewOption'; import { RequestMetadata } from './requestMetadata'; export type HostCertificates = { [key: string]: { cert?: string; key?: string; pfx?: string; passphrase?: string; } }; export interface IRestClientSettings { readonly followRedirect: boolean; readonly defaultHeaders: RequestHeaders; readonly timeoutInMilliseconds: number; readonly showResponseInDifferentTab: boolean; readonly requestNameAsResponseTabTitle: boolean; readonly proxy?: string; readonly proxyStrictSSL: boolean; readonly rememberCookiesForSubsequentRequests: boolean; readonly enableTelemetry: boolean; readonly excludeHostsForProxy: string[]; readonly fontSize?: number; readonly fontFamily?: string; readonly fontWeight?: string; readonly environmentVariables: { [key: string]: { [key: string]: string } }; readonly mimeAndFileExtensionMapping: { [key: string]: string }; readonly previewResponseInUntitledDocument: boolean; readonly hostCertificates: HostCertificates; readonly suppressResponseBodyContentTypeValidationWarning: boolean; readonly previewOption: PreviewOption; readonly disableHighlightResonseBodyForLargeResponse: boolean; readonly disableAddingHrefLinkForLargeResponse: boolean; readonly largeResponseBodySizeLimitInMB: number; readonly previewColumn: ViewColumn; readonly previewResponsePanelTakeFocus: boolean; readonly formParamEncodingStrategy: FormParamEncodingStrategy; readonly addRequestBodyLineIndentationAroundBrackets: boolean; readonly decodeEscapedUnicodeCharacters: boolean; readonly logLevel: LogLevel; readonly enableSendRequestCodeLens: boolean; readonly enableCustomVariableReferencesCodeLens: boolean; readonly useContentDispositionFilename: boolean; } export class SystemSettings implements IRestClientSettings { private _followRedirect: boolean; private _defaultHeaders: RequestHeaders; private _timeoutInMilliseconds: number; private _showResponseInDifferentTab: boolean; private _requestNameAsResponseTabTitle: boolean; private _proxy?: string; private _proxyStrictSSL: boolean; private _rememberCookiesForSubsequentRequests: boolean; private _enableTelemetry: boolean; private _excludeHostsForProxy: string[]; private _fontSize?: number; private _fontFamily?: string; private _fontWeight?: string; private _environmentVariables: { [key: string]: { [key: string]: string } }; private _mimeAndFileExtensionMapping: { [key: string]: string }; private _previewResponseInUntitledDocument: boolean; private _hostCertificates: HostCertificates; private _suppressResponseBodyContentTypeValidationWarning: boolean; private _previewOption: PreviewOption; private _disableHighlightResonseBodyForLargeResponse: boolean; private _disableAddingHrefLinkForLargeResponse: boolean; private _largeResponseBodySizeLimitInMB: number; private _previewColumn: ViewColumn; private _previewResponsePanelTakeFocus: boolean; private _formParamEncodingStrategy: FormParamEncodingStrategy; private _addRequestBodyLineIndentationAroundBrackets: boolean; private _decodeEscapedUnicodeCharacters: boolean; private _logLevel: LogLevel; private _enableSendRequestCodeLens: boolean; private _enableCustomVariableReferencesCodeLens: boolean; private _useContentDispositionFilename: boolean; public get followRedirect() { return this._followRedirect; } public get defaultHeaders() { return this._defaultHeaders; } public get timeoutInMilliseconds() { return this._timeoutInMilliseconds; } public get showResponseInDifferentTab() { return this._showResponseInDifferentTab; } public get requestNameAsResponseTabTitle() { return this._requestNameAsResponseTabTitle; } public get proxy() { return this._proxy; } public get proxyStrictSSL() { return this._proxyStrictSSL; } public get rememberCookiesForSubsequentRequests() { return this._rememberCookiesForSubsequentRequests; } public get enableTelemetry() { return this._enableTelemetry; } public get excludeHostsForProxy() { return this._excludeHostsForProxy; } public get fontSize() { return this._fontSize; } public get fontFamily() { return this._fontFamily; } public get fontWeight() { return this._fontWeight; } public get environmentVariables() { return this._environmentVariables; } public get mimeAndFileExtensionMapping() { return this._mimeAndFileExtensionMapping; } public get previewResponseInUntitledDocument() { return this._previewResponseInUntitledDocument; } public get hostCertificates() { return this._hostCertificates; } public get suppressResponseBodyContentTypeValidationWarning() { return this._suppressResponseBodyContentTypeValidationWarning; } public get previewOption() { return this._previewOption; } public get disableHighlightResonseBodyForLargeResponse() { return this._disableHighlightResonseBodyForLargeResponse; } public get disableAddingHrefLinkForLargeResponse() { return this._disableAddingHrefLinkForLargeResponse; } public get largeResponseBodySizeLimitInMB() { return this._largeResponseBodySizeLimitInMB; } public get previewColumn() { return this._previewColumn; } public get previewResponsePanelTakeFocus() { return this._previewResponsePanelTakeFocus; } public get formParamEncodingStrategy() { return this._formParamEncodingStrategy; } public get addRequestBodyLineIndentationAroundBrackets() { return this._addRequestBodyLineIndentationAroundBrackets; } public get decodeEscapedUnicodeCharacters() { return this._decodeEscapedUnicodeCharacters; } public get logLevel() { return this._logLevel; } public get enableSendRequestCodeLens() { return this._enableSendRequestCodeLens; } public get enableCustomVariableReferencesCodeLens() { return this._enableCustomVariableReferencesCodeLens; } public get useContentDispositionFilename() { return this._useContentDispositionFilename; } private readonly brackets: CharacterPair[]; private static _instance: SystemSettings; public static get Instance(): SystemSettings { if (!this._instance) { this._instance = new SystemSettings(); } return this._instance; } private readonly configurationUpdateEventEmitter = new EventEmitter<void>(); public get onDidChangeConfiguration(): Event<void> { return this.configurationUpdateEventEmitter.event; } private constructor() { this.brackets = configuration.brackets as CharacterPair[]; workspace.onDidChangeConfiguration(() => { this.initializeSettings(); this.configurationUpdateEventEmitter.fire(); }); window.onDidChangeActiveTextEditor(e => { if (e) { this.initializeSettings(); this.configurationUpdateEventEmitter.fire(); } }); this.initializeSettings(); } private initializeSettings() { const document = getCurrentTextDocument(); const restClientSettings = workspace.getConfiguration("rest-client", document?.uri); this._followRedirect = restClientSettings.get<boolean>("followredirect", true); this._defaultHeaders = restClientSettings.get<RequestHeaders>("defaultHeaders", { "User-Agent": "vscode-restclient" }); this._showResponseInDifferentTab = restClientSettings.get<boolean>("showResponseInDifferentTab", false); this._requestNameAsResponseTabTitle = restClientSettings.get<boolean>("requestNameAsResponseTabTitle", false); this._rememberCookiesForSubsequentRequests = restClientSettings.get<boolean>("rememberCookiesForSubsequentRequests", true); this._timeoutInMilliseconds = restClientSettings.get<number>("timeoutinmilliseconds", 0); if (this._timeoutInMilliseconds < 0) { this._timeoutInMilliseconds = 0; } this._excludeHostsForProxy = restClientSettings.get<string[]>("excludeHostsForProxy", []); this._fontSize = restClientSettings.get<number>("fontSize"); this._fontFamily = restClientSettings.get<string>("fontFamily"); this._fontWeight = restClientSettings.get<string>("fontWeight"); this._environmentVariables = restClientSettings.get<{ [key: string]: { [key: string]: string } }>("environmentVariables", {}); this._mimeAndFileExtensionMapping = restClientSettings.get<{ [key: string]: string }>("mimeAndFileExtensionMapping", {}); this._previewResponseInUntitledDocument = restClientSettings.get<boolean>("previewResponseInUntitledDocument", false); this._previewColumn = this.parseColumn(restClientSettings.get<string>("previewColumn", "two")); this._previewResponsePanelTakeFocus = restClientSettings.get<boolean>("previewResponsePanelTakeFocus", true); this._hostCertificates = restClientSettings.get<HostCertificates>("certificates", {}); this._disableHighlightResonseBodyForLargeResponse = restClientSettings.get<boolean>("disableHighlightResonseBodyForLargeResponse", true); this._disableAddingHrefLinkForLargeResponse = restClientSettings.get<boolean>("disableAddingHrefLinkForLargeResponse", true); this._largeResponseBodySizeLimitInMB = restClientSettings.get<number>("largeResponseBodySizeLimitInMB", 5); this._previewOption = ParsePreviewOptionStr(restClientSettings.get<string>("previewOption", "full")); this._formParamEncodingStrategy = ParseFormParamEncodingStr(restClientSettings.get<string>("formParamEncodingStrategy", "automatic")); this._enableTelemetry = restClientSettings.get<boolean>('enableTelemetry', true); this._suppressResponseBodyContentTypeValidationWarning = restClientSettings.get('suppressResponseBodyContentTypeValidationWarning', false); this._addRequestBodyLineIndentationAroundBrackets = restClientSettings.get<boolean>('addRequestBodyLineIndentationAroundBrackets', true); this._decodeEscapedUnicodeCharacters = restClientSettings.get<boolean>('decodeEscapedUnicodeCharacters', false); this._logLevel = ParseLogLevelStr(restClientSettings.get<string>('logLevel', 'error')); this._enableSendRequestCodeLens = restClientSettings.get<boolean>('enableSendRequestCodeLens', true); this._enableCustomVariableReferencesCodeLens = restClientSettings.get<boolean>('enableCustomVariableReferencesCodeLens', true); this._useContentDispositionFilename = restClientSettings.get<boolean>('useContentDispositionFilename', true); languages.setLanguageConfiguration('http', { brackets: this._addRequestBodyLineIndentationAroundBrackets ? this.brackets : [] }); const httpSettings = workspace.getConfiguration("http"); this._proxy = httpSettings.get<string>('proxy'); this._proxyStrictSSL = httpSettings.get<boolean>('proxyStrictSSL', false); } private parseColumn(value: string): ViewColumn { value = value.toLowerCase(); switch (value) { case 'current': return ViewColumn.Active; case 'beside': default: return ViewColumn.Beside; } } } export class RequestSettings implements Partial<IRestClientSettings> { private _followRedirect?: boolean = undefined; public get followRedirect() { return this._followRedirect; } public constructor(metadatas: Map<RequestMetadata, string | undefined>) { if (metadatas.has(RequestMetadata.NoRedirect)) { this._followRedirect = false; } } } export class RestClientSettings implements IRestClientSettings { public get followRedirect() { return this.requestSettings.followRedirect ?? this.systemSettings.followRedirect; } public get defaultHeaders() { return this.systemSettings.defaultHeaders; } public get timeoutInMilliseconds() { return this.systemSettings.timeoutInMilliseconds; } public get showResponseInDifferentTab() { return this.systemSettings.showResponseInDifferentTab; } public get requestNameAsResponseTabTitle() { return this.systemSettings.requestNameAsResponseTabTitle; } public get proxy() { return this.systemSettings.proxy; } public get proxyStrictSSL() { return this.systemSettings.proxyStrictSSL; } public get rememberCookiesForSubsequentRequests() { return this.systemSettings.rememberCookiesForSubsequentRequests; } public get enableTelemetry() { return this.systemSettings.enableTelemetry; } public get excludeHostsForProxy() { return this.systemSettings.excludeHostsForProxy; } public get fontSize() { return this.systemSettings.fontSize; } public get fontFamily() { return this.systemSettings.fontFamily; } public get fontWeight() { return this.systemSettings.fontWeight; } public get environmentVariables() { return this.systemSettings.environmentVariables; } public get mimeAndFileExtensionMapping() { return this.systemSettings.mimeAndFileExtensionMapping; } public get previewResponseInUntitledDocument() { return this.systemSettings.previewResponseInUntitledDocument; } public get hostCertificates() { return this.systemSettings.hostCertificates; } public get suppressResponseBodyContentTypeValidationWarning() { return this.systemSettings.suppressResponseBodyContentTypeValidationWarning; } public get previewOption() { return this.systemSettings.previewOption; } public get disableHighlightResonseBodyForLargeResponse() { return this.systemSettings.disableHighlightResonseBodyForLargeResponse; } public get disableAddingHrefLinkForLargeResponse() { return this.systemSettings.disableAddingHrefLinkForLargeResponse; } public get largeResponseBodySizeLimitInMB() { return this.systemSettings.largeResponseBodySizeLimitInMB; } public get previewColumn() { return this.systemSettings.previewColumn; } public get previewResponsePanelTakeFocus() { return this.systemSettings.previewResponsePanelTakeFocus; } public get formParamEncodingStrategy() { return this.systemSettings.formParamEncodingStrategy; } public get addRequestBodyLineIndentationAroundBrackets() { return this.systemSettings.addRequestBodyLineIndentationAroundBrackets; } public get decodeEscapedUnicodeCharacters() { return this.systemSettings.decodeEscapedUnicodeCharacters; } public get logLevel() { return this.systemSettings.logLevel; } public get enableSendRequestCodeLens() { return this.systemSettings.enableSendRequestCodeLens; } public get enableCustomVariableReferencesCodeLens() { return this.systemSettings.enableCustomVariableReferencesCodeLens; } public get useContentDispositionFilename() { return this.systemSettings.useContentDispositionFilename; } private readonly systemSettings = SystemSettings.Instance; public constructor(private readonly requestSettings: RequestSettings) { } }
mit
contactsamie/egodb
egodb/DocumentMetaData.cs
729
using System; using System.Collections.Generic; namespace egodb { public class DocumentMetaData:ICloneable { public DocumentMetaData() { Name = ""; Tag = new Etag(); Histories=new List<History>(); } public bool Deleted { set; get; } public List<History> Histories { set; get; } public string Name { set; get; } public long DocumentId { set; get; } public Etag Tag { set; get; } public string Etag { set { Tag.Value = value; } get { return Tag.Value; } } public object Clone() { return this.MemberwiseClone(); } } }
mit
christianbueschi/teambuddy_meanjs
app/routes/buddyevents.server.routes.js
609
'use strict'; module.exports = function(app) { var users = require('../../app/controllers/users.server.controller'); var buddyevents = require('../../app/controllers/buddyevents.server.controller'); // Buddyevents Routes // app.route('/buddyevents') // .get(buddyevents.list) // .post(users.requiresLogin, buddyevents.create); app.route('/buddyevents/:buddyeventId') .get(buddyevents.read) .put(buddyevents.update); //.delete(users.requiresLogin, teams.hasAuthorization, teams.delete); // Finish by binding the Team middleware app.param('buddyeventId', buddyevents.buddyeventByID); };
mit
cyanide4all/SharpAgenda
SharpAgenda/Meetings/Meets.cs
4308
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml; using System.Xml.Linq; namespace Meetings { public class Meets { public List<Cita> todasLasCitas; public string nombreXmlDoc; public Meets (string xml) //Direccion del archivo XML de Citas { nombreXmlDoc = xml; todasLasCitas = RecuperaXml (xml); } public List<Cita> RecuperaXml(string f) { var toret = new List<Cita>(); var docXml = new XmlDocument( ); try { docXml.Load( f ); if ( docXml.DocumentElement.Name == "Citas" ) { string nombre = ""; string nombreContacto = ""; string fecha = ""; string hora = ""; string descrip = ""; foreach(XmlNode nodo in docXml.DocumentElement.ChildNodes) { if ( nodo.Name == "cita" ){ foreach(XmlNode subNodo in nodo.ChildNodes) { if ( subNodo.Name == "nombreCita" ) { nombre = subNodo.InnerText.Trim(); //Trim quita los espacios en blanco } if ( subNodo.Name == "nombreContacto" ) { nombreContacto = subNodo.InnerText.Trim(); } if ( subNodo.Name == "fecha" ) { fecha = subNodo.InnerText.Trim(); } if ( subNodo.Name == "hora" ) { hora = subNodo.InnerText.Trim(); } if ( subNodo.Name == "descripcion" ) { descrip = subNodo.InnerText.Trim(); } } if ( nombre != "" ) //En caso de que el documento este vacio { toret.Add( new Cita( nombre, nombreContacto, fecha, hora, descrip ) ); } } } } } catch(Exception) { toret.Clear(); Console.WriteLine ("Exception" ); } return toret; } public void AddMeet (Cita cita) { todasLasCitas.Add (cita); //Añado la cita a todas las anteriores } public Boolean RemoveMeet (string nom) { Cita cita = this.GetByName (nom); if (todasLasCitas.Remove (cita)) return true; else return false; } public void ModifyMeet (string nom, Cita cita) //Le pasas el nombre de la cita a modificar y la cita nueva { Cita aux = this.GetByName (nom); int position = todasLasCitas.IndexOf (aux); todasLasCitas.Remove (aux); todasLasCitas.Insert (position, cita); //Vuelve a insertarla en la misma posicion } public String[] GetAll() { String[] toret = new string[todasLasCitas.Count]; int j = 0; foreach (var i in todasLasCitas) { toret [j++] = i.Nombre; } return toret; } public Cita GetByName(string nom) { return todasLasCitas.Find (x => x.Nombre == nom); } public Cita GetByContact(string nom) { return todasLasCitas.Find (x => x.NombreContacto == nom); } public void GenerateXml () { int j = 0; //Contador Actual XmlTextWriter textWriter = new XmlTextWriter( nombreXmlDoc, Encoding.UTF8 ); textWriter.WriteStartDocument(); textWriter.WriteStartElement("Citas"); foreach (var i in todasLasCitas) { textWriter.WriteStartElement ("cita"); textWriter.WriteStartElement ("nombreCita"); textWriter.WriteString (todasLasCitas.ElementAt (j).Nombre); textWriter.WriteEndElement (); textWriter.WriteStartElement ("nombreContacto"); textWriter.WriteString (todasLasCitas.ElementAt (j).NombreContacto); textWriter.WriteEndElement (); textWriter.WriteStartElement ("fecha"); textWriter.WriteString (todasLasCitas.ElementAt (j).Fecha); textWriter.WriteEndElement (); textWriter.WriteStartElement ("hora"); textWriter.WriteString (todasLasCitas.ElementAt (j).Hora); textWriter.WriteEndElement (); textWriter.WriteStartElement ("descripcion"); textWriter.WriteString (todasLasCitas.ElementAt (j).Descripcion); textWriter.WriteEndElement (); textWriter.WriteEndElement(); j++; } textWriter.WriteEndElement(); //Cerrar Citas textWriter.WriteEndDocument(); textWriter.Close(); } public override string ToString () { StringBuilder toret = new StringBuilder(); int j = 0; //System.Console.WriteLine (todasLasCitas.Count); if (todasLasCitas.Count == 0) { toret.Append(""); } else { foreach (var i in todasLasCitas) { toret.Append (i.ToString (++j) + " \n\n"); } } return toret.ToString(); } } }
mit
ee-in/python-api
plotly/matplotlylib/mpltools.py
18592
""" Tools A module for converting from mpl language to plotly language. """ import math import warnings import matplotlib.dates import pytz def check_bar_match(old_bar, new_bar): """Check if two bars belong in the same collection (bar chart). Positional arguments: old_bar -- a previously sorted bar dictionary. new_bar -- a new bar dictionary that needs to be sorted. """ tests = [] tests += new_bar['orientation'] == old_bar['orientation'], tests += new_bar['facecolor'] == old_bar['facecolor'], if new_bar['orientation'] == 'v': new_width = new_bar['x1'] - new_bar['x0'] old_width = old_bar['x1'] - old_bar['x0'] tests += new_width - old_width < 0.000001, tests += new_bar['y0'] == old_bar['y0'], elif new_bar['orientation'] == 'h': new_height = new_bar['y1'] - new_bar['y0'] old_height = old_bar['y1'] - old_bar['y0'] tests += new_height - old_height < 0.000001, tests += new_bar['x0'] == old_bar['x0'], if all(tests): return True else: return False def check_corners(inner_obj, outer_obj): inner_corners = inner_obj.get_window_extent().corners() outer_corners = outer_obj.get_window_extent().corners() if inner_corners[0][0] < outer_corners[0][0]: return False elif inner_corners[0][1] < outer_corners[0][1]: return False elif inner_corners[3][0] > outer_corners[3][0]: return False elif inner_corners[3][1] > outer_corners[3][1]: return False else: return True def convert_dash(mpl_dash): """Convert mpl line symbol to plotly line symbol and return symbol.""" if mpl_dash in DASH_MAP: return DASH_MAP[mpl_dash] else: return 'solid' # default def convert_path(path): verts = path[0] # may use this later code = tuple(path[1]) if code in PATH_MAP: return PATH_MAP[code] else: return None def convert_symbol(mpl_symbol): """Convert mpl marker symbol to plotly symbol and return symbol.""" if isinstance(mpl_symbol, list): symbol = list() for s in mpl_symbol: symbol += [convert_symbol(s)] return symbol elif mpl_symbol in SYMBOL_MAP: return SYMBOL_MAP[mpl_symbol] else: return 'dot' # default def convert_va(mpl_va): """Convert mpl vertical alignment word to equivalent HTML word. Text alignment specifiers from mpl differ very slightly from those used in HTML. See the VA_MAP for more details. Positional arguments: mpl_va -- vertical mpl text alignment spec. """ if mpl_va in VA_MAP: return VA_MAP[mpl_va] else: return None # let plotly figure it out! def convert_x_domain(mpl_plot_bounds, mpl_max_x_bounds): """Map x dimension of current plot to plotly's domain space. The bbox used to locate an axes object in mpl differs from the method used to locate axes in plotly. The mpl version locates each axes in the figure so that axes in a single-plot figure might have the bounds, [0.125, 0.125, 0.775, 0.775] (x0, y0, width, height), in mpl's figure coordinates. However, the axes all share one space in plotly such that the domain will always be [0, 0, 1, 1] (x0, y0, x1, y1). To convert between the two, the mpl figure bounds need to be mapped to a [0, 1] domain for x and y. The margins set upon opening a new figure will appropriately match the mpl margins. Optionally, setting margins=0 and simply copying the domains from mpl to plotly would place axes appropriately. However, this would throw off axis and title labeling. Positional arguments: mpl_plot_bounds -- the (x0, y0, width, height) params for current ax ** mpl_max_x_bounds -- overall (x0, x1) bounds for all axes ** ** these are all specified in mpl figure coordinates """ mpl_x_dom = [mpl_plot_bounds[0], mpl_plot_bounds[0]+mpl_plot_bounds[2]] plotting_width = (mpl_max_x_bounds[1]-mpl_max_x_bounds[0]) x0 = (mpl_x_dom[0]-mpl_max_x_bounds[0])/plotting_width x1 = (mpl_x_dom[1]-mpl_max_x_bounds[0])/plotting_width return [x0, x1] def convert_y_domain(mpl_plot_bounds, mpl_max_y_bounds): """Map y dimension of current plot to plotly's domain space. The bbox used to locate an axes object in mpl differs from the method used to locate axes in plotly. The mpl version locates each axes in the figure so that axes in a single-plot figure might have the bounds, [0.125, 0.125, 0.775, 0.775] (x0, y0, width, height), in mpl's figure coordinates. However, the axes all share one space in plotly such that the domain will always be [0, 0, 1, 1] (x0, y0, x1, y1). To convert between the two, the mpl figure bounds need to be mapped to a [0, 1] domain for x and y. The margins set upon opening a new figure will appropriately match the mpl margins. Optionally, setting margins=0 and simply copying the domains from mpl to plotly would place axes appropriately. However, this would throw off axis and title labeling. Positional arguments: mpl_plot_bounds -- the (x0, y0, width, height) params for current ax ** mpl_max_y_bounds -- overall (y0, y1) bounds for all axes ** ** these are all specified in mpl figure coordinates """ mpl_y_dom = [mpl_plot_bounds[1], mpl_plot_bounds[1]+mpl_plot_bounds[3]] plotting_height = (mpl_max_y_bounds[1]-mpl_max_y_bounds[0]) y0 = (mpl_y_dom[0]-mpl_max_y_bounds[0])/plotting_height y1 = (mpl_y_dom[1]-mpl_max_y_bounds[0])/plotting_height return [y0, y1] def display_to_paper(x, y, layout): """Convert mpl display coordinates to plotly paper coordinates. Plotly references object positions with an (x, y) coordinate pair in either 'data' or 'paper' coordinates which reference actual data in a plot or the entire plotly axes space where the bottom-left of the bottom-left plot has the location (x, y) = (0, 0) and the top-right of the top-right plot has the location (x, y) = (1, 1). Display coordinates in mpl reference objects with an (x, y) pair in pixel coordinates, where the bottom-left corner is at the location (x, y) = (0, 0) and the top-right corner is at the location (x, y) = (figwidth*dpi, figheight*dpi). Here, figwidth and figheight are in inches and dpi are the dots per inch resolution. """ num_x = x - layout['margin']['l'] den_x = layout['width'] - (layout['margin']['l'] + layout['margin']['r']) num_y = y - layout['margin']['b'] den_y = layout['height'] - (layout['margin']['b'] + layout['margin']['t']) return num_x/den_x, num_y/den_y def get_axes_bounds(fig): """Return the entire axes space for figure. An axes object in mpl is specified by its relation to the figure where (0,0) corresponds to the bottom-left part of the figure and (1,1) corresponds to the top-right. Margins exist in matplotlib because axes objects normally don't go to the edges of the figure. In plotly, the axes area (where all subplots go) is always specified with the domain [0,1] for both x and y. This function finds the smallest box, specified by two points, that all of the mpl axes objects fit into. This box is then used to map mpl axes domains to plotly axes domains. """ x_min, x_max, y_min, y_max = [], [], [], [] for axes_obj in fig.get_axes(): bounds = axes_obj.get_position().bounds x_min.append(bounds[0]) x_max.append(bounds[0]+bounds[2]) y_min.append(bounds[1]) y_max.append(bounds[1]+bounds[3]) x_min, y_min, x_max, y_max = min(x_min), min(y_min), max(x_max), max(y_max) return (x_min, x_max), (y_min, y_max) def get_axis_mirror(main_spine, mirror_spine): if main_spine and mirror_spine: return 'ticks' elif main_spine and not mirror_spine: return False elif not main_spine and mirror_spine: return False # can't handle this case yet! else: return False # nuttin'! def get_bar_gap(bar_starts, bar_ends, tol=1e-10): if len(bar_starts) == len(bar_ends) and len(bar_starts) > 1: sides1 = bar_starts[1:] sides2 = bar_ends[:-1] gaps = [s2-s1 for s2, s1 in zip(sides1, sides2)] gap0 = gaps[0] uniform = all([abs(gap0-gap) < tol for gap in gaps]) if uniform: return gap0 def convert_rgba_array(color_list): clean_color_list = list() for c in color_list: clean_color_list += [(dict(r=int(c[0]*255), g=int(c[1]*255), b=int(c[2]*255), a=c[3] ))] plotly_colors = list() for rgba in clean_color_list: plotly_colors += ["rgba({r},{g},{b},{a})".format(**rgba)] if len(plotly_colors) == 1: return plotly_colors[0] else: return plotly_colors def convert_path_array(path_array): symbols = list() for path in path_array: symbols += [convert_path(path)] if len(symbols) == 1: return symbols[0] else: return symbols def convert_linewidth_array(width_array): if len(width_array) == 1: return width_array[0] else: return width_array def convert_size_array(size_array): size = [math.sqrt(s) for s in size_array] if len(size) == 1: return size[0] else: return size def get_markerstyle_from_collection(props): markerstyle=dict( alpha=None, facecolor=convert_rgba_array(props['styles']['facecolor']), marker=convert_path_array(props['paths']), edgewidth=convert_linewidth_array(props['styles']['linewidth']), # markersize=convert_size_array(props['styles']['size']), # TODO! markersize=convert_size_array(props['mplobj'].get_sizes()), edgecolor=convert_rgba_array(props['styles']['edgecolor']) ) return markerstyle def get_rect_xmin(data): """Find minimum x value from four (x,y) vertices.""" return min(data[0][0], data[1][0], data[2][0], data[3][0]) def get_rect_xmax(data): """Find maximum x value from four (x,y) vertices.""" return max(data[0][0], data[1][0], data[2][0], data[3][0]) def get_rect_ymin(data): """Find minimum y value from four (x,y) vertices.""" return min(data[0][1], data[1][1], data[2][1], data[3][1]) def get_rect_ymax(data): """Find maximum y value from four (x,y) vertices.""" return max(data[0][1], data[1][1], data[2][1], data[3][1]) def get_spine_visible(ax, spine_key): """Return some spine parameters for the spine, `spine_key`.""" spine = ax.spines[spine_key] ax_frame_on = ax.get_frame_on() spine_frame_like = spine.is_frame_like() if not spine.get_visible(): return False elif not spine._edgecolor[-1]: # user's may have set edgecolor alpha==0 return False elif not ax_frame_on and spine_frame_like: return False elif ax_frame_on and spine_frame_like: return True elif not ax_frame_on and not spine_frame_like: return True # we've already checked for that it's visible. else: return False # oh man, and i thought we exhausted the options... def is_bar(bar_containers, **props): """A test to decide whether a path is a bar from a vertical bar chart.""" # is this patch in a bar container? for container in bar_containers: if props['mplobj'] in container: return True return False def make_bar(**props): """Make an intermediate bar dictionary. This creates a bar dictionary which aids in the comparison of new bars to old bars from other bar chart (patch) collections. This is not the dictionary that needs to get passed to plotly as a data dictionary. That happens in PlotlyRenderer in that class's draw_bar method. In other words, this dictionary describes a SINGLE bar, whereas, plotly will require a set of bars to be passed in a data dictionary. """ return { 'bar': props['mplobj'], 'x0': get_rect_xmin(props['data']), 'y0': get_rect_ymin(props['data']), 'x1': get_rect_xmax(props['data']), 'y1': get_rect_ymax(props['data']), 'alpha': props['style']['alpha'], 'edgecolor': props['style']['edgecolor'], 'facecolor': props['style']['facecolor'], 'edgewidth': props['style']['edgewidth'], 'dasharray': props['style']['dasharray'], 'zorder': props['style']['zorder'] } def prep_ticks(ax, index, ax_type, props): """Prepare axis obj belonging to axes obj. positional arguments: ax - the mpl axes instance index - the index of the axis in `props` ax_type - 'x' or 'y' (for now) props - an mplexporter poperties dictionary """ axis_dict = dict() if ax_type == 'x': axis = ax.get_xaxis() elif ax_type == 'y': axis = ax.get_yaxis() else: return dict() # whoops! scale = props['axes'][index]['scale'] if scale == 'linear': # get tick location information try: tickvalues = props['axes'][index]['tickvalues'] tick0 = tickvalues[0] dticks = [round(tickvalues[i]-tickvalues[i-1], 12) for i in range(1, len(tickvalues) - 1)] if all([dticks[i] == dticks[i-1] for i in range(1, len(dticks) - 1)]): dtick = tickvalues[1] - tickvalues[0] else: warnings.warn("'linear' {0}-axis tick spacing not even, " "ignoring mpl tick formatting.".format(ax_type)) raise TypeError except (IndexError, TypeError): axis_dict['nticks'] = props['axes'][index]['nticks'] else: axis_dict['tick0'] = tick0 axis_dict['dtick'] = dtick axis_dict['autotick'] = False elif scale == 'log': try: axis_dict['tick0'] = props['axes'][index]['tickvalues'][0] axis_dict['dtick'] = props['axes'][index]['tickvalues'][1] - \ props['axes'][index]['tickvalues'][0] axis_dict['autotick'] = False except (IndexError, TypeError): axis_dict = dict(nticks=props['axes'][index]['nticks']) base = axis.get_transform().base if base == 10: if ax_type == 'x': axis_dict['range'] = [math.log10(props['xlim'][0]), math.log10(props['xlim'][1])] elif ax_type == 'y': axis_dict['range'] = [math.log10(props['ylim'][0]), math.log10(props['ylim'][1])] else: axis_dict = dict(range=None, type='linear') warnings.warn("Converted non-base10 {0}-axis log scale to 'linear'" "".format(ax_type)) else: return dict() # get tick label formatting information formatter = axis.get_major_formatter().__class__.__name__ if ax_type == 'x' and 'DateFormatter' in formatter: axis_dict['type'] = 'date' try: axis_dict['tick0'] = mpl_dates_to_datestrings( axis_dict['tick0'], formatter ) except KeyError: pass finally: axis_dict.pop('dtick', None) axis_dict.pop('autotick', None) axis_dict['range'] = mpl_dates_to_datestrings( props['xlim'], formatter ) if formatter == 'LogFormatterMathtext': axis_dict['exponentformat'] = 'e' return axis_dict def prep_xy_axis(ax, props, x_bounds, y_bounds): xaxis = dict( type=props['axes'][0]['scale'], range=list(props['xlim']), showgrid=props['axes'][0]['grid']['gridOn'], domain=convert_x_domain(props['bounds'], x_bounds), side=props['axes'][0]['position'], tickfont=dict(size=props['axes'][0]['fontsize']) ) xaxis.update(prep_ticks(ax, 0, 'x', props)) yaxis = dict( type=props['axes'][1]['scale'], range=list(props['ylim']), showgrid=props['axes'][1]['grid']['gridOn'], domain=convert_y_domain(props['bounds'], y_bounds), side=props['axes'][1]['position'], tickfont=dict(size=props['axes'][1]['fontsize']) ) yaxis.update(prep_ticks(ax, 1, 'y', props)) return xaxis, yaxis def mpl_dates_to_datestrings(dates, mpl_formatter): """Convert matplotlib dates to iso-formatted-like time strings. Plotly's accepted format: "YYYY-MM-DD HH:MM:SS" (e.g., 2001-01-01 00:00:00) Info on mpl dates: http://matplotlib.org/api/dates_api.html """ _dates = dates # this is a pandas datetime formatter, times show up in floating point days # since the epoch (1970-01-01T00:00:00+00:00) if mpl_formatter == "TimeSeries_DateFormatter": try: dates = matplotlib.dates.epoch2num( [date*24*60*60 for date in dates] ) dates = matplotlib.dates.num2date(dates, tz=pytz.utc) except: return _dates # the rest of mpl dates are in floating point days since # (0001-01-01T00:00:00+00:00) + 1. I.e., (0001-01-01T00:00:00+00:00) == 1.0 # according to mpl --> try num2date(1) else: try: dates = matplotlib.dates.num2date(dates, tz=pytz.utc) except: return _dates time_stings = [' '.join(date.isoformat().split('+')[0].split('T')) for date in dates] return time_stings DASH_MAP = { '10,0': 'solid', '6,6': 'dash', '2,2': 'dot', '4,4,2,4': 'dashdot', 'none': 'solid' } PATH_MAP = { ('M', 'C', 'C', 'C', 'C', 'C', 'C', 'C', 'C', 'Z'): 'o', ('M', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'Z'): '*', ('M', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'Z'): '8', ('M', 'L', 'L', 'L', 'L', 'L', 'Z'): 'h', ('M', 'L', 'L', 'L', 'L', 'Z'): 'p', ('M', 'L', 'M', 'L', 'M', 'L'): '1', ('M', 'L', 'L', 'L', 'Z'): 's', ('M', 'L', 'M', 'L'): '+', ('M', 'L', 'L', 'Z'): '^', ('M', 'L'): '|' } SYMBOL_MAP = { 'o': 'dot', 'v': 'triangle-down', '^': 'triangle-up', '<': 'triangle-left', '>': 'triangle-right', 's': 'square', '+': 'cross', 'x': 'x', '*': 'x', # no star yet in plotly!! 'D': 'diamond', 'd': 'diamond', } VA_MAP = { 'center': 'middle', 'baseline': 'bottom', 'top': 'top' }
mit
m-alani/contests
york_2016/IceCream.java
1128
import java.util.ArrayList; import java.util.Scanner; public class IceCream { public static void main(String[] args) { Scanner input = new Scanner(System.in); int cases = Integer.parseInt(input.nextLine()); ArrayList<Integer> output = new ArrayList<>(); for (int i=0; i<cases; i++) { int options = Integer.parseInt(input.nextLine()); double[] value = new double[options]; for (int j=0; j<options; j++) { String row = input.nextLine(); String[] cells = row.split(" "); double h = Double.parseDouble(cells[1]); double r = Double.parseDouble(cells[2]); double price = Double.parseDouble(cells[3]); if (cells[0].contains("cone")) { double volume = ((Math.PI * Math.pow(r, 2) * (h / 3.0)) + (((4.0/6.0) * Math.PI * Math.pow(r, 3)))); value[j] = price / volume; } else { double volume = (Math.PI * Math.pow(r, 2) * h); value[j] = price / volume; } } int best = 0; for (int k=1; k<value.length; k++) if (value[k] < value[best]) best = k; output.add(best+1); } for (int value : output) System.out.println(value); input.close(); } }
mit
MorcoFreeCode/2014__Ubisoft-Game-Jam-2
full_project/Assets/Scripts/DrawDestruct.cs
442
using UnityEngine; using System.Collections; public class DrawDestruct : MonoBehaviour { void Update () { if (Input.GetKeyDown(KeyCode.Space)) { //drawClass.ChangeEnergy( cost /2 ); //GameManager gm = GameObject.Find("_GameManager").GetComponent<GameManager>(); //gm.UpdateScore(bonusScore); //gm.UpdateBonus(bonusScore); // Destroy(gameObject); } } }
mit
MatzeS/blackbird
core/src/main/java/blackbird/core/util/Hex.java
397
package blackbird.core.util; public class Hex { public static byte[] hexStringToByteArray(String s) { int len = s.length(); byte[] data = new byte[len / 2]; for (int i = 0; i < len; i += 2) { data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i + 1), 16)); } return data; } }
mit
stephenkearns1/TechnologyApp
AnalogSection/src/analogsection/Resistor5bandCalc.java
15019
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package analogsection; /** * * @author Stephen */ import java.text.DecimalFormat; import java.util.ArrayList; /** * * @author Stephen */ public class Resistor5bandCalc { //variables private String band1, band2, band3, band4,band5, resistorDigits, conversion, substrK, substrH, convertkilohm,maxConverKilohm,minConverKilohm; private int digit1, digit2,digit3, percent, resistorColorVals; private double maxValue, minValue, toloerance, tolrancPercent, multiplier; private double valueResistor; public Resistor5bandCalc(){ band1 = ""; band3 = ""; band3 = ""; band4 = ""; band5 = ""; resistorDigits = ""; conversion = ""; substrK = ""; substrH = ""; convertkilohm = ""; digit1 = 0; digit2 = 0; percent = 100; resistorColorVals = 0; maxValue = 0.0; minValue = 0.0; toloerance = 0.0; tolrancPercent = 0.0; multiplier = 0.0; valueResistor = 0.0; } //setters to set the band values public void setBand1(String band1) { this.band1 = band1; } public void setBand2(String band2) { this.band2 = band2; } public void setBand3(String band3) { this.band3 = band3; } public void setBand4(String band4) { this.band4 = band4; } public void setBand5(String band5) { this.band5 = band5; } //methods to assign values for each of the color bands public void AssignValues() { switch (band1) { case "black": digit1 = 0; break; case "brown": digit1 = 1; break; case "red": digit1 = 2; break; case "orange": digit1 = 3; break; case "yellow": digit1 = 4; break; case "green": digit1 = 5; break; case "blue": digit1 = 6; break; case "violet": digit1 = 7; break; case "grey": digit1 = 8; break; case "white": digit1 = 9; break; } } public void AssignBand2Values() { if(band2.equals("black")) { digit2 = 0; } else if (band2.equals("brown")) { digit2 = 1; } else if (band2.equals("red")) { digit2 = 2; } else if (band2.equals("orange")) { digit2 = 3; } else if (band2.equals("yellow")) { digit2 = 4; } else if (band2.equals("green")) { digit2 = 5; } else if (band2.equals("blue")) { digit2 = 6; } else if (band2.equals("violet")) { digit2 = 7; } else if (band1.equals("grey")) { digit2 = 8; } else if (band1.equals("white")) { digit2 = 9; } } public void Assignband3Values() { switch (band3) { case "black": digit3 = 0; break; case "brown": digit3 = 1; break; case "red": digit3 = 2; break; case "orange": digit3 = 3; break; case "yellow": digit3 = 4; break; case "green": digit3 = 5; break; case "blue": digit3 = 6; break; case "violet": digit3 = 7; break; case "grey": digit3 = 8; break; case "white": digit3 = 9; break; } } public void assignMulitiplier() { switch (band4) { case "black": multiplier = 1; break; case "brown": multiplier = 10; break; case "red": multiplier = 100; break; case "orange": multiplier = 1000; break; case "yellow": multiplier = 10000; break; case "green": multiplier = 100000; break; case "blue": multiplier = 1000000; break; case "violet": multiplier = 10000000; break; case "grey": multiplier = 1000000000; break; case "gold": multiplier = 0.1; break; case "silver": multiplier = 0.01; break; default: System.out.println("an error occoured"); break; } } public void assignToloerance() { switch (band5) { case "brown": toloerance = 1; break; case "red": toloerance = 2; break; case "green": toloerance = 0.5; break; case "blue": toloerance = 0.25; break; case "violet": toloerance = 0.25; break; case "gold": toloerance = 5; break; case "silver": toloerance = 10; break; case "none": toloerance = 20; break; default: System.out.println("an error occoured"); break; } } public void compute() { resistorColorVals = Integer.valueOf(String.valueOf(digit1) + String.valueOf(digit2)+ String.valueOf(digit3)); //error checker System.out.println(resistorColorVals); //calculates the resitor value valueResistor = (resistorColorVals * multiplier); } public void CalcToloerance() { try { //calc's the percent of the toloerance tolrancPercent = (valueResistor * (toloerance / percent)); } catch (ArithmeticException e) { System.out.println("error" + "\n" + e); } //calcs the maxValue, return values in ohms maxValue = tolrancPercent + valueResistor; //calcs the minValue, return values in ohms minValue = valueResistor - tolrancPercent; } public void convertToKilohm() { if(valueResistor < 100){ conversion = String.valueOf(valueResistor); substrK = conversion.substring(0, 2); substrH = conversion.substring(4, 5); convertkilohm = substrK + "." + substrH + "" + "ohms"; }else if(valueResistor > 99 && valueResistor < 1000) { conversion = String.valueOf(valueResistor); substrK = conversion.substring(0, 1); substrH = conversion.substring(1, 3); convertkilohm = substrK + "." + substrH + "" + "ohms"; } else if (valueResistor > 999 && valueResistor < 10000) { conversion = String.valueOf(valueResistor); substrK = conversion.substring(0, 1); substrH = conversion.substring(1, 2); convertkilohm = substrK + "." + substrH + "K" + "ohms"; } else if (valueResistor > 9999 && valueResistor < 100000) { conversion = String.valueOf(valueResistor); substrK = conversion.substring(0, 2); substrH = conversion.substring(3, 5); convertkilohm = substrK + "." + substrH + "K" + "ohms"; } else if (valueResistor > 100000 && valueResistor < 1000000) { conversion = String.valueOf(valueResistor); substrK = conversion.substring(0, 3); substrH = conversion.substring(4, 6); convertkilohm = substrK + "." + substrH + "K" + "ohms"; } else if (valueResistor > 999999 && valueResistor < 10000000) { conversion = String.valueOf(valueResistor); substrK = conversion.substring(0, 1); substrH = conversion.substring(1, 3); convertkilohm = substrK + "." + substrH + "M" + "ohms"; } else if (valueResistor >= 10000000 && valueResistor < 100000000) { long number; number = Long.parseLong(String.format("%.0f", valueResistor)); conversion = String.valueOf(number); substrK = conversion.substring(0, 2); substrH = conversion.substring(3, 5); convertkilohm = substrK + "." + substrH + "M" + "ohms"; } else if (valueResistor >= 100000000) { long number; number = Long.parseLong(String.format("%.0f", valueResistor)); conversion = String.valueOf(number); substrK = conversion.substring(0, 3); substrH = conversion.substring(4, 6); convertkilohm = substrK + "." + substrH + "M" + "ohms"; } // converts maximun resistor value to kilohmz if(maxValue < 100){ conversion = String.valueOf(maxValue); substrK = conversion.substring(0, 2); substrH = conversion.substring(4, 5); maxConverKilohm = substrK + "." + substrH + "" + "ohms"; }else if(maxValue > 99 && maxValue < 1000) { conversion = String.valueOf(maxValue); substrK = conversion.substring(0, 1); substrH = conversion.substring(1, 3); maxConverKilohm = substrK + "." + substrH + "" + "ohms"; }else if (maxValue > 999 && maxValue < 10000) { conversion = String.valueOf(maxValue); substrK = conversion.substring(0, 1); substrH = conversion.substring(1, 2); maxConverKilohm = substrK + "." + substrH + "K" + "ohms"; } else if (maxValue > 9999 && maxValue < 100000) { conversion = String.valueOf(maxValue); substrK = conversion.substring(0, 2); substrH = conversion.substring(3, 5); maxConverKilohm = substrK + "." + substrH + "K" + "ohms"; } else if (maxValue > 100000 && maxValue < 1000000) { conversion = String.valueOf(maxValue); substrK = conversion.substring(0, 3); substrH = conversion.substring(4, 6); maxConverKilohm = substrK + "." + substrH + "K" + "ohms"; } else if (maxValue > 999999 && maxValue < 10000000) { conversion = String.valueOf(maxValue); substrK = conversion.substring(0, 1); substrH = conversion.substring(1, 3); maxConverKilohm = substrK + "." + substrH + "M" + "ohms"; } // number is to larger so getting 1.2E7 //which i will have to try to revert to digital repersentation else if (maxValue >= 10000000 && maxValue < 100000000) { long number; number = Long.parseLong(String.format("%.0f", maxValue)); conversion = String.valueOf(number); substrK = conversion.substring(0, 2); substrH = conversion.substring(3, 5); maxConverKilohm = substrK + "." + substrH + "M" + "ohms"; } else if (maxValue >= 100000000) { long number; number = Long.parseLong(String.format("%.0f", maxValue)); conversion = String.valueOf(number); substrK = conversion.substring(0, 3); substrH = conversion.substring(4, 6); maxConverKilohm = substrK + "." + substrH + "M" + "ohms"; } //converts the minium resistor value to kiloohmz if(minValue < 100){ conversion = String.valueOf(minValue); substrK = conversion.substring(0, 2); substrH = conversion.substring(4, 5); minConverKilohm = substrK + "." + substrH + "" + "ohms"; }else if (minValue > 99 && minValue < 1000) { conversion = String.valueOf(minValue); substrK = conversion.substring(0, 1); substrH = conversion.substring(1, 3); minConverKilohm = substrK + "." + substrH + "" + "ohms"; }else if (minValue > 999 && minValue < 10000) { conversion = String.valueOf(minValue); substrK = conversion.substring(0, 1); substrH = conversion.substring(1, 2); minConverKilohm = substrK + "." + substrH + "K" + "ohms"; } else if (minValue > 9999 && minValue < 100000) { conversion = String.valueOf(minValue); substrK = conversion.substring(0, 2); substrH = conversion.substring(3, 5); minConverKilohm = substrK + "." + substrH + "K" + "ohms"; } else if (minValue > 100000 && minValue < 1000000) { conversion = String.valueOf(minValue); substrK = conversion.substring(0, 3); substrH = conversion.substring(4, 6); minConverKilohm = substrK + "." + substrH + "K" + "ohms"; } else if (minValue > 999999 && minValue < 10000000) { conversion = String.valueOf(minValue); substrK = conversion.substring(0, 1); substrH = conversion.substring(1, 3); minConverKilohm = substrK + "." + substrH + "M" + "ohms"; } // number is to larger so getting 1.2E7 //which i will have to try to revert to digital repersentation else if (minValue >= 10000000 && minValue < 100000000) { long number; number = Long.parseLong(String.format("%.0f", minValue)); conversion = String.valueOf(number); substrK = conversion.substring(0, 2); substrH = conversion.substring(3, 5); minConverKilohm = substrK + "." + substrH + "M" + "ohms"; } else if (minValue >= 100000000) { long number; number = Long.parseLong(String.format("%.0f", minValue)); conversion = String.valueOf(number); substrK = conversion.substring(0, 3); substrH = conversion.substring(4, 6); minConverKilohm = substrK + "." + substrH + "M" + "ohms"; } } //returns the resistor value in ohms public String getValueResistor() { return convertkilohm; } //returns the max resistor value in ohms public String getMaxValue() { return maxConverKilohm; } //returns the min resistor value in ohms public String getMinValue() { return minConverKilohm; } }
mit
sst19881025/fork_download_gitlab
app/controllers/merge_requests_controller.rb
4247
class MergeRequestsController < ApplicationController before_filter :authenticate_user! before_filter :project before_filter :module_enabled before_filter :merge_request, :only => [:edit, :update, :destroy, :show, :commits, :diffs, :automerge, :automerge_check] layout "project" # Authorize before_filter :add_project_abilities # Allow read any merge_request before_filter :authorize_read_merge_request! # Allow write(create) merge_request before_filter :authorize_write_merge_request!, :only => [:new, :create] # Allow modify merge_request before_filter :authorize_modify_merge_request!, :only => [:close, :edit, :update, :sort] # Allow destroy merge_request before_filter :authorize_admin_merge_request!, :only => [:destroy] def index @merge_requests = @project.merge_requests @merge_requests = case params[:f].to_i when 1 then @merge_requests when 2 then @merge_requests.closed when 3 then @merge_requests.opened.assigned(current_user) else @merge_requests.opened end.page(params[:page]).per(20) @merge_requests = @merge_requests.includes(:author, :project).order("created_at desc") end def show # Show git not found page if target branch doesnt exist return git_not_found! unless @project.repo.heads.map(&:name).include?(@merge_request.target_branch) # Show git not found page if source branch doesnt exist # and there is no saved commits between source & target branch return git_not_found! if !@project.repo.heads.map(&:name).include?(@merge_request.source_branch) && @merge_request.commits.blank? # Build a note object for comment form @note = @project.notes.new(:noteable => @merge_request) # Get commits from repository # or from cache if already merged @commits = @merge_request.commits respond_to do |format| format.html format.js end end def diffs @diffs = @merge_request.diffs @commit = @merge_request.last_commit @comments_allowed = true @line_notes = @merge_request.notes.where("line_code is not null") end def new @merge_request = @project.merge_requests.new(params[:merge_request]) end def edit end def create @merge_request = @project.merge_requests.new(params[:merge_request]) @merge_request.author = current_user if @merge_request.save @merge_request.reload_code redirect_to [@project, @merge_request], notice: 'Merge request was successfully created.' else render action: "new" end end def update if @merge_request.update_attributes(params[:merge_request].merge(:author_id_of_changes => current_user.id)) @merge_request.reload_code @merge_request.mark_as_unchecked redirect_to [@project, @merge_request], notice: 'Merge request was successfully updated.' else render action: "edit" end end def automerge_check if @merge_request.unchecked? @merge_request.check_if_can_be_merged end render :json => {:state => @merge_request.human_state} end def automerge return access_denied! unless can?(current_user, :accept_mr, @project) if @merge_request.open? && @merge_request.can_be_merged? @merge_request.should_remove_source_branch = params[:should_remove_source_branch] @merge_request.automerge!(current_user) @status = true else @status = false end end def destroy @merge_request.destroy respond_to do |format| format.html { redirect_to project_merge_requests_url(@project) } end end def branch_from @commit = project.commit(params[:ref]) end def branch_to @commit = project.commit(params[:ref]) end protected def merge_request @merge_request ||= @project.merge_requests.find(params[:id]) end def authorize_modify_merge_request! return render_404 unless can?(current_user, :modify_merge_request, @merge_request) end def authorize_admin_merge_request! return render_404 unless can?(current_user, :admin_merge_request, @merge_request) end def module_enabled return render_404 unless @project.merge_requests_enabled end end
mit
mrpapercut/wscript
testfiles/COMobjects/JSclasses/X509Enrollment.CCertProperty.1.js
798
class x509enrollment_ccertproperty_1 { constructor() { // string RawData (EncodingType) {get} this.Parameterized = undefined; // CERTENROLL_PROPERTYID PropertyId () {get} {set} this.PropertyId = undefined; } // void InitializeDecode (EncodingType, string) InitializeDecode(EncodingType, string) { } // void InitializeFromCertificate (bool, EncodingType, string) InitializeFromCertificate(bool, EncodingType, string) { } // void RemoveFromCertificate (bool, EncodingType, string) RemoveFromCertificate(bool, EncodingType, string) { } // void SetValueOnCertificate (bool, EncodingType, string) SetValueOnCertificate(bool, EncodingType, string) { } } module.exports = x509enrollment_ccertproperty_1;
mit
Vladeff/TelerikAcademy
C# OOP/ExtensionMethodsDelegatesLambdaLINQ/07.TimerClassWithEvents/Timer.cs
1279
namespace TimerClass { using System; using System.Threading; public delegate void TimerEventHandler(object sender, EventArgs e); public class Timer { private int seconds; private int numberExecutions; public event TimerEventHandler Tick; public Timer(int seconds, int numberExecutions) { if (seconds < 0) throw new ArgumentException("The seconds must be positive."); if (numberExecutions < 0) throw new ArgumentException("The number of executions must be positive."); this.seconds = seconds; this.numberExecutions = numberExecutions; } public int Counter { get; private set; } protected virtual void Trigger(EventArgs e) { if (this.Tick != null) { Thread.Sleep(4000); while (true) { Tick(this, e); this.Counter++; if (this.Counter == this.numberExecutions) break; Thread.Sleep(4000); } } } public void StartTimer() { this.Trigger(null); } } }
mit
cmndrbensisko/LocalLayer
samples/flatFileDataSource/widgets/LayerList/setting/nls/lt/strings.js
524
define({ "showLegend": "Rodyti legendą", "controlPopupMenuTitle": "Pasirinkti, kurie veiksmai bus rodomi sluoksnių kontekstiniame meniu.", "zoomto": "Pritraukti iki", "transparency": "Permatomumas", "controlPopup": "Įjungti / išjungti iškylančius langus", "moveUpAndDown": "Į viršų / į apačią", "attributeTable": "Peržiūrėti atributų lentelėje", "url": "Aprašymas / Rodyti elemento informaciją / Atsisiųsti", "layerSelectorTitle": "Pasirinkti, kurie sluoksniai bus rodomi sąraše." });
mit
tka/ideapool
webpack.config.js
2546
var webpack = require("webpack"); var ExtractTextPlugin = require("extract-text-webpack-plugin"); var ManifestPlugin = require('webpack-manifest-plugin'); var contextPath = __dirname + '/app/assets/javascripts'; module.exports = { context: contextPath, entry: { application: './application.js', //用來確保所有的圖片跟 vendors js 都會被打上 digest static_resource: './static_resources.js', }, output: { filename: '[name].[hash].js', path: __dirname + '/public/assets', publicPath: "/assets/" }, module: { loaders: [ { test: /vendors/, exclude: /node_modules/, loader: 'file-loader?name=[path][name].[hash].[ext]'}, { test: /\.jsx?$/, exclude: /(node_modules|vendors)/, loaders: ['react-hot', 'babel'] }, { test: /\.css$/, loader: ExtractTextPlugin.extract("style-loader", "css-loader") }, { test: /\.png$/, loader: "url-loader?limit=100000&name=[name].[hash].[ext]" }, { test: /\.jpg$/, loader: "file-loader?name=[name].[hash].[ext]" }, { test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "url-loader?limit=10000&minetype=application/font-woff&name=[name].[hash].[ext]", }, { test: /\.(otf|ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "file-loader?name=[name].[hash].[ext]", }, { test: /\.scss$/, loader: ExtractTextPlugin.extract( // activate source maps via loader query 'css?sourceMap!' + 'sass?sourceMap' ) } ], noParse: [ /[\/\\]vendors[\/\\].*\.js$/ ] }, resolve: { extensions: ['', '.js', '.jsx'], modulesDirectories: ["node_modules", "javascripts"], }, externals: { "react": 'React', "react/addons": "React", "jquery": 'window.jQuery', }, devtool: "sourcemap", plugins: [ new ExtractTextPlugin("[name].[hash].css", { disable: false, allChunks: true }), new webpack.ProvidePlugin({ $: "jquery", jQuery: "jquery", "window.jQuery": "jquery", React: 'react' }), // 生成 manifest.json, imageExtensions 這邊用來處理 static resource new ManifestPlugin({ imageExtensions: /^(css|jpe?g|png|gif|svg|woff|woff2|otf|ttf|eot|svg|js)(\.|$)/i }) ] };
mit
orvis-ec-pr/dnn-exp
DNN Platform/Modules/UrlManagement/FriendlyUrls.ascx.cs
2058
#region Copyright // // DotNetNuke® - http://www.dotnetnuke.com // Copyright (c) 2002-2017 // by DotNetNuke Corporation // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated // documentation files (the "Software"), to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and // to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions // of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED // TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF // CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #endregion using System; using DotNetNuke.Common.Utilities; using DotNetNuke.Entities.Controllers; using DotNetNuke.ExtensionPoints; using DotNetNuke.UI.Modules; namespace DotNetNuke.Modules.UrlManagement { public partial class FriendlyUrls : ModuleUserControlBase, IEditPagePanelControlActions { public void BindAction(int portalId, int tabId, int moduleId) { basicUrlPanel.Visible = Config.GetFriendlyUrlProvider() != "advanced"; chkUseFriendlyUrls.Checked = Entities.Host.Host.UseFriendlyUrls; } public void CancelAction(int portalId, int tabId, int moduleId) { } public void SaveAction(int portalId, int tabId, int moduleId) { HostController.Instance.Update("UseFriendlyUrls", chkUseFriendlyUrls.Checked ? "Y" : "N", false); } } }
mit
astudio/remixhair
extensions/multiple_uploads/lang/lang.ro.php
301
<?php $about = array( 'name' => 'Romana', 'author' => array( 'name' => 'Vlad Ghita', 'email' => 'vlad.ghita@xandergroup.ro', 'website' => '' ), 'release-date' => '2012-10-05' ); /** * Multiple uploads */ $dictionary = array( 'Upload files' => 'Incarcare fisiere', );
mit
memegen/meme_get
meme_get/ocr/memeocr.py
9124
from __future__ import print_function from __future__ import division from builtins import range from past.utils import old_div import random import json import sys import os import enchant import pyocr import pyocr.builders from PIL import Image, ImageDraw, ImageFont path = "images/img8.jpg" # characters to recognize C = "ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789" # standard character glyphs cimgs = [] # original image IM = None w, h = 0, 0 PX = None # display layer disp = None draw = None # threshold layer thim = None thpx = None thdr = None # character areas areas = [] badareas = [] def loadimg(path): global IM, w, h, PX, disp, draw, thim, thpx, thdr # original image IM = Image.open(path) w, h = IM.size PX = IM.load() # display layer disp = Image.new("RGB", (w, h)) draw = ImageDraw.Draw(disp) # threshold layer thim = Image.new("RGB", (w, h)) thpx = thim.load() thdr = ImageDraw.Draw(thim) def closeimg(): """ Close all the image """ IM.close() disp.close() thim.close() # rgb(255,255,255) to hsv(360,1.0,1.0) conversion def rgb2hsv(r, g, b): R = old_div(r, 255.0) G = old_div(g, 255.0) B = old_div(b, 255.0) cmax = max(R, G, B) cmin = min(R, G, B) delta = cmax - cmin H, S, V = 0, 0, 0 if delta == 0: H = 0 elif cmax == R: H = 60 * ((old_div((G - B), delta)) % 6) elif cmax == G: H = 60 * (old_div((B - R), delta) + 2) elif cmax == B: H = 60 * (old_div((R - G), delta) + 4) if cmax == 0: S = 0 else: S = old_div(delta, cmax) V = cmax return H, S, V # find the left cutoff of character glyph def firstwhitex(im): fwx = im.size[0] px = im.load() for y in range(0, im.size[1]): for x in range(0, im.size[0]): r, g, b = px[x, y][:3] if (r, g, b) == (255, 255, 255): if x < fwx: fwx = x return fwx # been there def visited(x, y, areas): for i in range(0, len(areas)): if (x, y) in areas[i]: return True return False # floodfill from pixel def flood(x, y, d): global areas area = [] seeds = [(x, y)] while d > 0 and len(seeds) > 0: d -= 1 if d == 0: # print "too large" badareas.append(area) return [] x, y = seeds.pop() if visited(x, y, areas) or visited(x, y, badareas): # print "visited" return [] if (d > 0 and x > 0 and x < w - 1 and y > 0 and y < h - 1): if not((x, y) in area): r, g, b = thpx[x, y][:3] if (r != 0): area.append((x, y)) seeds += [(x, y), (x - 1, y), (x, y - 1), (x + 1, y), (x, y + 1)] return area # get all character areas def getareas(): for y in list(range(0, int(old_div(h, 4)), 10)) + list(range(int(3 * h / 4), h, 10)): print(y, "/", h) for x in range(0, w, 5): area = flood(x, y, 30000) # print area if len(area) > 1: col = (random.randrange(0, 255), random.randrange( 0, 255), random.randrange(0, 255)) for i in range(0, len(area)): draw.point(list(area[i]), fill=col) areas.append(area) # boundaries of a character def getbounds(area): xmin = area[0][0] xmax = area[0][0] ymin = area[0][1] ymax = area[0][1] for i in range(0, len(area)): if area[i][0] < xmin: xmin = area[i][0] if area[i][1] < ymin: ymin = area[i][1] if area[i][0] > xmax: xmax = area[i][0] if area[i][1] > ymax: ymax = area[i][1] return xmin - 1, ymin - 1, xmax + 1, ymax + 1 # draw a boundary def drawbounds(): bds = [] for i in range(0, len(areas)): bd = getbounds(areas[i]) bds.append(bd) draw.rectangle(bd, outline=(255, 0, 0)) return bds # OCR def checkchars(): scoreboard = [] for i in range(0, len(areas)): print(i, "/", len(areas)) bd = getbounds(areas[i]) scores = [] print(len(cimgs)) for j in range(0, len(cimgs)): score = 0 px = cimgs[j].load() score = 0 sc = old_div((1.0 * (bd[3] - bd[1])), 100.0) for x in range(0, cimgs[j].size[0]): for y in range(0, cimgs[j].size[1]): xp = min(int(x * sc + bd[0]), w - 1) yp = min(int(y * sc + bd[1]), h - 1) r1, g1, b1 = px[x, y][:3] r2, g2, b2 = thpx[xp, yp][:3] if (xp < bd[2]): if (r1 == r2): score += 1 else: score -= 1 else: if (r1 == 0): score += 0 else: score -= 1 scores.append((C[j], old_div(int(score * 10), 10.0))) scoreboard.append(normalize(scores)) draw.text((bd[0], bd[1] - 5), normalize(scores)[0][0], (0, 255, 255)) return scoreboard # normalize scores to 0.0-1.0 def normalize(scores): scores = sorted(scores, key=lambda x: x[1], reverse=True) ns = sorted(scores, key=lambda x: x[1], reverse=True) for i in range(0, len(scores)): if scores[i][1] <= 0 or scores[0][1] == 0: ns[i] = (scores[i][0], 0) else: n = old_div((scores[i][1] * 1.0), scores[0][1]) ns[i] = (scores[i][0], old_div(int(n * 1000), 1000.0)) return ns # print OCR result def showresult(scoreboard): for i in range(0, len(scoreboard)): print("".join([s[0] for s in scoreboard[i]])) # make character glyphs def makeglyphs(): for i in range(0, len(C)): im = Image.new("RGB", (100, 110)) dr = ImageDraw.Draw(im) font = ImageFont.truetype(os.path.join(os.path.dirname(__file__),"fonts/Impact.ttf"), 124) dr.text((0, -25), C[i], (255, 255, 255), font=font) fwx = firstwhitex(im) im = Image.new("RGB", (100, 110)) dr = ImageDraw.Draw(im) font = ImageFont.truetype(os.path.join(os.path.dirname(__file__),"fonts/Impact.ttf"), 124) dr.text((-fwx, -26), C[i], (255, 255, 255), font=font) cimgs.append(im) # make threshold image def thresh(): for x in range(0, w): for y in range(0, h): r, g, b = PX[x, y][:3] hsv = rgb2hsv(r, g, b) if (hsv[2] > 0.9)and hsv[1] < 0.1: thdr.point([x, y], fill=(255, 255, 255)) else: thdr.point([x, y], fill=(0, 0, 0)) # returns possible characters and bounds in an image def rawocr(path): global cimgs print("Starting ocr for {}".format(str(path))) # Clear glyphs cimgs = [] loadimg(path) print("p0: ", len(cimgs)) makeglyphs() print("p1: ", len(cimgs)) thresh() # thim.show() getareas() bds = drawbounds() # disp.show() print("p2: ", len(cimgs)) ccr = checkchars() showresult(ccr) # disp.show() closeimg() print("Finish OCR.") return bds, ccr def tesseract_ocr_helper(base_image, config="Default"): """ A wrapper for using tesseract to do OCR """ tools = pyocr.get_available_tools() if len(tools) == 0: print("No OCR tool found") sys.exit(1) # The tools are returned in the recommended order of usage tool = tools[0] print("Will use tool '%s'" % (tool.get_name())) langs = tool.get_available_languages() print("Available languages: %s" % ", ".join(langs)) lang = langs[0] print("Will use lang '%s'" % (lang)) custom_builder = pyocr.builders.TextBuilder() if config != "Default": custom_builder.tesseract_configs = [config] txt = tool.image_to_string( base_image, lang=lang, builder=custom_builder ) # Spell correct dict_path = os.path.join(os.path.dirname(__file__),"dict/urban_dict.txt") d = enchant.DictWithPWL("en_US", dict_path) txtA = txt.replace('\n', ' \n ') A = txtA.split(" ") B = [] for x in A: if (x != '\n' and len(x) != 0 and d.check(x) is False and len(d.suggest(x)) != 0): B.append(d.suggest(x)[0]) else: B.append(x) return " ".join(B) def tesseract_ocr(path, thres=False, cfg="Default"): """ Wrapper for tesseract OCR """ loadimg(path) if thres: thresh() result = tesseract_ocr_helper(thim, config=cfg) return result else: result = tesseract_ocr_helper(IM, config=cfg) return result if __name__ == "__main__": bds, ccr = rawocr(path) js = json.dumps([bds, ccr]) fo = open("data/" + path.split("/")[-1].split(".")[0] + ".json", "w") fo.write(js)
mit