code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
<?php /** * Created by JetBrains PhpStorm. * User: etienne.lejariel * Date: 03/07/15 * Time: 09:46 * To change this template use File | Settings | File Templates. */ namespace Enneite\SwaggerBundle\Tests\Creator; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; use Enneite\SwaggerBundle\Creator\ApiControllerCreator; class ApiControllerCreatorTest extends WebTestCase { public function setup() { //$this->config = json_decode(file_get_contents(realpath( __DIR__ .'/../../Resources/example/config/swagger.json')), true); } public function testConstructAndGetters() { $twig = $this->getMockBuilder('\Twig_Environment')->disableOriginalConstructor()->getMock(); $apiModelCreator = $this->getMockBuilder('Enneite\SwaggerBundle\Creator\ApiModelCreator')->disableOriginalConstructor()->getMock(); $apiRoutingCreator = $this->getMockBuilder('Enneite\SwaggerBundle\Creator\ApiRoutingCreator')->disableOriginalConstructor()->getMock(); $creator = new ApiControllerCreator($twig, $apiModelCreator, $apiRoutingCreator); $this->assertInstanceOf('\Twig_Environment', $creator->getTwig(), 'twigEnv property must be an instance of \Twig_Environment'); $this->assertInstanceOf('Enneite\SwaggerBundle\Creator\ApiModelCreator', \PHPUnit_Framework_Assert::readAttribute($creator, 'apiModelCreator')); $this->assertInstanceOf('Enneite\SwaggerBundle\Creator\ApiRoutingCreator', \PHPUnit_Framework_Assert::readAttribute($creator, 'apiRoutingCreator')); } public function testGetAvailableExceptions() { $twig = $this->getMockBuilder('\Twig_Environment')->disableOriginalConstructor()->getMock(); $apiModelCreator = $this->getMockBuilder('Enneite\SwaggerBundle\Creator\ApiModelCreator')->disableOriginalConstructor()->getMock(); $apiRoutingCreator = $this->getMockBuilder('Enneite\SwaggerBundle\Creator\ApiRoutingCreator')->disableOriginalConstructor()->getMock(); $creator = new ApiControllerCreator($twig, $apiModelCreator, $apiRoutingCreator); $exceptions = $creator->getAvailableExceptions(); $this->assertInternalType('array', $exceptions); foreach (array(401, 403, 404) as $status) { $this->assertArrayHasKey($status, $exceptions); } } public function testHasResponseSchema() { $twig = $this->getMockBuilder('\Twig_Environment')->disableOriginalConstructor()->getMock(); $apiModelCreator = $this->getMockBuilder('Enneite\SwaggerBundle\Creator\ApiModelCreator')->disableOriginalConstructor()->getMock(); $apiRoutingCreator = $this->getMockBuilder('Enneite\SwaggerBundle\Creator\ApiRoutingCreator')->disableOriginalConstructor()->getMock(); $creator = new ApiControllerCreator($twig, $apiModelCreator, $apiRoutingCreator); $response = array( 'description' => 'successful operation', ); $this->assertFalse($creator->hasResponseSchema($response)); $response = array( 'description' => 'successful operation', 'schema' => array( 'type' => 'array', ), 'items' => array( "\$ref" => '#/definitions/Pet', ), ); $this->assertTrue($creator->hasResponseSchema($response)); } public function testHasResponseModel() { $twig = $this->getMockBuilder('\Twig_Environment')->disableOriginalConstructor()->getMock(); $apiModelCreator = $this->getMockBuilder('Enneite\SwaggerBundle\Creator\ApiModelCreator')->disableOriginalConstructor()->getMock(); $apiRoutingCreator = $this->getMockBuilder('Enneite\SwaggerBundle\Creator\ApiRoutingCreator')->disableOriginalConstructor()->getMock(); $creator = new ApiControllerCreator($twig, $apiModelCreator, $apiRoutingCreator); $response = array( 'description' => 'successful operation', ); $this->assertFalse($creator->hasResponseModel($response)); $response = array( 'description' => 'successful operation', 'schema' => array( 'type' => 'array', ), 'items' => array( "\$ref" => '#/definitions/Pet', ), ); $this->assertFalse($creator->hasResponseModel($response)); $response = array( 'description' => 'successful operation', 'schema' => array( "\$ref" => '#/definitions/Pet', ), ); $this->assertTrue($creator->hasResponseModel($response)); } public function testHasResponseCollection() { $twig = $this->getMockBuilder('\Twig_Environment')->disableOriginalConstructor()->getMock(); $apiModelCreator = $this->getMockBuilder('Enneite\SwaggerBundle\Creator\ApiModelCreator')->disableOriginalConstructor()->getMock(); $apiRoutingCreator = $this->getMockBuilder('Enneite\SwaggerBundle\Creator\ApiRoutingCreator')->disableOriginalConstructor()->getMock(); $creator = new ApiControllerCreator($twig, $apiModelCreator, $apiRoutingCreator); $response = array( 'description' => 'successful operation', ); $this->assertFalse($creator->hasResponseCollection($response)); $response = array( 'description' => 'successful operation', 'schema' => array( 'type' => 'array', 'items' => array( "\$ref" => '#/definitions/Pet', ), ), ); $this->assertTrue($creator->hasResponseCollection($response)); $response = array( 'description' => 'successful operation', 'schema' => array( "\$ref" => '#/definitions/Pet', ), ); $this->assertfalse($creator->hasResponseCollection($response)); } /** * @expectedException \Exception */ public function testHasResponseCollectionWithException() { $twig = $this->getMockBuilder('\Twig_Environment')->disableOriginalConstructor()->getMock(); $apiModelCreator = $this->getMockBuilder('Enneite\SwaggerBundle\Creator\ApiModelCreator')->disableOriginalConstructor()->getMock(); $apiRoutingCreator = $this->getMockBuilder('Enneite\SwaggerBundle\Creator\ApiRoutingCreator')->disableOriginalConstructor()->getMock(); $creator = new ApiControllerCreator($twig, $apiModelCreator, $apiRoutingCreator); $response = array( 'description' => 'successful operation', 'schema' => array( 'type' => 'array', ), ); $res = $creator->hasResponseCollection($response); } public function testGetAssociatedModel() { $twig = $this->getMockBuilder('\Twig_Environment')->disableOriginalConstructor()->getMock(); $apiModelCreator = $this->getMockBuilder('Enneite\SwaggerBundle\Creator\ApiModelCreator')->disableOriginalConstructor()->getMock(); $apiModelCreator->expects($this->any()) ->method('extractModel') ->will($this->returnValue('Pet')); $apiRoutingCreator = $this->getMockBuilder('Enneite\SwaggerBundle\Creator\ApiRoutingCreator')->disableOriginalConstructor()->getMock(); $creator = new ApiControllerCreator($twig, $apiModelCreator, $apiRoutingCreator); $response = array( 'description' => 'successful operation', 'schema' => array( "\$ref" => '#/definitions/Pet', ), ); $res = $creator->getAssociatedModel($response); $this->assertEquals('Pet', $res); $response = array( 'description' => 'successful operation', 'schema' => array( 'type' => 'array', 'items' => array( "\$ref" => '#/definitions/Pet', ), ), ); $res = $creator->getAssociatedModel($response); $this->assertEquals(false, $res); } public function testGetAssociatedCollection() { $twig = $this->getMockBuilder('\Twig_Environment')->disableOriginalConstructor()->getMock(); $apiModelCreator = $this->getMockBuilder('Enneite\SwaggerBundle\Creator\ApiModelCreator')->disableOriginalConstructor()->getMock(); $apiModelCreator->expects($this->any()) ->method('extractModel') ->will($this->returnValue('Pet')); $apiRoutingCreator = $this->getMockBuilder('Enneite\SwaggerBundle\Creator\ApiRoutingCreator')->disableOriginalConstructor()->getMock(); $creator = new ApiControllerCreator($twig, $apiModelCreator, $apiRoutingCreator); $response = array( 'description' => 'successful operation', 'schema' => array( "\$ref" => '#/definitions/Pet', ), ); $res = $creator->getAssociatedCollection($response); $this->assertEquals(false, $res); $response = array( 'description' => 'successful operation', 'schema' => array( 'type' => 'array', 'items' => array( "\$ref" => '#/definitions/Pet', ), ), ); $res = $creator->getAssociatedCollection($response); $this->assertEquals('PetCollection', $res); } public function testExtractCodesbyStatus() { $twig = $this->getMockBuilder('\Twig_Environment')->disableOriginalConstructor()->getMock(); $apiModelCreator = $this->getMockBuilder('Enneite\SwaggerBundle\Creator\ApiModelCreator')->disableOriginalConstructor()->getMock(); $apiRoutingCreator = $this->getMockBuilder('Enneite\SwaggerBundle\Creator\ApiRoutingCreator')->disableOriginalConstructor()->getMock(); $creator = new ApiControllerCreator($twig, $apiModelCreator, $apiRoutingCreator); $this->assertEquals(array(200), $creator->extractCodesByStatus(array(200, 401, 403, 500), 2)); $this->assertEquals(array(), $creator->extractCodesByStatus(array(200, 401, 403, 500), 3)); $this->assertEquals(array(401, 403), $creator->extractCodesByStatus(array(200, 401, 403, 500), 4)); $this->assertEquals(array(500), $creator->extractCodesByStatus(array(200, 401, 403, 500), 5)); } public function testGetActionParameters() { $twig = $this->getMockBuilder('\Twig_Environment')->disableOriginalConstructor()->getMock(); $apiModelCreator = $this->getMockBuilder('Enneite\SwaggerBundle\Creator\ApiModelCreator')->disableOriginalConstructor()->getMock(); $apiModelCreator->expects($this->any()) ->method('formatProperty') ->will($this->returnValue('myVariable')); $apiRoutingCreator = $this->getMockBuilder('Enneite\SwaggerBundle\Creator\ApiRoutingCreator')->disableOriginalConstructor()->getMock(); $creator = new ApiControllerCreator($twig, $apiModelCreator, $apiRoutingCreator); $objects = array( 'parameters' => array( array( 'description' => 'titi tata', 'name' => 'code', 'in' => 'path', 'type' => 'integer', 'required' => true, ), array( 'description' => 'user language', 'name' => 'Accept-language', 'in' => 'header', 'type' => 'string', ), ), ); $this->assertEquals(array( array( 'description' => null, 'name' => 'myVariable', 'in' => 'path', 'type' => 'integer', 'required' => true, ), array( 'description' => 'user language', 'name' => 'myVariable', 'in' => 'header', 'type' => 'string', 'required' => false, ), ), $creator->getActionParameters('get', $objects)); } /** * @expectedException \Exception */ public function testGetActionParametersWithException() { $twig = $this->getMockBuilder('\Twig_Environment')->disableOriginalConstructor()->getMock(); $apiModelCreator = $this->getMockBuilder('Enneite\SwaggerBundle\Creator\ApiModelCreator')->disableOriginalConstructor()->getMock(); $apiRoutingCreator = $this->getMockBuilder('Enneite\SwaggerBundle\Creator\ApiRoutingCreator')->disableOriginalConstructor()->getMock(); $creator = new ApiControllerCreator($twig, $apiModelCreator, $apiRoutingCreator); $objects = array( 'parameters' => array( array( 'description' => 'titi tata', 'name' => 'code', // 'in' => 'path', // parameter 'in' is missing => will throw an exception 'type' => 'integer', 'required' => true, ), ), ); $res = $creator->getActionParameters('get', $objects); } public function testCreateActionParameters() { $php = '(Request $request, $id)'; $template = $this->getMockBuilder('\Twig_Template')->disableOriginalConstructor()->getMock(); $template->expects($this->any()) ->method('render') ->will($this->returnvalue($php)); $twig = $this->getMockBuilder('\Twig_Environment')->disableOriginalConstructor()->getMock(); $twig->expects($this->any()) ->method('loadTemplate') ->will($this->returnvalue($template)); $apiModelCreator = $this->getMockBuilder('Enneite\SwaggerBundle\Creator\ApiModelCreator')->disableOriginalConstructor()->getMock(); $apiRoutingCreator = $this->getMockBuilder('Enneite\SwaggerBundle\Creator\ApiRoutingCreator')->disableOriginalConstructor()->getMock(); $creator = new ApiControllerCreator($twig, $apiModelCreator, $apiRoutingCreator); $objects = array( 'parameters' => array( array( 'name' => 'id', 'in' => 'path', 'type' => 'integer', 'required' => true, ), ), ); $this->assertEquals($php, $creator->createActionParameters('get', $objects)); } /** * @expectedException \Exception */ public function testCreateActionParametersWithException() { $twig = $this->getMockBuilder('\Twig_Environment')->disableOriginalConstructor()->getMock(); $apiModelCreator = $this->getMockBuilder('Enneite\SwaggerBundle\Creator\ApiModelCreator')->disableOriginalConstructor()->getMock(); $apiRoutingCreator = $this->getMockBuilder('Enneite\SwaggerBundle\Creator\ApiRoutingCreator')->disableOriginalConstructor()->getMock(); $creator = new ApiControllerCreator($twig, $apiModelCreator, $apiRoutingCreator); $objects = array( 'parameters' => array( array( 'name' => 'id', // 'in' => 'path', // parameter 'in' is missing => will throw an exception 'type' => 'integer', 'required' => true, ), ), ); $res = $creator->createActionParameters(200, $objects); } /** * */ public function testGetRoutingAnnotation() { $twig = $this->getMockBuilder('\Twig_Environment')->disableOriginalConstructor()->getMock(); $apiModelCreator = $this->getMockBuilder('Enneite\SwaggerBundle\Creator\ApiModelCreator')->disableOriginalConstructor()->getMock(); $apiRoutingCreator = $this->getMockBuilder('Enneite\SwaggerBundle\Creator\ApiRoutingCreator')->disableOriginalConstructor()->getMock(); $apiRoutingCreator->expects($this->any()) ->method('getRouteParametersAsArray') ->will($this->returnvalue(array())); $creator = new ApiControllerCreator($twig, $apiModelCreator, $apiRoutingCreator); $objects = array( 'parameters' => array( array( 'name' => 'id', // 'in' => 'path', // parameter 'in' is missing => will throw an exception 'type' => 'integer', 'required' => true, ), ), ); $this->assertEquals(array( 'route' => '/pets', 'parameters' => array(), 'method' => 'GET', ), $creator->getRoutingAnnotation('get', $objects, '/pets')); } /** * */ public function testGetActionComments() { $twig = $this->getMockBuilder('\Twig_Environment')->disableOriginalConstructor()->getMock(); $apiModelCreator = $this->getMockBuilder('Enneite\SwaggerBundle\Creator\ApiModelCreator')->disableOriginalConstructor()->getMock(); $apiModelCreator->expects($this->any()) ->method('formatProperty') ->will($this->returnvalue('id')); $apiRoutingCreator = $this->getMockBuilder('Enneite\SwaggerBundle\Creator\ApiRoutingCreator')->disableOriginalConstructor()->getMock(); $apiRoutingCreator->expects($this->any()) ->method('getRouteParametersAsArray') ->will($this->returnvalue(array())); $creator = new ApiControllerCreator($twig, $apiModelCreator, $apiRoutingCreator); // case 1 : without routing annotation generation and with description set $objects = array( 'description' => 'this is a good description', 'parameters' => array( array( 'name' => 'id', 'in' => 'path', // parameter 'in' is missing => will throw an exception 'type' => 'integer', 'required' => true, ), ), ); $this->assertEquals(array( 'description' => 'this is a good description', 'routing' => null, 'params' => array('id'), ), $creator->getActionComments('get', $objects, '/pets', false)); // case 2 : with routing annotation generation and no description set $objects = array( 'parameters' => array( array( 'name' => 'id', 'in' => 'path', // parameter 'in' is missing => will throw an exception 'type' => 'integer', 'required' => true, ), ), ); $this->assertEquals(array( 'description' => 'empty', 'routing' => array( 'route' => '/pets', 'parameters' => array(), 'method' => 'GET', ), 'params' => array('id'), ), $creator->getActionComments('get', $objects, '/pets', true)); } public function testExtractArguments() { include_once __DIR__ . '/../Controller/Mock/ProductController.php'; $reflexion = new \ReflectionClass('Enneite\SwaggerBundle\Tests\Controller\Mock\ProductController'); $method = $reflexion->getMethod('getAction'); $twig = $this->getMockBuilder('\Twig_Environment')->disableOriginalConstructor()->getMock(); $apiModelCreator = $this->getMockBuilder('Enneite\SwaggerBundle\Creator\ApiModelCreator')->disableOriginalConstructor()->getMock(); $apiRoutingCreator = $this->getMockBuilder('Enneite\SwaggerBundle\Creator\ApiRoutingCreator')->disableOriginalConstructor()->getMock(); $creator = new ApiControllerCreator($twig, $apiModelCreator, $apiRoutingCreator); $this->assertEquals(array('id'), $creator->extractArguments($method)); } public function testGetSchemaResponse() { $php = '(Request $request, $id)'; $template = $this->getMockBuilder('\Twig_Template')->disableOriginalConstructor()->getMock(); $template->expects($this->any()) ->method('render') ->will($this->returnvalue($php)); $twig = $this->getMockBuilder('\Twig_Environment')->disableOriginalConstructor()->getMock(); $twig->expects($this->any()) ->method('loadTemplate') ->will($this->returnvalue($template)); $apiModelCreator = $this->getMockBuilder('Enneite\SwaggerBundle\Creator\ApiModelCreator')->disableOriginalConstructor()->getMock(); $apiModelCreator->expects($this->any()) ->method('extractModel') ->will($this->returnvalue('Product')); $apiRoutingCreator = $this->getMockBuilder('Enneite\SwaggerBundle\Creator\ApiRoutingCreator')->disableOriginalConstructor()->getMock(); $creator = new ApiControllerCreator($twig, $apiModelCreator, $apiRoutingCreator); // tests the template twig arguments generation : $this->assertEquals(array('model' => null, 'method' => null), $creator->getSchemaPhpCode(array())); $this->assertEquals(array('model' => null, 'method' => null), $creator->getSchemaPhpCode(array('schema' => array('type' => 'string')))); $this->assertEquals(array('model' => 'Product', 'method' => 'buildResource'), $creator->getSchemaPhpCode(array( 'schema' => array( '$ref' => '#/definitions/Product', ), ))); $this->assertEquals(array('model' => 'Product', 'method' => 'buildCollection'), $creator->getSchemaPhpCode(array( 'schema' => array( 'type' => 'array', 'items' => array( '$ref' => '#/definitions/Product', ), ), ))); // test the php generation code : $this->assertEquals($php, $creator->createSchemaPhpCode(array())); } public function testCreateClassName() { $twig = $this->getMockBuilder('\Twig_Environment')->disableOriginalConstructor()->getMock(); $apiModelCreator = $this->getMockBuilder('Enneite\SwaggerBundle\Creator\ApiModelCreator')->disableOriginalConstructor()->getMock(); $apiRoutingCreator = $this->getMockBuilder('Enneite\SwaggerBundle\Creator\ApiRoutingCreator')->disableOriginalConstructor()->getMock(); $creator = new ApiControllerCreator($twig, $apiModelCreator, $apiRoutingCreator); $this->assertEquals('PetsController', $creator->getClassName('/pets')); $this->assertEquals('PetsIdController', $creator->getClassName('/pets/{id}')); $this->assertEquals('PetsIdController', $creator->getClassName('/pets/*/{id}$$$')); } }
enneite/swagger-bundle
Tests/Creator/ApiControllerCreatorTest.php
PHP
mit
23,086
var notify = require('gulp-notify'), path = require('path'); var c = exports; c.all = allFiles; c.target = targetFolder; c.TARGET_FOLDER = "./dist"; // fonts c.FOLDER_FONTS = './node_modules/font-awesome/fonts/*'; c.TARGET_FOLDER_FONTS = 'fonts'; // images c.FOLDER_IMAGES = './resources/images/*'; c.TARGET_FOLDER_IMAGES = 'images'; // images c.FOLDER_SOUNDS = './resources/sounds/*'; c.TARGET_FOLDER_SOUNDS = 'sounds'; // less c.FOLDER_LESS = './resources/less'; c.PATH_LESS_ENTRY = './resources/less/app.less'; c.TARGET_FILE_CSS = 'app.css'; c.TARGET_PATH_CSS = 'css/app.css'; c.TARGET_FOLDER_CSS = 'css'; // js c.FOLDER_JS = './resources/js'; c.PATH_JS_ENTRY = './resources/js/app.js'; c.TARGET_FILE_JS = 'app.js'; c.TARGET_PATH_JS = 'js/app.js'; c.TARGET_FOLDER_JS = 'js'; // html files c.PATH_INDEX = "./resources/html/index.html"; c.FOLDER_TEMPLATES = "./resources/templates"; // tests c.FOLDER_TESTS = './resources/js/tests'; // rev c.FILES_REV = [ { name: "appCss", entryPath: c.TARGET_PATH_CSS, targetFile: c.TARGET_FILE_CSS }, { name: "appJs", entryPath: c.TARGET_PATH_JS, targetFile: c.TARGET_FILE_JS }, ]; c.TARGET_FOLDER_ALL = [ c.TARGET_FOLDER_CSS, c.TARGET_FOLDER_FONTS, c.TARGET_FOLDER_JS ] .map(targetFolder) .map(function (folder) { return path.join(folder, "**"); }); c.notify = function (title, message) { return notify({ title: title, message: message }); }; c.notifyError = function notifyError (description) { return function () { var args = [].slice.call(arguments); notify.onError({ title: description + " error", message: "<%= error.message %>" }).apply(this, args); this.emit('end'); // Keep gulp from hanging on this task }; }; function allFiles (folder) { return path.join(folder, '**'); } function targetFolder (folder) { var root = c.TARGET_FOLDER; if (folder) { return path.join(root, folder); } return root; }
bekk/bekkboard
GUI/tasks/config.js
JavaScript
mit
1,991
import { Component, OnDestroy, OnInit, ViewEncapsulation } from '@angular/core'; import { SnotifyService } from '../../services/snotify.service'; import { SnotifyToast } from '../../models/snotify-toast.model'; import { Subscription } from 'rxjs'; import { SnotifyNotifications } from '../../interfaces/snotify-notifications.interface'; import { SnotifyPosition } from '../../enums/snotify-position.enum'; import { SnotifyEventType } from '../../types/snotify-event.type'; @Component({ selector: 'ng-snotify', templateUrl: './snotify.component.html', encapsulation: ViewEncapsulation.None }) export class SnotifyComponent implements OnInit, OnDestroy { /** * Toasts array */ notifications: SnotifyNotifications; /** * Toasts emitter */ emitter: Subscription; /** * Helper for slice pipe (maxOnScreen) */ dockSizeA: number; /** * Helper for slice pipe (maxOnScreen) */ dockSizeB: number | undefined; /** * Helper for slice pipe (maxAtPosition) */ blockSizeA: number; /** * Helper for slice pipe (maxAtPosition) */ blockSizeB: number | undefined; /** * Backdrop Opacity */ backdrop = -1; /** * How many toasts with backdrop in current queue */ withBackdrop: SnotifyToast[]; constructor(private service: SnotifyService) {} /** * Init base options. Subscribe to options, lifecycle change */ ngOnInit() { this.emitter = this.service.emitter.subscribe((toasts: SnotifyToast[]) => { if (this.service.config.global.newOnTop) { this.dockSizeA = -this.service.config.global.maxOnScreen; this.dockSizeB = undefined; this.blockSizeA = -this.service.config.global.maxAtPosition; this.blockSizeB = undefined; this.withBackdrop = toasts.filter(toast => toast.config.backdrop >= 0); } else { this.dockSizeA = 0; this.dockSizeB = this.service.config.global.maxOnScreen; this.blockSizeA = 0; this.blockSizeB = this.service.config.global.maxAtPosition; this.withBackdrop = toasts.filter(toast => toast.config.backdrop >= 0).reverse(); } this.notifications = this.splitToasts(toasts.slice(this.dockSizeA, this.dockSizeB)); this.stateChanged('mounted'); }); } // TODO: fix backdrop if more than one toast called in a row /** * Changes the backdrop opacity * @param event SnotifyEventType */ stateChanged(event: SnotifyEventType) { if (!this.withBackdrop.length) { if (this.backdrop >= 0) { this.backdrop = -1; } return; } switch (event) { case 'mounted': if (this.backdrop < 0) { this.backdrop = 0; } break; case 'beforeShow': this.backdrop = this.withBackdrop[this.withBackdrop.length - 1].config.backdrop; break; case 'beforeHide': if (this.withBackdrop.length === 1) { this.backdrop = 0; } break; case 'hidden': if (this.withBackdrop.length === 1) { this.backdrop = -1; } break; } } /** * Split toasts toasts into different objects * @param toasts SnotifyToast[] * @returns SnotifyNotifications */ splitToasts(toasts: SnotifyToast[]): SnotifyNotifications { const result: SnotifyNotifications = {}; for (const property in SnotifyPosition) { if (SnotifyPosition.hasOwnProperty(property)) { result[SnotifyPosition[property]] = []; } } toasts.forEach((toast: SnotifyToast) => { result[toast.config.position as string].push(toast); }); return result; } /** * Unsubscribe subscriptions */ ngOnDestroy() { this.emitter.unsubscribe(); } }
artemsky/ng-snotify
projects/ng-snotify/src/lib/components/snotify/snotify.component.ts
TypeScript
mit
3,726
using AzureBot.Services.Impl; using AzureBot.Services.Interfaces; using AzureBot.UnitTests.Mocks; using Microsoft.Bot.Connector; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AzureBot.UnitTests.Tests { [TestClass] public class ValidationTest { private IValidationService _validationService; private int MAX_MESSAGE_LENGTH = 500; private int MIN_MESSAGE_LENGTH = 1; public ValidationTest() { _validationService = new ValidationService(MIN_MESSAGE_LENGTH, MAX_MESSAGE_LENGTH); } [TestMethod] public async Task TestMaxiumumMessageLength() { var testUserName = "TestUser"; var testUserId = "0"; var message = new Message() { Type = "Message", Language = "en", From = new ChannelAccount { Id = testUserId, Name = testUserName } }; for (int i = 0; i < MAX_MESSAGE_LENGTH + 1; i++) { message.Text += "a"; } var actualResponse = await _validationService.IsValidMessage(message); var expectedResponse = false; Assert.IsTrue(actualResponse == expectedResponse); } [TestMethod] public async Task TestMinimumMessageLength() { var testUserName = "TestUser"; var testUserId = "0"; var message = new Message() { Type = "Message", Language = "en", From = new ChannelAccount { Id = testUserId, Name = testUserName }, Text = "" }; var actualResponse = await _validationService.IsValidMessage(message); var expectedResponse = false; Assert.IsTrue(actualResponse == expectedResponse); } [TestMethod] public async Task TestValidMessageLength() { var testUserName = "TestUser"; var testUserId = "0"; var message = new Message() { Type = "Message", Language = "en", From = new ChannelAccount { Id = testUserId, Name = testUserName } }; // Assumes MAX_MESSAGE_LENGTH > MIN_MESSAGE_LENGTH + 1 for(int i = 0; i <= MIN_MESSAGE_LENGTH; i++) { message.Text += "a"; } var actualResponse = await _validationService.IsValidMessage(message); var expectedResponse = true; Assert.IsTrue(actualResponse == expectedResponse); } } }
jjcollinge/AzureBot
AzureBot.UnitTests/Tests/ValidationTest.cs
C#
mit
2,999
'use strict'; var isArray = Array.isArray; module.exports = function (t, a) { var el1, el2, el3, result, nodes, c1, c2; if (typeof document === 'undefined') return; el1 = document.createElement('p'); el2 = document.createElement('div'); result = t.call(document, el2, el1, 'Test', null); a(isArray(result), true, "Is Array"); nodes = result; a(nodes[2].nodeType, 3, "String to Text node"); a(nodes[2].data, 'Test', "String to Text node: content"); a.deep(nodes, [el2, el1, nodes[2]], "Children"); el3 = document.createElement('p'); c1 = el3.appendChild(document.createElement('span')); c2 = el3.appendChild(document.createElement('hr')); a.deep(t.call(document, el2, el3.childNodes), [el2, c1, c2], "Child nodes"); a(t.call(document, [[el1]]), el1, "Nested list"); a.deep(t.call(document, [[el1]], el2, el3, el1, el3), [el2, el1, el3], "Unique"); };
egovernment/eregistrations-demo
node_modules/dom-ext/test/document/#/normalize.js
JavaScript
mit
876
# -*- coding: utf-8 -*- # Generated by Django 1.10.2 on 2017-08-17 20:30 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('app_pessoa', '0004_auto_20170817_1727'), ] operations = [ migrations.AlterField( model_name='pessoa', name='profissao', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='app_pessoa.Profissao'), ), ]
LEDS/X-data
Xdata/app_pessoa/migrations/0005_auto_20170817_1730.py
Python
mit
559
class AvailabilitiesController < ApplicationController before_action :authorise_booking_manager! def show @search = SlotSearch.new(search_params) @slots = @search.results end private def search_params params .fetch(:search, {}) .permit(:date, :room, :available) .merge( page: params[:page], location: location ) end def rooms @rooms ||= location.rooms.order(:name) end helper_method :rooms def location @location ||= current_user.locations.find(params[:location_id]) end helper_method :location end
guidance-guarantee-programme/tesco_planner
app/controllers/availabilities_controller.rb
Ruby
mit
589
#include "Build.h" #include "Profiler.h" #include "config/Git.h" #include "config/Version.h" #include <sstream> #include <vector> //OS #if defined(PR_OS_LINUX) #define PR_OS_NAME "Linux" #elif defined(PR_OS_WINDOWS_32) #define PR_OS_NAME "Microsoft Windows 32 Bit" #elif defined(PR_OS_WINDOWS_64) #define PR_OS_NAME "Microsoft Windows 64 Bit" #else #define PR_OS_NAME "Unknown" #endif //Compiler #if defined(PR_CC_CYGWIN) #define PR_CC_NAME "Cygwin" #endif #if defined(PR_CC_GNU) #define PR_CC_NAME "GNU C/C++" #endif #if defined(PR_CC_MINGW32) #if !defined(PR_CC_GNU) #define PR_CC_NAME "MinGW 32" #else #undef PR_CC_NAME #define PR_CC_NAME "GNU C/C++(MinGW 32)" #endif #endif #if defined(PR_CC_INTEL) #define PR_CC_NAME "Intel C/C++" #endif #if defined(PR_CC_MSC) #define PR_CC_NAME "Microsoft Visual C++" #endif #if !defined(PR_CC_NAME) #define PR_CC_NAME "Unknown" #endif #if defined(PR_DEBUG) #define PR_BUILDVARIANT_NAME "Debug" #else #define PR_BUILDVARIANT_NAME "Release" #endif namespace PR { namespace Build { Version getVersion() { return Version{ PR_VERSION_MAJOR, PR_VERSION_MINOR }; } std::string getVersionString() { return PR_VERSION_STRING; } std::string getGitString() { return PR_GIT_BRANCH " " PR_GIT_REVISION; } std::string getCopyrightString() { return PR_NAME_STRING " " PR_VERSION_STRING " (C) " PR_VENDOR_STRING; } std::string getCompilerName() { return PR_CC_NAME; } std::string getOSName() { return PR_OS_NAME; } std::string getBuildVariant() { return PR_BUILDVARIANT_NAME; } std::string getFeatureSet() { std::vector<std::string> list; // Skip basic features required by x64 anyway /*#ifdef PR_HAS_HW_FEATURE_MMX list.emplace_back("MMX"); #endif #ifdef PR_HAS_HW_FEATURE_SSE list.emplace_back("SSE"); #endif #ifdef PR_HAS_HW_FEATURE_SSE2 list.emplace_back("SSE2"); #endif*/ #ifdef PR_HAS_HW_FEATURE_SSE3 list.emplace_back("SSE3"); #endif #ifdef PR_HAS_HW_FEATURE_SSSE3 list.emplace_back("SSSE3"); #endif #ifdef PR_HAS_HW_FEATURE_SSE4_1 list.emplace_back("SSE4.1"); #endif #ifdef PR_HAS_HW_FEATURE_SSE4_2 list.emplace_back("SSE4.2"); #endif #ifdef PR_HAS_HW_FEATURE_AVX list.emplace_back("AVX"); #endif #ifdef PR_HAS_HW_FEATURE_AVX2 list.emplace_back("AVX2"); #endif #ifdef PR_HAS_HW_FEATURE_AVX512_F list.emplace_back("AVX512_F"); #endif #ifdef PR_HAS_HW_FEATURE_AVX512_DQ list.emplace_back("AVX512_DQ"); #endif #ifdef PR_HAS_HW_FEATURE_AVX512_IFMA list.emplace_back("AVX512_IFMA"); #endif #ifdef PR_HAS_HW_FEATURE_AVX512_PF list.emplace_back("AVX512_PF"); #endif #ifdef PR_HAS_HW_FEATURE_AVX512_ER list.emplace_back("AVX512_ER"); #endif #ifdef PR_HAS_HW_FEATURE_AVX512_CD list.emplace_back("AVX512_CD"); #endif #ifdef PR_HAS_HW_FEATURE_AVX512_BW list.emplace_back("AVX512_BW"); #endif #ifdef PR_HAS_HW_FEATURE_AVX512_VL list.emplace_back("AVX512_VL"); #endif #ifdef PR_HAS_HW_FEATURE_AVX512_VBMI list.emplace_back("AVX512_VBMI"); #endif #ifdef PR_HAS_HW_FEATURE_AVX512_VBMI2 list.emplace_back("AVX512_VBMI2"); #endif #ifdef PR_HAS_HW_FEATURE_AVX512_VNNI list.emplace_back("AVX512_VNNI"); #endif #ifdef PR_HAS_HW_FEATURE_AVX512_BITALG list.emplace_back("AVX512_BITALG"); #endif #ifdef PR_HAS_HW_FEATURE_AVX512_VPOPCNTDQ list.emplace_back("AVX512_VPOPCNTDQ"); #endif #ifdef PR_HAS_HW_FEATURE_AVX512_4VNNIW list.emplace_back("AVX512_4VNNIW"); #endif #ifdef PR_HAS_HW_FEATURE_AVX512_4FMAPS list.emplace_back("AVX512_4FMAPS"); #endif #ifdef PR_HAS_HW_FEATURE_AVX512_BF16 list.emplace_back("AVX512_BF16"); #endif #ifdef PR_HAS_HW_FEATURE_HLE list.emplace_back("HLE"); #endif #ifdef PR_HAS_HW_FEATURE_RTM list.emplace_back("RTM"); #endif #ifdef PR_HAS_HW_FEATURE_FMA list.emplace_back("FMA3"); #endif #ifdef PR_HAS_HW_FEATURE_FMA4 list.emplace_back("FMA4"); #endif #ifdef PR_HAS_HW_FEATURE_POPCNT list.emplace_back("POPCNT"); #endif if (list.empty()) return "NONE"; std::stringstream stream; for (size_t i = 0; i < (list.size() - 1); ++i) stream << list.at(i) << "; "; stream << list.back(); return stream.str(); } std::string getBuildString() { #ifdef PR_NO_ASSERTS constexpr bool hasAsserts = false; #else constexpr bool hasAsserts = true; #endif #ifdef PR_WITH_PROFILER constexpr bool hasProfiler = true; #else constexpr bool hasProfiler = false; #endif std::stringstream stream; stream << std::boolalpha << PR_NAME_STRING << " " << PR_VERSION_STRING << " (" << getBuildVariant() << ") on " __DATE__ " at " __TIME__ << " with " << getCompilerName() << " { OS: " << getOSName() << "; Branch: " PR_GIT_BRANCH << "; Rev: " PR_GIT_REVISION << "} [Features:<" << getFeatureSet() << ">; Asserts: " << hasAsserts << "; Profile: " << hasProfiler << "]"; return stream.str(); } } // namespace Build } // namespace PR
PearCoding/PearRay
src/base/config/Build.cpp
C++
mit
4,753
<?php class Contact_model extends CI_Model { function insert($arr = ''){ if(empty($arr)) return ; $sql = "insert into contact (name,email,message,ceatetime,ip) VALUES ('{$arr['name']}','{$arr['email']}','{$arr['message']}','".date('Y-m-d H:i:s')."','{$arr['ip']}')"; $this->db->query($sql); } }
0372/blog
blog/front/models/Contact_model.php
PHP
mit
327
package br.edu.fjn.maternidade.application.impl; import java.util.List; import br.edu.fjn.maternidade.application.SecretarioApplication; import br.edu.fjn.maternidade.domain.secretario.Secretario; import br.edu.fjn.maternidade.domain.secretario.SecretarioRepository; import br.edu.fjn.maternidade.domain.usuario.Usuario; import br.edu.fjn.maternidade.infraestructure.util.MaternidadeException; import br.edu.fjn.maternidade.repository.impl.SecretarioRepositoryImpl; public class SecretarioApplicationImpl implements SecretarioApplication { private SecretarioRepository repository = new SecretarioRepositoryImpl(); @Override public void inserir(Secretario secretario) { repository.inserir(secretario); } @Override public void alterar(Secretario secretario) { repository.alterar(secretario); } @Override public void apagar(Secretario secretario) throws MaternidadeException { if (repository.listar() != null) repository.apagar(secretario); else throw new MaternidadeException( "Voc� n�o pode remover este secret�rio, pois n�o existem outros cadastrados!"); } @Override public Secretario buscarPorId(Integer id) throws MaternidadeException { Secretario busca = repository.buscarPorId(id); if (busca == null) { throw new MaternidadeException("Não há registro de secretário para esta id"); } return busca; } @Override public List<Secretario> listar() throws MaternidadeException { List<Secretario> busca = repository.listar(); if (busca == null || busca.size() == 0) { throw new MaternidadeException("Não há registros de secretários"); } return busca; } @Override public Secretario buscarPorUsuario(Usuario usuario) throws MaternidadeException { Secretario busca = repository.buscarPorUsuario(usuario); if (busca == null) { throw new MaternidadeException("Não há registro de secretário para este usuário"); } return busca; } }
aldaypinheiro/maternidade-core
src/br/edu/fjn/maternidade/application/impl/SecretarioApplicationImpl.java
Java
mit
1,940
<?php session_start(); // declare that sessions are being used session_unset(); // unset sessions session_destroy(); // now destory them and remove them from the users browser header('Location: http://thewebbster.info/get/loginForm.php?logout=yes');// Forwards to a new page after logout exit(); // exit ?>
chwebb1/InsecureGetLoginFormPHP
logout.php
PHP
mit
413
lock '3.4.0' set :application, "people" set :repo_url, "git://github.com/netguru/people.git" set :deploy_to, ENV['DEPLOY_PATH'] set :docker_links, %w(postgres_ambassador:postgres) set :docker_additional_options, -> { "--env-file #{shared_path}/.env" } set :docker_apparmor_profile, "docker-ptrace" namespace :docker do namespace :npm do task :build do on roles(fetch(:docker_role)) do execute :docker, task_command("npm run build") end end end end after "docker:npm:install", "docker:npm:build"
netguru/people
config/deploy.rb
Ruby
mit
532
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import re import uuid from . import utils from .exceptions import (RevisionNotFound, RevisionAlreadyExists, NoRevisionsFound, GoingTooFar, AlreadyHere) def init(directory: str): print('Creating directory', directory) os.mkdir(directory) print('Creating file migro.yaml') with open('migro.yaml', 'w') as file: file.write('database_url: driver://user:pass@localhost/dbname\n' 'script_location: %s\n' % directory) print('Please edit migro.yaml before proceeding.') def current(config: dict): conn, curs = utils.connect(config['database_url']) revisions = utils.parse_dir(config['script_location']) if not revisions: raise NoRevisionsFound curr_rev_id = utils.get_curr_rev_id(conn) curr_rev = next( (x for x in revisions if x['revision'] == curr_rev_id), None) if curr_rev is None: raise RevisionNotFound(curr_rev_id) print(curr_rev['revision'], ':', curr_rev['description']) curs.close() conn.close() def revision(config: dict, message: str): revisions = utils.parse_dir(config['script_location']) latest_rev_id = revisions[-1]['revision'] if revisions else None new_rev_id = str(uuid.uuid4())[-12:] new_rev_filename = os.path.join( config['script_location'], '%s_%s.yaml' % ( new_rev_id, re.sub('\W', '_', message).lower() ) ) if os.path.isfile(new_rev_filename): raise RevisionAlreadyExists with open(new_rev_filename, 'w') as file: file.write( 'description: %s\n\nrevision: %s\n' 'down_revision: %s\n\nupgrade:\n\ndowngrade:\n' % ( message, new_rev_id, latest_rev_id if latest_rev_id is not None else 'null')) print('Created revision at %s' % new_rev_filename) def checkout(config: dict, arg: str): conn, curs = utils.connect(config['database_url']) revisions = utils.parse_dir(config['script_location']) if not revisions: raise NoRevisionsFound curr_rev_id = utils.get_curr_rev_id(conn) curr_rev_index = utils.get_index(revisions, curr_rev_id) if curr_rev_index is None and curr_rev_id is None: curr_rev_index = -1 elif curr_rev_index is None: raise RevisionNotFound(curr_rev_id) if arg == 'head': next_rev_index = len(revisions) - 1 elif utils.isnum(arg): next_rev_index = curr_rev_index + int(arg) if next_rev_index > len(revisions) - 1 or next_rev_index < -1: raise GoingTooFar else: next_rev_index = utils.get_index(revisions, arg) if next_rev_index is None: raise RevisionNotFound(arg) if next_rev_index == curr_rev_index: AlreadyHere() if next_rev_index > curr_rev_index: # Upgrading for rev_index in range(curr_rev_index + 1, next_rev_index + 1): print('Upgrading to', revisions[rev_index]['revision'], ':', revisions[rev_index]['description']) curs.execute(revisions[rev_index]['upgrade']) curs.execute( "TRUNCATE TABLE migro_ver; INSERT INTO migro_ver VALUES (%s);", (revisions[rev_index]['revision'],)) conn.commit() else: # Downgrading for rev_index in range(curr_rev_index, next_rev_index, -1): print('Downgrading from', revisions[rev_index]['revision'], ':', revisions[rev_index]['description']) curs.execute(revisions[rev_index]['downgrade']) curs.execute("TRUNCATE TABLE migro_ver;") if rev_index > 0: curs.execute("INSERT INTO migro_ver VALUES (%s);", (revisions[rev_index - 1]['revision'],)) conn.commit() curs.close() conn.close() def reapply(config: dict): conn, curs = utils.connect(config['database_url']) revisions = utils.parse_dir(config['script_location']) if not revisions: raise NoRevisionsFound curr_rev_id = utils.get_curr_rev_id(conn) curr_rev_index = utils.get_index(revisions, curr_rev_id) if curr_rev_index is None: raise RevisionNotFound(curr_rev_id) print('Reapplying', revisions[curr_rev_index]['revision'], ':', revisions[curr_rev_index]['description']) curs.execute(revisions[curr_rev_index]['downgrade']) curs.execute(revisions[curr_rev_index]['upgrade']) conn.commit() def show(config: dict): conn, curs = utils.connect(config['database_url']) revisions = utils.parse_dir(config['script_location']) if not revisions: raise NoRevisionsFound curr_rev_id = utils.get_curr_rev_id(conn) for rev in revisions: print('[%s]' % ('x' if curr_rev_id == rev['revision'] else ' '), rev['revision'], ':', rev['description'])
ALFminecraft/migro
migro/main.py
Python
mit
4,923
require 'spec_helper' # TODO: the usual respond_to? method doesn't seem to work on Thor objects. # Why not? For now, we'll check against instance_methods. RSpec.describe Moose::Inventory::Cli::Host do before(:all) do # Set up the configuration object @mockarg_parts = { config: File.join(spec_root, 'config/config.yml'), format: 'yaml', env: 'test', } @mockargs = [] @mockarg_parts.each do |key, val| @mockargs << "--#{key}" @mockargs << val end @config = Moose::Inventory::Config @config.init(@mockargs) @db = Moose::Inventory::DB @db.init if @db.db.nil? @host = Moose::Inventory::Cli::Host @app = Moose::Inventory::Cli::Application end before(:each) do @db.reset end #======================= describe 'addgroup' do #------------------------ it 'Host.addgroup() should be responsive' do result = @host.instance_methods(false).include?(:addgroup) expect(result).to eq(true) end #------------------------ it 'host addgroup <missing args> ... should abort with an error' do actual = runner do @app.start(%w(host addgroup)) # <- no group given end # Check output desired = { aborted: true } desired[:STDERR] = "ERROR: Wrong number of arguments, 0 for 2 or more.\n" expected(actual, desired) end #------------------------ it 'host addgroup HOST GROUP ... should abort if the host does not exist' do actual = runner do @app.start(%w(host addgroup not-a-host example)) end # Check output desired = { aborted: true } desired[:STDOUT] = "Associate host 'not-a-host' with groups 'example':\n"\ " - Retrieve host 'not-a-host'...\n" desired[:STDERR] = "An error occurred during a transaction, any changes have been rolled back.\n"\ "ERROR: The host 'not-a-host' was not found in the database.\n" expected(actual, desired) end #------------------------ it 'host addgroup HOST GROUP ... should add the host to an existing group' do # 1. Should add the host to the group # 2. Should remove the host from the 'ungrouped' automatic group name = 'test1' group_name = 'testgroup1' runner { @app.start(%W(host add #{name})) } @db.models[:group].create(name: group_name) actual = runner { @app.start(%W(host addgroup #{name} #{group_name})) } # rubocop:disable Metrics/LineLength desired = { aborted: false } desired[:STDOUT] = "Associate host '#{name}' with groups '#{group_name}':\n"\ " - Retrieve host '#{name}'...\n"\ " - OK\n"\ " - Add association {host:#{name} <-> group:#{group_name}}...\n"\ " - OK\n"\ " - Remove automatic association {host:#{name} <-> group:ungrouped}...\n"\ " - OK\n"\ " - All OK\n"\ "Succeeded\n" expected(actual, desired) # rubocop:enable Metrics/LineLength # We should have the correct group associations host = @db.models[:host].find(name: name) groups = host.groups_dataset expect(groups.count).to eq(1) expect(groups[name: group_name]).not_to be_nil expect(groups[name: 'ungrouped']).to be_nil # redundant, but for clarity! end #------------------------ it 'HOST \'ungrouped\' ... should abort with an error' do name = 'test1' group_name = 'ungrouped' runner { @app.start(%W(host add #{name})) } actual = runner { @app.start(%W(host addgroup #{name} #{group_name})) } desired = { aborted: true } desired[:STDERR] = "ERROR: Cannot manually manipulate the automatic group 'ungrouped'.\n" expected(actual, desired) end #------------------------ it 'HOST GROUP ... should add the host to an group, creating the group if necessary' do name = 'test1' group_name = 'testgroup1' runner { @app.start(%W(host add #{name})) } # DON'T CREATE THE GROUP! That's the point of the test. ;o) actual = runner { @app.start(%W(host addgroup #{name} #{group_name})) } # Check output desired = { aborted: false } desired[:STDOUT] = "Associate host '#{name}' with groups '#{group_name}':\n"\ " - Retrieve host '#{name}'...\n"\ " - OK\n"\ " - Add association {host:#{name} <-> group:#{group_name}}...\n"\ " - Group does not exist, creating now...\n"\ " - OK\n"\ " - OK\n"\ " - Remove automatic association {host:#{name} <-> group:ungrouped}...\n"\ " - OK\n"\ " - All OK\n"\ "Succeeded\n" desired[:STDERR] = "WARNING: Group '#{group_name}' does not exist and will be created." expected(actual, desired) # Check db host = @db.models[:host].find(name: name) groups = host.groups_dataset expect(groups.count).to eq(1) expect(groups[name: group_name]).not_to be_nil expect(groups[name: 'ungrouped']).to be_nil # redundant, but for clarity! end #------------------------ it 'HOST GROUP ... should skip associations that already '\ ' exist, but raise a warning.' do name = 'test1' group_name = 'testgroup1' runner { @app.start(%W(host add #{name})) } # DON'T CREATE THE GROUP! That's the point of the test. ;o) # Run once to make the association runner { @app.start(%W(host addgroup #{name} #{group_name})) } # Run again, to prove expected result actual = runner { @app.start(%W(host addgroup #{name} #{group_name})) } # Check output # Note: This time, we don't expect to see any messages about # dissociation from 'ungrouped' desired = { aborted: false } desired[:STDOUT] = "Associate host '#{name}' with groups '#{group_name}':\n"\ " - Retrieve host \'#{name}\'...\n"\ " - OK\n"\ " - Add association {host:#{name} <-> group:#{group_name}}...\n"\ " - Already exists, skipping.\n"\ " - OK\n"\ " - All OK\n"\ "Succeeded\n" desired[:STDERR] = "WARNING: Association {host:#{name} <-> group:#{group_name}} already exists, skipping." expected(actual, desired) # Check db host = @db.models[:host].find(name: name) groups = host.groups_dataset expect(groups.count).to eq(1) expect(groups[name: group_name]).not_to be_nil expect(groups[name: 'ungrouped']).to be_nil # redundant, but for clarity! end #------------------------ it 'host addgroup GROUP1 GROUP1 ... should add the host to'\ ' multiple groups at once' do name = 'test1' group_names = %w(group1 group2 group3) runner { @app.start(%W(host add #{name})) } actual = runner { @app.start(%W(host addgroup #{name}) + group_names) } # Check output desired = { aborted: false, STDERR: '' } desired[:STDOUT] = "Associate host '#{name}' with groups '#{group_names.join(',')}':\n"\ " - Retrieve host '#{name}'...\n"\ " - OK\n" group_names.each do |group| desired[:STDOUT] = desired[:STDOUT] + " - Add association {host:#{name} <-> group:#{group}}...\n"\ " - Group does not exist, creating now...\n"\ " - OK\n"\ " - OK\n" desired[:STDERR] = desired[:STDERR] + "WARNING: Group '#{group}' does not exist and will be created." end desired[:STDOUT] = desired[:STDOUT] + " - Remove automatic association {host:#{name} <-> group:ungrouped}...\n"\ " - OK\n"\ " - All OK\n"\ "Succeeded\n" expected(actual, desired) # We should have group associations host = @db.models[:host].find(name: name) groups = host.groups_dataset expect(groups).not_to be_nil # There should be 3 relationships, but not with 'ungrouped' expect(groups.count).to eq(3) group_names.each do |group| expect(groups[name: group]).not_to be_nil end expect(groups[name: 'ungrouped']).to be_nil end end end
RusDavies/moose-inventory
spec/lib/moose_inventory/cli/host_addgroup_spec.rb
Ruby
mit
8,359
$(function() { //switch the menu style in a area of site $(window).on("scroll", function() { var black_opacity = $("#top-session"); var projetos = $("#projetos"); var contatos = $("#contato"); var offsetblack_opacity = black_opacity.offset(); var offsetprojetos = projetos.offset(); var offsetcontatos = contatos.offset(); //scroll on top session div if($(window).scrollTop() >= offsetblack_opacity.top) { $("#menu-project").removeClass("menu-active"); $("#menu-inicio").addClass("menu-active"); $("#menu-contact").removeClass("menu-active"); $(".menu-text").css("color", "#FFF"); $("#ic_sn").attr("src", "images/sidenav_ic_light.png"); } //scroll on projects div if($(window).scrollTop() >= offsetprojetos.top) { $(".menu").addClass("menu2"); $("#menu-project").addClass("menu-active"); $("#menu-inicio").removeClass("menu-active"); $("#menu-contact").removeClass("menu-active"); $(".menu-text").css("color", "#282727"); $("#ic_sn").attr("src", "images/sidenav_ic_gray.png"); } else { $(".menu").removeClass("menu2"); } //scroll on contact div if($(window).scrollTop() >= offsetcontatos.top) { $("#menu-project").removeClass("menu-active"); $("#menu-inicio").removeClass("menu-active"); $("#menu-contact").addClass("menu-active"); } }); });
gabrieldev525/me
js/script-jquery.js
JavaScript
mit
1,335
<script type="text/javascript"> $(document).ready(function(){ $("#new-user").submit(function(e){ e.preventDefault(); if($("input[name=user_confirm_password]").val() != $("input[name=user_password]").val()){ $("input[name=user_password]").css("border-bottom", "1px solid red"); $("input[name=user_confirm_password]").css("border-bottom", "1px solid red").focus(); return false; }else{ $.ajax({ url: "<?php echo site_url('/UserController/createUser')?>", type: "POST", data: $("#new-user").serialize(), success: function(data){ if(data == 1){ Materialize.toast("Usuário cadastrado com sucesso", 4000); $("#new-user").each (function(){ this.reset(); }); }else{ Materialize.toast(data, 4000); } }, error: function(data){ console.log(data); Materialize.toast("Ocorreu algum erro", 4000); } }); } }); }); </script> <div class="container"> <div class="row"> <a href="<?=base_url('users') ?>">< Voltar para usuários</a> <div div class="row card-panel"> <h4 class="center">Novo Usuário</h4> <form id="new-user"> <div> <label for="user-name">Nome *</label> <input name="user_name" required="required" type="text"> </div> <div> <label for="user-name">Login de acesso *</label> <input name="user_login" required="required" type="text"> </div> <div> <label for="user-name">Senha *</label> <input name="user_password" required="required" type="password"> </div> <div> <label for="user-name">Confirmar senha *</label> <input name="user_confirm_password" required="required" type="password"> </div> <div class="" align="right"> <button type="submit" id="" class="btn green">Salvar<i class="material-icons right">send</i> </button> </div> </form> </div> </div> </div>
lds-ulbra-torres/projeto-slave
application/views/users/CreateUserView.php
PHP
mit
1,898
Items = new Mongo.Collection('items'); Items.allow({ insert: function(userId, doc) { return !!userId; }, update: function(userId, doc) { return !!userId; }, remove: function(userId, doc) { return !!userId; } }); ItemSchema = new SimpleSchema({ name: { type: String, label: "Item Name" }, description: { type: String, label: "Description" }, weight: { type: Number, label: "Weight" }, quantity: { type: Number, label: "Quantity" }, session: { type: String, label: "Session", autoValue: function(){ return this.userId }, autoform: { type: "hidden" } }, owner: { type: String, label: "Owner", defaultValue: "DM", autoform: { type: "hidden" } }, createdAt: { type: Date, label: "Created At", autoValue: function(){ return new Date() }, autoform: { type: "hidden" } }, inGroupStash: { type: Boolean, label: 'In Group Stash', defaultValue: false, autoform: { type: "hidden" } } }); Meteor.methods({ toggleGroupItem: function(id, currentState) { Items.update(id, { $set: { inGroupStash: !currentState } }); }, toggleDMItem: function(id) { Items.update(id, { $set: { owner: 'Group' } }); }, togglePlayerItem: function(id, newOwner) { Items.update(id, { $set: { owner: newOwner } }); } }); Items.attachSchema(ItemSchema);
mrogach2350/rpgLoot
collections/items.js
JavaScript
mit
1,589
package handler import ( "encoding/json" "io/ioutil" "net/http" "net/url" "strings" "github.com/playlyfe/go-graphql" "golang.org/x/net/context" ) //Shortcuts for the Content-Type header const ( ContentTypeJSON = "application/json" ContentTypeGraphQL = "application/graphql" ContentTypeFormURLEncoded = "application/x-www-form-urlencoded" ) //Handler structure type Handler struct { Executor *graphql.Executor Context interface{} Pretty bool } //RequestParameters from query like " /graphql?query=getUser($id:ID){lastName}&variables={"id":"4"} " type RequestParameters struct { Query string `json:"query" url:"query" schema:"query"` Variables map[string]interface{} `json:"variables" url:"variables" schema:"variables"` OperationName string `json:"operationName" url:"operationName" schema:"operationName"` } //RequestParametersCompatibility represents an workaround for getting`variables` as a JSON string type RequestParametersCompatibility struct { Query string `json:"query" url:"query" schema:"query"` Variables string `json:"variables" url:"variables" schema:"variables"` OperationName string `json:"operationName" url:"operationName" schema:"operationName"` } func getFromURL(values url.Values) *RequestParameters { if values.Get("query") != "" { // get variables map var variables map[string]interface{} variablesStr := values.Get("variables") json.Unmarshal([]byte(variablesStr), variables) return &RequestParameters{ Query: values.Get("query"), Variables: variables, OperationName: values.Get("operationName"), } } return nil } // NewRequestParameters Parses a http.Request into GraphQL request options struct func NewRequestParameters(r *http.Request) *RequestParameters { if reqParams := getFromURL(r.URL.Query()); reqParams != nil { return reqParams } if r.Method != "POST" { return &RequestParameters{} } if r.Body == nil { return &RequestParameters{} } // TODO: improve Content-Type handling contentTypeStr := r.Header.Get("Content-Type") contentTypeTokens := strings.Split(contentTypeStr, ";") contentType := contentTypeTokens[0] switch contentType { case ContentTypeGraphQL: body, err := ioutil.ReadAll(r.Body) if err != nil { return &RequestParameters{} } return &RequestParameters{ Query: string(body), } case ContentTypeFormURLEncoded: if err := r.ParseForm(); err != nil { return &RequestParameters{} } if reqParams := getFromURL(r.PostForm); reqParams != nil { return reqParams } return &RequestParameters{} case ContentTypeJSON: fallthrough default: var params RequestParameters body, err := ioutil.ReadAll(r.Body) if err != nil { return &params } err = json.Unmarshal(body, &params) if err != nil { // Probably `variables` was sent as a string instead of an object. // So, we try to be polite and try to parse that as a JSON string var CompatibleParams RequestParametersCompatibility json.Unmarshal(body, &CompatibleParams) json.Unmarshal([]byte(CompatibleParams.Variables), &params.Variables) } return &params } } // ContextHandler provides an entrypoint into executing graphQL queries with a // user-provided context. func (h *Handler) ContextHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) { // get query params := NewRequestParameters(r) // execute graphql query result, _ := (h.Executor).Execute(h.Context, params.Query, params.Variables, params.OperationName) if h.Pretty { w.WriteHeader(200) //http.StatusOK = 200 buff, _ := json.MarshalIndent(result, "", " ") w.Write(buff) } else { w.WriteHeader(200) //http.StatusOK = 200 buff, _ := json.Marshal(result) w.Write(buff) } } // ServeHTTP provides an entrypoint into executing graphQL queries. func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { h.ContextHandler(context.Background(), w, r) } //Config for handler of the schema type Config Handler //New config func New(c *Config) *Handler { if c == nil { c = &Config{ Executor: nil, Context: "", Pretty: true, } } if c.Executor == nil { panic("Undefined GraphQL Executor") } return &Handler{ Executor: c.Executor, Context: c.Context, Pretty: c.Pretty, } }
krypton97/HandleGraphQL
handler.go
GO
mit
4,325
/** * The slideshow controller. * Get settings and initialise PrismSlider for each layer, * add controls and events, then call slideTo method on click. * @return {Object} The set of public methods. */ var slideshow = (function(window, undefined) { 'use strict'; /** * Enum navigation classes, attributes and * provide navigation DOM element container. */ var navigation = { selector: '.navigation', element: null, bullet: 'li', attrs: { active: 'active', index: 'data-index' } }; /** * Enum main element, sizes and provide * main DOM element container. * @type {Object} */ var container = { selector: '.prism-slider', element: null, sizes: { w: 1200, h: 960 } }; /** * Set of images to be used. * @type {Array} */ var slides = [ 'img/nature-a.jpg', 'img/nature-b.jpg', 'img/nature-c.jpg', 'img/nature-d.jpg' ]; /** * Set of masks with related effects. * @type {Array} */ var masks = [ { source: 'img/masks/cube-a.svg', effects: { flip: 'Y', rotate: 167 // degrees } }, { source: 'img/masks/cube-b.svg', effects: { flip: 'X', rotate: 90 // degrees } }, { source: 'img/masks/cube-c.svg', effects: { flip: false, rotate: 13 // degrees } } ]; /** * Set global easing. * @type {Function(currentTime)} */ var easing = Easing.easeInOutQuint; /** * Set global duration. * @type {Number} */ var duration = 1300; /** * Container for PrismSlider instances. * @type {Object} */ var instances = {}; /** * Init. */ function init() { getContainer_(); initSlider_(); initPrism_(); addNavigation_(); addEvents_(); } /** * Get main container element, and store in container element. */ function getContainer_() { container.element = document.querySelector(container.selector); } /** * Init Slides. * Create and initialise main background slider (first layer). * Since we'll use this as main slider no mask is given. */ function initSlider_() { instances.slider = new PrismSlider({ container: container, slides: slides, mask: false, duration: duration, easing: easing }); // Initialise instance. instances.slider.init(); } /** * Init Masks. * Loop masks variable and create a new layer for each mask object. */ function initPrism_() { masks.forEach(function(mask, i) { // Generate reference name. var name = 'mask_' + i; instances[name] = new PrismSlider({ container: container, slides: slides, mask: mask, // Here is the mask object. duration: duration, easing: easing }); // Initialise instance. instances[name].init(); }); } /** * Add Navigation. * Create a new bullet for each slide and add it to navigation (ul) * with data-index reference. */ function addNavigation_() { // Store navigation element. navigation.element = document.querySelector(navigation.selector); slides.forEach(function(slide, i) { var bullet = document.createElement(navigation.bullet); bullet.setAttribute(navigation.attrs.index, i); // When it's first bullet set class as active. if (i === 0) bullet.className = navigation.attrs.active; navigation.element.appendChild(bullet); }); } /** * Add Events. * Bind click on bullets. */ function addEvents_() { // Detect click on navigation elment (ul). navigation.element.addEventListener('click', function(e) { // Get clicked element. var bullet = e.target; // Detect if the clicked element is actually a bullet (li). var isBullet = bullet.nodeName === navigation.bullet.toUpperCase(); // Check bullet and prevent action if animation is in progress. if (isBullet && !instances.slider.isAnimated) { // Remove active class from all bullets. for (var i = 0; i < navigation.element.childNodes.length; i++) { navigation.element.childNodes[i].className = ''; } // Add active class to clicked bullet. bullet.className = navigation.attrs.active; // Get index from data attribute and convert string to number. var index = Number(bullet.getAttribute(navigation.attrs.index)); // Call slideAllTo method with index. slideAllTo_(index); } }); } /** * Call slideTo method of each instance. * In order to sync sliding of all layers we'll loop through the * instances object and call the slideTo method for each instance. * @param {Number} index The index of the destination slide. */ function slideAllTo_(index) { // Loop PrismSlider instances. for (var key in instances) { if (instances.hasOwnProperty(key)) { // Call slideTo for current instance. instances[key].slideTo(index); } } } return { init: init }; })(window); /** * Bootstrap slideshow plugin. * For demo purposes images are preloaded inside a div hidden with css, * the plugin initialisation is delayed through window.onload, in a real life * scenario would be better to preload images asynchronously with javascript. */ window.onload = slideshow.init;
claudiocalautti/prism-slider
js/slideshow3.js
JavaScript
mit
5,466
// JavaScript Variables and Objects // I paired by myself on this challenge. // __________________________________________ // Write your code below. var secretNumber = 7 var password = 'just open the door' var allowedIn = false var members = ['John', 'Joe', 'Mike', 'Mary'] // __________________________________________ // Test Code: Do not alter code below this line. function assert(test, message, test_number) { if (!test) { console.log(test_number + "false"); throw "ERROR: " + message; } console.log(test_number + "true"); return true; } assert( (typeof secretNumber === 'number'), "The value of secretNumber should be a number.", "1. " ) assert( secretNumber === 7, "The value of secretNumber should be 7.", "2. " ) assert( typeof password === 'string', "The value of password should be a string.", "3. " ) assert( password === "just open the door", "The value of password should be 'just open the door'.", "4. " ) assert( typeof allowedIn === 'boolean', "The value of allowedIn should be a boolean.", "5. " ) assert( allowedIn === false, "The value of allowedIn should be false.", "6. " ) assert( members instanceof Array, "The value of members should be an array", "7. " ) assert( members[0] === "John", "The first element in the value of members should be 'John'.", "8. " ) assert( members[3] === "Mary", "The fourth element in the value of members should be 'Mary'.", "9. " )
robertreith/phase-0
week-7/variables-objects.js
JavaScript
mit
1,472
// Chargement des données (en queuing pour plus de rapidité) queue(1) .defer(d3.json, "/dataviz/rgph2014/tunisiageo.json") .defer(d3.csv, "/dataviz/rgph2014/rgph2014.csv") .awaitAll(function(error, results){ var topology = results[0] var governorates = topojson.feature(topology, topology.objects.governorates).features; // gouvernorats var data = results[1] data = d3.nest() .key(function(d){ return d.id_gouv ; }) .rollup(function(d){ return d[0]; }) .map(data, d3.map); var margin = {top: 0, right: 350, bottom: 50, left: 0}; var width = 680 - margin.left - margin.right, height = 580 - margin.top - margin.bottom; var scale = 3000; var map_container = d3.select("#carto").append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom); var left_map = map_container.append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); // créer la carte var projection = d3.geo.mercator() .center([9.7, 33.95]) .scale(scale) .translate([width/2 , height/2]); var path = d3.geo.path().projection(projection); left_map.selectAll(".governorate").data(governorates).enter().append("path") .attr("d", path) .attr("class", "governorate"); var right_map = map_container.append("g") .attr("transform", "translate(" + (margin.left + 400) + "," + margin.top + ")"); // créer la carte var projection = d3.geo.mercator() .center([9.7, 33.95]) .scale(scale) .translate([width/2 , height/2]); var path = d3.geo.path().projection(projection); right_map.selectAll(".governorate").data(governorates).enter().append("path") .attr("d", path) .attr("class", "governorate"); var chomage_color_scale = d3.scale.quantile() .domain(data.values().map(function(d){ return 100*+d.nb_chomeurs_total/(+d.nb_chomeurs_total + +d.nb_occupes_total) })) .range(colorbrewer.Reds[5]); var analphabetisme_color_scale = d3.scale.quantile() .domain(data.values().map(function(d){ return 100*+d.nb_analphabetes_total/+d.nb_population_total })) .range(colorbrewer.Oranges[5]); left_map.selectAll(".governorate").style("fill", function(d){ return chomage_color_scale( 100*+data.get(d.properties.gov_id).nb_chomeurs_total/(+data.get(d.properties.gov_id).nb_chomeurs_total + +data.get(d.properties.gov_id).nb_occupes_total)); }) right_map.selectAll(".governorate").style("fill", function(d){ return analphabetisme_color_scale( 100*+data.get(d.properties.gov_id).nb_analphabetes_total/+data.get(d.properties.gov_id).nb_population_total ); }) var left_legend = map_container.append("g") .attr("transform", "translate(" + (margin.left) + "," + (margin.top + height) + ")"); left_legend.append("text").text("Taux de chômage (%)").attr("class", "legend-title"); })
mahrsi/mahrsi.github.io
dataviz/rgph2014/rgph2014.js
JavaScript
mit
3,263
# frozen_string_literal: true module PeopleHelper def private_information(info, name: false) if name session[:privacy_mode] ? info.initials : info.full_name else session[:privacy_mode] ? 'hidden' : info end end alias pii private_information def address_fields_to_sentence(person) person.address? ? person.address_fields_to_sentence : 'No address' end def city_state_to_sentence(person) str = [person.city, person.state].reject(&:blank?).join(', ') str.empty? ? 'No address' : str end end
BlueRidgeLabs/kimball
app/helpers/people_helper.rb
Ruby
mit
541
// @flow import React, { Component } from 'react'; import type { Children } from 'react'; import { Sidebar } from '../components'; export default class App extends Component { props: { children: Children }; render() { return ( <div> <Sidebar /> <div className="main-panel"> {this.props.children} </div> </div> ); } }
hlynn93/basic_ims
app/containers/App.js
JavaScript
mit
385
import styled from 'styled-components'; import { colors } from '@keen.io/colors'; export const Wrapper = styled.div` padding: 20px; border-top: solid 1px ${colors.gray[300]}; `; export const Container = styled.div` display: flex; gap: 20px; `; export const TitleContainer = styled.div` min-width: 100px; `;
keen/explorer
src/components/BrowserPreview/components/DashboardsConnection/DashboardsConnection.styles.ts
TypeScript
mit
320
/* Copyright (c) 2014 code.fm 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 ductive.parse; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.junit.Before; import org.junit.Test; import ductive.parse.errors.UnexpectedCharacterException; import ductive.parse.jline.CompletorAdapter; import jline.console.completer.Completer; public class SimpleCompleterTests { private ArrayList<CharSequence> suggestions; private Parser<String> parser; private Completer completer; @Before public void before() { suggestions = new ArrayList<>(); parser = Parsers.string("aa").followedBy(Parsers.WHITESPACE).token(); completer = new CompletorAdapter<>(parser); } @Test public void a1() { Parser<String> example = Parsers.string("bla").example("a","b").token(); CompletorAdapter<String> completor = new CompletorAdapter<>(example); int pos = completor.complete("",0,suggestions); assertThat(suggestions,is(list("a","b"))); assertEquals(0,pos); } @Test public void empty() { long pos=completer.complete("",0,suggestions); assertThat(suggestions,is(list("aa "))); assertEquals(0,pos); } @Test public void a() { long pos=completer.complete("a",1,suggestions); assertThat(suggestions,is(list("aa "))); assertEquals(0,pos); } @Test public void aa() { long pos=completer.complete("aa",2,suggestions); assertThat(suggestions,is(list("aa "))); assertEquals(0,pos); } @Test public void aa_() { long pos=completer.complete("aa ",3,suggestions); assertEquals(0,suggestions.size()); assertEquals(0,pos); } @Test(expected=UnexpectedCharacterException.class) public void b() { long pos=completer.complete("b",1,suggestions); assertEquals(1,suggestions.size()); assertEquals(0,pos); } private List<CharSequence> list(String ... args) { List<CharSequence> result = new ArrayList<>(); for(String arg : args) result.add(arg); return result; } @Test public void list() { Parser<List<String>> p = Parsers.list(Arrays.asList(Parsers.string("--"),Parsers.string("arg"))).token(); CompletorAdapter<List<String>> completer = new CompletorAdapter<>(p); long pos=completer.complete("-",1,suggestions); assertThat(suggestions,is(list("--arg"))); assertEquals(0,pos); } @Test public void list2() { Parser<List<String>> p = Parsers.list(Arrays.asList(Parsers.string("--"),Parsers.string("arg"))).token(); CompletorAdapter<List<String>> completer = new CompletorAdapter<>(p); long pos=completer.complete("--",2,suggestions); assertThat(suggestions,is(list("--arg"))); assertEquals(0,pos); } @Test public void list3() { Parser<List<String>> p = Parsers.list(Arrays.asList(Parsers.string("--"),Parsers.string("arg"))).token(); CompletorAdapter<List<String>> completer = new CompletorAdapter<>(p); long pos=completer.complete("--a",3,suggestions); assertThat(suggestions,is(list("--arg"))); assertEquals(0,pos); } @Test public void list4() { Parser<List<String>> p = Parsers.list(Arrays.asList(Parsers.string("--"),Parsers.string("arg"))).token(); CompletorAdapter<List<String>> completer = new CompletorAdapter<>(p); long pos=completer.complete("--a",2,suggestions); assertThat(suggestions,is(list("--arg"))); assertEquals(0,pos); } @Test public void tuple1() { Parser<Tuple<String,String>> p = Parsers.tuple(Parsers.string("--"),Parsers.string("arg")).token(); CompletorAdapter<Tuple<String, String>> completer = new CompletorAdapter<>(p); long pos=completer.complete("-",1,suggestions); assertThat(suggestions,is(list("--arg"))); assertEquals(0,pos); } @Test public void tuple2() { Parser<Tuple<String,String>> p = Parsers.tuple(Parsers.string("--"),Parsers.string("arg")).token(); CompletorAdapter<Tuple<String, String>> completer = new CompletorAdapter<>(p); long pos=completer.complete("",0,suggestions); assertThat(suggestions,is(list("--arg"))); assertEquals(0,pos); } @Test public void tuple3() { Parser<Tuple<String,String>> p = Parsers.tuple(Parsers.string("--"),Parsers.string("arg")).token(); CompletorAdapter<Tuple<String, String>> completer = new CompletorAdapter<>(p); long pos=completer.complete("--a",3,suggestions); assertThat(suggestions,is(list("--arg"))); assertEquals(0,pos); } @Test public void optionalCompleteParseAvailable() { Parser<String> example = Parsers.WHITESPACE.optional().precedes(Parsers.string("blah").token()); CompletorAdapter<String> completor = new CompletorAdapter<>(example); int pos = completor.complete(" ",2,suggestions); assertThat(suggestions,is(list("blah"))); assertEquals(2,pos); } @Test public void optionalCompleteParseUnavailable() { Parser<String> example = Parsers.WHITESPACE.optional().precedes(Parsers.string("blah").token()); CompletorAdapter<String> completor = new CompletorAdapter<>(example); int pos = completor.complete("",0,suggestions); assertThat(suggestions,is(list("blah"))); assertEquals(0,pos); } @Test public void optionalCompleteAlreadyPartialParsed() { Parser<String> example = Parsers.WHITESPACE.optional().precedes(Parsers.string("blah").token()); CompletorAdapter<String> completor = new CompletorAdapter<>(example); int pos = completor.complete("bl",2,suggestions); assertThat(suggestions,is(list("blah"))); assertEquals(0,pos); } @Test public void doubleQuote1() { Parser<String> p = Parsers.string("\"data\"").token(); CompletorAdapter<String> completer = new CompletorAdapter<>(p); long pos=completer.complete("",0,suggestions); assertThat(suggestions,is(list("\"data\""))); assertEquals(0,pos); } @Test public void doubleQuote() { Parser<String> p = Parsers.doubleQuoted(Parsers.string("data")).token(); CompletorAdapter<String> completer = new CompletorAdapter<>(p); long pos=completer.complete("",0,suggestions); assertThat(suggestions,is(list("\"data\""))); assertEquals(0,pos); } @Test public void doubleQuote2() { Parser<String> p = Parsers.doubleQuoted(Parsers.string("data")).token(); CompletorAdapter<String> completer = new CompletorAdapter<>(p); long pos=completer.complete("\"",1,suggestions); assertThat(suggestions,is(list("\"data\""))); assertEquals(0,pos); } @Test public void openDoubleQuotedStringWithDanglingQuoteChar() { Parser<String> p = Parsers.doubleQuoted(Parsers.string("\\")).token(); CompletorAdapter<String> completer = new CompletorAdapter<>(p); long pos=completer.complete("\"\\",2,suggestions); assertThat(suggestions,is(list("\"\\\\\""))); assertEquals(0,pos); } @Test public void doubleQuoteMulti() { Parser<String> p = Parsers.doubleQuoted(Parsers.or(Parsers.string("data"),Parsers.string("datum"))).token(); CompletorAdapter<String> completer = new CompletorAdapter<>(p); long pos=completer.complete("\"",1,suggestions); assertThat(suggestions,is(list("\"data\"","\"datum\""))); assertEquals(0,pos); } @Test public void doubleQuoteMultiInnerParserHasCharsToEat() { Parser<String> p = Parsers.doubleQuoted(Parsers.or(Parsers.string("data"),Parsers.string("datum"))).token(); CompletorAdapter<String> completer = new CompletorAdapter<>(p); long pos=completer.complete("\"dat",4,suggestions); assertThat(suggestions,is(list("\"data\"","\"datum\""))); assertEquals(0,pos); } @Test public void doubleQuoteMultiInnerStringContainsQuotedChars() { Parser<String> p = Parsers.doubleQuoted(Parsers.or(Parsers.string("da\"ta"),Parsers.string("da\"tum"))).token(); CompletorAdapter<String> completer = new CompletorAdapter<>(p); long pos=completer.complete("\"da\\\"t",5,suggestions); assertThat(suggestions,is(list("\"da\\\"ta\"","\"da\\\"tum\""))); assertEquals(0,pos); } @Test public void doubleQuoteMultiInnerStringContainsQuotedChars2() { Parser<String> p = Parsers.doubleQuoted(Parsers.or(Parsers.string("da\"ta"),Parsers.string("da\"tum"))).token(); CompletorAdapter<String> completer = new CompletorAdapter<>(p); long pos=completer.complete("\"da\\\"ta",7,suggestions); assertThat(suggestions,is(list("\"da\\\"ta\""))); assertEquals(0,pos); } }
groestl/ductive
test-src/ductive/parse/SimpleCompleterTests.java
Java
mit
9,237
using BasicMessaging.Domain.Places.Models; using Brickweave.Cqrs; namespace BasicMessaging.Domain.Places.Commands { public class CreatePlace : ICommand<Place> { public CreatePlace(string name) { Name = name; } public string Name { get; } } }
agartee/Brickweave
samples/2. BasicMessaging/src/BasicMessaging.Domain/Places/Commands/CreatePlace.cs
C#
mit
303
/* * The MIT License (MIT) * * Copyright (c) 2014-2016 Christian Schudt * * 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 rocks.xmpp.extensions.muc.model; import rocks.xmpp.addr.Jid; /** * The {@code <actor/>} element, which is used in both <code>#admin</code> and <code>#user</code> namespace to indicate who has kicked or banned another user. * * @author Christian Schudt */ public interface Actor { /** * Gets the nick name. * * @return The nick name. */ String getNick(); /** * Gets the JID. * * @return The JID. */ Jid getJid(); }
jeozey/XmppServerTester
xmpp-extensions/src/main/java/rocks/xmpp/extensions/muc/model/Actor.java
Java
mit
1,690
package net.tofweb.starlite; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; public class CostBlockManagerTest { private CellSpace space; @Before public void setup() { space = new CellSpace(); space.setGoalCell(10, 10, 10); space.setStartCell(-5, -5, -5); } @Test public void test() { CostBlockManager manager = new CostBlockManager(space); Cell cell = space.makeNewCell(3, 3, 3); assertFalse(manager.isBlocked(cell)); CellInfo returnedInfo = space.getInfo(cell); assertNotNull(returnedInfo); assertTrue(1.0 == returnedInfo.getCost()); } @Test public void testBlocked() { CostBlockManager manager = new CostBlockManager(space); Cell cell = space.makeNewCell(3, 3, 3); manager.blockCell(cell); assertTrue(manager.isBlocked(cell)); CellInfo returnedInfo = space.getInfo(cell); assertNotNull(returnedInfo); assertTrue(-1.0 == returnedInfo.getCost()); } }
LynnOwens/starlite
src/test/java/net/tofweb/starlite/CostBlockManagerTest.java
Java
mit
1,036
export * from './components'; export * from './questions.module';
dormd/ng2-countries-trivia
src/app/modules/questions/index.ts
TypeScript
mit
65
<!-- Safe sample input : reads the field UserData from the variable $_GET sanitize : cast via + = 0 File : unsafe, use of untrusted data in the function setInterval --> <!--Copyright 2015 Bertrand STIVALET Permission is hereby granted, without written agreement or royalty fee, to use, copy, modify, and distribute this software and its documentation for any purpose, provided that the above copyright notice and the following three paragraphs appear in all copies of this software. IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.--> <!DOCTYPE html> <html> <head> <script> <?php $tainted = $_GET['UserData']; $tainted += 0 ; echo "window.setInterval('". $tainted ."');" ; ?> </script> </head> <body> <h1>Hello World!</h1> </body> </html>
stivalet/PHP-Vulnerability-test-suite
XSS/CWE_79/safe/CWE_79__GET__CAST-cast_int_sort_of__Use_untrusted_data_script-window_SetInterval.php
PHP
mit
1,289
<?php /* * This file is part of App/Validation. * * (c) Alexandre Gomes Gaigalas <alexandre@gaigalas.net> * * For the full copyright and license information, please view the "LICENSE.md" * file that was distributed with this source code. */ namespace App\Validation\Rules\SubdivisionCode; use App\Validation\Rules\AbstractSearcher; /** * Validator for El Salvador subdivision code. * * ISO 3166-1 alpha-2: SV * * @link http://www.geonames.org/SV/administrative-division-el-salvador.html */ class SvSubdivisionCode extends AbstractSearcher { public $haystack = [ 'AH', // Ahuachapan 'CA', // Cabanas 'CH', // Chalatenango 'CU', // Cuscatlan 'LI', // La Libertad 'MO', // Morazan 'PA', // La Paz 'SA', // Santa Ana 'SM', // San Miguel 'SO', // Sonsonate 'SS', // San Salvador 'SV', // San Vicente 'UN', // La Union 'US', // Usulutan ]; public $compareIdentical = true; }
Javier-Solis/admin-project
app/Validation/Rules/SubdivisionCode/SvSubdivisionCode.php
PHP
mit
1,011
package kusto // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. import ( "context" "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/azure" "github.com/Azure/go-autorest/autorest/validation" "github.com/Azure/go-autorest/tracing" "net/http" ) // DataConnectionsClient is the the Azure Kusto management API provides a RESTful set of web services that interact // with Azure Kusto services to manage your clusters and databases. The API enables you to create, update, and delete // clusters and databases. type DataConnectionsClient struct { BaseClient } // NewDataConnectionsClient creates an instance of the DataConnectionsClient client. func NewDataConnectionsClient(subscriptionID string) DataConnectionsClient { return NewDataConnectionsClientWithBaseURI(DefaultBaseURI, subscriptionID) } // NewDataConnectionsClientWithBaseURI creates an instance of the DataConnectionsClient client using a custom endpoint. // Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). func NewDataConnectionsClientWithBaseURI(baseURI string, subscriptionID string) DataConnectionsClient { return DataConnectionsClient{NewWithBaseURI(baseURI, subscriptionID)} } // CheckNameAvailability checks that the data connection name is valid and is not already in use. // Parameters: // resourceGroupName - the name of the resource group containing the Kusto cluster. // clusterName - the name of the Kusto cluster. // databaseName - the name of the database in the Kusto cluster. // dataConnectionName - the name of the data connection. func (client DataConnectionsClient) CheckNameAvailability(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, dataConnectionName DataConnectionCheckNameRequest) (result CheckNameResult, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/DataConnectionsClient.CheckNameAvailability") defer func() { sc := -1 if result.Response.Response != nil { sc = result.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } if err := validation.Validate([]validation.Validation{ {TargetValue: dataConnectionName, Constraints: []validation.Constraint{{Target: "dataConnectionName.Name", Name: validation.Null, Rule: true, Chain: nil}, {Target: "dataConnectionName.Type", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { return result, validation.NewError("kusto.DataConnectionsClient", "CheckNameAvailability", err.Error()) } req, err := client.CheckNameAvailabilityPreparer(ctx, resourceGroupName, clusterName, databaseName, dataConnectionName) if err != nil { err = autorest.NewErrorWithError(err, "kusto.DataConnectionsClient", "CheckNameAvailability", nil, "Failure preparing request") return } resp, err := client.CheckNameAvailabilitySender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "kusto.DataConnectionsClient", "CheckNameAvailability", resp, "Failure sending request") return } result, err = client.CheckNameAvailabilityResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "kusto.DataConnectionsClient", "CheckNameAvailability", resp, "Failure responding to request") return } return } // CheckNameAvailabilityPreparer prepares the CheckNameAvailability request. func (client DataConnectionsClient) CheckNameAvailabilityPreparer(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, dataConnectionName DataConnectionCheckNameRequest) (*http.Request, error) { pathParameters := map[string]interface{}{ "clusterName": autorest.Encode("path", clusterName), "databaseName": autorest.Encode("path", databaseName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2019-01-21" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsContentType("application/json; charset=utf-8"), autorest.AsPost(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/databases/{databaseName}/checkNameAvailability", pathParameters), autorest.WithJSON(dataConnectionName), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // CheckNameAvailabilitySender sends the CheckNameAvailability request. The method will close the // http.Response Body if it receives an error. func (client DataConnectionsClient) CheckNameAvailabilitySender(req *http.Request) (*http.Response, error) { return client.Send(req, azure.DoRetryWithRegistration(client.Client)) } // CheckNameAvailabilityResponder handles the response to the CheckNameAvailability request. The method always // closes the http.Response Body. func (client DataConnectionsClient) CheckNameAvailabilityResponder(resp *http.Response) (result CheckNameResult, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // CreateOrUpdate creates or updates a data connection. // Parameters: // resourceGroupName - the name of the resource group containing the Kusto cluster. // clusterName - the name of the Kusto cluster. // databaseName - the name of the database in the Kusto cluster. // dataConnectionName - the name of the data connection. // parameters - the data connection parameters supplied to the CreateOrUpdate operation. func (client DataConnectionsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, dataConnectionName string, parameters BasicDataConnection) (result DataConnectionsCreateOrUpdateFuture, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/DataConnectionsClient.CreateOrUpdate") defer func() { sc := -1 if result.FutureAPI != nil && result.FutureAPI.Response() != nil { sc = result.FutureAPI.Response().StatusCode } tracing.EndSpan(ctx, sc, err) }() } req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, clusterName, databaseName, dataConnectionName, parameters) if err != nil { err = autorest.NewErrorWithError(err, "kusto.DataConnectionsClient", "CreateOrUpdate", nil, "Failure preparing request") return } result, err = client.CreateOrUpdateSender(req) if err != nil { err = autorest.NewErrorWithError(err, "kusto.DataConnectionsClient", "CreateOrUpdate", result.Response(), "Failure sending request") return } return } // CreateOrUpdatePreparer prepares the CreateOrUpdate request. func (client DataConnectionsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, dataConnectionName string, parameters BasicDataConnection) (*http.Request, error) { pathParameters := map[string]interface{}{ "clusterName": autorest.Encode("path", clusterName), "databaseName": autorest.Encode("path", databaseName), "dataConnectionName": autorest.Encode("path", dataConnectionName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2019-01-21" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsContentType("application/json; charset=utf-8"), autorest.AsPut(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/databases/{databaseName}/dataConnections/{dataConnectionName}", pathParameters), autorest.WithJSON(parameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the // http.Response Body if it receives an error. func (client DataConnectionsClient) CreateOrUpdateSender(req *http.Request) (future DataConnectionsCreateOrUpdateFuture, err error) { var resp *http.Response future.FutureAPI = &azure.Future{} resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) if err != nil { return } var azf azure.Future azf, err = azure.NewFutureFromResponse(resp) future.FutureAPI = &azf future.Result = future.result return } // CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always // closes the http.Response Body. func (client DataConnectionsClient) CreateOrUpdateResponder(resp *http.Response) (result DataConnectionModel, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated, http.StatusAccepted), autorest.ByUnmarshallingJSON(&result.Value), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // DataConnectionValidationMethod checks that the data connection parameters are valid. // Parameters: // resourceGroupName - the name of the resource group containing the Kusto cluster. // clusterName - the name of the Kusto cluster. // databaseName - the name of the database in the Kusto cluster. // parameters - the data connection parameters supplied to the CreateOrUpdate operation. func (client DataConnectionsClient) DataConnectionValidationMethod(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, parameters DataConnectionValidation) (result DataConnectionValidationListResult, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/DataConnectionsClient.DataConnectionValidationMethod") defer func() { sc := -1 if result.Response.Response != nil { sc = result.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } req, err := client.DataConnectionValidationMethodPreparer(ctx, resourceGroupName, clusterName, databaseName, parameters) if err != nil { err = autorest.NewErrorWithError(err, "kusto.DataConnectionsClient", "DataConnectionValidationMethod", nil, "Failure preparing request") return } resp, err := client.DataConnectionValidationMethodSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "kusto.DataConnectionsClient", "DataConnectionValidationMethod", resp, "Failure sending request") return } result, err = client.DataConnectionValidationMethodResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "kusto.DataConnectionsClient", "DataConnectionValidationMethod", resp, "Failure responding to request") return } return } // DataConnectionValidationMethodPreparer prepares the DataConnectionValidationMethod request. func (client DataConnectionsClient) DataConnectionValidationMethodPreparer(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, parameters DataConnectionValidation) (*http.Request, error) { pathParameters := map[string]interface{}{ "clusterName": autorest.Encode("path", clusterName), "databaseName": autorest.Encode("path", databaseName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2019-01-21" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsContentType("application/json; charset=utf-8"), autorest.AsPost(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/databases/{databaseName}/dataConnectionValidation", pathParameters), autorest.WithJSON(parameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // DataConnectionValidationMethodSender sends the DataConnectionValidationMethod request. The method will close the // http.Response Body if it receives an error. func (client DataConnectionsClient) DataConnectionValidationMethodSender(req *http.Request) (*http.Response, error) { return client.Send(req, azure.DoRetryWithRegistration(client.Client)) } // DataConnectionValidationMethodResponder handles the response to the DataConnectionValidationMethod request. The method always // closes the http.Response Body. func (client DataConnectionsClient) DataConnectionValidationMethodResponder(resp *http.Response) (result DataConnectionValidationListResult, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // Delete deletes the data connection with the given name. // Parameters: // resourceGroupName - the name of the resource group containing the Kusto cluster. // clusterName - the name of the Kusto cluster. // databaseName - the name of the database in the Kusto cluster. // dataConnectionName - the name of the data connection. func (client DataConnectionsClient) Delete(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, dataConnectionName string) (result DataConnectionsDeleteFuture, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/DataConnectionsClient.Delete") defer func() { sc := -1 if result.FutureAPI != nil && result.FutureAPI.Response() != nil { sc = result.FutureAPI.Response().StatusCode } tracing.EndSpan(ctx, sc, err) }() } req, err := client.DeletePreparer(ctx, resourceGroupName, clusterName, databaseName, dataConnectionName) if err != nil { err = autorest.NewErrorWithError(err, "kusto.DataConnectionsClient", "Delete", nil, "Failure preparing request") return } result, err = client.DeleteSender(req) if err != nil { err = autorest.NewErrorWithError(err, "kusto.DataConnectionsClient", "Delete", result.Response(), "Failure sending request") return } return } // DeletePreparer prepares the Delete request. func (client DataConnectionsClient) DeletePreparer(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, dataConnectionName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "clusterName": autorest.Encode("path", clusterName), "databaseName": autorest.Encode("path", databaseName), "dataConnectionName": autorest.Encode("path", dataConnectionName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2019-01-21" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsDelete(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/databases/{databaseName}/dataConnections/{dataConnectionName}", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // DeleteSender sends the Delete request. The method will close the // http.Response Body if it receives an error. func (client DataConnectionsClient) DeleteSender(req *http.Request) (future DataConnectionsDeleteFuture, err error) { var resp *http.Response future.FutureAPI = &azure.Future{} resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) if err != nil { return } var azf azure.Future azf, err = azure.NewFutureFromResponse(resp) future.FutureAPI = &azf future.Result = future.result return } // DeleteResponder handles the response to the Delete request. The method always // closes the http.Response Body. func (client DataConnectionsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), autorest.ByClosing()) result.Response = resp return } // Get returns a data connection. // Parameters: // resourceGroupName - the name of the resource group containing the Kusto cluster. // clusterName - the name of the Kusto cluster. // databaseName - the name of the database in the Kusto cluster. // dataConnectionName - the name of the data connection. func (client DataConnectionsClient) Get(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, dataConnectionName string) (result DataConnectionModel, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/DataConnectionsClient.Get") defer func() { sc := -1 if result.Response.Response != nil { sc = result.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } req, err := client.GetPreparer(ctx, resourceGroupName, clusterName, databaseName, dataConnectionName) if err != nil { err = autorest.NewErrorWithError(err, "kusto.DataConnectionsClient", "Get", nil, "Failure preparing request") return } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "kusto.DataConnectionsClient", "Get", resp, "Failure sending request") return } result, err = client.GetResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "kusto.DataConnectionsClient", "Get", resp, "Failure responding to request") return } return } // GetPreparer prepares the Get request. func (client DataConnectionsClient) GetPreparer(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, dataConnectionName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "clusterName": autorest.Encode("path", clusterName), "databaseName": autorest.Encode("path", databaseName), "dataConnectionName": autorest.Encode("path", dataConnectionName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2019-01-21" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/databases/{databaseName}/dataConnections/{dataConnectionName}", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // GetSender sends the Get request. The method will close the // http.Response Body if it receives an error. func (client DataConnectionsClient) GetSender(req *http.Request) (*http.Response, error) { return client.Send(req, azure.DoRetryWithRegistration(client.Client)) } // GetResponder handles the response to the Get request. The method always // closes the http.Response Body. func (client DataConnectionsClient) GetResponder(resp *http.Response) (result DataConnectionModel, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // ListByDatabase returns the list of data connections of the given Kusto database. // Parameters: // resourceGroupName - the name of the resource group containing the Kusto cluster. // clusterName - the name of the Kusto cluster. // databaseName - the name of the database in the Kusto cluster. func (client DataConnectionsClient) ListByDatabase(ctx context.Context, resourceGroupName string, clusterName string, databaseName string) (result DataConnectionListResult, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/DataConnectionsClient.ListByDatabase") defer func() { sc := -1 if result.Response.Response != nil { sc = result.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } req, err := client.ListByDatabasePreparer(ctx, resourceGroupName, clusterName, databaseName) if err != nil { err = autorest.NewErrorWithError(err, "kusto.DataConnectionsClient", "ListByDatabase", nil, "Failure preparing request") return } resp, err := client.ListByDatabaseSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "kusto.DataConnectionsClient", "ListByDatabase", resp, "Failure sending request") return } result, err = client.ListByDatabaseResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "kusto.DataConnectionsClient", "ListByDatabase", resp, "Failure responding to request") return } return } // ListByDatabasePreparer prepares the ListByDatabase request. func (client DataConnectionsClient) ListByDatabasePreparer(ctx context.Context, resourceGroupName string, clusterName string, databaseName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "clusterName": autorest.Encode("path", clusterName), "databaseName": autorest.Encode("path", databaseName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2019-01-21" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/databases/{databaseName}/dataConnections", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // ListByDatabaseSender sends the ListByDatabase request. The method will close the // http.Response Body if it receives an error. func (client DataConnectionsClient) ListByDatabaseSender(req *http.Request) (*http.Response, error) { return client.Send(req, azure.DoRetryWithRegistration(client.Client)) } // ListByDatabaseResponder handles the response to the ListByDatabase request. The method always // closes the http.Response Body. func (client DataConnectionsClient) ListByDatabaseResponder(resp *http.Response) (result DataConnectionListResult, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // Update updates a data connection. // Parameters: // resourceGroupName - the name of the resource group containing the Kusto cluster. // clusterName - the name of the Kusto cluster. // databaseName - the name of the database in the Kusto cluster. // dataConnectionName - the name of the data connection. // parameters - the data connection parameters supplied to the Update operation. func (client DataConnectionsClient) Update(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, dataConnectionName string, parameters BasicDataConnection) (result DataConnectionsUpdateFuture, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/DataConnectionsClient.Update") defer func() { sc := -1 if result.FutureAPI != nil && result.FutureAPI.Response() != nil { sc = result.FutureAPI.Response().StatusCode } tracing.EndSpan(ctx, sc, err) }() } req, err := client.UpdatePreparer(ctx, resourceGroupName, clusterName, databaseName, dataConnectionName, parameters) if err != nil { err = autorest.NewErrorWithError(err, "kusto.DataConnectionsClient", "Update", nil, "Failure preparing request") return } result, err = client.UpdateSender(req) if err != nil { err = autorest.NewErrorWithError(err, "kusto.DataConnectionsClient", "Update", result.Response(), "Failure sending request") return } return } // UpdatePreparer prepares the Update request. func (client DataConnectionsClient) UpdatePreparer(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, dataConnectionName string, parameters BasicDataConnection) (*http.Request, error) { pathParameters := map[string]interface{}{ "clusterName": autorest.Encode("path", clusterName), "databaseName": autorest.Encode("path", databaseName), "dataConnectionName": autorest.Encode("path", dataConnectionName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2019-01-21" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsContentType("application/json; charset=utf-8"), autorest.AsPatch(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/databases/{databaseName}/dataConnections/{dataConnectionName}", pathParameters), autorest.WithJSON(parameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // UpdateSender sends the Update request. The method will close the // http.Response Body if it receives an error. func (client DataConnectionsClient) UpdateSender(req *http.Request) (future DataConnectionsUpdateFuture, err error) { var resp *http.Response future.FutureAPI = &azure.Future{} resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) if err != nil { return } var azf azure.Future azf, err = azure.NewFutureFromResponse(resp) future.FutureAPI = &azf future.Result = future.result return } // UpdateResponder handles the response to the Update request. The method always // closes the http.Response Body. func (client DataConnectionsClient) UpdateResponder(resp *http.Response) (result DataConnectionModel, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated, http.StatusAccepted), autorest.ByUnmarshallingJSON(&result.Value), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return }
Azure/azure-sdk-for-go
services/kusto/mgmt/2019-01-21/kusto/dataconnections.go
GO
mit
27,128
require 'rails_helper' RSpec.describe Parties::EmailsController, type: :request do describe '#edit' do before { signin_party } subject! { get '/party/email/edit' } it { expect(response).to be_success } end describe '#update' do before { signin_party } context 'success' do subject { put '/party/email', party: { email: '5566@gmail.com', current_password: '12321313213' } } it { expect { subject }.to change_sidekiq_jobs_size_of(Devise::Async::Backend::Sidekiq) } it { expect(subject).to redirect_to('/party/profile') } end context 'wrong password' do subject! { put '/party/email', party: { email: '5566@gmail.com', current_password: '' } } it { expect(current_party.email).not_to eq('5566@gmail.com') } it { expect(response.body).to match('5566@gmail.com') } it { expect(response.body).not_to match('目前等待驗證中信箱') } end end describe '#resend_confirmation_mail' do let!(:party) { create :party, :with_unconfirmed_email, :with_confirmation_token } before { signin_party(party) } subject { post '/party/email/resend_confirmation_mail' } it { expect { subject }.to change_sidekiq_jobs_size_of(CustomDeviseMailer, :resend_confirmation_instructions) } context 'redirect success' do before { subject } it { expect(flash[:notice]).to eq('您將在幾分鐘後收到一封電子郵件,內有驗證帳號的步驟說明。') } it { expect(response).to redirect_to('/party/profile') } end end end
JRF-tw/sunshine.jrf.org.tw
spec/requests/parties/emails_controller_spec.rb
Ruby
mit
1,540
package jsettlers.graphics.map.controls.original.panel.button; import jsettlers.common.images.EImageLinkType; import jsettlers.common.images.OriginalImageLink; import jsettlers.common.material.EMaterialType; import jsettlers.graphics.action.Action; import jsettlers.graphics.localization.Labels; import jsettlers.graphics.ui.Button; import jsettlers.graphics.ui.UIPanel; /** * A special material button with a green/red dot and a * * @author Michael Zangl */ public class MaterialButton extends Button { public enum DotColor { RED(7), GREEN(0), YELLOW(3); private OriginalImageLink image; private DotColor(int imageIndex) { image = new OriginalImageLink(EImageLinkType.SETTLER, 4, 6, imageIndex); } public OriginalImageLink getImage() { return image; } } private final EMaterialType material; private final UIPanel dot = new UIPanel(); private final UIPanel selected = new UIPanel(); public MaterialButton(Action action, EMaterialType material) { super(action, material.getIcon(), material.getIcon(), Labels.getName(material, false)); this.material = material; setBackground(material.getIcon()); addChild(dot, .1f, .6f, .4f, .9f); addChild(selected, 0, 0, 1, 1); } public void setDotColor(DotColor color) { dot.setBackground(color == null ? null : color.image); } public EMaterialType getMaterial() { return material; } public void setSelected(boolean selected) { this.selected.setBackground(selected ? new OriginalImageLink(EImageLinkType.GUI, 3, 339) : null); } }
JKatzwinkel/settlers-remake
jsettlers.graphics/src/jsettlers/graphics/map/controls/original/panel/button/MaterialButton.java
Java
mit
1,533
// Code generated by protoc-gen-go. DO NOT EDIT. // source: google/ads/googleads/v0/enums/frequency_cap_level.proto package enums // import "google.golang.org/genproto/googleapis/ads/googleads/v0/enums" import proto "github.com/golang/protobuf/proto" import fmt "fmt" import math "math" // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package // The level on which the cap is to be applied (e.g ad group ad, ad group). // Cap is applied to all the resources of this level. type FrequencyCapLevelEnum_FrequencyCapLevel int32 const ( // Not specified. FrequencyCapLevelEnum_UNSPECIFIED FrequencyCapLevelEnum_FrequencyCapLevel = 0 // Used for return value only. Represents value unknown in this version. FrequencyCapLevelEnum_UNKNOWN FrequencyCapLevelEnum_FrequencyCapLevel = 1 // The cap is applied at the ad group ad level. FrequencyCapLevelEnum_AD_GROUP_AD FrequencyCapLevelEnum_FrequencyCapLevel = 2 // The cap is applied at the ad group level. FrequencyCapLevelEnum_AD_GROUP FrequencyCapLevelEnum_FrequencyCapLevel = 3 // The cap is applied at the campaign level. FrequencyCapLevelEnum_CAMPAIGN FrequencyCapLevelEnum_FrequencyCapLevel = 4 ) var FrequencyCapLevelEnum_FrequencyCapLevel_name = map[int32]string{ 0: "UNSPECIFIED", 1: "UNKNOWN", 2: "AD_GROUP_AD", 3: "AD_GROUP", 4: "CAMPAIGN", } var FrequencyCapLevelEnum_FrequencyCapLevel_value = map[string]int32{ "UNSPECIFIED": 0, "UNKNOWN": 1, "AD_GROUP_AD": 2, "AD_GROUP": 3, "CAMPAIGN": 4, } func (x FrequencyCapLevelEnum_FrequencyCapLevel) String() string { return proto.EnumName(FrequencyCapLevelEnum_FrequencyCapLevel_name, int32(x)) } func (FrequencyCapLevelEnum_FrequencyCapLevel) EnumDescriptor() ([]byte, []int) { return fileDescriptor_frequency_cap_level_ca8c642a1d3010c4, []int{0, 0} } // Container for enum describing the level on which the cap is to be applied. type FrequencyCapLevelEnum struct { XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *FrequencyCapLevelEnum) Reset() { *m = FrequencyCapLevelEnum{} } func (m *FrequencyCapLevelEnum) String() string { return proto.CompactTextString(m) } func (*FrequencyCapLevelEnum) ProtoMessage() {} func (*FrequencyCapLevelEnum) Descriptor() ([]byte, []int) { return fileDescriptor_frequency_cap_level_ca8c642a1d3010c4, []int{0} } func (m *FrequencyCapLevelEnum) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_FrequencyCapLevelEnum.Unmarshal(m, b) } func (m *FrequencyCapLevelEnum) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_FrequencyCapLevelEnum.Marshal(b, m, deterministic) } func (dst *FrequencyCapLevelEnum) XXX_Merge(src proto.Message) { xxx_messageInfo_FrequencyCapLevelEnum.Merge(dst, src) } func (m *FrequencyCapLevelEnum) XXX_Size() int { return xxx_messageInfo_FrequencyCapLevelEnum.Size(m) } func (m *FrequencyCapLevelEnum) XXX_DiscardUnknown() { xxx_messageInfo_FrequencyCapLevelEnum.DiscardUnknown(m) } var xxx_messageInfo_FrequencyCapLevelEnum proto.InternalMessageInfo func init() { proto.RegisterType((*FrequencyCapLevelEnum)(nil), "google.ads.googleads.v0.enums.FrequencyCapLevelEnum") proto.RegisterEnum("google.ads.googleads.v0.enums.FrequencyCapLevelEnum_FrequencyCapLevel", FrequencyCapLevelEnum_FrequencyCapLevel_name, FrequencyCapLevelEnum_FrequencyCapLevel_value) } func init() { proto.RegisterFile("google/ads/googleads/v0/enums/frequency_cap_level.proto", fileDescriptor_frequency_cap_level_ca8c642a1d3010c4) } var fileDescriptor_frequency_cap_level_ca8c642a1d3010c4 = []byte{ // 300 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x32, 0x4f, 0xcf, 0xcf, 0x4f, 0xcf, 0x49, 0xd5, 0x4f, 0x4c, 0x29, 0xd6, 0x87, 0x30, 0x41, 0xac, 0x32, 0x03, 0xfd, 0xd4, 0xbc, 0xd2, 0xdc, 0x62, 0xfd, 0xb4, 0xa2, 0xd4, 0xc2, 0xd2, 0xd4, 0xbc, 0xe4, 0xca, 0xf8, 0xe4, 0xc4, 0x82, 0xf8, 0x9c, 0xd4, 0xb2, 0xd4, 0x1c, 0xbd, 0x82, 0xa2, 0xfc, 0x92, 0x7c, 0x21, 0x59, 0x88, 0x6a, 0xbd, 0xc4, 0x94, 0x62, 0x3d, 0xb8, 0x46, 0xbd, 0x32, 0x03, 0x3d, 0xb0, 0x46, 0xa5, 0x72, 0x2e, 0x51, 0x37, 0x98, 0x5e, 0xe7, 0xc4, 0x02, 0x1f, 0x90, 0x4e, 0xd7, 0xbc, 0xd2, 0x5c, 0xa5, 0x38, 0x2e, 0x41, 0x0c, 0x09, 0x21, 0x7e, 0x2e, 0xee, 0x50, 0xbf, 0xe0, 0x00, 0x57, 0x67, 0x4f, 0x37, 0x4f, 0x57, 0x17, 0x01, 0x06, 0x21, 0x6e, 0x2e, 0xf6, 0x50, 0x3f, 0x6f, 0x3f, 0xff, 0x70, 0x3f, 0x01, 0x46, 0x90, 0xac, 0xa3, 0x4b, 0xbc, 0x7b, 0x90, 0x7f, 0x68, 0x40, 0xbc, 0xa3, 0x8b, 0x00, 0x93, 0x10, 0x0f, 0x17, 0x07, 0x4c, 0x40, 0x80, 0x19, 0xc4, 0x73, 0x76, 0xf4, 0x0d, 0x70, 0xf4, 0x74, 0xf7, 0x13, 0x60, 0x71, 0x7a, 0xcd, 0xc8, 0xa5, 0x98, 0x9c, 0x9f, 0xab, 0x87, 0xd7, 0x79, 0x4e, 0x62, 0x18, 0x6e, 0x08, 0x00, 0xf9, 0x2a, 0x80, 0x31, 0xca, 0x09, 0xaa, 0x31, 0x3d, 0x3f, 0x27, 0x31, 0x2f, 0x5d, 0x2f, 0xbf, 0x28, 0x5d, 0x3f, 0x3d, 0x35, 0x0f, 0xec, 0x67, 0x58, 0x00, 0x15, 0x64, 0x16, 0xe3, 0x08, 0x2f, 0x6b, 0x30, 0xb9, 0x88, 0x89, 0xd9, 0xdd, 0xd1, 0x71, 0x15, 0x93, 0xac, 0x3b, 0xc4, 0x28, 0xc7, 0x94, 0x62, 0x3d, 0x08, 0x13, 0xc4, 0x0a, 0x33, 0xd0, 0x03, 0x05, 0x44, 0xf1, 0x29, 0x98, 0x7c, 0x8c, 0x63, 0x4a, 0x71, 0x0c, 0x5c, 0x3e, 0x26, 0xcc, 0x20, 0x06, 0x2c, 0xff, 0x8a, 0x49, 0x11, 0x22, 0x68, 0x65, 0xe5, 0x98, 0x52, 0x6c, 0x65, 0x05, 0x57, 0x61, 0x65, 0x15, 0x66, 0x60, 0x65, 0x05, 0x56, 0x93, 0xc4, 0x06, 0x76, 0x98, 0x31, 0x20, 0x00, 0x00, 0xff, 0xff, 0x1e, 0x6c, 0x55, 0x4b, 0xc7, 0x01, 0x00, 0x00, }
cloudfoundry-community/firehose-to-syslog
vendor/google.golang.org/genproto/googleapis/ads/googleads/v0/enums/frequency_cap_level.pb.go
GO
mit
5,878
// // 2_2_DefineVariables.cpp // CPP // // Created by akshay raj gollahalli on 2/02/16. // Copyright © 2016 akshay raj gollahalli. All rights reserved. // #include <cstdio> int main(int argc, char ** argv) { int someNumber = 10; /* this can also be written as int someNumber; someNumber = 10; */ const int constantNumber = 10; // constantNumber = 11; // this cannot be changed once initalized. printf("some number is %d\n", someNumber); printf("constant number is %d\n", constantNumber); return 0; }
akshaybabloo/CPP-Notes
2_Basics/2_2_DefineVariables.cpp
C++
mit
519
from django import forms from django.contrib.auth.forms import AuthenticationForm from django.utils.translation import ugettext_lazy as _ class EmailAuthenticationForm(AuthenticationForm): """Email authentication Form increase the size of the username field to fit long emails""" # TODO: consider to change this to an email only field username = forms.CharField(label=_("Username"), widget=forms.TextInput(attrs={'class': 'text'})) password = forms.CharField(label=_("Password"), widget=forms.PasswordInput( attrs={'class': 'text'})) remember_me = forms.BooleanField(label='Keep me logged in', required=False)
theteam/django-theteamcommon
src/theteamcommon/forms.py
Python
mit
770
module.exports = { Shape: require('./lib/shape'), Node: require('./lib/node'), Error: require('./lib/node_error'), MemorySource: require('./lib/memory_source'), };
LastLeaf/datree
index.js
JavaScript
mit
180
<?php /* FOSUserBundle:Profile:show.html.twig */ class __TwigTemplate_2d974d2be07c528b56adfa6823dca8b997fac47403b46447cbcad246a9aa4057 extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); $this->parent = $this->env->loadTemplate("FOSUserBundle::layout.html.twig"); $this->blocks = array( 'fos_user_content' => array($this, 'block_fos_user_content'), ); } protected function doGetParent(array $context) { return "FOSUserBundle::layout.html.twig"; } protected function doDisplay(array $context, array $blocks = array()) { $this->parent->display($context, array_merge($this->blocks, $blocks)); } // line 3 public function block_fos_user_content($context, array $blocks = array()) { // line 4 $this->env->loadTemplate("FOSUserBundle:Profile:show_content.html.twig")->display($context); } public function getTemplateName() { return "FOSUserBundle:Profile:show.html.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 31 => 4, 28 => 3,); } }
efrax/IMDER
app/cache/dev/twig/2d/97/4d2be07c528b56adfa6823dca8b997fac47403b46447cbcad246a9aa4057.php
PHP
mit
1,239
<?php /* * Skeleton Bundle * This file is part of the BardisCMS. * * (c) George Bardis <george@bardis.info> * */ namespace BardisCMS\SkeletonBundle\Repository; use Doctrine\ORM\EntityRepository; class SkeletonRepository extends EntityRepository { // Function to retrieve the pages of a category with pagination public function getCategoryItems($categoryIds, $currentPageId, $publishStates, $currentpage, $totalpageitems) { $pageList = null; if (!empty($categoryIds)) { // Initalize the query builder variables $qb = $this->_em->createQueryBuilder(); $countqb = $this->_em->createQueryBuilder(); // The query to get the page items for the current paginated listing page $qb->select('DISTINCT p') ->from('SkeletonBundle:Skeleton', 'p') ->innerJoin('p.categories', 'c') ->where($qb->expr()->andX( $qb->expr()->in('c.id', ':category'), $qb->expr()->in('p.publishState', ':publishState'), $qb->expr()->neq('p.pagetype', ':categorypagePageType'), $qb->expr()->neq('p.id', ':currentPage') )) ->orderBy('p.date', 'DESC') ->setParameter('category', $categoryIds) ->setParameter('publishState', $publishStates) ->setParameter('categorypagePageType', 'category_page') ->setParameter('currentPage', $currentPageId) ; // The query to get the total page items count $countqb->select('COUNT(DISTINCT p.id)') ->from('SkeletonBundle:Skeleton', 'p') ->innerJoin('p.categories', 'c') ->where($countqb->expr()->andX( $countqb->expr()->in('c.id', ':category'), $countqb->expr()->in('p.publishState', ':publishState'), $countqb->expr()->neq('p.pagetype', ':categorypagePageType'), $countqb->expr()->neq('p.id', ':currentPage') )) ->orderBy('p.date', 'DESC') ->setParameter('category', $categoryIds) ->setParameter('publishState', $publishStates) ->setParameter('categorypagePageType', 'category_page') ->setParameter('currentPage', $currentPageId) ; $totalResultsCount = intval($countqb->getQuery()->getSingleScalarResult()); // Get the paginated results $pageList = $this->getPaginatedResults($qb, $totalResultsCount, $currentpage, $totalpageitems); } return $pageList; } // Function to retrieve the pages of tag/category combination with pagination public function getTaggedCategoryItems($categoryIds, $currentPageId, $publishStates, $currentpage, $totalpageitems, $tagIds) { $pageList = null; if (!empty($categoryIds)) { // Initalize the query builder variables $qb = $this->_em->createQueryBuilder(); $countqb = $this->_em->createQueryBuilder(); // The query to get the page items for the current paginated listing page $qb->select('DISTINCT p') ->from('SkeletonBundle:Skeleton', 'p') ->innerJoin('p.categories', 'c') ->innerJoin('p.tags', 't') ->where($qb->expr()->andX( $qb->expr()->in('c.id', ':category'), $qb->expr()->in('t.id', ':tag'), $qb->expr()->in('p.publishState', ':publishState'), $qb->expr()->neq('p.id', ':currentPage'), $qb->expr()->eq('p.pagetype', ':pagetype') )) ->orderBy('p.date', 'DESC') ->setParameter('category', $categoryIds) ->setParameter('tag', $tagIds) ->setParameter('publishState', $publishStates) ->setParameter('pagetype', 'skeleton_article') ->setParameter('currentPage', $currentPageId) ; // The query to get the total page items count $countqb->select('COUNT(DISTINCT p.id)') ->from('SkeletonBundle:Skeleton', 'p') ->innerJoin('p.categories', 'c') ->innerJoin('p.tags', 't') ->where($countqb->expr()->andX( $countqb->expr()->in('c.id', ':category'), $countqb->expr()->in('t.id', ':tag'), $countqb->expr()->in('p.publishState', ':publishState'), $countqb->expr()->neq('p.id', ':currentPage'), $countqb->expr()->eq('p.pagetype', ':pagetype') )) ->orderBy('p.date', 'DESC') ->setParameter('category', $categoryIds) ->setParameter('tag', $tagIds) ->setParameter('publishState', $publishStates) ->setParameter('pagetype', 'skeleton_article') ->setParameter('currentPage', $currentPageId) ; $totalResultsCount = intval($countqb->getQuery()->getSingleScalarResult()); // Get the paginated results $pageList = $this->getPaginatedResults($qb, $totalResultsCount, $currentpage, $totalpageitems); } return $pageList; } // Function to retrieve the pages of a tag with pagination public function getTaggedItems($tagIds, $currentPageId, $publishStates, $currentpage, $totalpageitems) { $pageList = null; if (!empty($tagIds)) { // Initalize the query builder variables $qb = $this->_em->createQueryBuilder(); $countqb = $this->_em->createQueryBuilder(); // The query to get the page items for the current paginated listing page $qb->select('DISTINCT p') ->from('SkeletonBundle:Skeleton', 'p') ->innerJoin('p.tags', 't') ->where($qb->expr()->andX( $qb->expr()->in('t.id', ':tag'), $qb->expr()->in('p.publishState', ':publishState'), $qb->expr()->eq('p.pagetype', ':pagetype'), $qb->expr()->neq('p.id', ':currentPage') )) ->orderBy('p.date', 'DESC') ->setParameter('tag', $tagIds) ->setParameter('publishState', $publishStates) ->setParameter('pagetype', 'skeleton_article') ->setParameter('currentPage', $currentPageId) ; // The query to get the total page items count $countqb->select('COUNT(DISTINCT p.id)') ->from('SkeletonBundle:Skeleton', 'p') ->innerJoin('p.tags', 't') ->where($countqb->expr()->andX( $countqb->expr()->in('t.id', ':tag'), $countqb->expr()->in('p.publishState', ':publishState'), $countqb->expr()->eq('p.pagetype', ':pagetype'), $countqb->expr()->neq('p.id', ':currentPage') )) ->orderBy('p.date', 'DESC') ->setParameter('tag', $tagIds) ->setParameter('publishState', $publishStates) ->setParameter('pagetype', 'skeleton_article') ->setParameter('currentPage', $currentPageId) ; $totalResultsCount = intval($countqb->getQuery()->getSingleScalarResult()); // Get the paginated results $pageList = $this->getPaginatedResults($qb, $totalResultsCount, $currentpage, $totalpageitems); } return $pageList; } // Function to retrieve all the pages public function getAllItems($currentPageId, $publishStates, $currentpage, $totalpageitems) { $pageList = null; // Initalize the query builder variables $qb = $this->_em->createQueryBuilder(); $countqb = $this->_em->createQueryBuilder(); // The query to get the page items for the current paginated listing page $qb->select('p') ->from('SkeletonBundle:Skeleton', 'DISTINCT p') ->where($qb->expr()->andX( $qb->expr()->in('p.publishState', ':publishState'), $qb->expr()->eq('p.pagetype', ':pagetype'), $qb->expr()->neq('p.id', ':currentPage') )) ->orderBy('p.date', 'DESC') ->setParameter('publishState', $publishStates) ->setParameter('pagetype', 'skeleton_article') ->setParameter('currentPage', $currentPageId) ; // The query to get the total page items count $countqb->select('COUNT(DISTINCT p.id)') ->from('SkeletonBundle:Skeleton', 'p') ->where($countqb->expr()->andX( $countqb->expr()->in('p.publishState', ':publishState'), $countqb->expr()->eq('p.pagetype', ':pagetype'), $countqb->expr()->neq('p.id', ':currentPage') )) ->orderBy('p.date', 'DESC') ->setParameter('publishState', $publishStates) ->setParameter('pagetype', 'skeleton_article') ->setParameter('currentPage', $currentPageId) ; $totalResultsCount = intval($countqb->getQuery()->getSingleScalarResult()); // Get the paginated results $pageList = $this->getPaginatedResults($qb, $totalResultsCount, $currentpage, $totalpageitems); return $pageList; } // Function to retrieve the pages of the homepage category public function getHomepageItems($categoryIds, $publishStates) { $pageList = null; if (!empty($categoryIds)) { // Initalize the query builder variables $qb = $this->_em->createQueryBuilder(); // The query to get the page items for the homepage page $qb->select('DISTINCT p') ->from('SkeletonBundle:Skeleton', 'p') ->innerJoin('p.categories', 'c') ->where($qb->expr()->andX( $qb->expr()->in('c.id', ':category'), $qb->expr()->in('p.publishState', ':publishState') )) ->orderBy('p.pageOrder', 'ASC') ->setParameter('category', $categoryIds) ->setParameter('publishState', $publishStates) ; // Get the results $pageList = $qb->getQuery()->getResult(); } return $pageList; } // Function to retrieve a page list for sitemap public function getSitemapList($publishStates) { // Initalize the query builder variables $qb = $this->_em->createQueryBuilder(); // The query to get all page items $qb->select('DISTINCT p') ->from('SkeletonBundle:Skeleton', 'p') ->where( $qb->expr()->in('p.publishState', ':publishState') ) ->orderBy('p.id', 'ASC') ->setParameter('publishState', $publishStates) ; // Get the results $sitemapList = $qb->getQuery()->getResult(); return $sitemapList; } // Function to define what page items will be returned for each paginated listing page public function getPaginatedResults($qb, $totalResultsCount, $currentpage, $totalpageitems) { $pages = null; $totalPages = 1; // Calculate and set the starting and last page item to retrieve if ((isset($currentpage)) && (isset($totalpageitems))) { if ($totalpageitems > 0) { $startingItem = (intval($currentpage) * $totalpageitems); $qb->setFirstResult($startingItem); $qb->setMaxResults($totalpageitems); } } // Get paginated results $pages = $qb->getQuery()->getResult(); // Get the total pagination pages $totalPages = ceil($totalResultsCount / $totalpageitems); // Set the page items and pagination to be returned $pageList = array('pages' => $pages, 'totalPages' => $totalPages); return $pageList; } }
bardius/the-web-dev-ninja-blog
src/BardisCMS/SkeletonBundle/Repository/SkeletonRepository.php
PHP
mit
12,435
namespace Rib.Deployer.Steps.FileSystem { using System; using NUnit.Framework; [TestFixture] public class HasDestFsSettingsTests { [Test] public void HasDestFsSettingsNullTest() => Assert.Throws<ArgumentException>(() => new HasDestFsSettings("name", "src", null)); [Test] public void HasDestFsSettingsEmptyTest() => Assert.Throws<ArgumentException>(() => new HasDestFsSettings("name", "src", string.Empty)); [Test] public void HasDestFsSettingsWhiteSpaceTest() => Assert.Throws<ArgumentException>(() => new HasDestFsSettings("name", "src", " ")); } }
riberk/Rib.Deployer
Solution/Rib.Deployer.Steps.FileSystem.Tests/HasDestFsSettingsTests.cs
C#
mit
636
// Code generated by ffjson <https://github.com/pquerna/ffjson>. DO NOT EDIT. // source: vestingbalance.go package types import ( "bytes" "fmt" fflib "github.com/pquerna/ffjson/fflib/v1" ) // MarshalJSON marshal bytes to json - template func (j *VestingBalance) MarshalJSON() ([]byte, error) { var buf fflib.Buffer if j == nil { buf.WriteString("null") return buf.Bytes(), nil } err := j.MarshalJSONBuf(&buf) if err != nil { return nil, err } return buf.Bytes(), nil } // MarshalJSONBuf marshal buff to json - template func (j *VestingBalance) MarshalJSONBuf(buf fflib.EncodingBuffer) error { if j == nil { buf.WriteString("null") return nil } var err error var obj []byte _ = obj _ = err buf.WriteString(`{"id":`) { obj, err = j.ID.MarshalJSON() if err != nil { return err } buf.Write(obj) } buf.WriteString(`,"balance":`) { err = j.Balance.MarshalJSONBuf(buf) if err != nil { return err } } buf.WriteString(`,"owner":`) { obj, err = j.Owner.MarshalJSON() if err != nil { return err } buf.Write(obj) } buf.WriteString(`,"policy":`) { obj, err = j.Policy.MarshalJSON() if err != nil { return err } buf.Write(obj) } buf.WriteByte('}') return nil } const ( ffjtVestingBalancebase = iota ffjtVestingBalancenosuchkey ffjtVestingBalanceID ffjtVestingBalanceBalance ffjtVestingBalanceOwner ffjtVestingBalancePolicy ) var ffjKeyVestingBalanceID = []byte("id") var ffjKeyVestingBalanceBalance = []byte("balance") var ffjKeyVestingBalanceOwner = []byte("owner") var ffjKeyVestingBalancePolicy = []byte("policy") // UnmarshalJSON umarshall json - template of ffjson func (j *VestingBalance) UnmarshalJSON(input []byte) error { fs := fflib.NewFFLexer(input) return j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start) } // UnmarshalJSONFFLexer fast json unmarshall - template ffjson func (j *VestingBalance) UnmarshalJSONFFLexer(fs *fflib.FFLexer, state fflib.FFParseState) error { var err error currentKey := ffjtVestingBalancebase _ = currentKey tok := fflib.FFTok_init wantedTok := fflib.FFTok_init mainparse: for { tok = fs.Scan() // println(fmt.Sprintf("debug: tok: %v state: %v", tok, state)) if tok == fflib.FFTok_error { goto tokerror } switch state { case fflib.FFParse_map_start: if tok != fflib.FFTok_left_bracket { wantedTok = fflib.FFTok_left_bracket goto wrongtokenerror } state = fflib.FFParse_want_key continue case fflib.FFParse_after_value: if tok == fflib.FFTok_comma { state = fflib.FFParse_want_key } else if tok == fflib.FFTok_right_bracket { goto done } else { wantedTok = fflib.FFTok_comma goto wrongtokenerror } case fflib.FFParse_want_key: // json {} ended. goto exit. woo. if tok == fflib.FFTok_right_bracket { goto done } if tok != fflib.FFTok_string { wantedTok = fflib.FFTok_string goto wrongtokenerror } kn := fs.Output.Bytes() if len(kn) <= 0 { // "" case. hrm. currentKey = ffjtVestingBalancenosuchkey state = fflib.FFParse_want_colon goto mainparse } else { switch kn[0] { case 'b': if bytes.Equal(ffjKeyVestingBalanceBalance, kn) { currentKey = ffjtVestingBalanceBalance state = fflib.FFParse_want_colon goto mainparse } case 'i': if bytes.Equal(ffjKeyVestingBalanceID, kn) { currentKey = ffjtVestingBalanceID state = fflib.FFParse_want_colon goto mainparse } case 'o': if bytes.Equal(ffjKeyVestingBalanceOwner, kn) { currentKey = ffjtVestingBalanceOwner state = fflib.FFParse_want_colon goto mainparse } case 'p': if bytes.Equal(ffjKeyVestingBalancePolicy, kn) { currentKey = ffjtVestingBalancePolicy state = fflib.FFParse_want_colon goto mainparse } } if fflib.SimpleLetterEqualFold(ffjKeyVestingBalancePolicy, kn) { currentKey = ffjtVestingBalancePolicy state = fflib.FFParse_want_colon goto mainparse } if fflib.SimpleLetterEqualFold(ffjKeyVestingBalanceOwner, kn) { currentKey = ffjtVestingBalanceOwner state = fflib.FFParse_want_colon goto mainparse } if fflib.SimpleLetterEqualFold(ffjKeyVestingBalanceBalance, kn) { currentKey = ffjtVestingBalanceBalance state = fflib.FFParse_want_colon goto mainparse } if fflib.SimpleLetterEqualFold(ffjKeyVestingBalanceID, kn) { currentKey = ffjtVestingBalanceID state = fflib.FFParse_want_colon goto mainparse } currentKey = ffjtVestingBalancenosuchkey state = fflib.FFParse_want_colon goto mainparse } case fflib.FFParse_want_colon: if tok != fflib.FFTok_colon { wantedTok = fflib.FFTok_colon goto wrongtokenerror } state = fflib.FFParse_want_value continue case fflib.FFParse_want_value: if tok == fflib.FFTok_left_brace || tok == fflib.FFTok_left_bracket || tok == fflib.FFTok_integer || tok == fflib.FFTok_double || tok == fflib.FFTok_string || tok == fflib.FFTok_bool || tok == fflib.FFTok_null { switch currentKey { case ffjtVestingBalanceID: goto handle_ID case ffjtVestingBalanceBalance: goto handle_Balance case ffjtVestingBalanceOwner: goto handle_Owner case ffjtVestingBalancePolicy: goto handle_Policy case ffjtVestingBalancenosuchkey: err = fs.SkipField(tok) if err != nil { return fs.WrapErr(err) } state = fflib.FFParse_after_value goto mainparse } } else { goto wantedvalue } } } handle_ID: /* handler: j.ID type=types.VestingBalanceID kind=struct quoted=false*/ { if tok == fflib.FFTok_null { } else { tbuf, err := fs.CaptureField(tok) if err != nil { return fs.WrapErr(err) } err = j.ID.UnmarshalJSON(tbuf) if err != nil { return fs.WrapErr(err) } } state = fflib.FFParse_after_value } state = fflib.FFParse_after_value goto mainparse handle_Balance: /* handler: j.Balance type=types.AssetAmount kind=struct quoted=false*/ { if tok == fflib.FFTok_null { } else { err = j.Balance.UnmarshalJSONFFLexer(fs, fflib.FFParse_want_key) if err != nil { return err } } state = fflib.FFParse_after_value } state = fflib.FFParse_after_value goto mainparse handle_Owner: /* handler: j.Owner type=types.AccountID kind=struct quoted=false*/ { if tok == fflib.FFTok_null { } else { tbuf, err := fs.CaptureField(tok) if err != nil { return fs.WrapErr(err) } err = j.Owner.UnmarshalJSON(tbuf) if err != nil { return fs.WrapErr(err) } } state = fflib.FFParse_after_value } state = fflib.FFParse_after_value goto mainparse handle_Policy: /* handler: j.Policy type=types.VestingPolicy kind=struct quoted=false*/ { if tok == fflib.FFTok_null { } else { tbuf, err := fs.CaptureField(tok) if err != nil { return fs.WrapErr(err) } err = j.Policy.UnmarshalJSON(tbuf) if err != nil { return fs.WrapErr(err) } } state = fflib.FFParse_after_value } state = fflib.FFParse_after_value goto mainparse wantedvalue: return fs.WrapErr(fmt.Errorf("wanted value token, but got token: %v", tok)) wrongtokenerror: return fs.WrapErr(fmt.Errorf("ffjson: wanted token: %v, but got token: %v output=%s", wantedTok, tok, fs.Output.String())) tokerror: if fs.BigError != nil { return fs.WrapErr(fs.BigError) } err = fs.Error.ToError() if err != nil { return fs.WrapErr(err) } panic("ffjson-generated: unreachable, please report bug.") done: return nil }
denkhaus/bitshares
types/vestingbalance_ffjson.go
GO
mit
7,613
require "pact_broker/domain/pact" module PactBroker module Pacts class PlaceholderPact < PactBroker::Domain::Pact def initialize consumer = OpenStruct.new(name: "placeholder-consumer", labels: [OpenStruct.new(name: "placeholder-consumer-label")]) @provider = OpenStruct.new(name: "placeholder-provider", labels: [OpenStruct.new(name: "placeholder-provider-label")]) @consumer_version = OpenStruct.new(number: "gggghhhhjjjjkkkkllll66667777888899990000", pacticipant: consumer, tags: [OpenStruct.new(name: "master")]) @consumer_version_number = @consumer_version.number @created_at = DateTime.now @revision_number = 1 @pact_version_sha = "5d445a4612743728dfd99ccd4210423c052bb9db" end end end end
pact-foundation/pact_broker
lib/pact_broker/pacts/placeholder_pact.rb
Ruby
mit
776
<?php defined('BASEPATH') OR exit('No direct script access allowed'); // This can be removed if you use __autoload() in config.php OR use Modular Extensions require_once APPPATH . '/libraries/REST_Controller.php'; class Services extends REST_Controller { public function __construct() { parent::__construct(); $this->load->helper('url_helper'); } public function newHistoryDaily_post() { if($this->post()) { $this->load->model('User_model'); $this->load->model('Target_model'); $normalExpense = $this->Target_model->detail_target($this->post('id_target'))->normal_expense; $offset = $this->Target_model->detail_target($this->post('id_target'))->offset; $targetData = $this->User_model->detail_user($this->post('username')); $data = []; $save = 0; $expense = 0; foreach($this->post() as $key => $value) { $data[$key] = $value; if($key != 'username' && $key != 'id_target' && $key != 'date') { $expense += intval($value); } } $save = floor($targetData->penghasilan/30) - $expense; $data['save'] = $save; $data['expense'] = $expense; $offset = $offset+($normalExpense - $expense); $this->Target_model->update_offset_target($this->post('id_target'),$offset); $inp = file_get_contents(base_url().'json/history.json'); $tempArray = json_decode($inp); array_push($tempArray, $data); $jsonData = json_encode($tempArray); file_put_contents('././json/history.json', $jsonData); $this->response([[ 'status' => TRUE, 'message' => 'Pengeluaran Daily added' ]], REST_Controller::HTTP_CREATED); // OK (200) being the HTTP response code } else { $this->response(NULL, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code } } public function newHistoryDailyV1_post() { if($this->post()) { $this->load->model('User_model'); $this->load->model('Target_model'); $normalExpense = $this->Target_model->detail_target($this->post('id_target'))->normal_expense; $offset = $this->Target_model->detail_target($this->post('id_target'))->offset; $targetData = $this->User_model->detail_user($this->post('username')); $data = []; $save = 0; $expense = 0; foreach($this->post() as $key => $value) { $data[$key] = $value; if($key != 'username' && $key != 'id_target' && $key != 'date') { $expense += intval($value); } } $save = floor($targetData->penghasilan/30) - $expense; $data['save'] = $save; $data['expense'] = $expense; $offset = $offset+($normalExpense - $expense); $this->Target_model->update_offset_target($this->post('id_target'),$offset); $inp = file_get_contents(base_url().'json/history.json'); $tempArray = json_decode($inp); array_push($tempArray, $data); $jsonData = json_encode($tempArray); file_put_contents('././json/history.json', $jsonData); $this->response([[ 'status' => TRUE, 'message' => 'Pengeluaran Daily added' ]], REST_Controller::HTTP_CREATED); // OK (200) being the HTTP response code } else { $this->response(NULL, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code } } public function updateHistoryDaily_post() { $this->load->model('Target_model'); $normalExpense = $this->Target_model->detail_target($this->post('id_target'))->normal_expense; $offset = $this->Target_model->detail_target($this->post('id_target'))->offset; $amountKeys = []; $keys = []; foreach($this->post() as $key => $value) { if(substr($key,0,7) == 'amount_') { $datum = []; $datum['key'] = $key; $datum['value'] = $value; array_push($amountKeys,$datum); } else if($key != 'username' && $key != 'id_target' && $key != 'date'){ $datum = []; $datum['key'] = $key; $datum['value'] = $value; array_push($keys,$datum); } } $inp = file_get_contents(base_url().'json/history.json'); $tempArray = json_decode($inp); $i = 0; foreach($tempArray as $temp) { if ($temp->username == $this->post('username') && $temp->id_target == $this->post('id_target') && $temp->date == $this->post('date')) { $tempExpense = $temp->expense; foreach($amountKeys as $amountKey) { $tempKey = substr($amountKey['key'],7); $diff = $temp->$tempKey - $amountKey['value']; $temp->$tempKey = $amountKey['value']; $temp->save = $temp->save + $diff; $temp->expense = $temp->expense - $diff; } $endExpense = $tempExpense - $temp->expense; $offset = $offset+$endExpense; $this->Target_model->update_offset_target($this->post('id_target'),$offset); foreach($keys as $k) { if($k['value'] != $k['key']) { $tempArray[$i]->$k['value'] = $tempArray[$i]->$k['key']; unset($tempArray[$i]->$k['key']); } } } $i = $i+1; } $jsonData = json_encode($tempArray); file_put_contents('././json/history.json', $jsonData); $this->response([[ 'status' => TRUE, 'message' => 'Pengeluaran Daily updated' ]], REST_Controller::HTTP_CREATED); // OK (200) being the HTTP response code } public function updateHistoryDailyAmount_post() { $this->load->model('Target_model'); $normalExpense = $this->Target_model->detail_target($this->post('id_target'))->normal_expense; $offset = $this->Target_model->detail_target($this->post('id_target'))->offset; foreach($this->post() as $key => $value) { if($key != 'username' && $key != 'id_target' && $key != 'date') { $field = $key; } } $inp = file_get_contents(base_url().'json/history.json'); $tempArray = json_decode($inp); foreach($tempArray as $temp) { if ($temp->username == $this->post('username') && $temp->id_target == $this->post('id_target') && $temp->date == $this->post('date')) { foreach($temp as $key => $value) { if($key == $field) { $diff = $temp->$field - $this->post($field); $temp->$field = $this->post($field); } } $temp->save = $temp->save + $diff; $offset = $offset+$diff; $temp->expense = $temp->expense - $diff; $this->Target_model->update_offset_target($this->post('id_target'),$offset); } } $jsonData = json_encode($tempArray); file_put_contents('././json/history.json', $jsonData); $this->response([[ 'status' => TRUE, 'message' => 'Pengeluaran Daily updated' ]], REST_Controller::HTTP_CREATED); // OK (200) being the HTTP response code } public function deleteHistoryDaily_post() { $this->load->model('Target_model'); $normalExpense = $this->Target_model->detail_target($this->post('id_target'))->normal_expense; $offset = $this->Target_model->detail_target($this->post('id_target'))->offset; foreach($this->post() as $key => $value) { if($key != 'username' && $key != 'id_target' && $key != 'date') { $field = $key; } } $inp = file_get_contents(base_url().'json/history.json'); $tempArray = json_decode($inp, true); $i = 0; foreach($tempArray as $temp) { if ($temp['username'] == $this->post('username') && $temp['id_target'] == $this->post('id_target') && $temp['date'] == $this->post('date')) { foreach($temp as $key => $value) { if($key == $field) { $diff = $temp[$field]; unset($temp[$field]); $tempArray[$i] = $temp; } } $tempArray[$i]['save'] = $tempArray[$i]['save'] + $diff; $offset = $offset+$diff; $this->Target_model->update_offset_target($this->post('id_target'),$offset); $tempArray[$i]['expense'] = $tempArray[$i]['expense'] - $diff; } $i=$i+1; } // var_dump($temp); $jsonData = json_encode($tempArray); file_put_contents('././json/history.json', $jsonData); $this->response([[ 'status' => TRUE, 'message' => 'Pengeluaran Daily updated' ]], REST_Controller::HTTP_CREATED); // OK (200) being the HTTP response code } public function getHistoryDaily_get() { $response = array(); $inp = file_get_contents(base_url().'json/history.json'); $tempArray = json_decode($inp); foreach($tempArray as $temp) { if ($temp->username == $this->get('username') && $temp->id_target == $this->get('id_target')) { $response = array_push($response, $temp); } } $this->response($response, REST_Controller::HTTP_OK); } public function login_post() { $this->load->model('User_model'); $username = $this->post('username'); $password = $this->post('password'); if($username != NULL && $password != NULL) { $user = $this->User_model->login($username, md5($password)); if($user) { $this->response([[ 'status' => TRUE, 'message' => 'Login succeeded', 'username' => $user->username, 'nama_user' => $user->nama_user ]], REST_Controller::HTTP_OK); // OK (200) being the HTTP response code } else { $this->response([[ 'status' => FALSE, 'message' => 'Wrong username or password' ]]); } } else { $this->response(NULL, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code } } public function penghasilan_post(){ $this->load->model('User_model'); $username = $this->post('username'); $penghasilan = $this->post('penghasilan'); $responses = $this->User_model->updatePenghasilan($username, $penghasilan); $this->response(NULL, REST_Controller::HTTP_OK); } public function pengeluaran_get() { $this->load->model('Pengeluaran_model'); $username = $this->get('username'); if($username != NULL) { $responses = $this->Pengeluaran_model->getPengeluaranDefault($username); $this->response($responses, REST_Controller::HTTP_OK); } else { $this->response(NULL, REST_Controller::HTTP_BAD_REQUEST); } } public function historyTarget_get() { $this->load->model('HistoryTarget_model'); $username = $this->get('username'); $response = $this->HistoryTarget_model->getHistoryTarget($username); $this->response($response, REST_Controller::HTTP_OK); } public function newPengeluaran_post() { $this->load->model('Pengeluaran_model'); $username = $this->post('username'); $desc = $this->post('description'); $amount = $this->post('amount'); $response = $this->Pengeluaran_model->newPengeluaranDefault($username, $desc, $amount); if($response) { $this->response([[ 'status' => TRUE, 'message' => 'Pengeluaran added' ]], REST_Controller::HTTP_CREATED); // OK (200) being the HTTP response code } else { $this->response([[ 'status' => FALSE, 'message' => 'Pengeluaran failed' ]]); } } public function updatePengeluaran_post() { $this->load->model('Pengeluaran_model'); $username = $this->post('username'); $desc = $this->post('description'); $amount = $this->post('amount'); $response = $this->Pengeluaran_model->updatePengeluaranDefault($username, $desc, $amount); if($response) { $this->response([[ 'status' => TRUE, 'message' => 'Pengeluaran modified' ]], REST_Controller::HTTP_OK); // OK (200) being the HTTP response code } else { $this->response([[ 'status' => FALSE, 'message' => 'Wrong username or password' ]]); } } public function deletePengeluaran_post() { $this->load->model('Pengeluaran_model'); $username = $this->post('username'); $desc = $this->post('description'); $response = $this->Pengeluaran_model->deletePengeluaranDefault($username, $desc); if($response) { $this->response([[ 'status' => TRUE, 'message' => 'Pengeluaran deleted' ]], REST_Controller::HTTP_CREATED); // OK (200) being the HTTP response code } else { $this->response([[ 'status' => FALSE, 'message' => 'Wrong username or password' ]]); } } public function register_post() { $this->load->model('User_model'); $username = $this->post('username'); $password = $this->post('password'); $name = $this->post('nama_user'); if($username != NULL && $password != NULL && $name != NULL) { $post = array( 'username' => $username, 'password' => md5($password), 'nama_user' => $name ); if($this->User_model->register($post)) { $this->response([[ 'status' => TRUE, 'message' => 'User created' ]], REST_Controller::HTTP_CREATED); } else { $this->response([[ 'status' => FALSE, 'message' => 'Username already taken' ]], REST_Controller::HTTP_BAD_REQUEST); } } else { $this->response(NULL, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code } } public function newTarget_post() { $this->load->model('Target_model'); $this->load->model('HistoryTarget_model'); $desc = $this->post('target_desc'); $amount = $this->post('target_amount'); $startDate = $this->post('target_startdate'); $dueDate = $this->post('target_duedate'); $normalExpense = $this->post('normal_expense'); $username = $this->post('username'); if($username != NULL && $desc != NULL && $amount != NULL && $startDate != NULL && $dueDate != NULL && $normalExpense != NULL) { $args = array( 'target_desc' => $desc, 'target_amount' => $amount, 'target_startdate' => $startDate, 'target_duedate' => $dueDate, 'normal_expense' => $normalExpense ); $idTarget = $this->Target_model->insert_target($args); $post = array( 'id_target' => $idTarget, ); $this->Target_model->update_targetUser($username, $post); $history = array( 'username' => $username, 'id_target' => $idTarget ); $this->HistoryTarget_model->insert_historyTarget($history); $this->response([[ 'status' => TRUE, 'message' => 'Target created' ]], REST_Controller::HTTP_CREATED); } else { $this->response(NULL, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code } } public function updateTarget_post() { $this->load->model('Target_model'); $id = $this->post('id_target'); $desc = $this->post('target_desc'); $amount = $this->post('target_amount'); $startDate = $this->post('target_startdate'); $dueDate = $this->post('target_duedate'); $normalExpense = $this->post('normal_expense'); if($id != NULL && $desc != NULL && $amount != NULL && $startDate != NULL && $dueDate != NULL && $normalExpense != NULL) { $args = array( 'target_desc' => $desc, 'target_amount' => $amount, 'target_startdate' => $startDate, 'target_duedate' => $dueDate, 'normal_expense' => $normalExpense ); $idTarget = $this->Target_model->update_target($id, $args); $this->response([[ 'status' => TRUE, 'message' => 'Target updated' ]], REST_Controller::HTTP_OK); } else { $this->response(NULL, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code } } public function updateStatusTarget_post() { $this->load->model('Target_model'); $id = $this->post('id_target'); if($id != NULL) { $args = array( 'status' => 0, ); $idTarget = $this->Target_model->update_status_target($id, $args); $this->response([[ 'status' => TRUE, 'message' => 'Target updated' ]], REST_Controller::HTTP_OK); } else { $this->response(NULL, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code } } public function deleteTarget_post() { $this->load->model('Target_model'); $this->load->model('HistoryTarget_model'); $id = $this->post('id_target'); if($id != NULL) { $this->HistoryTarget_model->delete_history($id); $this->Target_model->delete_target($id); $this->response([[ 'status' => TRUE, 'message' => 'Target deleted' ]], REST_Controller::HTTP_OK); } else { $this->response(NULL, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code } } public function User_get() { $this->load->model('User_model'); $username = $this->get('username'); if($username != NULL) { $user = $this->User_model->detail_user($username); if($user) { $this->response($user, REST_Controller::HTTP_OK); } else { $this->response([[ 'status' => FALSE, 'message' => 'Username not found.' ]], REST_Controller::HTTP_BAD_REQUEST); } } else { $this->response(NULL, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code } } public function Target_get() { $this->load->model('Target_model'); $id = $this->get('id_target'); if($id != NULL) { $target = $this->Target_model->detail_target($id); if($target) { $this->response($target, REST_Controller::HTTP_OK); } else { $this->response([[ 'status' => FALSE, 'message' => 'Target not found.' ]], REST_Controller::HTTP_BAD_REQUEST); } } else { $this->response(NULL, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code } } }
vny1422/Asumu
application/controllers/Services.php
PHP
mit
17,633
from discrete import * f = factorial(100) s = str(f) print sum([int(s[i]) for i in range(len(s))])
jreese/euler
python/problem20.py
Python
mit
101
package de.mineformers.investiture.allomancy.network; import de.mineformers.investiture.allomancy.impl.misting.temporal.SpeedBubble; import de.mineformers.investiture.network.Message; import net.minecraft.util.math.BlockPos; import java.util.UUID; /** * Updates a metal extractor tile entity */ public class SpeedBubbleUpdate extends Message { public static final int ACTION_ADD = 0; public static final int ACTION_REMOVE = 1; public int action; public UUID owner; public int dimension; public BlockPos position; public double radius; public SpeedBubbleUpdate() { } public SpeedBubbleUpdate(int action, SpeedBubble bubble) { this.action = action; this.owner = bubble.owner; this.dimension = bubble.dimension; this.position = bubble.position; this.radius = bubble.radius; } }
PaleoCrafter/Allomancy
src/main/java/de/mineformers/investiture/allomancy/network/SpeedBubbleUpdate.java
Java
mit
875
// Copyright (c) 2011-2013 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "qvalidatedlineedit.h" #include "vikingcoinaddressvalidator.h" #include "guiconstants.h" QValidatedLineEdit::QValidatedLineEdit(QWidget *parent) : QLineEdit(parent), valid(true), checkValidator(0) { connect(this, SIGNAL(textChanged(QString)), this, SLOT(markValid())); } void QValidatedLineEdit::setValid(bool valid) { if(valid == this->valid) { return; } if(valid) { setStyleSheet(""); } else { setStyleSheet(STYLE_INVALID); } this->valid = valid; } void QValidatedLineEdit::focusInEvent(QFocusEvent *evt) { // Clear invalid flag on focus setValid(true); QLineEdit::focusInEvent(evt); } void QValidatedLineEdit::focusOutEvent(QFocusEvent *evt) { checkValidity(); QLineEdit::focusOutEvent(evt); } void QValidatedLineEdit::markValid() { // As long as a user is typing ensure we display state as valid setValid(true); } void QValidatedLineEdit::clear() { setValid(true); QLineEdit::clear(); } void QValidatedLineEdit::setEnabled(bool enabled) { if (!enabled) { // A disabled QValidatedLineEdit should be marked valid setValid(true); } else { // Recheck validity when QValidatedLineEdit gets enabled checkValidity(); } QLineEdit::setEnabled(enabled); } void QValidatedLineEdit::checkValidity() { if (text().isEmpty()) { setValid(true); } else if (hasAcceptableInput()) { setValid(true); // Check contents on focus out if (checkValidator) { QString address = text(); int pos = 0; if (checkValidator->validate(address, pos) == QValidator::Acceptable) setValid(true); else setValid(false); } } else setValid(false); } void QValidatedLineEdit::setCheckValidator(const QValidator *v) { checkValidator = v; }
i3lome/failfial
src/qt/qvalidatedlineedit.cpp
C++
mit
2,162
/* * Copyright 1997-2015 Optimatika (www.optimatika.se) * * 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 org.ojalgo.matrix.store; import org.ojalgo.ProgrammingError; import org.ojalgo.access.Access1D; import org.ojalgo.constant.PrimitiveMath; import org.ojalgo.scalar.Scalar; /** * IdentityStore * * @author apete */ final class IdentityStore<N extends Number> extends FactoryStore<N> { private final int myDimension; private IdentityStore(final org.ojalgo.matrix.store.PhysicalStore.Factory<N, ?> factory, final int rowsCount, final int columnsCount) { super(factory, rowsCount, columnsCount); myDimension = 0; ProgrammingError.throwForIllegalInvocation(); } IdentityStore(final PhysicalStore.Factory<N, ?> factory, final int dimension) { super(factory, dimension, dimension); myDimension = dimension; } @Override public MatrixStore<N> conjugate() { return this; } @Override public PhysicalStore<N> copy() { return this.factory().makeEye(myDimension, myDimension); } public double doubleValue(final long aRow, final long aCol) { if (aRow == aCol) { return PrimitiveMath.ONE; } else { return PrimitiveMath.ZERO; } } public int firstInColumn(final int col) { return col; } public int firstInRow(final int row) { return row; } public N get(final long aRow, final long aCol) { if (aRow == aCol) { return this.factory().scalar().one().getNumber(); } else { return this.factory().scalar().zero().getNumber(); } } @Override public int limitOfColumn(final int col) { return col + 1; } @Override public int limitOfRow(final int row) { return row + 1; } @Override public MatrixStore<N> multiply(final Access1D<N> right) { if (this.getColDim() == right.count()) { return this.factory().columns(right); } else if (right instanceof MatrixStore<?>) { return ((MatrixStore<N>) right).copy(); } else { return super.multiply(right); } } @Override public MatrixStore<N> multiplyLeft(final Access1D<N> leftMtrx) { if (leftMtrx.count() == this.getRowDim()) { return this.factory().rows(leftMtrx); } else if (leftMtrx instanceof MatrixStore<?>) { return ((MatrixStore<N>) leftMtrx).copy(); } else { return super.multiplyLeft(leftMtrx); } } public Scalar<N> toScalar(final long row, final long column) { if (row == column) { return this.factory().scalar().one(); } else { return this.factory().scalar().zero(); } } @Override public MatrixStore<N> transpose() { return this; } }
jpalves/ojAlgo
src/org/ojalgo/matrix/store/IdentityStore.java
Java
mit
3,940
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using XOMNI.SDK.Core.ApiAccess; using XOMNI.SDK.Core.Providers; namespace XOMNI.SDK.Private.ApiAccess.Catalog.ItemPrice { internal class BatchPrice : ApiAccessBase { protected override string SingleOperationBaseUrl { get { throw new NotImplementedException(); } } protected override string ListOperationBaseUrl { get { return "/private/catalog/items/{0}/prices"; } } public Task<List<Model.Private.Catalog.Price>> UpdateItemPricesAsync(int itemId, List<Model.Private.Catalog.Price> priceList, ApiBasicCredential credential) { return HttpProvider.PutAsync<List<Model.Private.Catalog.Price>>(GenerateUrl(string.Format(ListOperationBaseUrl, itemId)), priceList, credential); } internal XOMNIRequestMessage<List<Model.Private.Catalog.Price>> CreateUpdateItemPricesRequest(int itemId, List<Model.Private.Catalog.Price> priceList, ApiBasicCredential credential) { return new XOMNIRequestMessage<List<Model.Private.Catalog.Price>>(HttpProvider.CreatePutRequest(GenerateUrl(string.Format(ListOperationBaseUrl, itemId)), credential, priceList)); } } }
nseckinoral/xomni-sdk-dotnet
src/XOMNI.SDK.Private/ApiAccess/Catalog/ItemPrice/BatchPrice.cs
C#
mit
1,322
// All code points in the `Sora_Sompeng` script as per Unicode v8.0.0: [ 0x110D0, 0x110D1, 0x110D2, 0x110D3, 0x110D4, 0x110D5, 0x110D6, 0x110D7, 0x110D8, 0x110D9, 0x110DA, 0x110DB, 0x110DC, 0x110DD, 0x110DE, 0x110DF, 0x110E0, 0x110E1, 0x110E2, 0x110E3, 0x110E4, 0x110E5, 0x110E6, 0x110E7, 0x110E8, 0x110F0, 0x110F1, 0x110F2, 0x110F3, 0x110F4, 0x110F5, 0x110F6, 0x110F7, 0x110F8, 0x110F9 ];
mathiasbynens/unicode-data
8.0.0/scripts/Sora_Sompeng-code-points.js
JavaScript
mit
424
using System; namespace Dust { public interface IServiceAspect<TRequest, TResponse> { TResponse Process(TRequest request, Func<TRequest, TResponse> serviceOperation); } }
pjtown/dusty-web-services
Dust/IServiceAspect.cs
C#
mit
176
namespace nUpdate.Administration.Core.Operations.Panels { partial class ScriptExecuteOperationPanel { /// <summary> /// Erforderliche Designervariable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Verwendete Ressourcen bereinigen. /// </summary> /// <param name="disposing">True, wenn verwaltete Ressourcen gelöscht werden sollen; andernfalls False.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Vom Komponenten-Designer generierter Code /// <summary> /// Erforderliche Methode für die Designerunterstützung. /// Der Inhalt der Methode darf nicht mit dem Code-Editor geändert werden. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ScriptExecuteOperationPanel)); this.codeTextBox = new FastColoredTextBoxNS.FastColoredTextBox(); this.tabControl1 = new System.Windows.Forms.TabControl(); this.sourceCodeTabPage = new System.Windows.Forms.TabPage(); this.errorsTabPage = new System.Windows.Forms.TabPage(); this.errorListView = new System.Windows.Forms.ListView(); this.numberHeader = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.descriptionHeader = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.lineHeader = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.columnHeader = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); ((System.ComponentModel.ISupportInitialize)(this.codeTextBox)).BeginInit(); this.tabControl1.SuspendLayout(); this.sourceCodeTabPage.SuspendLayout(); this.errorsTabPage.SuspendLayout(); this.SuspendLayout(); // // codeTextBox // this.codeTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.codeTextBox.AutoCompleteBracketsList = new char[] { '(', ')', '{', '}', '[', ']', '\"', '\"', '\'', '\''}; this.codeTextBox.AutoScrollMinSize = new System.Drawing.Size(907, 252); this.codeTextBox.BackBrush = null; this.codeTextBox.CharHeight = 14; this.codeTextBox.CharWidth = 8; this.codeTextBox.Cursor = System.Windows.Forms.Cursors.IBeam; this.codeTextBox.DisabledColor = System.Drawing.Color.FromArgb(((int)(((byte)(100)))), ((int)(((byte)(180)))), ((int)(((byte)(180)))), ((int)(((byte)(180))))); this.codeTextBox.IsReplaceMode = false; this.codeTextBox.LeftBracket = '{'; this.codeTextBox.LeftBracket2 = '['; this.codeTextBox.Location = new System.Drawing.Point(0, 0); this.codeTextBox.Name = "codeTextBox"; this.codeTextBox.Paddings = new System.Windows.Forms.Padding(0); this.codeTextBox.RightBracket = '}'; this.codeTextBox.RightBracket2 = ']'; this.codeTextBox.SelectionColor = System.Drawing.Color.FromArgb(((int)(((byte)(60)))), ((int)(((byte)(0)))), ((int)(((byte)(0)))), ((int)(((byte)(255))))); this.codeTextBox.Size = new System.Drawing.Size(468, 197); this.codeTextBox.TabIndex = 2; this.codeTextBox.Text = resources.GetString("codeTextBox.Text"); this.codeTextBox.Zoom = 100; this.codeTextBox.TextChanged += new System.EventHandler<FastColoredTextBoxNS.TextChangedEventArgs>(this.codeTextBox_TextChanged); this.codeTextBox.Leave += new System.EventHandler(this.codeTextBox_Leave); // // tabControl1 // this.tabControl1.Controls.Add(this.sourceCodeTabPage); this.tabControl1.Controls.Add(this.errorsTabPage); this.tabControl1.Location = new System.Drawing.Point(2, 2); this.tabControl1.Name = "tabControl1"; this.tabControl1.SelectedIndex = 0; this.tabControl1.Size = new System.Drawing.Size(476, 223); this.tabControl1.TabIndex = 3; // // sourceCodeTabPage // this.sourceCodeTabPage.Controls.Add(this.codeTextBox); this.sourceCodeTabPage.Location = new System.Drawing.Point(4, 22); this.sourceCodeTabPage.Name = "sourceCodeTabPage"; this.sourceCodeTabPage.Padding = new System.Windows.Forms.Padding(3); this.sourceCodeTabPage.Size = new System.Drawing.Size(468, 197); this.sourceCodeTabPage.TabIndex = 0; this.sourceCodeTabPage.Text = "Source code"; this.sourceCodeTabPage.UseVisualStyleBackColor = true; // // errorsTabPage // this.errorsTabPage.Controls.Add(this.errorListView); this.errorsTabPage.Location = new System.Drawing.Point(4, 22); this.errorsTabPage.Name = "errorsTabPage"; this.errorsTabPage.Padding = new System.Windows.Forms.Padding(3); this.errorsTabPage.Size = new System.Drawing.Size(468, 197); this.errorsTabPage.TabIndex = 1; this.errorsTabPage.Text = "Errors (0)"; this.errorsTabPage.UseVisualStyleBackColor = true; // // errorListView // this.errorListView.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.numberHeader, this.descriptionHeader, this.lineHeader, this.columnHeader}); this.errorListView.Location = new System.Drawing.Point(0, 0); this.errorListView.Name = "errorListView"; this.errorListView.Size = new System.Drawing.Size(468, 197); this.errorListView.TabIndex = 0; this.errorListView.UseCompatibleStateImageBehavior = false; this.errorListView.View = System.Windows.Forms.View.Details; // // numberHeader // this.numberHeader.Text = "Number"; this.numberHeader.Width = 78; // // descriptionHeader // this.descriptionHeader.Text = "Description"; this.descriptionHeader.Width = 255; // // lineHeader // this.lineHeader.Text = "Line"; this.lineHeader.Width = 63; // // columnHeader // this.columnHeader.Text = "Column"; this.columnHeader.Width = 68; // // ScriptExecuteOperationPanel // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.SystemColors.Window; this.Controls.Add(this.tabControl1); this.Name = "ScriptExecuteOperationPanel"; this.Size = new System.Drawing.Size(488, 225); ((System.ComponentModel.ISupportInitialize)(this.codeTextBox)).EndInit(); this.tabControl1.ResumeLayout(false); this.sourceCodeTabPage.ResumeLayout(false); this.errorsTabPage.ResumeLayout(false); this.ResumeLayout(false); } #endregion private FastColoredTextBoxNS.FastColoredTextBox codeTextBox; private System.Windows.Forms.TabControl tabControl1; private System.Windows.Forms.TabPage sourceCodeTabPage; private System.Windows.Forms.TabPage errorsTabPage; private System.Windows.Forms.ListView errorListView; private System.Windows.Forms.ColumnHeader descriptionHeader; private System.Windows.Forms.ColumnHeader lineHeader; private System.Windows.Forms.ColumnHeader columnHeader; private System.Windows.Forms.ColumnHeader numberHeader; } }
ProgTrade/nUpdate
nUpdate.Administration/Core/Operations/Panels/ScriptExecuteOperationPanel.Designer.cs
C#
mit
8,690
import cPickle as pickle import numpy as np import os import sys sys.path.append('../') import gp from uitools import UITools class Manager(object): def __init__(self, output_dir): ''' ''' self._data_path = '/home/d/dojo_xp/data/' self._output_path = os.path.join(self._data_path, 'ui_out', output_dir) self._merge_errors = None self._corrections = [] self._correction_times = [] self._correction_vis = [] self._mode = 'GP' def start( self, mode, cnn_path='../nets/IPMLB_FULL.p', verbose=True ): ''' ''' self._cnn = UITools.load_cnn(cnn_path) self._mode = mode if self._mode == 'GP*': # now we use the matlab engine print 'Using Active Label Suggestion' import matlab.engine eng = matlab.engine.start_matlab() self._merge_errors = self.load_merge_errors() self._bigM = self.load_split_errors() # let's generate our active label features and store a lsit elif self._mode == 'GP': if verbose: print 'Using GP proper' self._merge_errors = self.load_merge_errors() self._bigM = self.load_split_errors() elif self._mode == 'FP': print 'Using FP' self._merge_errors = [] self._bigM = self.load_split_errors(filename='bigM_fp.p') elif self._mode == 'TEST': print 'Test mode using FP' self._merge_errors = [] self._bigM = self.load_split_errors(filename='bigM_fp_test.p') else: print 'WRONG MODE, should be GP, GP* or FP' sys.exit(2) # load data if self._mode == 'TEST': print 'We are using dummy data for testing' input_image, input_prob, input_gold, input_rhoana, dojo_bbox = gp.Legacy.read_dojo_test_data() self._mode = 'FP' else: input_image, input_prob, input_gold, input_rhoana, dojo_bbox = gp.Legacy.read_dojo_data() self._input_image = input_image self._input_prob = input_prob self._input_gold = input_gold self._input_rhoana = input_rhoana self._dojo_bbox = dojo_bbox if verbose: print 'VI at start:', UITools.VI(self._input_gold, self._input_rhoana)[1] print 'aRE at start:', UITools.adaptedRandError(self._input_rhoana, self._input_gold)[1] def gen_active_label_features(self): ''' ''' active_labels_file = os.path.join(self._data_path, 'split_active_labels.p') if os.path.exists(active_labels_file): with open(active_labels_file, 'rb') as f: feature_vector = pickle.load(f) print 'Feature vector loaded from pickle.' else: print 'Calculating active labels...' # we work on a copy of bigM, let's call it bigD like daddy bigD = self._bigM.copy() import theano import theano.tensor as T from lasagne.layers import get_output # go from highest prob to lowest in our bigD prediction = np.inf while prediction > -1: z, labels, prediction = UITools.find_next_split_error(bigD) # create patch l,n = labels patches = [] patches_l, patches_n = Patch.grab(image, prob, segmentation, l, n, sample_rate=10, oversampling=False) patches += patches_l patches += patches_n grouped_patches = Patch.group(patches) # let CNN without softmax analyze the patch to create features x = X_test[100].reshape(1,4,75,75) layer = net.layers_['hidden5'] xs = T.tensor4('xs').astype(theano.config.floatX) get_activity = theano.function([xs], get_output(layer, xs)) activity = get_activity(x) # create feature vector # store feature vector to pickle with open(active_labels_file, 'wb') as f: pickle.dump(feature_vector, f) print 'Feature vector stored.' # Now, we need to represent the distance between each of these items using the graph Laplacian matrix 'LGReg'. # We're going to build this now using a MATLAB function - 'BuildLGRegularizer.m' # First, we need to set two parameters, as this is an approximation of the true graph laplacian to allow us to # use this on very large datasets manifoldDim = 17; kNNSize = 20; # Second, we set the regularization strength of this graph Laplacian lambdaRP = 0.005; # Next, we call the function #LGReg = eng.BuildLGRegularizer( x, manifoldDim, kNNSize, nargout=1 ); # ...but, two problems: # 1) We need to transform our numpy array x into something MATLAB can handle xM = matlab.double( size=[nItems, nFeatures] ) for j in range(0, nFeatures-1): for i in range(0, nItems-1): xM[i][j] = x[i][j]; # 2) LGReg is a 'sparse' matrix type, and python doesn't support that. # Let's leave the output variable in the MATLAB workspace, and until we need to use it. eng.workspace['xM'] = xM; # We also need to pass our function variables eng.workspace['nItems'] = nItems; eng.workspace['nFeatures'] = nFeatures; eng.workspace['lambdaRP'] = lambdaRP; eng.workspace['manifoldDim'] = manifoldDim; eng.workspace['kNNSize'] = kNNSize; # OK, now let's call our function eng.eval( "LGReg = BuildLGRegularizer( xM, manifoldDim, kNNSize )", nargout=0 ) def load_merge_errors(self, filename='merges_new_cnn.p'): ''' ''' with open(os.path.join(self._data_path, filename), 'rb') as f: merge_errors = pickle.load(f) return sorted(merge_errors, key=lambda x: x[3], reverse=False) def load_split_errors(self, filename='bigM_new_cnn.p'): ''' ''' with open(os.path.join(self._data_path, filename), 'rb') as f: bigM = pickle.load(f) return bigM def get_next_merge_error(self): ''' ''' if len(self._merge_errors) == 0: return None return self._merge_errors[0] def get_next_split_error(self): ''' ''' if self._mode == 'GP' or self._mode == 'FP': z, labels, prediction = UITools.find_next_split_error(self._bigM) elif self._mode == 'GP*': # # here, let's check for the next active label suggestion # but only if we already corrected twice # pass self._split_error = (z, labels, prediction) return self._split_error def get_merge_error_image(self, merge_error, number): border = merge_error[3][number][1] z = merge_error[0] label = merge_error[1] prob = merge_error[2] input_image = self._input_image input_prob = self._input_prob input_rhoana = self._input_rhoana a,b,c,d,e,f,g,h,i,j,k = gp.Legacy.get_merge_error_image(input_image[z], input_rhoana[z], label, border, returnbb=True) border_before = b labels_before = h border_after = c labels_after = i slice_overview = g cropped_slice_overview = j bbox = k return border_before, border_after, labels_before, labels_after, slice_overview, cropped_slice_overview, bbox def get_split_error_image(self, split_error, number=1): z = split_error[0] labels = split_error[1] input_image = self._input_image input_prob = self._input_prob input_rhoana = self._input_rhoana a,b,c,d,e,f,g,h = gp.Legacy.get_split_error_image(input_image[z], input_rhoana[z], labels, returnbb=True) labels_before = b borders_before = c borders_after = d labels_after = e slice_overview = f cropped_slice_overview = g bbox = h return borders_before, borders_after, labels_before, labels_after, slice_overview, cropped_slice_overview, bbox def correct_merge(self, clicked_correction, do_oracle=False, do_GT=False): input_image = self._input_image input_prob = self._input_prob input_rhoana = self._input_rhoana # # # oracle_choice = '' delta_vi = -1 if do_oracle: # lets check what the oracle would do merge_error = self._merge_errors[0] number = 0 border = merge_error[3][number][1] z = merge_error[0] label = merge_error[1] a,b,c,d,e,f,g,h,i,j = gp.Legacy.get_merge_error_image(input_image[z], input_rhoana[z], label, border) oracle_rhoana = f # check VI delta old_vi = gp.Util.vi(self._input_gold[z], self._input_rhoana[z]) new_vi = gp.Util.vi(self._input_gold[z], oracle_rhoana) delta_vi = old_vi - new_vi if delta_vi > 0: oracle_choice = '1' else: oracle_choice = 'current' if not clicked_correction == 'current': clicked_correction = int(clicked_correction)-1 # # correct the merge # merge_error = self._merge_errors[0] number = clicked_correction border = merge_error[3][number][1] z = merge_error[0] label = merge_error[1] a,b,c,d,e,f,g,h,i,j = gp.Legacy.get_merge_error_image(input_image[z], input_rhoana[z], label, border) new_rhoana = f self._input_rhoana[z] = new_rhoana vi = UITools.VI(self._input_gold, input_rhoana) #print 'New global VI', vi[0] self._correction_vis.append(vi[2]) # # and remove the original label from our bigM matrix # self._bigM[z][label,:] = -3 self._bigM[z][:,label] = -3 # now add the two new labels label1 = new_rhoana.max() label2 = new_rhoana.max()-1 new_m = np.zeros((self._bigM[z].shape[0]+2, self._bigM[z].shape[1]+2), dtype=self._bigM[z].dtype) new_m[:,:] = -1 new_m[0:-2,0:-2] = self._bigM[z] #print 'adding', label1, 'to', z new_m = gp.Legacy.add_new_label_to_M(self._cnn, new_m, input_image[z], input_prob[z], new_rhoana, label1) new_m = gp.Legacy.add_new_label_to_M(self._cnn, new_m, input_image[z], input_prob[z], new_rhoana, label2) # re-propapage new_m to bigM self._bigM[z] = new_m # remove merge error del self._merge_errors[0] mode = 'merge' if len(self._merge_errors) == 0: mode = 'split' return mode, oracle_choice, delta_vi def correct_split(self, clicked_correction, do_oracle=False): input_image = self._input_image input_prob = self._input_prob input_rhoana = self._input_rhoana split_error = self._split_error z = split_error[0] labels = split_error[1] m = self._bigM[z] # # # oracle_choice = '' delta_vi = -1 if do_oracle: oracle_m, oracle_rhoana = UITools.correct_split(self._cnn, m, self._mode, input_image[z], input_prob[z], input_rhoana[z], labels[0], labels[1], oversampling=False) # check VI delta old_vi = gp.Util.vi(self._input_gold[z], self._input_rhoana[z]) new_vi = gp.Util.vi(self._input_gold[z], oracle_rhoana) delta_vi = old_vi - new_vi if delta_vi > 0: oracle_choice = '1' else: oracle_choice = 'current' if clicked_correction == 'current': # we skip this split # print 'FP or current' new_m = UITools.skip_split(m, labels[0], labels[1]) self._bigM[z] = new_m else: # we correct this split # print 'fixing slice',z,'labels', labels # vi = gp.Util.vi(self._input_gold[z], self._input_rhoana[z]) # print 'bef vi', vi new_m, new_rhoana = UITools.correct_split(self._cnn, m, self._mode, input_image[z], input_prob[z], input_rhoana[z], labels[0], labels[1], oversampling=False) self._bigM[z] = new_m self._input_rhoana[z] = new_rhoana # vi = gp.Util.vi(self._input_gold[z], self._input_rhoana[z]) # print 'New VI', vi[0] vi = UITools.VI(self._input_gold, self._input_rhoana) #print 'New global VI', vi[0] self._correction_vis.append(vi[2]) # self.finish() return 'split', oracle_choice, delta_vi def store(self): vi = UITools.VI(self._input_gold, self._input_rhoana) print 'New VI', vi[1] are = UITools.adaptedRandError(self._input_rhoana, self._input_gold) print 'New aRE', are[1] if not os.path.exists(self._output_path): os.makedirs(self._output_path) # store our changed rhoana with open(os.path.join(self._output_path, 'ui_results.p'), 'wb') as f: pickle.dump(self._input_rhoana, f) # store the times with open(os.path.join(self._output_path, 'times.p'), 'wb') as f: pickle.dump(self._correction_times, f) # store the corrections with open(os.path.join(self._output_path, 'corrections.p'), 'wb') as f: pickle.dump(self._corrections, f) with open(os.path.join(self._output_path, 'correction_vis.p'), 'wb') as f: pickle.dump(self._correction_vis, f) print 'All stored.'
VCG/gp
ui/manager.py
Python
mit
12,894
/* * This file is part of ViaVersion - https://github.com/ViaVersion/ViaVersion * Copyright (C) 2016-2021 ViaVersion and contributors * * 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 us.myles.ViaVersion.api.boss; @Deprecated public enum BossColor { PINK(0), BLUE(1), RED(2), GREEN(3), YELLOW(4), PURPLE(5), WHITE(6); private final int id; BossColor(int id) { this.id = id; } public int getId() { return id; } }
MylesIsCool/ViaVersion
api-legacy/src/main/java/us/myles/ViaVersion/api/boss/BossColor.java
Java
mit
1,520
require 'test_helper' module Disclaimer class DocumentsHelperTest < ActionView::TestCase end end
reggieb/Disclaimer
test/unit/helpers/disclaimer/documents_helper_test.rb
Ruby
mit
102
require "active_support/core_ext/string/inflections" module GreatPretender class Pretender def initialize(mockup) @mockup = mockup end def to_module pretenders = load_pretenders Module.new do define_method(:method_missing) do |method_name, *args, &block| pretender = pretenders.find { |p| p.respond_to?(method_name) } if pretender if defined? Rails deprecation_warning = I18n.t('great_pretender.deprecated_pretender') deprecation_warning_args = [method_name, pretender.class.name.underscore.gsub(/_pretender$/, ''), method_name] Rails.logger.debug deprecation_warning % deprecation_warning_args end pretender.send(method_name, *args, &block) else super(method_name, *args, &block) end end end end private def load_pretender(class_name) class_name = class_name + 'Pretender' begin klass = class_name.constantize rescue NameError return nil end initialize = klass.instance_method(:initialize) if initialize.arity == 1 klass.new(@mockup) else klass.new end end def load_pretenders pretenders = [] @mockup.slug.split("/").each do |pretender_name| # Given a mockup named something like 'social_contents', # support pretenders named 'SocialContentsPretender' AND 'SocialContentPretender' singular_class = pretender_name.classify plural_class = singular_class.pluralize [singular_class, plural_class].each do |class_name| if instance = load_pretender(class_name) pretenders.push(instance) end end end pretenders.reverse end end end
BackForty/great_pretender
lib/great_pretender/pretender.rb
Ruby
mit
1,831
{{-- Master Layout --}} @extends('cortex/foundation::frontarea.layouts.default') {{-- Page Title --}} @section('title') {{ extract_title(Breadcrumbs::render()) }} @endsection {{-- Scripts --}} @push('inline-scripts') {!! JsValidator::formRequest(Cortex\Auth\Http\Requests\Frontarea\TenantRegistrationProcessRequest::class)->selector("#frontarea-tenant-registration-form")->ignore('.skip-validation') !!} <script> window.countries = @json($countries); window.selectedCountry = '{{ old('tenant.country_code') }}'; </script> @endpush @section('body-attributes')class="auth-page"@endsection {{-- Main Content --}} @section('content') <div class="container"> <div class="row"> <div class="col-md-6 col-md-offset-3"> <section class="auth-form"> {{ Form::open(['url' => route('frontarea.register.tenant.process'), 'id' => 'frontarea-tenant-registration-form', 'role' => 'auth']) }} <div class="centered"><strong>{{ trans('cortex/auth::common.account_register') }}</strong></div> <div id="accordion" class="wizard"> <div class="panel wizard-step"> <div> <h4 class="wizard-step-title"> <a role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseOne">{{ trans('cortex/auth::common.manager_account') }}</a> </h4> </div> <div id="collapseOne" class="collapse in"> <div class="wizard-step-body"> <div class="form-group has-feedback{{ $errors->has('manager.given_name') ? ' has-error' : '' }}"> {{ Form::text('manager[given_name]', old('manager.given_name'), ['class' => 'form-control input-lg', 'placeholder' => trans('cortex/auth::common.given_name'), 'required' => 'required', 'autofocus' => 'autofocus']) }} @if ($errors->has('manager.given_name')) <span class="help-block">{{ $errors->first('manager.given_name') }}</span> @endif </div> <div class="form-group has-feedback{{ $errors->has('manager.family_name') ? ' has-error' : '' }}"> {{ Form::text('manager[family_name]', old('manager.family_name'), ['class' => 'form-control input-lg', 'placeholder' => trans('cortex/auth::common.family_name')]) }} @if ($errors->has('manager.family_name')) <span class="help-block">{{ $errors->first('manager.family_name') }}</span> @endif </div> <div class="form-group has-feedback{{ $errors->has('manager.username') ? ' has-error' : '' }}"> {{ Form::text('manager[username]', old('manager.username'), ['class' => 'form-control input-lg', 'placeholder' => trans('cortex/auth::common.username'), 'required' => 'required']) }} @if ($errors->has('manager.username')) <span class="help-block">{{ $errors->first('manager.username') }}</span> @endif </div> <div class="form-group has-feedback{{ $errors->has('manager.email') ? ' has-error' : '' }}"> {{ Form::email('manager[email]', old('manager.email'), ['class' => 'form-control input-lg', 'placeholder' => trans('cortex/auth::common.email'), 'required' => 'required']) }} @if ($errors->has('manager.email')) <span class="help-block">{{ $errors->first('manager.email') }}</span> @endif </div> <div class="form-group has-feedback{{ $errors->has('manager.password') ? ' has-error' : '' }}"> {{ Form::password('manager[password]', ['class' => 'form-control input-lg', 'placeholder' => trans('cortex/auth::common.password'), 'required' => 'required']) }} @if ($errors->has('manager.password')) <span class="help-block">{{ $errors->first('manager.password') }}</span> @endif </div> <div class="form-group has-feedback{{ $errors->has('manager.password_confirmation') ? ' has-error' : '' }}"> {{ Form::password('manager[password_confirmation]', ['class' => 'form-control input-lg', 'placeholder' => trans('cortex/auth::common.password_confirmation'), 'required' => 'required']) }} @if ($errors->has('manager.password_confirmation')) <span class="help-block">{{ $errors->first('manager.password_confirmation') }}</span> @endif </div> </div> </div> </div> <div class="panel wizard-step"> <div role="tab" id="headingTwo"> <h4 class="wizard-step-title"> <a class="collapsed" role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseTwo">{{ trans('cortex/auth::common.tenant_details') }}</a> </h4> </div> <div id="collapseTwo" class="panel-collapse collapse"> <div class="wizard-step-body"> <div class="form-group has-feedback{{ $errors->has('tenant.title') ? ' has-error' : '' }}"> {{ Form::text('tenant[title]', old('tenant.title'), ['class' => 'form-control input-lg', 'placeholder' => trans('cortex/auth::common.title'), 'data-slugify' => '[name="tenant\[name\]"]', 'required' => 'required']) }} @if ($errors->has('tenant.title')) <span class="help-block">{{ $errors->first('tenant.title') }}</span> @endif </div> <div class="form-group has-feedback{{ $errors->has('tenant.slug') ? ' has-error' : '' }}"> {{ Form::text('tenant[slug]', old('tenant.slug'), ['class' => 'form-control input-lg', 'placeholder' => trans('cortex/auth::common.slug'), 'required' => 'required']) }} @if ($errors->has('tenant.slug')) <span class="help-block">{{ $errors->first('tenant.slug') }}</span> @endif </div> <div class="form-group has-feedback{{ $errors->has('tenant.email') ? ' has-error' : '' }}"> {{ Form::text('tenant[email]', old('tenant.email'), ['class' => 'form-control input-lg', 'placeholder' => trans('cortex/auth::common.email'), 'required' => 'required']) }} @if ($errors->has('tenant.email')) <span class="help-block">{{ $errors->first('tenant.email') }}</span> @endif </div> <div class="form-group has-feedback{{ $errors->has('tenant.country_code') ? ' has-error' : '' }}"> {{ Form::hidden('tenant[country_code]', '', ['class' => 'skip-validation']) }} {{ Form::select('tenant[country_code]', [], null, ['class' => 'form-control select2 input-lg', 'placeholder' => trans('cortex/auth::common.select_country'), 'required' => 'required', 'data-allow-clear' => 'true', 'data-width' => '100%']) }} @if ($errors->has('tenant.country_code')) <span class="help-block">{{ $errors->first('tenant.country_code') }}</span> @endif </div> <div class="form-group{{ $errors->has('tenant.language_code') ? ' has-error' : '' }}"> {{ Form::hidden('tenant[language_code]', '') }} {{ Form::select('tenant[language_code]', $languages, null, ['class' => 'form-control select2', 'placeholder' => trans('cortex/auth::common.select_language'), 'data-allow-clear' => 'true', 'data-width' => '100%']) }} @if ($errors->has('tenant.language_code')) <span class="help-block">{{ $errors->first('tenant.language_code') }}</span> @endif </div> </div> </div> </div> </div> {{ Form::button('<i class="fa fa-user-plus"></i> '.trans('cortex/auth::common.register'), ['class' => 'btn btn-lg btn-primary btn-block', 'type' => 'submit']) }} <div> {{ Html::link(route('frontarea.login'), trans('cortex/auth::common.account_login')) }} {{ trans('cortex/foundation::common.or') }} {{ Html::link(route('frontarea.passwordreset.request'), trans('cortex/auth::common.passwordreset')) }} </div> {{ Form::close() }} </section> </div> </div> </div> @endsection
rinvex/cortex-fort
resources/views/frontarea/pages/tenant-registration.blade.php
PHP
mit
10,976
/** * The AnalysisShapeUploadView module. * * @return AnalysisShapeUploadView class (extends Backbone.View). */ define( [ 'backbone', 'mps', 'turf', 'map/services/ShapefileService', 'helpers/geojsonUtilsHelper' ], function(Backbone, mps, turf, ShapefileService, geojsonUtilsHelper) { 'use strict'; var AnalysisShapeUploadView = Backbone.View.extend({ defaults: { fileSizeLimit: 1000000 }, initialize: function() { this.fileSizeLimit = this.defaults.fileSizeLimit; this.$dropable = document.getElementById('drop-shape-analysis'); this.$fileSelector = document.getElementById('analysis-file-upload'); this._initDroppable(); }, _initDroppable: function() { if (this.$dropable && this.$fileSelector) { this.$fileSelector.addEventListener( 'change', function() { var file = this.$fileSelector.files[0]; if (file) { this._handleUpload(file); } }.bind(this) ); this.$dropable.addEventListener( 'click', function(event) { if (event.target.classList.contains('source')) { return true; } $(this.$fileSelector).trigger('click'); }.bind(this) ); this.$dropable.ondragover = function() { this.$dropable.classList.toggle('moving'); return false; }.bind(this); this.$dropable.ondragend = function() { this.$dropable.classList.toggle('moving'); return false; }.bind(this); this.$dropable.ondrop = function(e) { e.preventDefault(); var file = e.dataTransfer.files[0]; this._handleUpload(file); return false; }.bind(this); } }, _handleUpload: function(file) { var sizeMessage = 'The selected file is quite large and uploading ' + 'it might result in browser instability. Do you want to continue?'; if (file.size > this.fileSizeLimit && !window.confirm(sizeMessage)) { this.$dropable.classList.remove('moving'); return; } mps.publish('Spinner/start', []); var shapeService = new ShapefileService({ shapefile: file }); shapeService.toGeoJSON().then( function(data) { var combinedFeatures = data.features.reduce(turf.union); var bounds = geojsonUtilsHelper.getBoundsFromGeojson( combinedFeatures ); mps.publish('Analysis/upload', [combinedFeatures.geometry]); this.trigger('analysis:shapeUpload:draw', combinedFeatures); this.trigger('analysis:shapeUpload:fitBounds', bounds); }.bind(this) ); this.$dropable.classList.remove('moving'); } }); return AnalysisShapeUploadView; } );
Vizzuality/gfw-climate
app/assets/javascripts/map/views/tabs/AnalysisShapeUploadView.js
JavaScript
mit
3,022
class Api::V1::CharactersController < ApplicationController def show character = Character.find(params[:id]) response = Api::V1::CharacterSerializer.new(character) render(json: response) end def index if params[:name] character = Character.find_by(name: params[:name]) if character.nil? response = "Character does not exist." else response = Api::V1::CharacterSerializer.new(character) render(json: response) end else render plain: "Not authorized", status: 401 # characters = Character.all # # render( # json: ActiveModel::ArraySerializer.new( # characters, # each_serializer: Api::V1::CharacterSerializer, # root: 'characters', # ) # ) end end end
mbroadwater/shadowrun
app/controllers/api/v1/characters_controller.rb
Ruby
mit
806
package eu.thog92.isbrh.example; import eu.thog92.isbrh.ISBRH; import eu.thog92.isbrh.render.ITextureHandler; import eu.thog92.isbrh.render.TextureLoader; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumWorldBlockLayer; import net.minecraft.util.ResourceLocation; import net.minecraft.world.IBlockAccess; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; public class BlockExample extends Block implements ITextureHandler { @SideOnly(Side.CLIENT) private TextureLoader textureLoader; @SideOnly(Side.CLIENT) private final ResourceLocation textureLocation = new ResourceLocation( "isbrhcore:blocks/test"); public BlockExample() { super(Material.iron); this.setCreativeTab(CreativeTabs.tabBlock); } @Override public boolean isOpaqueCube() { return false; } @SideOnly(Side.CLIENT) public int getRenderType() { return ISBRH.testId; } @Override public boolean isNormalCube() { return false; } @SideOnly(Side.CLIENT) @Override public boolean shouldSideBeRendered(IBlockAccess world, BlockPos pos, EnumFacing face) { return true; } @SideOnly(Side.CLIENT) public EnumWorldBlockLayer getBlockLayer() { return EnumWorldBlockLayer.SOLID; } public boolean isFullCube() { return false; } @Override public TextureAtlasSprite getSidedTexture(IBlockState state, EnumFacing facing) { return textureLoader.getTextureMap().getAtlasSprite(textureLocation.toString()); } @Override public void loadTextures(TextureLoader loader) { this.textureLoader = loader; loader.registerTexture(textureLocation); } }
Thog/ISBRH
src/main/java/eu/thog92/isbrh/example/BlockExample.java
Java
mit
2,078
#include <set> #include <stdio.h> #include <stdlib.h> #include <string> #include <unistd.h> #include <uuid/uuid.h> #include <vector> #include <scxcorelib/scxcmn.h> #include <scxcorelib/scxprocess.h> #include <scxcorelib/stringaid.h> #include <testutils/scxunit.h> #include <testutils/providertestutils.h> #include "Container_ContainerStatistics_Class_Provider.h" #include "cjson/cJSON.h" using namespace std; using namespace SCXCoreLib; class ContainerStatisticsTest : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(ContainerStatisticsTest); CPPUNIT_TEST(TestEnumerateInstances); CPPUNIT_TEST_SUITE_END(); public: vector<string> containers; static string NewGuid() { uuid_t uuid; uuid_generate_random(uuid); char s[37]; uuid_unparse(uuid, s); return s; } static string RunCommand(const char* command) { istringstream processInput; ostringstream processOutput; ostringstream processErr; CPPUNIT_ASSERT(!SCXProcess::Run(StrFromMultibyte(string(command)), processInput, processOutput, processErr, 0)); CPPUNIT_ASSERT_EQUAL(processErr.str(), string()); return processOutput.str(); } public: void setUp() { // Get some images to use fputc('\n', stdout); RunCommand("docker pull centos"); } void tearDown() { char command[128]; // Remove the containers that were started by the tests for (unsigned i = 0; i < containers.size(); i++) { sprintf(command, "docker rm -f %s", containers[i].c_str()); RunCommand(command); } containers.clear(); } protected: void TestEnumerateInstances() { wstring errMsg; TestableContext context; vector<wstring> m_keyNames; m_keyNames.push_back(L"InstanceID"); char containerName[64]; strcpy(containerName, NewGuid().c_str()); containers.push_back(string(containerName)); char command[128]; sprintf(command, "docker run --name=%s centos sleep 60 &", containerName); system(command); sleep(5); // Enumerate provider StandardTestEnumerateInstances<mi::Container_ContainerStatistics_Class_Provider>(m_keyNames, context, CALL_LOCATION(errMsg)); CPPUNIT_ASSERT(context.Size()); // Only check that the values are present and within the valid range because it is not possible to create a controlled environment for (unsigned i = 0; i < context.Size(); ++i) { wstring instanceId = context[i].GetProperty(L"InstanceID", CALL_LOCATION(errMsg)).GetValue_MIString(CALL_LOCATION(errMsg)); CPPUNIT_ASSERT(instanceId.length()); CPPUNIT_ASSERT(context[i].GetProperty(L"NetRXBytes", CALL_LOCATION(errMsg)).GetValue_MIUint64(CALL_LOCATION(errMsg)) >= 0); CPPUNIT_ASSERT(context[i].GetProperty(L"NetTXBytes", CALL_LOCATION(errMsg)).GetValue_MIUint64(CALL_LOCATION(errMsg)) >= 0); CPPUNIT_ASSERT(context[i].GetProperty(L"MemUsedMB", CALL_LOCATION(errMsg)).GetValue_MIUint64(CALL_LOCATION(errMsg)) >= 0); CPPUNIT_ASSERT(context[i].GetProperty(L"CPUTotal", CALL_LOCATION(errMsg)).GetValue_MIUint64(CALL_LOCATION(errMsg)) >= 0); unsigned short cpuUse = context[i].GetProperty(L"CPUTotalPct", CALL_LOCATION(errMsg)).GetValue_MIUint16(CALL_LOCATION(errMsg)); CPPUNIT_ASSERT(cpuUse <= 100); CPPUNIT_ASSERT(context[i].GetProperty(L"DiskBytesRead", CALL_LOCATION(errMsg)).GetValue_MIUint64(CALL_LOCATION(errMsg)) >= 0); CPPUNIT_ASSERT(context[i].GetProperty(L"DiskBytesWritten", CALL_LOCATION(errMsg)).GetValue_MIUint64(CALL_LOCATION(errMsg)) >= 0); } } }; CPPUNIT_TEST_SUITE_REGISTRATION(ContainerStatisticsTest);
HenryRawas/Docker-Provider
test/code/providers/Container_ContainerStatistics_Class_Provider_UnitTest.cpp
C++
mit
3,861
package ru.vyarus.dropwizard.orient.configuration; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.JsonNode; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import com.orientechnologies.common.parser.OSystemVariableResolver; import com.orientechnologies.orient.server.config.OServerConfiguration; import com.orientechnologies.orient.server.config.OServerConfigurationLoaderXml; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; import java.io.File; import java.io.IOException; import java.nio.file.Paths; /** * Orient configuration object. * Defines database files storage path and orient server configuration. * Server configuration could be provided inside yaml file (yaml representation of xml format) * or using external xml configuration file (native orient format). * <p> * Orient security configuration (security.json) may be declared with yaml in "security:" section or with * file path (security-file). May work without security config (but with warning in log). * <p> * Server start could be disabled with 'start' option. * * @see <a href="https://orientdb.org/docs/3.0.x/internals/DB-Server.html#configuration">configuration documentation</a> */ public class OrientServerConfiguration { private static final String APP_HOME = Paths.get(".").toAbsolutePath().normalize().toString(); private static final String TMP = System.getProperty("java.io.tmpdir"); private final Logger logger = LoggerFactory.getLogger(OrientServerConfiguration.class); @NotEmpty private String filesPath; private boolean start = true; private String configFile; private boolean adminServlet = true; private boolean autoSsl; @NotNull private OServerConfiguration config; private JsonNode security; private String securityFile; /** * @return true if orient server must be started, false to avoid starting orient server */ public boolean isStart() { return start; } /** * @param start true to start server, false to avoid starting */ public void setStart(final boolean start) { this.start = start; } /** * @return path to database files storage */ public String getFilesPath() { return filesPath; } /** * Directory may not exist - orient will create it when necessary. * Any system property or environment variable may be used with ${prop} syntax. * Special variables: $TMP for ${java.io.tmpdir}, $APP_HOME for application starting directory. * * @param filesPath path to store database files. */ @JsonProperty("files-path") public void setFilesPath(final String filesPath) { this.filesPath = parsePath(filesPath); } /** * As an alternative to inline yaml configuration, external xml file could be used (but not both). * Any system property or environment variable may be used with ${prop} syntax. * Special variables: $TMP for ${java.io.tmpdir}, $FILES_HOME for configured files path and * $APP_HOME for application starting directory. * * @param configFile path to server xml configuration file */ @JsonProperty("config-file") public void setConfigFile(final String configFile) { this.configFile = parsePath(configFile); Preconditions.checkState(this.config == null, "Orient configuration already declared manually. " + "Use either xml file or direct yaml config, but not both."); this.config = parseXmlConfigFile(configFile); } /** * @return true to deploy orient info servlet (/orient) on admin context, false to avoid installing */ public boolean isAdminServlet() { return adminServlet; } /** * @param adminServlet true to start orient info servlet on admin context, false to avoid installation */ @JsonProperty("admin-servlet") public void setAdminServlet(final boolean adminServlet) { this.adminServlet = adminServlet; } /** * @return true to configure ssl for orient automatically, if it configured for dropwizard */ public boolean isAutoSsl() { return autoSsl; } /** * NOTE: this is not intended for production use (due to limitations)! Only to simplify first steps and experiments. * <p> * When enabled, and main dropwizard context is configured to use https (only or one of connectors) then * orient server will be configured to use https (ssl for binary and https for http). Note, not secured * connection will be impossible. It also changes default binary port range (2424-) will be changed to default * ssl port range (2434-). Also, orient client ssl will be enabled. This is important to let you use * connection like "remote:localhost/db" as before, but make it work with ssl (when client ssl option enabled * orient will use 2434 as default port, so changing ports used to mimic defaults). * <p> * Please pay attention, that when auto-ssl will be switched off, orient client ssl must be configured manually! * <p> * By default, auto ssl is, of course disabled. Auto ssl configuration will not be applied if at least one listener * is already configured to use ssl (custom ssl socket) to avoid * * @param autoSsl true to enable automatic ssl configuration, false to leave disabled * @see ru.vyarus.dropwizard.orient.internal.util.AutoSslConfigurator */ @JsonProperty("auto-ssl") public void setAutoSsl(final boolean autoSsl) { this.autoSsl = autoSsl; } /** * @return orient server configuration object (from yaml config or external xml file) */ public OServerConfiguration getConfig() { return config; } /** * @param config configuration object defined in yaml configuration file */ public void setConfig(final OServerConfiguration config) { Preconditions.checkState(this.config == null, "Orient configuration already loaded from file '" + configFile + "'. Use either xml file or direct yaml config, but not both."); this.config = config; } /** * @param security orient security definition */ public void setSecurity(final JsonNode security) { Preconditions.checkState(this.securityFile == null, "Orient security configuration already defined as file '" + securityFile + "'. Use either json file or direct yaml config, but not both."); this.security = security; } /** * Orient 2.2 and above provides advanced security configuration. In distribution, this is the file is * "config/security.json". It could be loaded only as separate file (not part of main configuration). * <p> * Optional - orient server will work without it, but print error message about missed file. * <p> * Security config may be declared inside yaml configuration under "security:" section. Write security json * in yaml format. Later it would be stored as json file and configured for orient automatically. * <p> * NOTE: it is not required to specify security only in yaml. You can ignore this section and use separate json * file. You may use "server.security.file" system property to configure it's location or place file inside * your files path (files-path property) as "${files/path}/config/security.json. * * @return security configuration * @see <a href="https://orientdb.org/docs/3.0.x/security/Security-Config.html">orient securty config</a> */ public JsonNode getSecurity() { return security; } /** * If orient security file (security.json) is not provided with security property in yaml, then it may be * specified as path to security file (but not both!). * Special variables: $TMP for ${java.io.tmpdir}, $FILES_HOME for configured files path and * $APP_HOME for application starting directory. * * @param securityFile path to security file */ @JsonProperty("security-file") public void setSecurityFile(final String securityFile) { Preconditions.checkState(this.security == null, "Orient security already defined in yaml. " + "Use either json file or yaml, but not both."); this.securityFile = parsePath(securityFile); } /** * @return orient security file path */ public String getSecurityFile() { return securityFile; } private OServerConfiguration parseXmlConfigFile(final String configFile) { logger.info("Loading orient configuration from file {}", configFile); final OServerConfigurationLoaderXml configurationLoader = new OServerConfigurationLoaderXml(OServerConfiguration.class, new File(configFile)); try { return configurationLoader.load(); } catch (IOException e) { throw new IllegalStateException("Failed to load configuration from file: " + configFile, e); } } private String parsePath(final String path) { String trimmedPath = Strings.emptyToNull(path); if (trimmedPath != null) { trimmedPath = trimmedPath.replace("$TMP", TMP); if (filesPath != null) { trimmedPath = trimmedPath.replace("$FILES_HOME", filesPath); } trimmedPath = trimmedPath.replace("$APP_HOME", APP_HOME); trimmedPath = OSystemVariableResolver.resolveSystemVariables(trimmedPath); } return trimmedPath; } }
xvik/dropwizard-orient-server
src/main/java/ru/vyarus/dropwizard/orient/configuration/OrientServerConfiguration.java
Java
mit
9,795
new Vue({ el: document.querySelector('.page-app-detail'), data: { selectedApp: {} }, created() { this._loadApp(); }, methods: { refreshSecret() { axios.post(`${AppConf.apiHost}/app/${serverData.appId}/refresh_secret`) .then(res => { this.selectedApp.AppSecret = res.data; }); }, _loadApp() { axios.get(`${AppConf.apiHost}/app/${serverData.appId}`) .then(res => { this.selectedApp = res.data; }); } } });
hstarorg/simple-sso
src/assets/js/app-detail.js
JavaScript
mit
506
// This is an open source non-commercial project. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com /* SearchContext.cs -- * Ars Magna project, http://arsmagna.ru * ------------------------------------------------------- * Status: poor */ #region Using directives using AM; using JetBrains.Annotations; using ManagedIrbis.Client; #endregion namespace ManagedIrbis.Search { /// <summary> /// /// </summary> [PublicAPI] public sealed class SearchContext { #region Properties /// <summary> /// Search manager. /// </summary> [NotNull] public SearchManager Manager { get; private set; } /// <summary> /// Providr. /// </summary> [NotNull] public IrbisProvider Provider { get; private set; } #endregion #region Construction /// <summary> /// Constructor. /// </summary> public SearchContext ( [NotNull] SearchManager manager, [NotNull] IrbisProvider provider ) { Sure.NotNull(manager, nameof(manager)); Sure.NotNull(provider, nameof(provider)); Manager = manager; Provider = provider; } #endregion } }
amironov73/ManagedIrbis2
OldSource/Libs/ManagedIrbis/Source/Search/Infrastructure/SearchContext.cs
C#
mit
1,370
import DetailsList from '@components/details-list.vue' describe('DetailsList Component', () => { let wrapper let options beforeEach(() => { options = { propsData: { id: '01-01', }, } wrapper = createWrapper(DetailsList, options) }) it('is a Vue instance', () => { expect(wrapper.exists()).toBeTruthy() }) it('renders correctly', () => { expect(wrapper).toMatchSnapshot() }) it('does not render correctly', () => { const wrapper = createWrapper( DetailsList, { ...options, }, { getters: { getArtworkById: () => () => { return null }, }, } ) expect(wrapper).toMatchSnapshot() }) })
patrickcate/dutch-art-daily
__tests__/unit/components/details-list.spec.js
JavaScript
mit
745
using System.Collections.Generic; using System.Linq; using PivotalTrackerDotNet.Domain; using RestSharp; using Parallel = System.Threading.Tasks.Parallel; namespace PivotalTrackerDotNet { public class StoryService : AAuthenticatedService, IStoryService { private const string SpecifiedIterationEndpoint = "projects/{0}/iterations?scope={1}"; private const string SingleStoryEndpoint = "projects/{0}/stories/{1}"; private const string StoriesEndpoint = "projects/{0}/stories"; private const string TaskEndpoint = "projects/{0}/stories/{1}/tasks"; private const string StoryActivityEndpoint = "projects/{0}/stories/{1}/activity"; private const string StoryCommentsEndpoint = "projects/{0}/stories/{1}/comments"; private const string SaveNewCommentEndpoint = "projects/{0}/stories/{1}/comments?text={2}"; private const string SingleTaskEndpoint = "projects/{0}/stories/{1}/tasks/{2}"; private const string StoryStateEndpoint = "projects/{0}/stories/{1}?story[current_state]={2}"; private const string StoryFilterEndpoint = StoriesEndpoint + "?filter={1}"; private const string IterationEndPoint = "projects/{0}/iterations"; private const string IterationRecentEndPoint = IterationEndPoint + "/done?offset=-{1}"; public StoryService(string token) : base(token) { } public StoryService(AuthenticationToken token) : base(token) { } public List<Story> GetAllStories(int projectId) { var request = BuildGetRequest(); request.Resource = string.Format(StoriesEndpoint, projectId); return this.GetStories(request); } public List<Story> GetAllStories(int projectId, StoryIncludeFields fields) { var request = BuildGetRequest(); request.Resource = string.Format(StoriesEndpoint, projectId); string fieldsQuery = ":default"; var fieldsToInclude = this.GetFieldsNames(fields); if (fieldsToInclude.Any()) fieldsQuery += "," + string.Join(",", fieldsToInclude); request.AddQueryParameter("fields", fieldsQuery); return this.GetStories(request); } public PagedResult<Story> GetAllStories(int projectId, int limit, int offset) { var request = this.BuildGetRequest(string.Format(StoriesEndpoint, projectId)) .SetPagination(offset, limit); return this.RestClient.ExecuteRequestWithChecks<PagedResult<Story>>(request); } public List<Story> GetAllStoriesMatchingFilter(int projectId, string filter) { var request = BuildGetRequest(); request.Resource = string.Format(StoryFilterEndpoint, projectId, filter); return this.GetStories(request); } public List<Story> GetAllStoriesMatchingFilter(int projectId, string filter, StoryIncludeFields fields) { var request = BuildGetRequest(); request.Resource = string.Format(StoryFilterEndpoint, projectId, filter); string fieldsQuery = ":default"; var fieldsToInclude = this.GetFieldsNames(fields); if (fieldsToInclude.Any()) fieldsQuery += "," + string.Join(",", fieldsToInclude); request.AddQueryParameter("fields", fieldsQuery); return this.GetStories(request); } public PagedResult<Story> GetAllStoriesMatchingFilter(int projectId, string filter, int limit, int offset) { var request = this.BuildGetRequest(string.Format(StoryFilterEndpoint, projectId, filter)) .SetPagination(offset, limit); return this.RestClient.ExecuteRequestWithChecks<PagedResult<Story>>(request); } public PagedResult<Story> GetAllStoriesMatchingFilter(int projectId, FilteringCriteria filter, int limit, int offset) { return this.GetAllStoriesMatchingFilter(projectId, filter.ToString(), limit, offset); } public List<Story> GetAllStoriesMatchingFilter(int projectId, FilteringCriteria filter) { return this.GetAllStoriesMatchingFilter(projectId, filter.ToString()); } public List<Story> GetAllStoriesMatchingFilter(int projectId, FilteringCriteria filter, StoryIncludeFields fields) { return this.GetAllStoriesMatchingFilter(projectId, filter.ToString(), fields); } public Story FinishStory(int projectId, int storyId) { var originalStory = this.GetStory(projectId, storyId); string finished = originalStory.StoryType == StoryType.Chore ? "accepted" : "finished"; var request = BuildPutRequest(); request.Resource = string.Format(StoryStateEndpoint, projectId, storyId, finished); var response = RestClient.Execute<Story>(request); var story = response.Data; return story; } public Story StartStory(int projectId, int storyId) { var request = BuildPutRequest(); request.Resource = string.Format(StoryStateEndpoint, projectId, storyId, "started"); var response = RestClient.Execute<Story>(request); var story = response.Data; return story; } public Story GetStory(int projectId, int storyId) { var request = BuildGetRequest(string.Format(SingleStoryEndpoint, projectId, storyId)); return RestClient.ExecuteRequestWithChecks<Story>(request); } public Story GetStory(int projectId, int storyId, StoryIncludeFields fields) { var request = BuildGetRequest(string.Format(SingleStoryEndpoint, projectId, storyId)); string fieldsQuery = ":default"; var fieldsToInclude = this.GetFieldsNames(fields); if (fieldsToInclude.Any()) fieldsQuery += "," + string.Join(",", fieldsToInclude); request.AddQueryParameter("fields", fieldsQuery); return RestClient.ExecuteRequestWithChecks<Story>(request); } public List<Iteration> GetAllIterations(int projectId) { var request = BuildGetRequest(); request.Resource = string.Format(IterationEndPoint, projectId); return this.GetIterations(request); } public List<Iteration> GetAllIterations(int projectId, StoryIncludeFields fields) { var request = BuildGetRequest(); request.Resource = string.Format(IterationEndPoint, projectId); string fieldsQuery = ":default"; var fieldsToInclude = this.GetFieldsNames(fields); if (fieldsToInclude.Any()) fieldsQuery += "," + string.Join(",", fieldsToInclude); request.AddQueryParameter("fields", ":default,stories(" + fieldsQuery + ")"); return this.GetIterations(request); } public PagedResult<Iteration> GetAllIterations(int projectId, int limit, int offset) { var request = this.BuildGetRequest(string.Format(IterationEndPoint, projectId)) .SetPagination(offset, limit); return this.RestClient.ExecuteRequestWithChecks<PagedResult<Iteration>>(request); } public List<Iteration> GetLastIterations(long projectId, int number) { var request = BuildGetRequest(); request.Resource = string.Format(IterationRecentEndPoint, projectId, number); return this.GetIterations(request); } public List<Iteration> GetCurrentIterations(int projectId) { return this.GetIterationsByType(projectId, "current"); } public List<Iteration> GetDoneIterations(int projectId) { return this.GetIterationsByType(projectId, "done"); } public List<Iteration> GetBacklogIterations(int projectId) { return this.GetIterationsByType(projectId, "backlog"); } public List<Story> GetCurrentStories(int projectId) { return this.GetStoriesByIterationType(projectId, "current"); } public List<Story> GetDoneStories(int projectId) { return this.GetStoriesByIterationType(projectId, "done"); } public List<Story> GetIceboxStories(int projectId) { return this.GetAllStoriesMatchingFilter(projectId, FilteringCriteria.FilterBy.State(StoryStatus.Unscheduled)); } public List<Story> GetBacklogStories(int projectId) { return this.GetStoriesByIterationType(projectId, "backlog"); } public void RemoveStory(int projectId, int storyId) { var request = BuildDeleteRequest(); request.Resource = string.Format(SingleStoryEndpoint, projectId, storyId); RestClient.ExecuteRequestWithChecks(request); } public Story AddNewStory(int projectId, Story toBeSaved) { var request = BuildPostRequest(); request.Resource = string.Format(StoriesEndpoint, projectId); request.AddParameter("application/json", toBeSaved.ToJson(), ParameterType.RequestBody); return RestClient.ExecuteRequestWithChecks<Story>(request); } public Story UpdateStory(int projectId, Story story) { var request = BuildPutRequest(); request.Resource = string.Format(SingleStoryEndpoint, projectId, story.Id); request.AddParameter("application/json", story.ToJson(), ParameterType.RequestBody); return RestClient.ExecuteRequestWithChecks<Story>(request); } public Task SaveTask(Task task) { var request = BuildPutRequest(); request.Resource = string.Format(SingleTaskEndpoint, task.ProjectId, task.StoryId, task.Id); request.AddParameter("application/json", task.ToJson(), ParameterType.RequestBody); var savedTask = RestClient.ExecuteRequestWithChecks<Task>(request); savedTask.ProjectId = task.ProjectId; return savedTask; } public void ReorderTasks(int projectId, int storyId, List<Task> tasks) { Parallel.ForEach(tasks, t => { var request = BuildPutRequest(); request.Resource = string.Format(TaskEndpoint + "/{2}?task[position]={3}", t.ProjectId, t.StoryId, t.Id, t.Position); RestClient.ExecuteRequestWithChecks(request); }); } public Task AddNewTask(Task task) { var request = BuildPostRequest(); request.Resource = string.Format(TaskEndpoint, task.ProjectId, task.StoryId); request.AddParameter("application/json", task.ToJson(), ParameterType.RequestBody); var savedTask = RestClient.ExecuteRequestWithChecks<Task>(request); savedTask.ProjectId = task.ProjectId; return savedTask; } public bool RemoveTask(int projectId, int storyId, int taskId) { var request = BuildDeleteRequest(); request.Resource = string.Format(SingleTaskEndpoint, projectId, storyId, taskId); var response = RestClient.ExecuteRequestWithChecks<Task>(request); return response == null; } public Task GetTask(int projectId, int storyId, int taskId) { var request = BuildGetRequest(); request.Resource = string.Format(SingleTaskEndpoint, projectId, storyId, taskId); var output = RestClient.ExecuteRequestWithChecks<Task>(request); output.StoryId = storyId; output.ProjectId = projectId; return output; } public List<Task> GetTasksForStory(int projectId, int storyId) { var request = this.BuildGetRequest(); request.Resource = string.Format(TaskEndpoint, projectId, storyId); return RestClient.ExecuteRequestWithChecks<List<Task>>(request); } public List<Task> GetTasksForStory(int projectId, Story story) { return this.GetTasksForStory(projectId, story.Id); } public void AddComment(int projectId, int storyId, string comment) { var request = BuildPostRequest(); request.Resource = string.Format(SaveNewCommentEndpoint, projectId, storyId, comment); RestClient.ExecuteRequestWithChecks(request); } public List<Activity> GetStoryActivity(int projectId, int storyId) { var request = this.BuildGetRequest(string.Format(StoryActivityEndpoint, projectId, storyId)); return RestClient.ExecuteRequestWithChecks<List<Activity>>(request); } public PagedResult<Activity> GetStoryActivity(int projectId, int storyId, int offset, int limit) { var request = this.BuildGetRequest(string.Format(StoryActivityEndpoint, projectId, storyId)) .SetPagination(offset, limit); return RestClient.ExecuteRequestWithChecks<PagedResult<Activity>>(request); } public List<Comment> GetStoryComments(int projectId, int storyId) { var request = this.BuildGetRequest(string.Format(StoryCommentsEndpoint, projectId, storyId)); return RestClient.ExecuteRequestWithChecks<List<Comment>>(request); } private List<Iteration> GetIterationsByType(int projectId, string iterationType) { var request = BuildGetRequest(); request.Resource = string.Format(SpecifiedIterationEndpoint, projectId, iterationType); return this.GetIterations(request); } private List<Story> GetStoriesByIterationType(int projectId, string iterationType) { var request = BuildGetRequest(); request.Resource = string.Format(SpecifiedIterationEndpoint, projectId, iterationType); var el = RestClient.ExecuteRequestWithChecks(request); var stories = new Stories(); stories.AddRange(el[0]["stories"].Select(storey => storey.ToObject<Story>())); return stories; } private List<Iteration> GetIterations(RestRequest request) { return RestClient.ExecuteRequestWithChecks<List<Iteration>>(request); } private List<Story> GetStories(RestRequest request) { return RestClient.ExecuteRequestWithChecks<List<Story>>(request); //var el = RestClient.ExecuteRequestWithChecks<List<Story>>(request); //var stories = new Stories(); //stories.AddRange(el.Select(storey => storey.ToObject<Story>())); //return stories; } private IEnumerable<string> GetFieldsNames(StoryIncludeFields fields) { if (fields.HasFlag(StoryIncludeFields.AfterId)) yield return "after_id"; if (fields.HasFlag(StoryIncludeFields.BeforeId)) yield return "before_id"; if (fields.HasFlag(StoryIncludeFields.Comments)) { yield return "comments(:default,person,file_attachments,google_attachments)"; } else if (fields.HasFlag(StoryIncludeFields.CommentIds)) yield return "comment_ids"; if (fields.HasFlag(StoryIncludeFields.Followers)) yield return "followers"; else if (fields.HasFlag(StoryIncludeFields.FollowerIds)) yield return "follower_ids"; if (fields.HasFlag(StoryIncludeFields.Tasks)) yield return "tasks"; else if (fields.HasFlag(StoryIncludeFields.TaskIds)) yield return "task_ids"; if (fields.HasFlag(StoryIncludeFields.Owners)) yield return "owners"; else if (fields.HasFlag(StoryIncludeFields.OwnerIds)) yield return "owner_ids"; if (fields.HasFlag(StoryIncludeFields.RequestedBy)) yield return "requested_by"; } } }
Charcoals/PivotalTracker.NET
PivotalTrackerDotNet/StoryService.cs
C#
mit
17,068
using System; using System.Globalization; using System.Reflection; using System.Windows.Media; namespace DataServer { public static class ColorReflector { public static void SetFromHex(this Color c, string hex) { var c1 = ToColorFromHex(hex); c.A = c1.A; c.R = c1.R; c.G = c1.G; c.B = c1.B; } public static Color GetThisColor(string colorString) { var colorType = (typeof (Colors)); if (colorType.GetProperty(colorString) != null) { var o = colorType.InvokeMember(colorString, BindingFlags.GetProperty, null, null, null); if (o != null) { return (Color) o; } } return Colors.Black; } public static Color? ToColorFromHexWithUndefined(string hex) { return string.IsNullOrEmpty(hex) ? (Color? )null : ToColorFromHex(hex); } public static Color ToColorFromHex(string hex) { if (string.IsNullOrEmpty(hex)) { return Colors.Transparent; } // remove any "#" characters while (hex.StartsWith("#")) { hex = hex.Substring(1); } var num = 0; // get the number out of the string if (!Int32.TryParse(hex, NumberStyles.HexNumber, null, out num)) { return GetThisColor(hex); } var pieces = new int[4]; if (hex.Length > 7) { pieces[0] = ((num >> 24) & 0x000000ff); pieces[1] = ((num >> 16) & 0x000000ff); pieces[2] = ((num >> 8) & 0x000000ff); pieces[3] = (num & 0x000000ff); } else if (hex.Length > 5) { pieces[0] = 255; pieces[1] = ((num >> 16) & 0x000000ff); pieces[2] = ((num >> 8) & 0x000000ff); pieces[3] = (num & 0x000000ff); } else if (hex.Length == 3) { pieces[0] = 255; pieces[1] = ((num >> 8) & 0x0000000f); pieces[1] += pieces[1]*16; pieces[2] = ((num >> 4) & 0x000000f); pieces[2] += pieces[2]*16; pieces[3] = (num & 0x000000f); pieces[3] += pieces[3]*16; } return Color.FromArgb((byte) pieces[0], (byte) pieces[1], (byte) pieces[2], (byte) pieces[3]); } } }
TNOCS/csTouch
framework/csCommonSense/Types/DataServer/PoI/ColorReflector.cs
C#
mit
2,540
require 'ox' module UPS module Builders # The {InternationalProductInvoiceBuilder} class builds UPS XML International invoice Produt Objects. # # @author Calvin Hughes # @since 0.9.3 # @attr [String] name The Containing XML Element Name # @attr [Hash] opts The international invoice product parts class InternationalInvoiceProductBuilder < BuilderBase include Ox attr_accessor :name, :opts def initialize(name, opts = {}) self.name = name self.opts = opts end def description element_with_value('Description', opts[:description]) end def number element_with_value('Number', opts[:number]) end def value element_with_value('Value', opts[:value]) end def dimensions_unit unit_of_measurement(opts[:dimensions_unit]) end def part_number element_with_value('PartNumber', opts[:part_number][0..9]) end def commodity_code element_with_value('CommodityCode', opts[:commodity_code]) end def origin_country_code element_with_value('OriginCountryCode', opts[:origin_country_code][0..2]) end def product_unit Element.new('Unit').tap do |unit| unit << number unit << value unit << dimensions_unit end end # Returns an XML representation of the current object # # @return [Ox::Element] XML representation of the current object def to_xml Element.new(name).tap do |product| product << description product << commodity_code if opts[:commodity_code] product << part_number if opts[:part_number] product << origin_country_code product << product_unit end end end end end
veeqo/ups-ruby
lib/ups/builders/international_invoice_product_builder.rb
Ruby
mit
1,835
require "octaccord/version" require "octaccord/errors" require "octaccord/command" require "octaccord/formatter" require "octaccord/iteration" require "extensions" module Octaccord # Your code goes here... end
nomlab/octaccord
lib/octaccord.rb
Ruby
mit
213
# Rushy Panchal """ See https://bittrex.com/Home/Api """ import urllib import time import requests import hmac import hashlib BUY_ORDERBOOK = 'buy' SELL_ORDERBOOK = 'sell' BOTH_ORDERBOOK = 'both' PUBLIC_SET = ['getmarkets', 'getcurrencies', 'getticker', 'getmarketsummaries', 'getorderbook', 'getmarkethistory'] MARKET_SET = ['getopenorders', 'cancel', 'sellmarket', 'selllimit', 'buymarket', 'buylimit'] ACCOUNT_SET = ['getbalances', 'getbalance', 'getdepositaddress', 'withdraw', 'getorder', 'getorderhistory', 'getwithdrawalhistory', 'getdeposithistory'] class Bittrex(object): """ Used for requesting Bittrex with API key and API secret """ def __init__(self, api_key, api_secret): self.api_key = str(api_key) if api_key is not None else '' self.api_secret = str(api_secret) if api_secret is not None else '' self.public_set = set(PUBLIC_SET) self.market_set = set(MARKET_SET) self.account_set = set(ACCOUNT_SET) def api_query(self, method, options=None): """ Queries Bittrex with given method and options :param method: Query method for getting info :type method: str :param options: Extra options for query :type options: dict :return: JSON response from Bittrex :rtype : dict """ if not options: options = {} nonce = str(int(time.time() * 1000)) base_url = 'https://bittrex.com/api/v1.1/%s/' request_url = '' if method in self.public_set: request_url = (base_url % 'public') + method + '?' elif method in self.market_set: request_url = (base_url % 'market') + method + '?apikey=' + self.api_key + "&nonce=" + nonce + '&' elif method in self.account_set: request_url = (base_url % 'account') + method + '?apikey=' + self.api_key + "&nonce=" + nonce + '&' request_url += urllib.urlencode(options) signature = hmac.new(self.api_secret, request_url, hashlib.sha512).hexdigest() headers = {"apisign": signature} ret = requests.get(request_url, headers=headers) return ret.json() def get_markets(self): """ Used to get the open and available trading markets at Bittrex along with other meta data. :return: Available market info in JSON :rtype : dict """ return self.api_query('getmarkets') def get_currencies(self): """ Used to get all supported currencies at Bittrex along with other meta data. :return: Supported currencies info in JSON :rtype : dict """ return self.api_query('getcurrencies') def get_ticker(self, market): """ Used to get the current tick values for a market. :param market: String literal for the market (ex: BTC-LTC) :type market: str :return: Current values for given market in JSON :rtype : dict """ return self.api_query('getticker', {'market': market}) def get_market_summaries(self): """ Used to get the last 24 hour summary of all active exchanges :return: Summaries of active exchanges in JSON :rtype : dict """ return self.api_query('getmarketsummaries') def get_orderbook(self, market, depth_type, depth=20): """ Used to get retrieve the orderbook for a given market :param market: String literal for the market (ex: BTC-LTC) :type market: str :param depth_type: buy, sell or both to identify the type of orderbook to return. Use constants BUY_ORDERBOOK, SELL_ORDERBOOK, BOTH_ORDERBOOK :type depth_type: str :param depth: how deep of an order book to retrieve. Max is 100, default is 20 :type depth: int :return: Orderbook of market in JSON :rtype : dict """ return self.api_query('getorderbook', {'market': market, 'type': depth_type, 'depth': depth}) def get_market_history(self, market, count): """ Used to retrieve the latest trades that have occured for a specific market. /market/getmarkethistory :param market: String literal for the market (ex: BTC-LTC) :type market: str :param count: Number between 1-100 for the number of entries to return (default = 20) :type count: int :return: Market history in JSON :rtype : dict """ return self.api_query('getmarkethistory', {'market': market, 'count': count}) def buy_market(self, market, quantity, rate): """ Used to place a buy order in a specific market. Use buymarket to place market orders. Make sure you have the proper permissions set on your API keys for this call to work /market/buymarket :param market: String literal for the market (ex: BTC-LTC) :type market: str :param quantity: The amount to purchase :type quantity: float :param rate: The rate at which to place the order. This is not needed for market orders :type rate: float :return: :rtype : dict """ return self.api_query('buymarket', {'market': market, 'quantity': quantity, 'rate': rate}) def buy_limit(self, market, quantity, rate): """ Used to place a buy order in a specific market. Use buylimit to place limit orders Make sure you have the proper permissions set on your API keys for this call to work /market/buylimit :param market: String literal for the market (ex: BTC-LTC) :type market: str :param quantity: The amount to purchase :type quantity: float :param rate: The rate at which to place the order. This is not needed for market orders :type rate: float :return: :rtype : dict """ return self.api_query('buylimit', {'market': market, 'quantity': quantity, 'rate': rate}) def sell_market(self, market, quantity, rate): """ Used to place a sell order in a specific market. Use sellmarket to place market orders. Make sure you have the proper permissions set on your API keys for this call to work /market/sellmarket :param market: String literal for the market (ex: BTC-LTC) :type market: str :param quantity: The amount to purchase :type quantity: float :param rate: The rate at which to place the order. This is not needed for market orders :type rate: float :return: :rtype : dict """ return self.api_query('sellmarket', {'market': market, 'quantity': quantity, 'rate': rate}) def sell_limit(self, market, quantity, rate): """ Used to place a sell order in a specific market. Use selllimit to place limit orders Make sure you have the proper permissions set on your API keys for this call to work /market/selllimit :param market: String literal for the market (ex: BTC-LTC) :type market: str :param quantity: The amount to purchase :type quantity: float :param rate: The rate at which to place the order. This is not needed for market orders :type rate: float :return: :rtype : dict """ return self.api_query('selllimit', {'market': market, 'quantity': quantity, 'rate': rate}) def cancel(self, uuid): """ Used to cancel a buy or sell order /market/cancel :param uuid: uuid of buy or sell order :type uuid: str :return: :rtype : dict """ return self.api_query('cancel', {'uuid': uuid}) def get_open_orders(self, market): """ Get all orders that you currently have opened. A specific market can be requested /market/getopenorders :param market: String literal for the market (ie. BTC-LTC) :type market: str :return: Open orders info in JSON :rtype : dict """ return self.api_query('getopenorders', {'market': market}) def get_balances(self): """ Used to retrieve all balances from your account /account/getbalances :return: Balances info in JSON :rtype : dict """ return self.api_query('getbalances', {}) def get_balance(self, currency): """ Used to retrieve the balance from your account for a specific currency /account/getbalance :param currency: String literal for the currency (ex: LTC) :type currency: str :return: Balance info in JSON :rtype : dict """ return self.api_query('getbalance', {'currency': currency}) def get_deposit_address(self, currency): """ Used to generate or retrieve an address for a specific currency /account/getdepositaddress :param currency: String literal for the currency (ie. BTC) :type currency: str :return: Address info in JSON :rtype : dict """ return self.api_query('getdepositaddress', {'currency': currency}) def withdraw(self, currency, quantity, address): """ Used to withdraw funds from your account /account/withdraw :param currency: String literal for the currency (ie. BTC) :type currency: str :param quantity: The quantity of coins to withdraw :type quantity: float :param address: The address where to send the funds. :type address: str :return: :rtype : dict """ return self.api_query('withdraw', {'currency': currency, 'quantity': quantity, 'address': address}) def get_order(self, uuid): """ Used to get an order from your account /account/getorder :param uuid: The order UUID to look for :type uuid: str :return: :rtype : dict """ return self.api_query('getorder', {'uuid': uuid}) def get_order_history(self, market = ""): """ Used to retrieve your order history /account/getorderhistory :param market: Bittrex market identifier (i.e BTC-DOGE) :type market: str :return: :rtype : dict """ return self.api_query('getorderhistory', {"market": market}) def get_withdrawal_history(self, currency = ""): """ Used to retrieve your withdrawal history /account/getwithdrawalhistory :param currency: String literal for the currency (ie. BTC) (defaults to all) :type currency: str :return: :rtype : dict """ return self.api_query('getwithdrawalhistory', {"currency": currency}) def get_deposit_history(self, currency = ""): """ Used to retrieve your deposit history /account/getdeposithistory :param currency: String literal for the currency (ie. BTC) (defaults to all) :type currency: str :return: :rtype : dict """ return self.api_query('getdeposithistory', {"currency": currency})
panchr/python-bittrex
bittrex/bittrex.py
Python
mit
9,819
package co.edu.eafit.solver.lib.systemsolver.iterative; public enum ENorm { One, Infinite, Euclidean }
halzate93/solver
lib/src/co/edu/eafit/solver/lib/systemsolver/iterative/ENorm.java
Java
mit
105
/** * CacheStorage * ============ */ var fs = require('fs'); var dropRequireCache = require('../fs/drop-require-cache'); /** * CacheStorage — хранилище для кэша. * @name CacheStorage * @param {String} filename Имя файла, в котором хранится кэш (в формате JSON). * @constructor */ function CacheStorage(filename) { this._filename = filename; this._data = {}; this._mtime = 0; } CacheStorage.prototype = { /** * Загружает кэш из файла. */ load: function () { if (fs.existsSync(this._filename)) { dropRequireCache(require, this._filename); try { this._data = require(this._filename); } catch (e) { this._data = {}; } this._mtime = fs.statSync(this._filename).mtime.getTime(); } else { this._data = {}; } }, /** * Сохраняет кэш в файл. */ save: function () { fs.writeFileSync(this._filename, 'module.exports = ' + JSON.stringify(this._data) + ';', 'utf8'); this._mtime = fs.statSync(this._filename).mtime.getTime(); }, /** * Возвращает значение по префику и ключу. * @param {String} prefix * @param {String} key * @returns {Object} */ get: function (prefix, key) { return this._data[prefix] && this._data[prefix][key]; }, /** * Устанавливает значение по префиксу и ключу. * @param {String} prefix * @param {String} key * @param {Object} value */ set: function (prefix, key, value) { (this._data[prefix] || (this._data[prefix] = {}))[key] = value; }, /** * Удаляет значение по префиксу и ключу. * @param {String} prefix * @param {String} key */ invalidate: function (prefix, key) { var prefixObj = this._data[prefix]; if (prefixObj) { delete prefixObj[key]; } }, /** * Удаляет все значения по префиксу. * @param {String} prefix */ dropPrefix: function (prefix) { delete this._data[prefix]; }, /** * Очищает кэш. */ drop: function () { this._data = {}; } }; module.exports = CacheStorage;
1999/enb
lib/cache/cache-storage.js
JavaScript
mit
2,450
#include "stdafx.h" #include "FrustumCone.h" using namespace glm; FrustumCone::FrustumCone() { } FrustumCone::~FrustumCone() { } void FrustumCone::update(mat4 rotprojmatrix) { leftBottom = getDir(vec2(-1, -1), rotprojmatrix); rightBottom = getDir(vec2(1, -1), rotprojmatrix); leftTop = getDir(vec2(-1, 1), rotprojmatrix); rightTop = getDir(vec2(1, 1), rotprojmatrix); } vec3 FrustumCone::getDir(vec2 uv, mat4 inv) { vec4 clip = inv * vec4(uv.x, uv.y, 0.1, 1.0); return normalize(vec3(clip.x, clip.y, clip.z) / clip.w); }
achlubek/vengineandroidndk
app/src/main/cpp/FrustumCone.cpp
C++
mit
549
import hexchat import re __module_name__ = 'BanSearch' __module_author__ = 'TingPing' __module_version__ = '2' __module_description__ = 'Search for bans/quiets matching a user' banhook = 0 quiethook = 0 endbanhook = 0 endquiethook = 0 banlist = [] quietlist = [] regexescapes = {'[':r'\[', ']':r'\]', '.':r'\.'} ircreplace = {'{':'[', '}':']', '|':'\\'} # IRC nick substitutions wildcards = {'?':r'.', '*': r'.*'} # translate wildcards to regex def print_result(mask, matchlist, _type): if matchlist: print('\00318{}\017 had \00320{}\017 {} matches:'.format(mask, len(matchlist), _type)) for match in matchlist: print('\t\t\t{}'.format(match)) else: print('No {} matches for \00318{}\017 were found.'.format(_type, mask)) def match_mask(mask, searchmask): if searchmask is None: searchmask = '' # A mask of $a:* can match a user with no account if searchmask == '' and mask != '*': return False # A mask of $a will not match a user with no account elif mask == '' and searchmask != '': return True # These have to be replaced in a very specific order for match, repl in ircreplace.items(): mask = mask.replace(match, repl) searchmask = searchmask.replace(match, repl) for match, repl in regexescapes.items(): mask = mask.replace(match, repl) for match, repl in wildcards.items(): mask = mask.replace(match, repl) if '$' in mask and mask[0] != '$': # $#channel is used to forward users, ignore it mask = mask.split('$')[0] return bool(re.match(mask, searchmask, re.IGNORECASE)) def match_extban(mask, host, account, realname, usermask): try: extban, banmask = mask.split(':') except ValueError: extban = mask banmask = '' if '~' in extban: invert = True else: invert = False # Extbans from http://freenode.net/using_the_network.shtml if ':' in usermask: # Searching for extban userextban, usermask = usermask.split(':') if extban == userextban: ret = match_mask(banmask, usermask) else: return False elif 'a' in extban: ret = match_mask (banmask, account) elif 'r' in extban: ret = match_mask (banmask, realname) elif 'x' in extban: ret = match_mask (banmask, '{}#{}'.format(host, realname)) else: return False if invert: return not ret else: return ret def get_user_info(nick): invalid_chars = ['*', '?', '$', '@', '!'] if any(char in nick for char in invalid_chars): return (None, None, None) # It's a mask not a nick. for user in hexchat.get_list('users'): if user.nick == nick: host = user.nick + '!' + user.host account = user.account realname = user.realname return (host, account, realname) return (nick + '!*@*', None, None) def search_list(list, usermask): matchlist = [] host, account, realname = get_user_info (usermask) for mask in list: # If extban we require userinfo or we are searching for extban if mask[0] == '$' and (host or usermask[0] == '$'): if match_extban (mask, host, account, realname, usermask): matchlist.append(mask) elif mask[0] != '$': if host: # Was given a user if match_mask (mask, host): matchlist.append(mask) else: # Was given a mask or no userinfo found if match_mask (mask, usermask): matchlist.append(mask) return matchlist def banlist_cb(word, word_eol, userdata): global banlist banlist.append(word[4]) return hexchat.EAT_HEXCHAT def endbanlist_cb(word, word_eol, usermask): global banhook global endbanhook global banlist matchlist = [] hexchat.unhook(banhook) banhook = 0 hexchat.unhook(endbanhook) endbanhook = 0 if banlist: matchlist = search_list(banlist, usermask) banlist = [] print_result (usermask, matchlist, 'Ban') return hexchat.EAT_HEXCHAT def quietlist_cb(word, word_eol, userdata): global quietlist quietlist.append(word[5]) return hexchat.EAT_HEXCHAT def endquietlist_cb(word, word_eol, usermask): global quiethook global endquiethook global quietlist matchlist = [] hexchat.unhook(quiethook) quiethook = 0 hexchat.unhook(endquiethook) endquiethook = 0 if quietlist: matchlist = search_list(quietlist, usermask) quietlist = [] print_result (usermask, matchlist, 'Quiet') return hexchat.EAT_HEXCHAT def search_cb(word, word_eol, userdata): global banhook global quiethook global endbanhook global endquiethook if len(word) == 2: hooks = (quiethook, banhook, endquiethook, endbanhook) if not any(hooks): banhook = hexchat.hook_server ('367', banlist_cb) quiethook = hexchat.hook_server ('728', quietlist_cb) endbanhook = hexchat.hook_server ('368', endbanlist_cb, word[1]) endquiethook = hexchat.hook_server ('729', endquietlist_cb, word[1]) hexchat.command('ban') hexchat.command('quiet') else: print('A ban search is already in progress.') else: hexchat.command('help bansearch') return hexchat.EAT_ALL def unload_cb(userdata): print(__module_name__ + ' version ' + __module_version__ + ' unloaded.') hexchat.hook_unload(unload_cb) hexchat.hook_command('bansearch', search_cb, help='BANSEARCH <mask|nick>') hexchat.prnt(__module_name__ + ' version ' + __module_version__ + ' loaded.')
TingPing/plugins
HexChat/bansearch.py
Python
mit
5,101
package pathtree // Items ... type Items map[string]Items // Add recursively adds a slice of strings to an Items map and makes parent // keys as needed. func (i Items) Add(path []string) { if len(path) > 0 { if v, ok := i[path[0]]; ok { v.Add(path[1:]) } else { result := make(Items) result.Add(path[1:]) i[path[0]] = result } } }
marcusolsson/passtray
pathtree/tree.go
GO
mit
353
<?php namespace DiabloDB\Http\Controllers; use Illuminate\Foundation\Bus\DispatchesCommands; use Illuminate\Routing\Controller as BaseController; use Illuminate\Foundation\Validation\ValidatesRequests; abstract class Controller extends BaseController { use DispatchesCommands, ValidatesRequests; }
taskforcedev/DiabloDB
app/Http/Controllers/Controller.php
PHP
mit
305
/** * Module dependencies */ var mongoose = require('mongoose') , Schema = mongoose.Schema; /** * @constructor */ var MongooseStore = function (Session) { this.Session = Session; }; /** * Load data */ // for koa-generic-session MongooseStore.prototype.get = function *(sid, parse) { try { var data = yield this.Session.findOne({ sid: sid }); if (data && data.sid) { if (parse === false) return data.blob; return JSON.parse(data.blob); } else { return null; } } catch (err) { console.error(err.stack); return null; } }; // for koa-session-store MongooseStore.prototype.load = function *(sid) { return yield this.get(sid, false); }; /** * Save data */ MongooseStore.prototype.set = MongooseStore.prototype.save = function *(sid, blob) { try { if (typeof blob === 'object') blob = JSON.stringify(blob); var data = { sid: sid, blob: blob, updatedAt: new Date() }; yield this.Session.findOneAndUpdate({ sid: sid }, data, { upsert: true, safe: true }); } catch (err) { console.error(err.stack); } }; /** * Remove data */ MongooseStore.prototype.destroy = MongooseStore.prototype.remove = function *(sid) { try { yield this.Session.remove({ sid: sid }); } catch (err) { console.error(err.stack); } }; /** * Create a Mongoose store */ exports.create = function (options) { options = options || {}; options.collection = options.collection || 'sessions'; options.connection = options.connection || mongoose; options.expires = options.expires || 60 * 60 * 24 * 14; // 2 weeks options.model = options.model || 'SessionStore'; var SessionSchema = new Schema({ sid: { type: String, index: true }, blob: String, updatedAt: { type: Date, default: new Date(), expires: options.expires } }); var Session = options.connection.model(options.model, SessionSchema, options.collection); return new MongooseStore(Session); };
rfink/koa-session-mongoose
index.js
JavaScript
mit
2,003
module DynamicModel module Type class Date < DynamicModel::Type::Base end end end
rmoliva/dynamic_model
lib/dynamic_model/type/date.rb
Ruby
mit
93
export function mapToCssModules (className, cssModule) { if (!cssModule) return className return className.split(' ').map(c => cssModule[c] || c).join(' ') }
suranartnc/graphql-blogs-app
.core/app/utils/coreui.js
JavaScript
mit
162
const alter = require('../lib/alter.js'); const _ = require('lodash'); const Chainable = require('../lib/classes/chainable'); const argType = require('../handlers/lib/arg_type.js'); module.exports = new Chainable('condition', { args: [ { name: 'inputSeries', types: ['seriesList'] }, { name: 'operator', // <, <=, >, >=, ==, != types: ['string'], help: 'Operator to use for comparison, valid operators are eq (equal), ne (not equal), lt (less than), lte ' + '(less than equal), gt (greater than), gte (greater than equal)' }, { name: 'if', types: ['number', 'seriesList', 'null'], help: 'The value to which the point will be compared. If you pass a seriesList here the first series will be used' }, { name: 'then', types: ['number', 'seriesList', 'null'], help: 'The value the point will be set to if the comparison is true. If you pass a seriesList here the first series will be used' }, { name: 'else', types: ['number', 'seriesList', 'null'], help: 'The value the point will be set to if the comparison is false. If you pass a seriesList here the first series will be used' } ], help: 'Compares each point to a number, or the same point in another series using an operator, then sets its value' + 'to the result if the condition proves true, with an optional else.', aliases: ['if'], fn: function conditionFn(args) { const config = args.byName; return alter(args, function (eachSeries) { const data = _.map(eachSeries.data, function (point, i) { function getNumber(source) { if (argType(source) === 'number') return source; if (argType(source) === 'null') return null; if (argType(source) === 'seriesList') return source.list[0].data[i][1]; throw new Error ('must be a number or a seriesList'); } const ifVal = getNumber(config.if); const thenVal = getNumber(config.then); const elseVal = _.isUndefined(config.else) ? point[1] : getNumber(config.else); const newValue = (function () { switch (config.operator) { case 'lt': return point[1] < ifVal ? thenVal : elseVal; case 'lte': return point[1] <= ifVal ? thenVal : elseVal; case 'gt': return point[1] > ifVal ? thenVal : elseVal; case 'gte': return point[1] >= ifVal ? thenVal : elseVal; case 'eq': return point[1] === ifVal ? thenVal : elseVal; case 'ne': return point[1] !== ifVal ? thenVal : elseVal; default: throw new Error ('Unknown operator'); } }()); return [point[0], newValue]; }); eachSeries.data = data; return eachSeries; }); } });
istresearch/PulseTheme
kibana/src/core_plugins/timelion/server/series_functions/condition.js
JavaScript
mit
2,900
package entity; import javax.persistence.*; @Entity @Table(name = "tag", schema = "streambot", catalog = "") public class TagEntity { @Id @Column(name = "ID", nullable = false) private long id; @ManyToOne @JoinColumn(name = "ServerID", nullable = false) private GuildEntity guild; @Basic @Column(name = "Name", nullable = true, length = -1) private String name; public long getId() { return id; } public void setId(long id) { this.id = id; } public GuildEntity getGuild() { return guild; } public void setGuild(GuildEntity guild) { this.guild = guild; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; TagEntity tagEntity = (TagEntity) o; if (id != tagEntity.id) return false; if (guild != null ? !guild.equals(tagEntity.guild) : tagEntity.guild != null) return false; return name != null ? name.equals(tagEntity.name) : tagEntity.name == null; } @Override public int hashCode() { int result = (int) (id ^ (id >>> 32)); result = 31 * result + (guild != null ? guild.hashCode() : 0); result = 31 * result + (name != null ? name.hashCode() : 0); return result; } }
Gyoo/Discord-Streambot
src/main/java/entity/TagEntity.java
Java
mit
1,494
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Copyright (c) 2014 The FutCoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "init.h" #include "util.h" #include "sync.h" #include "ui_interface.h" #include "base58.h" #include "bitcoinrpc.h" #include "db.h" #undef printf #include <boost/asio.hpp> #include <boost/asio/ip/v6_only.hpp> #include <boost/bind.hpp> #include <boost/filesystem.hpp> #include <boost/foreach.hpp> #include <boost/iostreams/concepts.hpp> #include <boost/iostreams/stream.hpp> #include <boost/algorithm/string.hpp> #include <boost/asio/ssl.hpp> #include <boost/filesystem/fstream.hpp> #include <boost/shared_ptr.hpp> #include <list> #define printf OutputDebugStringF using namespace std; using namespace boost; using namespace boost::asio; using namespace json_spirit; void ThreadRPCServer2(void* parg); static std::string strRPCUserColonPass; const Object emptyobj; void ThreadRPCServer3(void* parg); static inline unsigned short GetDefaultRPCPort() { return GetBoolArg("-testnet", false) ? 12346 : 2346; } Object JSONRPCError(int code, const string& message) { Object error; error.push_back(Pair("code", code)); error.push_back(Pair("message", message)); return error; } void RPCTypeCheck(const Array& params, const list<Value_type>& typesExpected, bool fAllowNull) { unsigned int i = 0; BOOST_FOREACH(Value_type t, typesExpected) { if (params.size() <= i) break; const Value& v = params[i]; if (!((v.type() == t) || (fAllowNull && (v.type() == null_type)))) { string err = strprintf("Expected type %s, got %s", Value_type_name[t], Value_type_name[v.type()]); throw JSONRPCError(RPC_TYPE_ERROR, err); } i++; } } void RPCTypeCheck(const Object& o, const map<string, Value_type>& typesExpected, bool fAllowNull) { BOOST_FOREACH(const PAIRTYPE(string, Value_type)& t, typesExpected) { const Value& v = find_value(o, t.first); if (!fAllowNull && v.type() == null_type) throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Missing %s", t.first.c_str())); if (!((v.type() == t.second) || (fAllowNull && (v.type() == null_type)))) { string err = strprintf("Expected type %s for %s, got %s", Value_type_name[t.second], t.first.c_str(), Value_type_name[v.type()]); throw JSONRPCError(RPC_TYPE_ERROR, err); } } } int64_t AmountFromValue(const Value& value) { double dAmount = value.get_real(); if (dAmount <= 0.0 || dAmount > MAX_MONEY) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount"); int64_t nAmount = roundint64(dAmount * COIN); if (!MoneyRange(nAmount)) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount"); return nAmount; } Value ValueFromAmount(int64_t amount) { return (double)amount / (double)COIN; } std::string HexBits(unsigned int nBits) { union { int32_t nBits; char cBits[4]; } uBits; uBits.nBits = htonl((int32_t)nBits); return HexStr(BEGIN(uBits.cBits), END(uBits.cBits)); } // // Utilities: convert hex-encoded Values // (throws error if not hex). // uint256 ParseHashV(const Value& v, string strName) { string strHex; if (v.type() == str_type) strHex = v.get_str(); if (!IsHex(strHex)) // Note: IsHex("") is false throw JSONRPCError(RPC_INVALID_PARAMETER, strName+" must be hexadecimal string (not '"+strHex+"')"); uint256 result; result.SetHex(strHex); return result; } uint256 ParseHashO(const Object& o, string strKey) { return ParseHashV(find_value(o, strKey), strKey); } vector<unsigned char> ParseHexV(const Value& v, string strName) { string strHex; if (v.type() == str_type) strHex = v.get_str(); if (!IsHex(strHex)) throw JSONRPCError(RPC_INVALID_PARAMETER, strName+" must be hexadecimal string (not '"+strHex+"')"); return ParseHex(strHex); } vector<unsigned char> ParseHexO(const Object& o, string strKey) { return ParseHexV(find_value(o, strKey), strKey); } /// /// Note: This interface may still be subject to change. /// string CRPCTable::help(string strCommand) const { string strRet; set<rpcfn_type> setDone; for (map<string, const CRPCCommand*>::const_iterator mi = mapCommands.begin(); mi != mapCommands.end(); ++mi) { const CRPCCommand *pcmd = mi->second; string strMethod = mi->first; // We already filter duplicates, but these deprecated screw up the sort order if (strMethod.find("label") != string::npos) continue; if (strCommand != "" && strMethod != strCommand) continue; try { Array params; rpcfn_type pfn = pcmd->actor; if (setDone.insert(pfn).second) (*pfn)(params, true); } catch (std::exception& e) { // Help text is returned in an exception string strHelp = string(e.what()); if (strCommand == "") if (strHelp.find('\n') != string::npos) strHelp = strHelp.substr(0, strHelp.find('\n')); strRet += strHelp + "\n"; } } if (strRet == "") strRet = strprintf("help: unknown command: %s\n", strCommand.c_str()); strRet = strRet.substr(0,strRet.size()-1); return strRet; } Value help(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "help [command]\n" "List commands, or get help for a command."); string strCommand; if (params.size() > 0) strCommand = params[0].get_str(); return tableRPC.help(strCommand); } Value stop(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "stop <detach>\n" "<detach> is true or false to detach the database or not for this stop only\n" "Stop FutCoin server (and possibly override the detachdb config value)."); // Shutdown will take long enough that the response should get back if (params.size() > 0) bitdb.SetDetach(params[0].get_bool()); StartShutdown(); return "FutCoin server stopping"; } // // Call Table // static const CRPCCommand vRPCCommands[] = { // name function safemd unlocked // ------------------------ ----------------------- ------ -------- { "help", &help, true, true }, { "stop", &stop, true, true }, { "getbestblockhash", &getbestblockhash, true, false }, { "getblockcount", &getblockcount, true, false }, { "getconnectioncount", &getconnectioncount, true, false }, { "getpeerinfo", &getpeerinfo, true, false }, { "getdifficulty", &getdifficulty, true, false }, { "getinfo", &getinfo, true, false }, { "getsubsidy", &getsubsidy, true, false }, { "getmininginfo", &getmininginfo, true, false }, { "getstakinginfo", &getstakinginfo, true, false }, { "getnewaddress", &getnewaddress, true, false }, { "getnewpubkey", &getnewpubkey, true, false }, { "getaccountaddress", &getaccountaddress, true, false }, { "setaccount", &setaccount, true, false }, { "getaccount", &getaccount, false, false }, { "getaddressesbyaccount", &getaddressesbyaccount, true, false }, { "sendtoaddress", &sendtoaddress, false, false }, { "getreceivedbyaddress", &getreceivedbyaddress, false, false }, { "getreceivedbyaccount", &getreceivedbyaccount, false, false }, { "listreceivedbyaddress", &listreceivedbyaddress, false, false }, { "listreceivedbyaccount", &listreceivedbyaccount, false, false }, { "backupwallet", &backupwallet, true, false }, { "keypoolrefill", &keypoolrefill, true, false }, { "walletpassphrase", &walletpassphrase, true, false }, { "walletpassphrasechange", &walletpassphrasechange, false, false }, { "walletlock", &walletlock, true, false }, { "encryptwallet", &encryptwallet, false, false }, { "validateaddress", &validateaddress, true, false }, { "validatepubkey", &validatepubkey, true, false }, { "getbalance", &getbalance, false, false }, { "move", &movecmd, false, false }, { "sendfrom", &sendfrom, false, false }, { "sendmany", &sendmany, false, false }, { "addmultisigaddress", &addmultisigaddress, false, false }, { "addredeemscript", &addredeemscript, false, false }, { "getrawmempool", &getrawmempool, true, false }, { "getblock", &getblock, false, false }, { "getblockbynumber", &getblockbynumber, false, false }, { "getblockhash", &getblockhash, false, false }, { "gettransaction", &gettransaction, false, false }, { "listtransactions", &listtransactions, false, false }, { "listaddressgroupings", &listaddressgroupings, false, false }, { "signmessage", &signmessage, false, false }, { "verifymessage", &verifymessage, false, false }, { "getwork", &getwork, true, false }, { "getworkex", &getworkex, true, false }, { "listaccounts", &listaccounts, false, false }, { "settxfee", &settxfee, false, false }, { "getblocktemplate", &getblocktemplate, true, false }, { "submitblock", &submitblock, false, false }, { "listsinceblock", &listsinceblock, false, false }, { "dumpprivkey", &dumpprivkey, false, false }, { "dumpwallet", &dumpwallet, true, false }, { "importwallet", &importwallet, false, false }, { "importprivkey", &importprivkey, false, false }, { "listunspent", &listunspent, false, false }, { "getrawtransaction", &getrawtransaction, false, false }, { "createrawtransaction", &createrawtransaction, false, false }, { "decoderawtransaction", &decoderawtransaction, false, false }, { "decodescript", &decodescript, false, false }, { "signrawtransaction", &signrawtransaction, false, false }, { "sendrawtransaction", &sendrawtransaction, false, false }, { "getcheckpoint", &getcheckpoint, true, false }, { "reservebalance", &reservebalance, false, true}, { "checkwallet", &checkwallet, false, true}, { "repairwallet", &repairwallet, false, true}, { "resendtx", &resendtx, false, true}, { "makekeypair", &makekeypair, false, true}, { "sendalert", &sendalert, false, false}, }; CRPCTable::CRPCTable() { unsigned int vcidx; for (vcidx = 0; vcidx < (sizeof(vRPCCommands) / sizeof(vRPCCommands[0])); vcidx++) { const CRPCCommand *pcmd; pcmd = &vRPCCommands[vcidx]; mapCommands[pcmd->name] = pcmd; } } const CRPCCommand *CRPCTable::operator[](string name) const { map<string, const CRPCCommand*>::const_iterator it = mapCommands.find(name); if (it == mapCommands.end()) return NULL; return (*it).second; } // // HTTP protocol // // This ain't Apache. We're just using HTTP header for the length field // and to be compatible with other JSON-RPC implementations. // string HTTPPost(const string& strMsg, const map<string,string>& mapRequestHeaders) { ostringstream s; s << "POST / HTTP/1.1\r\n" << "User-Agent: FutCoin-json-rpc/" << FormatFullVersion() << "\r\n" << "Host: 127.0.0.1\r\n" << "Content-Type: application/json\r\n" << "Content-Length: " << strMsg.size() << "\r\n" << "Connection: close\r\n" << "Accept: application/json\r\n"; BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapRequestHeaders) s << item.first << ": " << item.second << "\r\n"; s << "\r\n" << strMsg; return s.str(); } string rfc1123Time() { char buffer[64]; time_t now; time(&now); struct tm* now_gmt = gmtime(&now); string locale(setlocale(LC_TIME, NULL)); setlocale(LC_TIME, "C"); // we want POSIX (aka "C") weekday/month strings strftime(buffer, sizeof(buffer), "%a, %d %b %Y %H:%M:%S +0000", now_gmt); setlocale(LC_TIME, locale.c_str()); return string(buffer); } static string HTTPReply(int nStatus, const string& strMsg, bool keepalive) { if (nStatus == HTTP_UNAUTHORIZED) return strprintf("HTTP/1.0 401 Authorization Required\r\n" "Date: %s\r\n" "Server: FutCoin-json-rpc/%s\r\n" "WWW-Authenticate: Basic realm=\"jsonrpc\"\r\n" "Content-Type: text/html\r\n" "Content-Length: 296\r\n" "\r\n" "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\r\n" "\"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd\">\r\n" "<HTML>\r\n" "<HEAD>\r\n" "<TITLE>Error</TITLE>\r\n" "<META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=ISO-8859-1'>\r\n" "</HEAD>\r\n" "<BODY><H1>401 Unauthorized.</H1></BODY>\r\n" "</HTML>\r\n", rfc1123Time().c_str(), FormatFullVersion().c_str()); const char *cStatus; if (nStatus == HTTP_OK) cStatus = "OK"; else if (nStatus == HTTP_BAD_REQUEST) cStatus = "Bad Request"; else if (nStatus == HTTP_FORBIDDEN) cStatus = "Forbidden"; else if (nStatus == HTTP_NOT_FOUND) cStatus = "Not Found"; else if (nStatus == HTTP_INTERNAL_SERVER_ERROR) cStatus = "Internal Server Error"; else cStatus = ""; return strprintf( "HTTP/1.1 %d %s\r\n" "Date: %s\r\n" "Connection: %s\r\n" "Content-Length: %"PRIszu"\r\n" "Content-Type: application/json\r\n" "Server: FutCoin-json-rpc/%s\r\n" "\r\n" "%s", nStatus, cStatus, rfc1123Time().c_str(), keepalive ? "keep-alive" : "close", strMsg.size(), FormatFullVersion().c_str(), strMsg.c_str()); } int ReadHTTPStatus(std::basic_istream<char>& stream, int &proto) { string str; getline(stream, str); vector<string> vWords; boost::split(vWords, str, boost::is_any_of(" ")); if (vWords.size() < 2) return HTTP_INTERNAL_SERVER_ERROR; proto = 0; const char *ver = strstr(str.c_str(), "HTTP/1."); if (ver != NULL) proto = atoi(ver+7); return atoi(vWords[1].c_str()); } int ReadHTTPHeader(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet) { int nLen = 0; while (true) { string str; std::getline(stream, str); if (str.empty() || str == "\r") break; string::size_type nColon = str.find(":"); if (nColon != string::npos) { string strHeader = str.substr(0, nColon); boost::trim(strHeader); boost::to_lower(strHeader); string strValue = str.substr(nColon+1); boost::trim(strValue); mapHeadersRet[strHeader] = strValue; if (strHeader == "content-length") nLen = atoi(strValue.c_str()); } } return nLen; } int ReadHTTP(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet, string& strMessageRet) { mapHeadersRet.clear(); strMessageRet = ""; // Read status int nProto = 0; int nStatus = ReadHTTPStatus(stream, nProto); // Read header int nLen = ReadHTTPHeader(stream, mapHeadersRet); if (nLen < 0 || nLen > (int)MAX_SIZE) return HTTP_INTERNAL_SERVER_ERROR; // Read message if (nLen > 0) { vector<char> vch(nLen); stream.read(&vch[0], nLen); strMessageRet = string(vch.begin(), vch.end()); } string sConHdr = mapHeadersRet["connection"]; if ((sConHdr != "close") && (sConHdr != "keep-alive")) { if (nProto >= 1) mapHeadersRet["connection"] = "keep-alive"; else mapHeadersRet["connection"] = "close"; } return nStatus; } bool HTTPAuthorized(map<string, string>& mapHeaders) { string strAuth = mapHeaders["authorization"]; if (strAuth.substr(0,6) != "Basic ") return false; string strUserPass64 = strAuth.substr(6); boost::trim(strUserPass64); string strUserPass = DecodeBase64(strUserPass64); return TimingResistantEqual(strUserPass, strRPCUserColonPass); } // // JSON-RPC protocol. Bitcoin speaks version 1.0 for maximum compatibility, // but uses JSON-RPC 1.1/2.0 standards for parts of the 1.0 standard that were // unspecified (HTTP errors and contents of 'error'). // // 1.0 spec: http://json-rpc.org/wiki/specification // 1.2 spec: http://groups.google.com/group/json-rpc/web/json-rpc-over-http // http://www.codeproject.com/KB/recipes/JSON_Spirit.aspx // string JSONRPCRequest(const string& strMethod, const Array& params, const Value& id) { Object request; request.push_back(Pair("method", strMethod)); request.push_back(Pair("params", params)); request.push_back(Pair("id", id)); return write_string(Value(request), false) + "\n"; } Object JSONRPCReplyObj(const Value& result, const Value& error, const Value& id) { Object reply; if (error.type() != null_type) reply.push_back(Pair("result", Value::null)); else reply.push_back(Pair("result", result)); reply.push_back(Pair("error", error)); reply.push_back(Pair("id", id)); return reply; } string JSONRPCReply(const Value& result, const Value& error, const Value& id) { Object reply = JSONRPCReplyObj(result, error, id); return write_string(Value(reply), false) + "\n"; } void ErrorReply(std::ostream& stream, const Object& objError, const Value& id) { // Send error reply from json-rpc error object int nStatus = HTTP_INTERNAL_SERVER_ERROR; int code = find_value(objError, "code").get_int(); if (code == RPC_INVALID_REQUEST) nStatus = HTTP_BAD_REQUEST; else if (code == RPC_METHOD_NOT_FOUND) nStatus = HTTP_NOT_FOUND; string strReply = JSONRPCReply(Value::null, objError, id); stream << HTTPReply(nStatus, strReply, false) << std::flush; } bool ClientAllowed(const boost::asio::ip::address& address) { // Make sure that IPv4-compatible and IPv4-mapped IPv6 addresses are treated as IPv4 addresses if (address.is_v6() && (address.to_v6().is_v4_compatible() || address.to_v6().is_v4_mapped())) return ClientAllowed(address.to_v6().to_v4()); if (address == asio::ip::address_v4::loopback() || address == asio::ip::address_v6::loopback() || (address.is_v4() // Check whether IPv4 addresses match 127.0.0.0/8 (loopback subnet) && (address.to_v4().to_ulong() & 0xff000000) == 0x7f000000)) return true; const string strAddress = address.to_string(); const vector<string>& vAllow = mapMultiArgs["-rpcallowip"]; BOOST_FOREACH(string strAllow, vAllow) if (WildcardMatch(strAddress, strAllow)) return true; return false; } // // IOStream device that speaks SSL but can also speak non-SSL // template <typename Protocol> class SSLIOStreamDevice : public iostreams::device<iostreams::bidirectional> { public: SSLIOStreamDevice(asio::ssl::stream<typename Protocol::socket> &streamIn, bool fUseSSLIn) : stream(streamIn) { fUseSSL = fUseSSLIn; fNeedHandshake = fUseSSLIn; } void handshake(ssl::stream_base::handshake_type role) { if (!fNeedHandshake) return; fNeedHandshake = false; stream.handshake(role); } std::streamsize read(char* s, std::streamsize n) { handshake(ssl::stream_base::server); // HTTPS servers read first if (fUseSSL) return stream.read_some(asio::buffer(s, n)); return stream.next_layer().read_some(asio::buffer(s, n)); } std::streamsize write(const char* s, std::streamsize n) { handshake(ssl::stream_base::client); // HTTPS clients write first if (fUseSSL) return asio::write(stream, asio::buffer(s, n)); return asio::write(stream.next_layer(), asio::buffer(s, n)); } bool connect(const std::string& server, const std::string& port) { ip::tcp::resolver resolver(stream.get_io_service()); ip::tcp::resolver::query query(server.c_str(), port.c_str()); ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query); ip::tcp::resolver::iterator end; boost::system::error_code error = asio::error::host_not_found; while (error && endpoint_iterator != end) { stream.lowest_layer().close(); stream.lowest_layer().connect(*endpoint_iterator++, error); } if (error) return false; return true; } private: bool fNeedHandshake; bool fUseSSL; asio::ssl::stream<typename Protocol::socket>& stream; }; class AcceptedConnection { public: virtual ~AcceptedConnection() {} virtual std::iostream& stream() = 0; virtual std::string peer_address_to_string() const = 0; virtual void close() = 0; }; template <typename Protocol> class AcceptedConnectionImpl : public AcceptedConnection { public: AcceptedConnectionImpl( asio::io_service& io_service, ssl::context &context, bool fUseSSL) : sslStream(io_service, context), _d(sslStream, fUseSSL), _stream(_d) { } virtual std::iostream& stream() { return _stream; } virtual std::string peer_address_to_string() const { return peer.address().to_string(); } virtual void close() { _stream.close(); } typename Protocol::endpoint peer; asio::ssl::stream<typename Protocol::socket> sslStream; private: SSLIOStreamDevice<Protocol> _d; iostreams::stream< SSLIOStreamDevice<Protocol> > _stream; }; void ThreadRPCServer(void* parg) { // Make this thread recognisable as the RPC listener RenameThread("FutCoin-rpclist"); try { vnThreadsRunning[THREAD_RPCLISTENER]++; ThreadRPCServer2(parg); vnThreadsRunning[THREAD_RPCLISTENER]--; } catch (std::exception& e) { vnThreadsRunning[THREAD_RPCLISTENER]--; PrintException(&e, "ThreadRPCServer()"); } catch (...) { vnThreadsRunning[THREAD_RPCLISTENER]--; PrintException(NULL, "ThreadRPCServer()"); } printf("ThreadRPCServer exited\n"); } // Forward declaration required for RPCListen template <typename Protocol, typename SocketAcceptorService> static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor, ssl::context& context, bool fUseSSL, AcceptedConnection* conn, const boost::system::error_code& error); /** * Sets up I/O resources to accept and handle a new connection. */ template <typename Protocol, typename SocketAcceptorService> static void RPCListen(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor, ssl::context& context, const bool fUseSSL) { // Accept connection AcceptedConnectionImpl<Protocol>* conn = new AcceptedConnectionImpl<Protocol>(acceptor->get_io_service(), context, fUseSSL); acceptor->async_accept( conn->sslStream.lowest_layer(), conn->peer, boost::bind(&RPCAcceptHandler<Protocol, SocketAcceptorService>, acceptor, boost::ref(context), fUseSSL, conn, boost::asio::placeholders::error)); } /** * Accept and handle incoming connection. */ template <typename Protocol, typename SocketAcceptorService> static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor, ssl::context& context, const bool fUseSSL, AcceptedConnection* conn, const boost::system::error_code& error) { vnThreadsRunning[THREAD_RPCLISTENER]++; // Immediately start accepting new connections, except when we're cancelled or our socket is closed. if (error != asio::error::operation_aborted && acceptor->is_open()) RPCListen(acceptor, context, fUseSSL); AcceptedConnectionImpl<ip::tcp>* tcp_conn = dynamic_cast< AcceptedConnectionImpl<ip::tcp>* >(conn); // TODO: Actually handle errors if (error) { delete conn; } // Restrict callers by IP. It is important to // do this before starting client thread, to filter out // certain DoS and misbehaving clients. else if (tcp_conn && !ClientAllowed(tcp_conn->peer.address())) { // Only send a 403 if we're not using SSL to prevent a DoS during the SSL handshake. if (!fUseSSL) conn->stream() << HTTPReply(HTTP_FORBIDDEN, "", false) << std::flush; delete conn; } // start HTTP client thread else if (!NewThread(ThreadRPCServer3, conn)) { printf("Failed to create RPC server client thread\n"); delete conn; } vnThreadsRunning[THREAD_RPCLISTENER]--; } void ThreadRPCServer2(void* parg) { printf("ThreadRPCServer started\n"); strRPCUserColonPass = mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]; if ((mapArgs["-rpcpassword"] == "") || (mapArgs["-rpcuser"] == mapArgs["-rpcpassword"])) { unsigned char rand_pwd[32]; RAND_bytes(rand_pwd, 32); string strWhatAmI = "To use FutCoind"; if (mapArgs.count("-server")) strWhatAmI = strprintf(_("To use the %s option"), "\"-server\""); else if (mapArgs.count("-daemon")) strWhatAmI = strprintf(_("To use the %s option"), "\"-daemon\""); uiInterface.ThreadSafeMessageBox(strprintf( _("%s, you must set a rpcpassword in the configuration file:\n %s\n" "It is recommended you use the following random password:\n" "rpcuser=FutCoinrpc\n" "rpcpassword=%s\n" "(you do not need to remember this password)\n" "The username and password MUST NOT be the same.\n" "If the file does not exist, create it with owner-readable-only file permissions.\n" "It is also recommended to set alertnotify so you are notified of problems;\n" "for example: alertnotify=echo %%s | mail -s \"FutCoin Alert\" admin@foo.com\n"), strWhatAmI.c_str(), GetConfigFile().string().c_str(), EncodeBase58(&rand_pwd[0],&rand_pwd[0]+32).c_str()), _("Error"), CClientUIInterface::OK | CClientUIInterface::MODAL); StartShutdown(); return; } const bool fUseSSL = GetBoolArg("-rpcssl"); asio::io_service io_service; ssl::context context(io_service, ssl::context::sslv23); if (fUseSSL) { context.set_options(ssl::context::no_sslv2); filesystem::path pathCertFile(GetArg("-rpcsslcertificatechainfile", "server.cert")); if (!pathCertFile.is_complete()) pathCertFile = filesystem::path(GetDataDir()) / pathCertFile; if (filesystem::exists(pathCertFile)) context.use_certificate_chain_file(pathCertFile.string()); else printf("ThreadRPCServer ERROR: missing server certificate file %s\n", pathCertFile.string().c_str()); filesystem::path pathPKFile(GetArg("-rpcsslprivatekeyfile", "server.pem")); if (!pathPKFile.is_complete()) pathPKFile = filesystem::path(GetDataDir()) / pathPKFile; if (filesystem::exists(pathPKFile)) context.use_private_key_file(pathPKFile.string(), ssl::context::pem); else printf("ThreadRPCServer ERROR: missing server private key file %s\n", pathPKFile.string().c_str()); string strCiphers = GetArg("-rpcsslciphers", "TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH"); SSL_CTX_set_cipher_list(context.impl(), strCiphers.c_str()); } // Try a dual IPv6/IPv4 socket, falling back to separate IPv4 and IPv6 sockets const bool loopback = !mapArgs.count("-rpcallowip"); asio::ip::address bindAddress = loopback ? asio::ip::address_v6::loopback() : asio::ip::address_v6::any(); ip::tcp::endpoint endpoint(bindAddress, GetArg("-rpcport", GetDefaultRPCPort())); boost::system::error_code v6_only_error; boost::shared_ptr<ip::tcp::acceptor> acceptor(new ip::tcp::acceptor(io_service)); boost::signals2::signal<void ()> StopRequests; bool fListening = false; std::string strerr; try { acceptor->open(endpoint.protocol()); acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true)); // Try making the socket dual IPv6/IPv4 (if listening on the "any" address) acceptor->set_option(boost::asio::ip::v6_only(loopback), v6_only_error); acceptor->bind(endpoint); acceptor->listen(socket_base::max_connections); RPCListen(acceptor, context, fUseSSL); // Cancel outstanding listen-requests for this acceptor when shutting down StopRequests.connect(signals2::slot<void ()>( static_cast<void (ip::tcp::acceptor::*)()>(&ip::tcp::acceptor::close), acceptor.get()) .track(acceptor)); fListening = true; } catch(boost::system::system_error &e) { strerr = strprintf(_("An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s"), endpoint.port(), e.what()); } try { // If dual IPv6/IPv4 failed (or we're opening loopback interfaces only), open IPv4 separately if (!fListening || loopback || v6_only_error) { bindAddress = loopback ? asio::ip::address_v4::loopback() : asio::ip::address_v4::any(); endpoint.address(bindAddress); acceptor.reset(new ip::tcp::acceptor(io_service)); acceptor->open(endpoint.protocol()); acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true)); acceptor->bind(endpoint); acceptor->listen(socket_base::max_connections); RPCListen(acceptor, context, fUseSSL); // Cancel outstanding listen-requests for this acceptor when shutting down StopRequests.connect(signals2::slot<void ()>( static_cast<void (ip::tcp::acceptor::*)()>(&ip::tcp::acceptor::close), acceptor.get()) .track(acceptor)); fListening = true; } } catch(boost::system::system_error &e) { strerr = strprintf(_("An error occurred while setting up the RPC port %u for listening on IPv4: %s"), endpoint.port(), e.what()); } if (!fListening) { uiInterface.ThreadSafeMessageBox(strerr, _("Error"), CClientUIInterface::OK | CClientUIInterface::MODAL); StartShutdown(); return; } vnThreadsRunning[THREAD_RPCLISTENER]--; while (!fShutdown) io_service.run_one(); vnThreadsRunning[THREAD_RPCLISTENER]++; StopRequests(); } class JSONRequest { public: Value id; string strMethod; Array params; JSONRequest() { id = Value::null; } void parse(const Value& valRequest); }; void JSONRequest::parse(const Value& valRequest) { // Parse request if (valRequest.type() != obj_type) throw JSONRPCError(RPC_INVALID_REQUEST, "Invalid Request object"); const Object& request = valRequest.get_obj(); // Parse id now so errors from here on will have the id id = find_value(request, "id"); // Parse method Value valMethod = find_value(request, "method"); if (valMethod.type() == null_type) throw JSONRPCError(RPC_INVALID_REQUEST, "Missing method"); if (valMethod.type() != str_type) throw JSONRPCError(RPC_INVALID_REQUEST, "Method must be a string"); strMethod = valMethod.get_str(); if (strMethod != "getwork" && strMethod != "getblocktemplate") printf("ThreadRPCServer method=%s\n", strMethod.c_str()); // Parse params Value valParams = find_value(request, "params"); if (valParams.type() == array_type) params = valParams.get_array(); else if (valParams.type() == null_type) params = Array(); else throw JSONRPCError(RPC_INVALID_REQUEST, "Params must be an array"); } static Object JSONRPCExecOne(const Value& req) { Object rpc_result; JSONRequest jreq; try { jreq.parse(req); Value result = tableRPC.execute(jreq.strMethod, jreq.params); rpc_result = JSONRPCReplyObj(result, Value::null, jreq.id); } catch (Object& objError) { rpc_result = JSONRPCReplyObj(Value::null, objError, jreq.id); } catch (std::exception& e) { rpc_result = JSONRPCReplyObj(Value::null, JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id); } return rpc_result; } static string JSONRPCExecBatch(const Array& vReq) { Array ret; for (unsigned int reqIdx = 0; reqIdx < vReq.size(); reqIdx++) ret.push_back(JSONRPCExecOne(vReq[reqIdx])); return write_string(Value(ret), false) + "\n"; } static CCriticalSection cs_THREAD_RPCHANDLER; void ThreadRPCServer3(void* parg) { // Make this thread recognisable as the RPC handler RenameThread("FutCoin-rpchand"); { LOCK(cs_THREAD_RPCHANDLER); vnThreadsRunning[THREAD_RPCHANDLER]++; } AcceptedConnection *conn = (AcceptedConnection *) parg; bool fRun = true; while (true) { if (fShutdown || !fRun) { conn->close(); delete conn; { LOCK(cs_THREAD_RPCHANDLER); --vnThreadsRunning[THREAD_RPCHANDLER]; } return; } map<string, string> mapHeaders; string strRequest; ReadHTTP(conn->stream(), mapHeaders, strRequest); // Check authorization if (mapHeaders.count("authorization") == 0) { conn->stream() << HTTPReply(HTTP_UNAUTHORIZED, "", false) << std::flush; break; } if (!HTTPAuthorized(mapHeaders)) { printf("ThreadRPCServer incorrect password attempt from %s\n", conn->peer_address_to_string().c_str()); /* Deter brute-forcing short passwords. If this results in a DOS the user really shouldn't have their RPC port exposed.*/ if (mapArgs["-rpcpassword"].size() < 20) MilliSleep(250); conn->stream() << HTTPReply(HTTP_UNAUTHORIZED, "", false) << std::flush; break; } if (mapHeaders["connection"] == "close") fRun = false; JSONRequest jreq; try { // Parse request Value valRequest; if (!read_string(strRequest, valRequest)) throw JSONRPCError(RPC_PARSE_ERROR, "Parse error"); string strReply; // singleton request if (valRequest.type() == obj_type) { jreq.parse(valRequest); Value result = tableRPC.execute(jreq.strMethod, jreq.params); // Send reply strReply = JSONRPCReply(result, Value::null, jreq.id); // array of requests } else if (valRequest.type() == array_type) strReply = JSONRPCExecBatch(valRequest.get_array()); else throw JSONRPCError(RPC_PARSE_ERROR, "Top-level object parse error"); conn->stream() << HTTPReply(HTTP_OK, strReply, fRun) << std::flush; } catch (Object& objError) { ErrorReply(conn->stream(), objError, jreq.id); break; } catch (std::exception& e) { ErrorReply(conn->stream(), JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id); break; } } delete conn; { LOCK(cs_THREAD_RPCHANDLER); vnThreadsRunning[THREAD_RPCHANDLER]--; } } json_spirit::Value CRPCTable::execute(const std::string &strMethod, const json_spirit::Array &params) const { // Find method const CRPCCommand *pcmd = tableRPC[strMethod]; if (!pcmd) throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found"); // Observe safe mode string strWarning = GetWarnings("rpc"); if (strWarning != "" && !GetBoolArg("-disablesafemode") && !pcmd->okSafeMode) throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, string("Safe mode: ") + strWarning); try { // Execute Value result; { if (pcmd->unlocked) result = pcmd->actor(params, false); else { LOCK2(cs_main, pwalletMain->cs_wallet); result = pcmd->actor(params, false); } } return result; } catch (std::exception& e) { throw JSONRPCError(RPC_MISC_ERROR, e.what()); } } Object CallRPC(const string& strMethod, const Array& params) { if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "") throw runtime_error(strprintf( _("You must set rpcpassword=<password> in the configuration file:\n%s\n" "If the file does not exist, create it with owner-readable-only file permissions."), GetConfigFile().string().c_str())); // Connect to localhost bool fUseSSL = GetBoolArg("-rpcssl"); asio::io_service io_service; ssl::context context(io_service, ssl::context::sslv23); context.set_options(ssl::context::no_sslv2); asio::ssl::stream<asio::ip::tcp::socket> sslStream(io_service, context); SSLIOStreamDevice<asio::ip::tcp> d(sslStream, fUseSSL); iostreams::stream< SSLIOStreamDevice<asio::ip::tcp> > stream(d); if (!d.connect(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", itostr(GetDefaultRPCPort())))) throw runtime_error("couldn't connect to server"); // HTTP basic authentication string strUserPass64 = EncodeBase64(mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]); map<string, string> mapRequestHeaders; mapRequestHeaders["Authorization"] = string("Basic ") + strUserPass64; // Send request string strRequest = JSONRPCRequest(strMethod, params, 1); string strPost = HTTPPost(strRequest, mapRequestHeaders); stream << strPost << std::flush; // Receive reply map<string, string> mapHeaders; string strReply; int nStatus = ReadHTTP(stream, mapHeaders, strReply); if (nStatus == HTTP_UNAUTHORIZED) throw runtime_error("incorrect rpcuser or rpcpassword (authorization failed)"); else if (nStatus >= 400 && nStatus != HTTP_BAD_REQUEST && nStatus != HTTP_NOT_FOUND && nStatus != HTTP_INTERNAL_SERVER_ERROR) throw runtime_error(strprintf("server returned HTTP error %d", nStatus)); else if (strReply.empty()) throw runtime_error("no response from server"); // Parse reply Value valReply; if (!read_string(strReply, valReply)) throw runtime_error("couldn't parse reply from server"); const Object& reply = valReply.get_obj(); if (reply.empty()) throw runtime_error("expected reply to have result, error and id properties"); return reply; } template<typename T> void ConvertTo(Value& value, bool fAllowNull=false) { if (fAllowNull && value.type() == null_type) return; if (value.type() == str_type) { // reinterpret string as unquoted json value Value value2; string strJSON = value.get_str(); if (!read_string(strJSON, value2)) throw runtime_error(string("Error parsing JSON:")+strJSON); ConvertTo<T>(value2, fAllowNull); value = value2; } else { value = value.get_value<T>(); } } // Convert strings to command-specific RPC representation Array RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams) { Array params; BOOST_FOREACH(const std::string &param, strParams) params.push_back(param); int n = params.size(); // // Special case non-string parameter types // if (strMethod == "stop" && n > 0) ConvertTo<bool>(params[0]); if (strMethod == "sendtoaddress" && n > 1) ConvertTo<double>(params[1]); if (strMethod == "settxfee" && n > 0) ConvertTo<double>(params[0]); if (strMethod == "getreceivedbyaddress" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "getreceivedbyaccount" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "listreceivedbyaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "listreceivedbyaddress" && n > 1) ConvertTo<bool>(params[1]); if (strMethod == "listreceivedbyaccount" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "listreceivedbyaccount" && n > 1) ConvertTo<bool>(params[1]); if (strMethod == "getbalance" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "getblock" && n > 1) ConvertTo<bool>(params[1]); if (strMethod == "getblockbynumber" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "getblockbynumber" && n > 1) ConvertTo<bool>(params[1]); if (strMethod == "getblockhash" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "move" && n > 2) ConvertTo<double>(params[2]); if (strMethod == "move" && n > 3) ConvertTo<boost::int64_t>(params[3]); if (strMethod == "sendfrom" && n > 2) ConvertTo<double>(params[2]); if (strMethod == "sendfrom" && n > 3) ConvertTo<boost::int64_t>(params[3]); if (strMethod == "listtransactions" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "listtransactions" && n > 2) ConvertTo<boost::int64_t>(params[2]); if (strMethod == "listaccounts" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "walletpassphrase" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "walletpassphrase" && n > 2) ConvertTo<bool>(params[2]); if (strMethod == "getblocktemplate" && n > 0) ConvertTo<Object>(params[0]); if (strMethod == "listsinceblock" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "sendalert" && n > 2) ConvertTo<boost::int64_t>(params[2]); if (strMethod == "sendalert" && n > 3) ConvertTo<boost::int64_t>(params[3]); if (strMethod == "sendalert" && n > 4) ConvertTo<boost::int64_t>(params[4]); if (strMethod == "sendalert" && n > 5) ConvertTo<boost::int64_t>(params[5]); if (strMethod == "sendalert" && n > 6) ConvertTo<boost::int64_t>(params[6]); if (strMethod == "sendmany" && n > 1) ConvertTo<Object>(params[1]); if (strMethod == "sendmany" && n > 2) ConvertTo<boost::int64_t>(params[2]); if (strMethod == "reservebalance" && n > 0) ConvertTo<bool>(params[0]); if (strMethod == "reservebalance" && n > 1) ConvertTo<double>(params[1]); if (strMethod == "addmultisigaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "addmultisigaddress" && n > 1) ConvertTo<Array>(params[1]); if (strMethod == "listunspent" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "listunspent" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "listunspent" && n > 2) ConvertTo<Array>(params[2]); if (strMethod == "getrawtransaction" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "createrawtransaction" && n > 0) ConvertTo<Array>(params[0]); if (strMethod == "createrawtransaction" && n > 1) ConvertTo<Object>(params[1]); if (strMethod == "signrawtransaction" && n > 1) ConvertTo<Array>(params[1], true); if (strMethod == "signrawtransaction" && n > 2) ConvertTo<Array>(params[2], true); if (strMethod == "keypoolrefill" && n > 0) ConvertTo<boost::int64_t>(params[0]); return params; } int CommandLineRPC(int argc, char *argv[]) { string strPrint; int nRet = 0; try { // Skip switches while (argc > 1 && IsSwitchChar(argv[1][0])) { argc--; argv++; } // Method if (argc < 2) throw runtime_error("too few parameters"); string strMethod = argv[1]; // Parameters default to strings std::vector<std::string> strParams(&argv[2], &argv[argc]); Array params = RPCConvertValues(strMethod, strParams); // Execute Object reply = CallRPC(strMethod, params); // Parse reply const Value& result = find_value(reply, "result"); const Value& error = find_value(reply, "error"); if (error.type() != null_type) { // Error strPrint = "error: " + write_string(error, false); int code = find_value(error.get_obj(), "code").get_int(); nRet = abs(code); } else { // Result if (result.type() == null_type) strPrint = ""; else if (result.type() == str_type) strPrint = result.get_str(); else strPrint = write_string(result, true); } } catch (std::exception& e) { strPrint = string("error: ") + e.what(); nRet = 87; } catch (...) { PrintException(NULL, "CommandLineRPC()"); } if (strPrint != "") { fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str()); } return nRet; } #ifdef TEST int main(int argc, char *argv[]) { #ifdef _MSC_VER // Turn off Microsoft heap dump noise _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_WARN, CreateFile("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0)); #endif setbuf(stdin, NULL); setbuf(stdout, NULL); setbuf(stderr, NULL); try { if (argc >= 2 && string(argv[1]) == "-server") { printf("server ready\n"); ThreadRPCServer(NULL); } else { return CommandLineRPC(argc, argv); } } catch (std::exception& e) { PrintException(&e, "main()"); } catch (...) { PrintException(NULL, "main()"); } return 0; } #endif const CRPCTable tableRPC;
Futcoin/Futcoin
src/bitcoinrpc.cpp
C++
mit
48,271
interface CalculatePositionOptions { horizontalPosition: string; verticalPosition: string; matchTriggerWidth: boolean; previousHorizontalPosition?: string; previousVerticalPosition?: string; renderInPlace: boolean; dropdown: any; } export type CalculatePositionResultStyle = { top?: number; left?: number; right?: number; width?: number; height?: number; [key: string]: string | number | undefined; }; export type CalculatePositionResult = { horizontalPosition: string; verticalPosition: string; style: CalculatePositionResultStyle; }; export type CalculatePosition = ( trigger: Element, content: HTMLElement, destination: HTMLElement, options: CalculatePositionOptions ) => CalculatePositionResult; export let calculateWormholedPosition: CalculatePosition = ( trigger, content, destination, { horizontalPosition, verticalPosition, matchTriggerWidth, previousHorizontalPosition, previousVerticalPosition, } ) => { // Collect information about all the involved DOM elements let scroll = { left: window.pageXOffset, top: window.pageYOffset }; let { left: triggerLeft, top: triggerTop, width: triggerWidth, height: triggerHeight, } = trigger.getBoundingClientRect(); let { height: dropdownHeight, width: dropdownWidth } = content.getBoundingClientRect(); let viewportWidth = document.body.clientWidth || window.innerWidth; let style: CalculatePositionResultStyle = {}; // Apply containers' offset let anchorElement = destination.parentNode as HTMLElement; let anchorPosition = window.getComputedStyle(anchorElement).position; while ( anchorPosition !== 'relative' && anchorPosition !== 'absolute' && anchorElement.tagName.toUpperCase() !== 'BODY' ) { anchorElement = anchorElement.parentNode as HTMLElement; anchorPosition = window.getComputedStyle(anchorElement).position; } if (anchorPosition === 'relative' || anchorPosition === 'absolute') { let rect = anchorElement.getBoundingClientRect(); triggerLeft = triggerLeft - rect.left; triggerTop = triggerTop - rect.top; let { offsetParent } = anchorElement; if (offsetParent) { triggerLeft -= offsetParent.scrollLeft; triggerTop -= offsetParent.scrollTop; } } // Calculate drop down width dropdownWidth = matchTriggerWidth ? triggerWidth : dropdownWidth; if (matchTriggerWidth) { style.width = dropdownWidth; } // Calculate horizontal position let triggerLeftWithScroll = triggerLeft + scroll.left; if (horizontalPosition === 'auto' || horizontalPosition === 'auto-left') { // Calculate the number of visible horizontal pixels if we were to place the // dropdown on the left and right let leftVisible = Math.min(viewportWidth, triggerLeft + dropdownWidth) - Math.max(0, triggerLeft); let rightVisible = Math.min(viewportWidth, triggerLeft + triggerWidth) - Math.max(0, triggerLeft + triggerWidth - dropdownWidth); if (dropdownWidth > leftVisible && rightVisible > leftVisible) { // If the drop down won't fit left-aligned, and there is more space on the // right than on the left, then force right-aligned horizontalPosition = 'right'; } else if (dropdownWidth > rightVisible && leftVisible > rightVisible) { // If the drop down won't fit right-aligned, and there is more space on // the left than on the right, then force left-aligned horizontalPosition = 'left'; } else { // Keep same position as previous horizontalPosition = previousHorizontalPosition || 'left'; } } else if (horizontalPosition === 'auto-right') { // Calculate the number of visible horizontal pixels if we were to place the // dropdown on the left and right let leftVisible = Math.min(viewportWidth, triggerLeft + dropdownWidth) - Math.max(0, triggerLeft); let rightVisible = Math.min(viewportWidth, triggerLeft + triggerWidth) - Math.max(0, triggerLeft + triggerWidth - dropdownWidth); if (dropdownWidth > rightVisible && leftVisible > rightVisible) { // If the drop down won't fit right-aligned, and there is more space on the // left than on the right, then force left-aligned horizontalPosition = 'left'; } else if (dropdownWidth > leftVisible && rightVisible > leftVisible) { // If the drop down won't fit left-aligned, and there is more space on // the right than on the left, then force right-aligned horizontalPosition = 'right'; } else { // Keep same position as previous horizontalPosition = previousHorizontalPosition || 'right'; } } if (horizontalPosition === 'right') { style.right = viewportWidth - (triggerLeftWithScroll + triggerWidth); } else if (horizontalPosition === 'center') { style.left = triggerLeftWithScroll + (triggerWidth - dropdownWidth) / 2; } else { style.left = triggerLeftWithScroll; } // Calculate vertical position let triggerTopWithScroll = triggerTop; /** * Fixes bug where the dropdown always stays on the same position on the screen when * the <body> is relatively positioned */ let isBodyPositionRelative = window.getComputedStyle(document.body).getPropertyValue('position') === 'relative'; if (!isBodyPositionRelative) { triggerTopWithScroll += scroll.top; } if (verticalPosition === 'above') { style.top = triggerTopWithScroll - dropdownHeight; } else if (verticalPosition === 'below') { style.top = triggerTopWithScroll + triggerHeight; } else { let viewportBottom = scroll.top + window.innerHeight; let enoughRoomBelow = triggerTopWithScroll + triggerHeight + dropdownHeight < viewportBottom; let enoughRoomAbove = triggerTop > dropdownHeight; if (!enoughRoomBelow && !enoughRoomAbove) { verticalPosition = 'below'; } else if ( previousVerticalPosition === 'below' && !enoughRoomBelow && enoughRoomAbove ) { verticalPosition = 'above'; } else if ( previousVerticalPosition === 'above' && !enoughRoomAbove && enoughRoomBelow ) { verticalPosition = 'below'; } else if (!previousVerticalPosition) { verticalPosition = enoughRoomBelow ? 'below' : 'above'; } else { verticalPosition = previousVerticalPosition; } style.top = triggerTopWithScroll + (verticalPosition === 'below' ? triggerHeight : -dropdownHeight); } return { horizontalPosition, verticalPosition, style }; }; export let calculateInPlacePosition: CalculatePosition = ( trigger, content, _destination, { horizontalPosition, verticalPosition } ) => { let dropdownRect; let positionData: CalculatePositionResult = { horizontalPosition: 'left', verticalPosition: 'below', style: {}, }; if (horizontalPosition === 'auto') { let triggerRect = trigger.getBoundingClientRect(); dropdownRect = content.getBoundingClientRect(); let viewportRight = window.pageXOffset + window.innerWidth; positionData.horizontalPosition = triggerRect.left + dropdownRect.width > viewportRight ? 'right' : 'left'; } else if (horizontalPosition === 'center') { let { width: triggerWidth } = trigger.getBoundingClientRect(); let { width: dropdownWidth } = content.getBoundingClientRect(); positionData.style = { left: (triggerWidth - dropdownWidth) / 2 }; } else if (horizontalPosition === 'auto-right') { let triggerRect = trigger.getBoundingClientRect(); let dropdownRect = content.getBoundingClientRect(); positionData.horizontalPosition = triggerRect.right > dropdownRect.width ? 'right' : 'left'; } else if (horizontalPosition === 'right') { positionData.horizontalPosition = 'right'; } if (verticalPosition === 'above') { positionData.verticalPosition = verticalPosition; dropdownRect = dropdownRect || content.getBoundingClientRect(); positionData.style.top = -dropdownRect.height; } else { positionData.verticalPosition = 'below'; } return positionData; }; export function getScrollParent(element: Element) { let style = window.getComputedStyle(element); let excludeStaticParent = style.position === 'absolute'; let overflowRegex = /(auto|scroll)/; if (style.position === 'fixed') return document.body; for ( let parent: Element | null = element; (parent = parent.parentElement); ) { style = window.getComputedStyle(parent); if (excludeStaticParent && style.position === 'static') { continue; } if ( overflowRegex.test(style.overflow + style.overflowY + style.overflowX) ) { return parent; } } return document.body; } let calculatePosition: CalculatePosition = ( trigger, content, destination, options ) => { if (options.renderInPlace) { return calculateInPlacePosition(trigger, content, destination, options); } else { return calculateWormholedPosition(trigger, content, destination, options); } }; export default calculatePosition;
cibernox/ember-basic-dropdown
addon/utils/calculate-position.ts
TypeScript
mit
9,067
<?php /* * This file is part of the API Platform project. * * (c) Kévin Dunglas <dunglas@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace ApiPlatform\Metadata\Resource\Factory; use ApiPlatform\Metadata\Resource\ResourceNameCollection; /** * Creates a resource name collection value object. * * @author Kévin Dunglas <dunglas@gmail.com> */ interface ResourceNameCollectionFactoryInterface { /** * Creates the resource name collection. */ public function create(): ResourceNameCollection; }
api-platform/core
src/Metadata/Resource/Factory/ResourceNameCollectionFactoryInterface.php
PHP
mit
652
using System; using System.Collections.Generic; using System.Reflection; using Xunit.Sdk; namespace Oryza.TestBase.Xunit.Extensions { public class ClassData : DataAttribute { private readonly Type _type; public ClassData(Type type) { if (!typeof (IEnumerable<object[]>).IsAssignableFrom(type)) { throw new Exception("Type mismatch. Must implement IEnumerable<object[]>."); } _type = type; } public override IEnumerable<object[]> GetData(MethodInfo testMethod) { return (IEnumerable<object[]>) Activator.CreateInstance(_type); } } }
sonbua/Oryza
src/Oryza.TestBase/Xunit.Extensions/ClassData.cs
C#
mit
682
__inline('ajax.js'); __inline('amd.js'); __inline('appendToHead.js'); __inline('bind.js'); __inline('copyProperties.js'); __inline('counter.js'); __inline('derive.js'); __inline('each.js'); __inline('hasOwnProperty.js'); __inline('inArray.js'); __inline('isArray.js'); __inline('isEmpty.js'); __inline('isFunction.js'); __inline('JSON.js'); __inline('nextTick.js'); __inline('queueCall.js'); __inline('slice.js'); __inline('toArray.js'); __inline('type.js');
hao123-fe/her-runtime
src/javascript/util/util.js
JavaScript
mit
459
package dsl import ( "fmt" "github.com/emicklei/melrose/core" "github.com/emicklei/melrose/notify" ) // At is called from expr after patching []. One-based func (v variable) At(index int) interface{} { m, ok := v.store.Get(v.Name) if !ok { return nil } if intArray, ok := m.([]int); ok { if index < 1 || index > len(intArray) { return nil } return intArray[index-1] } if indexable, ok := m.(core.Indexable); ok { return indexable.At(index) } if sequenceable, ok := m.(core.Sequenceable); ok { return core.BuildSequence(sequenceable.S().At(index)) } return nil } // AtVariable is called from expr after patching []. func (v variable) AtVariable(index variable) interface{} { indexVal := core.Int(index) if indexVal == 0 { return nil } return v.At(indexVal) } // dispatchSubFrom v(l) - r func (v variable) dispatchSub(r interface{}) interface{} { if vr, ok := r.(core.HasValue); ok { // int il, lok := resolveInt(v) ir, rok := resolveInt(vr) if lok && rok { return il - ir } } if ir, ok := r.(int); ok { // int il, lok := resolveInt(v) if lok { return il - ir } } notify.Panic(fmt.Errorf("subtraction failed [%v (%T) - %v (%T)]", v, v, r, r)) return nil } // dispatchSubFrom l - v(r) func (v variable) dispatchSubFrom(l interface{}) interface{} { if vl, ok := l.(core.HasValue); ok { // int il, lok := resolveInt(vl) ir, rok := resolveInt(v) if lok && rok { return il - ir } } if il, ok := l.(int); ok { // int ir, rok := resolveInt(v) if rok { return il - ir } } notify.Panic(fmt.Errorf("subtraction failed [%v (%T) - %v (%T)]", l, l, v, v)) return nil } func (v variable) dispatchAdd(r interface{}) interface{} { if vr, ok := r.(core.HasValue); ok { // int il, lok := resolveInt(v) ir, rok := resolveInt(vr) if lok && rok { return il + ir } } if ir, ok := r.(int); ok { il, lok := resolveInt(v) if lok { return il + ir } } notify.Panic(fmt.Errorf("addition failed [%v (%T) + %v (%T)]", r, r, v, v)) return nil } // func (v variable) dispatchMultiply(r interface{}) interface{} { // if vr, ok := r.(core.HasValue); ok { // // int // il, lok := resolveInt(v) // ir, rok := resolveInt(vr) // if lok && rok { // return il * ir // } // } // if ir, ok := r.(int); ok { // il, lok := resolveInt(v) // if lok { // return il * ir // } // } // notify.Panic(fmt.Errorf("multiplication failed [%v (%T) * %v (%T)]", r, r, v, v)) // return nil // } func resolveInt(v core.HasValue) (int, bool) { vv := v.Value() if i, ok := vv.(int); ok { return i, true } if vvv, ok := vv.(core.HasValue); ok { return resolveInt(vvv) } return 0, false }
emicklei/melrose
dsl/var_delegates.go
GO
mit
2,696
'use strict'; var _ = require('lodash'); var fs = require('fs'); var path = require('path'); var util = require('util'); var async = require('./async'); /** * Read a directory recursively. * The directory will be read depth-first and will return paths relative * to the base directory. It will only result in file names, not directories. * * @function * @param {string} dir The directory to read * @param {function} cb The callback to call when complete. Receives error * and array of relative file paths. */ var readdirRecursive = module.exports.readdirRecursive = function(dir, cb) { var remaining = ['.']; var result = []; var next = function() { var relativeDirPath = remaining.shift(); var dirPath = path.join(dir, relativeDirPath); fs.readdir(dirPath, function(err, files) { if (err) { return cb(err); } async.each(files, function(file, done) { if (file[0] === '.') { return done(); } var filePath = path.join(dirPath, file); var relativeFilePath = path.join(relativeDirPath, file); fs.stat(filePath, function(err, stats) { if (err) { return done(err); } if (stats.isDirectory()) { remaining.push(relativeFilePath); } else { result.push(relativeFilePath); } done(); }); }, function(err) { if (err) { return cb(err); } if (remaining.length === 0) { cb(null, result.sort()); } else { next(); } }); }); }; next(); }; /** * Test if files are equal. * * @param {string} fileA Path to first file * @param {string} fileB Path to second file * @param {function} cb Callback to call when finished check. Receives error * and boolean. */ var filesEqual = module.exports.filesEqual = function(fileA, fileB, cb) { var options = { encoding: 'utf8' }; fs.readFile(fileA, options, function(err, contentsA) { if (err) { return cb(err); } fs.readFile(fileB, options, function(err, contentsB) { if (err) { return cb(err); } cb(null, contentsA === contentsB); }); }) }; /** * Recursively test if directories are equal. * * @param {string} dirA Path to first dir * @param {string} dirB Path to second dir * @param {function} cb Callback to call when finished check. Receives error * and boolean. */ module.exports.directoriesEqual = function(directoryA, directoryB, cb) { readdirRecursive(directoryA, function(err, directoryAContents) { if (err) { return cb(err); } readdirRecursive(directoryB, function(err, directoryBContents) { if (err) { return cb(err); } if (directoryAContents.length !== directoryBContents.length) { cb(null, false); } else { directoryAContents = directoryAContents.sort(); directoryBContents = directoryBContents.sort(); if (!_.isEqual(directoryAContents, directoryBContents)) { cb(null, false); } else { var result = true; async.each(directoryAContents, function(relativePath, done) { var aFilePath = path.join(directoryA, relativePath); var bFilePath = path.join(directoryB, relativePath); filesEqual(aFilePath, bFilePath, function(err, singleResult) { if (err) { return done(err); } result = singleResult && result; done(); }); }, function(err) { if (err) { return cb(err); } cb(null, result); }); } } }); }); }; /** * Make a directory and all the directories that lead to it. * * @function * @param {string} path Path to the directory to make * @param {function} cb The callback to call once created. This just * receives an error. */ module.exports.mkdirp = function(dirPath, cb) { var attempt = [dirPath]; var next = function() { var attemptPath = attempt.pop(); fs.mkdir(attemptPath, function(err) { if (err && ( err.code === 'EISDIR' || err.code === 'EEXIST')) { cb(); } else if (err && err.code === 'ENOENT') { attempt.push(attemptPath); attempt.push(path.dirname(attemptPath)); next(); } else if (err) { cb(err); } else if (attempt.length) { next(); } else if (attemptPath === '/') { cb(new Error(util.format('Could not make path to %s', dirPath))); } else { cb(); } }); }; next(); };
wbyoung/jsi-blowtorch
lib/fs-extras.js
JavaScript
mit
4,456
class Bitcask require 'zlib' require 'stringio' $LOAD_PATH << File.expand_path(File.dirname(__FILE__)) require 'bitcask/hint_file' require 'bitcask/data_file' require 'bitcask/keydir' require 'bitcask/errors' require 'bitcask/version' include Enumerable TOMBSTONE = "bitcask_tombstone" # Opens a bitcask backed by the given directory. attr_accessor :keydir attr_reader :dir def initialize(dir) @dir = dir @keydir = Bitcask::Keydir.new end # Uses the keydir to get an object from the bitcask. Returns a # value. def [](key) index = @keydir[key] or return nil @keydir.data_files[index.file_id][index.value_pos, index.value_sz].value end # Close filehandles and keydir def close close_filehandles close_keydir end # Close all filehandles loaded by the keydir. def close_filehandles @keydir.data_files.each do |data_file| data_file.close if h = data_file.instance_variable_get('@hint_file') h.close end end end # Close the keydir. def close_keydir @keydir = nil end # Returns a list of all data filenames in this bitcask, sorted from oldest # to newest. def data_file_names Dir.glob(File.join(@dir, '*.data')).sort! do |a, b| a.to_i <=> b.to_i end end # Returns a list of Bitcask::DataFiles in chronological order. def data_files data_file_names.map! do |filename| Bitcask::DataFile.new filename end end # Iterates over all keys in keydir. Yields key, value pairs. def each @keydir.each do |key, index| entry = @keydir.data_files[index.file_id][index.value_pos, index.value_sz] yield [entry.key, entry.value] end end # Keydir keys. def keys keydir.keys end # Populate the keydir. def load data_files.each do |d| if h = d.hint_file load_hint_file h else load_data_file d end end end # Load a DataFile into the keydir. def load_data_file(data_file) # Determine data_file index. @keydir.data_files |= [data_file] file_id = @keydir.data_files.index data_file pos = 0 data_file.each do |entry| # Check for existing newer entry in keydir if (cur = @keydir[entry.key]).nil? or entry.tstamp >= cur.tstamp @keydir[entry.key] = Keydir::Entry.new( file_id, data_file.pos - pos, pos, entry.tstamp ) end pos = data_file.pos end end # Load a HintFile into the keydir. def load_hint_file(hint_file) # Determine data_file index. @keydir.data_files |= [hint_file.data_file] file_id = @keydir.data_files.index hint_file.data_file hint_file.each do |entry| # Check for existing newer entry in keydir if (cur = @keydir[entry.key]).nil? or entry.tstamp >= cur.tstamp @keydir[entry.key] = Keydir::Entry.new( file_id, entry.value_sz, entry.value_pos, entry.tstamp ) end end end # Keydir size. def size @keydir.size end end
aphyr/bitcask-ruby
lib/bitcask.rb
Ruby
mit
3,087
'use strict' /* MIT License Copyright (c) 2016 Ilya Shaisultanov 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. */ var dgram = require('dgram') , EE = require('events').EventEmitter , util = require('util') , ip = require('ip') , debug = require('debug') , os = require('os') , async = require('async') , extend = require('extend') , SsdpHeader = require('./ssdpHeader') var httpHeader = /HTTP\/\d{1}\.\d{1} \d+ .*/ , ssdpHeader = /^([^:]+):\s*(.*)$/ /* consts */ var c = require('./const') var nodeVersion = process.version.substr(1) , moduleVersion = require('../package.json').version , moduleName = require('../package.json').name /** * Options: * * @param {Object} opts * @param {String} opts.ssdpSig SSDP signature * @param {String} opts.ssdpIp SSDP multicast group * @param {String} opts.ssdpPort SSDP port * @param {Number} opts.ssdpTtl Multicast TTL * @param {Number} opts.adInterval Interval at which to send out advertisement (ms) * @param {String} opts.description Path to SSDP description file * @param {String} opts.udn SSDP Unique Device Name * @param {Object} opts.headers Additional headers * @param {Array} opts.interfaces Names of interfaces to use. When set, other interfaces are ignored. * * @param {Number} opts.ttl Packet TTL * @param {Boolean} opts.allowWildcards Allow wildcards in M-SEARCH packets (non-standard) * * @returns {SSDP} * @constructor */ function SSDP(opts) { var self = this if (!(this instanceof SSDP)) return new SSDP(opts) this._subclass = this._subclass || 'node-ssdp:base' opts = opts || {} this._logger = opts.customLogger || debug(this._subclass) EE.call(self) this._init(opts) } util.inherits(SSDP, EE) /** * Initializes instance properties. * @param opts * @private */ SSDP.prototype._init = function (opts) { this._ssdpSig = opts.ssdpSig || getSsdpSignature() this._explicitSocketBind = opts.explicitSocketBind this._interfaces = opts.interfaces this._reuseAddr = opts.reuseAddr === undefined ? true : opts.reuseAddr // User shouldn't need to set these this._ssdpIp = opts.ssdpIp || c.SSDP_DEFAULT_IP this._ssdpPort = opts.ssdpPort || c.SSDP_DEFAULT_PORT this._ssdpTtl = opts.ssdpTtl || 4 // port on which to listen for messages // this generally should be left up to the system for SSDP Client // For server, this will be set by the server constructor // unless user sets a value. this._sourcePort = opts.sourcePort || 0 this._adInterval = opts.adInterval || 10000 this._ttl = opts.ttl || 1800 if (typeof opts.location === 'function') { Object.defineProperty(this, '_location', { enumerable: true, get: opts.location }) } else if (typeof opts.location === 'object') { this._locationProtocol = opts.location.protocol || 'http://' this._locationPort = opts.location.port this._locationPath = opts.location.path } else { // Probably should specify this explicitly this._location = opts.location || 'http://' + ip.address() + ':' + 10293 + '/upnp/desc.html' } this._ssdpServerHost = this._ssdpIp + ':' + this._ssdpPort this._usns = {} this._udn = opts.udn || 'uuid:f40c2981-7329-40b7-8b04-27f187aecfb5' this._extraHeaders = opts.headers || {} this._allowWildcards = opts.allowWildcards this._suppressRootDeviceAdvertisements = opts.suppressRootDeviceAdvertisements } /** * Creates and returns UDP4 socket. * Prior to node v0.12.x `dgram.createSocket` did not accept * an object and socket reuse was not available; this method * contains a crappy workaround to make version of node before 0.12 * to work correctly. See https://github.com/diversario/node-ssdp/pull/38 * * @returns {Socket} * @private */ SSDP.prototype._createSockets = function () { var interfaces = os.networkInterfaces() , self = this this.sockets = {} Object.keys(interfaces).forEach(function (iName) { if (!self._interfaces || self._interfaces.indexOf(iName) > -1) { self._logger('discovering all IPs from interface %s', iName) interfaces[iName].forEach(function (ipInfo) { if (ipInfo.internal == false && ipInfo.family == "IPv4") { self._logger('Will use interface %s', iName) var socket if (parseFloat(process.version.replace(/\w/, '')) >= 0.12) { socket = dgram.createSocket({type: 'udp4', reuseAddr: self._reuseAddr}) } else { socket = dgram.createSocket('udp4') } if (socket) { socket.unref() self.sockets[ipInfo.address] = socket } } }) } }) if (Object.keys(this.sockets) == 0) { throw new Error('No sockets available, cannot start.') } } /** * Advertise shutdown and close UDP socket. */ SSDP.prototype._stop = function () { var self = this if (!this.sockets) { this._logger('Already stopped.') return } Object.keys(this.sockets).forEach(function (ipAddress) { var socket = self.sockets[ipAddress] socket && socket.close() self._logger('Stopped socket on %s', ipAddress) }) this.sockets = null this._socketBound = this._started = false } /** * Configures UDP socket `socket`. * Binds event listeners. */ SSDP.prototype._start = function (cb) { var self = this if (self._started) { self._logger('Already started.') return } if (!this.sockets) { this._createSockets() } self._started = true var interfaces = Object.keys(this.sockets) async.each(interfaces, function (iface, next) { var socket = self.sockets[iface] socket.on('error', function onSocketError(err) { self._logger('Socker error: %s', err.message) }) socket.on('message', function onSocketMessage(msg, rinfo) { self._parseMessage(msg, rinfo) }) socket.on('listening', function onSocketListening() { var addr = socket.address() self._logger('SSDP listening: %o', {address: 'http://' + addr.address + ':' + addr.port, 'interface': iface}) try { addMembership() } catch (e) { if (e.code === 'ENODEV' || e.code === 'EADDRNOTAVAIL') { self._logger('Interface %s is not present to add multicast group membership. Scheduling a retry. Error: %s', addr, e.message) delay().then(addMembership).catch(e => { throw e }) } else { throw e } } function addMembership() { socket.addMembership(self._ssdpIp, iface) // TODO: specifying the interface in there might make a difference socket.setMulticastTTL(self._ssdpTtl) } function delay() { return new Promise((resolve) => { setTimeout(resolve, 5000); }); } }) if (self._explicitSocketBind) { socket.bind(self._sourcePort, iface, next) } else { socket.bind(self._sourcePort, next) // socket binds on 0.0.0.0 } }, cb) } /** * Routes a network message to the appropriate handler. * * @param msg * @param rinfo */ SSDP.prototype._parseMessage = function (msg, rinfo) { msg = msg.toString() var type = msg.split('\r\n').shift() // HTTP/#.# ### Response to M-SEARCH if (httpHeader.test(type)) { this._parseResponse(msg, rinfo) } else { this._parseCommand(msg, rinfo) } } /** * Parses SSDP command. * * @param msg * @param rinfo */ SSDP.prototype._parseCommand = function parseCommand(msg, rinfo) { var method = this._getMethod(msg) , headers = this._getHeaders(msg) switch (method) { case c.NOTIFY: this._notify(headers, msg, rinfo) break case c.M_SEARCH: this._msearch(headers, msg, rinfo) break default: this._logger('Unhandled command: %o', {'message': msg, 'rinfo': rinfo}) } } /** * Handles NOTIFY command * Emits `advertise-alive`, `advertise-bye` events. * * @param headers * @param msg * @param rinfo */ SSDP.prototype._notify = function (headers, msg, rinfo) { if (!headers.NTS) { this._logger('Missing NTS header: %o', headers) return } switch (headers.NTS.toLowerCase()) { // Device coming to life. case c.SSDP_ALIVE: this.emit(c.ADVERTISE_ALIVE, headers, rinfo) break // Device shutting down. case c.SSDP_BYE: this.emit(c.ADVERTISE_BYE, headers, rinfo) break default: this._logger('Unhandled NOTIFY event: %o', {'message': msg, 'rinfo': rinfo}) } } /** * Handles M-SEARCH command. * * @param headers * @param msg * @param rinfo */ SSDP.prototype._msearch = function (headers, msg, rinfo) { this._logger('SSDP M-SEARCH event: %o', {'ST': headers.ST, 'address': rinfo.address, 'port': rinfo.port}) if (!headers.MAN || !headers.MX || !headers.ST) return this._respondToSearch(headers.ST, rinfo) } /** * Sends out a response to M-SEARCH commands. * * @param {String} serviceType Service type requested by a client * @param {Object} rinfo Remote client's address * @private */ SSDP.prototype._respondToSearch = function (serviceType, rinfo) { var self = this , peer_addr = rinfo.address , peer_port = rinfo.port , stRegex , acceptor // unwrap quoted string if (serviceType[0] == '"' && serviceType[serviceType.length - 1] == '"') { serviceType = serviceType.slice(1, -1) } if (self._allowWildcards) { stRegex = new RegExp(serviceType.replace(/\*/g, '.*') + '$') acceptor = function (usn, serviceType) { return serviceType === c.SSDP_ALL || stRegex.test(usn) } } else { acceptor = function (usn, serviceType) { return serviceType === c.SSDP_ALL || usn === serviceType } } Object.keys(self._usns).forEach(function (usn) { var udn = self._usns[usn] if (self._allowWildcards) { udn = udn.replace(stRegex, serviceType) } if (acceptor(usn, serviceType)) { var header = new SsdpHeader('200 OK', { 'ST': serviceType === c.SSDP_ALL ? usn : serviceType, 'USN': udn, 'CACHE-CONTROL': 'max-age=' + self._ttl, 'DATE': new Date().toUTCString(), 'SERVER': self._ssdpSig, 'EXT': '' }, true) header.setHeaders(self._extraHeaders) if (self._location) { header.setHeader('LOCATION', self._location) } else { header.overrideLocationOnSend() } self._logger('Sending a 200 OK for an M-SEARCH: %o', {'peer': peer_addr, 'port': peer_port}) self._send(header, peer_addr, peer_port, function (err, bytes) { self._logger('Sent M-SEARCH response: %o', {'message': header.toString(), id: header.id()}) }) } }) } /** * Parses SSDP response message. * * @param msg * @param rinfo */ SSDP.prototype._parseResponse = function parseResponse(msg, rinfo) { this._logger('SSDP response: %o', {'message': msg}) var headers = this._getHeaders(msg) , statusCode = this._getStatusCode(msg) this.emit('response', headers, statusCode, rinfo) } SSDP.prototype.addUSN = function (device) { this._usns[device] = this._udn + '::' + device } SSDP.prototype._getMethod = function _getMethod(msg) { var lines = msg.split("\r\n") , type = lines.shift().split(' ')// command, such as "NOTIFY * HTTP/1.1" , method = (type[0] || '').toLowerCase() return method } SSDP.prototype._getStatusCode = function _getStatusCode(msg) { var lines = msg.split("\r\n") , type = lines.shift().split(' ')// command, such as "NOTIFY * HTTP/1.1" , code = parseInt(type[1], 10) return code } SSDP.prototype._getHeaders = function _getHeaders(msg) { var lines = msg.split("\r\n") var headers = {} lines.forEach(function (line) { if (line.length) { var pairs = line.match(ssdpHeader) if (pairs) headers[pairs[1].toUpperCase()] = pairs[2] // e.g. {'HOST': 239.255.255.250:1900} } }) return headers } SSDP.prototype._send = function (message, host, port, cb) { var self = this if (typeof host === 'function') { cb = host host = this._ssdpIp port = this._ssdpPort } var ipAddresses = Object.keys(this.sockets) async.each(ipAddresses, function (ipAddress, next) { var socket = self.sockets[ipAddress] var buf if (message instanceof SsdpHeader) { if (message.isOverrideLocationOnSend()) { var location = self._locationProtocol + ipAddress + ':' + self._locationPort + self._locationPath self._logger('Setting LOCATION header "%s" on message ID %s', location, message.id()) buf = message.toBuffer({'LOCATION': location}) } else { buf = message.toBuffer() } } else { buf = message } self._logger('Sending a message to %s:%s', host, port) socket.send(buf, 0, buf.length, port, host, next) }, cb) } function getSsdpSignature() { return 'node.js/' + nodeVersion + ' UPnP/1.1 ' + moduleName + '/' + moduleVersion } module.exports = SSDP
diversario/node-ssdp
lib/index.js
JavaScript
mit
13,902
<?php namespace App; use App\Models\User; use RuntimeException; class UserSettingForm { private string $setting_name; private ?User $current_user; private bool $can_save; public const INPUT_MAP = [ 'cg_defaultguide' => [ 'type' => 'select', 'options' => [ 'desc' => 'Choose your preferred color guide: ', 'optg' => 'Available guides', 'opts' => CGUtils::GUIDE_MAP, 'null_opt' => 'Guide Index', ], ], 'cg_itemsperpage' => [ 'type' => 'number', 'options' => [ 'desc' => 'Appearances per page', 'min' => 7, 'max' => 20, ], ], 'cg_hidesynon' => [ 'type' => 'checkbox', 'options' => [ 'perm' => 'staff', 'desc' => 'Hide synonym tags under appearances', ], ], 'cg_hideclrinfo' => [ 'type' => 'checkbox', 'options' => [ 'desc' => 'Hide color details on appearance pages', ], ], 'cg_fulllstprev' => [ 'type' => 'checkbox', 'options' => [ 'desc' => 'Display previews and alternate names on the full list', ], ], 'cg_nutshell' => [ 'type' => 'checkbox', 'options' => [ 'desc' => 'Use joke character names (does not affect search)', ], ], 'p_vectorapp' => [ 'type' => 'select', 'options' => [ 'desc' => 'Publicly show my vector program of choice: ', 'optg' => 'Vectoring applications', 'opts' => CoreUtils::VECTOR_APPS, ], ], 'p_hidediscord' => [ 'type' => 'checkbox', 'options' => [ 'perm' => 'not_discord_member', 'desc' => 'Hide Discord server link from the sidebar', ], ], 'p_hidepcg' => [ 'type' => 'checkbox', 'options' => [ 'desc' => 'Hide my Personal Color Guide from the public', ], ], 'p_homelastep' => [ 'type' => 'checkbox', 'options' => [ 'desc' => '<span class="typcn typcn-home">&nbsp;Home</span> should open latest episode (instead of preferred color guide)', ], ], 'ep_hidesynopses' => [ 'type' => 'checkbox', 'options' => [ 'desc' => 'Hide the synopsis section from episode pages', ], ], 'ep_noappprev' => [ 'type' => 'checkbox', 'options' => [ 'desc' => 'Hide preview squares in front of related appearance names', ], ], 'ep_revstepbtn' => [ 'type' => 'checkbox', 'options' => [ 'desc' => 'Reverse order of next/previous episode buttons', ], ], 'a_pcgearn' => [ 'type' => 'checkbox', 'options' => [ 'desc' => 'Can earn PCG slots (from finishing requests)', ], ], 'a_pcgmake' => [ 'type' => 'checkbox', 'options' => [ 'desc' => 'Can create PCG appearances', ], ], 'a_pcgsprite' => [ 'type' => 'checkbox', 'options' => [ 'desc' => 'Can add sprites to PCG appearances', ], ], 'a_postreq' => [ 'type' => 'checkbox', 'options' => [ 'desc' => 'Can post requests', ], ], 'a_postres' => [ 'type' => 'checkbox', 'options' => [ 'desc' => 'Can post reservations', ], ], 'a_reserve' => [ 'type' => 'checkbox', 'options' => [ 'desc' => 'Can reserve requests', ], ], ]; public function __construct(string $setting_name, ?User $current_user = null, ?string $req_perm = null) { if (!array_key_exists($setting_name, UserPrefs::DEFAULTS)) throw new RuntimeException('Could not instantiate '.__CLASS__." for non-existing setting $setting_name"); if (!isset(self::INPUT_MAP[$setting_name])) throw new RuntimeException('Could not instantiate '.__CLASS__." for $setting_name: Missing INPUT_MAP entry"); $this->setting_name = $setting_name; if ($current_user === null && Auth::$signed_in) $current_user = Auth::$user; $this->current_user = $current_user; // By default only the user themselves can change this setting if ($req_perm === null) $this->can_save = Auth::$signed_in && $this->current_user->id === Auth::$user->id; // If a permission is required, make sure the authenticated user has it else $this->can_save = Permission::sufficient($req_perm); } private function _permissionCheck(string $check_name) { switch ($check_name){ case 'discord_member': case 'not_discord_member': if ($this->current_user === null) return false; if ($this->current_user->isDiscordServerMember()) return $check_name === 'discord_member'; else return $check_name === 'not_discord_member'; default: return true; } } private function _getInput(string $type, array $options = []):string { if (isset($options['perm'])){ if (isset(Permission::ROLES[$options['perm']])){ if (Permission::insufficient($options['perm'])) return ''; } else { if (!$this->_permissionCheck($options['perm'])) return ''; } } $disabled = !$this->can_save ? 'disabled' : ''; $value = UserPrefs::get($this->setting_name, $this->current_user); switch ($type){ case 'select': $select = ''; $optgroup = ''; if (isset($options['null_opt'])){ $selected = $value === null ? 'selected' : ''; $select .= "<option value='' $selected>".CoreUtils::escapeHTML($options['null_opt']).'</option>'; } /** @noinspection ForeachSourceInspection */ foreach ($options['opts'] as $name => $label){ $selected = $value === $name ? 'selected' : ''; $opt_disabled = isset($options['optperm'][$name]) && !$this->_permissionCheck($options['optperm'][$name]) ? 'disabled' : ''; $optgroup .= "<option value='$name' $selected $opt_disabled>".CoreUtils::escapeHTML($label).'</option>'; } $label = CoreUtils::escapeHTML($options['optg'], ENT_QUOTES); $select .= "<optgroup label='$label'>$optgroup</optgroup>"; return "<select name='value' $disabled>$select</select>"; case 'number': $min = isset($options['min']) ? "min='{$options['min']}'" : ''; $max = isset($options['max']) ? "max='{$options['max']}'" : ''; $value = CoreUtils::escapeHTML($value, ENT_QUOTES); return "<input type='number' $min $max name='value' value='$value' step='1' $disabled>"; case 'checkbox': $checked = $value ? ' checked' : ''; return "<input type='checkbox' name='value' value='1' $checked $disabled>"; } } public function render() { $map = self::INPUT_MAP[$this->setting_name]; $input = $this->_getInput($map['type'], $map['options'] ?? []); if ($input === '') return ''; echo Twig::$env->render('user/_setting_form.html.twig', [ 'map' => $map, 'input' => $input, 'can_save' => $this->can_save, 'setting_name' => $this->setting_name, 'current_user' => $this->current_user, 'signed_in' => Auth::$signed_in, ]); } }
ponydevs/MLPVC-RR
app/UserSettingForm.php
PHP
mit
7,139
using System.Web.Mvc; namespace SOURCE.BackOffice.Web.Controllers.Modularity { public class BaseController : Controller { protected string Rubrique { get; set; } protected string Page { get; set; } protected string Secteur { get; set; } public BaseController() : base() { } protected override void OnActionExecuting(ActionExecutingContext filterContext) { /* List<ModuleModel> leftmodules = new List<ModuleModel>(); leftmodules.Add(new ModuleModel { BaseModuleName = "Nouveautes", ID = 12 }); ViewData["modules_gauche"] = (IEnumerable<ModuleModel>)leftmodules; List<ModuleModel> rightmodules = new List<ModuleModel>(); rightmodules.Add(new ModuleModel { BaseModuleName = "Nouveautes", ID = 13 }); rightmodules.Add(new ModuleModel { BaseModuleName = "MeilleuresVentes", ID = 20 }); rightmodules.Add(new ModuleModel { BaseModuleName = "Nouveautes", ID = 14 }); ViewData["modules_droite"] = (IEnumerable<ModuleModel>)rightmodules; if (RouteData.Values["secteur"] != null) this.Secteur = RouteData.Values["secteur"].ToString(); else this.Secteur = string.Empty; if (RouteData.Values["subpage"] != null) this.Rubrique = RouteData.Values["subpage"].ToString(); else this.Rubrique = "Normes"; if (RouteData.Values["page"] != null) this.Page = RouteData.Values["page"].ToString(); else this.Page = "Home"; */ } } }
apo-j/Projects_Working
S/SOURCE/SOURCE.BackOffice/SOURCE.BackOffice.Web.Controllers/Modularity/BaseController.cs
C#
mit
1,754
import signal import subprocess import sys import time import numba import numpy as np import SharedArray as sa sys.path.append('./pymunk') import pymunk as pm max_creatures = 50 @numba.jit def _find_first(vec, item): for i in range(len(vec)): if vec[i] == item: return i return -1 @numba.jit(nopython=True) def random_circle_point(): theta = np.random.rand()*2*np.pi x,y = 5*np.cos(theta), 5*np.sin(theta) return x,y class Culture(object): def __init__(self): try: self.creature_parts = sa.create('creature_parts', (max_creatures*3, 12), dtype=np.float32) except FileExistsError: sa.delete('creature_parts') self.creature_parts = sa.create('creature_parts', (max_creatures*3, 12), dtype=np.float32) # X POSITION, Y POSITION self.creature_parts[:, :2] = (30.0, 30.0)#np.random.random((max_creatures, 2)).astype(np.float32)*20.0 - 10.0 # ROTATION self.creature_parts[:, 2] = np.random.random(max_creatures*3)*2*np.pi - np.pi # SCALE self.creature_parts[:, 3] = 0.5 # TEXTURE INDEX self.creature_parts[:, 4] = np.random.randint(0, 10, max_creatures*3) # COLOR ROTATION self.creature_parts[:, 5] = np.random.randint(0, 4, max_creatures*3)/4.0 # SATURATION self.creature_parts[:, 6] = 1.0 # ALPHA self.creature_parts[:, 7] = 1.0 # TIME OFFSET (FOR ANIMATION self.creature_parts[:, 8] = np.random.random(max_creatures).repeat(3)*2*np.pi self.creature_parts[1::3, 8] += 0.4 self.creature_parts[2::3, 8] += 0.8 # BEAT ANIMATION FREQUENCY self.creature_parts[:, 9] = 2.0 # SWIRL ANIMATON RADIUS self.creature_parts[:, 10] = 2.3 # SWIRL ANIMATION FREQUENCY self.creature_parts[:, 11] = 1.0 self.creature_data = np.zeros((max_creatures, 4)) self.creature_data[:, 1] = 1.0 # max_age self.creature_data[:, 3] = 0.5 # creature size self.pm_space = pm.Space() self.pm_space.damping = 0.4 # self.pm_space.gravity = 0.0, -1.0 self.pm_body = [] self.pm_body_joint = [] self.pm_target = [] self.pm_target_spring = [] for i in range(max_creatures): head = pm.Body(10.0, 5.0) head.position = tuple(self.creature_parts[i, :2]) mid = pm.Body(1.0, 1.0) mid.position = head.position + (0.0, -1.0) tail = pm.Body(1.0, 1.0) tail.position = head.position + (0.0, -2.0) self.pm_body.append([head, mid, tail]) head_mid_joint1 = pm.constraint.SlideJoint(head, mid, (0.4, -0.3), (0.4, 0.3), 0.1, 0.2) head_mid_joint2 = pm.constraint.SlideJoint(head, mid, (-0.4, -0.3), (-0.4, 0.3), 0.1, 0.2) mid_tail_joint = pm.constraint.SlideJoint(mid, tail, (0.0, -0.1), (0.0, 0.1), 0.1, 0.5) self.pm_body_joint.append([head_mid_joint1, head_mid_joint2, mid_tail_joint]) target = pm.Body(10.0, 10.0) target.position = tuple(self.creature_parts[i, :2] + (0.0, 5.0)) self.pm_target.append(target) head_offset = pm.vec2d.Vec2d((0.0, 0.8)) * float(0.5) target_spring = pm.constraint.DampedSpring(head, target, head_offset, (0.0, 0.0), 0.0, 10.0, 15.0) self.pm_target_spring.append(target_spring) self.pm_space.add([head, mid, tail]) self.pm_space.add([head_mid_joint1, head_mid_joint2, mid_tail_joint]) self.pm_space.add([target_spring]) self.prev_update = time.perf_counter() self.ct = time.perf_counter() #self.dt = p0.0 def add_creature(self, type=None): if type is None: type = 0#np.random.randint(2) print('adding creature {}'.format(type)) ind = _find_first(self.creature_data[:, 0], 0.0) if ind != -1: if type == 0: # Meduusa new_pos = pm.vec2d.Vec2d(tuple(np.random.random(2)*20.0 - 10.0)) print('at position: ', new_pos) head_offset = pm.vec2d.Vec2d((0.0, 0.8)) * 0.5 self.pm_target[ind].position = new_pos + head_offset self.pm_body[ind][0].position = new_pos #creature_data[ind, :2] = new_pos self.pm_body[ind][1].position = new_pos + (0.0, -0.5) self.pm_body[ind][2].position = new_pos + (0.0, -1.0) for i in range(3): self.pm_body[ind][i].reset_forces() self.pm_body[ind][i].velocity = 0.0, 0.0 self.creature_parts[ind*3+i, 3] = 0.5 # size/scale self.creature_parts[ind*3+i, 6] = 1.0 self.creature_parts[ind*3+i, 4] = 2+i self.creature_data[ind, :] = [1.0, np.random.random(1)*10+10, 0.0, 0.5] # Alive, max_age, age, size if type == 1: # Ötö pass def update(self, dt): self.ct = time.perf_counter() if self.ct - self.prev_update > 5.0: self.add_creature() #i = np.random.randint(0, max_creatures) #self.pm_target[i].position = tuple(np.random.random(2)*20.0 - 10.0) self.prev_update = self.ct alive = self.creature_data[:, 0] max_age = self.creature_data[:, 1] cur_age = self.creature_data[:, 2] cur_age[:] += dt self.creature_parts[:, 6] = np.clip(1.0 - (cur_age / max_age), 0.0, 1.0).repeat(3) # dying_creatures = (alive == 1.0) & (cur_age > max_age) self.creature_parts[:, 7] = np.clip(1.0 - (cur_age - max_age)/5.0, 0.0, 1.0).repeat(3) dead_creatures = (alive == 1.0) & (cur_age > max_age + 5.0) self.creature_data[dead_creatures, 0] = 0.0 self.pm_space.step(dt) for i in range(max_creatures): head_offset = pm.vec2d.Vec2d((0.0, 0.8)) * 0.5 if alive[i] == 1.0 and \ (self.pm_body[i][0].position - (self.pm_target[i].position - head_offset)).get_length() < 2.0: self.pm_target[i].position += random_circle_point() for j in range(3): self.creature_parts[3*i+j, :2] = tuple(self.pm_body[i][j].position) self.creature_parts[3*i+j, 2] = self.pm_body[i][j].angle #self.creature_data[:, 2] += dt @staticmethod def cleanup(): print('Cleaning up') sa.delete('creature_parts') def main(): culture = Culture() gfx_p = subprocess.Popen(['python', 'main.py']) running = True def signal_handler(signal_number, frame): print('Received signal {} in frame {}'.format(signal_number, frame)) nonlocal running running = False signal.signal(signal.SIGINT, signal_handler) print('Press Ctrl+C to quit') while running: culture.update(0.01) time.sleep(0.01) if gfx_p.poll() == 0: break culture.cleanup() if __name__ == "__main__": main()
brains-on-art/culture
culture_logic.py
Python
mit
7,076
//go:build go1.16 // +build go1.16 // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. package armazuredata import "net/http" // OperationsClientListResponse contains the response from method OperationsClient.List. type OperationsClientListResponse struct { OperationsClientListResult // RawResponse contains the underlying HTTP response. RawResponse *http.Response } // OperationsClientListResult contains the result from method OperationsClient.List. type OperationsClientListResult struct { OperationListResult } // SQLServerRegistrationsClientCreateOrUpdateResponse contains the response from method SQLServerRegistrationsClient.CreateOrUpdate. type SQLServerRegistrationsClientCreateOrUpdateResponse struct { SQLServerRegistrationsClientCreateOrUpdateResult // RawResponse contains the underlying HTTP response. RawResponse *http.Response } // SQLServerRegistrationsClientCreateOrUpdateResult contains the result from method SQLServerRegistrationsClient.CreateOrUpdate. type SQLServerRegistrationsClientCreateOrUpdateResult struct { SQLServerRegistration } // SQLServerRegistrationsClientDeleteResponse contains the response from method SQLServerRegistrationsClient.Delete. type SQLServerRegistrationsClientDeleteResponse struct { // RawResponse contains the underlying HTTP response. RawResponse *http.Response } // SQLServerRegistrationsClientGetResponse contains the response from method SQLServerRegistrationsClient.Get. type SQLServerRegistrationsClientGetResponse struct { SQLServerRegistrationsClientGetResult // RawResponse contains the underlying HTTP response. RawResponse *http.Response } // SQLServerRegistrationsClientGetResult contains the result from method SQLServerRegistrationsClient.Get. type SQLServerRegistrationsClientGetResult struct { SQLServerRegistration } // SQLServerRegistrationsClientListByResourceGroupResponse contains the response from method SQLServerRegistrationsClient.ListByResourceGroup. type SQLServerRegistrationsClientListByResourceGroupResponse struct { SQLServerRegistrationsClientListByResourceGroupResult // RawResponse contains the underlying HTTP response. RawResponse *http.Response } // SQLServerRegistrationsClientListByResourceGroupResult contains the result from method SQLServerRegistrationsClient.ListByResourceGroup. type SQLServerRegistrationsClientListByResourceGroupResult struct { SQLServerRegistrationListResult } // SQLServerRegistrationsClientListResponse contains the response from method SQLServerRegistrationsClient.List. type SQLServerRegistrationsClientListResponse struct { SQLServerRegistrationsClientListResult // RawResponse contains the underlying HTTP response. RawResponse *http.Response } // SQLServerRegistrationsClientListResult contains the result from method SQLServerRegistrationsClient.List. type SQLServerRegistrationsClientListResult struct { SQLServerRegistrationListResult } // SQLServerRegistrationsClientUpdateResponse contains the response from method SQLServerRegistrationsClient.Update. type SQLServerRegistrationsClientUpdateResponse struct { SQLServerRegistrationsClientUpdateResult // RawResponse contains the underlying HTTP response. RawResponse *http.Response } // SQLServerRegistrationsClientUpdateResult contains the result from method SQLServerRegistrationsClient.Update. type SQLServerRegistrationsClientUpdateResult struct { SQLServerRegistration } // SQLServersClientCreateOrUpdateResponse contains the response from method SQLServersClient.CreateOrUpdate. type SQLServersClientCreateOrUpdateResponse struct { SQLServersClientCreateOrUpdateResult // RawResponse contains the underlying HTTP response. RawResponse *http.Response } // SQLServersClientCreateOrUpdateResult contains the result from method SQLServersClient.CreateOrUpdate. type SQLServersClientCreateOrUpdateResult struct { SQLServer } // SQLServersClientDeleteResponse contains the response from method SQLServersClient.Delete. type SQLServersClientDeleteResponse struct { // RawResponse contains the underlying HTTP response. RawResponse *http.Response } // SQLServersClientGetResponse contains the response from method SQLServersClient.Get. type SQLServersClientGetResponse struct { SQLServersClientGetResult // RawResponse contains the underlying HTTP response. RawResponse *http.Response } // SQLServersClientGetResult contains the result from method SQLServersClient.Get. type SQLServersClientGetResult struct { SQLServer } // SQLServersClientListByResourceGroupResponse contains the response from method SQLServersClient.ListByResourceGroup. type SQLServersClientListByResourceGroupResponse struct { SQLServersClientListByResourceGroupResult // RawResponse contains the underlying HTTP response. RawResponse *http.Response } // SQLServersClientListByResourceGroupResult contains the result from method SQLServersClient.ListByResourceGroup. type SQLServersClientListByResourceGroupResult struct { SQLServerListResult }
Azure/azure-sdk-for-go
sdk/resourcemanager/azuredata/armazuredata/zz_generated_response_types.go
GO
mit
5,207
# # Author:: MJ Rossetti (@s2t2) # Cookbook Name:: trailmix # Recipe:: mail # # Install sendmail package. package "sendmail" package "sendmail-cf" # Upload sendmail configuration files. template "/etc/mail/local-host-names" do source "mail/local-host-names.erb" owner "root" group "root" end template "/etc/mail/sendmail.mc" do source "mail/sendmail.mc.erb" owner "root" group "root" end # Configure sendmail according to configuration files. bash "regenerate sendmail.cf from sendmail.mc" do code "/etc/mail/make" user "root" end # Restart sendmail to apply changes in configuration. bash "restart sendmail service" do code "/etc/init.d/sendmail reload" user "root" end
s2t2/trailmix-solo
site-cookbooks/trailmix/recipes/mail.rb
Ruby
mit
700
package main.java.util; /** * * @author mancim */ public class Sorter implements SortUtil,AscSortUtil{ }
stoiandan/msg-code
Marius/Day6/src/main/java/util/Sorter.java
Java
mit
118
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("03Megapixels")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("03Megapixels")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("482789e3-146d-429e-b686-dc45003a8a9d")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
Avarea/Programming-Fundamentals
IntroAndSyntax/03Megapixels/Properties/AssemblyInfo.cs
C#
mit
1,395
# frozen_string_literal: true class FixSangerSequencingSubmissionCascadesForOracle < ActiveRecord::Migration[4.2] def change # Oracle does not support on_update so we need to remove and re-add it to keep # consistent with the MySQL installations remove_foreign_key :sanger_sequencing_samples, column: :submission_id add_foreign_key :sanger_sequencing_samples, :sanger_sequencing_submissions, column: :submission_id, on_delete: :cascade end end
tablexi/nucore-open
vendor/engines/sanger_sequencing/db/migrate/20160802202924_fix_sanger_sequencing_submission_cascades_for_oracle.rb
Ruby
mit
467
var express = require('express'); var scraptcha = require('scraptcha'); // Scraptcha images source information. var imageInformation = {path: __dirname + "/images/green/", filePrefix: "i_cha_", fileExtension: ".gif"}; // Initialize the Scraptcha data. scraptcha.initialize(imageInformation); // Static file server. var server = new express(); server.use(express.static(__dirname)); server.listen(8800); console.log("Server is listening on http://localhost:8800"); // Gets the scratcha code sequence. "id" compensates for a browser update bug. server.get('/scraptcha/:id', function (req, res) { res.send(scraptcha.getHTMLSnippet()); }); // Returns validation response. server.get('/scraptchaValidate/:data', function (req, res) { res.send(scraptcha.verify(req)); });
deckerld/scraptcha
test/file-server.js
JavaScript
mit
847
package observerSampleJavaAPI; import java.util.Scanner; public class Main { public static void main(String[] args) { NameArrayObservable na = new NameArrayObservable(); NameArrayObserver nav = new NameArrayObserver(); na.addObserver(nav); Scanner sc = new Scanner(System.in); System.out.print("Index (0-9): "); int index = sc.nextInt(); System.out.print("Name: "); String name = sc.next(); na.setName(name, index); } }
dmpe/Semester2and5-Examples
src-semester2/observerSampleJavaAPI/Main.java
Java
mit
467