repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
kimkulling/osre
test/UnitTests/src/Scene/DbgRendererTest.cpp
2196
/*----------------------------------------------------------------------------------------------- The MIT License (MIT) Copyright (c) 2015-2021 OSRE ( Open Source Render Engine ) by Kim Kulling 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. -----------------------------------------------------------------------------------------------*/ #include "osre_testcommon.h" #include <osre/RenderBackend/RenderBackendService.h> #include <osre/Scene/MaterialBuilder.h> #include <osre/Scene/DbgRenderer.h> namespace OSRE { namespace UnitTest { class TestRenderBackendService : public RenderBackend::RenderBackendService { public: TestRenderBackendService() : RenderBackendService() {} ~TestRenderBackendService(){} }; using namespace ::OSRE::Scene; class DbgRendererTest : public ::testing::Test { protected: void SetUp() override { MaterialBuilder::create(); } void TearDown() override { MaterialBuilder::destroy(); } }; TEST_F( DbgRendererTest, create_Success ) { RenderBackend::RenderBackendService *tstRBSrv = new TestRenderBackendService; DbgRenderer::create( tstRBSrv ); DbgRenderer::destroy(); delete tstRBSrv; } } // Namespace UnitTest } // Namespace OSRE
mit
SebSept/onemorelaravelblog
app/tests/admin/AdminModerate_DeleteCept.php
725
<?php use SebSept\OMLB\Models\Comment\Comment; use Laracasts\TestDummy\Factory; // prepare data $post = Factory::create('SebSept\OMLB\Models\Post\Post', ['published' => 1]); $comment = Laracasts\TestDummy\Factory::create('SebSept\OMLB\Models\Comment\Comment', ['post_id' => $post->id]); $I = new Admin($scenario); $I->wantTo('delete a comment'); $I->amAdmin(); // comment to moderate listed $I->amOnPage('/admin/comment/moderate'); $I->see($comment->title); $I->click('#delete_'.$comment->id); $I->see(trans('admin.comment.destroyed')); $I->seeInCurrentUrl('/admin/comment/moderate'); $I->dontSee($comment->title); // neither published on post page (post->id = 5) $I->amOnPostPage($post); $I->dontSee($comment->title);
mit
directhex/xwt
Xwt.XamMac/Xwt.Mac/TextEntryBackend.cs
6948
// // TextEntryBackend.cs // // Author: // Lluis Sanchez <lluis@xamarin.com> // // Copyright (c) 2011 Xamarin Inc // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using Xwt.Backends; using System; #if MONOMAC using nint = System.Int32; using nfloat = System.Single; using MonoMac.Foundation; using MonoMac.AppKit; #else using Foundation; using AppKit; #endif namespace Xwt.Mac { public class TextEntryBackend: ViewBackend<NSView,ITextEntryEventSink>, ITextEntryBackend { int cacheSelectionStart, cacheSelectionLength; bool checkMouseSelection; public TextEntryBackend () { } internal TextEntryBackend (MacComboBox field) { ViewObject = field; } public override void Initialize () { base.Initialize (); if (ViewObject is MacComboBox) { ((MacComboBox)ViewObject).SetEntryEventSink (EventSink); } else { var view = new CustomTextField (EventSink, ApplicationContext); ViewObject = new CustomAlignedContainer (EventSink, ApplicationContext, (NSView)view); MultiLine = false; } Frontend.MouseEntered += delegate { checkMouseSelection = true; }; Frontend.MouseExited += delegate { checkMouseSelection = false; HandleSelectionChanged (); }; Frontend.MouseMoved += delegate { if (checkMouseSelection) HandleSelectionChanged (); }; } protected override void OnSizeToFit () { Container.SizeToFit (); } CustomAlignedContainer Container { get { return base.Widget as CustomAlignedContainer; } } public new NSTextField Widget { get { return (ViewObject is MacComboBox) ? (NSTextField)ViewObject : (NSTextField) Container.Child; } } protected override Size GetNaturalSize () { var s = base.GetNaturalSize (); return new Size (EventSink.GetDefaultNaturalSize ().Width, s.Height); } #region ITextEntryBackend implementation public string Text { get { return Widget.StringValue; } set { Widget.StringValue = value ?? string.Empty; } } public Alignment TextAlignment { get { return Widget.Alignment.ToAlignment (); } set { Widget.Alignment = value.ToNSTextAlignment (); } } public bool ReadOnly { get { return !Widget.Editable; } set { Widget.Editable = !value; } } public bool ShowFrame { get { return Widget.Bordered; } set { Widget.Bordered = value; } } public string PlaceholderText { get { return ((NSTextFieldCell) Widget.Cell).PlaceholderString; } set { ((NSTextFieldCell) Widget.Cell).PlaceholderString = value; } } public bool MultiLine { get { if (Widget is MacComboBox) return false; return Widget.Cell.UsesSingleLineMode; } set { if (Widget is MacComboBox) return; if (value) { Widget.Cell.UsesSingleLineMode = false; Widget.Cell.Scrollable = false; Widget.Cell.Wraps = true; } else { Widget.Cell.UsesSingleLineMode = true; Widget.Cell.Scrollable = true; Widget.Cell.Wraps = false; } Container.ExpandVertically = value; } } public int CursorPosition { get { if (Widget.CurrentEditor == null) return 0; return (int)Widget.CurrentEditor.SelectedRange.Location; } set { Widget.CurrentEditor.SelectedRange = new NSRange (value, SelectionLength); HandleSelectionChanged (); } } public int SelectionStart { get { if (Widget.CurrentEditor == null) return 0; return (int)Widget.CurrentEditor.SelectedRange.Location; } set { Widget.CurrentEditor.SelectedRange = new NSRange (value, SelectionLength); HandleSelectionChanged (); } } public int SelectionLength { get { if (Widget.CurrentEditor == null) return 0; return (int)Widget.CurrentEditor.SelectedRange.Length; } set { Widget.CurrentEditor.SelectedRange = new NSRange (SelectionStart, value); HandleSelectionChanged (); } } public string SelectedText { get { if (Widget.CurrentEditor == null) return String.Empty; int start = SelectionStart; int end = start + SelectionLength; if (start == end) return String.Empty; try { return Text.Substring (start, end - start); } catch { return String.Empty; } } set { int cacheSelStart = SelectionStart; int pos = cacheSelStart; if (SelectionLength > 0) { Text = Text.Remove (pos, SelectionLength).Insert (pos, value); } SelectionStart = pos; SelectionLength = value.Length; HandleSelectionChanged (); } } void HandleSelectionChanged () { if (cacheSelectionStart != SelectionStart || cacheSelectionLength != SelectionLength) { cacheSelectionStart = SelectionStart; cacheSelectionLength = SelectionLength; ApplicationContext.InvokeUserCode (delegate { EventSink.OnSelectionChanged (); }); } } public override void SetFocus () { Widget.BecomeFirstResponder (); } #endregion } class CustomTextField: NSTextField, IViewObject { ITextEntryEventSink eventSink; ApplicationContext context; public CustomTextField (ITextEntryEventSink eventSink, ApplicationContext context) { this.context = context; this.eventSink = eventSink; } public NSView View { get { return this; } } public ViewBackend Backend { get; set; } public override void DidChange (NSNotification notification) { base.DidChange (notification); context.InvokeUserCode (delegate { eventSink.OnChanged (); eventSink.OnSelectionChanged (); }); } int cachedCursorPosition; public override void KeyUp (NSEvent theEvent) { base.KeyUp (theEvent); if (cachedCursorPosition != CurrentEditor.SelectedRange.Location) context.InvokeUserCode (delegate { eventSink.OnSelectionChanged (); }); cachedCursorPosition = (int)CurrentEditor.SelectedRange.Location; } } }
mit
kybarg/material-ui
packages/material-ui-icons/src/ArrowDropDownTwoTone.js
168
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M7 10l5 5 5-5H7z" /> , 'ArrowDropDownTwoTone');
mit
boomcms/boom-core
tests/Database/Models/PageTest.php
18074
<?php namespace BoomCMS\Tests\Database\Models; use BoomCMS\Database\Models\Page; use BoomCMS\Database\Models\PageVersion; use BoomCMS\Database\Models\Site; use BoomCMS\Database\Models\Tag; use BoomCMS\Database\Models\URL; use BoomCMS\Support\Helpers\URL as URLHelper; use DateTime; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Relations\BelongsToMany; use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Support\Facades\DB; use Mockery as m; class PageTest extends AbstractModelTestCase { use Traits\HasFeatureImageTests; protected $model = Page::class; public function testAclEnabled() { $values = [ null => false, 1 => true, 0 => false, ]; foreach ($values as $value => $enabled) { $page = new Page([Page::ATTR_ENABLE_ACL => $value]); $this->assertEquals($enabled, $page->aclEnabled()); } } /** * @depends testAclEnabled */ public function testSetAclEnabled() { $page = new Page(); $page->setAclEnabled(true); $this->assertTrue($page->aclEnabled()); $page->setAclEnabled(false); $this->assertFalse($page->aclEnabled()); } public function testAddAclGroupId() { $groupId = 1; $page = m::mock(Page::class)->makePartial(); $query = DB::shouldReceive('table') ->once() ->with('page_acl') ->andReturnSelf(); $query ->shouldReceive('insert') ->once() ->with([ 'page_id' => $page->getId(), 'group_id' => $groupId, ]) ->andReturnSelf(); $page->addAclGroupId($groupId); } public function testAddTag() { $tag = new Tag(); $tag->{Tag::ATTR_ID} = 1; $relation = m::mock(BelongsToMany::class); $page = m::mock(Page::class)->makePartial(); $page ->shouldReceive('tags') ->once() ->andReturn($relation); $relation ->shouldReceive('syncWithoutDetaching') ->once() ->with([$tag->getId()]); $this->assertEquals($page, $page->addTag($tag)); } public function testRemoveAclGroupId() { $groupId = 1; $page = m::mock(Page::class)->makePartial(); $query = DB::shouldReceive('table') ->once() ->with('page_acl') ->andReturnSelf(); $query ->shouldReceive('where') ->once() ->with([ 'page_id' => $page->getId(), 'group_id' => $groupId, ]) ->andReturnSelf(); $query ->shouldReceive('delete') ->once(); $page->removeAclGroupId($groupId); } public function testCanBeDeleted() { $values = [ true => false, false => true, null => true, ]; foreach ($values as $disableDelete => $canBeDeleted) { $page = new Page([Page::ATTR_DISABLE_DELETE => $disableDelete]); $this->assertEquals($canBeDeleted, $page->canBeDeleted()); } } public function testGetAclGroupIds() { $collection = collect([1, 2]); $pageId = 1; $page = m::mock(Page::class)->makePartial(); $page ->shouldReceive('getId') ->once() ->andReturn($pageId); $query = DB::shouldReceive('table') ->once() ->with('page_acl') ->andReturnSelf(); $query ->shouldReceive('select') ->once() ->with('group_id') ->andReturnSelf(); $query ->shouldReceive('where') ->once() ->with('page_id', $pageId) ->andReturnSelf(); $query ->shouldReceive('pluck') ->once() ->with('group_id') ->andReturn($collection); $page->getAclGroupIds(); } public function testGetAddPageBehaviour() { $page = new Page([Page::ATTR_ADD_BEHAVIOUR => Page::ADD_PAGE_CHILD]); $this->assertEquals(Page::ADD_PAGE_CHILD, $page->getAddPageBehaviour()); } public function testGetAddPageBehaviourDefaultIsNone() { $page = new Page(); $this->assertEquals(Page::ADD_PAGE_NONE, $page->getAddPageBehaviour()); } public function testGetChildAddPageBehaviour() { $page = new Page([Page::ATTR_CHILD_ADD_BEHAVIOUR => Page::ADD_PAGE_CHILD]); $this->assertEquals(Page::ADD_PAGE_CHILD, $page->getChildAddPageBehaviour()); } /** * The add page parent is the current page if the add page behaviour is to add a child * Or it's to add a sibling but the page doesn't have a parent. */ public function testGetAddPageParentReturnsSelf() { $page = m::mock(Page::class.'[isRoot]'); $page ->shouldReceive('isRoot') ->twice() ->andReturn(true); foreach ([Page::ADD_PAGE_CHILD, Page::ADD_PAGE_SIBLING, Page::ADD_PAGE_NONE] as $behaviour) { $page->{Page::ATTR_ADD_BEHAVIOUR} = $behaviour; $this->assertEquals($page, $page->getAddPageParent()); } } public function testGetAddPageParentReturnsItsParent() { $parent = new Page(); $page = m::mock(Page::class.'[isRoot,getParent]'); $page->{Page::ATTR_ADD_BEHAVIOUR} = Page::ADD_PAGE_SIBLING; $page ->shouldReceive('isRoot') ->once() ->andReturn(false); $page ->shouldReceive('getParent') ->once() ->andReturn($parent); $this->assertEquals($parent, $page->getAddPageParent()); } /** * getAddPageParent() should return null when the behaviour is to prompt and it doesn't have a parent * since the parent is then determined by the user response. */ public function testGetAddPageParentInheritsSettingFromParent() { $parent = new Page(); $page = m::mock(Page::class.'[isRoot,getParent]'); $values = [ Page::ADD_PAGE_CHILD => $page, Page::ADD_PAGE_SIBLING => $parent, Page::ADD_PAGE_NONE => $page, ]; $page->{Page::ATTR_ADD_BEHAVIOUR} = Page::ADD_PAGE_NONE; $page ->shouldReceive('isRoot') ->andReturn(false); $page ->shouldReceive('getParent') ->andReturn($parent); foreach ($values as $v => $addParent) { $parent->{Page::ATTR_CHILD_ADD_BEHAVIOUR} = $v; $this->assertEquals($addParent, $page->getAddPageParent()); } } public function testGetChildAddPageBehaviourDefaultIsNone() { $page = new Page(); $this->assertEquals(Page::ADD_PAGE_NONE, $page->getChildAddPageBehaviour()); } public function testGetChildOrderingPolicy() { $values = [ Page::ORDER_TITLE => ['title', 'desc'], // Default is descending Page::ORDER_TITLE | Page::ORDER_ASC => ['title', 'asc'], Page::ORDER_TITLE | Page::ORDER_DESC => ['title', 'desc'], Page::ORDER_VISIBLE_FROM | Page::ORDER_ASC => ['visible_from', 'asc'], Page::ORDER_VISIBLE_FROM | Page::ORDER_DESC => ['visible_from', 'desc'], Page::ORDER_SEQUENCE | Page::ORDER_ASC => ['sequence', 'asc'], Page::ORDER_SEQUENCE | Page::ORDER_DESC => ['sequence', 'desc'], 0 => ['sequence', 'desc'], ]; foreach ($values as $order => $expected) { $page = new Page([Page::ATTR_CHILD_ORDERING_POLICY => $order]); $this->assertEquals($expected, $page->getChildOrderingPolicy()); } } public function testGetDefaultChildTemplateIdReturnsInt() { $page = new Page(); $page->{Page::ATTR_CHILD_TEMPLATE} = '1'; $this->assertEquals(1, $page->getDefaultChildTemplateId()); $this->assertInternalType('integer', $page->getDefaultChildTemplateId()); } /** * Give a page with no parent and no default child template ID. * * getDefaultChildTemplateId should return the page's template ID */ public function testGetDefaultChildTemplateIdAtRootPage() { $page = m::mock(Page::class)->makePartial(); $page->shouldReceive('getParent')->once()->andReturnNull(); $page->shouldReceive('getTemplateId')->once()->andReturn(1); $this->assertEquals(1, $page->getDefaultChildTemplateId()); } public function testGetDefaultGrandchildTemplateIdReturnsTemplateId() { $values = [0, null, '']; $templateId = 2; $page = m::mock(Page::class)->makePartial(); $page->shouldReceive('getTemplateId')->times(3)->andReturn($templateId); foreach ($values as $grandchildTemplateId) { $page->{Page::ATTR_GRANDCHILD_TEMPLATE} = $grandchildTemplateId; $this->assertEquals($templateId, $page->getDefaultGrandchildTemplateId()); } } public function testGetDefaultGrandchildTemplateIdReturnsDefinedValue() { $values = [1, 2, 3]; $page = m::mock(Page::class)->makePartial(); $page->shouldReceive('getTemplateId')->never(); foreach ($values as $grandchildTemplateId) { $page->{Page::ATTR_GRANDCHILD_TEMPLATE} = $grandchildTemplateId; $this->assertEquals($grandchildTemplateId, $page->getDefaultGrandchildTemplateId()); } } public function testGetGrandchildTemplateIdReturnsInt() { $page = new Page(); $page->{Page::ATTR_GRANDCHILD_TEMPLATE} = '1'; $this->assertEquals(1, $page->getGrandchildTemplateId()); $this->assertInternalType('integer', $page->getGrandchildTemplateId()); } public function testGetDescriptionReturnsDescriptionIfSet() { $page = new Page([Page::ATTR_DESCRIPTION => 'test']); $this->assertEquals('test', $page->getDescription()); } public function testGetDescriptionReturnsStringIfEmpty() { $page = new Page(); $this->assertEquals('', $page->getDescription()); } public function testGetDescriptionRemovesHtml() { $page = new Page([Page::ATTR_DESCRIPTION => '<p>description</p>']); $this->assertEquals('description', $page->getDescription()); } public function testGetParentWithNoParentId() { $page = new Page([Page::ATTR_PARENT => null]); $this->assertNull($page->getParent()); } public function testGetSite() { $site = new Site(); $page = m::mock(Page::class.'[belongsTo,first]'); $page ->shouldReceive('belongsTo') ->once() ->with(Site::class, 'site_id') ->andReturnSelf(); $page ->shouldReceive('first') ->once() ->andReturn($site); $this->assertEquals($site, $page->getSite()); } public function testIsDeleted() { $values = [ 0 => false, null => false, time() => true, ]; foreach ($values as $deletedAt => $isDeleted) { $page = new Page(['deleted_at' => $deletedAt]); $this->assertEquals($isDeleted, $page->isDeleted()); } } public function testIsVisibleAtAnyTime() { $yes = [1, true]; $no = [0, false, null]; foreach ($yes as $y) { $page = new Page([Page::ATTR_VISIBLE => $y]); $this->assertTrue($page->isVisibleAtAnyTime(), $y); } foreach ($no as $n) { $page = new Page([Page::ATTR_VISIBLE => $n]); $this->assertFalse($page->isVisibleAtAnyTime(), $n); } } public function testScopeIsVisibleAtTime() { $time = time(); $query = m::mock(Builder::class); $query ->shouldReceive('where') ->once() ->with(Page::ATTR_VISIBLE, '=', true) ->andReturnSelf(); $query ->shouldReceive('where') ->once() ->with(Page::ATTR_VISIBLE_FROM, '<=', time()) ->andReturnSelf(); $query ->shouldReceive('where') ->once() ->andReturnUsing(function ($callback) use ($query) { return $callback($query); }); $query ->shouldReceive('where') ->once() ->with(Page::ATTR_VISIBLE_TO, '>=', $time) ->andReturnSelf(); $query ->shouldReceive('orWhere') ->once() ->with(Page::ATTR_VISIBLE_TO, '=', 0) ->andReturnSelf(); $page = new Page(); $page->scopeIsVisibleAtTime($query, $time); } public function testSetAddPageBehaviour() { $page = new Page(); $this->assertEquals($page, $page->setAddPageBehaviour(Page::ADD_PAGE_CHILD)); $this->assertEquals(Page::ADD_PAGE_CHILD, $page->getAddPageBehaviour()); } public function testSetChildAddPageBehaviour() { $page = new Page(); $this->assertEquals($page, $page->setChildAddPageBehaviour(Page::ADD_PAGE_CHILD)); $this->assertEquals(Page::ADD_PAGE_CHILD, $page->getChildAddPageBehaviour()); } public function testSetAndGetChildOrderingPolicy() { $values = [ ['title', 'asc'], ['title', 'desc'], ['visible_from', 'asc'], ['visible_from', 'desc'], ['sequence', 'asc'], ['sequence', 'desc'], ]; foreach ($values as $v) { list($column, $direction) = $v; $page = new Page(); $page->setChildOrderingPolicy($column, $direction); list($newCol, $newDirection) = $page->getChildOrderingPolicy(); $this->assertEquals($column, $newCol); $this->assertEquals($direction, $newDirection); } } public function testSetCurrentVersion() { $page = new Page(); $version = new PageVersion(); $this->assertEquals($page, $page->setCurrentVersion($version)); $this->assertEquals($version, $page->getCurrentVersion()); } /** * A page internal name can contain lowercase letters, underscores, hyphens, or numbers. * * All other characters should be removed. */ public function testSetInternalNameRemovesInvalidCharacters() { $page = new Page(); $values = [ '404' => '404', ' test ' => 'test', 'test' => 'test', '£$%^&*()' => '', 'TEST' => 'test', ]; foreach ($values as $in => $out) { $page->setInternalName($in); $this->assertEquals($out, $page->getInternalName()); } } public function testSetParentPageCantBeChildOfItself() { $page = new Page([Page::ATTR_PARENT => 2]); $page->{Page::ATTR_ID} = 1; $page->setParent($page); $this->assertEquals(2, $page->getParentId()); } public function testSetPrimaryUriIsSantized() { $url = '% not /// a good URL.'; $page = new Page(); $page->{Page::ATTR_PRIMARY_URI} = $url; $this->assertEquals(URLHelper::sanitise($url), $page->getAttribute(Page::ATTR_PRIMARY_URI)); } public function testSetVisibleAtAnyTime() { $values = [ 1 => true, true => true, 0 => false, false => false, ]; foreach ($values as $value => $expected) { $page = new Page(); $page->setVisibleAtAnyTime($value); $this->assertEquals($expected, $page->isVisibleAtAnyTime()); } } public function testSetVisibleFrom() { $page = new Page(); $time = new DateTime('now'); $page->setVisibleFrom($time); $this->assertEquals($time->getTimestamp(), $page->{Page::ATTR_VISIBLE_FROM}); $page->setVisibleFrom(null); $this->assertNull($page->{Page::ATTR_VISIBLE_FROM}); } public function testHasChildren() { $hasMany = m::mock(HasMany::class); $hasMany ->shouldReceive('exists') ->once() ->andReturn(false); $hasMany ->shouldReceive('exists') ->once() ->andReturn(true); $page = m::mock(Page::class)->makePartial(); $page ->shouldReceive('children') ->times(2) ->andReturn($hasMany); $this->assertFalse($page->hasChildren()); $this->assertTrue($page->hasChildren()); } public function testIsParentOf() { $parent = $this->validPage(); $child = new Page([Page::ATTR_PARENT => $parent->getId()]); $notAChild = new Page([Page::ATTR_PARENT => 2]); $this->assertTrue($parent->isParentOf($child), 'Child'); $this->assertFalse($parent->isParentOf($notAChild), 'Not child'); } public function testSetSequence() { $page = new Page(); $this->assertEquals($page, $page->setSequence(2)); $this->assertEquals(2, $page->getManualOrderPosition()); } public function testUrlReturnsNullIfNoPrimaryUri() { $page = new Page(); $this->assertNull($page->url()); } public function testUrlReturnsUrlObject() { $page = new Page([Page::ATTR_PRIMARY_URI => 'test']); $url = $page->url(); $this->assertInstanceOf(URL::class, $url); $this->assertEquals('test', $url->getLocation()); } }
mit
marcosQuesada/WhiteOctober-Admin-Generator
src/Base/TestBundle/Admin/CategoryAdmin.php
520
<?php namespace Base\TestBundle\Admin; use WhiteOctober\AdminBundle\DataManager\Doctrine\ORM\Admin\DoctrineORMAdmin; class CategoryAdmin extends DoctrineORMAdmin { protected function configure() { $this ->setName('Category') ->setDataClass('Base\TestBundle\Entity\Category') ->addActions(array( 'doctrine.orm.crud', )) ->addFields(array( 'title', 'published', )) ; } }
mit
dieggop/prefeiturasertania
app/Downloads.php
338
<?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class Downloads extends Model { use SoftDeletes; protected $table = 'downloads'; protected $fillable = ['title','arquivo','sobre','quantidade']; protected $dates = ['deleted_at','created_at','updated_at']; }
mit
SUTDMEC/TripInference
mainActivites.py
5972
import numpy as np import oldTripParse as tp import getActivities as ga import itertools ######################### # Read pilot nodes data # ######################### # 0 1 2 3 4 # Data is nid / ts / mode / lat / lon data = np.genfromtxt("pilot2_trimmed.csv", delimiter=",") data = data[1:-1,:] # Remove header nodes = np.unique(data[:,0]) # Get list of nodes length_POI_before = np.zeros(len(nodes)) # For statistical purposes, compute how many POIs we removed length_POI_after = np.zeros(len(nodes)) activity_types = ['home', 'school', 'food', 'commercial', 'sports', 'others'] num_activities = len(activity_types) ############################################# # Construct outside bounds from GIS data # # By outside we mean sports and parks # ############################################# with open('sports.json') as data_file: sports = json.load(data_file) with open('parks.json') as data_file: parks = json.load(data_file) outside_activities = sports["features"]+parks["features"] outside_bounds = [] for i in range(0, len(outside_activities)): coordinates = outside_activities[i]["geometry"]["coordinates"] chain = itertools.chain(*coordinates) # coordinates is an array with depth 4, for some reason, so we flatten it chain = itertools.chain(*list(chain)) coordinates = list(chain) bounds = ga.getBounds(coordinates) if max(abs(bounds[0][0]-bounds[1][0]), abs(bounds[0][1]-bounds[1][1])) < 0.1: # remove absurd bounding boxes outside_bounds += [bounds] ################### # Node processing # ################### for i in range(0, len(nodes)): # Iterate over nodes nid = nodes[i] cur_data = data[data[:,0]==nid,:] # Get data associated to nid t = cur_data[:, 1] lat = cur_data[:, 3] lon = cur_data[:, 4] mode = cur_data[:, 2] # tripParse takes args t, lat, lon, mode (POI_final, trip_store, vel, trip_dist, latlon_school, latlon_home, school_home_dist) = tp.tripParse(t, lat, lon, mode) if POI_final[0] == [None] or len(POI_final[0]) != 1: POI_final[0] = [] if POI_final[1] == [None] or len(POI_final[1]) != 1: POI_final[1] = [] print "-------------------------" print i length_POI_before[i] = len(POI_final[0])+len(POI_final[1])+len(POI_final[2]) POI = ga.separatePOI(POI_final, 75) # Reduce POIs to avoid redundancies length_POI_after[i] = len(POI[0])+len(POI[1])+len(POI[2]) list_POI = POI[0]+POI[1]+POI[2] # Flatten POI_final array (easier)... index_POI = range(0, len(POI[0])) + range(1, len(POI[1])+1) + range(2, len(POI[2])+2) # ... but keep track of indices with index_POI activities = [] print list_POI if len(list_POI) > 0: for j in range(0, len(list_POI)): # Build coefficients dictionary that weighs different activity options if index_POI[j] == 0: activities += ["home"] elif index_POI[j] == 1: activities += ["school"] else: (lat, lon) = list_POI[j] coefs = { "food": 0, "commercial": 0, "sports": 0 } # If we can assert that a point is inside a park or a sports installation, then we weigh the sports item a lot if ga.pointOutside([lat, lon], outside_bounds) == True: coefs["sports"] += 10 # Google Places request types = ['store', 'park', 'restaurant', 'gym', 'food'] radius = 50 results = ga.getPlaces(lat, lon, radius, types) for k in range(0, len(results)): result = results[k] distance_from_point = tp.distance_on_earth(lat, lon, result["geometry"]["location"]["lat"], result["geometry"]["location"]["lng"]) distance_from_point = min(radius, distance_from_point) for t in result["types"]: # Weight decreases as distance from point increases if t == "store": coefs["commercial"] += 2*(1-distance_from_point/radius) if t == "food" or t == "restaurant": coefs["food"] += 1*(1-distance_from_point/radius) if t == "park" or t == "gym": coefs["sports"] += 2*(1-distance_from_point/radius) # If Google Places returned good results, we select the one with the highest weight if max(coefs.values()) > 0: max_coef = ga.maxValueInDict(coefs) activities += [max_coef] else: # Otherwise, we file it under "others" activities += ["others"] # Build trip matrix for chord diagram (trips, ft) = ga.processTrips(trip_store, list_POI) trip_matrix = np.zeros((num_activities, num_activities)) # we have 6 different activities home/school/food/commercial/sports/others for j in range(0, len(trips)): trip_matrix[activity_types.index(activities[trips[j][0]]), activity_types.index(activities[trips[j][1]])] += 1.0 # Save trip matrices and POI lat/lon + assigned activity np.savetxt("trip_matrices/"+str(int(nid))+".csv", trip_matrix) act_index = [activity_types.index(activities[j]) for j in range(0, len(activities))] # index in act_types array np_act = np.array(act_index) np_act = np.reshape(np_act, (len(np_act),1)) POI = np.hstack([np.array(list_POI), np_act]) # POI associated with their activities np.savetxt("POI/"+str(int(nid))+".csv", POI) # How many POIs we are throwing away with our separatePOI function (at least half it turns out, for threshold of 50 meters!) ratios_length = np.divide(length_POI_after, length_POI_before) ratios_length = ratios_length[~np.isnan(ratios_length)] percentage_remaining = sum(ratios_length)/len(ratios_length)*100
mit
podefr/es6-fun
arrow-function.js
357
// Use with traceur: traceur arrow-function.js --experimental "use strict"; function Klass() { this.value = 2; this.test = (p, q = 6) => p * q * this.value; this.rest = (first, ...otherParams) => console.log(otherParams); } var klass = new Klass(); console.log(klass.test(3)); console.log(klass.rest("test", "other test", "last param"));
mit
UmassJin/Leetcode
LintCode/Count of Smaller Number.py
1705
''' Give you an integer array (index from 0 to n-1, where n is the size of this array, value from 0 to 10000) and an query list. For each query, give you an integer, return the number of element in the array that are smaller that the given integer. Have you met this question in a real interview? Yes Example For array [1,2,7,8,5], and queries [1,8,5], return [0,4,2] Note We suggest you finish problem Segment Tree Build and Segment Tree Query II first. Challenge Could you use three ways to do it. Just loop Sort and binary search Build Segment Tree and Search. ''' class Solution: """ @param A: A list of integer @return: The number of element in the array that are smaller that the given integer """ def countOfSmallerNumber(self, A, queries): if not queries: return [] if not A: return [0 for i in xrange(len(queries))] A.sort() n = len(A) result = [] for i in xrange(len(queries)): if len(A) == 0 or A[-1] < queries[i]: # Here we check if the A[-1] is larger than the queries[i] result.append(len(A)) continue left = 0; right = n-1 subres = 0 while left < right - 1: # Here we need to seperate left, right, could not use left <= right mid = (left + right) / 2 if queries[i] > A[mid]: left = mid elif queries[i] <= A[mid]: right = mid if A[left] >= queries[i]: subres = left elif A[right] >= queries[i]: subres = right result.append(subres) return result
mit
Azure/azure-sdk-for-ruby
management/azure_mgmt_network/lib/2018-12-01/generated/azure_mgmt_network/models/ddos_settings.rb
1758
# encoding: utf-8 # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::Network::Mgmt::V2018_12_01 module Models # # Contains the DDoS protection settings of the public IP. # class DdosSettings include MsRestAzure # @return [SubResource] The DDoS custom policy associated with the public # IP. attr_accessor :ddos_custom_policy # @return [Enum] The DDoS protection policy customizability of the public # IP. Only standard coverage will have the ability to be customized. # Possible values include: 'Basic', 'Standard' attr_accessor :protection_coverage # # Mapper for DdosSettings class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'DdosSettings', type: { name: 'Composite', class_name: 'DdosSettings', model_properties: { ddos_custom_policy: { client_side_validation: true, required: false, serialized_name: 'ddosCustomPolicy', type: { name: 'Composite', class_name: 'SubResource' } }, protection_coverage: { client_side_validation: true, required: false, serialized_name: 'protectionCoverage', type: { name: 'String' } } } } } end end end end
mit
martyndavies/cmdgrid
lib/cmdgrid.js
6272
#!/usr/bin/env node var program = require('commander'), Table = require('cli-table'), request = require('request'); var username, pwd, optionsString; var table = new Table({ head: ['#', 'Hostname', 'URL', 'Spam Check?'] , colWidths: [5, 20, 50, 15] }); function errorCatcher(){ console.log('\033[31mThere was an error connecting to SendGrid. Please try your request again.\033[39m\n'); } // Generic logging in function loginAndRequest(endpoint, options, callback){ 'use strict'; if (options){ if(!options.spam){ options.spamcheck = '0'; } else if (options.spam === 'on' || options.spam === 'On'){ options.spamcheck = '1'; } else { options.spam = '1'; } if (!options.endpoint) { var optionsString = '&hostname='+options.hostname; } else { var optionsString = '&hostname='+options.hostname+'&url='+options.endpoint+'&spam_check='+options.spamcheck; } } request('https://sendgrid.com/api/'+endpoint+'.json?api_user='+username+'&api_key='+pwd+optionsString, function (error, response, body) { if (!error && response.statusCode === 200) { callback(error, body); } else { callback(error); } }); } function perform(action, hostname, endpoint, spam){ program.prompt('Username: ', function(inputName){ username = inputName; program.password('Password: ', ' ', function(inputPassword){ pwd = inputPassword; process.stdin.destroy(); // This is a massive hack, that deletes the record, then replaces it with updated information // because the update endpoint doesn't work... :( if (action === 'parse.update'){ loginAndRequest('parse.delete', {hostname: hostname}, function(error, body){ if (!body) { errorCatcher(); } else { var res = JSON.parse(body); if (res.error){ console.log('\033[31m'+res.error.message+'\033[39m\n'); } else if (res.message === 'error'){ console.log('\033[31mSorry, '+res.errors[0]+'\033[39m\n'); } else if (res.message === 'success') { loginAndRequest('parse.set', {hostname: hostname, endpoint: endpoint, spam: spam}, function(error, body){ if (!body) { errorCatcher(); } else { var res = JSON.parse(body); if (res.error){ console.log('\033[31m'+res.error.message+'\033[39m\n'); } else if (res.message === 'error'){ console.log('\033[31mSorry, '+res.errors[0]+'\033[39m\n'); } else if (res.message === 'success') { console.log('\n\033[32mSuccessfully updated '+hostname+' to '+endpoint+'!\033[39m\n'); } else { console.log('\033[31mSo much error! '+res.error+'\033[39m\n'); } } }); } else { console.log('\033[31mSo much error! '+res.error+'\033[39m\n'); } } }); } else { loginAndRequest(action, {hostname: hostname, endpoint: endpoint, spam: spam}, function(error, body){ if (!body) { errorCatcher(); } else { var res = JSON.parse(body); if (res.error){ console.log('\033[31m'+res.error.message+'\033[39m\n'); } else if (res.message === 'error'){ console.log('\033[31mSorry, '+res.errors[0]+'\033[39m\n'); } else if (res.message === 'success') { if (action === 'parse.delete'){ console.log('\n\033[32mSuccessfully removed '+hostname+' and its settings\033[39m\n'); } else { console.log('\n\033[32mSuccessfully pointed '+hostname+' to '+endpoint+'!\033[39m\n'); console.log('\033[35mNOTE:\033[39m\r'); console.log('\033[35mTo complete the setup, add an MX record to the DNS for '+hostname+' and point it to mx.sendgrid.net\033[39m\n'); } } else { console.log('\033[31mSo much error! '+res.error+'\033[39m\n'); } } }); } }); }); } program .version('0.0.1') .option('-p, --parse <option>', '[add|update|delete|list] a new Parse API setting') .option('-u, --url <url>', 'specify a url endpoint') .option('-h, --hostname <url>', 'specify a hostname') .option('-s, --spamcheck <option>', 'specify if spam checking is to be performed (on|off)', 'on') .parse(process.argv); if(program.parse === 'add') { console.log('Adding a new hostname to the Parse API\n'); if(program.hostname && program.url) { if (program.spamcheck) { perform('parse.set', program.hostname, program.url, program.spamcheck); } else { perform('parse.set', program.hostname, program.url); } } } else if (program.parse === 'update') { console.log('Updating details for '+program.hostname+' using the Parse API\n'); if(program.hostname && program.url) { if (program.spamcheck) { perform('parse.update', program.hostname, program.url, program.spamcheck); } else { perform('parse.update', program.hostname, program.url); } } } else if (program.parse === 'delete') { console.log('Removing '+program.hostname+' and all settings (you can confirm this again before action is taken!\n'); if(program.hostname) { program.confirm('Are you sure you want to delete the settings for '+program.hostname, function(ok){ if (ok === true) { console.log('Deleting '+ program.hostname); perform('parse.delete', program.hostname); } else { console.log('Right, we\'ll just forget you mentioned it then...\n'); process.stdin.destroy(); } }); } } else if (program.parse === 'list'){ console.log('Listing all your Parse API settings...\n'); program.prompt('Username: ', function(inputName){ username = inputName; program.password('Password: ', ' ', function(inputPassword){ pwd = inputPassword; process.stdin.destroy(); loginAndRequest('parse.get',{},function(err, body){ if (!body || err){ errorCatcher(); } else { var res = JSON.parse(body); if (res.error){ console.log('\033[31m'+res.error.message+'\033[39m\n'); } else if (res.message === 'error'){ console.log('\033[31mSorry, '+res.errors[0]+'\033[39m\n'); } else { for (var i=0; i < res.parse.length; i++) { var spamCheck = res.parse[i].spam_check === 0 ? 'Off' : 'On'; table.push([i+1, res.parse[i].hostname, res.parse[i].url, spamCheck]); } console.log(table.toString()); } } }); }); }); } else { program.outputHelp(); }
mit
alucidwolf/alucidwolf.github.io
tinymce/onclick.js
12795
function activateTinyEditor(el) { if ($(el).hasClass('is-editable')) { //console.log(el); var selectorTinyId = el.id; var selectorTiny = "#" + selectorTinyId; //console.log(selectorTinyId); //console.log(selectorTiny); // remove other editors from being active // var allEditorsTinyIds = $('.is-editable').map(function () { // return this.id // }).get(); // allEditorsTinyIds.map(function (item) { // if (item !== selectorTinyId) { // var itemToRemove = "#" + item; // tinymce.remove(itemToRemove) // } // }) tinymce.init({ selector: selectorTiny, toolbar: 'storedcontent newdocument bold italic underline', menubar: false, inline: true, mobile: { theme: 'mobile', toolbar: ['undo', 'bold'] }, // custom menu button for stored content setup: function (editor) { editor.addButton('storedcontent', { type: 'menubutton', text: 'Stored Content', icon: false, menu: [{ text: 'Sallys Paragraph', onclick: function () { var content = `<p>&nbsp;</p> <p align="center"><strong style="color: #000080;">WHY BIRMINGHAM?</strong></p> <p>The <strong>largest</strong> British City outside of London: - UK Central - <a target="_blank" href="http://birminghamtoolkit.com/">Find out more</a><br /> </p> <p>International Airport: -<span> </span>18 <strong>US Destinations</strong>; 110&nbsp;Worldwide <a target="_blank" href="http://www.want2gothere.com/bhx/destinations/">destinations</a>&nbsp;</p> <p><a target="_blank" href="http://visitbirmingham.com/what-to-do/attractions/">Attractions</a>:&nbsp;Stratford &#8211;upon- Avon (Birthplace of <strong>William Shakespeare</strong>) Edgbaston Cricket Ground, Birmingham Library (Europe&#8217;s Largest) Barclaycard Arena (host of the 2016 Davis Cup)</p> <p>Reknowned for <strong><a target="_blank" href="http://www.meetbirmingham.com/">Business Tourism</a></strong>:&nbsp;National Exhibition Centre, Resort World entertainment complex</p> <p>Did you know? Birmingham has more canals than <strong>Venice.</strong></p> <p>A London style Hotel in the provinces, <strong>without the</strong> London prices and with ease of access on a secure site. - <a target="_blank" href="http://connectplusathiltonworldwide.com/property/hilton-birmingham-metropole-hotel/">Discover Hilton Birmingham Metropole</a>&nbsp;</p> <p align="center"><strong><span style="color: #000080;">WHY HILTON BIRMINGHAM METROPOLE?</span></strong></p> <p>62904&nbsp;&nbsp; Total square feet of event space</p> <p>2000&nbsp;&nbsp; &nbsp; Successful events hosted&nbsp;each year</p> <p>790&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; Guest rooms and suites</p> <p>33&nbsp;&nbsp; &nbsp;&nbsp; &nbsp;&nbsp; Flexible event space</p> <p>3&nbsp;&nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp; Dining experiences</p> <p>1&nbsp;&nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp; LivingWell Health Club and The Ocean Rooms Spa</p> <p>&nbsp;</p> <p><span style="font-size:12.0pt;line-height:115%;font-family: " times="" new="" roman","serif";="" roman";"="">Easily accessible by rail, road and air networks and located next to the National Exhibition Centre, we are at the hub that connects Birmingham International Airport with the International Railway station with the M42, M6 and M40. Regular complimentary transport ensures your guests will only be minutes from the airport and railway station.<br /> <br /> Hilton Birmingham Metropole sets the stage for business events with impact and social occasions that are memorable. Our prime location allows you and your delegates to explore some of the best there is to see in the United Kingdom, from the bustling city centre of Birmingham, to historic locations such as Warwick Castle or even the famous Cadbury World.<br /> </span>&nbsp; </p> <p><span style="font-size:12.0pt;line-height:115%;font-family: " times="" new="" roman","serif";="" roman";"="">Where connections are made and partnerships forged. Where productive days lead to constructive results. And where our expertise is your guarantee of success. Where it all happens: Hilton Birmingham Metropole &#8211; the heart of exceptional service in the heart of England, and in one of the most accessible cities in Europe. This is where a passionate and creative team make the incredible happen every day, and make your conference, meeting or event, the best one ever.</span></p> <p><span id="ctl00_ctl00_MainContent_MainContent_rptParaType_ctl00_rptParagraphs_ctl01_lblContents"><span id="ctl00_ctl00_MainContent_MainContent__dataListRB_ctl01_lbContent"><br /> </span></span></p> <div>Please take a moment to review the links above for a comprehensive overview of our hotel offerings.</div> <p>&nbsp;</p>` editor.insertContent(content); } }, { text: 'Bryce\'s Paragraph', onclick: function () { var content = `<p style="line-height: normal;"><span style="font-family: &quot;Verdana&quot;,&quot;sans-serif&quot;; font-size: 9pt;">Thank you for your interest in the <hilton brighton="" metropole="" hotel=""> we are delighted that you are considering us for your forthcoming event. </hilton></span></p> <p style="line-height: normal;">&nbsp;</p> <p style="line-height: normal;"><strong><span style="font-family: &quot;Verdana&quot;,&quot;sans-serif&quot;; font-size: 9pt;">Why Hilton?</span></strong><span style="font-family: &quot;Verdana&quot;,&quot;sans-serif&quot;; font-size: 9pt;"> <hilton brighton="" metropole="" hotel=""> <the perfect="" hotel="" for="" your="" small="" business="" needs.&#160; private="" meeting="" rooms,="" many="" with="" direct="" sea="" views="" enabling="" delegates="" to="" feel="" relaxed="" and="" stress="" free="" whilst="" attending="" a="" at="" the="" hotel.&#160; conveniently="" located="" in="" central="" brighton="" on="" seafront,="" close="" all="" transport="" links="" amenities.="" &#160; the="" rooms="" are="" quiet="" area="" of="" be="" great="" success.&#160; innovative="" catering="" options="" available="" ensuring="" guests="" fulfilled="" throughout="" day.=""> </the></hilton></span></p> <p style="line-height: normal;">&nbsp;</p> <p style="line-height: normal;"><span style="font-family: &quot;Verdana&quot;,&quot;sans-serif&quot;; font-size: 9pt;">We would be happy to offer the <insert name="" of="" room="">for your meeting on <insert date="" &="" times="">. </insert></insert></span></p> <p style="line-height: normal;">&nbsp;</p> <p style="line-height: normal;"><span style="font-family: &quot;Verdana&quot;,&quot;sans-serif&quot;; font-size: 9pt;">We could offer you our meeting simplified rate which includes: </span></p> <p style="line-height: normal;">&nbsp;</p> <p style="line-height: normal;"><span style="font-family: &quot;Verdana&quot;,&quot;sans-serif&quot;; font-size: 9pt;">Free Wi-Fi internet access </span></p> <p style="line-height: normal;"><span style="font-family: &quot;Verdana&quot;,&quot;sans-serif&quot;; font-size: 9pt;">Two servings of tea/coffee with refreshments </span></p> <p style="line-height: normal;"><span style="font-family: &quot;Verdana&quot;,&quot;sans-serif&quot;; font-size: 9pt;">Two course lunch </span></p> <p style="line-height: normal;"><span style="font-family: &quot;Verdana&quot;,&quot;sans-serif&quot;; font-size: 9pt;">LCD Projector &amp; Screen </span></p> <p style="line-height: normal;"><span style="font-family: &quot;Verdana&quot;,&quot;sans-serif&quot;; font-size: 9pt;">A flipchart Complimentary stationery for the delegates </span></p> <p style="line-height: normal;"><span style="font-family: &quot;Verdana&quot;,&quot;sans-serif&quot;; font-size: 9pt;">24 hour cancellation </span></p> <p style="line-height: normal;">&nbsp;</p> <p style="line-height: normal;"><span style="font-family: &quot;Verdana&quot;,&quot;sans-serif&quot;; font-size: 9pt;">The rate we could offer for the above date is <insert rate=""> inc VAT per person. </insert></span></p> <p style="line-height: normal;">&nbsp;</p> <p style="line-height: normal;"><strong><span style="font-family: &quot;Verdana&quot;,&quot;sans-serif&quot;; font-size: 9pt;">Our additional recommendations</span></strong><span style="font-family: &quot;Verdana&quot;,&quot;sans-serif&quot;; font-size: 9pt;"> &lt; Treat your guests to a sumptuous afternoon tea - served in your meeting room or our Waterhouse Bar &amp; Terrace, or celebrate a milestone in your company with some enticing cocktails using Brighton Gin, or Brighton Bier, the perfect end to your day &gt; </span></p> <p style="line-height: normal;"><span style="font-family: &quot;Verdana&quot;,&quot;sans-serif&quot;; font-size: 9pt;">&nbsp;<a name="_GoBack" style='width: 20px; height: 20px; text-indent: 20px; background-image: url("/CuteSoft_Client/CuteEditor/Load.ashx?type=image&file=anchor.gif"); background-repeat: no-repeat;'></a></span></p> <p style="line-height: normal;"><span style="font-family: &quot;Verdana&quot;,&quot;sans-serif&quot;; font-size: 9pt;">As agreed we are currently holding a provisional booking for you, which will be held until <insert date="">. Should we receive another enquiry for these dates within this period, we will contact you to discuss whether you would like to proceed with the booking and we may require a signed contract from you in order to continue holding the space. </insert></span></p> <p style="line-height: normal;">&nbsp;</p> <p style="line-height: normal;"><span style="font-family: &quot;Verdana&quot;,&quot;sans-serif&quot;; font-size: 9pt;">OR <remove either="" above="" or="" below="" as="" appropriate=""> </remove></span></p> <p style="line-height: normal;">&nbsp;</p> <p style="line-height: normal;"><span style="font-family: &quot;Verdana&quot;,&quot;sans-serif&quot;; font-size: 9pt;">As agreed we are not currently holding a provisional booking for you, and whilst the dates are currently available we cannot guarantee the same space or rates being offered in the future.&nbsp;</span></p> <p style="line-height: normal;">&nbsp;</p> <p style="line-height: normal;"><span style="font-family: &quot;Verdana&quot;,&quot;sans-serif&quot;; font-size: 9pt;">&nbsp;If you would like to come and view our facilities, or discuss your booking in person, I will be happy to make the arrangements for you. </span></p> <p style="line-height: normal;">&nbsp;</p> <p style="line-height: normal;"><span style="font-family: &quot;Verdana&quot;,&quot;sans-serif&quot;; font-size: 9pt;">Many Thanks, </span></p>` editor.insertContent(content); } }] }) }, init_instance_callback: function (editor) { // remove editor when it loses focus // editor.on('blur', function (e) { // console.log('Element Clicked: ', e.target.id); // var editorTinyToRemove = "#" + e.target.id; // tinymce.remove(editorTinyToRemove) // }) // get content from editor when it loses focus editor.on('GetContent', function (e) { console.log(e.content); }) } }) } }
mit
D10221/ng-shell
test/view2/view2_test.js
323
'use strict'; describe('ngShell.view2 module', function() { beforeEach(module('ngShell.view2')); describe('view2 controller', function(){ it('should ....', inject(function($controller) { //spec body var view2Ctrl = $controller('View2Ctrl'); expect(view2Ctrl).toBeDefined(); })); }); });
mit
wknishio/variable-terminal
src/lanterna/com/googlecode/lanterna/input/KeyStroke.java
15442
/* * This file is part of lanterna (https://github.com/mabe02/lanterna). * * lanterna is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Copyright (C) 2010-2020 Martin Berglund */ package com.googlecode.lanterna.input; import java.util.ArrayList; import java.util.Arrays; /** * Represents the user pressing a key on the keyboard. If the user held down ctrl and/or alt before pressing the key, * this may be recorded in this class, depending on the terminal implementation and if such information in available. * KeyStroke objects are normally constructed by a KeyDecodingProfile, which works off a character stream that likely * coming from the system's standard input. Because of this, the class can only represent what can be read and * interpreted from the input stream; for example, certain key-combinations like ctrl+i is indistinguishable from a tab * key press. * <p> * Use the <tt>keyType</tt> field to determine what kind of key was pressed. For ordinary letters, numbers and symbols, the * <tt>keyType</tt> will be <tt>KeyType.Character</tt> and the actual character value of the key is in the * <tt>character</tt> field. Please note that return (\n) and tab (\t) are not sorted under type <tt>KeyType.Character</tt> * but <tt>KeyType.Enter</tt> and <tt>KeyType.Tab</tt> instead. * @author martin */ public class KeyStroke { private final KeyType keyType; private final Character character; private final boolean ctrlDown; private final boolean altDown; private final boolean shiftDown; private final long eventTime; public KeyStroke(KeyType keyType) { this(keyType, null, false, false, false); } /** * Constructs a KeyStroke based on a supplied keyType; character will be null. * If you try to construct a KeyStroke with type KeyType.Character with this constructor, it * will always throw an exception; use another overload that allows you to specify the character value instead. * @param keyType Type of the key pressed by this keystroke * @param ctrlDown Was ctrl held down when the main key was pressed? * @param altDown Was alt held down when the main key was pressed? */ public KeyStroke(KeyType keyType, boolean ctrlDown, boolean altDown) { this(keyType, null, ctrlDown, altDown, false); } /** * Constructs a KeyStroke based on a supplied keyType; character will be null. * If you try to construct a KeyStroke with type KeyType.Character with this constructor, it * will always throw an exception; use another overload that allows you to specify the character value instead. * @param keyType Type of the key pressed by this keystroke * @param ctrlDown Was ctrl held down when the main key was pressed? * @param altDown Was alt held down when the main key was pressed? * @param shiftDown Was shift held down when the main key was pressed? */ public KeyStroke(KeyType keyType, boolean ctrlDown, boolean altDown, boolean shiftDown) { this(keyType, null, ctrlDown, altDown, shiftDown); } /** * Constructs a KeyStroke based on a supplied character, keyType is implicitly KeyType.Character. * <p> * A character-based KeyStroke does not support the shiftDown flag, as the shift state has * already been accounted for in the character itself, depending on user's keyboard layout. * @param character Character that was typed on the keyboard * @param ctrlDown Was ctrl held down when the main key was pressed? * @param altDown Was alt held down when the main key was pressed? */ public KeyStroke(Character character, boolean ctrlDown, boolean altDown) { this(KeyType.Character, character, ctrlDown, altDown, false); } /** * Constructs a KeyStroke based on a supplied character, keyType is implicitly KeyType.Character. * <p> * A character-based KeyStroke does not support the shiftDown flag, as the shift state has * already been accounted for in the character itself, depending on user's keyboard layout. * @param character Character that was typed on the keyboard * @param ctrlDown Was ctrl held down when the main key was pressed? * @param altDown Was alt held down when the main key was pressed? * @param shiftDown Was shift held down when the main key was pressed? */ public KeyStroke(Character character, boolean ctrlDown, boolean altDown, boolean shiftDown) { this(KeyType.Character, character, ctrlDown, altDown, shiftDown); } private KeyStroke(KeyType keyType, Character character, boolean ctrlDown, boolean altDown, boolean shiftDown) { if(keyType == KeyType.Character && character == null) { throw new IllegalArgumentException("Cannot construct a KeyStroke with type KeyType.Character but no character information"); } //Enforce character for some key types switch(keyType) { case Backspace: character = '\b'; break; case Enter: character = '\n'; break; case Tab: character = '\t'; break; default: } this.keyType = keyType; this.character = character; this.shiftDown = shiftDown; this.ctrlDown = ctrlDown; this.altDown = altDown; this.eventTime = System.currentTimeMillis(); } /** * an F3-KeyStroke that is distinguishable from a CursorLocation report. */ public static class RealF3 extends KeyStroke { public RealF3() { super(KeyType.F3,false,false,false); } } /** * Type of key that was pressed on the keyboard, as represented by the KeyType enum. If the value if * KeyType.Character, you need to call getCharacter() to find out which letter, number or symbol that was actually * pressed. * @return Type of key on the keyboard that was pressed */ public KeyType getKeyType() { return keyType; } /** * For keystrokes of ordinary keys (letters, digits, symbols), this method returns the actual character value of the * key. For all other key types, it returns null. * @return Character value of the key pressed, or null if it was a special key */ public Character getCharacter() { return character; } /** * @return Returns true if ctrl was help down while the key was typed (depending on terminal implementation) */ public boolean isCtrlDown() { return ctrlDown; } /** * @return Returns true if alt was help down while the key was typed (depending on terminal implementation) */ public boolean isAltDown() { return altDown; } /** * @return Returns true if shift was help down while the key was typed (depending on terminal implementation) */ public boolean isShiftDown() { return shiftDown; } /** * Gets the time when the keystroke was recorded. This isn't necessarily the time the keystroke happened, but when * Lanterna received the event, so it may not be accurate down to the millisecond. * @return The unix time of when the keystroke happened, in milliseconds */ public long getEventTime() { return eventTime; } public String toString() { StringBuilder sb = new StringBuilder(); sb.append("KeyStroke{keytype=").append(keyType); if (character != null) { char ch = character; sb.append(", character='"); switch (ch) { // many of these cases can only happen through user code: case 0x00: sb.append("^@"); break; case 0x08: sb.append("\\b"); break; case 0x09: sb.append("\\t"); break; case 0x0a: sb.append("\\n"); break; case 0x0d: sb.append("\\r"); break; case 0x1b: sb.append("^["); break; case 0x1c: sb.append("^\\"); break; case 0x1d: sb.append("^]"); break; case 0x1e: sb.append("^^"); break; case 0x1f: sb.append("^_"); break; default: if (ch <= 26) { sb.append('^').append((char)(ch+64)); } else { sb.append(ch); } } sb.append('\''); } if (ctrlDown || altDown || shiftDown) { String sep=""; sb.append(", modifiers=["); if (ctrlDown) { sb.append(sep).append("ctrl"); sep=","; } if (altDown) { sb.append(sep).append("alt"); sep=","; } if (shiftDown) { sb.append(sep).append("shift"); sep=","; } sb.append("]"); } return sb.append('}').toString(); } public int hashCode() { int hash = 3; hash = 41 * hash + (this.keyType != null ? this.keyType.hashCode() : 0); hash = 41 * hash + (this.character != null ? this.character.hashCode() : 0); hash = 41 * hash + (this.ctrlDown ? 1 : 0); hash = 41 * hash + (this.altDown ? 1 : 0); hash = 41 * hash + (this.shiftDown ? 1 : 0); return hash; } @SuppressWarnings("SimplifiableIfStatement") public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final KeyStroke other = (KeyStroke) obj; if (this.keyType != other.keyType) { return false; } if (this.character != other.character && (this.character == null || !this.character.equals(other.character))) { return false; } return this.ctrlDown == other.ctrlDown && this.altDown == other.altDown && this.shiftDown == other.shiftDown; } /** * Creates a Key from a string representation in Vim's key notation. * * @param keyStr the string representation of this key * @return the created {@link KeyType} */ public static KeyStroke fromString(String keyStr) { String keyStrLC = keyStr.toLowerCase(); KeyStroke k; if (keyStr.length() == 1) { k = new KeyStroke(KeyType.Character, keyStr.charAt(0), false, false, false); } else if (keyStr.startsWith("<") && keyStr.endsWith(">")) { if (keyStrLC.equals("<s-tab>")) { k = new KeyStroke(KeyType.ReverseTab); } else if (keyStr.contains("-")) { ArrayList<String> segments = new ArrayList<String>(Arrays.asList(keyStr.substring(1, keyStr.length() - 1).split("-"))); if (segments.size() < 2) { throw new IllegalArgumentException("Invalid vim notation: " + keyStr); } String characterStr = segments.remove(segments.size() - 1); boolean altPressed = false; boolean ctrlPressed = false; for (String modifier : segments) { if ("c".equals(modifier.toLowerCase())) { ctrlPressed = true; } else if ("a".equals(modifier.toLowerCase())) { altPressed = true; } else if ("s".equals(modifier.toLowerCase())) { characterStr = characterStr.toUpperCase(); } } k = new KeyStroke(characterStr.charAt(0), ctrlPressed, altPressed); } else { if (keyStrLC.startsWith("<esc")) { k = new KeyStroke(KeyType.Escape); } else if (keyStrLC.equals("<cr>") || keyStrLC.equals("<enter>") || keyStrLC.equals("<return>")) { k = new KeyStroke(KeyType.Enter); } else if (keyStrLC.equals("<bs>")) { k = new KeyStroke(KeyType.Backspace); } else if (keyStrLC.equals("<tab>")) { k = new KeyStroke(KeyType.Tab); } else if (keyStrLC.equals("<space>")) { k = new KeyStroke(' ', false, false); } else if (keyStrLC.equals("<up>")) { k = new KeyStroke(KeyType.ArrowUp); } else if (keyStrLC.equals("<down>")) { k = new KeyStroke(KeyType.ArrowDown); } else if (keyStrLC.equals("<left>")) { k = new KeyStroke(KeyType.ArrowLeft); } else if (keyStrLC.equals("<right>")) { k = new KeyStroke(KeyType.ArrowRight); } else if (keyStrLC.equals("<insert>")) { k = new KeyStroke(KeyType.Insert); } else if (keyStrLC.equals("<del>")) { k = new KeyStroke(KeyType.Delete); } else if (keyStrLC.equals("<home>")) { k = new KeyStroke(KeyType.Home); } else if (keyStrLC.equals("<end>")) { k = new KeyStroke(KeyType.End); } else if (keyStrLC.equals("<pageup>")) { k = new KeyStroke(KeyType.PageUp); } else if (keyStrLC.equals("<pagedown>")) { k = new KeyStroke(KeyType.PageDown); } else if (keyStrLC.equals("<f1>")) { k = new KeyStroke(KeyType.F1); } else if (keyStrLC.equals("<f2>")) { k = new KeyStroke(KeyType.F2); } else if (keyStrLC.equals("<f3>")) { k = new KeyStroke(KeyType.F3); } else if (keyStrLC.equals("<f4>")) { k = new KeyStroke(KeyType.F4); } else if (keyStrLC.equals("<f5>")) { k = new KeyStroke(KeyType.F5); } else if (keyStrLC.equals("<f6>")) { k = new KeyStroke(KeyType.F6); } else if (keyStrLC.equals("<f7>")) { k = new KeyStroke(KeyType.F7); } else if (keyStrLC.equals("<f8>")) { k = new KeyStroke(KeyType.F8); } else if (keyStrLC.equals("<f9>")) { k = new KeyStroke(KeyType.F9); } else if (keyStrLC.equals("<f10>")) { k = new KeyStroke(KeyType.F10); } else if (keyStrLC.equals("<f11>")) { k = new KeyStroke(KeyType.F11); } else if (keyStrLC.equals("<f12>")) { k = new KeyStroke(KeyType.F12); } else { throw new IllegalArgumentException("Invalid vim notation: " + keyStr); } } } else { throw new IllegalArgumentException("Invalid vim notation: " + keyStr); } return k; } }
mit
madhusudhand/markdown-docs
src/app/offline/doc-nav/doc-nav.component.ts
477
import { Component, OnInit, Input } from '@angular/core'; import {MarkdownService} from '../../markdown/markdown.service'; @Component({ selector: 'app-doc-nav', templateUrl: './doc-nav.component.html', styleUrls: ['./doc-nav.component.scss'] }) export class DocNavComponent implements OnInit { @Input() markup: any; constructor(private mdService: MarkdownService) { } ngOnInit() { } onMenuSelection(item) { this.mdService.currentMarkUpItem = item; } }
mit
dibley1973/UnityStateManager
Assets/Scripts/StateManager/State.cs
2969
using Assets.Scripts.StateManager; using Dibware.UnityStateManager.Assets.Scripts.Resources; using UnityEngine; namespace Dibware.UnityStateManager.Assets.Scripts.StateManager { /// <summary> /// The State object follows a singleton pattern to ensure there is only ever /// one instant of any of the StateManagers /// </summary> public class State : MonoBehaviour { #region Fields /// <summary> /// Holds the static game manager instance. /// </summary> private static GameManager _gameManagerInstance = null; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="State"/> class. /// </summary> protected State() { } #endregion #region Properties /// <summary> /// Gets a value indicating whether this <see cref="State"/> is active. /// </summary> /// <value><c>true</c> if is active; otherwise, <c>false</c>.</value> static public bool IsActive { get { return _gameManagerInstance != null; } } /// <summary> /// Gets the instance. /// </summary> /// <value>The instance.</value> public static GameManager GameManager { get { // First check if we have a reference to the instance has... if (State._gameManagerInstance == null) { // ... we dont, so see if we can get one if one exists... _gameManagerInstance = Object.FindObjectOfType(typeof(GameManager)) as GameManager; // ... check again if we now have an instance... if (_gameManagerInstance == null) { _gameManagerInstance = GetNewGameManagerInstance(); } } // Finally return the instance return State._gameManagerInstance; } } #endregion #region Methods /// <summary> /// Gets a new instance of the game amanger. /// </summary> /// <returns> /// The new instance. /// </returns> static GameManager GetNewGameManagerInstance() { // ... we still dont so we need to create one GameObject gameObject = new GameObject(StateManagerKeys.GameManger); // We need to ensure that the instance is not destroyed when // loading or changing to a new Scene DontDestroyOnLoad(gameObject); // Tie the instance of the GameManager to the game object _gameManagerInstance = gameObject.AddComponent<GameManager>(); // Finally return the instance return _gameManagerInstance; } #endregion } }
mit
hyp/nnFit
src/nn/trainer.cpp
3674
#include <iostream> #include <chrono> #include "trainer.h" #include "errorCriterion.h" #include "optimizers/optimizer.h" using namespace nnFit; Trainer::Trainer(Network &network, ErrorCriterion &criterion, Dataset &data, size_t parallelisationFactor) : network(network), criterion(criterion), data(data), trainingExampleCount(data.size()), parallelisationFactor(parallelisationFactor) { reshuffleIndices = false; profile = false; } void Trainer::gradientDescent(Optimizer &opt, size_t iterations) { train(opt, iterations, trainingExampleCount); } void Trainer::miniBatchGradientDescent(Optimizer &opt, size_t iterations, size_t miniBatchSize) { train(opt, iterations, miniBatchSize); } void Trainer::train(Optimizer &opt, size_t iterations, size_t miniBatchSize) { Vector input(network.device(), data.inputSize() * parallelisationFactor); Vector output(network.device(), data.outputSize() * parallelisationFactor); Vector errors(network.device(), data.outputSize() * parallelisationFactor); Vector errorSum(network.device(), 1); std::vector<float> errs; auto weightsAndGradients = network.weightsAndGradients(); assert((trainingExampleCount % parallelisationFactor) == 0); assert((trainingExampleCount % miniBatchSize) == 0); assert((miniBatchSize % parallelisationFactor) == 0); assert(miniBatchSize >= parallelisationFactor); size_t batchCount = trainingExampleCount / miniBatchSize; size_t passCount = trainingExampleCount / parallelisationFactor; size_t passPerBatchCount = miniBatchSize / parallelisationFactor; std::vector<size_t> indices(passCount); for (size_t i = 0; i < indices.size(); ++i) indices[i] = i; std::chrono::high_resolution_clock::time_point iterationStart; for (size_t iteration = 0; iteration < iterations; ++iteration) { // Reset errors errors.zeros(); if (profile) iterationStart = std::chrono::high_resolution_clock::now(); // Shuffle indices if needed if (reshuffleIndices) std::random_shuffle(indices.begin(), indices.end()); for (size_t batch = 0; batch < batchCount; ++batch) { // Reset gradients for (auto &i : weightsAndGradients) { i.second->zeros(); } // Train for (size_t i = 0; i < passPerBatchCount; ++i) { data.get(indices[batch*passPerBatchCount + i]*parallelisationFactor, parallelisationFactor, input, output); const auto &prediction = network.feedforward(input); criterion.computeError(network.context(), prediction, output, errors); network.backpropagate(output, criterion); } // gradients = gradients / numberOfTrainingExamples // Scale the gradients while optimizing to avoid redundant division step. opt.optimize(weightsAndGradients, miniBatchSize); } // Compute the iteration error. partialSum(errorSum, errors); errorSum.copy(errs); float iterationError = errs[0] / float(trainingExampleCount); if (profile) { network.device().queue().finish(); auto now = std::chrono::high_resolution_clock::now(); auto seconds = std::chrono::duration_cast<std::chrono::seconds>(now - iterationStart).count(); std::cout << "One training iteration ran for " << seconds << "s\n"; } if (afterIteration) { afterIteration(iteration, iterationError); } } }
mit
Ybalrid/LeapRift
AbstractLevel.hpp
677
#ifndef ABSTRACTLEVEL #define ABSTRACTLEVEL #include <Annwvyn.h> namespace Annwvyn { //AnnEngine should really be a singleton class with a static method to get the instance... class AbstractLevel { public: ///Construct the level AbstractLevel(); ///Pure virtual methods that loads the level virtual void load() = 0; ///Destroy the level virtual ~AbstractLevel(); ///Unload the level by destroying every objects in "levelContent" and every lights in "levelLighting" virtual void unload(); ///Run logic code from the level virtual void runLogic() =0; protected: AnnGameObjectVect levelContent; AnnLightVect levelLighting; }; } #endif
mit
JordyBaylac/academic-tracker
e2e/app.e2e-spec.ts
338
import { AcademicTrackerPage } from './app.po'; describe('academic-tracker App', () => { let page: AcademicTrackerPage; beforeEach(() => { page = new AcademicTrackerPage(); }); it('should display message saying app works', () => { page.navigateTo(); expect(page.getParagraphText()).toEqual('app works!'); }); });
mit
ekyna/Characteristics
Tests/ManagerTest.php
1598
<?php namespace Ekyna\Component\Characteristics\Tests; use Ekyna\Component\Characteristics\Manager; use Ekyna\Component\Characteristics\ManagerBuilder; use Ekyna\Component\Characteristics\Schema\Registry; use Symfony\Component\Filesystem\Filesystem; /** * Class ManagerTest * @package Ekyna\Component\Characteristics\Tests */ class ManagerTest extends \PHPUnit_Framework_TestCase { /** * @var Manager */ private $manager; /** * @var Filesystem */ private $fs; /** * @var string */ private $tmpDir; public function setUp() { $this->tmpDir = sys_get_temp_dir() . '/characteristics'; $this->fs = new Filesystem(); $this->fs->remove($this->tmpDir); clearstatcache(); $builder = ManagerBuilder::create(); $this->manager = $builder ->setSchemaDirs(array(__DIR__ . '/Fixtures/config')) ->setMetadataDirs(array()) ->setCacheDir($this->tmpDir) ->build(); } public function tearDown() { $this->manager = null; $this->fs->remove($this->tmpDir); } public function testGetSchemaForClass() { $productSchema = $this->manager->getSchemaForClass('Ekyna\Component\Characteristics\Tests\Fixtures\ProductCharacteristics'); $this->assertEquals('product', $productSchema->getName()); $productSchema = $this->manager->getSchemaForClass('Ekyna\Component\Characteristics\Tests\Fixtures\VariantCharacteristics'); $this->assertEquals('product', $productSchema->getName()); } }
mit
validate-io/typed-array-function
lib/create.js
2158
/* jshint evil:true */ 'use strict'; // MODULES // var isFunction = require( 'validate.io-function' ), isTypedArray = require( 'validate.io-typed-array' ); // CREATE // /** * FUNCTION: create( fcn ) * Returns a function for validating whether an input is a typed array for which all elements pass the test function. * * @param {Function} fcn - function to apply * @returns {Function} validation function */ function create( fcn ) { var f; if ( !isFunction( fcn ) ) { throw new TypeError( 'invalid input argument. Must provide a function to test for each array element. Value: `' + fcn + '`.' ); } // Code generation. Start with the function definition... f = 'return function validate(v){'; // Create the function body... // Create internal variables... // => var len, i; f += 'var len,i;'; // Return false if input argument is not a typed array... f += 'if(!validate._isTypedArray(v)){'; f += 'return false;'; f += '}'; f += 'len = v.length;'; // Return false if provided an empty array... f += 'if(!len){'; f += 'return false;'; f += '}'; // Test each array element... f += 'for(i=0;i<len;i++){'; f += 'if(validate._f(v[i])===false){'; f += 'return false;'; f += '}'; f += '}'; /* for ( i = 0; i < len; i++ ) { if ( validate._f(v[i]) === false ) { // Return false if test is violated for at least one element: return false; } } */ // Otherwise, return true: f += 'return true;'; // Close the function: f += '};'; // Create the function in the global scope... f = ( new Function( f ) )(); // Bind the test function to the created function so it may be referenced during invocation... f._f = fcn; // Bind the typed array validation function to the created function so it may be referenced during invocation... f._isTypedArray = isTypedArray; return f; /* function validate( v ) { var len, i; if( !validate._isTypedArray( v ) ) { return false; } len = v.length; for ( i = 0; i < len; i++ ) { if ( validate._f( v[i] ) === false ) { return false; } } return true; } */ } // end FUNCTION create() // EXPORTS // module.exports = create;
mit
akaraatanasov/SoftUni
Technologies Fundamentals/Software Technologies/JavaScript - Blog Admin Functionality/SoftUniBlog/controllers/article.js
4265
const Article = require('mongoose').model('Article'); module.exports = { createGet: (req, res) => { res.render('article/create'); }, createPost: (req, res) => { let articleArgs = req.body; let errorMsg = ''; if(!req.isAuthenticated()){ errorMsg = 'You should be logged in to make articles!' } else if (!articleArgs.title){ errorMsg = 'Invalid title!'; } else if (!articleArgs.content){ errorMsg = 'Invalid content!'; } if (errorMsg) { res.render('article/create', {error: errorMsg}); return; } articleArgs.author = req.user.id; Article.create(articleArgs).then(article => { req.user.articles.push(article.id); req.user.save(err => { if (err) { res.redirect('/', {error: err.message}); } else { res.redirect('/'); } }) }) }, details: (req, res) => { let id = req.params.id; Article.findById(id).populate('author').then(article => { res.render('article/details', article); }) }, editGet: (req, res) => { let id = req.params.id; if(!req.isAuthenticated()){ let returnUrl = `/article/edit/${id}`; req.session.returnUrl = returnUrl; res.redirect('/user/login'); return; } Article.findById(id).then(article => { req.user.isInRole('Admin').then(isAdmin => { if(req.user === undefined || (!req.user.isAuthor(article) && !isAdmin)) { res.render('home/index', {error: 'You cannot edit this article'}); return; } res.render('article/edit', article) }); }); }, editPost: (req, res) => { let id = req.params.id; let articleArgs = req.body; let errorMsg = ''; if (!articleArgs.title){ errorMsg = 'Article title cannot be empty!'; } else if (!articleArgs.content) { errorMsg = 'Article content cannot be empty!' } req.user.isInRole('Admin').then(isAdmin => { Article.findById(id).then(article => { if(req.user === undefined || (!req.user.isAuthor(article) && !isAdmin)) { return; } if(errorMsg) { res.render('article/edit', {error: errorMsg}); } else { Article.update({_id: id}, {$set: {title: articleArgs.title, content: articleArgs.content}}) .then(updateStatus => { res.redirect(`/article/details/${id}`); }); } }) }); }, deleteGet: (req, res) => { let id = req.params.id; Article.findById(id).then(article => { req.user.isInRole('Admin').then(isAdmin => { if(req.user === undefined || (!req.user.isAuthor(article) && !isAdmin)) { res.render('home/index', {error: 'You cannot delete this article'}); return; } res.render('article/delete', article) }); }); }, deletePost: (req, res) => { let id = req.params.id; Article.findOneAndRemove({_id: id}).populate('author').then(article => { let author = article.author; let index = author.articles.indexOf(article.id); req.user.isInRole('Admin').then(isAdmin => { if(req.user === undefined || (!req.user.isAuthor(article) && !isAdmin)) { return; } }); if(index < 0) { let errorMsg = 'Article was not found for that author!'; res.render('article/delete', {error: errorMsg}) } else { let count = 1; author.articles.splice(index, count); author.save().then((user) => { res.redirect('/'); }); } }) } };
mit
stopyoukid/DojoToTypescriptConverter
out/separate/dojox.atom.widget.FeedViewerGrouping.d.ts
791
/// <reference path="Object.d.ts" /> /// <reference path="dijit._Widget.d.ts" /> /// <reference path="dijit._Templated.d.ts" /> module dojox.atom.widget{ export class FeedViewerGrouping extends dijit._Widget { templateString : String; templatePath : String; widgetsInTemplate : bool; _skipNodeCache : bool; _earlyTemplatedStartup : bool; _attachPoints : any; _attachEvents : any[]; declaredClass : any; _startupWidgets : Object; _supportingWidgets : Object; _templateCache : Object; _stringRepl (tmpl:any) : any; _fillContent (source:HTMLElement) : any; _attachTemplateNodes (rootNode:HTMLElement,getAttrFunc?:Function) : any; getCachedTemplate (templatePath:String,templateString?:String,alwaysUseString?:any) : any; groupingNode : Object; titleNode : Object; setText (text:any) : any; } }
mit
MIWPFM/pfmweb
src/MIW/BackendBundle/Admin/UserAdmin.php
4065
<?php namespace MIW\BackendBundle\Admin; use Sonata\AdminBundle\Admin\Admin; use Sonata\AdminBundle\Datagrid\DatagridMapper; use Sonata\AdminBundle\Datagrid\ListMapper; use Sonata\AdminBundle\Form\FormMapper; use Sonata\AdminBundle\Show\ShowMapper; class UserAdmin extends Admin { /** * @param DatagridMapper $datagridMapper */ protected function configureDatagridFilters(DatagridMapper $datagridMapper) { $datagridMapper ->add('username', null, array('label' => 'Nombre de Usuario')) ->add('email', null, array('label' => 'Email')) ->add('enabled', null, array('label' => 'Activado')) ->add('name', null, array('label' => 'Nombre')) ; } /** * @param ListMapper $listMapper */ protected function configureListFields(ListMapper $listMapper) { $listMapper ->add('username', null, array('label' => 'Nombre de Usuario')) ->add('email', null, array('label' => 'Email')) ->add('enabled', null, array('label' => 'Activado', 'editable' => true)) ->add('lastLogin', 'date', array('format' => 'd/m/Y H:i', 'label' => 'Última Conexión ')) ->add('created', 'date', array('format' => 'd/m/Y H:i', 'label' => 'Fecha Creación')) ->add('_action', 'actions', array( 'label' => 'Acciones', 'actions' => array( 'show' => array(), 'edit' => array() ) )) ; } /** * @param FormMapper $formMapper */ protected function configureFormFields(FormMapper $formMapper) { $formMapper ->with('Datos Genéricos') ->add('username', null, array('label' => 'Usuario')) ->add('email', null, array('label' => 'Email')) ->add('enabled', null, array('label' => 'Activado')) ->with('Cambiar contraseña') ->add('plainPassword', 'password', array('label' => 'Contaseña','required'=>false)) ; } /** * @param ShowMapper $showMapper */ protected function configureShowFields(ShowMapper $showMapper) { $showMapper ->with('Datos Genéricos') ->add('id', null, array('label' => 'MongoID')) ->add('username', null, array('label' => 'Nombre de Usuario')) ->add('email', null, array('label' => 'Email')) ->add('enabled', null, array('label' => 'Activado')) ->add('salt', null, array('label' => 'Salt')) ->add('password', null, array('label' => 'Contraseña')) ->add('lastLogin', 'date', array('format' => 'd/m/Y H:i', 'label' => 'Última Conexión')) ->add('created', 'date', array('format' => 'd/m/Y H:i', 'label' => 'Fecha Creación')) ->add('roles', null, array('label' => 'Roles')) ->with('Datos Personales') ->add('name', null, array('label' => 'Nombre')) ->add('birthday', 'date', array('format' => 'd/m/Y', 'label' => 'Fecha de Nacimiento')) ->add('address.address', null, array('label' => 'Dirección')) ->add('address.province', null, array('label' => 'Provincia')) ; } public function prePersist($user) { if($user->getPlainPassword()){ $this->encodeUserPassword($user); } } public function preUpdate($user) { if($user->getPlainPassword()){ $this->encodeUserPassword($user); } } private function encodeUserPassword($user) { $container=$this->getConfigurationPool()->getContainer(); $encoder = $container->get('security.encoder_factory')->getEncoder($user); $cryptedPassword = $encoder->encodePassword($user->getPlainPassword(), $user->getSalt()); $user->setPassword($cryptedPassword); } }
mit
mangafas/siball-analysis-archive
text-based/beta/0.6/0.6.8/0.6.8.py
96310
import subprocess as sub import time # -----> * Filing * <----- # ask the user the name of the game to create a .txt file print("Enter game's name:") name_file = input("") name_file_string = str(name_file) file_name = name_file_string + ".txt" # create a writable .txt file safile = open(file_name, "w") # -----> * Team Separator * <----- home, away, date = name_file_string.split('-') # -----> * Timing * <----- # Referencing variables so the are available to use in function elapsed_home = 0 elapsed_away = 0 start_home = 0 start_away = 0 ball_home = False ball_away = True # Assuming that away team has the starting kick def body(): # -----> * Introduction * <----- intro_part_one = ''' Welcome to Siball-Analysis v0.6.5-beta. If you do not know the commands ''' intro_part_two = ''' type help to open the howto file. I hope you enjoy the game between %s and %s. Are you recording for %s or %s?''' intro_one = intro_part_one + intro_part_two # assigning the home and away teams to the intro so the intro is user friendly print(intro_one % (home, away, home, away)) home_or_away = input() # asking the user which team are they recording stats for if True: if home_or_away == home: team = home intro_two = ''' Great! I hope %s has a good game! ''' print(intro_two % team) elif home_or_away == away: team = away intro_two = ''' Great! I hope %s has a good game! ''' print(intro_two % team) # -----> * Colors Variables * <----- # adding color to the output # red is if something did not go well ex. missed penalty kick red = "\033[1;31;50m%s" # blue if something went well ex. goal from penalty kick blue = "\033[1;34;50m%s" # white for general things like the total of penalty kicks white = "\033[1;38;50m%s" # -----> * Penalty Kicks Variables * <----- # create a range from 0 to 1000 pk_range = range(0, 1000) # list the range to be accessible pk_list = list(pk_range) pk_range_goal = range(0, 1000) pk_list_goal = list(pk_range_goal) pk_range_saved = range(0, 1000) pk_list_saved = list(pk_range_saved) pk_range_missed = range(0, 1000) pk_list_missed = list(pk_range_missed) pk_input = '''goal/saved/missed ''' goal_pk, saved_pk, missed_pk = pk_input.split("/") # a list of possible words that the user may type in order to record stats pk_words = ["pk", "penalty kick", "Penalty kick", "Penalty Kick", "penalty Kick", "PK", "Pk", "pK", "penalty kicks", "Penalty kicks", "Penalty Kicks", "penalty Kicks", "penalty kick "] goal_words = ["goal", "Goal", "GOAL", "goal ", "Goal ", "GOAL "] missed_words = ["missed", "Missed", "MISSED", "missed ", "Missed ", "MISSED ", "miss", "Miss", "MISS", "miss ", "Miss ", "MISS "] saved_words = ["saved", "Saved", "SAVED", "saved ", "Saved ", "SAVED ", "save", "Save", "SAVE", "save ", "Save ", "SAVE "] # -----> * Free Kicks Variables <----- fk_range = range(0, 1000) fk_list = list(fk_range) fk_range_gd = range(0, 1000) fk_list_gd = list(fk_range_gd) fk_range_pd = range(0, 1000) fk_list_pd = list(fk_range_pd) fk_input = '''gd/pd ''' gd_fk, pd_fk = fk_input.split("/") fk_words = ["fk", "free kick", "Free kick", "Free Kick", "free Kick", "Free kicks", "Free Kicks", "free Kicks", "free kick ", "FK", "free kicks ", "Free kicks ", "Free Kicks ", "free Kicks ", "Fk", "free kicks", "Free kick ", "Free Kick ", "free Kick "] fk_gd_words = ["gd", "GD", "gd ", "GD "] fk_pd_words = ["pd", "PD", "pd ", "PD "] # -----> * Corner Kicks Variables * <----- ck_range = range(0, 1000) ck_list = list(ck_range) ck_range_gd = range(0, 1000) ck_list_gd = list(ck_range_gd) ck_range_pd = range(0, 1000) ck_list_pd = list(ck_range_pd) ck_input = '''gd/pd ''' gd_ck, pd_ck = ck_input.split("/") ck_words = ["ck", "corner kick", "Corner kick", "Corner Kick", "corner kicks", "Corner kicks", "Corner Kicks", "Corner Kick ", "corner Kick ", "corner kicks ", "corner Kick", "CK", "Ck", "cK", "Corner kicks ", "Corner Kicks ", "corner Kicks ""Corner kicks ", "Corner Kicks ", "corner Kicks ", "Corner kick ", "corner Kicks", "corner kick "] ck_gd_words = ["gd", "GD", "gd ", "GD ", "031"] ck_pd_words = ["pd", "PD", "pd ", "PD ", "032"] # -----> * Throw Ins Variables * <----- ti_range = range(0, 1000) ti_list = list(ti_range) ti_range_gd = range(0, 1000) ti_list_gd = list(ti_range_gd) ti_range_pd = range(0, 1000) ti_list_pd = list(ti_range_pd) ti_input = '''gd/pd ''' gd_ti, pd_ti = ti_input.split("/") ti_words = ["ti", "throw in", "Throw in", "Throw In", "throw In", "TI", "Throw ins", "Throw Ins", "throw Ins", "throw in ", "Throw ins ", "Throw Ins ", "throw Ins ", "throw In ", "Ti", "tI", "throw ins", "Throw in ", "Throw In ", "throw ins "] ti_gd_words = ["gd", "GD", "gd ", "GD ", "041"] ti_pd_words = ["pd", "PD", "pd ", "PD ", "042"] # -----> * Crosses Variables * <----- crosses_range = range(0, 1000) crosses_list = list(crosses_range) crosses_range_gd = range(0, 1000) crosses_list_gd = list(crosses_range_gd) crosses_range_pd = range(0, 1000) crosses_list_pd = list(crosses_range_pd) crosses_input = '''gd/pd ''' gd_cross, pd_cross = crosses_input.split("/") cross_words = ["cross", "Cross", "Cross ", "cross ", "crosses", "Crosses", "Crosses ", "crosses "] cross_gd_words = ["gd", "GD", "gd ", "GD ", "051"] cross_pd_words = ["pd", "PD", "pd ", "PD ", "052"] # -----> * True vs True Variables * <----- v1_range = range(0, 1000) v1_list = list(v1_range) v1_range_w = range(0, 1000) v1_list_w = list(v1_range_w) v1_range_l = range(0, 1000) v1_list_l = list(v1_range_l) v1_input = '''w/l ''' w_v1, l_v1 = v1_input.split("/") v1_words = ["1v1", "1vs1", "1 versus 1", "1 Versus 1", "1VS1", "1v1 ", "1vs1 ", "1 versus 1 ", "1 Versus 1 ", "1VS1 "] w_words = ["w", "W", "w ", "W ", "won", "Won", "WON", "won ", "Won ", "WON "] l_words = ["l", "L", "l ", "L ", "lost", "Lost", "LOST", "lost ", "Lost ", "LOST ", "062"] # -----> * Shots Variables * <----- shots_range = range(0, 1000) shots_list = list(shots_range) shots_range_gd = range(0, 1000) shots_list_gd = list(shots_range_gd) shots_range_pd = range(0, 1000) shots_list_pd = list(shots_range_pd) shots_range_bs = range(0, 1000) shots_list_bs = list(shots_range_bs) shots_input = '''on target/off target/blocked shots ''' ont_shot, oft_shot, blocked_shot = shots_input.split("/") shot_words = ["shot", "Shot", "SHOT", "shot ", "Shot ", "SHOT ", "shots", "SHOTS ", "Shots", "SHOTS", "shots ", "Shots "] shot_ont_words = ["on target", "On target", "On Target", "ON TARGET", "ON TARGET ", "ont", "ONT", "ont ", "ONT ", "on target ", "On target ", "On Target "] shot_oft_words = ["off target", "Off target", "Off Target", "OFF TARGET", "Off Target ", "OFF TARGET ", "oft", "OFT", "oft ", "OFT ", "off target ", "Off target "] blocked_shot_words = ["blocked shot", "Blocked Shot", "BLOCKED SHOT", "blocked shot ", "Blocked Shot ", "BLOCKED SHOT ", "BS", "bs", "BS ", "bs "] # -----> * Headers Variables * <----- headers_range = range(0, 1000) headers_list = list(headers_range) headers_range_gd = range(0, 1000) headers_list_gd = list(headers_range_gd) headers_range_pd = range(0, 1000) headers_list_pd = list(headers_range_pd) headers_input = '''on target/off target ''' ont_header, oft_header = headers_input.split("/") header_words = ["header", "Header", "HEADER", "header ", "Header ", "headers ", "Headers ", "HEADERS ", "a1ta", "HEADER ", "header", "Header", "HEADER"] header_ont_words = ["on target", "On target", "On Target", "ON TARGET", "ON TARGET ", "ont", "ONT", "ont ", "ONT ", "on target ", "On target ", "On Target "] header_oft_words = ["off target", "Off target", "Off Target", "Off Target ", "OFF TARGET ", "oft", "OFT", "oft ", "OFT ", "OFF TARGET", "off target ", "Off target "] # -----> * Saves Variables * <----- saves_range = range(0, 1000) saves_list = list(saves_range) save_words = ["save", "Save", "SAVE", "saves", "Saves", "SAVES", "save ", "SAVES "] # -----> * Long Pass Variables * <----- lpi_range = range(0, 1000) lpi_list = list(lpi_range) lpi_range_sb_defense = range(0, 1000) lpi_list_sb_defense = list(lpi_range_sb_defense) lpi_range_tb_defense = range(0, 1000) lpi_list_tb_defense = list(lpi_range_tb_defense) lpi_range_attack = range(0, 1000) lpi_list_attack = list(lpi_range_attack) lpi_range_sb_attack = range(0, 1000) lpi_list_sb_attack = list(lpi_range_sb_attack) lpi_range_tb_attack = range(0, 1000) lpi_list_tb_attack = list(lpi_range_tb_attack) lpi_range_defense = range(0, 1000) lpi_list_defense = list(lpi_range_defense) lpi_input_defense = '''sb/tb ''' lpi_input = '''attack/defence ''' lpi_input_attack = '''second ball/third ball ''' attack_lpi, defense_lpi = lpi_input.split("/") long_pass_words = ["long pass", "Long pass", "long pass ", "Long Pass ", "long pass interception", "Long pass interception", "Long Pass Interception ", "LPI", "lpi", "LPI ", "LP", "lp", "LP ", "lp ", "long pass interception ", "lpi "] lpi_attack_words = ["attack", "Attack", "ATTACK", "attack ", "Attack ", "ATTACK ", "a", "33", "3/3", "33 ", "3/3 "] attack_sb_words = ["second ball", "Second ball", "SECOND BALL ", "SB", "sb", "SB ", "sb ", "second ball ", "Second ball ", "SECOND BALL "] attack_tb_words = ["third ball", "Third ball", "THIRD BALL ", "tb", "TB ", "tb ", "third ball ", "Third ball ", "THIRD BALL ", "TB"] lpi_defense_words = ["defense", "Defense", "DEFENSE", "defense ", "1/3", "Defense ", "DEFENSE ", "d", "13", "1/3", "13 "] defense_sb_words = ["second ball", "Second ball", "SECOND BALL ", "SB", "second ball ", "Second ball ", "SECOND BALL ", "sb", "SB ", "sb "] defense_tb_words = ["third ball", "Third ball", "THIRD BALL ", "third ball ", "Third ball ", "THIRD BALL ", "TB", "tb", "TB ", "tb "] # -----> * Possession Loss Variables * <----- pl_range = range(0, 1000) pl_list = list(pl_range) pl_range_33 = range(0, 1000) pl_list_33 = list(pl_range_33) pl_range_33_23 = range(0, 1000) pl_list_33_23 = list(pl_range_33_23) pl_range_33_13 = range(0, 1000) pl_list_33_13 = list(pl_range_33_13) pl_range_23 = range(0, 1000) pl_list_23 = list(pl_range_23) pl_range_23_33 = range(0, 1000) pl_list_23_33 = list(pl_range_23_33) pl_range_23_13 = range(0, 1000) pl_list_23_13 = list(pl_range_23_13) pl_range_13 = range(0, 1000) pl_list_13 = list(pl_range_13) pl_range_13_33 = range(0, 1000) pl_list_13_33 = list(pl_range_13_33) pl_range_13_23 = range(0, 1000) pl_list_13_23 = list(pl_range_13_23) pl_input = '''3/3 2/3 1/3 ''' attack_print = ''' 2/3 1/3 ''' midfield_print = ''' 3/3 1/3 ''' defense_print = ''' 3/3 2/3 ''' pl_words = ["pl", "PL", "Possession Loss", "Possession loss", "possession loss", "pl ", "PL ", "Possession Loss ", "Possession loss ", "possession loss "] pl_attack_words = ["attack", "Attack", "ATTACK", "attack ", "Attack ", "ATTACK ", "a", "33", "3/3", "33 ", "3/3 "] attack_midfield_words = ["midfield", "Midfield", "MIDFIELD", "midfield ", "Midfield ", "MIDFIELD ", "m", "23", "2/3", "23 ", "2/3 "] attack_defense_words = ["defense", "Defense", "DEFENSE", "defense ", "Defense ", "DEFENSE ", "d", "13", "1/3", "13 ", "1/3"] pl_midfield_words = ["midfield", "Midfield", "MIDFIELD", "midfield ", "Midfield ", "MIDFIELD ", "m", "23", "2/3", "23 ", "2/3 "] midfield_attack_words = ["attack", "Attack", "ATTACK", "attack ", "Attack ", "ATTACK ", "a", "33", "3/3", "33 ", "3/3 "] midfield_defense_words = ["defense", "Defense", "DEFENSE", "defense ", "Defense ", "DEFENSE ", "d", "13", "1/3", "13 ", "1/3"] pl_defense_words = ["defense", "Defense", "DEFENSE", "defense ", "Defense ", "DEFENSE ", "d", "13", "1/3", "13 ", "1/3"] defense_attack_words = ["attack", "Attack", "ATTACK", "attack ", "Attack ", "ATTACK ", "a", "33", "3/3", "33 ", "3/3 "] defense_midfield_words = ["midfield", "Midfield", "MIDFIELD", "midfield ", "Midfield ", "MIDFIELD ", "m", "23", "2/3", "23 ", "2/3 "] # -----> * Offside * <----- offside_range = range(0, 1000) offside_list = list(offside_range) offside_words = ["offside", "Offside", "offside ", "Offside "] # -----> * Transition * <----- pw_range_33_home = range(0, 1000) pw_list_33_home = list(pw_range_33_home) pw_range_home = range(0, 1000) pw_list_home = list(pw_range_home) pw_range_23_33_home = range(0, 1000) pw_list_23_33_home = list(pw_range_23_33_home) pw_range_13_home = range(0, 1000) pw_list_13_home = list(pw_range_13_home) pw_range_13_33_home = range(0, 1000) pw_list_13_33_home = list(pw_range_13_33_home) pw_range_13_23_home = range(0, 1000) pw_list_13_23_home = list(pw_range_13_23_home) pw_input = home + "/" + away + ''' ''' home_input_home = '''3/3 2/3 1/3 ''' defense_pw_print_home = '''3/3 2/3 ''' pw_words = ["transition", "Transition", "Transition ", "transition"] pw_midfield_words_home = ["midfield", "Midfield", "MIDFIELD", "midfield ", "Midfield ", "MIDFIELD ", "m", "23", "2/3", "23 ", "2/3 "] pw_defense_words_home = ["defense", "Defense", "DEFENSE", "defense ", "Defense ", "DEFENSE ", "d", "13", "1/3", "13 ", "1/3", "113"] defense_attack_pw_words_home = ["attack", "Attack", "ATTACK", "attack ", "Attack ", "ATTACK ", "3/3", "a", "33", "33 ", "3/3 "] defense_midfield_pw_words_home = ["midfield", "Midfield", "MIDFIELD", "midfield ", "Midfield ", "MIDFIELD ", "23", "2/3", "23 ", "2/3 ", "m"] pw_attack_words_home = ["attack", "Attack", "ATTACK", "attack ", "Attack ", "ATTACK ", "a", "33", "3/3", "33 ", "3/3"] pw_range_33_away = range(0, 1000) pw_list_33_away = list(pw_range_33_away) # ---------------------------------500th line--------------------------------- pw_range_away = range(0, 1000) pw_list_away = list(pw_range_away) pw_range_23_33_away = range(0, 1000) pw_list_23_33_away = list(pw_range_23_33_away) pw_range_13_away = range(0, 1000) pw_list_13_away = list(pw_range_13_away) pw_range_13_33_away = range(0, 1000) pw_list_13_33_away = list(pw_range_13_33_away) pw_range_13_23_away = range(0, 1000) pw_list_13_23_away = list(pw_range_13_23_away) away_input_away = '''3/3 2/3 1/3 ''' defense_pw_print_away = '''3/3 2/3 ''' pw_midfield_words_away = ["midfield", "Midfield", "MIDFIELD", "midfield ", "Midfield ", "MIDFIELD ", "23", "m", "2/3", "23 ", "2/3 "] pw_defense_words_away = ["defense", "Defense", "DEFENSE", "defense ", "Defense ", "DEFENSE ", "d", "1/3", "13", "13 ", "1/3"] defense_attack_pw_words_away = ["attack", "Attack", "ATTACK", "attack ", "Attack ", "ATTACK ", "33 ", "3/3 ", "a", "33", "3/3"] defense_midfield_pw_words_away = ["midfield", "Midfield", "MIDFIELD", "midfield ", "Midfield ", "MIDFIELD ", "m", "23", "2/3", "23 ", "2/3 "] pw_attack_words_away = ["attack", "Attack", "ATTACK", "attack ", "Attack ", "ATTACK ", "a", "33", "3/3", "33 ", "3/3"] # -----> * Goalkeeper Turnover * <----- gkto_range = range(0, 1000) gkto_list = list(gkto_range) gkto_words = ["gkto", "Goalkeeper Turnover", "GOALKEEPER TURNOVER", "gkto ", "Goalkeeper Turnover ", "GOALKEEPER TURNOVER "] kp_range = range(0, 1000) kp_list = list(kp_range) kp_words = ["kp", "Key Pass", "KEY PASS", "kp ", "Key Pass ", "KEY PASS "] # global each variable to be able to be referenced later when you # print/write the total stat on each game at the end global string_number_pk_goal, string_number_pk_missed global string_number_fk_pd, string_number_fk, string_number_ck_pd global string_number_crosses_gd, string_number_crosses_pd global string_number_headers_pd, string_number_headers_gd global string_number_v1_l, string_number_v1, string_number_v1_w global string_number_lpi_tb, string_number_lpi global string_number_ti_gd, string_number_ti, string_number_pl_23 global string_number_lpi_sb_defense global string_number_lpi_attack, string_number_pl_23_13 global string_number_lpi_sb_attack, string_number_ti_pd global string_number_pl_13_23, string_number_pl_13, midfield_input global string_number_pl_33, string_number_pl_23_33, string_number_pl_33_13 global string_number_pk_saved, string_number_pk, string_number_fk_gd global string_number_offside, string_number_pw_23_33_away global string_number_ck_gd, string_number_ck, end_away, start_home, team global string_number_pw_33_home, string_number_shots_pd global string_number_crosses, string_number_shots, elapsed_away, ball_away global string_number_pl, string_number_transition global string_number_pw_13_23_away, string_number_shots_gd global string_number_pw_23_33_home, elapsed_home global string_number_pw_home, string_number_pw_33_away global string_number_lpi_sb, string_number_pl_13_33 global string_number_pw_23_33, string_number_pw_13_33_away global string_number_save, start_away, string_number_headers global string_number_lpi_defense, string_number_pw_23 global string_number_pw_away, string_number_pw_13_33_home global string_number_lpi_tb_defense, string_number_kp global string_number_pw_13_33, string_number_pw_13_away global string_number_lpi_tb_attack, string_number_gkto global string_number_pl_33_23, string_number_pw_13 global string_number_pw_13_23, string_number_pw_13_23_home global string_number_pw_13_home, end_home, ball_home # false each variable to declare if a stat was called before or not int_number_pk_goal = False int_number_pk_saved = False int_number_pk_missed = False int_number_pk = False int_number_fk_gd = False int_number_fk_pd = False int_number_fk = False int_number_ck_gd = False int_number_ck_pd = False int_number_ck = False int_number_ti_gd = False int_number_ti_pd = False int_number_ti = False int_number_crosses_gd = False int_number_crosses_pd = False int_number_crosses = False int_number_shots_gd = False int_number_shots_pd = False int_number_shots_bs = False int_number_shots = False int_number_headers_gd = False int_number_headers_pd = False int_number_headers = False int_number_v1_w = False int_number_v1_l = False int_number_v1 = False int_number_lpi_sb_attack = False int_number_lpi_tb_attack = False int_number_lpi_attack = False int_number_lpi_sb_defense = False int_number_lpi_tb_defense = False int_number_lpi_defense = False int_number_lpi = False int_number_saves = False int_number_pl_33_23 = False int_number_pl_33_13 = False int_number_pl_23_33 = False int_number_pl_23_13 = False int_number_pl_23 = False int_number_pl_33 = False int_number_pl_13_33 = False int_number_pl_13_23 = False int_number_pl_13 = False int_number_pl = False int_number_offside = False int_number_transition = False int_number_pw_13_home = False int_number_pw_13_23_home = False int_number_pw_13_33_home = False int_number_pw_23_33_home = False int_number_pw_33_home = False int_number_pw_home = False int_number_pw_13_away = False int_number_pw_13_23_away = False int_number_pw_13_33_away = False int_number_pw_23_33_away = False int_number_pw_33_away = False int_number_pw_away = False int_number_gkto = False # it creates a while loop so the function will go on and on until # the user decides to quit the function while True: # the user decides which stat to record by calling it choice = input() # -----> * Penalty Kicks Function * <----- # user inserts one of the words in the list if choice in pk_words: # the user decides whether a stat was successful or not print(blue % goal_pk, red % saved_pk, red % missed_pk) good_bad_input_pk = input() if good_bad_input_pk in goal_words: # take the first number on the list first_number_pk_goal = pk_list_goal[0] # remove the first number on the lis # the first time it is called it deletes 0 pk_list_goal.remove(first_number_pk_goal) # takes the next number on a list which is the number # that will be called number_pk_goal = pk_list_goal[0] # strings the number so it will be printable/writable string_number_pk_goal = str(number_pk_goal) # true the integer so it knows it was called int_number_pk_goal = True pk_goal_1 = "Penalty Kick goal(s): " pk_goal_2 = string_number_pk_goal pk_print_string_goal = pk_goal_1 + pk_goal_2 # print a nice introduction and the time a stat was called print(blue % pk_print_string_goal) elif good_bad_input_pk in saved_words: first_number_pk_saved = pk_list_saved[0] pk_list_saved.remove(first_number_pk_saved) number_pk_saved = pk_list_saved[0] string_number_pk_saved = str(number_pk_saved) int_number_pk_saved = True pk_saved_1 = "Penalty Kick(s) saved: " pk_saved_2 = string_number_pk_saved pk_print_string_saved = pk_saved_1 + pk_saved_2 print(red % pk_print_string_saved) elif good_bad_input_pk in missed_words: first_number_pk_missed = pk_list_missed[0] pk_list_missed.remove(first_number_pk_missed) number_pk_missed = pk_list_missed[0] string_number_pk_missed = str(number_pk_missed) int_number_pk_missed = True pk_miss_1 = "Penalty Kick(s) missed: " pk_miss_2 = string_number_pk_missed pk_print_string_missed = pk_miss_1 + pk_miss_2 print(red % pk_print_string_missed) first_number_pk = pk_list[0] pk_list.remove(first_number_pk) number_pk = pk_list[0] string_number_pk = str(number_pk) int_number_pk = True pk_print_string = "Penalty Kick(s) : " + string_number_pk print(white % pk_print_string) # -----> * Free Kicks Function * <----- elif choice in fk_words: print(blue % gd_fk, red % pd_fk) good_bad_input_fk = input() if good_bad_input_fk in fk_gd_words: first_number_fk_gd = fk_list_gd[0] fk_list_gd.remove(first_number_fk_gd) number_fk_gd = fk_list_gd[0] string_number_fk_gd = str(number_fk_gd) int_number_fk_gd = True fk_string_gd_1 = "Free Kick(s) with a Good Delivery: " fk_string_gd_2 = string_number_fk_gd fk_print_string_gd = fk_string_gd_1 + fk_string_gd_2 print(blue % fk_print_string_gd) elif good_bad_input_fk in fk_pd_words: first_number_fk_pd = fk_list_pd[0] fk_list_pd.remove(first_number_fk_pd) number_fk_pd = fk_list_pd[0] string_number_fk_pd = str(number_fk_pd) int_number_fk_pd = True fk_string_pd_1 = "Free Kick(s) with a Poor Delivery: " fk_string_pd_2 = string_number_fk_pd fk_print_string_pd = fk_string_pd_1 + fk_string_pd_2 print(red % fk_print_string_pd) first_number_fk = fk_list[0] fk_list.remove(first_number_fk) number_fk = fk_list[0] string_number_fk = str(number_fk) int_number_fk = True fk_print_string = "Free Kick(s)" + string_number_fk print(white % fk_print_string) # -----> * Corner Kick Variables * <----- elif choice in ck_words: print(blue % gd_ck, red % pd_ck) good_bad_input_ck = input() if good_bad_input_ck in ck_gd_words: first_number_ck_gd = ck_list_gd[0] ck_list_gd.remove(first_number_ck_gd) number_ck_gd = ck_list_gd[0] string_number_ck_gd = str(number_ck_gd) int_number_ck_gd = True ck_string_gd_1 = "Corner Kick(s) with a Good Delivery: " ck_string_gd_2 = string_number_ck_gd ck_print_string_gd = ck_string_gd_1 + ck_string_gd_2 print(blue % ck_print_string_gd) elif good_bad_input_ck in ck_pd_words: first_number_ck_pd = ck_list_pd[0] ck_list_pd.remove(first_number_ck_pd) number_ck_pd = ck_list_pd[0] string_number_ck_pd = str(number_ck_pd) int_number_ck_pd = True ck_string_pd_1 = "Corner Kick(s) with a Poor Delivery: " ck_string_pd_2 = string_number_ck_pd ck_print_string_pd = ck_string_pd_1 + ck_string_pd_2 print(red % ck_print_string_pd) first_number_ck = ck_list[0] ck_list.remove(first_number_ck) number_ck = ck_list[0] string_number_ck = str(number_ck) int_number_ck = True ck_print_string = "Corner Kick(s): " + string_number_ck print(white % ck_print_string) # -----> * Throw Ins Functions * <----- elif choice in ti_words: print(blue % gd_ti, red % pd_ti) good_bad_input_ti = input() if good_bad_input_ti in ti_gd_words: first_number_ti_gd = ti_list_gd[0] ti_list_gd.remove(first_number_ti_gd) number_ti_gd = ti_list_gd[0] string_number_ti_gd = str(number_ti_gd) int_number_ti_gd = True ti_string_gd_1 = "Throw In(s) with a Good Delivery: " ti_string_gd_2 = string_number_ti_gd ti_print_string_gd = ti_string_gd_1 + ti_string_gd_2 print(blue % ti_print_string_gd) elif good_bad_input_ti in ti_pd_words: first_number_ti_pd = ti_list_pd[0] ti_list_pd.remove(first_number_ti_pd) number_ti_pd = ti_list_pd[0] string_number_ti_pd = str(number_ti_pd) int_number_ti_pd = True ti_string_pd_1 = "Throw In(s) with a Poor Delivery: " ti_string_pd_2 = string_number_ti_pd ti_print_string_pd = ti_string_pd_1 + ti_string_pd_2 print(red % ti_print_string_pd) first_number_ti = ti_list[0] ti_list.remove(first_number_ti) number_ti = ti_list[0] string_number_ti = str(number_ti) int_number_ti = True ti_print_string = "Throw In(s): " + string_number_ti print(white % ti_print_string) # -----> * Crosses Function * <----- elif choice in cross_words: print(blue % gd_cross, red % pd_cross) good_bad_input_crosses = input() if good_bad_input_crosses in cross_gd_words: first_number_crosses_gd = crosses_list_gd[0] crosses_list_gd.remove(first_number_crosses_gd) number_crosses_gd = crosses_list_gd[0] string_number_crosses_gd = str(number_crosses_gd) int_number_crosses_gd = True cross_string_gd_1 = "Cross(es) with a Good Delivery: " cross_string_gd_2 = string_number_crosses_gd cross_print_string_gd = cross_string_gd_1 + cross_string_gd_2 print(blue % cross_print_string_gd) elif good_bad_input_crosses in cross_pd_words: first_number_crosses_pd = crosses_list_pd[0] crosses_list_pd.remove(first_number_crosses_pd) number_crosses_pd = crosses_list_pd[0] string_number_crosses_pd = str(number_crosses_pd) int_number_crosses_pd = True cross_string_pd_1 = "Cross(es) with a Poor Delivery: " cross_string_pd_2 = string_number_crosses_pd cross_print_string_pd = cross_string_pd_1 + cross_string_pd_2 print(red % cross_print_string_pd) first_number_crosses = crosses_list[0] crosses_list.remove(first_number_crosses) number_crosses = crosses_list[0] string_number_crosses = str(number_crosses) int_number_crosses = True cross_print_string = "Cross(es): " + string_number_crosses print(white % cross_print_string) # -----> * 1 versus 1 Function * <----- elif choice in v1_words: print(blue % w_v1, red % l_v1) good_bad_input_v1 = input() if good_bad_input_v1 in w_words: first_number_v1_w = v1_list_w[0] v1_list_w.remove(first_number_v1_w) number_v1_w = v1_list_w[0] string_number_v1_w = str(number_v1_w) int_number_v1_w = True v1_print_string_w = "Won 1vs1: " + string_number_v1_w print(blue % v1_print_string_w) elif good_bad_input_v1 in l_words: first_number_v1_l = v1_list_l[0] v1_list_l.remove(first_number_v1_l) number_v1_l = v1_list_l[0] string_number_v1_l = str(number_v1_l) int_number_v1_l = True v1_print_string_l = "Lost 1vs1: " + string_number_v1_l print(red % v1_print_string_l) first_number_v1 = v1_list[0] v1_list.remove(first_number_v1) number_v1 = v1_list[0] string_number_v1 = str(number_v1) int_number_v1 = True v1_print_string = "1vs1: " + string_number_v1 print(white % v1_print_string) # -----> * Shots Function * <----- elif choice in shot_words: print(blue % ont_shot, red % oft_shot, red % blocked_shot) good_bad_input_shots = input() if good_bad_input_shots in shot_ont_words: first_number_shots_gd = shots_list_gd[0] shots_list_gd.remove(first_number_shots_gd) number_shots_gd = shots_list_gd[0] string_number_shots_gd = str(number_shots_gd) int_number_shots_gd = True shot_string_ont_1 = "Shot(s) on target: " shot_string_ont_2 = string_number_shots_gd shot_print_string_ont = shot_string_ont_1 + shot_string_ont_2 print(blue % shot_print_string_ont) elif good_bad_input_shots in shot_oft_words: first_number_shots_pd = shots_list_pd[0] shots_list_pd.remove(first_number_shots_pd) number_shots_pd = shots_list_pd[0] string_number_shots_pd = str(number_shots_pd) int_number_shots_pd = True shot_string_oft_1 = "Shot(s) off target: " shot_string_oft_2 = string_number_shots_pd shot_print_string_oft = shot_string_oft_1 + shot_string_oft_2 print(red % shot_print_string_oft) elif good_bad_input_shots in blocked_shot_words: first_number_shots_bs = shots_list_bs[0] shots_list_bs.remove(first_number_shots_bs) number_shots_bs = shots_list_bs[0] string_number_shots_bs = str(number_shots_bs) int_number_shots_bs = True shot_string_bs_1 = "Blocked Shot(s): " shot_string_bs_2 = string_number_shots_bs shot_print_string_bs = shot_string_bs_1 + shot_string_bs_2 print(red % shot_print_string_bs) first_number_shots = shots_list[0] shots_list.remove(first_number_shots) number_shots = shots_list[0] string_number_shots = str(number_shots) int_number_shots = True shot_print_string = "Shot(s): " + string_number_shots print(white % shot_print_string) # -----> * Headers Function * <----- elif choice in header_words: print(blue % ont_header, red % oft_header) good_bad_input_headers = input() if good_bad_input_headers in header_ont_words: first_number_headers_gd = headers_list_gd[0] headers_list_gd.remove(first_number_headers_gd) number_headers_gd = headers_list_gd[0] string_number_headers_gd = str(number_headers_gd) int_number_headers_gd = True header_ont_1 = "Header(s) on target: " header_ont_2 = string_number_headers_gd header_print_string_ont = header_ont_1 + header_ont_2 print(blue % header_print_string_ont) elif good_bad_input_headers in header_oft_words: first_number_headers_pd = headers_list_pd[0] headers_list_pd.remove(first_number_headers_pd) number_headers_pd = headers_list_pd[0] string_number_headers_pd = str(number_headers_pd) int_number_headers_pd = True header_oft_1 = "Header(s) off target: " header_oft_2 = string_number_headers_pd header_print_string_oft = header_oft_1 + header_oft_2 print(red % header_print_string_oft) first_number_headers = headers_list[0] headers_list.remove(first_number_headers) number_headers = headers_list[0] string_number_headers = str(number_headers) int_number_crosses = True header_print_string = "Header(s): ", white % string_number_headers print(white % header_print_string) # -----> * Long Passes * <----- # -----------------------------1000th line----------------------------- elif choice in long_pass_words: print(blue % attack_lpi, red % defense_lpi) attack_defense_input_long_pass = input() if attack_defense_input_long_pass in lpi_attack_words: print(blue % lpi_input_attack) sec_third_input_long_pass_attack = input() if sec_third_input_long_pass_attack in attack_sb_words: first_number_lpi_sb_attack = lpi_list_sb_attack[0] lpi_list_sb_attack.remove(first_number_lpi_sb_attack) number_lpi_sb_attack = lpi_list_sb_attack[0] string_number_lpi_sb_attack = str(number_lpi_sb_attack) lpi_attack_sb_1 = "Second Ball Long Pass Interceptions " \ "on Attack: " lpi_attack_sb_2 = string_number_lpi_sb_attack lpi_print_attack_sb = lpi_attack_sb_1 + lpi_attack_sb_2 print(white % lpi_print_attack_sb) int_number_lpi_sb_attack = True elif sec_third_input_long_pass_attack in attack_tb_words: first_number_lpi_tb_attack = lpi_list_tb_attack[0] lpi_list_tb_attack.remove(first_number_lpi_tb_attack) number_lpi_tb_attack = lpi_list_tb_attack[0] string_number_lpi_tb_attack = str(number_lpi_tb_attack) lpi_attack_tb_1 = "Third Ball Long Pass " \ "Interceptions on Attack: " lpi_attack_tb_2 = string_number_lpi_tb_attack lpi_print_attack_tb = lpi_attack_tb_1 + lpi_attack_tb_2 print(white % lpi_print_attack_tb) int_number_lpi_tb_attack = True first_number_lpi_attack = lpi_list_attack[0] lpi_list_attack.remove(first_number_lpi_attack) number_lpi_attack = lpi_list_attack[0] string_number_lpi_attack = str(number_lpi_attack) lpi_attack_1 = "Long Pass Interceptions on Attack: " lpi_attack_2 = string_number_lpi_attack lpi_print_string_attack = lpi_attack_1 + lpi_attack_2 print(white % lpi_print_string_attack) int_number_lpi_attack = True elif attack_defense_input_long_pass in lpi_defense_words: print(red % lpi_input_defense) sec_third_input_long_pass_defense = input() if sec_third_input_long_pass_defense in defense_sb_words: first_number_lpi_sb_defense = lpi_list_sb_defense[0] lpi_list_sb_defense.remove(first_number_lpi_sb_defense) number_lpi_sb_defense = lpi_list_sb_defense[0] string_number_lpi_sb_defense = str(number_lpi_sb_defense) lpi_defense_sb_1 = "Second Ball Long Pass " \ "Interceptions on Defense: " lpi_defense_sb_2 = string_number_lpi_sb_defense lpi_print_defense_sb = lpi_defense_sb_1 + lpi_defense_sb_2 print(white % lpi_print_defense_sb) int_number_lpi_sb_defense = True elif sec_third_input_long_pass_defense in defense_tb_words: first_number_lpi_tb_defense = lpi_list_tb_defense[0] lpi_list_tb_defense.remove(first_number_lpi_tb_defense) number_lpi_tb_defense = lpi_list_tb_defense[0] string_number_lpi_tb_defense = str(number_lpi_tb_defense) lpi_defense_tb_1 = "Third Ball Long Pass " \ "Interceptions on Defense: " lpi_defense_tb_2 = string_number_lpi_tb_defense lpi_print_defense_tb = lpi_defense_tb_1 + lpi_defense_tb_2 print(white % lpi_print_defense_tb) int_number_lpi_tb_defense = True first_number_lpi_defense = lpi_list_defense[0] lpi_list_defense.remove(first_number_lpi_defense) number_lpi_defense = lpi_list_defense[0] string_number_lpi_defense = str(number_lpi_defense) pk_goal_1 = "Long Pass Interceptions on Defense:" pk_goal_2 = string_number_lpi_defense pk_print_string_goal = pk_goal_1 + pk_goal_2 print(white % pk_print_string_goal) int_number_lpi_defense = True first_number_lpi = lpi_list[0] lpi_list.remove(first_number_lpi) number_lpi = lpi_list[0] string_number_lpi = str(number_lpi) lpi_print_string = "Long Pass Interceptions: " + string_number_lpi print(white % lpi_print_string) int_number_lpi = True # -----> * Saves * <----- elif choice in save_words: first_number_save = saves_list[0] saves_list.remove(first_number_save) number_save = saves_list[0] string_number_save = str(number_save) int_number_saves = True saves_print_string = "Save(s)" + string_number_save print(white % saves_print_string) # -----> * Possession Loss * <----- elif choice in pl_words: good_bad_input_pl = input(pl_input) if good_bad_input_pl in pl_attack_words: attack_input = input(attack_print) if attack_input in attack_midfield_words: first_number_pl_33_23 = pl_list_33_23[0] pl_list_33_23.remove(first_number_pl_33_23) number_pl_33_23 = pl_list_33_23[0] string_number_pl_33_23 = str(number_pl_33_23) int_number_pl_33_23 = True pl_33_23_1 = "Possession lost on offence " \ "that came from Midfield: " pl_33_23_2 = string_number_pl_33_23 pl_print_string_33_23 = pl_33_23_1 + pl_33_23_2 print(white % pl_print_string_33_23) elif attack_input in attack_defense_words: first_number_pl_33_13 = pl_list_33_13[0] pl_list_33_13.remove(first_number_pl_33_13) number_pl_33_13 = pl_list_33_13[0] string_number_pl_33_13 = str(number_pl_33_13) int_number_pl_33_13 = True pl_33_13_1 = "Possession lost on offence" \ " that came from Defense: " pl_33_13_2 = string_number_pl_33_13 pl_print_string_33_13 = pl_33_13_1 + pl_33_13_2 print(white % pl_print_string_33_13) first_number_pl_33 = pl_list_33[0] pl_list_33.remove(first_number_pl_33) number_pl_33 = pl_list_33[0] string_number_pl_33 = str(number_pl_33) int_number_pl_33 = True pl_33_1 = "Possession lost on offence: " pl_33_2 = string_number_pl_33 pl_print_string_33 = pl_33_1 + pl_33_2 print(white % pl_print_string_33) elif good_bad_input_pl in pl_midfield_words: midfield_input = input(midfield_print) if midfield_input in midfield_attack_words: first_number_pl_23_33 = pl_list_23_33[0] pl_list_23_33.remove(first_number_pl_23_33) number_pl_23_33 = pl_list_23_33[0] string_number_pl_23_33 = str(number_pl_23_33) int_number_pl_23_33 = True pl_23_33_1 = "Possession lost on midfield that " \ "came from Offense: " pl_23_33_2 = string_number_pl_23_33 pl_print_string_23_33 = pl_23_33_1 + pl_23_33_2 print(white % pl_print_string_23_33) elif midfield_input in midfield_defense_words: first_number_pl_23_13 = pl_list_23_13[0] pl_list_23_13.remove(first_number_pl_23_13) number_pl_23_13 = pl_list_23_13[0] string_number_pl_23_13 = str(number_pl_23_13) int_number_pl_23_13 = True pl_23_13_1 = "Possession lost on midfield " \ "that came from Defense: " pl_23_13_2 = string_number_pl_23_13 pl_print_string_23_13 = pl_23_13_1 + pl_23_13_2 print(white % pl_print_string_23_13) first_number_pl_23 = pl_list_23[0] pl_list_23.remove(first_number_pl_23) number_pl_23 = pl_list_23[0] string_number_pl_23 = str(number_pl_23) int_number_pl_23 = True pl_23_1 = "Possession lost on midfield: " pl_23_2 = string_number_pl_23 pl_print_string_23 = pl_23_1 + pl_23_2 print(white % pl_print_string_23) elif good_bad_input_pl in pl_defense_words: defense_input = input(defense_print) if defense_input in defense_attack_words: first_number_pl_13_33 = pl_list_13_33[0] pl_list_13_33.remove(first_number_pl_13_33) number_pl_13_33 = pl_list_13_33[0] string_number_pl_13_33 = str(number_pl_13_33) int_number_pl_13_33 = True pl_13_33_1 = "Possession lost on defense " \ "that came from offense: " pl_13_33_2 = string_number_pl_13_33 pl_print_string_13_33 = pl_13_33_1 + pl_13_33_2 print(white % pl_print_string_13_33) elif defense_input in defense_midfield_words: first_number_pl_13_23 = pl_list_13_23[0] pl_list_13_23.remove(first_number_pl_13_23) number_pl_13_23 = pl_list_13_23[0] string_number_pl_13_23 = str(number_pl_13_23) int_number_pl_13_23 = True pl_13_23_1 = "Possession lost on defense that came " \ "from midfield: " pl_13_23_2 = string_number_pl_13_23 pl_print_string_13_23 = pl_13_23_1 + pl_13_23_2 print(white % pl_print_string_13_23) first_number_pl_13 = pl_list_13[0] pl_list_13.remove(first_number_pl_13) number_pl_13 = pl_list_13[0] string_number_pl_13 = str(number_pl_13) int_number_pl_13 = True pl_13_1 = "Possession lost on defense: " pl_13_2 = string_number_pl_13 pl_print_string_13 = pl_13_1 + pl_13_2 print(white % pl_print_string_13) first_number_pl = pl_list[0] pl_list.remove(first_number_pl) number_pl = pl_list[0] string_number_pl = str(number_pl) int_number_pl = True pl_print_string = "Possession lost:" + string_number_pl print(white % pl_print_string) elif choice in offside_words: first_number_offside = offside_list[0] offside_list.remove(first_number_offside) number_offside = offside_list[0] string_number_offside = str(number_offside) int_number_offside = True offside_print_string = "Offside(s):" + string_number_offside print(white % offside_print_string) elif choice in pw_words: attack_defense_input_transition = input(pw_input) if attack_defense_input_transition == home: home_input_pw_home = input(home_input_home) if home_input_pw_home in pw_attack_words_home: first_number_pw_33_home = pw_list_33_home[0] pw_list_33_home.remove(first_number_pw_33_home) number_pw_33_home = pw_list_33_home[0] string_number_pw_33_home = str(number_pw_33_home) int_number_pw_33_home = True pw_33_home_1 = "Offensive Transitions: " pw_33_home_2 = string_number_pw_33_home pw_print_string_33_home = pw_33_home_1 + pw_33_home_2 print(white % pw_print_string_33_home) elif home_input_pw_home in pw_midfield_words_home: first_number_pw_23_33_home = pw_list_23_33_home[0] pw_list_23_33_home.remove(first_number_pw_23_33_home) int_number_pw_23_33_home = True number_pw_23_33_home = pw_list_23_33_home[0] string_number_pw_23_33_home = str(number_pw_23_33_home) pw_23_33_home_1 = "Offensive Transition that came from " \ "midfield: " pw_23_33_home_2 = string_number_pw_23_33_home pw_print_23_33_home = pw_23_33_home_1 + pw_23_33_home_2 print(white % pw_print_23_33_home) elif home_input_pw_home in pw_defense_words_home: defense_input_home = input(defense_pw_print_home) if defense_input_home in defense_attack_pw_words_home: first_number_pw_13_33_home = pw_list_13_33_home[0] pw_list_13_33_home.remove(first_number_pw_13_33_home) number_pw_13_33_home = pw_list_13_33_home[0] string_number_pw_13_33_home = str(number_pw_13_33_home) int_number_pw_13_33_home = True pw_13_33_home_1 = "Offensive Transition that came " \ "from defense: " pw_13_33_home_2 = string_number_pw_13_33_home pw_print_13_33_home = pw_13_33_home_1 + pw_13_33_home_2 print(white % pw_print_13_33_home) elif defense_input_home in defense_midfield_pw_words_home: first_number_pw_13_23_home = pw_list_13_23_home[0] pw_list_13_23_home.remove(first_number_pw_13_23_home) number_pw_13_23_home = pw_list_13_23_home[0] string_number_pw_13_23_home = str(number_pw_13_23_home) int_number_pw_13_23_home = True pw_13_23_home_1 = "Midfield Transition that came " \ "from defense: " pw_13_23_home_2 = string_number_pw_13_23_home pw_print_13_23_home = pw_13_23_home_1 + pw_13_23_home_2 print(white % pw_print_13_23_home) first_number_pw_13_home = pw_list_13_home[0] pw_list_13_home.remove(first_number_pw_13_home) number_pw_13_home = pw_list_13_home[0] string_number_pw_13_home = str(number_pw_13_home) int_number_pw_13_home = True pw_13_home_1 = "Transition that came from defense: " pw_13_home_2 = string_number_pw_13_home pw_print_string_13_home = pw_13_home_1 + pw_13_home_2 print(white % pw_print_string_13_home) first_number_pw_home = pw_list_home[0] pw_list_home.remove(first_number_pw_home) number_pw_home = pw_list_home[0] string_number_pw_home = str(number_pw_home) int_number_pw_home = True pw_print_string_home = "Transitions from " + home + ": " \ + string_number_pw_home print(white % pw_print_string_home) elif attack_defense_input_transition == away: away_input_pw_away = input(away_input_away) if away_input_pw_away in pw_attack_words_away: first_number_pw_33_away = pw_list_33_away[0] pw_list_33_away.remove(first_number_pw_33_away) number_pw_33_away = pw_list_33_away[0] string_number_pw_33_away = str(number_pw_33_away) int_number_pw_33_away = True pw_33_away_1 = "Offensive Transitions: " pw_33_away_2 = string_number_pw_33_away pw_print_string_33_away = pw_33_away_1 + pw_33_away_2 print(white % pw_print_string_33_away) elif away_input_pw_away in pw_midfield_words_away: first_number_pw_23_33_away = pw_list_23_33_away[0] pw_list_23_33_away.remove(first_number_pw_23_33_away) int_number_pw_23_33_away = True number_pw_23_33_away = pw_list_23_33_away[0] string_number_pw_23_33_away = str(number_pw_23_33_away) pw_23_33_away_1 = "Offensive Transition that came from " \ "midfield: " pw_23_33_away_2 = string_number_pw_23_33_away pw_print_23_33_away = pw_23_33_away_1 + pw_23_33_away_2 print(white % pw_print_23_33_away) elif away_input_pw_away in pw_defense_words_away: defense_input_away = input(defense_pw_print_away) if defense_input_away in defense_attack_pw_words_away: first_number_pw_13_33_away = pw_list_13_33_away[0] pw_list_13_33_away.remove(first_number_pw_13_33_away) number_pw_13_33_away = pw_list_13_33_away[0] string_number_pw_13_33_away = str(number_pw_13_33_away) int_number_pw_13_33_away = True pw_13_33_away_1 = "Offensive Transition that came " \ "from defense: " pw_13_33_away_2 = string_number_pw_13_33_away pw_print_13_33_away = pw_13_33_away_1 + pw_13_33_away_2 print(white % pw_print_13_33_away) elif defense_input_away in defense_midfield_pw_words_away: first_number_pw_13_23_away = pw_list_13_23_away[0] pw_list_13_23_away.remove(first_number_pw_13_23_away) number_pw_13_23_away = pw_list_13_23_away[0] string_number_pw_13_23_away = str(number_pw_13_23_away) int_number_pw_13_23_away = True pw_13_23_away_1 = "Midfield Transition that came " \ "from defense: " pw_13_23_away_2 = string_number_pw_13_23_away pw_print_13_23_away = pw_13_23_away_1 + pw_13_23_away_2 print(white % pw_print_13_23_away) first_number_pw_13_away = pw_list_13_away[0] pw_list_13_away.remove(first_number_pw_13_away) number_pw_13_away = pw_list_13_away[0] string_number_pw_13_away = str(number_pw_13_away) int_number_pw_13_away = True pw_13_away_1 = "Transition that came from defense: " pw_13_away_2 = string_number_pw_13_away pw_print_string_13_away = pw_13_away_1 + pw_13_away_2 print(white % pw_print_string_13_away) first_number_pw_away = pw_list_away[0] pw_list_away.remove(first_number_pw_away) number_pw_away = pw_list_away[0] string_number_pw_away = str(number_pw_away) int_number_pw_away = True pw_print_string_away = "Transitions from " + away + ": " \ + string_number_pw_away print(white % pw_print_string_away) elif choice in gkto_words: first_number_gkto = gkto_list[0] gkto_list.remove(first_number_gkto) number_gkto = gkto_list[0] string_number_gkto = str(number_gkto) int_number_gkto = True gkto_print_string = "Free Kick(s)" + string_number_gkto print(red % gkto_print_string) elif choice in kp_words: first_number_kp = kp_list[0] kp_list.remove(first_number_kp) number_kp = kp_list[0] string_number_kp = str(number_kp) int_number_kp = True kp_print_string = "Key Passes" + string_number_kp print(red % kp_print_string) if choice == home: if ball_home: continue else: ball_away = False ball_home = True start_home = time.time() elapsed_away += time.time() - start_away if choice == away: if ball_away: continue else: ball_away = True ball_home = False start_away = time.time() elapsed_home += time.time() - start_home # when the user does not know the commands a howto.txt will pop up elif choice == "help": howto = "notepad.exe howto.txt" sub.Popen(howto) # -----> * Quit Function * <----- # if the user wants to quit he types q to begin the process elif choice == "q": # text to appear in the end of the program and the separate file draft_end_1 = '''The game between %s and %s finished.''' draft_end_2 = '''The following stats were recorded for %s:''' draft_ending_statement = draft_end_1 + draft_end_2 ending_statement = draft_ending_statement % (home, away, team) print(ending_statement) safile.write(ending_statement) # math function to calculate the percentage of each team in a match total_num = elapsed_home + elapsed_away percentage_num_possession = 100 / total_num final_home = elapsed_home * percentage_num_possession final_away = elapsed_away * percentage_num_possession round_home = round(final_home, 1) round_away = round(final_away, 1) string_home = str(round_home) string_away = str(round_away) print_home = home + " had " + string_home + "% possession" print_away = away + " had " + string_away + "% possession" # blues and reds are the percentage of possession depending on # team you have selected above if home_or_away == home: print(blue % print_home) print(red % print_away) elif home_or_away == away: print(blue % print_away) print(red % print_home) safile.write(print_home) safile.write(print_away) int_final_pk_goal = int(string_number_pk_goal) int_final_pk_missed = int(string_number_pk_missed) int_final_pk_saved = int(string_number_pk_saved) all_pk_bad = int_final_pk_missed + int_final_pk_saved all_pk_final = int_final_pk_goal + int_final_pk_missed all_pk_final += int_final_pk_saved int_final_pk = int(string_number_pk) if int_number_pk_goal and \ int_number_pk_saved and \ int_number_pk_missed and \ int_number_pk and \ int_final_pk == all_pk_final: perc_num_pk = 100 / all_pk_final perc_num_pk_good = perc_num_pk * int_final_pk_goal perc_num_pk_bad = perc_num_pk * all_pk_bad round_pk_good = round(perc_num_pk_good, 1) round_pk_bad = round(perc_num_pk_bad, 1) print_pk_good = str(round_pk_good) print_pk_bad = str(round_pk_bad) final_pk_good = print_pk_good + "% of the Penalty Kicks " \ "were good" final_pk_bad = print_pk_bad + "% of the Penalty Kicks were " \ "bad" print(blue % final_pk_good) print(red % final_pk_bad) # start print out/write on file each stat # if it was called if int_number_pk_goal: # print the number of the stat end_pk_goal = "Penalty Kick goal(s): " + string_number_pk_goal print(white % end_pk_goal) # write on the file safile.write("Penalty Kick goal(s): ") safile.write(string_number_pk_goal) # if it was not called elif not int_number_pk_goal: # print/write the time that the stat was called was None print("Penalty Kick goal(s): 0") safile.write("\nPenalty Kick goal(s): 0") if int_number_pk_missed: print("Penalty Kick(s) missed: ", string_number_pk_missed) safile.write("\nPenalty Kick(s) missed: ") safile.write(string_number_pk_missed) elif not int_number_pk_missed: print("Penalty Kick(s) missed: 0") safile.write("\nPenalty Kick(s) missed: 0 ") if int_number_pk_saved: print("Penalty Kick(s) saved: ", string_number_pk_saved) safile.write("\nPenalty Kick(s) saved: ") safile.write(string_number_pk_saved) elif not int_number_pk_saved: print("Penalty Kick(s) saved: 0") safile.write("\nPenalty Kick(s) saved: 0") if int_number_pk: print("Penalty Kick(s): ", string_number_pk) safile.write("\nPenalty Kick(s): ") safile.write(string_number_pk) elif not int_number_pk: print("Penalty Kick(s): 0") safile.write("\nPenalty Kick(s): 0") int_final_fk_gd = int(string_number_fk_gd) int_final_fk_pd = int(string_number_fk_pd) all_fk_final = int_final_fk_gd + int_final_fk_pd int_final_fk = int(string_number_fk) if int_number_fk_gd and \ int_number_fk_pd and \ int_number_fk and \ int_final_fk == all_fk_final: perc_num_fk = 100 / all_fk_final perc_num_fk_good = perc_num_fk * int_final_fk_gd perc_num_fk_bad = perc_num_fk * int_final_fk_pd round_fk_good = round(perc_num_fk_good, 1) round_fk_bad = round(perc_num_fk_bad, 1) print_fk_good = str(round_fk_good) print_fk_bad = str(round_fk_bad) final_fk_good = print_fk_good + "% of the Free Kicks were " \ "good" final_fk_bad = print_fk_bad + "% of the Free Kicks were " \ "bad" print(blue % final_fk_good) print(red % final_fk_bad) if int_number_fk_gd: print("Free Kick(s) with Good Delivery: ", string_number_fk_gd) safile.write("\nFree Kick(s) with Good Delivery: ") safile.write(string_number_fk_gd) elif not int_number_fk_gd: print("Free Kick(s) with Good Delivery: 0") safile.write("\nFree Kick(s) with Good Delivery: 0") if int_number_fk_pd: print("Free Kick(s) with Good Delivery: ", string_number_fk_pd) safile.write("\nFree Kick(s) with Poor Delivery: ") safile.write(string_number_fk_pd) elif not int_number_fk_pd: print("Free Kick(s) with Poor Delivery: 0") safile.write("\nFree Kick(s) with Poor Delivery: 0") if int_number_fk: print("Free Kick(s): ", string_number_fk) safile.write("\nFree Kick(s): ") safile.write(string_number_fk) elif not int_number_fk: print("Free Kick(s): 0") safile.write("\nFree Kick(s): 0") int_final_ck_gd = int(string_number_ck_gd) int_final_ck_pd = int(string_number_ck_pd) all_ck_final = int_final_ck_gd + int_final_ck_pd int_final_ck = int(string_number_ck) if int_number_ck_gd and \ int_number_ck_pd and \ int_number_ck and \ int_final_ck == all_ck_final: perc_num_ck = 100 / all_ck_final perc_num_ck_good = perc_num_ck * int_final_ck_gd perc_num_ck_bad = perc_num_ck * int_final_ck_pd round_ck_good = round(perc_num_ck_good, 1) round_ck_bad = round(perc_num_ck_bad, 1) print_ck_good = str(round_ck_good) print_ck_bad = str(round_ck_bad) final_ck_good = print_ck_good + "% of the Corner Kicks were " \ "good" final_ck_bad = print_ck_bad + "% of the Corner Kicks were " \ "bad" print(blue % final_ck_good) print(red % final_ck_bad) if int_number_ck_gd: end_ck_gd = "Corner Kick(s) with Good Delivery: " print(end_ck_gd + string_number_ck_gd) safile.write("\nCorner Kick(s) with Good Delivery: ") safile.write(string_number_ck_gd) elif not int_number_ck_gd: print("Corner Kick(s) with Good Delivery: 0") safile.write("\nCorner Kick(s) with Good Delivery: ") if int_number_ck_pd: end_ck_pd = "Corner Kick(s) with Poor Delivery: " print(end_ck_pd + string_number_ck_pd) safile.write("\nCorner Kick(s) with Good Delivery: ") safile.write(string_number_ck_pd) elif not int_number_ck_pd: print("Corner Kick(s) with Poor Delivery: 0") safile.write("\nCorner Kick(s) with Good Delivery: 0") if int_number_ck: print("Corner Kick(s): ", string_number_ck) safile.write("\nCorner Kick(s): ") safile.write(string_number_ck) elif not int_number_ck: print("Corner Kick(s): 0") safile.write("\nCorner Kick(s): 0") int_final_ti_gd = int(string_number_ti_gd) int_final_ti_pd = int(string_number_ti_pd) all_ti_final = int_final_ti_gd + int_final_ti_pd int_final_ti = int(string_number_ti) if int_number_ti_gd and \ int_number_ti_pd and \ int_number_ti and \ int_final_ti == all_ti_final: perc_num_ti = 100 / all_ti_final perc_num_ti_good = perc_num_ti * int_final_ti_gd perc_num_ti_bad = perc_num_ti * int_final_ti_pd round_ti_good = round(perc_num_ti_good, 1) round_ti_bad = round(perc_num_ti_bad, 1) print_ti_good = str(round_ti_good) print_ti_bad = str(round_ti_bad) final_ti_good = print_ti_good + "% of the Corner Kicks were " \ "good" final_ti_bad = print_ti_bad + "% of the Corner Kicks were " \ "bad" print(blue % final_ti_good) print(red % final_ti_bad) if int_number_ti_gd: print("Throw In(s) with Good Delivery: ", string_number_ti_gd) safile.write("\nThrow In(s) with Good Delivery: ") safile.write(string_number_ti_gd) elif not int_number_ti_gd: print("Throw In(s) with Good Delivery: 0") safile.write("\nThrow In(s) with Good Delivery: 0") if int_number_ti_pd: print("Throw In(s) with Poor Delivery: ", string_number_ti_pd) safile.write("\nThrow In(s) with Poor Delivery: ") safile.write(string_number_ti_pd) elif not int_number_ti_pd: print("Throw In(s) with Poor Delivery: 0") safile.write("\nThrow In(s) with Poor Delivery: 0") if int_number_ti: print("Throw In(s): ", string_number_ti) safile.write("\nThrow In(s): ") safile.write(string_number_ti) elif not int_number_ti: print("Throw In(s): 0") safile.write("\nThrow In(s): 0") int_final_crosses_gd = int(string_number_crosses_gd) int_final_crosses_pd = int(string_number_crosses_pd) all_crosses_final = int_final_crosses_gd + int_final_crosses_pd int_final_crosses = int(string_number_crosses) if int_number_crosses_gd and \ int_number_crosses_pd and \ int_number_crosses and \ int_final_crosses == all_crosses_final: perc_num_crosses = 100 / all_crosses_final perc_num_crosses_good = perc_num_crosses * int_final_crosses_gd perc_num_crosses_bad = perc_num_crosses * int_final_crosses_pd round_crosses_good = round(perc_num_crosses_good, 1) round_crosses_bad = round(perc_num_crosses_bad, 1) print_crosses_good = str(round_crosses_good) print_crosses_bad = str(round_crosses_bad) final_crosses_good = print_crosses_good + "% of the Crosses " \ "were good " final_crosses_bad = print_crosses_bad + "% of the Crosses " \ " were bad" print(blue % final_crosses_good) print(red % final_crosses_bad) if int_number_crosses_gd: end_cross_gd = "Cross(es) with Good Delivery: " print(end_cross_gd + string_number_crosses_gd) safile.write("\nCross(es) with Good Delivery: ") safile.write(string_number_crosses_gd) elif not int_number_crosses_gd: print("Cross(es) with Good Delivery: 0") safile.write("\nCross(es) with Good Delivery: ") if int_number_crosses_pd: end_cross_pd = "Cross(es) with Poor Delivery: " print(end_cross_pd + string_number_crosses_pd) safile.write("\nCross(es) with Poor Delivery: ") safile.write(string_number_crosses_pd) elif not int_number_crosses_pd: print("Cross(es) with Poor Delivery: 0") safile.write("\nCross(es) with Poor Delivery: 0") if int_number_crosses: print("Cross(es): ", string_number_crosses) safile.write("\nCross(es): ") safile.write(string_number_crosses) elif not int_number_crosses: print("Cross(es): 0") safile.write("\nCross(es): 0") int_final_shot_gd = int(string_number_shots_gd) int_final_shot_pd = int(string_number_shots_pd) int_final_shot_bs = int(string_number_shots_bs) all_shot_bad = int_final_shot_bs + int_final_shot_pd all_shot_final = int_final_shot_gd + int_final_shot_pd all_shot_final += int_final_shot_bs int_final_shot = int(string_number_shots) if int_number_shots_gd and \ int_number_shots_pd and \ int_number_shots and \ int_final_shot == all_shot_final: perc_num_shot = 100 / all_shot_final perc_num_shot_good = perc_num_shot * int_final_shot_gd perc_num_shot_bad = perc_num_shot * all_shot_bad round_shot_good = round(perc_num_shot_good, 1) round_shot_bad = round(perc_num_shot_bad, 1) print_shot_good = str(round_shot_good) print_shot_bad = str(round_shot_bad) final_shot_good = print_shot_good + "% of the Shots " \ "were good " final_shot_bad = print_shot_bad + "% of the Shots " \ " were bad" print(blue % final_shot_good) print(red % final_shot_bad) if int_number_shots_gd: print("Shot(s) on Target: ", string_number_shots_gd) safile.write("\nShot(s) on Target: ") safile.write(string_number_shots_gd) elif not int_number_shots_gd: print("Shot(s) on Target: 0") safile.write("\nShot(s) on Target: 0") if int_number_shots_pd: print("Shot(s) off Target: ", string_number_shots_pd) safile.write("\nShot(s) off Target: ") safile.write(string_number_shots_pd) elif not int_number_shots_pd: print("Shot(s) off Target: 0") safile.write("\nShot(s) off Target: 0") if int_number_shots_bs: print("Blocked Shot(s): ", string_number_shots_bs) safile.write("\nBlocked Shot(s): ") safile.write(string_number_shots_bs) elif not int_number_shots_bs: print("Blocked Shot(s): 0") safile.write("\nBlocked Shot(s): 0") if int_number_shots: print("Shot(s): ", string_number_shots) safile.write("\nShot(s): ") safile.write(string_number_shots) elif not int_number_shots: print("Shot(s): 0") safile.write("\nShot(s): 0") int_final_header_gd = int(string_number_headers_gd) int_final_header_pd = int(string_number_headers_pd) all_header_final = int_final_header_gd + int_final_header_pd int_final_header = int(string_number_headers) if int_number_headers_gd and \ int_number_headers_pd and \ int_number_headers and \ int_final_header == all_header_final: perc_num_header = 100 / all_header_final perc_num_header_good = perc_num_header * int_final_header_gd perc_num_header_bad = perc_num_header * int_final_header_pd round_header_good = round(perc_num_header_good, 1) round_header_bad = round(perc_num_header_bad, 1) print_header_good = str(round_header_good) print_header_bad = str(round_header_bad) final_header_good = print_header_good + "% of the Headers " \ "were good " final_header_bad = print_header_bad + "% of the Headers " \ " were bad" print(blue % final_header_good) print(red % final_header_bad) if int_number_headers_gd: print("Header(s) on Target: ", string_number_headers_gd) safile.write("\nHeader(s) on Target: ") safile.write(string_number_headers_gd) elif not int_number_headers_gd: print("Header(s) on Target: 0") safile.write("\nHeader(s) on Target: 0") if int_number_headers_pd: print("Header(s) off Target: ", string_number_headers_pd) safile.write("\nHeader(s) off Target: ") safile.write(string_number_headers_pd) elif not int_number_headers_pd: print("Header(s) off Target: 0") safile.write("\nHeader(s) off Target: 0") if int_number_headers: print("Header(s): ", string_number_headers) safile.write("\nHeader(s): ") safile.write(string_number_headers) elif not int_number_headers: print("Header(s): 0") safile.write("\nHeader(s): 0") int_final_v1_w = int(string_number_v1_w) int_final_v1_l = int(string_number_v1_l) all_v1_final = int_final_v1_w + int_final_v1_l int_final_v1 = int(string_number_v1) if int_number_v1_w and \ int_number_v1_l and \ int_number_v1 and \ int_final_v1 == all_v1_final: perc_num_v1 = 100 / all_v1_final perc_num_v1_good = perc_num_v1 * int_final_v1_w perc_num_v1_bad = perc_num_v1 * int_final_v1_l round_v1_good = round(perc_num_v1_good, 1) round_v1_bad = round(perc_num_v1_bad, 1) print_v1_good = str(round_v1_good) print_v1_bad = str(round_v1_bad) final_v1_good = print_v1_good + "% of the 1vs1 " \ "were good " final_v1_bad = print_v1_bad + "% of the 1vs1 " \ " were bad" print(blue % final_v1_good) print(red % final_v1_bad) if int_number_v1_w: print("1vs1 Won: ", string_number_v1_w) safile.write("\n1vs1 Won: ") safile.write(string_number_v1_w) elif not int_number_v1_w: print("1vs1 Won: 0") safile.write("\n1vs1 Won: 0") if int_number_v1_l: print("1vs1 Lost: ", string_number_v1_l) safile.write("\n1vs1 Lost: ") safile.write(string_number_v1_l) elif not int_number_v1_l: print("1vs1 Lost: 0") safile.write("\n1vs1 Lost: 0") if int_number_v1: print("1vs1: ", string_number_v1) safile.write("\n1vs1: ") safile.write(string_number_v1) elif not int_number_v1: print("1vs1: 0") safile.write("\n1vs1: 0") if int_number_lpi_sb_attack: end_lpi_sb_attack = "Second Ball Long Pass Interceptions on " \ "Attack: " print(end_lpi_sb_attack + string_number_lpi_sb_attack) lpisba_f = "\nSecond Ball Long Pass Interceptions on Attack: " safile.write(lpisba_f) safile.write(string_number_lpi_sb_attack) elif not int_number_lpi_sb_attack: lpisba_f0 = "Second Ball Long Pass Interceptions on Attack: 0" print(lpisba_f0) safile.write("\n" + lpisba_f0) if int_number_lpi_tb_attack: lpitba = "Third Ball Long Pass Interceptions on Attack: " print(lpitba + string_number_lpi_tb_attack) safile.write(lpitba) safile.write(string_number_lpi_tb_attack) elif not int_number_lpi_tb_attack: lpitba_f0 = "Third Ball Long Pass Interceptions on Attack: 0" print(lpitba_f0) safile.write("\n" + lpitba_f0) if int_number_lpi_attack: lpia = "Long Pass Interceptions on Attack: " print("\n" + lpia + string_number_lpi_attack) safile.write("\nLong Pass Interceptions on Attack: ") safile.write(string_number_lpi_attack) elif not int_number_lpi_attack: print("Long Pass Interceptions on Attack: 0") safile.write("\nLong Pass Interceptions on Attack: 0") if int_number_lpi_sb_defense: lpisbd = "Second Ball Long Pass Interceptions on Defense: " print(lpisbd + string_number_lpi_sb_defense) safile.write("\n" + lpisbd) safile.write(string_number_lpi_sb_defense) elif not int_number_lpi_sb_defense: lpisbb_f0 = "Second Ball Long Pass Interceptions on Defense: 0" print("Second Ball Long Pass Interceptions on Defense: 0") safile.write("\n" + lpisbb_f0) if int_number_lpi_tb_defense: lpitbd = "Third Ball Long Pass Interceptions on Defense: " print(lpitbd + string_number_lpi_tb_defense) safile.write("\n" + lpitbd) safile.write(string_number_lpi_tb_defense) elif not int_number_lpi_tb_defense: lpitbd_f0 = "Third Ball Long Pass Interceptions on Defense: 0" print(lpitbd_f0) safile.write("\n" + lpitbd_f0) if int_number_lpi_defense: lpid = "Long Pass Interceptions on Defense: " print(lpid + string_number_lpi_defense) safile.write("\nLong Pass Interceptions on Defense: ") safile.write(string_number_lpi_defense) elif not int_number_lpi_defense: print("Long Pass Interceptions on Defense: 0") safile.write("\nLong Pass Interceptions on Defense: 0") if int_number_lpi: print("Long Pass Interceptions: ", string_number_lpi) safile.write("\nLong Pass Interceptions: ") safile.write(string_number_lpi) elif not int_number_lpi: print("Long Pass Interceptions: 0") safile.write("\nLg Pass Interceptions: 0") if int_number_saves: print("Saves: ", string_number_save) safile.write("\nSaves: ") safile.write(string_number_save) elif not int_number_saves: print("\nSaves: 0") safile.write("\nSaves: 0") if int_number_pl_33_23: pl233 = "Possession(s) lost on offence that came from " \ "midfield: " print(pl233 + string_number_pl_33_23) safile.write("\n" + pl233) safile.write(string_number_pl_33_23) elif not int_number_pl_33_23: pl233_f0 = "Possession lost on offence that came from " \ "midfield: 0" print(pl233_f0) safile.write("\n" + pl233_f0) if int_number_pl_33_13: pl3313 = "Possession(s) lost on offence that came " \ "from defense: " print(pl3313 + string_number_pl_33_13) safile.write("\n" + pl3313) safile.write(string_number_pl_33_13) elif not int_number_pl_33_13: pl3313 = "Possession lost on offence that came from defense: 0" print(pl3313) safile.write("\n" + pl3313) if int_number_pl_33: print("Possession(s) lost on offence: ", string_number_pl_33) safile.write("\nPossession(s) lost on offence: ") safile.write(string_number_pl_33) elif not int_number_pl_33: print("Possession lost on offence: 0") safile.write("\nPossession lost on offence: 0") if int_number_pl_23_33: pl2333 = "Possession(s) lost on midfield that came from " \ "offense: " print(pl2333 + string_number_pl_23_33) safile.write("\n" + pl2333) safile.write(string_number_pl_23_33) elif not int_number_pl_23_33: pl2333_f0 = "Possession lost on midfield that came from " \ "offense: 0" print(pl2333_f0) safile.write("\n" + pl2333_f0) if int_number_pl_23_13: pl2313 = "Possession(s) lost on midfield that came from " \ "defense: " print(pl2313 + string_number_pl_23_13) safile.write("\n" + pl2313) safile.write(string_number_pl_23_13) elif not int_number_pl_23_13: pl2313_f0 = "Possession lost on midfield that came from " \ "defense: 0" print(pl2313_f0) safile.write("\n" + pl2313_f0) if int_number_pl_23: print("Possession(s) lost on midfield: ", string_number_pl_23) safile.write("\nPossession(s) lost on midfield: ") safile.write(string_number_pl_23) elif not int_number_pl_23: print("Possession lost on midfield: 0") safile.write("\nPossession lost on midfield: 0") if int_number_pl_13_33: pl1333 = "Possession(s) lost on defense that came from " \ "offense: " print(pl1333 + string_number_pl_13_33) safile.write("\n" + pl1333) safile.write(string_number_pl_13_33) elif not int_number_pl_13_33: pl1333_f0 = "Possession lost on defense that came from " \ "offense: 0" print(pl1333_f0) safile.write("\n" + pl1333_f0) if int_number_pl_13_23: pl1323 = "Possession(s) lost on defense that came from " \ "offense: " print(pl1323 + string_number_pl_13_23) safile.write("\n" + pl1323) safile.write(string_number_pl_13_23) elif not int_number_pl_13_23: pl1323_f0 = "Possession lost on defense that came from " \ "offense: 0" print(pl1323_f0) safile.write("\n" + pl1323_f0) if int_number_pl_13: print("Possession(s) lost on defense: ", string_number_pl_13) safile.write("\nPossession(s) lost on defense: ") safile.write(string_number_pl_13) elif not int_number_pl_13: print("Possession lost on defense: 0") safile.write("\nPossession lost on defense: 0") if int_number_pl: print("Possession(s) lost: ", string_number_pl) safile.write("\nPossession(s) lost: ") safile.write(string_number_pl) elif not int_number_pl: print("Possessions lost: 0") safile.write("\nPossession lost: 0") if int_number_offside: print("Offside(s): ", string_number_offside) safile.write("\nOffside(s): ") safile.write(string_number_offside) elif not int_number_offside: print("Offside(s) h2: 0") safile.write("\nOffside(s): 0 ") if int_number_pw_33_home: print("Offensive Transitions: ", string_number_pw_33_home) safile.write("\nOffensive Transitions: ") safile.write(string_number_pw_33_home) elif not int_number_pw_33_home: print("Offensive Transitions: 0") safile.write("\nOffensive Transitions: 0") if int_number_pw_23_33_home: pw2333h = "Offensive transitions that came from midfield: " print(pw2333h + string_number_pw_23_33_home) safile.write("\n" + pw2333h) safile.write(string_number_pw_23_33_home) elif not int_number_pw_23_33_home: pw2333h_f0 = "Offensive transitions that came from midfield: 0" print(pw2333h_f0) safile.write("\n" + pw2333h_f0) if int_number_pw_13_33_home: pw1333h = "Offensive transitions that came from defense: " print(pw1333h + string_number_pw_13_33_home) safile.write("\n" + pw1333h) safile.write(string_number_pw_13_33_home) elif not int_number_pw_13_33_home: pw1333h_f0 = "Offensive transitions that came from defense: 0" print(pw1333h_f0) safile.write("\n" + pw1333h_f0) if int_number_pw_13_23_home: pw1323h = "Midfield transitions that came from defense: " print(pw1323h + string_number_pw_13_23_home) safile.write("\nMidfield transitions that came from defense: ") safile.write(string_number_pw_13_23_home) elif not int_number_pw_13_23_home: pw1323h_f0 = "Midfield transitions that came from defense: 0" print(pw1323h_f0) safile.write("\n" + pw1323h_f0) if int_number_pw_13_home: pw13h = "Transitions that came from defense: " print(pw13h + string_number_pw_13_home) safile.write("\nTransitions that came from defense: ") safile.write(string_number_pw_13_home) elif not int_number_pw_13_home: print("Transitions that came from defense: 0") safile.write("\nTransitions that came from defense: 0") if int_number_pw_home: print("Transitions from " + home + ": ", string_number_pw_home) safile.write("\nTransitions from " + home + ": ") safile.write(string_number_pw_home) elif not int_number_pw_home: print("Transitions from " + home + ": 0") safile.write("\nTransitions from " + home + ": 0") if int_number_pw_33_away: print("Offensive Transitions: ", string_number_pw_33_away) safile.write("\nOffensive Transitions: ") safile.write(string_number_pw_33_away) elif not int_number_pw_33_away: print("Offensive Transitions: 0") safile.write("\nOffensive Transitions: 0") if int_number_pw_23_33_away: pw2333a = "Offensive transitions that came from midfield: " print(pw2333a + string_number_pw_23_33_away) safile.write("\n" + pw2333a) safile.write(string_number_pw_23_33_away) elif not int_number_pw_23_33_away: pw2333a_f0 = "Offensive transitions that came from midfield: 0" print("Offensive transitions that came from midfield: 0") safile.write("\n" + pw2333a_f0) if int_number_pw_13_33_away: pw1333a = "Offensive transitions that came from defense: " print(pw1333a + string_number_pw_13_33_away) safile.write("\n" + pw1333a) safile.write(string_number_pw_13_33_away) elif not int_number_pw_13_33_away: pw1333a_f0 = "Offensive transitions that came from defense: 0" print("Offensive transitions that came from defense: 0") safile.write("\n" + pw1333a_f0) if int_number_pw_13_23_away: pw1323a = "Midfield transitions that came from defense: " print(pw1323a + string_number_pw_13_23_away) safile.write("\nMidfield transitions that came from defense: ") safile.write(string_number_pw_13_23_away) elif not int_number_pw_13_23_away: pw1323a_f0 = "Midfield transitions that came from defense: 0" print("Midfield transitions that came from defense: 0") safile.write("\n" + pw1323a_f0) if int_number_pw_13_away: pw13a = "Transitions that came from defense: " print(pw13a + string_number_pw_13_away) safile.write("\nTransitions that came from defense: ") safile.write(string_number_pw_13_away) elif not int_number_pw_13_away: print("Transitions that came from defense: 0") safile.write("\nTransitions that came from defense: 0") if int_number_pw_away: print("Transitions from " + away + ": ", string_number_pw_away) safile.write("\nTransitions from " + away + ": ") safile.write(string_number_pw_away) elif not int_number_pw_away: print("Transitions from " + away + ": 0") safile.write("\nTransitions from " + away + ": 0") if int_number_transition: print("Transitions: ", string_number_transition) safile.write("\nTransitions: ") safile.write(string_number_transition) elif not int_number_transition: print("Transitions: 0") safile.write("\nTransitions: 0") if int_number_gkto: # print the number of the stat print("Goalkeeper Turnovers: ", string_number_gkto) # write on the file safile.write("Goalkeeper Turnovers: ") safile.write(string_number_gkto) # if it was not called elif not int_number_gkto: # print/write the time that the stat was called was None print("Goalkeeper Turnovers: 0") safile.write("\nGoalkeeper Turnover: 0") if int_number_kp: # print the number of the stat print("Goalkeeper Turnovers: ", string_number_kp) # write on the file safile.write("Goalkeeper Turnovers: ") safile.write(string_number_kp) # if it was not called elif not int_number_kp: # print/write the time that the stat was called was None print("Goalkeeper Turnovers: 0") safile.write("\nGoalkeeper Turnover: 0") # close the file safile.close() # break the while loop, quiting the function break # i have no idea why this is necessary but it is if ball_away: start_away = time.time() else: start_home = time.time() body()
mit
JKorf/Binance.Net
Binance.Net/Enums/ExecutionType.cs
715
namespace Binance.Net.Enums { /// <summary> /// The type of execution /// </summary> public enum ExecutionType { /// <summary> /// New /// </summary> New, /// <summary> /// Canceled /// </summary> Canceled, /// <summary> /// Replaced /// </summary> Replaced, /// <summary> /// Rejected /// </summary> Rejected, /// <summary> /// Trade /// </summary> Trade, /// <summary> /// Expired /// </summary> Expired, /// <summary> /// Amendment /// </summary> Amendment } }
mit
xtrementl/focus
tests/runtests.py
392
import os import sys from focus_unittest import TestLoader, TextTestRunner TEST_DIR = os.path.dirname(os.path.realpath(__file__)) START_DIR = os.path.join(TEST_DIR, 'unit') VERBOSITY = 1 loader = TestLoader() tests = loader.discover(START_DIR, 'test_*.py', TEST_DIR) runner = TextTestRunner(verbosity=VERBOSITY).run(tests) if runner.wasSuccessful(): sys.exit(0) else: sys.exit(1)
mit
netlogix/angular2-jsonapi
domain/paginator/load-more-paginator.js
1224
"use strict"; var paginator_1 = require('./paginator'); var LoadMorePaginator = (function () { function LoadMorePaginator(firstPage, consumerBackend) { var _this = this; this.firstPage = firstPage; this.consumerBackend = consumerBackend; this._data = []; this.paginator = new paginator_1.Paginator(firstPage, consumerBackend); this.paginator.resultPage$.subscribe(function (resultPage) { _this._data = _this._data.concat(resultPage.data); }); } LoadMorePaginator.prototype.more = function () { if (this.hasMore) { this.paginator.next(); } return this._data; }; Object.defineProperty(LoadMorePaginator.prototype, "hasMore", { get: function () { return this.paginator.hasNext; }, enumerable: true, configurable: true }); Object.defineProperty(LoadMorePaginator.prototype, "data", { get: function () { return this._data.slice(); }, enumerable: true, configurable: true }); return LoadMorePaginator; }()); exports.LoadMorePaginator = LoadMorePaginator; //# sourceMappingURL=load-more-paginator.js.map
mit
bkahlert/seqan-research
raw/pmsb13/pmsb13-data-20130530/sources/fjt74l9mlcqisdus/2013-05-10T16-04-15.171+0200/sandbox/my_sandbox/apps/blastX/blastX.cpp
2110
// BLASTX IMPLEMENTIERUNG VON ANNKATRIN BRESSIN UND MARJAN FAIZI // SOFTWAREPROJEKT VOM 2.4. - 29.5.2012 // VERSION VOM 04.MAI.2013 #include "own_functions.h" // MAIN FUNKTION ------------------------------------------------------------------------------- int main(int argc, char const ** argv){ // Klasse Variable enthält alle Parameter die der // Benutzer über Kommandozeile festlegen kann // -> own_functions.h Variable comVal; // comVal wird mit default Parameter initialisiert // -> parse_arguments.cpp DEFAULT_VALUES(comVal); // Eingabe vom Benutzer wird gelesen und default // Parameter wenn Eingabe vorhanden ist ueberschrieben if (argc>=2){ // -> parse_arguments.cpp if (PARSE_ARGUMENTS(argc,argv,comVal)) return 1; } // Alphabet enthält nach GET_ALPHABET numb_alp mal // String<int> der laenge einundzwanzig wobei jede Position // eine AS repraesentiert und der Eintrag der // jeweiligen zugehoerigen Gruppe (reduziertes Alphabet) // in diesem Alphabet // -> alphabet.cpp StringSet<String<AminoAcid> > forceAlphabet = GET_ALPHABET_FORCE(); unsigned alpGroup = 10; unsigned number = 1; StringSet<String<int> > alphabet = GET_ALPHABET(alpGroup, number); /*for(unsigned i = 0; i < length(alphabet); ++i) { cout<<alphabet[i]<<endl; } */ StringSet<String<Dna> > Reads; StringSet<String<char> > ReadID; // fuellen der Container // -> own_functions.h if (GET_DATAS(comVal.fastq_file,Reads,ReadID)) return 1; StrSetSA Proteine; StringSet<String<char> > ProteinID; // fuellen der Container // -> own_functions.h if (GET_DATAS(comVal.fasta_file,Proteine,ProteinID)) return 1; // kontrolle der Eingabeparameter auf Machbarkeit if (check_values(comVal,Reads)==1) return 1; // fuer alle alphabete werden matches gesucht verifiziert und ausgegeben if (FIND_MATCHES_FOR_ALL(Reads,ReadID,Proteine,ProteinID,comVal.seed,comVal.hamming_distance,forceAlphabet)==1) return 1; return 0; } // MAIN FUNKTION -------------------------------------------------------------------------------
mit
InnovateUKGitHub/innovation-funding-service
ifs-web-service/ifs-competition-mgt-service/src/main/java/org/innovateuk/ifs/management/competition/setup/milestone/populator/MilestonesFormPopulator.java
3531
package org.innovateuk.ifs.management.competition.setup.milestone.populator; import org.innovateuk.ifs.competition.resource.CompetitionResource; import org.innovateuk.ifs.competition.resource.CompetitionSetupSection; import org.innovateuk.ifs.competition.resource.MilestoneResource; import org.innovateuk.ifs.competition.resource.MilestoneType; import org.innovateuk.ifs.competition.service.MilestoneRestService; import org.innovateuk.ifs.management.competition.setup.core.form.CompetitionSetupForm; import org.innovateuk.ifs.management.competition.setup.core.form.GenericMilestoneRowForm; import org.innovateuk.ifs.management.competition.setup.core.populator.CompetitionSetupFormPopulator; import org.innovateuk.ifs.management.competition.setup.core.service.CompetitionSetupMilestoneService; import org.innovateuk.ifs.management.competition.setup.milestone.form.MilestoneRowForm; import org.innovateuk.ifs.management.competition.setup.milestone.form.MilestonesForm; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.time.ZonedDateTime; import java.util.Comparator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; /** * Form populator for the milestones competition setup section. */ @Service public class MilestonesFormPopulator implements CompetitionSetupFormPopulator { @Autowired private MilestoneRestService milestoneRestService; @Autowired private CompetitionSetupMilestoneService competitionSetupMilestoneService; @Override public CompetitionSetupSection sectionToFill() { return CompetitionSetupSection.MILESTONES; } @Override public CompetitionSetupForm populateForm(CompetitionResource competitionResource) { MilestonesForm competitionSetupForm = new MilestonesForm(); List<MilestoneResource> milestonesByCompetition = milestoneRestService.getAllMilestonesByCompetitionId(competitionResource.getId()).getSuccess(); if (milestonesByCompetition.isEmpty()) { milestonesByCompetition.addAll(competitionSetupMilestoneService.createMilestonesForIFSCompetition(competitionResource.getId()).getSuccess()); } else { milestonesByCompetition = milestonesByCompetition.stream() .filter(m -> !competitionResource.isAlwaysOpen() || MilestoneType.alwaysOpenCompSetupMilestones().contains(m.getType())) .sorted(Comparator.comparing(MilestoneResource::getType)) .collect(Collectors.toList()); } Map<String, GenericMilestoneRowForm> milestoneFormEntries = new LinkedHashMap<>(); milestonesByCompetition.stream().forEachOrdered(milestone -> milestoneFormEntries.put(milestone.getType().name(), populateMilestoneFormEntries(milestone, competitionResource)) ); competitionSetupForm.setMilestoneEntries(milestoneFormEntries); return competitionSetupForm; } private MilestoneRowForm populateMilestoneFormEntries(MilestoneResource milestone, CompetitionResource competitionResource) { return new MilestoneRowForm(milestone.getType(), milestone.getDate(), isEditable(milestone, competitionResource)); } private boolean isEditable(MilestoneResource milestone, CompetitionResource competitionResource) { return !competitionResource.isSetupAndLive() || milestone.getDate() == null || milestone.getDate().isAfter(ZonedDateTime.now()); } }
mit
Mazuh/UrnaEleitoral
src/painel_comite.php
3453
<?php session_start(); function __autoload($file){ if(file_exists('class/' . $file . '.php')){ require_once('class/' . $file . '.php'); } else{ exit('O arquivo ' . $file . ' não encontrado.'); } } // auth $usuario = unserialize($_SESSION["membro_comite"]) or die("Você não está autorizado a ver esta página."); ?> <!DOCTYPE html> <html lang="pt-br"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta charset="utf-8"> <title>Painel do Comitê Eleitoral</title> <meta name="generator" content="Bootply" /> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> <link href="css/bootstrap.min.css" rel="stylesheet"> <script type="text/javascript"> function pedirMatricula(){ var matricula = window.prompt("Membro do comitê, confirme sua matrícula se deseja realmente ver os resultados finais:"); if (matricula == "<?php echo $usuario->getMatricula() ; ?>"){ window.location = "resultado_final.php"; } else{ alert("Tá bom. Vou esquecer que você clicou aí."); } } </script> </head> <body style="background: #DCDCDC;"> <div id="loginModal" class="modal show" tabindex="-1" role="dialog" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h1 class="text-center">Eleições 2015 do Grêmio Estudantil Paulo Freire</h1> <h4 class="text-center">ACESSO À URNA ELEITORAL</h4> </div> <form class="modal-body" method="post" action="urna.php"> <div class="form col-md-12 center-block"> <div class="form-group"> <label>Matrícula do eleitor:</label> <input type="number" name="matricula" class="form-control input-lg" placeholder="Matrícula"> </div> <div class="form-group"> <button type="submit" class="btn btn-success btn-lg btn-block">Acessar urna do eleitor</button> <button class="btn btn-primary btn-lg btn-block" type="button" onclick="pedirMatricula()">Ver resultado final</button> <a href="script/sair.php"><button type="button" class="btn btn-danger btn-lg btn-block">Sair</button></a> </div> </div> </form> <div class="panel-footer"> <p class="text-center"> <a href="https://opensource.org/licenses/MIT">MIT License (MIT)</a> Copyright (c) 2015 <a href="https://github.com/Mazuh/UrnaEleitoral-GremioIFRNZN"> Marcell Guilherme & Yuri Henrique </a> </p> </div> </div> </div> </div> </body> </html>
mit
dominikgrygiel/e-0.3.6
lib/e/helpers/status.rb
636
class E # kindly borrowed from Sinatra Framework # whether or not the status is set to 1xx def informational? status.between? 100, 199 end # whether or not the status is set to 2xx def success? status.between? 200, 299 end # whether or not the status is set to 3xx def redirect? status.between? 300, 399 end # whether or not the status is set to 4xx def client_error? status.between? 400, 499 end # whether or not the status is set to 5xx def server_error? status.between? 500, 599 end # whether or not the status is set to 404 def not_found? status == 404 end end
mit
kyerematics/mesaknust
header.php
1945
<?php /** * Created by PhpStorm. * User: joe * Date: 02/10/2016 * Time: 19:59 */ ?> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>MESA</title> <link rel="stylesheet" href="css/bootstrap.min.css" /> <link rel="stylesheet" href="css/custom.css" /> <!--[if IE]> <script src="js/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <header> <!--Navigation--> <div class="row"> <div class="col-lg-8 col-md 8"> <nav class="navbar navbar-default navbar-brand" role="navigation"> <div class="navbar-header"> <a class="navbar-brand" href="index.php"> <img alt="mesa" src="images/logo.png"> </a> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#collapse"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> </div> <div class="collapse navbar-collapse" id="collapse"> <ul class="nav navbar-nav"> <li class="active"><a href="#">Home</a></li> <li><a href="#">Academics</a></li> <li><a href="#">Community</a></li> <li><a href="#">Gallery</a></li> <li><a href="#">About</a></li> </ul> </div> </nav><!--End of Navigation--> </div> </header><!-- End of header-->
mit
roroacms/roroacms
app/controllers/roroacms/comments_controller.rb
1236
require_dependency "roroacms/application_controller" module Roroacms class CommentsController < ApplicationController # CommentsController is simply used for the blog comments form. On post it will save the data in the database for the admin to filter. include Roroacms::CommentsHelper def create # Check to see if comments are actually allowed, this can be switched on and off in the admin panel if comments_on session[:return_to] = request.referer @comment = Comment.new(comments_params) respond_to do |format| if @comment.save Roroacms::Emailer.comment(@comment).deliver format.html { redirect_to "#{session[:return_to]}#commentsArea", notice: comments_success_message.html_safe } else format.html { redirect_to "#{session[:return_to]}#commentsArea", notice: comments_error_display(@comment).html_safe} end end else render :inline => I18n.t("controllers.comments.create.error") end end private # Strong parameters def comments_params params.require(:comment).permit(:post_id, :author, :email, :website, :comment, :parent_id) end end end
mit
manisharc/CPTweetsM
app/src/main/java/com/codepath/apps/CPTweetsM/activities/TimelineActivity.java
6452
package com.codepath.apps.CPTweetsM.activities; import android.content.Intent; import android.databinding.DataBindingUtil; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.View; import android.widget.ImageView; import android.widget.Toast; import com.astuetz.PagerSlidingTabStrip; import com.bumptech.glide.Glide; import com.codepath.apps.CPTweetsM.R; import com.codepath.apps.CPTweetsM.TwitterApplication; import com.codepath.apps.CPTweetsM.adapters.TweetsPagerAdapter; import com.codepath.apps.CPTweetsM.databinding.ActivityTimelineBinding; import com.codepath.apps.CPTweetsM.fragments.ComposeTweetFragment; import com.codepath.apps.CPTweetsM.fragments.HomeTimelineFragment; import com.codepath.apps.CPTweetsM.fragments.TweetsListFragment; import com.codepath.apps.CPTweetsM.models.Tweet; import com.codepath.apps.CPTweetsM.models.User; import com.codepath.apps.CPTweetsM.network.NetworkStatus; import com.codepath.apps.CPTweetsM.network.TwitterClient; import com.loopj.android.http.JsonHttpResponseHandler; import org.json.JSONObject; import cz.msebera.android.httpclient.Header; import jp.wasabeef.glide.transformations.CropCircleTransformation; public class TimelineActivity extends AppCompatActivity implements TweetsListFragment.TweetsListActionListener, ComposeTweetFragment.ComposeTweetDialogListener { private ActivityTimelineBinding binding; TwitterClient client; private boolean isOnline = true; private Toolbar toolbar; ViewPager vpPager; User currentUser; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_timeline); client = TwitterApplication.getRestClient(); binding = DataBindingUtil.setContentView(this, R.layout.activity_timeline); // Set a Toolbar to replace the ActionBar. toolbar = (Toolbar) findViewById(R.id.toolbar); //toolbar = binding.toolbar; setSupportActionBar(toolbar); getSupportActionBar().setDisplayShowHomeEnabled(true); getSupportActionBar().setElevation(0); getSupportActionBar().setLogo(R.drawable.twitter); getSupportActionBar().setDisplayUseLogoEnabled(true); getSupportActionBar().setTitle(""); getCurrentUser(); NetworkStatus networkStatus = NetworkStatus.getSharedInstance(); isOnline = networkStatus.checkNetworkStatus(getApplicationContext()); vpPager = binding.viewpager; vpPager.setAdapter(new TweetsPagerAdapter(getSupportFragmentManager())); PagerSlidingTabStrip tabStrip = binding.tabs; tabStrip.setViewPager(vpPager); } @Override public void onAddNewTweet() { if (isOnline) { FragmentManager fm = getSupportFragmentManager(); ComposeTweetFragment editNameDialogFragment = ComposeTweetFragment.newInstance(null); editNameDialogFragment.show(fm, "fragment_compose_tweet"); } else Toast.makeText(getApplicationContext(), "You are offline. Can't update tweet", Toast.LENGTH_LONG).show(); } @Override public void onReplyTweet(Tweet tweet) { if (isOnline) { FragmentManager fm = getSupportFragmentManager(); ComposeTweetFragment editNameDialogFragment = ComposeTweetFragment.newInstance(tweet); editNameDialogFragment.show(fm, "fragment_compose_tweet"); } else Toast.makeText(getApplicationContext(), "You are offline. Can't reply to tweets", Toast.LENGTH_LONG).show(); } @Override public void onItemClickDetailView(Tweet tweet) { if (isOnline) { Intent i = new Intent(getApplicationContext(), TweetDetailActivity.class); i.putExtra("tweet", tweet); startActivity(i); } else Toast.makeText(getApplicationContext(), "You are offline. Can't see details.", Toast.LENGTH_LONG).show(); } @Override public void onProfilePicClick(User user) { if (isOnline) { Intent i = new Intent(this, ProfileActivity.class); i.putExtra("screen_name", user.getScreenName()); startActivity(i); } else Toast.makeText(getApplicationContext(), "You are offline. Can't see details.", Toast.LENGTH_LONG).show(); } public void onFinishComposeDialog(Tweet newTweet) { HomeTimelineFragment homeTimeline = (HomeTimelineFragment) getSupportFragmentManager() .findFragmentByTag("android:switcher:" + R.id.viewpager + ":" + "0"); Fragment currentTimeline = getSupportFragmentManager() .findFragmentByTag("android:switcher:" + R.id.viewpager + ":" + vpPager.getCurrentItem()); if (currentTimeline != null) { if (!(currentTimeline instanceof HomeTimelineFragment)) { vpPager.setCurrentItem(0); } homeTimeline.addTweet(newTweet); } } // Menu icons are inflated just as they were with actionbar @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } public void getCurrentUser(){ client.getUserInfo(new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { currentUser = User.fromJSON(response); ImageView profileView = (ImageView) toolbar.findViewById(R.id.miProfile); Glide.with(getApplicationContext()).load(currentUser.getProfileImageUrl()) .bitmapTransform(new CropCircleTransformation(getApplicationContext())) .into(profileView); } }); } public void onProfileViewToolbar(View view) { // Launch the profile view Intent i = new Intent(this, ProfileActivity.class); if (currentUser != null) i.putExtra("screen_name", currentUser.getScreenName()); startActivity(i); } }
mit
cookpad/arproxy
spec/arproxy_spec.rb
3925
require "spec_helper" describe Arproxy do before do allow(Arproxy).to receive(:logger) { Logger.new('/dev/null') } end class ProxyA < Arproxy::Base def execute(sql, name) super "#{sql}_A", "#{name}_A" end end class ProxyB < Arproxy::Base def initialize(opt=nil) @opt = opt end def execute(sql, name) super "#{sql}_B#{@opt}", "#{name}_B#{@opt}" end end module ::ActiveRecord module ConnectionAdapters class DummyAdapter def execute(sql, name = nil) {:sql => sql, :name => name} end end end end let(:connection) { ::ActiveRecord::ConnectionAdapters::DummyAdapter.new } subject { connection.execute "SQL", "NAME" } after(:each) do Arproxy.disable! end context "with a proxy" do before do Arproxy.clear_configuration Arproxy.configure do |config| config.adapter = "dummy" config.use ProxyA end Arproxy.enable! end it { should == {:sql => "SQL_A", :name => "NAME_A"} } end context "with 2 proxies" do before do Arproxy.clear_configuration Arproxy.configure do |config| config.adapter = "dummy" config.use ProxyA config.use ProxyB end Arproxy.enable! end it { should == {:sql => "SQL_A_B", :name => "NAME_A_B"} } end context "with 2 proxies which have an option" do before do Arproxy.clear_configuration Arproxy.configure do |config| config.adapter = "dummy" config.use ProxyA config.use ProxyB, 1 end Arproxy.enable! end it { should == {:sql => "SQL_A_B1", :name => "NAME_A_B1"} } end context do before do Arproxy.clear_configuration Arproxy.configure do |config| config.adapter = "dummy" config.use ProxyA end end context "enable -> disable" do before do Arproxy.enable! Arproxy.disable! end it { should == {:sql => "SQL", :name => "NAME"} } end context "enable -> enable" do before do Arproxy.enable! Arproxy.enable! end it { should == {:sql => "SQL_A", :name => "NAME_A"} } end context "enable -> disable -> disable" do before do Arproxy.enable! Arproxy.disable! Arproxy.disable! end it { should == {:sql => "SQL", :name => "NAME"} } end context "enable -> disable -> enable" do before do Arproxy.enable! Arproxy.disable! Arproxy.enable! end it { should == {:sql => "SQL_A", :name => "NAME_A"} } end context "re-configure" do before do Arproxy.configure do |config| config.use ProxyB end Arproxy.enable! end it { should == {:sql => "SQL_A_B", :name => "NAME_A_B"} } end end context "use a plug-in" do before do Arproxy.clear_configuration Arproxy.configure do |config| config.adapter = "dummy" config.plugin :test, :option_a, :option_b end Arproxy.enable! end it { should == {:sql => "SQL_PLUGIN", :name => "NAME_PLUGIN", :options => [:option_a, :option_b]} } end context "ProxyChain thread-safety" do class ProxyWithConnectionId < Arproxy::Base def execute(sql, name) sleep 0.1 super "#{sql} /* connection_id=#{self.proxy_chain.connection.object_id} */", name end end before do Arproxy.clear_configuration Arproxy.configure do |config| config.adapter = "dummy" config.use ProxyWithConnectionId end Arproxy.enable! end context "with two threads" do let!(:thr1) { Thread.new { connection.dup.execute 'SELECT 1' } } let!(:thr2) { Thread.new { connection.dup.execute 'SELECT 1' } } it { expect(thr1.value).not_to eq(thr2.value) } end end end
mit
bstaykov/Telerik-DSA
2015/HashTablesAndSets/06.PhoneBook/PhoneBookItem.cs
406
namespace _06.PhoneBook { public class PhoneBookItem { public PhoneBookItem(string name, string town, string phoneNumber) { this.Name = name; this.Town = town; this.PhoneNumber = phoneNumber; } public string Name { get; set; } public string Town { get; set; } public string PhoneNumber { get; set; } } }
mit
itoufo/stoq-web2
src/js/plugins/jsgrid/js/jsgrid-script.js
8464
$(function() { // Static Data $("#jsGrid-static").jsGrid({ height: "70%", width: "100%", sorting: true, paging: true, fields: [ { name: "Name", type: "text", width: 150 }, { name: "Age", type: "number", width: 50 }, { name: "Address", type: "text", width: 200 }, { name: "Country", type: "select", items: db.countries, valueField: "Id", textField: "Name" }, { name: "Married", type: "checkbox", title: "Is Married" } ], data: db.clients }); // Basic Data $("#jsGrid-basic").jsGrid({ height: "70%", width: "100%", filtering: true, editing: true, sorting: true, paging: true, autoload: true, pageSize: 15, pageButtonCount: 5, deleteConfirm: "Do you really want to delete the client?", controller: db, fields: [ { name: "Name", type: "text", width: 150 }, { name: "Age", type: "number", width: 50 }, { name: "Address", type: "text", width: 200 }, { name: "Country", type: "select", items: db.countries, valueField: "Id", textField: "Name" }, { name: "Married", type: "checkbox", title: "Is Married", sorting: false }, { type: "control" } ] }); // OData Service $("#jsGrid-odata").jsGrid({ height: "auto", width: "100%", sorting: true, paging: false, autoload: true, controller: { loadData: function() { var d = $.Deferred(); $.ajax({ url: "http://services.odata.org/V3/(S(3mnweai3qldmghnzfshavfok))/OData/OData.svc/Products", dataType: "json" }).done(function(response) { d.resolve(response.value); }); return d.promise(); } }, fields: [ { name: "Name", type: "text" }, { name: "Description", type: "textarea", width: 150 }, { name: "Rating", type: "number", width: 50, align: "center", itemTemplate: function(value) { return $("<div>").addClass("rating").append(Array(value + 1).join("&#9733;")); } }, { name: "Price", type: "number", width: 50, itemTemplate: function(value) { return value.toFixed(2) + "$"; } } ] }); // Sorting $("#jsGrid-sorting").jsGrid({ height: "80%", width: "100%", autoload: true, selecting: false, controller: db, fields: [ { name: "Name", type: "text", width: 150 }, { name: "Age", type: "number", width: 50 }, { name: "Address", type: "text", width: 200 }, { name: "Country", type: "select", items: db.countries, valueField: "Id", textField: "Name" }, { name: "Married", type: "checkbox", title: "Is Married" } ] }); $("#sortingField").change(function() { var field = $(this).val(); $("#jsGrid-sorting").jsGrid("sort", field); }); $("#jsGrid-page").jsGrid({ height: "70%", width: "100%", autoload: true, paging: true, pageLoading: true, pageSize: 15, pageIndex: 2, controller: { loadData: function(filter) { var startIndex = (filter.pageIndex - 1) * filter.pageSize; return { data: db.clients.slice(startIndex, startIndex + filter.pageSize), itemsCount: db.clients.length }; } }, fields: [ { name: "Name", type: "text", width: 150 }, { name: "Age", type: "number", width: 50 }, { name: "Address", type: "text", width: 200 }, { name: "Country", type: "select", items: db.countries, valueField: "Id", textField: "Name" }, { name: "Married", type: "checkbox", title: "Is Married" } ] }); $("#pager").on("change", function() { var page = parseInt($(this).val(), 10); $("#jsGrid-page").jsGrid("openPage", page); }); // Custom View $("#jsGrid-custom").jsGrid({ height: "70%", width: "100%", filtering: true, editing: true, sorting: true, paging: true, autoload: true, pageSize: 15, pageButtonCount: 5, controller: db, fields: [ { name: "Name", type: "text", width: 150 }, { name: "Age", type: "number", width: 50 }, { name: "Address", type: "text", width: 200 }, { name: "Country", type: "select", items: db.countries, valueField: "Id", textField: "Name" }, { name: "Married", type: "checkbox", title: "Is Married", sorting: false }, { type: "control", modeSwitchButton: false, editButton: false } ] }); $(".configs-panel input[type=checkbox]").on("click", function() { var $cb = $(this); $("#jsGrid-custom").jsGrid("option", $cb.attr("id"), $cb.is(":checked")); }); // Custom Row Renderer $("#jsGrid-custom-row").jsGrid({ height: "90%", width: "100%", autoload: true, paging: true, controller: { loadData: function() { var deferred = $.Deferred(); $.ajax({ url: 'http://api.randomuser.me/?results=40', dataType: 'json', success: function(data){ deferred.resolve(data.results); } }); return deferred.promise(); } }, rowRenderer: function(item) { var user = item.user; var $photo = $("<div>").addClass("client-photo").append($("<img>").attr("src", user.picture.medium)); var $info = $("<div>").addClass("client-info") .append($("<p>").append($("<strong>").text(user.name.first.capitalize() + " " + user.name.last.capitalize()))) .append($("<p>").text("Location: " + user.location.city.capitalize() + ", " + user.location.street)) .append($("<p>").text("Email: " + user.email)) .append($("<p>").text("Phone: " + user.phone)) .append($("<p>").text("Cell: " + user.cell)); return $("<tr>").append($("<td>").append($photo).append($info)); }, fields: [ { title: "Clients" } ] }); String.prototype.capitalize = function() { return this.charAt(0).toUpperCase() + this.slice(1); }; });
mit
trelly/stoneoa
application/controllers/Contact.php
482
<?php /** * 联系管理 */ class ContactController extends Controller{ public function init(){ } public function IndexAction(){ $this->scripts[] = '/public/stone/approve.js'; $this->content = $this->getView()->render('contact/index.phtml',array()); } public function listAction(){ $this->scripts[] = '/public/stone/contact_list.js'; $this->content = $this->getView()->render('contact/list.phtml',array()); } }
mit
phlipper/chef-percona
recipes/default.rb
78
# # Cookbook:: percona # Recipe:: default # include_recipe 'percona::client'
mit
azzahrafz99/Appron-Revisi
application/views/browse.php
79
<?php $this->load->view('menubar/v_menubar'); $this->load->view('v_browse');
mit
muddyfish/PYKE
node/product.py
1254
#!/usr/bin/env python import datetime import ephem from nodes import Node from type.type_time import TypeTime class Product(Node): char = "B" args = 1 results = 1 contents = "><+-.,[]" # Possible bytes in a BF program @Node.test_func([[1,2]], [2]) @Node.test_func([[3,4]], [12]) @Node.test_func([[3,4,2]], [24]) def func(self, inp: Node.sequence): """return product of integer sequence""" current = 1 for val in inp: if isinstance(val, Node.sequence): current *= self.func(val)[0] else: current *= val return [current] def to_int(self, inp:Node.number): """Return int(inp)""" return int(inp) @Node.test_func(["HELLO"], [1]) @Node.test_func(["World7"], [0]) @Node.test_func(["@"], [0]) def is_alpha(self, string:str): """Is a string alphabetic?""" return int(string.isalpha()) def get_next_full_moon(self, time: Node.clock): """Gets the date of the next full moon""" new_time = datetime.datetime(*time.time_obj[:7]) rtn_time = ephem.next_full_moon(new_time).datetime() return TypeTime.parse_struct_time(rtn_time.timetuple())
mit
miconblog/parse-react-redux-router-intl
app/actions/parse.js
2393
/** * Redux Actions for ParseSever * */ import { PARSE, Schemas } from '../middleware/parse' export const PARSE_FETCH_REQUEST = 'PARSE_FETCH_REQUEST'; export const PARSE_FETCH_SUCCESS = 'PARSE_FETCH_SUCCESS'; export const PARSE_FETCH_FAILURE = 'PARSE_FETCH_FAILURE'; export function fetch(params) { const schema = Schemas[`${params.objectName.toUpperCase()}_ARRAY`]; return (dispatch, getState) => { return dispatch(function() { return { [PARSE]: { method: 'fetch', types: [ PARSE_FETCH_REQUEST, PARSE_FETCH_SUCCESS, PARSE_FETCH_FAILURE ], schema: schema, params: params } } }()) } } export const PARSE_ADD_REQUEST = 'PARSE_ADD_REQUEST'; export const PARSE_ADD_SUCCESS = 'PARSE_ADD_SUCCESS'; export const PARSE_ADD_FAILURE = 'PARSE_ADD_FAILURE'; export function add(params) { const schema = Schemas[`${params.objectName.toUpperCase()}`]; return (dispatch, getState) => { return dispatch(function() { return { [PARSE]: { method: 'add', types: [ PARSE_ADD_REQUEST, PARSE_ADD_SUCCESS, PARSE_ADD_FAILURE ], schema: schema, params: params } } }()) } } export const PARSE_UPDATE_REQUEST = 'PARSE_UPDATE_REQUEST'; export const PARSE_UPDATE_SUCCESS = 'PARSE_UPDATE_SUCCESS'; export const PARSE_UPDATE_FAILURE = 'PARSE_UPDATE_FAILURE'; export function update(params) { const schema = Schemas[`${params.objectName.toUpperCase()}`]; return (dispatch, getState) => { return dispatch(function() { return { [PARSE]: { method: 'update', types: [ PARSE_UPDATE_REQUEST, PARSE_UPDATE_SUCCESS, PARSE_UPDATE_FAILURE ], schema: schema, params: params } } }()) } } export const PARSE_REMOVE_REQUEST = 'PARSE_REMOVE_REQUEST'; export const PARSE_REMOVE_SUCCESS = 'PARSE_REMOVE_SUCCESS'; export const PARSE_REMOVE_FAILURE = 'PARSE_REMOVE_FAILURE'; export function remove(params) { const schema = Schemas[`${params.objectName.toUpperCase()}`]; return (dispatch, getState) => { return dispatch(function() { return { [PARSE]: { method: 'remove', types: [ PARSE_REMOVE_REQUEST, PARSE_REMOVE_SUCCESS, PARSE_REMOVE_FAILURE ], schema: schema, params: params } } }()) } }
mit
najd-mrabet/federation-tunisienne-tennis
src/Ftt/GestionActualiteBundle/Entity/ActualiteRepository.php
276
<?php namespace Ftt\GestionActualiteBundle\Entity; use Doctrine\ORM\EntityRepository; /** * ActualiteRepository * * This class was generated by the Doctrine ORM. Add your own custom * repository methods below. */ class ActualiteRepository extends EntityRepository { }
mit
yiq/SubcloneSeeker
test/TestGenomicLocation.cc
1324
/** * @file Unit tests for class GenomicLocation * * @see GenomicLocation * @author Yi Qiao */ /* The MIT License (MIT) Copyright (c) 2013 Yi Qiao 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: 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. */ #include "GenomicLocation.h" #include "common.h" SUITE(testGenomicLocation) { TEST(ObjectCreation) { SubcloneSeeker::GenomicLocation loc; CHECK( true /* object creation should always pass */); } } TEST_MAIN
mit
51breeze/breezejs
javascript/fix/Function-ie-9.js
784
/** * 绑定一个对象到返回的函数中 * 返回一个函数 * @type {bind} */ Function.prototype.bind = $Function.prototype.bind; if( !$Function.prototype.bind ) { Function.prototype.bind = function bind(thisArg) { if (typeof this !== "function")throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable"); var args = Array.prototype.slice.call(arguments, 1), fn = this, Nop = function () { }, Bound = function () { return fn.apply(this instanceof Nop ? this : thisArg || this, args.concat(Array.prototype.slice.call(arguments))); }; Nop.prototype = this.prototype; Bound.prototype = new Nop(); return Bound; }; }
mit
DragonSpark/Framework
DragonSpark.Application/Runtime/IThrottling.cs
144
using DragonSpark.Model.Operations; namespace DragonSpark.Application.Runtime; public interface IThrottling<T> : IOperation<Throttle<T>> {}
mit
Maroc-OS/nheqminer
nheqminer/zcash/JoinSplit.hpp
2903
#ifndef _ZCJOINSPLIT_H_ #define _ZCJOINSPLIT_H_ #include "Address.hpp" #include "IncrementalMerkleTree.hpp" #include "Note.hpp" #include "NoteEncryption.hpp" #include "Proof.hpp" #include "Zcash.h" #include "uint252.h" #include "uint256.h" #include <boost/array.hpp> namespace libzcash { class JSInput { public: ZCIncrementalWitness witness; Note note; SpendingKey key; JSInput(); JSInput(ZCIncrementalWitness witness, Note note, SpendingKey key) : witness(witness), note(note), key(key) {} uint256 nullifier() const { return note.nullifier(key); } }; class JSOutput { public: PaymentAddress addr; uint64_t value; boost::array<unsigned char, ZC_MEMO_SIZE> memo = { {0xF6}}; // 0xF6 is invalid UTF8 as per spec, rest of array is 0x00 JSOutput(); JSOutput(PaymentAddress addr, uint64_t value) : addr(addr), value(value) {} Note note(const uint252 &phi, const uint256 &r, size_t i, const uint256 &h_sig) const; }; template <size_t NumInputs, size_t NumOutputs> class JoinSplit { public: virtual ~JoinSplit() {} static JoinSplit<NumInputs, NumOutputs> *Generate(); static JoinSplit<NumInputs, NumOutputs> *Unopened(); static uint256 h_sig(const uint256 &randomSeed, const boost::array<uint256, NumInputs> &nullifiers, const uint256 &pubKeyHash); // TODO: #789 virtual void setProvingKeyPath(std::string) = 0; virtual void loadProvingKey() = 0; virtual void saveProvingKey(std::string path) = 0; virtual void loadVerifyingKey(std::string path) = 0; virtual void saveVerifyingKey(std::string path) = 0; virtual void saveR1CS(std::string path) = 0; virtual ZCProof prove(const boost::array<JSInput, NumInputs> &inputs, const boost::array<JSOutput, NumOutputs> &outputs, boost::array<Note, NumOutputs> &out_notes, boost::array<ZCNoteEncryption::Ciphertext, NumOutputs> &out_ciphertexts, uint256 &out_ephemeralKey, const uint256 &pubKeyHash, uint256 &out_randomSeed, boost::array<uint256, NumInputs> &out_hmacs, boost::array<uint256, NumInputs> &out_nullifiers, boost::array<uint256, NumOutputs> &out_commitments, uint64_t vpub_old, uint64_t vpub_new, const uint256 &rt, bool computeProof = true) = 0; virtual bool verify(const ZCProof &proof, ProofVerifier &verifier, const uint256 &pubKeyHash, const uint256 &randomSeed, const boost::array<uint256, NumInputs> &hmacs, const boost::array<uint256, NumInputs> &nullifiers, const boost::array<uint256, NumOutputs> &commitments, uint64_t vpub_old, uint64_t vpub_new, const uint256 &rt) = 0; protected: JoinSplit() {} }; } typedef libzcash::JoinSplit<ZC_NUM_JS_INPUTS, ZC_NUM_JS_OUTPUTS> ZCJoinSplit; #endif // _ZCJOINSPLIT_H_
mit
mezae/pfptech
modules/core/client/app/config.js
832
'use strict'; // Init the application configuration module for AngularJS application var ApplicationConfiguration = (function() { // Init module configuration options var applicationModuleName = 'pfptech'; var applicationModuleVendorDependencies = ['ngResource', 'ui.router', 'ui.bootstrap', 'ui.utils', 'angularFileUpload', 'ngCkeditor', 'ngSanitize']; // Add a new vertical module var registerModule = function(moduleName, dependencies) { // Create angular module angular.module(moduleName, dependencies || []); // Add the module to the AngularJS configuration file angular.module(applicationModuleName).requires.push(moduleName); }; return { applicationModuleName: applicationModuleName, applicationModuleVendorDependencies: applicationModuleVendorDependencies, registerModule: registerModule }; })();
mit
infosimples/ir_investidor
config/environments/production.rb
3694
Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # Code is not reloaded between requests. config.cache_classes = true # Eager load code on boot. This eager loads most of Rails and # your application in memory, allowing both threaded web servers # and those relying on copy on write to perform better. # Rake tasks automatically ignore this option for performance. config.eager_load = true # Full error reports are disabled and caching is turned on. config.consider_all_requests_local = false config.action_controller.perform_caching = true # Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"] # or in config/master.key. This key is used to decrypt credentials (and other encrypted files). # config.require_master_key = true # Disable serving static files from the `/public` folder by default since # Apache or NGINX already handles this. config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present? # Compress JavaScripts and CSS. config.assets.js_compressor = :uglifier # config.assets.css_compressor = :sass # Do not fallback to assets pipeline if a precompiled asset is missed. config.assets.compile = false # `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb # Enable serving of images, stylesheets, and JavaScripts from an asset server. # config.action_controller.asset_host = 'http://assets.example.com' # Specifies the header that your server uses for sending files. # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX # Store uploaded files on the local file system (see config/storage.yml for options) config.active_storage.service = :local # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. # config.force_ssl = true # Use the lowest log level to ensure availability of diagnostic information # when problems arise. config.log_level = :debug # Prepend all log lines with the following tags. config.log_tags = [ :request_id ] # Use a different cache store in production. # config.cache_store = :mem_cache_store # Use a real queuing backend for Active Job (and separate queues per environment) # config.active_job.queue_adapter = :resque # config.active_job.queue_name_prefix = "ir_investidor_#{Rails.env}" config.action_mailer.perform_caching = false # Ignore bad email addresses and do not raise email delivery errors. # Set this to true and configure the email server for immediate delivery to raise delivery errors. # config.action_mailer.raise_delivery_errors = false # Enable locale fallbacks for I18n (makes lookups for any locale fall back to # the I18n.default_locale when a translation cannot be found). config.i18n.fallbacks = true # Send deprecation notices to registered listeners. config.active_support.deprecation = :notify # Use default logging formatter so that PID and timestamp are not suppressed. config.log_formatter = ::Logger::Formatter.new # Use a different logger for distributed setups. # require 'syslog/logger' # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name') if ENV["RAILS_LOG_TO_STDOUT"].present? logger = ActiveSupport::Logger.new(STDOUT) logger.formatter = config.log_formatter config.logger = ActiveSupport::TaggedLogging.new(logger) end # Do not dump schema after migrations. config.active_record.dump_schema_after_migration = false end
mit
cignoir/trinamo
spec/trinamo/converter/base_converter_spec.rb
163
require 'spec_helper' require 'unindent' describe Trinamo::BaseConverter do it 'has been defined' do expect(Trinamo::BaseConverter).not_to be nil end end
mit
shrift/ads_demo
app/src/main/java/com/bubbletastic/android/appia/ads/service/AdvertisementService.java
464
package com.bubbletastic.android.appia.ads.service; import com.bubbletastic.android.appia.ads.model.Advertisement; import java.util.List; /** * Created by brendanmartens on 1/28/16. */ public interface AdvertisementService { /** * Gets a list of advertisements from Appia's service. * The list returned is filtered by the advertisements minOSVersion. * @return List of Advertisement. */ List<Advertisement> getAdvertisements(); }
mit
abc-dev/2016
tasks/scss.js
640
'use strict'; let gulp = require('gulp'); let plumber = require('gulp-plumber'); let sass = require('gulp-sass'); let autoprefixer = require('gulp-autoprefixer'); let cssnano = require('gulp-cssnano'); let rename = require('gulp-rename'); gulp.task('scss', scssTask); function scssTask() { let autoprefixerOptions = { browsers: ['last 2 versions'], cascade: false, }; return gulp .src(['src/scss/**/[^_]*.scss']) .pipe(plumber()) .pipe(sass().on('error', sass.logError)) .pipe(autoprefixer(autoprefixerOptions)) .pipe(cssnano()) .pipe(rename({suffix: '.min'})) .pipe(gulp.dest('build/css')); }
mit
luego/botb
functions.php
2308
<?php /** * Author: Ole Fredrik Lie * URL: http://olefredrik.com * * FoundationPress functions and definitions * * Set up the theme and provides some helper functions, which are used in the * theme as custom template tags. Others are attached to action and filter * hooks in WordPress to change core functionality. * * @link https://codex.wordpress.org/Theme_Development * @package FoundationPress * @since FoundationPress 1.0.0 */ /** Various clean up functions */ require_once( 'library/cleanup.php' ); /** Required for Foundation to work properly */ require_once( 'library/foundation.php' ); /** Register all navigation menus */ require_once( 'library/navigation.php' ); /** Add menu walkers for top-bar and off-canvas */ require_once( 'library/menu-walkers.php' ); /** Create widget areas in sidebar and footer */ require_once( 'library/widget-areas.php' ); /** Return entry meta information for posts */ require_once( 'library/entry-meta.php' ); /** Enqueue scripts */ require_once( 'library/enqueue-scripts.php' ); /** Add theme support */ require_once( 'library/theme-support.php' ); /** Add Nav Options to Customer */ require_once( 'library/custom-nav.php' ); /** Change WP's sticky post class */ require_once( 'library/sticky-posts.php' ); /** Configure responsive image sizes */ require_once( 'library/responsive-images.php' ); /** If your site requires protocol relative url's for theme assets, uncomment the line below */ // require_once( 'library/protocol-relative-theme-assets.php' ); /* function foundationpress_add_fields_to_ticket($default_fields) { $default_fields[] = array( 'field_name' => 'ticket_desc_name', 'field_title' => 'Ticket Description', 'tc', 'placeholder' => '', 'field_type' => 'text', 'tooltip' => __( 'Description', 'tc' ), 'table_visibility' => true, 'post_field_type' => 'post_meta' ); $default_fields[] = array( 'field_name' => 'ticket_image', 'field_title' => 'Image ticket', 'tc', 'placeholder' => '', 'field_type' => 'image', 'tooltip' => __( 'Image ticket', 'tc' ), 'table_visibility' => true, 'post_field_type' => 'post_meta' ); return $default_fields; } add_filter('tc_ticket_fields', 'foundationpress_add_fields_to_ticket');*/
mit
TeamApple/RecepiesClient
RecepiesClient/Models/RegisterUserResponseModel.cs
190
using System; namespace RecepiesClient.Models { public class RegisterUserResponseModel { public int Id { get; set; } public string Username { get; set; } } }
mit
401LearningAnalytics/Project
ui/main/usage/intro.php
3925
<?php /** * This page is scatter for Introduction to Software Product Management course. * The scatter plot shows the current time versus performance for each student. * Each dot in the plot means each student. * The color means each student process. * * @package ui * * @author Wei Song <wsong1@ualberta.ca> 2016 * * @since 1.0 * */ ?> <!DOCTYPE html> <meta charset="utf-8"> <style> /* set the CSS */ .line { fill: none; stroke: steelblue; stroke-width: 2px; } div.tooltip { position: absolute; text-align: center; width: 50px; height: 28px; padding: 2px; font: 12px sans-serif; background: lightsteelblue; border: 0px; border-radius: 8px; } .axis text { font-family: sans-serif; font-size: 11px; } </style> <body> <!-- load the d3.js library --> <script src="https://d3js.org/d3.v3.min.js"></script> <script src="https://d3js.org/d3.v4.min.js"></script> <script> // set the dimensions and margins of the graph var margin = {top: 20, right: 20, bottom: 30, left: 50}, width = 650 - margin.left - margin.right, height = 400 - margin.top - margin.bottom; // parse the date / time var parseTime = d3.timeParse("%d-%b-%Y"); var formatTime = d3.timeFormat("%Y %m %e"); // set the ranges var x = d3.scaleTime().range([0, width]); var y = d3.scaleLinear().range([height, 0]); var div = d3.select("body").append("div") .attr("class", "tooltip") .style("opacity", 0); // append the svg obgect to the body of the page // appends a 'group' element to 'svg' // moves the 'group' element to the top left margin var svg = d3.select("body").append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .call(d3.behavior.zoom().on("zoom", function () { svg.attr("transform", "translate(" + d3.event.translate + ")" + " scale(" + d3.event.scale + ")") })) .append("g"); //.attr("transform", // "translate(" + margin.left + "," + margin.top + ")"); // Get the data d3.csv("csv_file/intro.csv", function(error, data) { if (error) throw error; // format the data data.forEach(function(d) { d.id = +d.ualberta_user_id; d.date = parseTime(d.course_grade_ts); d.grade = +d.course_grade_verified; }); // scale the range of the data x.domain(d3.extent(data, function(d) { return d.date; })); y.domain([0, d3.max(data, function(d) { return d.grade; })]); colors = d3.scale.category10(); // add the dots with tooltips svg.selectAll("dot") .data(data) .enter().append("circle") .attr("r", 5) .attr("cx", function(d) { return x(d.date); }) .attr("cy", function(d) { return y(d.grade); }) .attr("fill",function(d,i){return colors(i)}) .on("mouseover", function(d) { div.transition() .duration(200) .style("opacity", .9); div .html( '<a href="studentPage.php?student_id=' + d.ualberta_user_id + '">' + // The first <a> tag formatTime(d.date) + "</a>" + // closing </a> tag "<br/>" + d.grade) .style("left", (d3.event.pageX) + "px") .style("top", (d3.event.pageY - 28) + "px"); }); // add the X Axis svg.append("g") .attr("transform", "translate(0," + height + ")") .call(d3.axisBottom(x)) ; // add the Y Axis svg.append("g") .call(d3.axisLeft(y)) ; svg.append("text") // text label for the x axis .attr("x", width / 2 ) .attr("y", height + margin.bottom ) .style("text-anchor", "middle") .text("Last Attempt Time"); svg.append("text") .attr("transform", "rotate(-90)") .attr("y", 0 - margin.left) .attr("x",0 - (height / 2)) .attr("dy", "1em") .style("text-anchor", "middle") .text("Performance"); }); </script> </body>
mit
hellorich/go-craft
craft/app/elementtypes/BaseElementType.php
16402
<?php namespace Craft; /** * The base class for all Craft element types. Any element type must extend this class. * * @author Pixel & Tonic, Inc. <support@pixelandtonic.com> * @copyright Copyright (c) 2014, Pixel & Tonic, Inc. * @license http://craftcms.com/license Craft License Agreement * @see http://craftcms.com * @package craft.app.elementtypes * @since 1.0 */ abstract class BaseElementType extends BaseComponentType implements IElementType { // Properties // ========================================================================= /** * The type of component, e.g. "Plugin", "Widget", "FieldType", etc. Defined by the component type's base class. * * @var string */ protected $componentType = 'ElementType'; /** * @var */ private $_sourcesByContext; // Public Methods // ========================================================================= // Basic info methods // ------------------------------------------------------------------------- /** * @inheritDoc IElementType::hasContent() * * @return bool */ public function hasContent() { return false; } /** * @inheritDoc IElementType::hasTitles() * * @return bool */ public function hasTitles() { return false; } /** * @inheritDoc IElementType::isLocalized() * * @return bool */ public function isLocalized() { return false; } /** * @inheritDoc IElementType::hasStatuses() * * @return bool */ public function hasStatuses() { return false; } /** * @inheritDoc IElementType::getStatuses() * * @return array|null */ public function getStatuses() { return array( BaseElementModel::ENABLED => Craft::t('Enabled'), BaseElementModel::DISABLED => Craft::t('Disabled') ); } /** * @inheritDoc IElementType::getSources() * * @param null $context * * @return array|bool|false */ public function getSources($context = null) { return false; } /** * @inheritDoc IElementType::getSource() * * @param string $key * @param null $context * * @return array|null */ public function getSource($key, $context = null) { $contextKey = ($context ? $context : '*'); if (!isset($this->_sourcesByContext[$contextKey])) { $this->_sourcesByContext[$contextKey] = $this->getSources($context); } return $this->_findSource($key, $this->_sourcesByContext[$contextKey]); } /** * @inheritDoc IElementType::getAvailableActions() * * @param string|null $source * * @return array|null */ public function getAvailableActions($source = null) { return array(); } /** * @inheritDoc IElementType::defineSearchableAttributes() * * @return array */ public function defineSearchableAttributes() { return array(); } // Element index methods // ------------------------------------------------------------------------- /** * @inheritDoc IElementType::getIndexHtml() * * @param ElementCriteriaModel $criteria * @param array $disabledElementIds * @param array $viewState * @param null|string $sourceKey * @param null|string $context * @param bool $includeContainer * @param bool $showCheckboxes * * @return string */ public function getIndexHtml($criteria, $disabledElementIds, $viewState, $sourceKey, $context, $includeContainer, $showCheckboxes) { $variables = array( 'viewMode' => $viewState['mode'], 'context' => $context, 'elementType' => new ElementTypeVariable($this), 'disabledElementIds' => $disabledElementIds, 'collapsedElementIds' => craft()->request->getParam('collapsedElementIds'), 'showCheckboxes' => $showCheckboxes, ); // Special case for sorting by structure if (isset($viewState['order']) && $viewState['order'] == 'structure') { $source = $this->getSource($sourceKey, $context); if (isset($source['structureId'])) { $criteria->order = 'lft asc'; $variables['structure'] = craft()->structures->getStructureById($source['structureId']); // Are they allowed to make changes to this structure? if ($context == 'index' && $variables['structure'] && !empty($source['structureEditable'])) { $variables['structureEditable'] = true; // Let StructuresController know that this user can make changes to the structure craft()->userSession->authorize('editStructure:'.$variables['structure']->id); } } else { unset($viewState['order']); } } else if (!empty($viewState['order']) && $viewState['order'] == 'score') { $criteria->order = 'score'; } else { $sortableAttributes = $this->defineSortableAttributes(); if ($sortableAttributes) { $order = (!empty($viewState['order']) && isset($sortableAttributes[$viewState['order']])) ? $viewState['order'] : ArrayHelper::getFirstKey($sortableAttributes); $sort = (!empty($viewState['sort']) && in_array($viewState['sort'], array('asc', 'desc'))) ? $viewState['sort'] : 'asc'; // Combine them, accounting for the possibility that $order could contain multiple values, // and be defensive about the possibility that the first value actually has "asc" or "desc" // typeId => typeId [sort] // typeId, title => typeId [sort], title // typeId, title desc => typeId [sort], title desc // typeId desc => typeId [sort] $criteria->order = preg_replace('/^(.*?)(?:\s+(?:asc|desc))?(,.*)?$/i', "$1 {$sort}$2", $order); } } switch ($viewState['mode']) { case 'table': { // Get the table columns $variables['attributes'] = $this->getTableAttributesForSource($sourceKey); // Give each attribute a chance to modify the criteria foreach ($variables['attributes'] as $attribute) { $this->prepElementCriteriaForTableAttribute($criteria, $attribute[0]); } break; } } $variables['elements'] = $criteria->find(); $template = '_elements/'.$viewState['mode'].'view/'.($includeContainer ? 'container' : 'elements'); return craft()->templates->render($template, $variables); } /** * @inheritDoc IElementType::defineSortableAttributes() * * @return array */ public function defineSortableAttributes() { $tableAttributes = craft()->elementIndexes->getAvailableTableAttributes($this->getClassHandle()); $sortableAttributes = array(); foreach ($tableAttributes as $key => $labelInfo) { $sortableAttributes[$key] = $labelInfo['label']; } return $sortableAttributes; } /** * @inheritDoc IElementType::defineAvailableTableAttributes() * * @return array */ public function defineAvailableTableAttributes() { if (method_exists($this, 'defineTableAttributes')) { // Classic. return $this->defineTableAttributes(); } return array(); } /** * @inheritDoc IElementType::getDefaultTableAttributes() * * @param string|null $source * * @return array */ public function getDefaultTableAttributes($source = null) { if (method_exists($this, 'defineTableAttributes')) { // Classic. $availableTableAttributes = $this->defineTableAttributes($source); } else { $availableTableAttributes = $this->defineAvailableTableAttributes(); } return array_keys($availableTableAttributes); } /** * @inheritDoc IElementType::getTableAttributeHtml() * * @param BaseElementModel $element * @param string $attribute * * @return mixed|string */ public function getTableAttributeHtml(BaseElementModel $element, $attribute) { switch ($attribute) { case 'link': { $url = $element->getUrl(); if ($url) { return '<a href="'.$url.'" target="_blank" data-icon="world" title="'.Craft::t('Visit webpage').'"></a>'; } else { return ''; } } case 'uri': { $url = $element->getUrl(); if ($url) { $value = $element->uri; if ($value == '__home__') { $value = '<span data-icon="home" title="'.Craft::t('Homepage').'"></span>'; } else { // Add some <wbr> tags in there so it doesn't all have to be on one line $find = array('/'); $replace = array('/<wbr>'); $wordSeparator = craft()->config->get('slugWordSeparator'); if ($wordSeparator) { $find[] = $wordSeparator; $replace[] = $wordSeparator.'<wbr>'; } $value = str_replace($find, $replace, $value); } return '<a href="'.$url.'" target="_blank" class="go" title="'.Craft::t('Visit webpage').'"><span dir="ltr">'.$value.'</span></a>'; } else { return ''; } } default: { // Is this a custom field? if (preg_match('/^field:(\d+)$/', $attribute, $matches)) { $fieldId = $matches[1]; $field = craft()->fields->getFieldById($fieldId); if ($field) { $fieldType = $field->getFieldType(); if ($fieldType && $fieldType instanceof IPreviewableFieldType) { // Was this field value eager-loaded? if ($fieldType instanceof IEagerLoadingFieldType && $element->hasEagerLoadedElements($field->handle)) { $value = $element->getEagerLoadedElements($field->handle); } else { $value = $element->getFieldValue($field->handle); } $fieldType->setElement($element); return $fieldType->getTableAttributeHtml($value); } } return ''; } $value = $element->$attribute; if ($value instanceof DateTime) { return '<span title="'.$value->localeDate().' '.$value->localeTime().'">'.$value->uiTimestamp().'</span>'; } return HtmlHelper::encode($value); } } } /** * @inheritDoc IElementType::defineCriteriaAttributes() * * @return array */ public function defineCriteriaAttributes() { return array(); } // Methods for customizing the content table // ----------------------------------------------------------------------------- /** * @inheritDoc IElementType::getContentTableForElementsQuery() * * @param ElementCriteriaModel $criteria * * @return false|string */ public function getContentTableForElementsQuery(ElementCriteriaModel $criteria) { return 'content'; } /** * @inheritDoc IElementType::getFieldsForElementsQuery() * * @param ElementCriteriaModel $criteria * * @return FieldModel[] */ public function getFieldsForElementsQuery(ElementCriteriaModel $criteria) { $contentService = craft()->content; $originalFieldContext = $contentService->fieldContext; $contentService->fieldContext = 'global'; $fields = craft()->fields->getAllFields(); $contentService->fieldContext = $originalFieldContext; return $fields; } /** * @inheritDoc IElementType::getContentFieldColumnsForElementsQuery() * * @param ElementCriteriaModel $criteria * * @deprecated Deprecated in 2.3. Element types should implement {@link getFieldsForElementsQuery()} instead. * @return array */ public function getContentFieldColumnsForElementsQuery(ElementCriteriaModel $criteria) { $columns = array(); $fields = $this->getFieldsForElementsQuery($criteria); foreach ($fields as $field) { if ($field->hasContentColumn()) { $columns[] = array( 'handle' => $field->handle, 'column' => ($field->columnPrefix ? $field->columnPrefix : 'field_') . $field->handle ); } } return $columns; } // Methods for customizing ElementCriteriaModel's for this element type... // ------------------------------------------------------------------------- /** * @inheritDoc IElementType::getElementQueryStatusCondition() * * @param DbCommand $query * @param string $status * * @return false|string|void */ public function getElementQueryStatusCondition(DbCommand $query, $status) { } /** * @inheritDoc IElementType::modifyElementsQuery() * * @param DbCommand $query * @param ElementCriteriaModel $criteria * * @return false|null|void */ public function modifyElementsQuery(DbCommand $query, ElementCriteriaModel $criteria) { } // Element methods /** * @inheritDoc IElementType::populateElementModel() * * @param array $row * * @return BaseElementModel|void */ public function populateElementModel($row) { } /** * @inheritDoc IElementType::getEagerLoadingMap() * * @param BaseElementModel[] $sourceElements * @param string $handle * * @return array|false */ public function getEagerLoadingMap($sourceElements, $handle) { // Is $handle a custom field handle? // (Leave it up to the extended class to set the field context, if it shouldn't be 'global') $field = craft()->fields->getFieldByHandle($handle); if ($field) { $fieldType = $field->getFieldType(); if ($fieldType && $fieldType instanceof IEagerLoadingFieldType) { return $fieldType->getEagerLoadingMap($sourceElements); } } return false; } /** * @inheritDoc IElementType::getEditorHtml() * * @param BaseElementModel $element * * @return string */ public function getEditorHtml(BaseElementModel $element) { $html = ''; $fieldLayout = $element->getFieldLayout(); if ($fieldLayout) { $originalNamespace = craft()->templates->getNamespace(); $namespace = craft()->templates->namespaceInputName('fields', $originalNamespace); craft()->templates->setNamespace($namespace); foreach ($fieldLayout->getFields() as $fieldLayoutField) { $fieldHtml = craft()->templates->render('_includes/field', array( 'element' => $element, 'field' => $fieldLayoutField->getField(), 'required' => $fieldLayoutField->required )); $html .= craft()->templates->namespaceInputs($fieldHtml, 'fields'); } craft()->templates->setNamespace($originalNamespace); } return $html; } /** * @inheritDoc IElementType::saveElement() * * @param BaseElementModel $element * @param array $params * * @return bool */ public function saveElement(BaseElementModel $element, $params) { return craft()->elements->saveElement($element); } /** * @inheritDoc IElementType::routeRequestForMatchedElement() * * @param BaseElementModel $element * * @return bool|mixed */ public function routeRequestForMatchedElement(BaseElementModel $element) { return false; } /** * @inheritDoc IElementType::onAfterMoveElementInStructure() * * @param BaseElementModel $element * @param int $structureId * * @return null|void */ public function onAfterMoveElementInStructure(BaseElementModel $element, $structureId) { } // Protected Methods // ========================================================================= /** * Returns the attributes that should be shown for the given source. * * @param string $sourceKey The source key * * @return array The attributes that should be shown for the given source */ protected function getTableAttributesForSource($sourceKey) { return craft()->elementIndexes->getTableAttributes($this->getClassHandle(), $sourceKey); } /** * Preps the element criteria for a given table attribute * * @param ElementCriteriaModel $criteria * @param string $attribute * * @return void */ protected function prepElementCriteriaForTableAttribute(ElementCriteriaModel $criteria, $attribute) { // Is this a custom field? if (preg_match('/^field:(\d+)$/', $attribute, $matches)) { $fieldId = $matches[1]; $field = craft()->fields->getFieldById($fieldId); if ($field) { $fieldType = $field->getFieldType(); if ($fieldType && $fieldType instanceof IEagerLoadingFieldType) { $with = $criteria->with ?: array(); $with[] = $field->handle; $criteria->with = $with; } } } } // Private Methods // ========================================================================= /** * Finds a source by its key, even if it's nested. * * @param array $sources * @param string $key * * @return array|null */ private function _findSource($key, $sources) { if (isset($sources[$key])) { return $sources[$key]; } else { // Look through any nested sources foreach ($sources as $source) { if (!empty($source['nested']) && ($nestedSource = $this->_findSource($key, $source['nested']))) { return $nestedSource; } } } } }
mit
rhythmagency/formulate
src/formulate.app/Directives/layoutEditor/layoutEditor.js
708
// Variables. var app = angular.module("umbraco"); // Associate directive/controller. app.directive("formulateLayoutEditor", directive); // Directive. function directive(formulateDirectives, $compile) { return { restrict: "E", template: formulateDirectives.get("layoutEditor/layoutEditor.html"), replace: true, scope: { directive: "=", data: "=" }, link: function (scope, element) { // Create directive. var markup = "<" + scope.directive + " data=\"data\"></" + scope.directive + ">"; var directive = $compile(markup)(scope); element.replaceWith(directive); } }; }
mit
winnlab/Optimeal
public/js/lib/funcunit/test/funcunit/open_test.js
709
module("funcunit-open") test('F.open accepts a window', function() { F.open(window); F('#tester').click(); F("#tester").text("Changed", "Changed link") F.open(frames["myapp"]); F("#typehere").type("").type("javascriptmvc") F("#seewhatyoutyped").text("typed javascriptmvc","typing"); }) test("Back to back opens", function(){ F.open("//test/myotherapp.html"); F.open("//test/myapp.html"); F("#changelink").click() F("#changelink").text("Changed","href javascript run") }) test('Testing win.confirm in multiple pages', function() { F.open('//test/open/first.html'); F('.next').click(); F('.show-confirm').click(); F.confirm(true); F('.results').text('confirmed!', "Confirm worked!"); })
mit
Juba95/newart
src/NAE/PlateformBundle/Tests/Controller/DefaultControllerTest.php
419
<?php namespace NAE\PlateformBundle\Tests\Controller; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; class DefaultControllerTest extends WebTestCase { public function testIndex() { $client = static::createClient(); $crawler = $client->request('GET', '/hello/Fabien'); $this->assertTrue($crawler->filter('html:contains("Hello Fabien")')->count() > 0); } }
mit
leotizzei/MobileMedia-Cosmos-v5
src/br/unicamp/ic/sed/mobilemedia/filesystemmgr/impl/AlbumData.java
8104
/** * University of Campinas - Brazil * Institute of Computing * SED group * * date: February 2009 * */ package br.unicamp.ic.sed.mobilemedia.filesystemmgr.impl; import java.util.Hashtable; import javax.microedition.lcdui.Image; import javax.microedition.rms.RecordStoreException; import br.unicamp.ic.sed.mobilemedia.filesystemmgr.spec.dt.ImageData; import br.unicamp.ic.sed.mobilemedia.filesystemmgr.spec.excep.ImageNotFoundException; import br.unicamp.ic.sed.mobilemedia.filesystemmgr.spec.excep.InvalidImageDataException; import br.unicamp.ic.sed.mobilemedia.filesystemmgr.spec.excep.InvalidPhotoAlbumNameException; import br.unicamp.ic.sed.mobilemedia.filesystemmgr.spec.excep.NullAlbumDataReference; import br.unicamp.ic.sed.mobilemedia.filesystemmgr.spec.excep.PersistenceMechanismException; import br.unicamp.ic.sed.mobilemedia.filesystemmgr.spec.excep.UnavailablePhotoAlbumException; import br.unicamp.ic.sed.mobilemedia.main.spec.prov.IImageData; /** * @author tyoung * * This class represents the data model for Photo Albums. A Photo Album object * is essentially a list of photos or images, stored in a Hashtable. Due to * constraints of the J2ME RecordStore implementation, the class stores a table * of the images, indexed by an identifier, and a second table of image metadata * (ie. labels, album name etc.) * * This uses the ImageAccessor class to retrieve the image data from the * recordstore (and eventually file system etc.) */ class AlbumData { public boolean existingRecords = false; //If no records exist, try to reset private ImageAccessor imageAccessor; //imageInfo holds image metadata like label, album name and 'foreign key' index to // corresponding RMS entry that stores the actual Image object private Hashtable imageInfoTable = new Hashtable(); /** * Constructor. Creates a new instance of ImageAccessor */ public AlbumData() { imageAccessor = new ImageAccessor(this); } /** * Added in MobileMedia-Cosmos-OO-v4 * @param photoname * @param imgdata * @param albumname * @throws InvalidImageDataException * @throws PersistenceMechanismException */ // #ifdef includeCopyPhoto protected void addImageData(String photoname, IImageData imageData, String albumname) throws InvalidImageDataException, PersistenceMechanismException{ imageAccessor.addImageData(photoname, imageData, albumname); } //TODO:[cosmos] I think this 'ifdef' definition must not include this method! /** * @param photoname * @param img * @param albumname * @throws InvalidImageDataException * @throws PersistenceMechanismException */ /**[Original][cosmos sms]Included in cosmos v5*/ //#ifdef includeSmsFeature public void addImageData(String photoname, byte[] img, String albumname) throws InvalidImageDataException, PersistenceMechanismException { //imageAccessor.addImageData(photoname,img,albumname); try { imageAccessor.addMediaArrayOfBytes(photoname, img, albumname); } catch (RecordStoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //#endif // #endif protected void addNewPhotoToAlbum(String label, String path, String album) throws InvalidImageDataException, PersistenceMechanismException{ imageAccessor.addImageData(label, path, album); } /** * Define a new user photo album. This results in the creation of a new * RMS Record store. * @throws PersistenceMechanismException * @throws InvalidPhotoAlbumNameException */ protected void createNewPhotoAlbum(String albumName) throws PersistenceMechanismException, InvalidPhotoAlbumNameException { imageAccessor.createNewPhotoAlbum(albumName); } /** * Delete a photo from the photo album. This permanently deletes the image from the record store * @throws ImageNotFoundException * @throws PersistenceMechanismException */ protected void deleteImage(String imageName, String storeName) throws PersistenceMechanismException, ImageNotFoundException { try { imageAccessor.deleteSingleImageFromRMS( storeName, imageName); } catch (NullAlbumDataReference e) { imageAccessor = new ImageAccessor(this); e.printStackTrace(); } } protected void deletePhotoAlbum(String albumName) throws PersistenceMechanismException{ imageAccessor.deletePhotoAlbum(albumName); } /** * Load any photo albums that are currently defined in the record store */ protected String[] getAlbumNames() { //Shouldn't load all the albums each time //Add a check somewhere in ImageAccessor to see if they've been //loaded into memory already, and avoid the extra work... System.out.println("[AlbumData.getAlbumNames()]"); try { imageAccessor.loadAlbums(); } catch (InvalidImageDataException e) { e.printStackTrace(); } catch (PersistenceMechanismException e) { e.printStackTrace(); } return imageAccessor.getAlbumNames(); } private ImageAccessor getImageAccessor() { return imageAccessor; } /** * Get a particular image (by name) from a photo album. The album name corresponds * to a record store. * @throws ImageNotFoundException * @throws PersistenceMechanismException */ protected Image getImageFromRecordStore(String recordStore, String imageName) throws ImageNotFoundException, PersistenceMechanismException { IImageData imageInfo = null; try { imageInfo = imageAccessor.getImageInfo(imageName); } catch (NullAlbumDataReference e) { imageAccessor = new ImageAccessor(this); } //Find the record ID and store name of the image to retrieve int imageId = imageInfo.getForeignRecordId(); String album = imageInfo.getParentAlbumName(); //Now, load the image (on demand) from RMS and cache it in the hashtable Image imageRec = imageAccessor.loadSingleImageFromRMS(album, imageName, imageId); //rs.getRecord(recordId); return imageRec; } /** * [CD] Add in order to have access to ImageData * @return */ protected IImageData getImageInfo(String name)throws ImageNotFoundException, NullAlbumDataReference{ return imageAccessor.getImageInfo(name); } /** * Get the hashtable that stores the image metadata in memory. * @return Returns the imageInfoTable. */ protected Hashtable getImageInfoTable() { return imageInfoTable; } /** * Get the names of all images for a given Photo Album that exist in the Record Store. * @throws UnavailablePhotoAlbumException * @throws InvalidImageDataException * @throws PersistenceMechanismException */ protected ImageData[] getImages(String recordName) throws UnavailablePhotoAlbumException { ImageData[] result; try { result = imageAccessor.loadImageDataFromRMS(recordName); } catch (PersistenceMechanismException e) { throw new UnavailablePhotoAlbumException( e.getMessage() ); } catch (InvalidImageDataException e) { throw new UnavailablePhotoAlbumException( e.getMessage() ); } return result; } /** * Reset the image data for the application. This is a wrapper to the ImageAccessor.resetImageRecordStore * method. It is mainly used for testing purposes, to reset device data to the default album and photos. * @throws PersistenceMechanismException * @throws InvalidImageDataException */ protected void resetImageData() throws PersistenceMechanismException { try { imageAccessor.resetImageRecordStore(); } catch (InvalidImageDataException e) { e.printStackTrace(); } } /** * [EF] Add in order to have access to ImageData * @param imageAccessor */ private void setImageAccessor(ImageAccessor imageAccessor) { this.imageAccessor = imageAccessor; } /** * Update the hashtable that stores the image metadata in memory * @param imageInfoTable * The imageInfoTable to set. */ private void setImageInfoTable(Hashtable imageInfoTable) { this.imageInfoTable = imageInfoTable; } /** * [CD] Add in order to have access to ImageData */ protected void updateImageInfo(IImageData oldData,IImageData newData) throws InvalidImageDataException, PersistenceMechanismException{ imageAccessor.updateImageInfo(oldData, newData); } }
mit
stangelandcl/Actors
Actors/Distributed/Proxies/DynamicProxy.cs
1322
using System; using System.Dynamic; using Cls.Extensions; using Cls.Connections; using Cls.Serialization; namespace Cls.Actors { public interface IDynamicProxy : IDisposable { RemoteActor Proxy { get; } } public class DynamicProxy : DynamicObject, IDynamicProxy { public DynamicProxy (RemoteActor actor) { this.Proxy = actor; } public RemoteActor Proxy { get; private set; } public override bool TryInvokeMember (InvokeMemberBinder binder, object[] args, out object result) { var isSend = binder.Name.StartsWith("Send"); var name = binder.Name; if (isSend) name = binder.Name.Substring(4); var msg = Proxy.Send(name, args); if (!binder.Name.StartsWith("Send")) result = Proxy.Receive(msg).As<RpcMail>().Message.Args[0]; else result = null; return true; } public override bool TryGetMember (GetMemberBinder binder, out object result) { var msg = Proxy.Send(binder.Name); result = Proxy.Receive(msg); return true; } public override bool TrySetMember (SetMemberBinder binder, object value) { Proxy.Send(binder.Name, value); return true; } public void Dispose(){ Proxy.Dispose(); } } }
mit
seedboxtech/goauthorizer
authorizerHandler.go
5664
package goauthorizer import ( "encoding/json" "errors" "log" "net/http" "strings" "github.com/gorilla/securecookie" ) type LoginFunc func(uname, pword string) bool type AuthorizerHandler struct { loginfn LoginFunc authorizedfn func(uname string, resource string) bool //UnauthorizedHandler is used in cases where the user isn't logged in. By default it will write 401 and terminate the connection. UnauthorizedHandler http.HandlerFunc cookiename string UserNameField string PassWordField string securecookie *securecookie.SecureCookie //Status messages to users. UnauthorizedMessage string ForbiddenMessage string LoginSuccessMessage string LoginFailureMessage string } var DefaultSuccessMessage = map[string]string{"result": "true"} var DefaultFailureMessage = map[string]string{"result": "false", "reason": "Bad username or password"} var DefaultUnauthorizedMessage = map[string]string{"result": "false", "reason": "401 Unauthorized"} var DefaultForbiddenMessage = map[string]string{"result": "false", "reason": "403 Forbidden"} //loginfn should be a function that accepts a username and password and returns true or false. //authorizedfn should be a function that checks if a given username has access to a given resource. //unauthorizedfn. //Last parameter NEEDS to be 8, 16, or 32 bytes long. See securecookie documentation. //Note that IF the last parameter is SET TO NIL, ENCRYPTION OF THE COOKIE VALUE IS DISABLED. func NewAuthorizerHandler(loginfn LoginFunc, authorizedfn func(string, string) bool, cookiename string, cookieHashKey, cookieBlockKey []byte) *AuthorizerHandler { var s = securecookie.New(cookieHashKey, cookieBlockKey) ah := &AuthorizerHandler{loginfn: loginfn, cookiename: cookiename, securecookie: s, authorizedfn: authorizedfn} ah.UserNameField = "uname" ah.PassWordField = "pword" b, _ := json.Marshal(DefaultSuccessMessage) b2, _ := json.Marshal(DefaultFailureMessage) unauthorized, _ := json.Marshal(DefaultUnauthorizedMessage) forbidden, _ := json.Marshal(DefaultForbiddenMessage) ah.LoginFailureMessage = string(b2) ah.LoginSuccessMessage = string(b) ah.UnauthorizedMessage = string(unauthorized) ah.ForbiddenMessage = string(forbidden) ah.UnauthorizedHandler = func(w http.ResponseWriter, req *http.Request) { w.WriteHeader(http.StatusUnauthorized) } return ah } //Generic login handler uses the specified login function to authenticate users. //Returns a Forbidden when it fails. func (lh *AuthorizerHandler) Login(w http.ResponseWriter, req *http.Request) { err := req.ParseForm() if err != nil { log.Println(err) } original_ip := getOriginalIp(req) uname := req.FormValue(lh.UserNameField) if lh.loginfn(uname, req.FormValue(lh.PassWordField)) { //Encode IP, User Agent, and UserName in cookie. cookie := lh.encodeLoginCookie(uname, original_ip, req.UserAgent()) http.SetCookie(w, cookie) w.Write([]byte(lh.LoginSuccessMessage)) } else { w.WriteHeader(http.StatusUnauthorized) w.Write([]byte(lh.LoginFailureMessage)) } } func (lh *AuthorizerHandler) Logout(w http.ResponseWriter, req *http.Request) { //If cookie doesn't exist, nothing to do. if cookie, err := req.Cookie(lh.cookiename); err == nil { cookie.Value = "" cookie.MaxAge = -1 http.SetCookie(w, cookie) } } func getOriginalIp(req *http.Request) string { forwards := strings.Split(req.Header.Get("X-Forwarded-For"), ",") var original_ip string if len(forwards) > 0 { original_ip = forwards[0] } return original_ip } func (lh *AuthorizerHandler) encodeLoginCookie(uname string, original_ip string, user_agent string) *http.Cookie { secval, _ := lh.securecookie.Encode(lh.cookiename, map[string]string{lh.UserNameField: uname, "ip": original_ip, "ua": user_agent}) cookie := &http.Cookie{} cookie.Name = lh.cookiename cookie.Value = secval return cookie } func (lh *AuthorizerHandler) AuthorizeHandler(allowhandler http.Handler, denyhandler http.HandlerFunc) http.Handler { return &blankHandler{lh.AuthorizeFunc(allowhandler.ServeHTTP, denyhandler)} } type blankHandler struct { fn http.HandlerFunc } func (bh *blankHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) { bh.fn(w, req) } //Use this to wrap an http.HandlerFunc you pass to an http.ServeMux's HandleFunc. func (lh *AuthorizerHandler) AuthorizeFunc(allowhandler http.HandlerFunc, denyhandler http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, req *http.Request) { if cookie, err := req.Cookie(lh.cookiename); err == nil { if uname, err := lh.GetUserName(req); err == nil { //User is logged in. if lh.authorizedfn(uname, req.URL.String()) { allowhandler(w, req) return } else { denyhandler(w, req) return } } else { //Bad cookie, remove. cookie.Value = "" cookie.MaxAge = -1 http.SetCookie(w, cookie) } } //By default you are not authorized. lh.UnauthorizedHandler(w, req) } } func (lh *AuthorizerHandler) GetUserName(req *http.Request) (string, error) { if cookie, err := req.Cookie(lh.cookiename); err == nil { value := make(map[string]string) if err := lh.securecookie.Decode(lh.cookiename, cookie.Value, &value); err == nil { //This is to check against cookie theft and/or forgery. if value["ip"] == getOriginalIp(req) && value["ua"] == req.UserAgent() { return value[lh.UserNameField], nil } else { return "", errors.New("Authorizer: Bad cookie.") } } else { return "", err } } else { return "", err } } func (lh *AuthorizerHandler) IsLoggedIn(req *http.Request) bool { u, e := lh.GetUserName(req) return u != "" && e == nil }
mit
UchiKir/SymfonyPadelApp
var/cache/prod/doctrine/orm/Proxies/__CG__AppBundleEntityMatch.php
6523
<?php namespace Proxies\__CG__\AppBundle\Entity; /** * DO NOT EDIT THIS FILE - IT WAS CREATED BY DOCTRINE'S PROXY GENERATOR */ class Match extends \AppBundle\Entity\Match implements \Doctrine\ORM\Proxy\Proxy { /** * @var \Closure the callback responsible for loading properties in the proxy object. This callback is called with * three parameters, being respectively the proxy object to be initialized, the method that triggered the * initialization process and an array of ordered parameters that were passed to that method. * * @see \Doctrine\Common\Persistence\Proxy::__setInitializer */ public $__initializer__; /** * @var \Closure the callback responsible of loading properties that need to be copied in the cloned object * * @see \Doctrine\Common\Persistence\Proxy::__setCloner */ public $__cloner__; /** * @var boolean flag indicating if this object was already initialized * * @see \Doctrine\Common\Persistence\Proxy::__isInitialized */ public $__isInitialized__ = false; /** * @var array properties to be lazy loaded, with keys being the property * names and values being their default values * * @see \Doctrine\Common\Persistence\Proxy::__getLazyProperties */ public static $lazyPropertiesDefaults = []; /** * @param \Closure $initializer * @param \Closure $cloner */ public function __construct($initializer = null, $cloner = null) { $this->__initializer__ = $initializer; $this->__cloner__ = $cloner; } /** * * @return array */ public function __sleep() { if ($this->__isInitialized__) { return ['__isInitialized__', '' . "\0" . 'AppBundle\\Entity\\Match' . "\0" . 'id', '' . "\0" . 'AppBundle\\Entity\\Match' . "\0" . 'players', '' . "\0" . 'AppBundle\\Entity\\Match' . "\0" . 'player2']; } return ['__isInitialized__', '' . "\0" . 'AppBundle\\Entity\\Match' . "\0" . 'id', '' . "\0" . 'AppBundle\\Entity\\Match' . "\0" . 'players', '' . "\0" . 'AppBundle\\Entity\\Match' . "\0" . 'player2']; } /** * */ public function __wakeup() { if ( ! $this->__isInitialized__) { $this->__initializer__ = function (Match $proxy) { $proxy->__setInitializer(null); $proxy->__setCloner(null); $existingProperties = get_object_vars($proxy); foreach ($proxy->__getLazyProperties() as $property => $defaultValue) { if ( ! array_key_exists($property, $existingProperties)) { $proxy->$property = $defaultValue; } } }; } } /** * */ public function __clone() { $this->__cloner__ && $this->__cloner__->__invoke($this, '__clone', []); } /** * Forces initialization of the proxy */ public function __load() { $this->__initializer__ && $this->__initializer__->__invoke($this, '__load', []); } /** * {@inheritDoc} * @internal generated method: use only when explicitly handling proxy specific loading logic */ public function __isInitialized() { return $this->__isInitialized__; } /** * {@inheritDoc} * @internal generated method: use only when explicitly handling proxy specific loading logic */ public function __setInitialized($initialized) { $this->__isInitialized__ = $initialized; } /** * {@inheritDoc} * @internal generated method: use only when explicitly handling proxy specific loading logic */ public function __setInitializer(\Closure $initializer = null) { $this->__initializer__ = $initializer; } /** * {@inheritDoc} * @internal generated method: use only when explicitly handling proxy specific loading logic */ public function __getInitializer() { return $this->__initializer__; } /** * {@inheritDoc} * @internal generated method: use only when explicitly handling proxy specific loading logic */ public function __setCloner(\Closure $cloner = null) { $this->__cloner__ = $cloner; } /** * {@inheritDoc} * @internal generated method: use only when explicitly handling proxy specific cloning logic */ public function __getCloner() { return $this->__cloner__; } /** * {@inheritDoc} * @internal generated method: use only when explicitly handling proxy specific loading logic * @static */ public function __getLazyProperties() { return self::$lazyPropertiesDefaults; } /** * {@inheritDoc} */ public function getId() { if ($this->__isInitialized__ === false) { return (int) parent::getId(); } $this->__initializer__ && $this->__initializer__->__invoke($this, 'getId', []); return parent::getId(); } /** * {@inheritDoc} */ public function setPlayer($player) { $this->__initializer__ && $this->__initializer__->__invoke($this, 'setPlayer', [$player]); return parent::setPlayer($player); } /** * {@inheritDoc} */ public function getPlayer() { $this->__initializer__ && $this->__initializer__->__invoke($this, 'getPlayer', []); return parent::getPlayer(); } /** * {@inheritDoc} */ public function setPlayer2($player2) { $this->__initializer__ && $this->__initializer__->__invoke($this, 'setPlayer2', [$player2]); return parent::setPlayer2($player2); } /** * {@inheritDoc} */ public function getPlayer2() { $this->__initializer__ && $this->__initializer__->__invoke($this, 'getPlayer2', []); return parent::getPlayer2(); } /** * {@inheritDoc} */ public function setPlayers(\AppBundle\Entity\AppUser $players = NULL) { $this->__initializer__ && $this->__initializer__->__invoke($this, 'setPlayers', [$players]); return parent::setPlayers($players); } /** * {@inheritDoc} */ public function getPlayers() { $this->__initializer__ && $this->__initializer__->__invoke($this, 'getPlayers', []); return parent::getPlayers(); } }
mit
kbase/browse
ws-browser/assets/data/maps/maps-to-json.py
12664
#!/usr/bin/env python import io import json import sys import os from xml.dom import minidom import wsclient # this is the kegg rxn/cpds to seed mapping json files. with open('rxn_mapping.json') as file: json_str = file.read() rxn_mapping = json.loads(json_str) with open('cpd_mapping.json') as file: json_str = file.read() cpd_mapping = json.loads(json_str) MAPSJSON = [] def data_to_json(file_name): print 'Converting reactions/compounds from file:', file_name try: xmldoc = minidom.parse(file_name) except: sys.stderr.write("could not parse xml file: "+file_name+'\n') return itemlist = xmldoc.getElementsByTagName('pathway') try: name = itemlist[0].attributes['title'].value except: name = "None" map_number = itemlist[0].attributes['number'].value link = itemlist[0].attributes['link'].value rxns = [] cpds = [] entries = xmldoc.getElementsByTagName('entry') for obj in entries : if (obj.attributes['type'].value == 'group'): continue if (obj.attributes['type'].value == 'enzyme' and obj.getElementsByTagName('graphics')): try: obj.attributes['reaction'].value except: continue # get list of kegg rxn ids from the entry kegg_rxns = obj.attributes['reaction'].value \ .replace('rn:','').split(' ') # for each kegg_rxn, get the seed rxn id, add to list for kegg_rxn in kegg_rxns: try: seed_rxn = rxn_mapping[kegg_rxn] rxns.append( seed_rxn ) except: sys.stderr.write("Warning: [Converting "+file_name+ "] Could not find seed rxn id for KEGG id: "+kegg_rxn+'\n') rxns.append( kegg_rxn ) elif (obj.attributes['type'].value == 'compound' and obj.getElementsByTagName('graphics') ): e_obj = obj.attributes kegg_cpds = e_obj['name'].value \ .replace('cpd:','').split(' ') for kegg_cpd in kegg_cpds: try: # replace this with seed mapping result in future seed_cpd = cpd_mapping[kegg_cpd] cpds.append( seed_cpd ) except: sys.stderr.write("Warning: [Converting "+file_name+ "] Could not find seed cpd id for KEGG id: "+kegg_cpd+'\n') cpds.append( kegg_cpd ) map_obj = {'name': name, 'map':'map'+map_number, 'link': link, } map_obj['reaction_count'] = len(rxns) map_obj['compound_count'] = len(cpds) MAPSJSON.append(map_obj) json_obj = {'name': name, 'map':'map'+map_number, 'link': link, } json_obj['reactions'] = rxns json_obj['compounds'] = cpds #print json_obj json_file = file_name.replace('.xml', '_bio.json') outfile = open(json_file, 'w') json.dump(json_obj, outfile) print "Reaction/Compound ids converted to:", json_file outfile = open('maps.json', 'w') json.dump(MAPSJSON, outfile) def graph_to_json(file_name): print 'Converting graph data from file:', file_name try: xmldoc = minidom.parse(file_name) except: sys.stderr.write("could not parse xml file: "+file_name+'\n') return itemlist = xmldoc.getElementsByTagName('pathway') try: name = itemlist[0].attributes['title'].value except: name = "None" map_number = itemlist[0].attributes['number'].value link = itemlist[0].attributes['link'].value json_obj = {'id': 'map'+map_number, 'name': name, 'link': link, 'source_id': 'map'+map_number, 'source': 'KEGG', 'reactions':[], 'compounds':[], 'reaction_ids': [], 'compound_ids': [], 'linkedmaps': [] } entries = xmldoc.getElementsByTagName('entry') reaction_ids = [] compound_ids = [] for obj in entries: if (obj.attributes['type'].value == 'group'): continue #<entry id="41" name="path:ec00030" type="map" # link="http://www.kegg.jp/dbget-bin/www_bget?ec00030"> # <graphics name="Pentose phosphate pathway" fgcolor="#000000" bgcolor="#FFFFFF" # type="roundrectangle" x="656" y="339" width="62" height="237"/> # </entry> #string id; #map_ref map_ref; #string name; #string shape; #string link; #int h; #int w; #int y; #int x; #map_id map_id; if (obj.attributes['type'].value == 'map'): e_obj = obj.attributes g_obj = obj.getElementsByTagName('graphics')[0].attributes obj = {"id": e_obj['id'].value, "shape": g_obj['type'].value, "name": g_obj['name'].value, "h": g_obj['height'].value, "w": g_obj['width'].value, "x": g_obj['x'].value, "y": g_obj['y'].value, } name = e_obj['name'].value; if 'ec' in name: name = name.split('ec')[1] elif 'map' in name: name = name.split('map')[1] obj['map_id'] = 'map'+name obj['map_ref'] = name json_obj['linkedmaps'].append(obj) continue if (obj.attributes['type'].value == 'enzyme' and obj.getElementsByTagName('graphics')): try: obj.attributes['reaction'].value except: continue e_obj = obj.attributes # get list of kegg rxn ids from the entry kegg_rxns = e_obj['reaction'].value \ .replace('rn:','').split(' ') reactions = xmldoc.getElementsByTagName('reaction') # substrate and product data from kgml # for each kegg_rxn, get the seed rxn id, add to list rxns = [] for kegg_rxn in kegg_rxns: try: rxn_id = rxn_mapping[kegg_rxn] except: sys.stderr.write("Warning: [Converting "+file_name+ "] Could not find seed rxn id for KEGG id: "+kegg_rxn+'\n') rxn_id = kegg_rxn rxns.append(rxn_id) reaction_ids.append(rxn_id) for reaction in reactions: r_obj = reaction.attributes #rn_ids = r_obj['name'].value.split(' ') #rn_ids = [id.split(':')[1] for id in rn_ids] #print rn_ids if r_obj['id'].value == e_obj['id'].value: substrates = [] for substrate in reaction.getElementsByTagName('substrate'): s_obj = {'id': substrate.attributes['id'].value, 'cpd': substrate.attributes['name'].value.split(':')[1] } substrates.append(s_obj) products = [] for product in reaction.getElementsByTagName('product'): p_obj = {'id': product.attributes['id'].value, 'cpd': product.attributes['name'].value.split(':')[1] } products.append(p_obj) break #json_obj['arrows'].append(obj) g_obj = obj.getElementsByTagName('graphics')[0].attributes try: link = e_obj['link'].value except: sys.stderr.write("Warning: [Converting "+file_name+ "] Could not find link for reaction: "+kegg_rxn+'\n') pass x = y = h = w = False try: x = int(g_obj['x'].value) y = int(g_obj['y'].value) h = int(g_obj['height'].value) w = int(g_obj['width'].value) except: sys.stderr.write("Warning: [Converting "+file_name+ "] Could not find coordinates for reaction: "+kegg_rxn+'\n') pass obj = {"id": e_obj['id'].value, "rxns": rxns, "ec": e_obj['name'].value, "shape": g_obj['type'].value, "name": g_obj['name'].value, } try: if substrates: obj['substrates'] = substrates if products: obj['products'] = products except: sys.stderr.write("Warning: [Converting "+file_name+ "] Could not find substrates and/or products for: "+kegg_rxn+'\n') if link: obj['link'] = link if x: obj['x'] = x if y: obj['y'] = y if h: obj['h'] = h if w: obj['w'] = w json_obj['reactions'].append(obj) elif (obj.attributes['type'].value == 'compound' and obj.getElementsByTagName('graphics') ): e_obj = obj.attributes kegg_cpds = e_obj['name'].value \ .replace('cpd:','').split(' ') # for each kegg_rxn, get the seed rxn id, add to list cpds = [] for kegg_cpd in kegg_cpds: try: # replace this with seed mapping result in future cpd_id = cpd_mapping[kegg_cpd] # get seed_id except: sys.stderr.write("Warning: [Converting "+file_name+ "] Could not find seed cpd id for KEGG id: "+kegg_cpd+'\n') cpd_id = kegg_cpd cpds.append( cpd_id ) compound_ids.append(cpd_id) g_obj = obj.getElementsByTagName('graphics')[0].attributes obj = {"id": e_obj['id'].value, "name": g_obj['name'].value, "cpds": cpds, "ec": e_obj['name'].value, "link": e_obj['link'].value, "shape": g_obj['type'].value, "x": int(g_obj['x'].value), "y": int(g_obj['y'].value), "h": int(g_obj['height'].value), "w": int(g_obj['width'].value), "link_refs": [] #fixme: I don't know what this is... } json_obj['compounds'].append(obj) #print json_obj json_obj['reaction_ids'] = reaction_ids json_obj['compound_ids'] = compound_ids #print json_obj json_file = file_name.replace('.xml', '_graph.json') outfile = open(json_file, 'w') json.dump(json_obj, outfile) print "Graph data converted to:", json_file def save_kegg_object(map_id): ws = wsclient.Workspace() json_data=open('xml/'+map_id+'_graph.json') data = json.load(json_data) print data test= ws.save_object({'workspace': 'nconrad:paths', 'data': data, 'id': map_id, 'type': 'KBaseBiochem.MetabolicMap' }) print test # this function attempts to convert all .xml files in the current directory def convert_all_data(): os.chdir('xml') # print '\n\n*** Converting reactions and compounds ***\n' # for name in os.listdir(os.getcwd()): # if name.endswith('.xml'): # data_to_json(name) print '\n\n*** Converting graph data ***\n' for name in os.listdir(os.getcwd()): if name.endswith('.xml'): graph_to_json(name) if __name__ == "__main__": #ws = wsclient.Workspace() # workspaces = ws.list_workspaces({}) # for arr in workspaces: # if str(arr[1]) != 'nconrad': continue # print str(arr) + '\n' if (sys.argv[1] == 'save'): save_kegg_object('map00010') elif (sys.argv[1] == 'convert'): convert_all_data() #convert_all_data() # use one of these to convert a single file #data_to_json(sys.argv[1]) #graph_to_json(sys.argv[1]) print 'Done.'
mit
trifort/skarn
project/TestBuild.scala
637
import sbt._ import Keys._ object TestBuild extends Build { lazy val E2ETest = config("e2e") extend(Test) lazy val ITest = config("it") extend(Test) def itFilter(name: String): Boolean = name endsWith "ITest" def unitFilter(name: String): Boolean = !itFilter(name) && !e2eFilter(name) def e2eFilter(name: String): Boolean = (name endsWith "E2ETest") override lazy val settings = super.settings ++ Seq( testOptions in Test := Seq(Tests.Filter(unitFilter)), testOptions in ITest := Seq(Tests.Filter(itFilter)), testOptions in E2ETest := Seq(Tests.Filter(e2eFilter)), parallelExecution in ITest := false ) }
mit
kirbysayshi/sea
test/test.dom.js
21918
var assert = require('assert') , sinon = require('sinon') , sea = require('../index.databind') // skip running if not in a browser if(typeof window === 'undefined') return; var scratch = document.querySelector('#scratch'); var $ = function(query, ctx){ return [].slice.call((ctx || scratch).querySelectorAll(query)); } function calledTwice(item, i){ assert.equal(item.calledTwice, true, 'observable is only accessed twice: ' + item.callCount + ' index: ' + i); } // HACK: shortcut for assertions! sea.bindings.assert = { init: function(el, cmpAttr, rootModel, currentModel){ Object.keys(assert).forEach(function(assertKey){ currentModel[assertKey] = assert[assertKey]; }) // HACK!: delete the already cached binding... delete sea._cmpBindings[el.dataset.assert]; // so this one's arguments come through var ret = sea.compileBinding(el.dataset.assert, Object.keys(currentModel))(currentModel); el.textContent = ret || 'ok'; } ,update: function(){} } exports['Data Binding'] = { '': '' ,'idFor': { 'returns the same id for a div': function(){ var el = document.createElement('div') , id = sea.dom.idFor(el); assert.equal(sea.dom.idFor(el), id); } ,'returns the same id for a document fragment': function(){ var el = document.createDocumentFragment() , id = sea.dom.idFor(el); assert.equal(sea.dom.idFor(el), id); } } ,'destroyBindings': { before: function(){ //sea.destroyBindings(scratch); var html = '' + '<p data-text="same()"></p>' + '<ul data-foreach="items()">' + ' <li data-text="$data"></li>' + '</ul>'; scratch.innerHTML = html } ,'ceases updates after': function(){ var items = sea.observableArray(['a']) , same = sea.observable('a'); sea.applyBindings({ items: items, same: same }, scratch); sea.destroyBindings(scratch); items.push('b'); same('b') var lis = $('ul li') , p = $('p'); assert.equal(lis.length, 1, 'no new dom elements'); assert.equal(p[0].textContent, 'a', 'paragraph has not been updated'); } } ,'data-text': { beforeEach: function(){ var html = '<p data-text="t()"></p>'; scratch.innerHTML = html } ,'observable updates value': function(){ var t = sea.observable('Hello!'); sea.applyBindings({ t: t }, scratch); var p = $('p')[0]; assert.equal(p.textContent, 'Hello!'); t('Goodbye!'); assert.equal(p.textContent, 'Goodbye!'); } ,'computed depending on observable updates value': function(){ var h = sea.observable('Hello!') , t = sea.computed(function(){ return h() + ' Goodbye!'; }); sea.applyBindings({ t: t }, scratch); var p = $('p')[0]; assert.equal(p.textContent, 'Hello! Goodbye!'); h('Goodbye!'); assert.equal(p.textContent, 'Goodbye! Goodbye!'); } } ,'data-css': { 'depends on observable': { before: function(){ var html = '<p class="css-class-name-1" data-css="{ \'css-class-name-1\': !a(), \'css-class-name-2\': a() }"></p>'; scratch.innerHTML = html; } ,'and toggles': function(){ var a = sea.observable(true); sea.applyBindings({ a: a }, scratch); var p = sea.dom.select('p', scratch)[0]; assert.equal(p.classList.contains('css-class-name-2'), true) assert.equal(p.classList.contains('css-class-name-1'), false) a(false); assert.equal(a(), false, 'a should be false'); console.log(p); assert.equal(p.classList.contains('css-class-name-2'), false) assert.equal(p.classList.contains('css-class-name-1'), true) } } } ,'data-foreach': { beforeEach: function(){ //sea.destroyBindings(scratch); var html = '' + '<ul data-foreach="items()">' + ' <li data-text="$data"></li>' + '</ul>'; scratch.innerHTML = html } ,'renders intially': function(){ var items = sea.observableArray(['a', 'b', 'c']); sea.applyBindings({ items: items }, scratch); var lis = $('ul li'); assert.equal(lis.length, 3); lis.forEach(function(li, i){ assert.equal(li.textContent, items()[i]); }) } ,'.push appends a new li': function(){ var items = sea.observableArray(['d', 'e', 'f']); sea.applyBindings({ items: items }, scratch); items.push('g'); var lis = $('ul li'); lis.forEach(function(li, i){ assert.equal(li.textContent, items()[i]); }) assert.equal(lis.length, 4, 'there should be 4 list items'); } ,'replacing array keeps DOM elements': function(){ var items = sea.observableArray(['a', 'b', 'c']); sea.applyBindings({ items: items }, scratch); var lis = $('ul li'); assert.equal(lis.length, 3); items(['d', 'e', 'f']); var newlis = $('ul li'); newlis.forEach(function(li, i){ assert.equal(li.textContent, items()[i]); assert.strictEqual(newlis[i], lis[i]); }) } ,'.push multiple items updates once': function(){ var items = sea.observableArray(['d', 'e', 'f']); var origUpdate = sea.bindings.foreach.update; var updateSpy = sea.bindings.foreach.update = sinon.spy(sea.bindings.foreach.update); sea.applyBindings({ items: items }, scratch); assert.equal(updateSpy.calledOnce, true, 'update method should be called once during applyBindings') items.push('g', 'h', 'i', 'j'); assert.equal(updateSpy.calledTwice, true, 'update method should be called once more after push') var lis = $('ul li'); lis.forEach(function(li, i){ assert.equal(li.textContent, items()[i]); }) assert.equal(lis.length, 7, 'there should be 7 list items'); sea.bindings.foreach.update = origUpdate; } ,'.sort rerenders': function(){ var items = sea.observableArray(['z', '1', 'x', 'y']); sea.applyBindings({ items: items }, scratch); items.sort(); var lis = $('ul li') , sorted = ['1', 'x', 'y', 'z']; lis.forEach(function(li, i){ assert.equal(li.textContent, sorted[i]); }) } ,'.splice removes elements': function(){ var items = sea.observableArray(['a', 'b', 'c']); sea.applyBindings({ items: items }, scratch); items.splice(1, 1); var lis = $('ul li'); assert.equal(lis.length, 2, 'expect 2 elements: ' + lis.length); lis.forEach(function(li, i){ assert.equal(li.textContent, items()[i]); }) } ,'nested properties': { '': '' ,beforeEach: function(){ var html = '' + '<ul data-foreach="items()">' + ' <li data-text="name"></li>' + '</ul>'; scratch.innerHTML = html } ,'are exposed to the scope': function(){ var items = sea.observableArray([{ name: 'a' }, { name: 'b' }]); sea.applyBindings({ items: items }, scratch); var lis = $('ul li'); assert.equal(lis.length, 2, 'expect 2 elements: ' + lis.length); lis.forEach(function(li, i){ assert.equal(li.textContent, items()[i].name); }) } ,'are exposed to the scope even if empty when bindings applied': function(){ var items = sea.observableArray(); sea.applyBindings({ items: items }, scratch); items.push({ name: 'a' }, { name: 'b' }); var lis = $('ul li'); assert.equal(lis.length, 2, 'expect 2 elements: ' + lis.length); lis.forEach(function(li, i){ assert.equal(li.textContent, items()[i].name); }) } } ,'special properties': { '':'' ,'$index': function(){ var html = '' + '<ul data-foreach="items()">' + ' <li data-text="$index"></li>' + '</ul>'; scratch.innerHTML = html var items = sea.observableArray([1, 2, 3]); sea.applyBindings({ items: items }, scratch); var lis = $('li') assert.equal(lis.length, 3); lis.forEach(function(li, i){ assert.equal(li.textContent, i, '$index matches nodeList index'); }) } ,'$parent': function(){ var html = '' + '<ul data-foreach="items">' + ' <li data-assert="equal($parent.fromRoot, \'fromRoot\')"></li>' + ' <ul data-foreach="$data">' + ' <li data-assert="ok(!$parent.fromRoot, \'fromRoot is not available in child $parent\')"></li>' + ' <li data-assert="notStrictEqual($parent, $root)"></li>' + ' </ul>' + '</ul>'; scratch.innerHTML = html var items = [[{ a: 1 }], [{ a: 2 }], [{ a: 3 }]]; sea.applyBindings({ items: items, fromRoot: 'fromRoot' }, scratch); } ,'$data': function(){ var html = '' + '<ul data-foreach="items()">' + ' <li data-text="$data"></li>' + '</ul>'; scratch.innerHTML = html var items = sea.observableArray([1, 2, 3]); sea.applyBindings({ items: items }, scratch); var lis = $('li') assert.equal(lis.length, 3); lis.forEach(function(li, i){ assert.equal(li.textContent, i+1, '$data matches value'); }) } ,'$root': function(){ var html = '' + '<ul data-foreach="items">' + ' <ul data-foreach="[0]">' + ' <li data-text="$root.a"></li>' + ' </ul>' + '</ul>'; scratch.innerHTML = html sea.applyBindings({ items: [1, 2, 3], a: 'a' }, scratch); var lis = $('li') assert.equal(lis.length, 3); lis.forEach(function(li, i){ assert.equal(li.textContent, 'a', '$root.a matches original model'); }) } } ,'modelFor': { 'creates object with properties': function(){ var el = document.createElement('div') , parent = { name: 'parent' } , data = { name: 'data' } , index = 2; var modelA = sea.bindings.foreach.modelFor(el, parent, data, index) assert.strictEqual(modelA.$parent, parent, '$parent is present'); assert.strictEqual(modelA.$data, data, '$data is present'); assert.strictEqual(modelA.$index, index, '$index is present'); } ,'retrieves same object for same data': function(){ var el = document.createElement('div') , parent = { name: 'parent' } , data = { name: 'data' } , index = 2; var modelA = sea.bindings.foreach.modelFor(el, parent, data, index) , modelB = sea.bindings.foreach.modelFor(el, parent, data, index) assert.strictEqual(modelA, modelB, 'same arguments returns same model'); } ,'retrieves same object for same element': function(){ var el = document.createElement('div') , parent = { name: 'parent' } , data = { name: 'data' } , index = 2; var modelA = sea.bindings.foreach.modelFor(el, parent, data, index); var modelB = sea.bindings.foreach.modelFor(el, parent, data, 3); assert.strictEqual(modelA, modelB, 'same element returns same model'); assert.equal(modelA.$index, 3, 'index has been updated'); } } ,'elModelWillChange': { 'returns true if model does not exist': function(){ var el = document.createElement('div') , parent = { name: 'parent' } , data = { name: 'data' } , index = 2; assert.equal(sea.bindings.foreach.elModelWillChange(el, parent, data, index), true); } ,'returns true if model will change': function(){ var el = document.createElement('div') , parent = { name: 'parent' } , data = { name: 'data' } , index = 2; var modelA = sea.bindings.foreach.modelFor(el, parent, data, index); index = 3; assert.equal(sea.bindings.foreach.elModelWillChange(el, parent, data, index), true); } ,'returns false if model will not change': function(){ var el = document.createElement('div') , parent = { name: 'parent' } , data = { name: 'data' } , index = 2; var modelA = sea.bindings.foreach.modelFor(el, parent, data, index); assert.equal(sea.bindings.foreach.elModelWillChange(el, parent, data, index), false); } } ,'nested observables': { beforeEach: function(){ var html = '' + '<ul data-foreach="items()">' + ' <li data-text="$data()"></li>' + '</ul>'; scratch.innerHTML = html } ,'are rendered': function(){ var items = sea.observableArray([ sinon.spy(sea.observable('a')) , sinon.spy(sea.observable('b')) , sinon.spy(sea.observable('c')) ]); sea.applyBindings({ items: items }, scratch); var lis = $('ul li'); assert.equal(lis.length, 3); // observable is accessed twice, once for text binding, once for creation of bound computed for element items().forEach(calledTwice) lis.forEach(function(li, i){ assert.equal(li.textContent, items()[i]()); }) } ,'are not rerendered with a push': function(){ var items = sea.observableArray([ sinon.spy(sea.observable('a')) , sinon.spy(sea.observable('b')) , sinon.spy(sea.observable('c')) ]); sea.applyBindings({ items: items }, scratch); items().forEach(calledTwice) items.push(sinon.spy(sea.observable('d'))); items().forEach(calledTwice) items.push(sinon.spy(sea.observable('e'))); items().forEach(calledTwice) } ,'are rerendered if order changes': function(){ var items = sea.observableArray([ sinon.spy(sea.observable('a')) , sinon.spy(sea.observable('b')) , sinon.spy(sea.observable('c')) ]); sea.applyBindings({ items: items }, scratch); items().forEach(calledTwice) var d = sinon.spy(sea.observable('d')) , a = items()[0]; items()[0] = d; items.self.notifyDependents(); // manually signal a change //assert.equal(d.calledOnce, true, 'd is only evaluated for the text binding since the element computed already exists'); // the originals will not have been rerendered items().slice(1).forEach(calledTwice); // ensure that no silliness is going on calledTwice(a); } } ,'nested bindings': { beforeEach: function(){ var html = '' + '<ul data-foreach="items()">' + ' <li data-css="{ \'css-class-name-1\': $data() }" data-text="$data()"></li>' + '</ul>'; scratch.innerHTML = html } ,'data-css': function(){ var items = sea.observableArray([ sea.observable('a') , sea.observable('b') ]); sea.applyBindings({ items: items }, scratch); var lis = sea.dom.select('li', scratch); assert.equal(lis[0].classList.contains('css-class-name-1'), true); assert.equal(lis[1].classList.contains('css-class-name-1'), true); items()[0](false); assert.equal(lis[0].classList.contains('css-class-name-1'), false); assert.equal(lis[1].classList.contains('css-class-name-1'), true); } ,'data-foreach': { beforeEach: function(){ var html = '' + '<div data-foreach="tasks()">' + ' <h1 data-text="$data.name"></h1>' + ' <ul data-foreach="$data.assignees()">' + ' <li data-text="$data.name"></li>' + ' </ul>' + '</div>'; scratch.innerHTML = html this.task1 = { name: 'task1', assignees: sea.observableArray([{name: 'Aang'}, {name: 'Katara'}]) } this.task2 = { name: 'task2', assignees: sea.observableArray([{name: 'Sokka'}, {name: 'Toph'}, {name: 'Appa'}]) } this.seamodel = { tasks: sea.observableArray() } sea.applyBindings(this.seamodel, scratch); } ,'each group of assignees are unique': function(){ this.seamodel.tasks.push(this.task1, this.task2); var lis = $('li'); assert.equal(lis.length, 5, 'expect 5 list items: ' + lis.length); lis.forEach(function(li, i){ if(i >= 2){ assert.equal(li.textContent, this.task2.assignees()[i-2].name) } else { assert.equal(li.textContent, this.task1.assignees()[i].name) } }, this) } ,'each task name is unique': function(){ this.seamodel.tasks.push(this.task1, this.task2); var h1s = $('h1'); assert.equal(h1s.length, 2); assert.equal(h1s[0].textContent, this.task1.name) assert.equal(h1s[1].textContent, this.task2.name) } } ,'data-if': { beforeEach: function(){ var html = '' + '<ul data-foreach="items()">' + ' <li>' + ' <div data-if="doing()">' + ' <label data-text="title()"></label>' + ' </div>' + ' </li>' + '</ul>'; scratch.innerHTML = html } ,'use unique models': function(){ function Thing(title){ this.title = sea.observable(title) this.doing = sea.observable(true) } var model = { items: sea.observableArray() } sea.applyBindings(model, scratch); model.items.push(new Thing('bbbb')) model.items.unshift(new Thing('aaaa')) model.items.push(new Thing('cccc')) var labels = $('label') labels.forEach(function(label, i){ assert.equal(label.textContent, model.items()[i].title(), 'label should equal title') }) } } } } ,'data-if': { 'when used alone': { beforeEach: function(){ var html = '' + '<div data-if="a()">' + '<p data-text="a()"></p>' + '</div>'; scratch.innerHTML = html } ,'hides if falsy': function(){ var a = sea.observable(false); sea.applyBindings({ a: a }, scratch); var p = sea.dom.select('p', scratch); assert.equal(p.length, 0); } ,'shows if truthy': function(){ var a = sea.observable('a'); sea.applyBindings({ a: a }, scratch); var p = sea.dom.select('p', scratch); assert.equal(p.length, 1); assert.equal(p[0].textContent, 'a'); } } } ,'data-checked': { beforeEach: function(){ var html = '' + '<input type="checkbox" data-checked="a" />'; scratch.innerHTML = html } ,'binds to an observable': function(){ var a = sea.observable(false); sea.applyBindings({ a: a }, scratch); var box = $('input')[0]; assert.equal(box.checked, false, '.checked should be false') a(true); assert.equal(box.checked, true, '.checked should be true') } ,'maintains initial observable state': function(){ var a = sea.observable(true); sea.applyBindings({ a: a }, scratch); var box = $('input')[0]; assert.equal(box.checked, true, '.checked should be true') a(false); assert.equal(box.checked, false, '.checked should be false') } } ,'data-style': { 'sets basic styles': { beforeEach: function(){ var html = '' + '<div data-style="{ backgroundColor: \'blue\' }"></div>'; scratch.innerHTML = html } ,'on a div': function(){ sea.applyBindings({}, scratch); var box = $('div')[0]; assert.equal(box.style.backgroundColor, 'blue', 'should have blue background'); } } ,'sets more advanced values': { beforeEach: function(){ var html = '' + '<div data-style="{ backgroundColor: a() }"></div>'; scratch.innerHTML = html } ,'based on an observable': function(){ var a = sea.observable('blue'); sea.applyBindings({ a: a }, scratch); var box = $('div')[0]; assert.equal(box.style.backgroundColor, 'blue', 'should have blue background'); a('white'); assert.equal(box.style.backgroundColor, 'white', 'should have white background after observable change'); } ,'based on an computed': function(){ var b = sea.observable('blue'); var a = sea.computed(function(newVal){ return b(); }); sea.applyBindings({ a: a }, scratch); var box = $('div')[0]; assert.equal(box.style.backgroundColor, 'blue', 'should have blue background'); b('white'); assert.equal(box.style.backgroundColor, 'white', 'should have white background after computed change'); } } ,'and can use expressions': { beforeEach: function(){ var html = '' + '<div data-style="{ backgroundColor: a() > 2 ? \'blue\' : \'white\' }"></div>'; scratch.innerHTML = html } ,'based on an observable': function(){ var a = sea.observable(3); sea.applyBindings({ a: a }, scratch); var box = $('div')[0]; assert.equal(box.style.backgroundColor, 'blue', 'should have blue background'); a(0); assert.equal(box.style.backgroundColor, 'white', 'should have white background after observable change'); } } } }
mit
IamAdamJowett/angular-logger-max
logger.service.js
15785
/* global angular */ (function() { 'use strict'; angular .module('angular-logger-max', []) .factory('Logger', [Logger]); // check for the availablility of the variety of console functions and create holders if necessary (function() { // handles all the console methods to make the console persistent, mainly for IE if (window.console === undefined) { window.console = {}; } // assign holder functions to any console method not available to avoid old browser errors (function() { var methods = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml", "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"], i = methods.length; for (; i--;) { if (!window.console[methods[i]]) { window.console[methods[i]] = function() {}; } } }()); }()); /** * @ngdoc service * @module angular-logger-max * @name angular-logger-max.service:Logger * @description Service to provide smarter and more descriptive logs to the console and remote logging services */ function Logger() { var _debug = false, _api = { log: log, error: error, warn: warn, info: info, data: data, shout: shout, loaded: loaded, track: track, get debug() { return _debug; }, set debug(val) { _debug = val; } }; return _api; /** * @ngdoc method * @name log * @description Method to log out a message or object along the lines of console.log * @methodOf angular-logger-max.service:Logger * @param {*} prepend A string or object to prepend the message with * @param {*} msg The message to display * @param {Boolean} fullStack Whether to show the full stack with the message * @param {Boolean} expand Whether to expand the structure of any objects or arrays logged out * @return {*} The string or object to log to the console */ function log(prepend, msg, fullStack, expand) { if (!_debug) return; _formatOutput('log', 'color: green', prepend, msg, _formatStackTrace(fullStack), expand); if (console.re) { console.re.log(prepend, (msg) ? msg : '<< END'); } } /** * @ngdoc method * @name info * @description Method to log out a message or object along the lines of console.info * @methodOf angular-logger-max.service:Logger * @param {*} prepend A string or object to prepend the message with * @param {*} msg The message to display * @param {Boolean} fullStack Whether to show the full stack with the message * @param {Boolean} expand Whether to expand the structure of any objects or arrays logged out * @return {*} The string or object to log to the console */ function info(prepend, msg, fullStack, expand) { if (!_debug) return; _formatOutput('info', 'color: blue', prepend, msg, _formatStackTrace(fullStack), expand); if (console.re) { console.re.info(prepend, (msg) ? msg : '<< END'); } } /** * @ngdoc method * @name warn * @description Method to log out a message or object along the lines of console.warn * @methodOf angular-logger-max.service:Logger * @param {*} prepend A string or object to prepend the message with * @param {*} msg The message to display * @param {Boolean} fullStack Whether to show the full stack with the message * @param {Boolean} expand Whether to expand the structure of any objects or arrays logged out * @return {*} The string or object to log to the console */ function warn(prepend, msg, fullStack, expand) { // always show warnings, debug or not _formatOutput('warn', 'color: orange', prepend, msg, _formatStackTrace(fullStack), expand); if (console.re) { console.warn(prepend, (msg) ? msg : '<< END'); } } /** * @ngdoc method * @name error * @description Method to log out a message or object along the lines of console.error * @methodOf angular-logger-max.service:Logger * @param {*} prepend A string or object to prepend the message with * @param {*} msg The message to display * @param {Boolean} fullStack Whether to show the full stack with the message (defaults to true) * @param {Boolean} expand Whether to expand the structure of any objects or arrays logged out * @return {*} The string or object to log to the console */ function error(prepend, msg, fullStack, expand) { fullStack = typeof fullStack === 'undefined' ? true : fullStack; // always show errors, debug or not _formatOutput('error', 'background-color: maroon; font-weight: bold; color: white', prepend, msg, _formatStackTrace(fullStack), expand); if (console.re) { console.re.error(prepend, (msg) ? msg : '<< END'); console.re.trace(); } } /** * @ngdoc method * @name data * @description Method to log out the structure of an object or array * @methodOf angular-logger-max.service:Logger * @param {*} prepend A string or object to prepend the message with * @param {*} msg The message to display * @param {Boolean} fullStack Whether to show the full stack with the message * @param {Boolean} expand Whether to expand the structure of any objects or arrays logged out (defaults to true) * @return {*} The string or object to log to the console */ function data(prepend, msg, fullStack, expand) { if (!_debug) return; // for data, by default log them out as full objects expand = typeof expand === 'undefined' ? true : expand; _formatOutput('data', 'color: hotpink', prepend, msg, _formatStackTrace(fullStack), expand); if (console.re) { console.re.debug(prepend, (msg) ? msg : '<< END'); } } /** * @ngdoc method * @name shout * @description Method to log out a message in a way to make the message more noticable in the console * @methodOf angular-logger-max.service:Logger * @param {*} prepend A string or object to prepend the message with * @param {*} msg The message to display * @param {Boolean} fullStack Whether to show the full stack with the message * @param {Boolean} expand Whether to expand the structure of any objects or arrays logged out * @return {*} The string or object to log to the console */ function shout(prepend, msg, fullStack, expand) { if (!_debug) return; _formatOutput('shout', 'color: red; font-weight: bold; font-size: 125%;', prepend, msg, _formatStackTrace(fullStack), expand); if (console.re) { console.re.log(prepend, (msg) ? msg : '<< END'); } } /** * @ngdoc method * @name loaded * @description Method to log out a message in a different colour than a standard log * @methodOf angular-logger-max.service:Logger * @param {*} prepend A string or object to prepend the message with * @param {*} msg The message to display * @param {Boolean} fullStack Whether to show the full stack with the message * @param {Boolean} expand Whether to expand the structure of any objects or arrays logged out * @return {*} The string or object to log to the console */ function loaded(prepend, msg, fullStack, expand) { if (!_debug) return; _formatOutput('loaded', 'color: purple', prepend, msg, _formatStackTrace(fullStack), expand); if (console.re) { console.re.log(prepend, (msg) ? msg : '<< END'); } } /** * @ngdoc method * @name track * @description Method to log out a message in a muted colour than a standard log * @methodOf angular-logger-max.service:Logger * @param {*} prepend A string or object to prepend the message with * @param {*} msg The message to display * @param {Boolean} fullStack Whether to show the full stack with the message * @param {Boolean} expand Whether to expand the structure of any objects or arrays logged out * @return {*} The string or object to log to the console */ function track(prepend, msg, fullStack, expand) { if (!_debug) return; _formatOutput('tracking', 'color: grey', prepend, msg, _formatStackTrace(fullStack), expand); if (console.re) { console.re.log(prepend, (msg) ? msg : '<< END'); } } /** * @description Function to format the console outputs according to what types of things are passed * @param {String} type A string to indicate the type of log * @param {String} styles A string of css styles * @param {String} prepend Text to prepend the output with * @param {Mixed} msg What is to be outputted to the console * @param {Boolean} fullStack Indicate whether the full stack trace should be shown (false by default) * @param {Boolean} expandObj Indicate whether any object being logged should be expanded in string form (false by default) */ function _formatOutput(type, styles, prepend, msg, fullStack, expandObj, remote) { var stackString = _trace() || '[unknown]', moduleType; fullStack = fullStack || ''; // pre-process type according to calling function moduleType = fullStack.substring(fullStack.indexOf('.', 0) + 1, _xIndexOf('.', fullStack, 2)); type = (_xIndexOf('.', fullStack, 2) > 0) ? ((stackString) ? '%c' : '') + '[#][' + type.toUpperCase() + '][' + _toTitleCase(moduleType) + '] ' : ((stackString) ? '%c' : '') + '[#][' + type.toUpperCase() + '] '; if (msg === undefined && typeof prepend !== 'object' && typeof prepend !== 'function') { // if a plain string if (stackString && stackString.length > 0) { console.log(type, styles, prepend, fullStack); } else { console.log(type, prepend, fullStack); } } else if (typeof prepend === 'object') { // if a single object with no prepending text if (expandObj) { if (stackString.length > 0) { console.log(type + JSON.stringify(prepend, null, '\t'), styles, fullStack); } else { console.log(type + JSON.stringify(prepend, null, '\t')); } } else { if (stackString.length > 0) { console.log(type, styles, prepend, fullStack); } else { console.log(type, prepend, fullStack); } } } else { // if prepend and msg exists if (typeof msg === 'object' && expandObj) { // if msg is an object and it needs to be automatically expanded if (stackString.length > 0) { console.log(type + prepend, styles, JSON.stringify(msg, null, '\t'), fullStack); } else { console.log(type + prepend, JSON.stringify(msg, null, '\t'), fullStack); } } else { // log it out as per normal if (stackString.length > 0) { console.log(type + prepend, styles, msg, fullStack); } else { console.log(type + prepend, msg, fullStack); } } } } /** * @description get the stack track from the output of a dummy error message so we can provide meaningful path information */ function _trace() { var err = new Error(); return err.stack; } /** * @description Function to format the full or summary stack trace to the console * @param {Boolean} fullStack Indicate whether the full stack should be shown in the console or just the filename * @return {String} */ function _formatStackTrace(fullStack) { fullStack = typeof fullStack === 'undefined' ? false : fullStack; if (!fullStack) { var lines = (_trace()) ? _trace().split('\n') : '', i, l; for (i = 0; i < lines.length; i++) { var val = lines[i]; if (val.toString() .indexOf('logger.js') === -1 && val.toString() !== 'Error') { return ('____ [' + lines[4].substring(lines[4].lastIndexOf('/') + 1) + ']') .replace(')', ''); } } } return (console.re) ? console.re.trace() : _trace(); } /** * @description Function to return the 2nd, 3rd or nth instance of a needle in a string * @usage var PicPath = "/somedirectory/pics/"; * var AppPath = picpath.substring(0, xIndexOf('/', PicPath, 2) + 1); * @param {Number} instance the number instance to find * @param {String} needle the needle to search for * @param {String} haystack the string to search within * @return {Number} the position in the string the nth instance of the needle was found in */ function _xIndexOf(needle, haystack, instance) { var found, i; if (instance <= (haystack.split(needle).length - 1)) { found = haystack.indexOf(needle); if (instance > 1) { for (i = 1; i < instance; i++) { found = haystack.indexOf(needle, found + 1); } } return found; } else { return 0; } } /** * Function to title case a string * @param {String} str the string to title case * @return {String} */ function _toTitleCase(str) { return str.replace(/\w\S*/g, function(txt) { return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); }); } } })();
mit
designermonkey/symphony-psr
symphony/lib/SymphonyCms/Toolkit/AuthorManager.php
9373
<?php namespace SymphonyCms\Toolkit; use \SymphonyCms\Symphony; use \SymphonyCms\Toolkit\Author; /** * The `AuthorManager` class is responsible for managing all Author objects * in Symphony. Unlike other Manager objects, Authors are stored in the * database in `tbl_authors` and not on the file system. CRUD methods are * implemented to allow Authors to be created (add), read (fetch), updated * (edit) and deleted (delete). */ class AuthorManager { /** * An array of all the objects that the Manager is responsible for. * Defaults to an empty array. * @var array */ protected static $_pool = array(); /** * Given an associative array of fields, insert them into the database * returning the resulting Author ID if successful, or false if there * was an error * * @param array $fields * Associative array of field names => values for the Author object * @return integer|boolean * Returns an Author ID of the created Author on success, false otherwise. */ public static function add(array $fields) { if (!Symphony::get('Database')->insert($fields, 'tbl_authors')) { return false; } $author_id = Symphony::get('Database')->getInsertID(); return $author_id; } /** * Given an Author ID and associative array of fields, update an existing Author * row in the `tbl_authors` database table. Returns boolean for success/failure * * @param integer $id * The ID of the Author that should be updated * @param array $fields * Associative array of field names => values for the Author object * This array does need to contain every value for the author object, it * can just be the changed values. * @return boolean */ public static function edit($id, array $fields) { return Symphony::get('Database')->update( $fields, 'tbl_authors', sprintf( " `id` = %d", $id ) ); } /** * Given an Author ID, delete an Author from Symphony. * * @param integer $id * The ID of the Author that should be deleted * @return boolean */ public static function delete($id) { return Symphony::get('Database')->delete( 'tbl_authors', sprintf( " `id` = %d", $id ) ); } /** * The fetch method returns all Authors from Symphony with the option to sort * or limit the output. This method returns an array of Author objects. * * @param string $sortby * The field to sort the authors by, defaults to 'id' * @param string $sortdirection * Available values of ASC (Ascending) or DESC (Descending), which refer to the * sort order for the query. Defaults to ASC (Ascending) * @param integer $limit * The number of rows to return * @param integer $start * The offset start point for limiting, maps to the LIMIT {x}, {y} MySQL functionality * @param string $where * Any custom WHERE clauses. The `tbl_authors` alias is `a` * @param string $joins * Any custom JOIN's * @return array * An array of Author objects. If no Authors are found, an empty array is returned. */ public static function fetch($sortby = 'id', $sortdirection = 'ASC', $limit = null, $start = null, $where = null, $joins = null) { $sortby = is_null($sortby) ? 'id' : Symphony::get('Database')->cleanValue($sortby); $sortdirection = $sortdirection === 'ASC' ? 'ASC' : 'DESC'; $records = Symphony::get('Database')->fetch( sprintf( "SELECT a.* FROM `tbl_authors` AS `a` %s WHERE %s ORDER BY %s %s %s %s", $joins, ($where ? $where : 1), 'a.'. $sortby, $sortdirection, ($limit ? "LIMIT " . $limit : ''), ($start && $limit ? ', ' . $start : '') ) ); if (!is_array($records) || empty($records)) { return array(); } $authors = array(); foreach ($records as $row) { $author_class = Symphony::get('classname.author'); $author = new $author_class; foreach ($row as $field => $val) { $author->set($field, $val); } self::$_pool[$author->get('id')] = $author; $authors[] = $author; } return $authors; } /** * Returns Author's that match the provided ID's with the option to * sort or limit the output. This function will search the * `AuthorManager::$_pool` for Authors first before querying `tbl_authors` * * @param integer|array $id * A single ID or an array of ID's * @return mixed * If `$id` is an integer, the result will be an Author object, * otherwise an array of Author objects will be returned. If no * Authors are found, or no `$id` is given, `null` is returned. */ public static function fetchByID($id) { $return_single = false; if (is_null($id)) { return null; } if (!is_array($id)) { $return_single = true; $id = array((int)$id); } if (empty($id)) { return null; } $authors = array(); $pooledauthors = array(); // Get all the Author ID's that are already in `self::$_pool` $pooledauthors = array_intersect($id, array_keys(self::$_pool)); foreach ($pooledauthors as $poolauthor) { $authors[] = self::$_pool[$poolauthor]; } // Get all the Author ID's that are not already stored in `self::$_pool` $id = array_diff($id, array_keys(self::$_pool)); $id = array_filter($id); if (empty($id)) { return ($return_single ? $authors[0] : $authors); } $records = Symphony::get('Database')->fetch( sprintf( "SELECT * FROM `tbl_authors` WHERE `id` IN (%s)", implode(",", $id) ) ); if (!is_array($records) || empty($records)) { return ($return_single ? $authors[0] : $authors); } foreach ($records as $row) { $author_class = Symphony::get('classname.author'); $author = new $author_class; foreach ($row as $field => $val) { $author->set($field, $val); } self::$_pool[$author->get('id')] = $author; $authors[] = $author; } return ($return_single ? $authors[0] : $authors); } /** * Returns an Author by Username. This function will search the * `AuthorManager::$_pool` for Authors first before querying `tbl_authors` * * @param string $username * The Author's username * @return Author|null * If an Author is found, an Author object is returned, otherwise null. */ public static function fetchByUsername($username) { if (!isset(self::$_pool[$username])) { $records = Symphony::get('Database')->fetchRow( 0, sprintf( "SELECT * FROM `tbl_authors` WHERE `username` = '%s' LIMIT 1", Symphony::get('Database')->cleanValue($username) ) ); if (!is_array($records) || empty($records)) { return array(); } $author = new Author; foreach ($records as $field => $val) { $author->set($field, $val); } self::$_pool[$username] = $author; } return self::$_pool[$username]; } /** * This function will allow an Author to sign into Symphony by using their * authentication token as well as username/password. * * @param integer $author_id * The Author ID to allow to use their authentication token. * @return boolean */ public static function activateAuthToken($author_id) { if (!is_int($author_id)) { return false; } return Symphony::get('Database')->query( sprintf( "UPDATE `tbl_authors` SET `auth_token_active` = 'yes' WHERE `id` = %d", $author_id ) ); } /** * This function will remove the ability for an Author to sign into Symphony * by using their authentication token * * @param integer $author_id * The Author ID to allow to use their authentication token. * @return boolean */ public static function deactivateAuthToken($author_id) { if (!is_int($author_id)) { return false; } return Symphony::get('Database')->query( sprintf( "UPDATE `tbl_authors` SET `auth_token_active` = 'no' WHERE `id` = %d", $author_id ) ); } }
mit
madhon/statsd.net
statsd.net.shared/Listeners/StatsdnetTcpListener.cs
4938
namespace statsd.net.shared.Listeners { using System; using System.IO; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Threading.Tasks.Dataflow; using statsd.net.core; using statsd.net.shared.Logging; using statsd.net.shared.Structures; public class StatsdnetTcpListener : IListener { private const int READ_TIMEOUT = 5000; /* 5 seconds */ private static string[] SPACE_SPLITTER = new String[] { " " }; private static string[] NEWLINE_SPLITTER = new String[] { Environment.NewLine }; private ITargetBlock<string> _target; private CancellationToken _token; private ISystemMetricsService _systemMetrics; private TcpListener _tcpListener; private int _activeConnections; private ActionBlock<DecoderBlockPacket> _decoderBlock; private readonly ILog _log = LogProvider.GetCurrentClassLogger(); public bool IsListening { get; private set; } public StatsdnetTcpListener(int port, ISystemMetricsService systemMetrics) { _systemMetrics = systemMetrics; IsListening = false; _activeConnections = 0; _tcpListener = new TcpListener(IPAddress.Any, port); _decoderBlock = new ActionBlock<DecoderBlockPacket>((data) => { DecodePacketAndForward(data); }, Utility.UnboundedExecution()); } public async void LinkTo(ITargetBlock<string> target, CancellationToken token) { _target = target; _token = token; await Listen(); } private async Task Listen() { _tcpListener.Start(); IsListening = true; while(!_token.IsCancellationRequested) { var tcpClient = await _tcpListener.AcceptTcpClientAsync(); ProcessIncomingConnection(tcpClient); } } private void ProcessIncomingConnection(TcpClient tcpClient) { try { Interlocked.Increment(ref _activeConnections); _systemMetrics.LogGauge("listeners.statsdnet.activeConnections", _activeConnections); _systemMetrics.LogCount("listeners.statsdnet.connection.open"); using (BinaryReader reader = new BinaryReader(tcpClient.GetStream())) { while (true) { if (reader.PeekChar() == 0) { // close the socket return; } // Get the length var packetLength = reader.ReadInt32(); // Is it compressed? var isCompressed = reader.ReadBoolean(); // Now get the packet var packet = reader.ReadBytes(packetLength); // Decode _decoderBlock.Post(new DecoderBlockPacket(packet, isCompressed)); } } } catch (SocketException se) { // oops, we're done _systemMetrics.LogCount("listeners.statsdnet.error.SocketException." + se.SocketErrorCode.ToString()); _log.ErrorException(String.Format("Socket Error occurred while listening. Code: {0}", se.SocketErrorCode), se); } catch (Exception ex) { _systemMetrics.LogCount("listeners.statsdnet.error." + ex.GetType().Name); _log.ErrorException(String.Format("{0} Error occurred while listening: ", ex.GetType().Name, ex.Message), ex); } finally { try { tcpClient.Close(); } catch { // Do nothing but log that this happened _systemMetrics.LogCount("listeners.statsdnet.error.closeThrewException"); } _systemMetrics.LogCount("listeners.statsdnet.connection.closed"); Interlocked.Decrement(ref _activeConnections); _systemMetrics.LogGauge("listeners.statsdnet.activeConnections", _activeConnections); } } private void DecodePacketAndForward(DecoderBlockPacket packet) { try { byte[] rawData; if (packet.isCompressed) { rawData = packet.data.Decompress(); _systemMetrics.LogCount("listeners.statsdnet.bytes.gzip", packet.data.Length); } else { rawData = packet.data; } _systemMetrics.LogCount("listeners.statsdnet.bytes.raw", rawData.Length); var lines = Encoding.UTF8.GetString(rawData).Split( NEWLINE_SPLITTER, StringSplitOptions.RemoveEmptyEntries ); foreach(var line in lines) { // Format this as raw and send it on. var parts = line.Split(SPACE_SPLITTER, StringSplitOptions.RemoveEmptyEntries); _target.Post(parts[0] + ":" + parts[1] + "|r|" + parts[2]); } _systemMetrics.LogCount("listeners.statsdnet.lines", lines.Length); } catch (Exception ex) { _systemMetrics.LogCount("listeners.statsdnet.decodingError." + ex.GetType().Name); } } } }
mit
cculianu/bitcoin-abc
test/functional/mining_basic.py
11862
#!/usr/bin/env python3 # Copyright (c) 2014-2019 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test mining RPCs - getmininginfo - getblocktemplate proposal mode - submitblock""" import copy from decimal import Decimal from test_framework.blocktools import ( create_coinbase, TIME_GENESIS_BLOCK, ) from test_framework.messages import ( CBlock, CBlockHeader, ) from test_framework.mininode import ( P2PDataStore, ) from test_framework.test_framework import BitcoinTestFramework from test_framework.util import ( assert_equal, assert_raises_rpc_error, connect_nodes_bi, ) def assert_template(node, block, expect, rehash=True): if rehash: block.hashMerkleRoot = block.calc_merkle_root() rsp = node.getblocktemplate( template_request={ 'data': block.serialize().hex(), 'mode': 'proposal'}) assert_equal(rsp, expect) class MiningTest(BitcoinTestFramework): def set_test_params(self): self.num_nodes = 2 self.setup_clean_chain = True def mine_chain(self): self.log.info('Create some old blocks') node = self.nodes[0] address = node.get_deterministic_priv_key().address for t in range(TIME_GENESIS_BLOCK, TIME_GENESIS_BLOCK + 200 * 600, 600): node.setmocktime(t) node.generatetoaddress(1, address) mining_info = node.getmininginfo() assert_equal(mining_info['blocks'], 200) assert_equal(mining_info['currentblocktx'], 0) assert_equal(mining_info['currentblocksize'], 1000) self.restart_node(0) connect_nodes_bi(self.nodes[0], self.nodes[1]) def run_test(self): self.mine_chain() node = self.nodes[0] def assert_submitblock(block, result_str_1, result_str_2=None): block.solve() result_str_2 = result_str_2 or 'duplicate-invalid' assert_equal(result_str_1, node.submitblock( hexdata=block.serialize().hex())) assert_equal(result_str_2, node.submitblock( hexdata=block.serialize().hex())) self.log.info('getmininginfo') mining_info = node.getmininginfo() assert_equal(mining_info['blocks'], 200) assert_equal(mining_info['chain'], 'regtest') assert 'currentblocktx' not in mining_info assert 'currentblocksize' not in mining_info assert_equal(mining_info['difficulty'], Decimal('4.656542373906925E-10')) assert_equal(mining_info['networkhashps'], Decimal('0.003333333333333334')) assert_equal(mining_info['pooledtx'], 0) # Mine a block to leave initial block download node.generatetoaddress(1, node.get_deterministic_priv_key().address) tmpl = node.getblocktemplate() self.log.info("getblocktemplate: Test capability advertised") assert 'proposal' in tmpl['capabilities'] assert 'coinbasetxn' not in tmpl coinbase_tx = create_coinbase(height=int(tmpl["height"]) + 1) # sequence numbers must not be max for nLockTime to have effect coinbase_tx.vin[0].nSequence = 2 ** 32 - 2 coinbase_tx.rehash() block = CBlock() block.nVersion = tmpl["version"] block.hashPrevBlock = int(tmpl["previousblockhash"], 16) block.nTime = tmpl["curtime"] block.nBits = int(tmpl["bits"], 16) block.nNonce = 0 block.vtx = [coinbase_tx] self.log.info("getblocktemplate: Test valid block") assert_template(node, block, None) self.log.info("submitblock: Test block decode failure") assert_raises_rpc_error(-22, "Block decode failed", node.submitblock, block.serialize()[:-15].hex()) self.log.info( "getblocktemplate: Test bad input hash for coinbase transaction") bad_block = copy.deepcopy(block) bad_block.vtx[0].vin[0].prevout.hash += 1 bad_block.vtx[0].rehash() assert_template(node, bad_block, 'bad-cb-missing') self.log.info("submitblock: Test invalid coinbase transaction") assert_raises_rpc_error(-22, "Block does not start with a coinbase", node.submitblock, bad_block.serialize().hex()) self.log.info("getblocktemplate: Test truncated final transaction") assert_raises_rpc_error(-22, "Block decode failed", node.getblocktemplate, { 'data': block.serialize()[:-1].hex(), 'mode': 'proposal'}) self.log.info("getblocktemplate: Test duplicate transaction") bad_block = copy.deepcopy(block) bad_block.vtx.append(bad_block.vtx[0]) assert_template(node, bad_block, 'bad-txns-duplicate') assert_submitblock(bad_block, 'bad-txns-duplicate', 'bad-txns-duplicate') self.log.info("getblocktemplate: Test invalid transaction") bad_block = copy.deepcopy(block) bad_tx = copy.deepcopy(bad_block.vtx[0]) bad_tx.vin[0].prevout.hash = 255 bad_tx.rehash() bad_block.vtx.append(bad_tx) assert_template(node, bad_block, 'bad-txns-inputs-missingorspent') assert_submitblock(bad_block, 'bad-txns-inputs-missingorspent') self.log.info("getblocktemplate: Test nonfinal transaction") bad_block = copy.deepcopy(block) bad_block.vtx[0].nLockTime = 2 ** 32 - 1 bad_block.vtx[0].rehash() assert_template(node, bad_block, 'bad-txns-nonfinal') assert_submitblock(bad_block, 'bad-txns-nonfinal') self.log.info("getblocktemplate: Test bad tx count") # The tx count is immediately after the block header TX_COUNT_OFFSET = 80 bad_block_sn = bytearray(block.serialize()) assert_equal(bad_block_sn[TX_COUNT_OFFSET], 1) bad_block_sn[TX_COUNT_OFFSET] += 1 assert_raises_rpc_error(-22, "Block decode failed", node.getblocktemplate, { 'data': bad_block_sn.hex(), 'mode': 'proposal'}) self.log.info("getblocktemplate: Test bad bits") bad_block = copy.deepcopy(block) bad_block.nBits = 469762303 # impossible in the real world assert_template(node, bad_block, 'bad-diffbits') self.log.info("getblocktemplate: Test bad merkle root") bad_block = copy.deepcopy(block) bad_block.hashMerkleRoot += 1 assert_template(node, bad_block, 'bad-txnmrklroot', False) assert_submitblock(bad_block, 'bad-txnmrklroot', 'bad-txnmrklroot') self.log.info("getblocktemplate: Test bad timestamps") bad_block = copy.deepcopy(block) bad_block.nTime = 2 ** 31 - 1 assert_template(node, bad_block, 'time-too-new') assert_submitblock(bad_block, 'time-too-new', 'time-too-new') bad_block.nTime = 0 assert_template(node, bad_block, 'time-too-old') assert_submitblock(bad_block, 'time-too-old', 'time-too-old') self.log.info("getblocktemplate: Test not best block") bad_block = copy.deepcopy(block) bad_block.hashPrevBlock = 123 assert_template(node, bad_block, 'inconclusive-not-best-prevblk') assert_submitblock(bad_block, 'prev-blk-not-found', 'prev-blk-not-found') self.log.info('submitheader tests') assert_raises_rpc_error(-22, 'Block header decode failed', lambda: node.submitheader(hexdata='xx' * 80)) assert_raises_rpc_error(-22, 'Block header decode failed', lambda: node.submitheader(hexdata='ff' * 78)) assert_raises_rpc_error(-25, 'Must submit previous header', lambda: node.submitheader(hexdata='ff' * 80)) block.nTime += 1 block.solve() def chain_tip(b_hash, *, status='headers-only', branchlen=1): return {'hash': b_hash, 'height': 202, 'branchlen': branchlen, 'status': status} assert chain_tip(block.hash) not in node.getchaintips() node.submitheader(hexdata=block.serialize().hex()) assert chain_tip(block.hash) in node.getchaintips() # Noop node.submitheader(hexdata=CBlockHeader(block).serialize().hex()) assert chain_tip(block.hash) in node.getchaintips() bad_block_root = copy.deepcopy(block) bad_block_root.hashMerkleRoot += 2 bad_block_root.solve() assert chain_tip(bad_block_root.hash) not in node.getchaintips() node.submitheader(hexdata=CBlockHeader( bad_block_root).serialize().hex()) assert chain_tip(bad_block_root.hash) in node.getchaintips() # Should still reject invalid blocks, even if we have the header: assert_equal(node.submitblock( hexdata=bad_block_root.serialize().hex()), 'bad-txnmrklroot') assert_equal(node.submitblock( hexdata=bad_block_root.serialize().hex()), 'bad-txnmrklroot') assert chain_tip(bad_block_root.hash) in node.getchaintips() # We know the header for this invalid block, so should just return # early without error: node.submitheader(hexdata=CBlockHeader( bad_block_root).serialize().hex()) assert chain_tip(bad_block_root.hash) in node.getchaintips() bad_block_lock = copy.deepcopy(block) bad_block_lock.vtx[0].nLockTime = 2**32 - 1 bad_block_lock.vtx[0].rehash() bad_block_lock.hashMerkleRoot = bad_block_lock.calc_merkle_root() bad_block_lock.solve() assert_equal(node.submitblock( hexdata=bad_block_lock.serialize().hex()), 'bad-txns-nonfinal') assert_equal(node.submitblock( hexdata=bad_block_lock.serialize().hex()), 'duplicate-invalid') # Build a "good" block on top of the submitted bad block bad_block2 = copy.deepcopy(block) bad_block2.hashPrevBlock = bad_block_lock.sha256 bad_block2.solve() assert_raises_rpc_error(-25, 'bad-prevblk', lambda: node.submitheader( hexdata=CBlockHeader(bad_block2).serialize().hex())) # Should reject invalid header right away bad_block_time = copy.deepcopy(block) bad_block_time.nTime = 1 bad_block_time.solve() assert_raises_rpc_error(-25, 'time-too-old', lambda: node.submitheader( hexdata=CBlockHeader(bad_block_time).serialize().hex())) # Should ask for the block from a p2p node, if they announce the header # as well: node.add_p2p_connection(P2PDataStore()) # Drop the first getheaders node.p2p.wait_for_getheaders(timeout=5) node.p2p.send_blocks_and_test(blocks=[block], node=node) # Must be active now: assert chain_tip(block.hash, status='active', branchlen=0) in node.getchaintips() # Building a few blocks should give the same results node.generatetoaddress(10, node.get_deterministic_priv_key().address) assert_raises_rpc_error(-25, 'time-too-old', lambda: node.submitheader( hexdata=CBlockHeader(bad_block_time).serialize().hex())) assert_raises_rpc_error(-25, 'bad-prevblk', lambda: node.submitheader( hexdata=CBlockHeader(bad_block2).serialize().hex())) node.submitheader(hexdata=CBlockHeader(block).serialize().hex()) node.submitheader(hexdata=CBlockHeader( bad_block_root).serialize().hex()) # valid assert_equal(node.submitblock( hexdata=block.serialize().hex()), 'duplicate') if __name__ == '__main__': MiningTest().main()
mit
isukces/isukces.code
isukces.code/Compatibility/System.Windows/FrameworkElement.cs
264
namespace iSukces.Code.Compatibility.System.Windows { [EmitType("System.Windows")] public class FrameworkElement { public Thickness Margin { get; set; } public VerticalAlignment VerticalAlignment { get; set; } } }
mit
bashaus/oriancci
src/Oriancci/Drivers/SQLite/Table.php
404
<?php namespace Oriancci\Drivers\SQLite; class Table extends \Oriancci\Table { public function describe() { $modelName = $this->modelName; $connection = $modelName::connection(); return $connection->query('PRAGMA table_info([' . $this->tableFullName() . '])'); } public function columnClass() { return 'Oriancci\Drivers\SQLite\Column'; } }
mit
afunai/bike
t/test_img.rb
8318
# encoding: UTF-8 # Author:: Akira FUNAI # Copyright:: Copyright (c) 2009-2010 Akira FUNAI require "#{::File.dirname __FILE__}/t" class TC_Img < Test::Unit::TestCase def setup Bike.current[:uri] = nil File.open('t/skin/t_img/test.jpg') {|f| @img = f.read @file = Tempfile.open('tc_img') @file << @img } meta = nil Bike::Parser.gsub_scalar('$(foo img 32*32 1..100000 jpg, gif, png crop)') {|id, m| meta = m '' } @f = Bike::Field.instance meta.merge(:id => 'foo') end def test_meta assert_equal( 1, @f[:min], 'Img#initialize should set :min from the range token' ) assert_equal( 100000, @f[:max], 'Img#initialize should set :max from the range token' ) assert_equal( ['jpg', 'gif', 'png'], @f[:options], 'Img#initialize should set :options from the csv token' ) assert_equal( true, @f[:crop], 'Img#initialize should set :options from the csv token' ) end def test_val_cast_from_rack @f.create( :type => 'image/jpeg', :tempfile => @file, :head => <<'_eos', Content-Disposition: form-data; name="t_img"; filename="baz.jpg" Content-Type: image/jpeg _eos :filename => 'baz.jpg', :name => 't_img' ) assert_equal( { 'basename' => 'baz.jpg', 'type' => 'image/jpeg', 'size' => @file.length, }, @f.val, 'Img#val_cast should re-map a hash from Rack' ) assert_equal( @img, @f.body, 'Img#val_cast should store the file body in @body' ) assert_equal( @f.send(:_thumbnail, @file), @f.thumbnail, 'Img#val_cast should store the thumbnail in @thumbnail' ) end def test_val_cast_load @f.load( 'basename' => 'baz.jpg', 'type' => 'image/jpeg', 'size' => 123 ) assert_equal( { 'basename' => 'baz.jpg', 'type' => 'image/jpeg', 'size' => 123, }, @f.val, 'Img#val_cast should load() a hash without :tempfile like Set#load' ) end def test_large_thumbnail @f[:width] = @f[:height] = 640 @f.create( :type => 'image/jpeg', :tempfile => @file, :head => <<'_eos', Content-Disposition: form-data; name="t_img"; filename="baz.jpg" Content-Type: image/jpeg _eos :filename => 'baz.jpg', :name => 't_img' ) assert_not_equal( 0, @f.instance_variable_get(:@thumbnail).to_s.size, 'Img#_thumbnail should make a thumbnail larger than the original img' ) end def test_get Bike.client = 'root' @f[:parent] = Bike::Set::Static::Folder.root.item('t_img', 'main') Bike.current[:base] = @f[:parent] tid = @f[:parent][:tid] @f.load({}) assert_equal( <<'_html'.chomp, <span class="dummy_img" style="width: 32px; height: 32px;"></span> _html @f.get, 'Img#get should return default span when the val is empty' ) @f.load( 'basename' => 'baz.jpg', 'type' => 'image/jpeg', 'size' => 12 ) assert_equal( <<'_html'.chomp, <a href="/t_img/main/foo/baz.jpg"><img src="/t_img/main/foo/baz_small.jpg" alt="baz.jpg" /></a> _html @f.get, 'Img#get should return proper string' ) assert_equal( <<"_html", <span class="img"> <a href="/t_img/#{tid}/foo/baz.jpg"><img src="/t_img/#{tid}/foo/baz_small.jpg" alt="baz.jpg" /></a> <input type="file" name="foo" size="" class="file" /> </span> _html @f.get(:action => :update), 'Img#get should return proper string' ) @f.load( 'basename' => '<baz>.jpg', 'type' => 'image/<jpeg>', 'size' => 12 ) assert_equal( <<'_html'.chomp, <a href="/t_img/main/foo/&lt;baz&gt;.jpg"><img src="/t_img/main/foo/&lt;baz&gt;_small.jpg" alt="&lt;baz&gt;.jpg" /></a> _html @f.get, 'Img#get should escape the special characters in file information' ) end def test_get_not_image @f.create( :type => 'text/plain', :tempfile => @file, :head => <<'_eos', Content-Disposition: form-data; name="t_img"; filename="baz.txt" Content-Type: text/plain _eos :filename => 'baz.txt', :name => 't_img' ) assert_equal( '<a href="foo/baz.txt">baz.txt (3535 bytes)</a>', @f.get, 'Img#get should fall back to File#get if the file is not an image' ) end def test_call_body Bike.client = 'root' sd = Bike::Set::Static::Folder.root.item('t_img', 'main') sd.storage.clear # post a multipart request input = <<"_eos".gsub(/\r?\n/, "\r\n").sub('@img', @img) ---foobarbaz Content-Disposition: form-data; name="_1-foo"; filename="foo.jpg" Content-Type: image/jpeg Content-Transfer-Encoding: binary @img ---foobarbaz Content-Disposition: form-data; name="_token" #{Bike.token} ---foobarbaz-- _eos res = Rack::MockRequest.new(Bike.new).post( 'http://example.com/t_img/main/update.html', { :input => input, 'CONTENT_TYPE' => 'multipart/form-data; boundary=-foobarbaz', 'CONTENT_LENGTH' => input.respond_to?(:bytesize) ? input.bytesize : input.size, } ) tid = res.headers['Location'][Bike::REX::TID] # commit the base res = Rack::MockRequest.new(Bike.new).post( "http://example.com/#{tid}/update.html", { :input => ".status-public=create&_token=#{Bike.token}", } ) res.headers['Location'] =~ Bike::REX::PATH_ID new_id = sprintf('%.8d_%.4d', $1, $2) res = Rack::MockRequest.new(Bike.new).get( "http://example.com/t_img/#{new_id}/foo/foo.jpg" ) assert_equal( 'image/jpeg', res.headers['Content-Type'], 'Bike#call to a img item should return the mime type of the file' ) assert_equal( @img.respond_to?(:bytesize) ? @img.bytesize : @img.size, res.body.respond_to?(:bytesize) ? res.body.bytesize : res.body.size, 'Bike#call to a img item should return the binary body of the file' ) res = Rack::MockRequest.new(Bike.new).get( "http://example.com/t_img/#{new_id}/foo/foo_small.jpg" ) assert_equal( 'image/jpeg', res.headers['Content-Type'], "Bike#call to 'file-small.*' should return the thumbnail of the file" ) @file.rewind assert_equal( @f.send(:_thumbnail, @file).size, res.body.size, "Bike#call to 'file-small.*' should return the thumbnail of the file" ) # delete Rack::MockRequest.new(Bike.new).post( 'http://example.com/t_img/update.html', { :input => "#{new_id}.action=delete&.status-public=delete&_token=#{Bike.token}", } ) res = Rack::MockRequest.new(Bike.new).get( "http://example.com/t_img/#{new_id}/foo/foo.jpg" ) assert_equal( 404, res.status, 'Bike#call should delete child files as well' ) res = Rack::MockRequest.new(Bike.new).get( "http://example.com/t_img/#{new_id}/foo/foo_small.jpg" ) assert_equal( 404, res.status, 'Bike#call should delete child files as well' ) end def test_errors File.open('t/skin/t_img/index.html') {|f| @img = f.read @file = Tempfile.open('tc_img') @file << @img } @f.create( :type => 'image/jpeg', :tempfile => @file, :head => <<'_eos', Content-Disposition: form-data; name="t_img"; filename="baz.jpg" Content-Type: image/jpeg _eos :filename => 'baz.jpg', :name => 't_img' ) assert_equal( ['wrong file type: should be jpg/gif/png'], @f.errors, "Img#errors should regard quick_magick errors as 'wrong file type'" ) File.open('t/skin/t_img/test.jpg') {|f| @img = f.read @file = Tempfile.open('tc_img') @file << @img } @f.update( :type => 'image/jpeg', :tempfile => @file, :head => <<'_eos', Content-Disposition: form-data; name="t_img"; filename="baz.jpg" Content-Type: image/jpeg _eos :filename => 'baz.jpg', :name => 't_img' ) assert_equal( [], @f.errors, "Img#errors should raise no errors for good imgs" ) end end
mit
bear454/osem
db/migrate/20140930092923_move_sponsor_email_to_contact.rb
731
# frozen_string_literal: true class MoveSponsorEmailToContact < ActiveRecord::Migration class TempConference < ActiveRecord::Base self.table_name = 'conferences' end class TempContact < ActiveRecord::Base self.table_name = 'contacts' end def change add_column :contacts, :sponsor_email, :string TempConference.all.each do |conference| contact = TempContact.find_by(conference_id: conference.id) if contact contact.sponsor_email = conference.sponsor_email contact.save else Contact.create(conference_id: conference.id, sponsors_email: conference.sponsor_email) end end remove_column :conferences, :sponsor_email end end
mit
uqtimes/OnionRingCSharp
Assets/Editor/OnionRingCSharp.cs
11303
using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Text; using UnityEditor; using UnityEngine; // Original // https://github.com/kyubuns/onion_ring/blob/master/onion_ring.rb namespace OnionRingCSharp { /// <summary> /// 'oily_png'のインタフェースを模したクラス /// </summary> namespace ChunkyPng { // http://www.rubydoc.info/github/wvanbergen/chunky_png/ChunkyPNG/Color enum Color { Transparent, } // http://www.rubydoc.info/github/wvanbergen/chunky_png/ChunkyPNG/Image class Image { public int height { get; private set; } public int width { get; private set; } Texture2D texture = null; /// <summary> /// イメージの読み込み /// </summary> /// <param name="path">読み込む画像のパス</param> /// <returns></returns> public static Image FromFile(string path) { return new Image(path); } protected Image(string path) { texture = AssetDatabase.LoadAssetAtPath(path, typeof(Texture2D)) as Texture2D; width = texture.width; height = texture.height; } /// <summary> /// イメージの新規作成 /// </summary> /// <param name="width"></param> /// <param name="height"></param> /// <param name="bgColor">画像の背景色(現在未使用)</param> /// <returns></returns> public static Image New(int width, int height, ChunkyPng.Color bgColor) { return new Image(width, height, bgColor); } protected Image(int width, int height, ChunkyPng.Color bgColor) { this.width = width; this.height = height; texture = new Texture2D(width, height, TextureFormat.RGBA32, false); } /// <summary> /// 指定されたx座標の一行を返す /// </summary> /// <param name="x"></param> /// <returns></returns> public IEnumerable<UnityEngine.Color> Column(int x) { return texture.GetPixels(x, 0, 1, height).Reverse(); } /// <summary> /// 指定されたy座標の一列を返す /// </summary> /// <param name="y"></param> /// <returns></returns> public IEnumerable<UnityEngine.Color> Row(int y) { return texture.GetPixels(0, height - 1 - y, width, 1); } /// <summary> /// GetPixelは左下スタートなので、左上スタートの色情報を返す /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <returns></returns> public UnityEngine.Color GetPixel(int x, int y) { return texture.GetPixel(x, height - 1 - y); } /// <summary> /// SetPixelは左下スタートなので、左上スタートの色情報を変更する /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <param name="color"></param> public void SetPixel(int x, int y, UnityEngine.Color color) { texture.SetPixel(x, height - 1 - y, color); } /// <summary> /// x,yの座標で色情報にアクセスさせるためのインデクサ /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <returns></returns> public UnityEngine.Color this[int x, int y] { get { return GetPixel(x, y); } set { SetPixel(x, y, value); } } /// <summary> /// 指定したファイルへ画像を書き出す /// </summary> /// <param name="filePath"></param> public void Save(string filePath) { File.WriteAllBytes(filePath, texture.EncodeToPNG()); } } } namespace Digest { /// <summary> /// 'digest/sha1'のインタフェースを模したクラス /// </summary> static class SHA1 { static SHA1CryptoServiceProvider sha = new SHA1CryptoServiceProvider(); public static string HexDigest(string str) { return ToHashString(ComputeHash(str)); } static byte[] ComputeHash(string str) { return sha.ComputeHash(Encoding.ASCII.GetBytes(str)); } static string ToHashString(byte[] bytes) { var sb = new StringBuilder(); foreach (var b in bytes) { sb.Append(b.ToString("X2")); } return sb.ToString(); } } } /// <summary> /// Rubyの記述と同じように書けるようにするためのLINQ拡張 /// </summary> static partial class LinqExtensions { public static string Join<T>(this IEnumerable<T> list, string separator) { return string.Join(separator, list.Select(o => o.ToString()).ToArray()); } public static void Each<T>(this IEnumerable<T> list, System.Action<T> action) { foreach (T item in list) { action(item); } } public static void EachWithIndex<T>(this IEnumerable<T> list, System.Action<T, int> action) { var e = list.GetEnumerator(); var i = 0; while (e.MoveNext()) { action(e.Current, i++); } } } /// <summary> /// OnionRingの本体 /// オリジナルのソースコードと見た目が変わらないことを優先してある (実行速度 < オリジナルとの差分) /// </summary> static class OnionRing { public static SpriteBorder Run(string sourceFileName, string outputFileName = null) { outputFileName = outputFileName ?? sourceFileName; var png = ChunkyPng.Image.FromFile(sourceFileName); var rangeWidth = CalcTrimRange(Enumerable.Range(0, png.width) .Select(x => Digest.SHA1.HexDigest(png.Column(x).Select(c => (c.a != 0) ? c : new Color(0, 0, 0, 0)).Join(",")))); var rangeHeight = CalcTrimRange(Enumerable.Range(0, png.height) .Select(x => Digest.SHA1.HexDigest(png.Row(x).Select(c => (c.a != 0) ? c : new Color(0, 0, 0, 0)).Join(",")))); var dpix = 2; if (rangeWidth == null || rangeWidth[1] - rangeWidth[0] <= dpix * 2) { rangeWidth = new int[] { 0, -1 }; } else { rangeWidth[0] += dpix; rangeWidth[1] -= dpix; } if (rangeHeight == null || rangeHeight[1] - rangeHeight[0] <= dpix * 2) { rangeHeight = new int[] { 0, -1 }; } else { rangeHeight[0] += dpix; rangeHeight[1] -= dpix; } CreateSlicedImage(png, outputFileName, rangeWidth, rangeHeight); if (rangeWidth[0] == 0 && rangeWidth[1] == -1) { rangeWidth = new int[] { 1, png.width - dpix }; } if (rangeHeight[0] == 0 && rangeHeight[1] == -1) { rangeHeight = new int[] { 1, png.height - dpix }; } var left = rangeWidth[0] - 1; var top = rangeHeight[0] - 1; var right = png.width - rangeWidth[1] - dpix; var bottom = png.height - rangeHeight[1] - dpix; return new SpriteBorder(left, top, right, bottom); } static int[] CalcTrimRange(IEnumerable<string> hashList) { string tmpHash = null; var tmpStartIndex = 0; var maxLength = 0; int[] maxRange = null; var _maxRange = new int[2]; // newが何度も呼び出されるため、事前に確保 hashList.EachWithIndex((hash, index) => { var length = ((index - 1) - tmpStartIndex); if (length > maxLength) { maxLength = length; // C#用に変更 _maxRange[0] = tmpStartIndex; _maxRange[1] = index - 1; maxRange = _maxRange; } if (tmpHash != hash) { tmpHash = hash; tmpStartIndex = index; } }); return maxRange; } static void CreateSlicedImage(ChunkyPng.Image png, string outputFileName, int[] rangeWidth, int[] rangeHeight) { var outputWidth = png.width - ((rangeWidth[1] - rangeWidth[0]) + 1); var outputHeight = png.height - ((rangeHeight[1] - rangeHeight[0]) + 1); var output = ChunkyPng.Image.New(outputWidth, outputHeight, ChunkyPng.Color.Transparent); Enumerable.Range(0, outputWidth).Each(ax => { Enumerable.Range(0, outputHeight).Each(ay => { var bx = ax; var by = ay; if (bx >= rangeWidth[0]) { bx = ax + ((rangeWidth[1] - rangeWidth[0]) + 1); } if (by >= rangeHeight[0]) { by = ay + ((rangeHeight[1] - rangeHeight[0]) + 1); } output[ax, ay] = png.GetPixel(bx, by); }); }); output.Save(outputFileName); } } /// <summary> /// スライス後のボーダーを定義 /// </summary> public struct SpriteBorder { public int left { get; private set; } public int top { get; private set; } public int right { get; private set; } public int bottom { get; private set; } public SpriteBorder(int left, int top, int right, int bottom) { this.left = left; this.top = top; this.right = right; this.bottom = bottom; } /// <summary> /// NGUIやSpriteで利用する順序でVector4を返す /// </summary> /// <returns></returns> public Vector4 ToVector4() { return new Vector4(left, bottom, right, top); } /// <summary> /// OnionRingで返された値をそのままの順序で返す /// </summary> /// <returns></returns> public new string ToString() { return string.Format("[{0},{1},{2},{3}]", left, top, right, bottom); } } }
mit
Timothep/SimpleExpressions
SimpleExpression/SimpleExpression.Core/AbstractTree/Nodes/BaseNode.cs
560
using SimpleExpressions.Core.AbstractTree.DomainObjects; using SimpleExpressions.Core.Converters; namespace SimpleExpressions.Core.AbstractTree.Nodes { public abstract class BaseNode : INode { public INode Parent { get; set; } public Cardinality Cardinality { get; set; } public IConverter Converter { get; set; } public abstract string Generate(); protected BaseNode(IConverter converter) { this.Converter = converter; this.Cardinality = new Cardinality(); } } }
mit
GluuFederation/community-edition-setup
setup_app/utils/progress.py
4603
import sys import time from setup_app import static from setup_app.config import Config from threading import Thread # credit https://github.com/verigak/progress/blob/master/progress/spinner.py phases = ['◑', '◒', '◐', '◓'] phases = ('-', '\\', '|', '/') phases = ['◷', '◶', '◵', '◴'] phases = ['⎺', '⎻', '⎼', '⎽', '⎼', '⎻'] phases = ['⣾', '⣷', '⣯', '⣟', '⡿', '⢿', '⣻', '⣽'] finished_char = '✓' class ShowProgress(Thread): def __init__(self, services, queue, timeout=15): Thread.__init__(self) self.services = services self.service_names = [s['name'] for s in services] self.queue = queue self.end_time = time.time() + timeout * 60 def get_max_len(self): max_len = 0 for s in self.services: if len(s['name']) > max_len: max_len = len(s['name']) max_len += 1 return max_len def run(self): number_of_services = len(self.services) current_service = 0 phase_counter = 0 data = {} msg = '' last_completed = 0 max_len = self.get_max_len() while True: if time.time() > self.end_time: print("Timed out. Ending up process.") break if not self.queue.empty(): data = self.queue.get() if data.get('current'): for si, s in enumerate(self.services): if s['name'] == data['current']: current_service = si s['msg'] = data.get('msg','') last_completed = si break else: if data['current'] == static.COMPLETED: current_service = 99 # this means service was not registered before, do it now elif not data['current'] in self.service_names: self.services.insert(last_completed + 1, { 'name': data['current'], 'app_type': static.AppType.APPLICATION, 'install_type': static.InstallOption.OPTONAL, 'msg': data.get('msg','') }) number_of_services += 1 max_len = self.get_max_len() for i, service in enumerate(self.services): spin_char = ' ' if i == current_service: spin_char = phases[phase_counter%len(phases)] elif i < current_service: spin_char = '\033[92m{}\033[0m'.format(finished_char) sys.stdout.write(spin_char + ' ' + service['name'].ljust(max_len) + ' ' + service.get('msg','') +'\n') if current_service < number_of_services: for _ in range(number_of_services): sys.stdout.write("\x1b[1A\x1b[2K") else: sys.stdout.write(data.get('msg',"Installation completed")) print() break time.sleep(0.15) phase_counter += 1 class GluuProgress: services = [] queue = None def register(self, installer): progress_entry = { 'name': installer.service_name, 'app_type': installer.app_type, 'install_type': installer.install_type, 'object': installer, 'install_var': installer.install_var, } self.services.append(progress_entry) def before_start(self): for service in self.services[:]: if service['name'] != 'post-setup': if Config.installed_instance: if not service['install_var'] in Config.addPostSetupService: self.services.remove(service) else: if not Config.get(service['install_var']): self.services.remove(service) def start(self): if self.queue: th = ShowProgress(self.services, self.queue) th.setDaemon(True) th.start() def progress(self, service_name, msg='', incr=False): if self.queue: self.queue.put({'current': service_name, 'msg': msg}) elif service_name != static.COMPLETED: print("Process {}: {}".format(service_name, msg)) gluuProgress = GluuProgress()
mit
MichalPaszkiewicz/depictr
scripts/initialise.ts
319
"use strict"; module Depictr { export var canvas = <HTMLCanvasElement>document.getElementById("my-canvas"); export var ctx = canvas.getContext("2d"); canvas.width = 500; canvas.height = 500; ctx.textAlign = "center"; ctx.fillText("Drop image here", canvas.width / 2, canvas.height / 2); }
mit
resir014/thebestmotherfuckingwebsite.co
src/components/Epilogue/Epilogue.tsx
3117
import * as React from 'react' import { Container } from '../Container' import { FullScreenSection } from '../FullScreenSection' export const Epilogue: React.SFC = () => ( <FullScreenSection name="epilogue"> <Container> <h1> AND YES, THIS WHOLE THING IS <em>STILL</em> SATIRE, YOU DIPSHIT. </h1> <p> I&apos;m gonna end this motherfucking rant with some positivity. My point is, yes, it&apos;s true that the{' '} <a href="https://www.wired.com/2016/04/average-webpage-now-size-original-doom/" target="_blank" rel="noopener noreferrer"> average webpage is now the size of the original DOOM </a> . Sure, websites are getting more and more bloated. But all of these matter less than what they used to be. In fact, the developers of No Man&apos;s Sky tried to make their procedurally-generated game as small as they can. Look how well that turned out. </p> <p> This whole increase in size is natural, but also, recent innovation in web development has made it easier to make your codebase less shit. When one door closes, another one opens wide. What matters is how can you optimize for that sweet, sweet Lighthouse score, that sweet, sweet first meaningful paint (FMP) time. Be it by code splitting, preloading your essentials, lazyloading your shit, or whatever kind of black magic you came up with. I don&apos;t care, it&apos;s your app. I don&apos;t make the rules. </p> <p> And sure, the JavaScript platform is exploding like diarrhea, and we&apos;ve seen a lot of shitty apps written in JavaScript as of late. But just like many other{' '} <a href="https://secure.php.net/" target="_blank" rel="noopener noreferrer"> shitty languages </a> , <strong>the language itself is hardly an issue</strong>. Any bad developer can take any platform/ecosystem and shit on it. But amongst the dark alleyways filled with piles of shit, there&apos;s still a majority of people trying their hardest to make things better for everyone. </p> <blockquote> <p>&quot;Hey you know the best way to write apps? The way that ends up with an app.&quot;</p> <cite> &mdash;{' '} <a href="https://twitter.com/ken_wheeler/status/1022443093679845377" target="_blank" rel="noopener noreferrer"> Ken Fucking Wheeler </a> </cite> </blockquote> <p> Anyways, this website is made by{' '} <a href="https://resir014.xyz/" target="_blank" rel="noopener noreferrer"> me </a> , and the domain name is generously donated by{' '} <a href="https://twitter.com/A7_145" target="_blank" rel="noopener noreferrer"> him </a> . It&apos;s entirely open-source and available on{' '} <a href="https://github.com/resir014/thebestmotherfuckingwebsite.co" target="_blank" rel="noopener noreferrer"> GitHub </a> . </p> </Container> </FullScreenSection> )
mit
jasonmit/ember-i18n-errors
tests/dummy/app/locales/en/translations.js
148
export default { errors: { blank: "can't blank", invalid: "generic invalid", email: { blank: "email can't be blank" } } }
mit
Hand-Talk/android-library
android-sdk/src/main/java/br/com/handtalk/androidlib/HugoActivity.java
6756
package br.com.handtalk.androidlib; import android.content.Context; import android.content.SharedPreferences; import android.graphics.PixelFormat; import android.os.Bundle; import android.os.Handler; import android.preference.PreferenceManager; import android.util.DisplayMetrics; import android.util.Log; import android.view.View; import android.view.Window; import android.widget.FrameLayout; import android.widget.RelativeLayout; import com.unity3d.player.UnityPlayer; import static br.com.handtalk.androidlib.Constants.Configurations.TAG; /** * HAND TALK - A Translator Plataform from Spoken and * Written Languages to Sign languages. * http://www.handtalk.me * * Created by carloswanderlan on 3/6/17. */ public class HugoActivity extends CallbackInterface implements CallbackInterface.OnUnityListener { protected UnityPlayer mUnityPlayer; protected Handler handler; protected String textToTranslate = ""; protected boolean touchoutsideToExit; protected int typeOfWindow; protected RelativeLayout loaderRl; protected HandTalkSDK htsdk; protected Context ctx; @Override protected void onCreate(Bundle savedInstanceState) { requestWindowFeature(Window.FEATURE_NO_TITLE); super.onCreate(savedInstanceState); setContentView(R.layout.activity_hugo); loaderRl = (RelativeLayout) findViewById(R.id.HTSDKloader); ctx = this; mOUL = this; handler = new Handler(); setupUnity(); setConfigPopUp(); setConfigByBundleExtras(); } private void dismissActivity(){ onBackPressed(); } private void setConfigByBundleExtras() { Bundle b = getIntent().getExtras(); if(b!=null) { textToTranslate = (String) b.get("HT_StringToTranslate"); touchoutsideToExit = (boolean) b.get("HT_TouchableToExit"); typeOfWindow = (int) b.get("HT_WindowType"); if (touchoutsideToExit) { setFinishOnTouchOutside(true); } } } private void setConfigPopUp() { DisplayMetrics dm = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(dm); int width = dm.widthPixels; int height = dm.heightPixels; getWindow().setLayout((int)(width/1.3), (int)(height/1.5)); Log.i(TAG,"typeOfWindow on HugoActivity: "+typeOfWindow); } public void setupUnity() { try { getWindow().setFormat(PixelFormat.RGBX_8888); // <--- This makes xperia play happy mUnityPlayer = new UnityPlayer(this); // if (mUnityPlayer.getSettings().getBoolean("hide_status_bar", true)) { // getWindow().setFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN, WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN); // getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); // getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); // } View playerView = mUnityPlayer.getView(); FrameLayout layout = (FrameLayout) findViewById(R.id.frameUnity); layout.addView(playerView, getWindow().getAttributes().width, getWindow().getAttributes().height); mUnityPlayer.requestFocus(); } catch (Exception e) { Log.e(TAG, "setupUnity() : " + e.getMessage()); } } //Override METHODS @Override protected void onRestart() { super.onRestart(); Log.i(TAG, "onRestart()"); } // Quit Unity @Override protected void onDestroy () { mUnityPlayer.quit(); super.onDestroy(); Log.i(TAG, "onDestroy()"); } // Pause Unity @Override protected void onPause() { super.onPause(); mUnityPlayer.pause(); Log.i(TAG, "onPause()"); } // Notify Unity of the focus change. @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); mUnityPlayer.windowFocusChanged(hasFocus); } @Override protected void onStart() { super.onStart(); Log.i(TAG, "onStart()"); } @Override protected void onStop() { super.onStop(); mUnityPlayer.pause(); Log.i(TAG, "onStop()"); } @Override protected void onResume() { super.onResume(); mUnityPlayer.resume(); Log.i(TAG, "onResume()"); } //UNITY CALLBACK FUCNTIONS public void OnAnimationEnd() { Log.i(TAG, "OnAnimationEnd()"); handler.post(new Runnable() { @Override public void run() { dismissActivity(); Log.i(TAG, "OnAnimationEnd()"); } }); } public void OnDataLoaded() { handler.postDelayed(new Runnable() { @Override public void run() { Log.i(TAG, "OnDataLoaded()"); } }, 300); } public void OnLoadingDatas() { handler.post(new Runnable() { @Override public void run() { Log.i(TAG, "OnLoadingDatas()"); } }); } public void OnStopAnimation() { handler.post(new Runnable() { @Override public void run() { Log.i(TAG, "OnStopAnimation()"); } }); } public void OnUnityStarted() { Log.i(TAG,"OnUnityStarted called."); handler.postDelayed(new Runnable() { @Override public void run() { try { mUnityPlayer.requestFocus(); loaderRl.setVisibility(View.GONE); //USER TOKEN SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(ctx); String token = preferences.getString("HandTalkSDKToken", ""); if(!token.isEmpty()) { setUserID(token); Log.i(TAG, "OnUnityStarted()"); if (!textToTranslate.isEmpty()) { playHugo(textToTranslate); } else { Log.e(TAG, "The 'textToTranslate' variable is empty!"); } }else{ Log.e(TAG, "The 'user token' is necessary. Visit http://www.handtalk.me e create your account."); } } catch (Exception e) { Log.e(TAG, "OnUnityStarted() ERROR: " + e.getMessage()); } } }, 300); } }
mit
GeovisionGroup/tvb.a
types/rn-viewpager/index.d.ts
383
declare module 'rn-viewpager' { import React, { Component } from 'react' class PagerTabIndicator extends Component<any> { } class IndicatorViewPager extends Component<any> { setPage(pageNumber: number): void } class PagerTitleIndicator extends Component<any> { } class PagerDotIndicator extends Component<any> { } class PageControl extends Component<any> { } }
mit
jayli/kissy
tools/module-compiler/src/com/google/protobuf/ExtensionRegistry.java
10427
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // http://code.google.com/p/protobuf/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package com.google.protobuf; import com.google.protobuf.Descriptors.Descriptor; import com.google.protobuf.Descriptors.FieldDescriptor; import java.util.Collections; import java.util.HashMap; import java.util.Map; /** * A table of known extensions, searchable by name or field number. When * parsing a protocol message that might have extensions, you must provide * an {@code ExtensionRegistry} in which you have registered any extensions * that you want to be able to parse. Otherwise, those extensions will just * be treated like unknown fields. * * <p>For example, if you had the {@code .proto} file: * * <pre> * option java_class = "MyProto"; * * message Foo { * extensions 1000 to max; * } * * extend Foo { * optional int32 bar; * } * </pre> * * Then you might write code like: * * <pre> * ExtensionRegistry registry = ExtensionRegistry.newInstance(); * registry.add(MyProto.bar); * MyProto.Foo message = MyProto.Foo.parseFrom(input, registry); * </pre> * * <p>Background: * * <p>You might wonder why this is necessary. Two alternatives might come to * mind. First, you might imagine a system where generated extensions are * automatically registered when their containing classes are genned. This * is a popular technique, but is bad design; among other things, it creates a * situation where behavior can change depending on what classes happen to be * genned. It also introduces a security vulnerability, because an * unprivileged class could cause its code to be called unexpectedly from a * privileged class by registering itself as an extension of the right type. * * <p>Another option you might consider is lazy parsing: do not parse an * extension until it is first requested, at which point the caller must * provide a type to use. This introduces a different set of problems. First, * it would require a mutex lock any time an extension was accessed, which * would be slow. Second, corrupt data would not be detected until first * access, at which point it would be much harder to deal with it. Third, it * could violate the expectation that message objects are immutable, since the * type provided could be any arbitrary message class. An unprivileged user * could take advantage of this to inject a mutable object into a message * belonging to privileged code and create mischief. * * @author kenton@google.com Kenton Varda */ public final class ExtensionRegistry extends ExtensionRegistryLite { /** Construct a new, empty instance. */ public static ExtensionRegistry newInstance() { return new ExtensionRegistry(); } /** Get the unmodifiable singleton empty instance. */ public static ExtensionRegistry getEmptyRegistry() { return EMPTY; } /** Returns an unmodifiable view of the registry. */ @Override public ExtensionRegistry getUnmodifiable() { return new ExtensionRegistry(this); } /** A (Descriptor, Message) pair, returned by lookup methods. */ public static final class ExtensionInfo { /** The extension's descriptor. */ public final FieldDescriptor descriptor; /** * A default instance of the extension's type, if it has a message type. * Otherwise, {@code null}. */ public final Message defaultInstance; private ExtensionInfo(final FieldDescriptor descriptor) { this.descriptor = descriptor; defaultInstance = null; } private ExtensionInfo(final FieldDescriptor descriptor, final Message defaultInstance) { this.descriptor = descriptor; this.defaultInstance = defaultInstance; } } /** * Find an extension by fully-qualified field name, in the proto namespace. * I.e. {@code result.descriptor.fullName()} will match {@code fullName} if * a match is found. * * @return Information about the extension if found, or {@code null} * otherwise. */ public ExtensionInfo findExtensionByName(final String fullName) { return extensionsByName.get(fullName); } /** * Find an extension by containing type and field number. * * @return Information about the extension if found, or {@code null} * otherwise. */ public ExtensionInfo findExtensionByNumber(final Descriptor containingType, final int fieldNumber) { return extensionsByNumber.get( new DescriptorIntPair(containingType, fieldNumber)); } /** Add an extension from a generated file to the registry. */ public void add(final GeneratedMessage.GeneratedExtension<?, ?> extension) { if (extension.getDescriptor().getJavaType() == FieldDescriptor.JavaType.MESSAGE) { if (extension.getMessageDefaultInstance() == null) { throw new IllegalStateException( "Registered message-type extension had null default instance: " + extension.getDescriptor().getFullName()); } add(new ExtensionInfo(extension.getDescriptor(), extension.getMessageDefaultInstance())); } else { add(new ExtensionInfo(extension.getDescriptor(), null)); } } /** Add a non-message-type extension to the registry by descriptor. */ public void add(final FieldDescriptor type) { if (type.getJavaType() == FieldDescriptor.JavaType.MESSAGE) { throw new IllegalArgumentException( "ExtensionRegistry.add() must be provided a default instance when " + "adding an embedded message extension."); } add(new ExtensionInfo(type, null)); } /** Add a message-type extension to the registry by descriptor. */ public void add(final FieldDescriptor type, final Message defaultInstance) { if (type.getJavaType() != FieldDescriptor.JavaType.MESSAGE) { throw new IllegalArgumentException( "ExtensionRegistry.add() provided a default instance for a " + "non-message extension."); } add(new ExtensionInfo(type, defaultInstance)); } // ================================================================= // Private stuff. private ExtensionRegistry() { this.extensionsByName = new HashMap<String, ExtensionInfo>(); this.extensionsByNumber = new HashMap<DescriptorIntPair, ExtensionInfo>(); } private ExtensionRegistry(ExtensionRegistry other) { callSuper(other); this.extensionsByName = Collections.unmodifiableMap(other.extensionsByName); this.extensionsByNumber = Collections.unmodifiableMap(other.extensionsByNumber); } private final Map<String, ExtensionInfo> extensionsByName; private final Map<DescriptorIntPair, ExtensionInfo> extensionsByNumber; private ExtensionRegistry(boolean empty) { callSuper(ExtensionRegistryLite.getEmptyRegistry()); this.extensionsByName = Collections.<String, ExtensionInfo>emptyMap(); this.extensionsByNumber = Collections.<DescriptorIntPair, ExtensionInfo>emptyMap(); } private static final ExtensionRegistry EMPTY = new ExtensionRegistry(true); private void add(final ExtensionInfo extension) { if (!extension.descriptor.isExtension()) { throw new IllegalArgumentException( "ExtensionRegistry.add() was given a FieldDescriptor for a regular " + "(non-extension) field."); } extensionsByName.put(extension.descriptor.getFullName(), extension); extensionsByNumber.put( new DescriptorIntPair(extension.descriptor.getContainingType(), extension.descriptor.getNumber()), extension); final FieldDescriptor field = extension.descriptor; if (field.getContainingType().getOptions().getMessageSetWireFormat() && field.getType() == FieldDescriptor.Type.MESSAGE && field.isOptional() && field.getExtensionScope() == field.getMessageType()) { // This is an extension of a MessageSet type defined within the extension // type's own scope. For backwards-compatibility, allow it to be looked // up by type name. extensionsByName.put(field.getMessageType().getFullName(), extension); } } /** A (GenericDescriptor, int) pair, used as a map key. */ private static final class DescriptorIntPair { private final Descriptor descriptor; private final int number; DescriptorIntPair(final Descriptor descriptor, final int number) { this.descriptor = descriptor; this.number = number; } @Override public int hashCode() { return descriptor.hashCode() * ((1 << 16) - 1) + number; } @Override public boolean equals(final Object obj) { if (!(obj instanceof DescriptorIntPair)) { return false; } final DescriptorIntPair other = (DescriptorIntPair)obj; return descriptor == other.descriptor && number == other.number; } } }
mit
p-org/PSharp
Source/LanguageServices/Syntax/Blocks/BlockSyntax.cs
5928
// ------------------------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------------------------------------------ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.CodeAnalysis; using Microsoft.PSharp.LanguageServices.Parsing; namespace Microsoft.PSharp.LanguageServices.Syntax { /// <summary> /// Block syntax node. /// </summary> internal sealed class BlockSyntax : PSharpSyntaxNode { /// <summary> /// The machine parent node. /// </summary> internal readonly MachineDeclaration Machine; /// <summary> /// The state parent node. /// </summary> internal readonly StateDeclaration State; /// <summary> /// The statement block. /// </summary> internal SyntaxTree Block; /// <summary> /// The open brace token. /// </summary> internal Token OpenBraceToken; /// <summary> /// The close brace token. /// </summary> internal Token CloseBraceToken; /// <summary> /// Initializes a new instance of the <see cref="BlockSyntax"/> class. /// </summary> internal BlockSyntax(IPSharpProgram program, MachineDeclaration machineNode, StateDeclaration stateNode) : base(program) { this.Machine = machineNode; this.State = stateNode; } /// <summary> /// Rewrites the syntax node declaration to the intermediate C# /// representation. /// </summary> internal override void Rewrite(int indentLevel) { if (this.Configuration.IsRewritingForVsLanguageService) { // Do not change formatting. this.TextUnit = this.OpenBraceToken.TextUnit.WithText(this.Block.ToString()); return; } // Adjust the indent of lines in the block to match the surrounding indentation, according to // the line in the block with the minimum indentation. var lines = this.Block.ToString().Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None); var splitLines = this.SplitAndNormalizeLeadingWhitespace(lines).ToArray(); // Ignore the open and close braces as they are indented one level higher and the parsing leaves // the first one with no indent. 'indentLevel' is the level of the block's open/close braces. // This has to handle code being on the same line as the open and/or close brackets; this is // preserved, so in that case the result would also be on a single line (e.g. "{ }", as opposed // to an empty machine or state definition which would put the empty braces on separate lines). var skipFirst = splitLines.First().Item2.StartsWith("{") ? 1 : 0; var skipLast = splitLines.Last().Item2.StartsWith("}") ? 1 : 0; var midLines = splitLines.Skip(skipFirst).Take(splitLines.Length - skipFirst - skipLast).ToArray(); // If there are no lines between {} or they are all empty or whitespace, generate empty brackets. var minLeadingWsLen = (skipFirst + skipLast == splitLines.Length) ? 0 : midLines.Where(s => s.Item2.Length > 0).Select(s => s.Item1.Length).DefaultIfEmpty(0).Min(); // Adjust line indents to the proper level. var numIndentSpaces = ((indentLevel + 1) * SpacesPerIndent) - minLeadingWsLen; var indent = GetIndent(indentLevel); var sb = new StringBuilder(); if (skipFirst > 0) { sb.Append(indent).Append(splitLines.First().Item2); } if (midLines.Length > 0) { sb.Append("\n").Append(string.Join("\n", this.ComposeLines(numIndentSpaces, midLines))); } if (skipLast > 0) { sb.Append("\n").Append(indent).Append(splitLines.Last().Item2); } this.TextUnit = this.OpenBraceToken.TextUnit.WithText(sb.ToString()); } private IEnumerable<Tuple<string, string>> SplitAndNormalizeLeadingWhitespace(IEnumerable<string> lines) { foreach (var line in lines) { // All-blank lines may have a misleadingly small number of spaces (if not 0) if (string.IsNullOrWhiteSpace(line)) { yield return Tuple.Create(string.Empty, string.Empty); } else { // Normalize leading whitespace to spaces instead of tabs. This won't be perfect if there is an uneven mix of the two. var leadingWsLen = line.TakeWhile(char.IsWhiteSpace).Count(); yield return Tuple.Create(line.Substring(0, leadingWsLen).Replace("\t", OneIndent), line.Substring(leadingWsLen).Trim()); } } } private IEnumerable<string> ComposeLines(int numIndentSpaces, IEnumerable<Tuple<string, string>> splitLines) { Func<string, string> adjustIndent; if (numIndentSpaces < 0) { adjustIndent = ws => ws.Substring(-numIndentSpaces); } else { var indent = new string(' ', numIndentSpaces); adjustIndent = ws => indent + ws; } return splitLines.Select(line => line.Item2.Length == 0 ? string.Empty : adjustIndent(line.Item1) + line.Item2); } } }
mit
schneidmaster/debatevid.io
app/assets/components/store/records/tournament.js
243
import { Record } from "immutable"; const defaultTournament = { id: null, name: null, year: null }; export default class Tournament extends Record(defaultTournament) { getYearAndName() { return `${this.year} ${this.name}`; } }
mit
digitalheir/dutch-case-law-to-couchdb
src/deprecated-ruby-importer/deprecated/update_couchdb_bulk.rb
1161
# require 'nokogiri' # require 'json' # require 'erb' # require 'logger' # require 'tilt' # require 'open-uri' # require 'base64' # require_relative 'couch/couch' # require_relative 'rechtspraak-nl/rechtspraak_utils' # include RechtspraakUtils # # # Deprecated for being inefficient on memory # # def update_couchdb # today = Date.today.strftime('%Y-%m-%d') # doc_last_updated = Couch::CLOUDANT_CONNECTION.get_doc('informal_schema', 'general') # # # Resolve new docs and update database # current_revs = get_current_revs # puts "found #{current_revs.length} documents in db" # # new_docs = get_new_docs(doc_last_updated['date_last_updated']) # #todo REMOVE # new_docs # new_docs.select! { |ecli| current_revs[ecli].nil? } # #TODO remove # puts "#{new_docs.length} new docs" # # update_docs(new_docs, current_revs) # # # Update the document that tracks our last update date # doc_last_updated['date_last_updated'] = today # Couch::CLOUDANT_CONNECTION.put('/informal_schema/general', doc_last_updated.to_json) # end # # # Script starts here # # RES_MAX=1000 # LOGGER = Logger.new('update_couchdb.log') # update_couchdb # LOGGER.close
mit
yilliot/souls
app/Services/ServicesGenerator.php
2284
<?php namespace App\Services; use App\Models\Service; use App\Models\User; use Carbon\Carbon; class ServicesGenerator { public function scheduler(Carbon $from, $months = 3) { $last_at = $from->copy(); $last = Service::where('created_by', 0) ->orderBy('at', 'desc') ->first(); if ($last) $last_at = $last->at; $till = $from->copy()->addMonths($months); while ($till->gt($from)) { // SATURDAY SERVICE if ($last_at->lt($from) && $this->is_right_day_for_service($from)) { $service_timing = $this->make_service_timing($from); $this->service_maker($service_timing); } // SUPREME SERVICE if ($last_at->lt($from) && $this->is_right_day_for_supreme($from)) { $service_timing = $this->make_supreme_timing($from); $this->supreme_maker($service_timing); } $from->addDay(); } } protected function make_service_timing(Carbon $dt) { $dt->hour = 17; $dt->minute = 0; $dt->second = 0; return $dt; } protected function make_supreme_timing(Carbon $dt) { $dt->hour = 19; $dt->minute = 0; $dt->second = 0; return $dt; } protected function is_right_day_for_service(Carbon $dt) { return $dt->dayOfWeek === Carbon::SATURDAY; } protected function is_right_day_for_supreme(Carbon $dt) { return $dt->dayOfWeek === Carbon::FRIDAY; } public function service_maker($dt) { $service = new Service(); $service->at = $dt; $service->type_id = 1; $service->venue_id = 1; $service->speaker_id = 1; $service->forecast_size = 0; $service->attendance_size = 0; $service->created_by = 0; $service->save(); } public function supreme_maker($dt) { $service = new Service(); $service->at = $dt; $service->type_id = 2; $service->venue_id = 1; $service->speaker_id = 1; $service->forecast_size = 0; $service->attendance_size = 0; $service->created_by = 0; $service->save(); } }
mit
chengluyu/sheet
src/ast/AstNodePrinter.java
1828
package ast; public class AstNodePrinter { public AstNodePrinter(boolean useTab, int tabSize) { tabStr_ = useTab ? "\t" : AstNodePrinter.repeat(" ", tabSize); currentLevel_ = 0; indent_ = ""; text_ = new StringBuilder(); } private final String tabStr_; private int currentLevel_; private String indent_; private StringBuilder text_; private void increaseIndent() { currentLevel_++; indent_ = AstNodePrinter.repeat(tabStr_, currentLevel_); } private void decreaseIndent() { currentLevel_--; indent_ = AstNodePrinter.repeat(tabStr_, currentLevel_); } private void printIndent() { text_.append(indent_); } private void nextLine() { text_.append('\n'); } private void print(char c) { text_.append(c); } private void print(String str) { text_.append(str); } public void subBlock(String title) { printIndent(); increaseIndent(); print(title); print(' '); print('{'); nextLine(); } public void beginBlock(String title) { increaseIndent(); print(title); print(' '); print('{'); nextLine(); } public void beginBlock() { increaseIndent(); print('{'); nextLine(); } public void text(String name) { print(name); print(' '); nextLine(); } public void property(String property, String value) { printIndent(); print(property); print(" := "); print(value); nextLine(); } public void child(String property, AstNode child) { printIndent(); print(property); print(" := "); child.inspect(this); } public void endBlock() { decreaseIndent(); printIndent(); print('}'); nextLine(); } public String result() { return text_.toString(); } private static String repeat(String str, int n) { StringBuilder sb = new StringBuilder(); while (n-- > 0) sb.append(str); return sb.toString(); } }
mit
squidfunk/mkdocs-material
src/assets/javascripts/browser/element/focus/index.ts
2522
/* * Copyright (c) 2016-2022 Martin Donath <martin.donath@squidfunk.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ import { Observable, debounceTime, distinctUntilChanged, fromEvent, map, merge, startWith } from "rxjs" import { getActiveElement } from "../_" /* ---------------------------------------------------------------------------- * Functions * ------------------------------------------------------------------------- */ /** * Watch element focus * * Previously, this function used `focus` and `blur` events to determine whether * an element is focused, but this doesn't work if there are focusable elements * within the elements itself. A better solutions are `focusin` and `focusout` * events, which bubble up the tree and allow for more fine-grained control. * * `debounceTime` is necessary, because when a focus change happens inside an * element, the observable would first emit `false` and then `true` again. * * @param el - Element * * @returns Element focus observable */ export function watchElementFocus( el: HTMLElement ): Observable<boolean> { return merge( fromEvent(document.body, "focusin"), fromEvent(document.body, "focusout") ) .pipe( debounceTime(1), map(() => { const active = getActiveElement() return typeof active !== "undefined" ? el.contains(active) : false }), startWith(el === getActiveElement()), distinctUntilChanged() ) }
mit
andrewreedy/meteor-organizations
src/models/User.js
1698
/** * User * * @requires Users Collection * * @class User */ class User { /** * @constructor * * @param {String} data Model data * @param {User} app App * @param {Array} components Model Components */ constructor (data, org, app, components) { this._data = data; this._org = org; this._app = app; this._components = components || {}; // Apply Components this._applyComponents() } /** * Update the property of the Model * * @method updateProperty * @memberOf OrgModel * @param {String} field Field * @param {?} value Value * @param {String} operator MongoDB Operator */ updateProperty (field, value, operator) { Meteor.call('organizations.organization.user.update', this._data._id, this._org.getProperty('_id'), field, value, operator, function (error, result) { }); } /** * Get a property of the Model * * @method getProperty * @memberOf OrgModel * @param {String} field Get property from the Model */ getProperty (field) { let data = _.find(this._data['organizations'], (organization) => { return organization._id == this._org.getProperty('_id'); }); return data[field]; } /** * Applies the components to the Model instance * * @method _applyComponents * @private * @memberOf Model */ _applyComponents () { for (let key of Object.keys(this._components)) { this[key] = new this._components[key](this, this._app); } } } Organizations.models.User = User;
mit
OpenSiteMobile/mobilesiteos
apps/bootstrap2/controllers/dropdown.js
892
msos.provide("apps.bootstrap2.controllers.dropdown"); apps.bootstrap2.controllers.dropdown.version = new msos.set_version(14, 8, 6); angular.module( 'apps.bootstrap2.controllers.dropdown', ['ng.bootstrap.ui.dropdown'] ).controller( 'apps.bootstrap2.controllers.dropdown.ctrl', [ '$scope',function ($scope) { "use strict"; $scope.items = ['The first choice!', 'And another choice for you.', 'but wait! A third!']; $scope.status = { isopen: false }; $scope.toggled = function (open) { console.log('Dropdown is now: ', open); }; $scope.toggleDropdown = function ($event) { $event.preventDefault(); $event.stopPropagation(); $scope.status.isopen = !$scope.status.isopen; }; } ] );
mit
rfceron/mongo-monitor-webapp-boot
src/main/java/com/mongodash/dao/mapper/BackupDBObjectMapper.java
2719
package com.mongodash.dao.mapper; import java.util.ArrayList; import java.util.List; import org.springframework.stereotype.Component; import com.mongodash.Config; import com.mongodash.dao.DBObjectMapper; import com.mongodash.model.Backup; import com.mongodb.BasicDBList; import com.mongodb.BasicDBObject; import com.mongodb.DBObject; @Component public class BackupDBObjectMapper implements DBObjectMapper<Backup> { @Override public Backup mapDBObject(BasicDBObject object) { Backup backup = new Backup(); backup.setId(object.getInt(Config.COMMON_FIELDS._id.name())); backup.setName(object.getString(Config.COMMON_FIELDS.name.name())); backup.setServerId(object.getInt(Backup.fields.serverId.name())); backup.setDumpFormat(object.getString(Backup.fields.dumpFormat.name())); backup.setCompressFolder(object.getBoolean(Backup.fields.compressFolder.name())); backup.setRunDaily(object.getBoolean(Backup.fields.runDaily.name())); backup.setIncludeOpLog(object.getBoolean(Backup.fields.includeOpLog.name())); backup.setNotifyOnFinish(object.getBoolean(Backup.fields.notifyOnFinish.name())); backup.setOutputFolder(object.getString(Backup.fields.outputFolder.name())); backup.setLastExecution(object.getDate(Backup.fields.lastExecution.name())); if (object.containsField(Backup.fields.databases.name())) { BasicDBList list = (BasicDBList) object.get(Backup.fields.databases.name()); List<String> databases = new ArrayList<String>(); for (int i = 0; i < list.size(); i++) { databases.add((String) list.get(i)); } backup.setDatabases(databases); } return backup; } @Override public DBObject mapObject(Backup backup) { DBObject object = new BasicDBObject(); object.put(Config.COMMON_FIELDS._id.name(), backup.getId()); object.put(Config.COMMON_FIELDS.name.name(), backup.getName()); object.put(Backup.fields.serverId.name(), backup.getServerId()); object.put(Backup.fields.dumpFormat.name(), backup.getDumpFormat()); object.put(Backup.fields.compressFolder.name(), backup.isCompressFolder()); object.put(Backup.fields.runDaily.name(), backup.isRunDaily()); object.put(Backup.fields.includeOpLog.name(), backup.isIncludeOpLog()); object.put(Backup.fields.notifyOnFinish.name(), backup.isNotifyOnFinish()); object.put(Backup.fields.outputFolder.name(), backup.getOutputFolder()); object.put(Backup.fields.lastExecution.name(), backup.getLastExecution()); if (backup.getDatabases() != null && backup.getDatabases().size() > 0) { BasicDBList databases = new BasicDBList(); for (String database : backup.getDatabases()) { databases.add(database); } object.put(Backup.fields.databases.name(), databases); } return object; } }
mit
williamcspace/vscode
src/vs/workbench/parts/debug/electron-browser/debugHover.ts
10098
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import lifecycle = require('vs/base/common/lifecycle'); import { TPromise } from 'vs/base/common/winjs.base'; import errors = require('vs/base/common/errors'); import { CommonKeybindings } from 'vs/base/common/keyCodes'; import dom = require('vs/base/browser/dom'); import * as nls from 'vs/nls'; import { ITree } from 'vs/base/parts/tree/browser/tree'; import { Tree } from 'vs/base/parts/tree/browser/treeImpl'; import { DefaultController, ICancelableEvent } from 'vs/base/parts/tree/browser/treeDefaults'; import { IConfigurationChangedEvent } from 'vs/editor/common/editorCommon'; import editorbrowser = require('vs/editor/browser/editorBrowser'); import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import debug = require('vs/workbench/parts/debug/common/debug'); import {evaluateExpression, Expression} from 'vs/workbench/parts/debug/common/debugModel'; import viewer = require('vs/workbench/parts/debug/electron-browser/debugViewer'); import {IKeyboardEvent} from 'vs/base/browser/keyboardEvent'; import {Position} from 'vs/editor/common/core/position'; import {Range} from 'vs/editor/common/core/range'; const $ = dom.emmet; const debugTreeOptions = { indentPixels: 6, twistiePixels: 15, ariaLabel: nls.localize('treeAriaLabel', "Debug Hover") }; const MAX_ELEMENTS_SHOWN = 18; const MAX_VALUE_RENDER_LENGTH_IN_HOVER = 4096; export class DebugHoverWidget implements editorbrowser.IContentWidget { public static ID = 'debug.hoverWidget'; // editor.IContentWidget.allowEditorOverflow public allowEditorOverflow = true; private domNode: HTMLElement; public isVisible: boolean; private tree: ITree; private showAtPosition: Position; private highlightDecorations: string[]; private complexValueContainer: HTMLElement; private treeContainer: HTMLElement; private complexValueTitle: HTMLElement; private valueContainer: HTMLElement; private stoleFocus: boolean; private toDispose: lifecycle.IDisposable[]; constructor(private editor: editorbrowser.ICodeEditor, private debugService: debug.IDebugService, private instantiationService: IInstantiationService) { this.domNode = $('.debug-hover-widget monaco-editor-background'); this.complexValueContainer = dom.append(this.domNode, $('.complex-value')); this.complexValueTitle = dom.append(this.complexValueContainer, $('.title')); this.treeContainer = dom.append(this.complexValueContainer, $('.debug-hover-tree')); this.treeContainer.setAttribute('role', 'tree'); this.tree = new Tree(this.treeContainer, { dataSource: new viewer.VariablesDataSource(this.debugService), renderer: this.instantiationService.createInstance(VariablesHoverRenderer), controller: new DebugHoverController(editor) }, debugTreeOptions); this.toDispose = []; this.registerListeners(); this.valueContainer = dom.append(this.domNode, $('.value')); this.valueContainer.tabIndex = 0; this.valueContainer.setAttribute('role', 'tooltip'); this.isVisible = false; this.showAtPosition = null; this.highlightDecorations = []; this.editor.addContentWidget(this); this.editor.applyFontInfo(this.domNode); } private registerListeners(): void { this.toDispose.push(this.tree.addListener2('item:expanded', () => { this.layoutTree(); })); this.toDispose.push(this.tree.addListener2('item:collapsed', () => { this.layoutTree(); })); this.toDispose.push(dom.addStandardDisposableListener(this.domNode, 'keydown', (e: IKeyboardEvent) => { if (e.equals(CommonKeybindings.ESCAPE)) { this.hide(); } })); this.toDispose.push(this.editor.onDidChangeConfiguration((e: IConfigurationChangedEvent) => { if (e.fontInfo) { this.editor.applyFontInfo(this.domNode); } })); } public getId(): string { return DebugHoverWidget.ID; } public getDomNode(): HTMLElement { return this.domNode; } public showAt(range: Range, hoveringOver: string, focus: boolean): TPromise<void> { const pos = range.getStartPosition(); const model = this.editor.getModel(); const focusedStackFrame = this.debugService.getViewModel().getFocusedStackFrame(); if (!hoveringOver || !focusedStackFrame || (focusedStackFrame.source.uri.toString() !== model.uri.toString())) { return; } // string magic to get the parents of the variable (a and b for a.b.foo) const lineContent = model.getLineContent(pos.lineNumber); const namesToFind = lineContent.substring(0, lineContent.indexOf('.' + hoveringOver)) .split('.').map(word => word.trim()).filter(word => !!word); namesToFind.push(hoveringOver); namesToFind[0] = namesToFind[0].substring(namesToFind[0].lastIndexOf(' ') + 1); return this.getExpression(namesToFind).then(expression => { if (!expression || !expression.available) { this.hide(); return; } // show it this.highlightDecorations = this.editor.deltaDecorations(this.highlightDecorations, [{ range: { startLineNumber: pos.lineNumber, endLineNumber: pos.lineNumber, startColumn: lineContent.indexOf(hoveringOver) + 1, endColumn: lineContent.indexOf(hoveringOver) + 1 + hoveringOver.length }, options: { className: 'hoverHighlight' } }]); return this.doShow(pos, expression, focus); }); } private getExpression(namesToFind: string[]): TPromise<Expression> { const session = this.debugService.getActiveSession(); const focusedStackFrame = this.debugService.getViewModel().getFocusedStackFrame(); if (session.configuration.capabilities.supportsEvaluateForHovers) { return evaluateExpression(session, focusedStackFrame, new Expression(namesToFind.join('.'), true), 'hover'); } const variables: debug.IExpression[] = []; return focusedStackFrame.getScopes(this.debugService).then(scopes => { // flatten out scopes lists return scopes.reduce((accum, scopes) => { return accum.concat(scopes); }, []) // no expensive scopes .filter((scope: debug.IScope) => !scope.expensive) // get the scopes variables .map((scope: debug.IScope) => scope.getChildren(this.debugService).done((children: debug.IExpression[]) => { // look for our variable in the list. First find the parents of the hovered variable if there are any. for (var i = 0; i < namesToFind.length && children; i++) { // some languages pass the type as part of the name, so need to check if the last word of the name matches. const filtered = children.filter(v => typeof v.name === 'string' && (namesToFind[i] === v.name || namesToFind[i] === v.name.substr(v.name.lastIndexOf(' ') + 1))); if (filtered.length !== 1) { break; } if (i === namesToFind.length - 1) { variables.push(filtered[0]); } else { filtered[0].getChildren(this.debugService).done(c => children = c, children = null); } } }, errors.onUnexpectedError)); // only show if there are no duplicates across scopes }).then(() => variables.length === 1 ? TPromise.as(variables[0]) : TPromise.as(null)); } private doShow(position: Position, expression: debug.IExpression, focus: boolean, forceValueHover = false): TPromise<void> { this.showAtPosition = position; this.isVisible = true; this.stoleFocus = focus; if (expression.reference === 0 || forceValueHover) { this.complexValueContainer.hidden = true; this.valueContainer.hidden = false; viewer.renderExpressionValue(expression, this.valueContainer, false, MAX_VALUE_RENDER_LENGTH_IN_HOVER); this.valueContainer.title = ''; this.editor.layoutContentWidget(this); if (focus) { this.editor.render(); this.valueContainer.focus(); } return TPromise.as(null); } this.valueContainer.hidden = true; this.complexValueContainer.hidden = false; return this.tree.setInput(expression).then(() => { this.complexValueTitle.textContent = expression.value; this.complexValueTitle.title = expression.value; this.layoutTree(); this.editor.layoutContentWidget(this); if (focus) { this.editor.render(); this.tree.DOMFocus(); } }); } private layoutTree(): void { const navigator = this.tree.getNavigator(); let visibleElementsCount = 0; while (navigator.next()) { visibleElementsCount++; } if (visibleElementsCount === 0) { this.doShow(this.showAtPosition, this.tree.getInput(), false, true); } else { const height = Math.min(visibleElementsCount, MAX_ELEMENTS_SHOWN) * 18; if (this.treeContainer.clientHeight !== height) { this.treeContainer.style.height = `${ height }px`; this.tree.layout(); } } } public hide(): void { if (!this.isVisible) { return; } this.isVisible = false; this.editor.deltaDecorations(this.highlightDecorations, []); this.highlightDecorations = []; this.editor.layoutContentWidget(this); if (this.stoleFocus) { this.editor.focus(); } } public getPosition(): editorbrowser.IContentWidgetPosition { return this.isVisible ? { position: this.showAtPosition, preference: [ editorbrowser.ContentWidgetPositionPreference.ABOVE, editorbrowser.ContentWidgetPositionPreference.BELOW ] } : null; } public dispose(): void { this.toDispose = lifecycle.dispose(this.toDispose); } } class DebugHoverController extends DefaultController { constructor(private editor: editorbrowser.ICodeEditor) { super(); } /* protected */ public onLeftClick(tree: ITree, element: any, eventish: ICancelableEvent, origin: string = 'mouse'): boolean { if (element.reference > 0) { super.onLeftClick(tree, element, eventish, origin); tree.clearFocus(); tree.deselect(element); this.editor.focus(); } return true; } } class VariablesHoverRenderer extends viewer.VariablesRenderer { public getHeight(tree: ITree, element: any): number { return 18; } }
mit
segwit/atbcoin-insight
src/rpc/server.cpp
14709
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2015 The The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "rpc/server.h" #include "base58.h" #include "init.h" #include "random.h" #include "sync.h" #include "ui_interface.h" #include "util.h" #include "utilstrencodings.h" #include <univalue.h> #include <boost/bind.hpp> #include <boost/filesystem.hpp> #include <boost/foreach.hpp> #include <boost/iostreams/concepts.hpp> #include <boost/iostreams/stream.hpp> #include <boost/shared_ptr.hpp> #include <boost/signals2/signal.hpp> #include <boost/thread.hpp> #include <boost/algorithm/string/case_conv.hpp> // for to_upper() using namespace RPCServer; using namespace std; static bool fRPCRunning = false; static bool fRPCInWarmup = true; static std::string rpcWarmupStatus("RPC server started"); static CCriticalSection cs_rpcWarmup; /* Timer-creating functions */ static RPCTimerInterface* timerInterface = NULL; /* Map of name to timer. * @note Can be changed to std::unique_ptr when C++11 */ static std::map<std::string, boost::shared_ptr<RPCTimerBase> > deadlineTimers; static struct CRPCSignals { boost::signals2::signal<void ()> Started; boost::signals2::signal<void ()> Stopped; boost::signals2::signal<void (const CRPCCommand&)> PreCommand; boost::signals2::signal<void (const CRPCCommand&)> PostCommand; } g_rpcSignals; void RPCServer::OnStarted(boost::function<void ()> slot) { g_rpcSignals.Started.connect(slot); } void RPCServer::OnStopped(boost::function<void ()> slot) { g_rpcSignals.Stopped.connect(slot); } void RPCServer::OnPreCommand(boost::function<void (const CRPCCommand&)> slot) { g_rpcSignals.PreCommand.connect(boost::bind(slot, _1)); } void RPCServer::OnPostCommand(boost::function<void (const CRPCCommand&)> slot) { g_rpcSignals.PostCommand.connect(boost::bind(slot, _1)); } void RPCTypeCheck(const UniValue& params, const list<UniValue::VType>& typesExpected, bool fAllowNull) { unsigned int i = 0; BOOST_FOREACH(UniValue::VType t, typesExpected) { if (params.size() <= i) break; const UniValue& v = params[i]; if (!((v.type() == t) || (fAllowNull && (v.isNull())))) { string err = strprintf("Expected type %s, got %s", uvTypeName(t), uvTypeName(v.type())); throw JSONRPCError(RPC_TYPE_ERROR, err); } i++; } } void RPCTypeCheckObj(const UniValue& o, const map<string, UniValueType>& typesExpected, bool fAllowNull, bool fStrict) { for (const auto& t : typesExpected) { const UniValue& v = find_value(o, t.first); if (!fAllowNull && v.isNull()) throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Missing %s", t.first)); if (!(t.second.typeAny || v.type() == t.second.type || (fAllowNull && v.isNull()))) { string err = strprintf("Expected type %s for %s, got %s", uvTypeName(t.second.type), t.first, uvTypeName(v.type())); throw JSONRPCError(RPC_TYPE_ERROR, err); } } if (fStrict) { BOOST_FOREACH(const string& k, o.getKeys()) { if (typesExpected.count(k) == 0) { string err = strprintf("Unexpected key %s", k); throw JSONRPCError(RPC_TYPE_ERROR, err); } } } } CAmount AmountFromValue(const UniValue& value) { if (!value.isNum() && !value.isStr()) throw JSONRPCError(RPC_TYPE_ERROR, "Amount is not a number or string"); CAmount amount; if (!ParseFixedPoint(value.getValStr(), 8, &amount)) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount"); if (!MoneyRange(amount)) throw JSONRPCError(RPC_TYPE_ERROR, "Amount out of range"); return amount; } UniValue ValueFromAmount(const CAmount& amount) { bool sign = amount < 0; int64_t n_abs = (sign ? -amount : amount); int64_t quotient = n_abs / COIN; int64_t remainder = n_abs % COIN; return UniValue(UniValue::VNUM, strprintf("%s%d.%08d", sign ? "-" : "", quotient, remainder)); } uint256 ParseHashV(const UniValue& v, string strName) { string strHex; if (v.isStr()) 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 UniValue& o, string strKey) { return ParseHashV(find_value(o, strKey), strKey); } vector<unsigned char> ParseHexV(const UniValue& v, string strName) { string strHex; if (v.isStr()) 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 UniValue& o, string strKey) { return ParseHexV(find_value(o, strKey), strKey); } /** * Note: This interface may still be subject to change. */ std::string CRPCTable::help(const std::string& strCommand) const { string strRet; string category; set<rpcfn_type> setDone; vector<pair<string, const CRPCCommand*> > vCommands; for (map<string, const CRPCCommand*>::const_iterator mi = mapCommands.begin(); mi != mapCommands.end(); ++mi) vCommands.push_back(make_pair(mi->second->category + mi->first, mi->second)); sort(vCommands.begin(), vCommands.end()); BOOST_FOREACH(const PAIRTYPE(string, const CRPCCommand*)& command, vCommands) { const CRPCCommand *pcmd = command.second; string strMethod = pcmd->name; // We already filter duplicates, but these deprecated screw up the sort order if (strMethod.find("label") != string::npos) continue; if ((strCommand != "" || pcmd->category == "hidden") && strMethod != strCommand) continue; try { UniValue params; rpcfn_type pfn = pcmd->actor; if (setDone.insert(pfn).second) (*pfn)(params, true); } catch (const 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')); if (category != pcmd->category) { if (!category.empty()) strRet += "\n"; category = pcmd->category; string firstLetter = category.substr(0,1); boost::to_upper(firstLetter); strRet += "== " + firstLetter + category.substr(1) + " ==\n"; } } strRet += strHelp + "\n"; } } if (strRet == "") strRet = strprintf("help: unknown command: %s\n", strCommand); strRet = strRet.substr(0,strRet.size()-1); return strRet; } UniValue help(const UniValue& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "help ( \"command\" )\n" "\nList all commands, or get help for a specified command.\n" "\nArguments:\n" "1. \"command\" (string, optional) The command to get help on\n" "\nResult:\n" "\"text\" (string) The help text\n" ); string strCommand; if (params.size() > 0) strCommand = params[0].get_str(); return tableRPC.help(strCommand); } UniValue stop(const UniValue& params, bool fHelp) { // Accept the deprecated and ignored 'detach' boolean argument if (fHelp || params.size() > 1) throw runtime_error( "stop\n" "\nStop ATBCoin server."); // Event loop will exit after current HTTP requests have been handled, so // this reply will get back to the client. StartShutdown(); return "ATBCoin server stopping"; } /** * Call Table */ static const CRPCCommand vRPCCommands[] = { // category name actor (function) okSafeMode // --------------------- ------------------------ ----------------------- ---------- /* Overall control/query calls */ { "control", "help", &help, true }, { "control", "stop", &stop, true }, }; 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[](const std::string &name) const { map<string, const CRPCCommand*>::const_iterator it = mapCommands.find(name); if (it == mapCommands.end()) return NULL; return (*it).second; } bool CRPCTable::appendCommand(const std::string& name, const CRPCCommand* pcmd) { if (IsRPCRunning()) return false; // don't allow overwriting for now map<string, const CRPCCommand*>::const_iterator it = mapCommands.find(name); if (it != mapCommands.end()) return false; mapCommands[name] = pcmd; return true; } bool StartRPC() { LogPrint("rpc", "Starting RPC\n"); fRPCRunning = true; g_rpcSignals.Started(); return true; } void InterruptRPC() { LogPrint("rpc", "Interrupting RPC\n"); // Interrupt e.g. running longpolls fRPCRunning = false; } void StopRPC() { LogPrint("rpc", "Stopping RPC\n"); deadlineTimers.clear(); g_rpcSignals.Stopped(); } bool IsRPCRunning() { return fRPCRunning; } void SetRPCWarmupStatus(const std::string& newStatus) { LOCK(cs_rpcWarmup); rpcWarmupStatus = newStatus; } void SetRPCWarmupFinished() { LOCK(cs_rpcWarmup); assert(fRPCInWarmup); fRPCInWarmup = false; } bool RPCIsInWarmup(std::string *outStatus) { LOCK(cs_rpcWarmup); if (outStatus) *outStatus = rpcWarmupStatus; return fRPCInWarmup; } void JSONRequest::parse(const UniValue& valRequest) { // Parse request if (!valRequest.isObject()) throw JSONRPCError(RPC_INVALID_REQUEST, "Invalid Request object"); const UniValue& request = valRequest.get_obj(); // Parse id now so errors from here on will have the id id = find_value(request, "id"); // Parse method UniValue valMethod = find_value(request, "method"); if (valMethod.isNull()) throw JSONRPCError(RPC_INVALID_REQUEST, "Missing method"); if (!valMethod.isStr()) throw JSONRPCError(RPC_INVALID_REQUEST, "Method must be a string"); strMethod = valMethod.get_str(); if (strMethod != "getblocktemplate") LogPrint("rpc", "ThreadRPCServer method=%s\n", SanitizeString(strMethod)); // Parse params UniValue valParams = find_value(request, "params"); if (valParams.isArray()) params = valParams.get_array(); else if (valParams.isNull()) params = UniValue(UniValue::VARR); else throw JSONRPCError(RPC_INVALID_REQUEST, "Params must be an array"); } static UniValue JSONRPCExecOne(const UniValue& req) { UniValue rpc_result(UniValue::VOBJ); JSONRequest jreq; try { jreq.parse(req); UniValue result = tableRPC.execute(jreq.strMethod, jreq.params); rpc_result = JSONRPCReplyObj(result, NullUniValue, jreq.id); } catch (const UniValue& objError) { rpc_result = JSONRPCReplyObj(NullUniValue, objError, jreq.id); } catch (const std::exception& e) { rpc_result = JSONRPCReplyObj(NullUniValue, JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id); } return rpc_result; } std::string JSONRPCExecBatch(const UniValue& vReq) { UniValue ret(UniValue::VARR); for (unsigned int reqIdx = 0; reqIdx < vReq.size(); reqIdx++) ret.push_back(JSONRPCExecOne(vReq[reqIdx])); return ret.write() + "\n"; } UniValue CRPCTable::execute(const std::string &strMethod, const UniValue &params) const { // Return immediately if in warmup { LOCK(cs_rpcWarmup); if (fRPCInWarmup) throw JSONRPCError(RPC_IN_WARMUP, rpcWarmupStatus); } // Find method const CRPCCommand *pcmd = tableRPC[strMethod]; if (!pcmd) throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found"); g_rpcSignals.PreCommand(*pcmd); try { // Execute return pcmd->actor(params, false); } catch (const std::exception& e) { throw JSONRPCError(RPC_MISC_ERROR, e.what()); } g_rpcSignals.PostCommand(*pcmd); } std::vector<std::string> CRPCTable::listCommands() const { std::vector<std::string> commandList; typedef std::map<std::string, const CRPCCommand*> commandMap; std::transform( mapCommands.begin(), mapCommands.end(), std::back_inserter(commandList), boost::bind(&commandMap::value_type::first,_1) ); return commandList; } std::string HelpExampleCli(const std::string& methodname, const std::string& args) { return "> atbcoin-cli " + methodname + " " + args + "\n"; } std::string HelpExampleRpc(const std::string& methodname, const std::string& args) { return "> curl --user myusername --data-binary '{\"jsonrpc\": \"1.0\", \"id\":\"curltest\", " "\"method\": \"" + methodname + "\", \"params\": [" + args + "] }' -H 'content-type: text/plain;' http://127.0.0.1:8332/\n"; } void RPCSetTimerInterfaceIfUnset(RPCTimerInterface *iface) { if (!timerInterface) timerInterface = iface; } void RPCSetTimerInterface(RPCTimerInterface *iface) { timerInterface = iface; } void RPCUnsetTimerInterface(RPCTimerInterface *iface) { if (timerInterface == iface) timerInterface = NULL; } void RPCRunLater(const std::string& name, boost::function<void(void)> func, int64_t nSeconds) { if (!timerInterface) throw JSONRPCError(RPC_INTERNAL_ERROR, "No timer handler registered for RPC"); deadlineTimers.erase(name); LogPrint("rpc", "queue run of timer %s in %i seconds (using %s)\n", name, nSeconds, timerInterface->Name()); deadlineTimers.insert(std::make_pair(name, boost::shared_ptr<RPCTimerBase>(timerInterface->NewTimer(func, nSeconds*1000)))); } CRPCTable tableRPC;
mit
squareitechnologies/ABCPdfHtmlToPdfAzure
ABCPdfHtmlToPdfAzure/Scripts/index.js
188
$(function () { $('#generateBtn').click(function () { var url = '/Home/CreateHtmlPdf?url=' + $('#url').val(); var win = window.open(url, '_blank'); win.focus(); }); });
mit
ianhalpern/python-payment-processor
payment_processor/methods/__init__.py
3799
from payment_processor.exceptions import * import datetime class GenericMethod: first_name = None last_name = None company = None card_code = None address = None address2 = None city = None state = None zip_code = None country = None phone = None fax = None email = None def __init__( self, first_name=None, last_name=None, company=None, card_code=None, address=None, address2=None, city=None, state=None, zip_code=None, country=None, phone=None, fax=None, email=None ): self.first_name = first_name self.last_name = last_name self.company = company self.card_code = card_code self.address = address self.address2 = address2 self.city = city self.state = state self.zip_code = zip_code self.country = country self.phone = phone self.fax = fax self.email = email class CreditCard( GenericMethod ): # Required card_number = None expiration_date = None # datetime.datetime or datetime.date # Optional card_code = None def __init__( self, card_number=None, expiration_date=None, card_code=None, **kwargs ): GenericMethod.__init__( self, **kwargs ) if not card_number or not expiration_date: raise TypeError( "Credit Card method requires both a 'card_number' and 'expiration_date' argument." ) if not isinstance( expiration_date, ( datetime.datetime, datetime.date ) ): raise ValueError( "Credit method require the 'expiration_date' argument to be of type 'datetime.datetime' or 'datetime.date'." ) self.card_number = card_number self.expiration_date = expiration_date self.card_code = card_code class Check( GenericMethod ): CHECKING = 'checking' SAVINGS = 'savings' PERSONAL = 'personal' BUSINESS = 'business' account_types = ( CHECKING, SAVINGS ) account_holder_types = ( PERSONAL, BUSINESS ) account_number = None routing_number = None account_type = None account_holder_type = None check_number = None def __init__( self, account_number=None, routing_number=None, account_type=CHECKING, account_holder_type=PERSONAL, check_number = None, check_checkdigit=True, **kwargs ): GenericMethod.__init__( self, **kwargs ) if not account_number or not routing_number: raise TypeError( "Check method requires both an 'account_number' and 'routing_number' argument." ) if not ( self.first_name and self.last_name ) and not self.company: raise TypeError( "Check method requires either 'first_name' and 'last_name' arguments or 'company' argument." ) if check_checkdigit and not self.validCheckdigit( routing_number ): raise ValueError( "Invalid routing_number: checkdigit is invalid." ) if account_type not in self.account_types: raise ValueError( "Invalid account_type: Either '%s' required but '%s' was provided." % ( self.account_types, account_type ) ) if account_holder_type not in self.account_holder_types: raise ValueError( "Invalid account_holder_type: Either '%s' required but '%s' was provided." % ( self.account_holder_types, account_holder_type ) ) self.account_number = account_number self.routing_number = routing_number self.account_type = account_type self.account_holder_type = account_holder_type @classmethod def validCheckdigit( cls, routing_number, routing_number_length=9 ): '''Validates the routing number's check digit''' routing_number = str( routing_number ).rjust( routing_number_length, '0' ) sum_digit = 0 for i in range( routing_number_length - 1 ): n = int( routing_number[i:i+1] ) sum_digit += n * (3,7,1)[i % 3] if sum_digit % 10 > 0: return 10 - ( sum_digit % 10 ) == int( routing_number[-1] ) else: return not int( routing_number[-1] )
mit
DXCanas/kolibri
kolibri/core/assets/src/api-resources/facility.js
99
import { Resource } from '../api-resource'; export default new Resource({ name: 'facility', });
mit
AlanaFarkas/Crossroads
spec/models/address_spec.rb
1976
require 'rails_helper' describe Address do let(:address){Address.create({address_1: "test", city: "test", state: "test", zip: "12345"})} let(:address_2){Address.new} let(:user){User.create({first_name: "test", last_name: "test", email: "test@test.com", phone_number: "1231231123", password: "Testing1"})} context "Validations" do describe "address_1" do it "is not valid when nil" do address_2.valid? expect(address_2.errors[:address_1]).to_not be_empty end it "is valid when not nil" do address.valid? expect(address.errors[:address_1]).to be_empty end end describe "city" do it "is not valid when nil" do address_2.valid? expect(address_2.errors[:city]).to_not be_empty end it "is valid when not nil" do address.valid? expect(address.errors[:city]).to be_empty end end describe "state" do it "is not valid when nil" do address_2.valid? expect(address_2.errors[:state]).to_not be_empty end it "is valid when not nil" do address.valid? expect(address.errors[:state]).to be_empty end end describe "zip" do it "is not valid when nil" do address_2.valid? expect(address_2.errors[:zip]).to_not be_empty end it "is valid when not nil" do address.valid? expect(address.errors[:zip]).to be_empty end end end context "Associations" do describe "user" do it "returns the user if it has one" do user.addresses << address expect(address.user).to eq(user) end it "returns nil if it doesn't have one" do expect(address.user).to eq(nil) end end end context "Methods" do describe "#full_address" do it "interpolates the addresses fields into one string" do expect(address.full_address).to eq("test test test 12345") end end end end
mit