code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
""" Tests for a door card. """ import pytest from onirim import card from onirim import component from onirim import core from onirim import agent class DoorActor(agent.Actor): """ """ def __init__(self, do_open): self._do_open = do_open def open_door(self, content, door_card): return self._do_open DRAWN_CAN_NOT_OPEN = ( card.Color.red, False, component.Content( undrawn_cards=[], hand=[card.key(card.Color.blue)]), component.Content( undrawn_cards=[], hand=[card.key(card.Color.blue)], limbo=[card.door(card.Color.red)]), ) DRAWN_DO_NOT_OPEN = ( card.Color.red, False, component.Content( undrawn_cards=[], hand=[card.key(card.Color.red)]), component.Content( undrawn_cards=[], hand=[card.key(card.Color.red)], limbo=[card.door(card.Color.red)]), ) DRAWN_DO_OPEN = ( card.Color.red, True, component.Content( undrawn_cards=[], hand=[ card.key(card.Color.red), card.key(card.Color.red), card.key(card.Color.red), ]), component.Content( undrawn_cards=[], discarded=[card.key(card.Color.red)], hand=[card.key(card.Color.red), card.key(card.Color.red)], opened=[card.door(card.Color.red)]), ) DRAWN_DO_OPEN_2 = ( card.Color.red, True, component.Content( undrawn_cards=[], hand=[ card.key(card.Color.blue), card.key(card.Color.red), ]), component.Content( undrawn_cards=[], discarded=[card.key(card.Color.red)], hand=[card.key(card.Color.blue)], opened=[card.door(card.Color.red)]), ) DRAWN_CASES = [ DRAWN_CAN_NOT_OPEN, DRAWN_DO_NOT_OPEN, DRAWN_DO_OPEN, DRAWN_DO_OPEN_2, ] @pytest.mark.parametrize( "color, do_open, content, content_after", DRAWN_CASES) def test_drawn(color, do_open, content, content_after): door_card = card.door(color) door_card.drawn(core.Core(DoorActor(do_open), agent.Observer(), content)) assert content == content_after
cwahbong/onirim-py
tests/test_door.py
Python
mit
2,159
/* **============================================================================== ** ** Copyright (c) 2003, 2004, 2005, 2006, Michael Brasher, Karl Schopmeyer ** ** 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 "OS.h" int OS::close(Sock sock) { int result; SF_RESTART(::close(sock), result); return result; }
LegalizeAdulthood/cimple
src/server/OS_close.cpp
C++
mit
1,444
'use strict'; const test = require('ava'); const hashSet = require('../index'); const MySet = hashSet(x => x); test('should not change empty set', t => { const set = new MySet(); set.clear(); t.is(set.size, 0); }); test('should clear set', t => { const set = new MySet(); set.add(1); set.clear(); t.is(set.size, 0); });
blond/hash-set
test/clear.js
JavaScript
mit
356
# 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::V2019_08_01 module Models # # Response for ListBastionHosts API service call. # class BastionHostListResult include MsRestAzure include MsRest::JSONable # @return [Array<BastionHost>] List of Bastion Hosts in a resource group. attr_accessor :value # @return [String] URL to get the next set of results. attr_accessor :next_link # return [Proc] with next page method call. attr_accessor :next_method # # Gets the rest of the items for the request, enabling auto-pagination. # # @return [Array<BastionHost>] operation results. # def get_all_items items = @value page = self while page.next_link != nil && !page.next_link.strip.empty? do page = page.get_next_page items.concat(page.value) end items end # # Gets the next page of results. # # @return [BastionHostListResult] with next page content. # def get_next_page response = @next_method.call(@next_link).value! unless @next_method.nil? unless response.nil? @next_link = response.body.next_link @value = response.body.value self end end # # Mapper for BastionHostListResult class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'BastionHostListResult', type: { name: 'Composite', class_name: 'BastionHostListResult', model_properties: { value: { client_side_validation: true, required: false, serialized_name: 'value', type: { name: 'Sequence', element: { client_side_validation: true, required: false, serialized_name: 'BastionHostElementType', type: { name: 'Composite', class_name: 'BastionHost' } } } }, next_link: { client_side_validation: true, required: false, serialized_name: 'nextLink', type: { name: 'String' } } } } } end end end end
Azure/azure-sdk-for-ruby
management/azure_mgmt_network/lib/2019-08-01/generated/azure_mgmt_network/models/bastion_host_list_result.rb
Ruby
mit
2,770
### This script fetches level-1 PACS imaging data, using a list generated by the ### archive (in the CSV format), attaches sky coordinates and masks to them ### (by calling the convertL1ToScanam task) and save them to disk in the correct ### format for later use by Scanamorphos. ### See important instructions below. ####################################################### ### This script is part of the Scanamorphos package. ### HCSS 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. ####################################################### ## Import classes and definitions: import os from herschel.pacs.spg.phot import ConvertL1ToScanamTask ####################################################### ## local settings: dir_root = "/pcdisk/stark/aribas/Desktop/modeling_TDs/remaps_Cha/PACS/scanamorphos/" path = dir_root +"L1/" ### number of observations: n_obs = 2 ####################################################### ## Do a multiple target search in the archive and use the "save all results as CSV" option. ## --> ascii table 'results.csv' where lines can be edited ## (suppress unwanted observations and correct target names) ## Create the directories contained in the dir_out variables (l. 57) ## before running this script. ####################################################### ## observations: table_obs = asciiTableReader(file=dir_root+'results_fast.csv', tableType='CSV', skipRows=1) list_obsids = table_obs[0].data list_names = table_obs[1].data for i_obs in range(n_obs): ## num_obsid = list_obsids[i_obs] source = list_names[i_obs] source = str.lower(str(source)) dir_out = path+source+"_processed_obsids" # create directory if it does not exist if not(os.path.exists(dir_out)): os.system('mkdir '+dir_out) ## print "" print "Downloading obsid " + `num_obsid` obs = getObservation(num_obsid, useHsa=True, instrument="PACS", verbose=True) ### frames = obs.level1.refs["HPPAVGR"].product.refs[0].product convertL1ToScanam(frames, cancelGlitch=1, assignRaDec=1, outDir=dir_out) ### frames = obs.level1.refs["HPPAVGB"].product.refs[0].product convertL1ToScanam(frames, cancelGlitch=1, assignRaDec=1, outDir=dir_out) ### END OF SCRIPT #######################################################
alvaroribas/modeling_TDs
Herschel_mapmaking/scanamorphos/PACS/general_script_L1_PACS.py
Python
mit
2,499
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Sim908Connect.Lib.Constants { internal class CommandFormats { internal const string AT_CGSNBASE = "AT+CGSN"; internal const string ATE = "ATE"; internal const string AT_CFUN = "AT_CFUN"; } }
thehoneymad/Sim908Connect
Sim908Connect/Lib/Constants/CommandFormats.cs
C#
mit
358
<!-- START REVOLUTION SLIDER 5.0 --> <div id="slider_container" class="rev_slider_wrapper"> <div id="rev-slider" class="rev_slider" data-version="5.0"> <ul> <li data-transition="slideremovedown"> <!-- MAIN IMAGE --> <img src="<?php echo $this->common->theme_link(); ?>img/slider/revolution/slider01.jpg" alt="" width="1920" height="600"> <!-- LAYER NR. 1 --> <div class="tp-caption captionHeadline3 text-shadow" id="slide-51-layer-1" data-x="['left','left','left','left']" data-hoffset="['80','80','80','80']" data-y="['top','top','top','top']" data-voffset="['180','180','180','180']" data-width="504" data-height="133" data-whitespace="normal" data-transform_idle="o:1;" data-transform_in="y:[100%];z:0;rX:0deg;rY:0;rZ:0;sX:1;sY:1;skX:0;skY:0;s:1500;e:Power3.easeInOut;" data-transform_out="y:[100%];s:1000;s:1000;" data-mask_in="x:0px;y:0px;s:inherit;e:inherit;" data-mask_out="x:inherit;y:inherit;s:inherit;e:inherit;" data-start="500" data-splitin="none" data-splitout="none" data-responsive_offset="on" style="z-index: 5; white-space: normal;"> Lulusan dijamin Kerja </div> <!-- LAYER NR. 2 --> <div class="tp-caption captionButtonlink" id="slide-400-layer-3" data-x="['left','left','left','left']" data-hoffset="['85','85','85','85']" data-y="['top','top','top','top']" data-voffset="['355','355','355','355']" data-width="['auto','auto','auto','auto']" data-height="['auto','auto','auto','auto']" data-transform_idle="o:1;" data-transform_in="x:right;s:2000;e:Power4.easeInOut;" data-transform_out="s:1000;e:Power2.easeInOut;s:1000;e:Power2.easeInOut;" data-start="700" data-splitin="none" data-splitout="none" data-responsive_offset="on" style="z-index: 6; white-space: nowrap;"><a href="#" class="btn btn-primary btn-icon">Learn more <i class="fa fa-link"></i></a> </div> <!-- <div class="tp-caption" id="slide-400-layer-4" data-x="['right','right','right','right']" data-hoffset="['200','200','150','200']" data-y="['bottom','bottom','bottom','bottom']" data-voffset="['0','0','0','0']" data-transform_idle="o:1;" data-transform_in="y:[100%];z:0;rX:0deg;rY:0;rZ:0;sX:1;sY:1;skX:0;skY:0;s:1500;e:Power3.easeInOut;" data-transform_out="y:[100%];s:1000;s:1000;" data-start="2500" data-splitin="none" data-splitout="none" data-responsive_offset="on" style="z-index: 6; white-space: nowrap;"> <img src="<?php echo $this->common->theme_link(); ?>img/slider/revolution/workerno1.png" class="img-Construction" width="400" alt=""> </div> --> </li> <li data-transition="slideremovedown"> <!-- MAIN IMAGE --> <img src="<?php echo $this->common->theme_link(); ?>img/slider/revolution/slider02.jpg" alt="" width="1920" height="600"> <!-- LAYER NR. 1 --> <div class="tp-caption captionHeadline3 text-shadow" id="slide-51-layer-1" data-x="['left','left','left','left']" data-hoffset="['80','80','80','80']" data-y="['top','top','top','top']" data-voffset="['180','180','180','180']" data-width="700" data-height="133" data-whitespace="normal" data-transform_idle="o:1;" data-transform_in="y:[100%];z:0;rX:0deg;rY:0;rZ:0;sX:1;sY:1;skX:0;skY:0;s:1500;e:Power3.easeInOut;" data-transform_out="y:[100%];s:1000;s:1000;" data-mask_in="x:0px;y:0px;s:inherit;e:inherit;" data-mask_out="x:inherit;y:inherit;s:inherit;e:inherit;" data-start="500" data-splitin="none" data-splitout="none" data-responsive_offset="on" style="z-index: 5; white-space: normal;"> Fasilitas belajar lengkap </div> <!-- LAYER NR. 2 --> <div class="tp-caption captionButtonlink" id="slide-400-layer-3" data-x="['left','left','left','left']" data-hoffset="['85','85','85','85']" data-y="['top','top','top','top']" data-voffset="['355','355','355','355']" data-width="['auto','auto','auto','auto']" data-height="['auto','auto','auto','auto']" data-transform_idle="o:1;" data-transform_in="x:right;s:2000;e:Power4.easeInOut;" data-transform_out="s:1000;e:Power2.easeInOut;s:1000;e:Power2.easeInOut;" data-start="700" data-splitin="none" data-splitout="none" data-responsive_offset="on" style="z-index: 6; white-space: nowrap;"><a href="#" class="btn btn-primary btn-icon">Learn more <i class="fa fa-link"></i></a> </div> <div class="tp-caption" id="slide-400-layer-4" data-x="['right','right','right','right']" data-hoffset="['200','200','150','200']" data-y="['bottom','bottom','bottom','bottom']" data-voffset="['0','0','0','0']" data-transform_idle="o:1;" data-transform_in="y:[100%];z:0;rX:0deg;rY:0;rZ:0;sX:1;sY:1;skX:0;skY:0;s:1500;e:Power3.easeInOut;" data-transform_out="y:[100%];s:1000;s:1000;" data-start="2500" data-splitin="none" data-splitout="none" data-responsive_offset="on" style="z-index: 6; white-space: nowrap;"> <img src="<?php echo $this->common->theme_link(); ?>img/slider/revolution/fitur01.png" class="img-Construction" width="400" alt=""> </div> </li> <li data-transition="slideremovedown"> <!-- MAIN IMAGE --> <img src="<?php echo $this->common->theme_link(); ?>img/slider/revolution/slider03.jpg" alt="" width="1920" height="600"> <!-- LAYER NR. 1 --> <div class="tp-caption captionHeadline3 text-shadow" id="slide-51-layer-1" data-x="['left','left','left','left']" data-hoffset="['80','80','80','80']" data-y="['top','top','top','top']" data-voffset="['180','180','180','180']" data-width="700" data-height="133" data-whitespace="normal" data-transform_idle="o:1;" data-transform_in="y:[100%];z:0;rX:0deg;rY:0;rZ:0;sX:1;sY:1;skX:0;skY:0;s:1500;e:Power3.easeInOut;" data-transform_out="y:[100%];s:1000;s:1000;" data-mask_in="x:0px;y:0px;s:inherit;e:inherit;" data-mask_out="x:inherit;y:inherit;s:inherit;e:inherit;" data-start="500" data-splitin="none" data-splitout="none" data-responsive_offset="on" style="z-index: 5; white-space: normal;"> Agen Langsung Cruiseline </div> <!-- LAYER NR. 2 --> <div class="tp-caption captionButtonlink" id="slide-400-layer-3" data-x="['left','left','left','left']" data-hoffset="['85','85','85','85']" data-y="['top','top','top','top']" data-voffset="['355','355','355','355']" data-width="['auto','auto','auto','auto']" data-height="['auto','auto','auto','auto']" data-transform_idle="o:1;" data-transform_in="x:right;s:2000;e:Power4.easeInOut;" data-transform_out="s:1000;e:Power2.easeInOut;s:1000;e:Power2.easeInOut;" data-start="700" data-splitin="none" data-splitout="none" data-responsive_offset="on" style="z-index: 6; white-space: nowrap;"><a href="#" class="btn btn-primary btn-icon">Learn more <i class="fa fa-link"></i></a> </div> <div class="tp-caption" id="slide-400-layer-4" data-x="['right','right','right','right']" data-hoffset="['200','200','150','200']" data-y="['bottom','bottom','bottom','bottom']" data-voffset="['0','0','0','0']" data-transform_idle="o:1;" data-transform_in="y:[100%];z:0;rX:0deg;rY:0;rZ:0;sX:1;sY:1;skX:0;skY:0;s:1500;e:Power3.easeInOut;" data-transform_out="y:[100%];s:1000;s:1000;" data-start="2500" data-splitin="none" data-splitout="none" data-responsive_offset="on" style="z-index: 6; white-space: nowrap;"> <img src="<?php echo $this->common->theme_link(); ?>img/slider/revolution/fitur02.png" class="img-Construction" width="400" alt=""> </div> </li> </ul> </div><!-- END REVOLUTION SLIDER --> </div> <!-- END OF SLIDER WRAPPER --> <!-- Start contain wrapp --> <div class="contain-wrapp gray-container padding-clear margin-mintop85 feature-Construction"> <div class="container"> <div class="icon-wrapp"> <div class="icon-boxline"> <i class="fa fa-home fa-3x fa-primary"></i> <h5>Lulusan Dijamin Siap Kerja</h5> <p> Dengan dididik dan dilatih oleh instruktur berpengalaman luas di dalam dan luar negeri serta didukung oleh sarana yang lengkap serya kurikulum yang up to date dalam menjamin lulusan bosssignalfx siap kerja. </p> </div> <div class="icon-boxline"> <i class="fa fa-wrench fa-3x fa-primary"></i> <h5>Recruitmen Supporting Cruiseline</h5> <p> Poltenkas Denpasar adalah salah satu kampus yang ditunjuk sebagai Rekruitmen Supporting Partner untuk Royal Carribean Cruiseline, Carnival Cruiseline, dan MSC Cruiseline. </p> </div> <div class="icon-boxline"> <i class="fa fa-group fa-3x fa-primary"></i> <h5>Pendidikan Berkualitas dengan Harga Terjangkau</h5> <p> Dengan biaya kuliah yang terjangkau dan transparan. bosssignalfx mampu memberikan pendidikan bermutu tinggi dan tambahan keahlian seperti Fruit Carving, Bar Flair, Barista, Winecology, Banquet Service, Pastry Bakery, Event Organizer, E-Commerce. </p> </div> </div> </div> </div> <!-- End contain wrapp --> <div class="clearfix"></div> <!-- Start contain wrapp --> <div class="contain-wrapp gray-container padding-bot40"> <div class="container"> <div class="row"> <div class="col-md-8 col-md-offset-2"> <div class="section-heading"> <h3>Build Your Future with Us!</h3> <p>Doctus salutatus est ea, postea doming veritus in nec, sanctus fierent antiopam no pro</p> <i class="fa fa-rocket"></i> </div> </div> </div> <div class="row marginbot30"> <div class="col-md-8 col-md-offset-2 text-center"> <p> Quod assum persecuti ne eum. Et eam paulo menandri dissentiet. Mei eu altera offendit accusamus. Mel te sint verear deseruisse, cu graece disputando quo. Zril putent mel et, eam quot accusam ea. Quo voluptatibus signiferumque te, in partem argumentum honestatis duo. </p> <p><a href="#" class="btn btn-default">View our profile</a> <a href="#" class="btn btn-primary">View our services</a></p> </div> </div> <div class="row"> <div class="col-md-10 col-md-offset-1 text-center"> <img src="<?php echo $this->common->theme_link(); ?>img/group.png" class="img-responsive" alt="" /> <div class="divider margintop-clear"></div> </div> </div> <div class="row"> <div class="col-md-3 col-sm-6"> <div class="col-icon centered"> <i class="fa fa-tablet fa-2x icon-circle icon-bordered"></i> <h5>Responsive</h5> <p> Cu nec salutandi voluptat teros definitionem ad ius, ut eam unumiunanios. </p> </div> </div> <div class="col-md-3 col-sm-6"> <div class="col-icon centered"> <i class="fa fa-magic fa-2x icon-circle icon-bordered"></i> <h5>Clean</h5> <p> Cu nec salutandi voluptat teros definitionem ad ius, ut eam unumiunanios. </p> </div> </div> <div class="col-md-3 col-sm-6"> <div class="col-icon centered"> <i class="fa fa-flask fa-2x icon-circle icon-bordered"></i> <h5>Bootstrap3</h5> <p> Cu nec salutandi voluptat teros definitionem ad ius, ut eam unumiunanios. </p> </div> </div> <div class="col-md-3 col-sm-6"> <div class="col-icon centered"> <i class="fa fa-code fa-2x icon-circle icon-bordered"></i> <h5>Valid code</h5> <p> Cu nec salutandi voluptat teros definitionem ad ius, ut eam unumiunanios. </p> </div> </div> </div> </div> </div> <!-- End contain wrapp --> <div class="clearfix"></div> <!-- Start contain wrapp --> <div id="portfolio" class="contain-wrapp paddingbot-clear"> <div class="container"> <div class="row"> <div class="col-md-8 col-md-offset-2"> <div class="section-heading"> <h3>Galeri Kami</h3> <p>Adhuc doming placerat sea ut, graeci perfecto scriptorem nam</p> <i class="fa fa-image"></i> </div> </div> </div> <div class="row"> <div class="col-md-12"> <!-- Start gallery filter --> <ul class="filter-items"> <li><a href="#" data-filter="" class="active">All</a></li> <li><a href="#" data-filter="web">Kampus Activity</a></li> <li><a href="#" data-filter="graphic">Fasilitas</a></li> <li><a href="#" data-filter="logo">Belajar Mengajar</a></li> </ul> <!-- End gallery filter --> </div> </div> </div> <!-- Start Images Gallery --> <div class="fullwidth"> <div id="gallery" class="masonry gallery"> <div class="grid-sizer col-md-3 col-sm-6 col-xs-6"></div> <!-- Start Gallery 01 --> <div data-filter="web" class="grid-item col-md-3 col-sm-6 col-xs-6"> <div class="img-wrapper"> <div class="img-caption capZoomIn"> <a href="img/gallery/zoom980x980.jpg" data-pretty="prettyPhoto" class="zoomer"><i class="fa fa-search"></i></a> <h5><a href="portfolio-detail.html">Vituperatoribus</a></h5> <a href="#" class="img-categorie">Web design</a> </div> <img src="<?php echo $this->common->theme_link(); ?>img/gallery/380x380/img13.jpg" class="img-fullwidth" alt="" /> </div> </div> <!-- End Gallery 01 --> <!-- Star Gallery 02 --> <div data-filter="graphic" class="grid-item col-md-3 col-sm-6 col-xs-6"> <div class="img-wrapper"> <div class="img-caption capZoomIn"> <a href="img/gallery/zoom980x980.jpg" data-pretty="prettyPhoto" class="zoomer"><i class="fa fa-search"></i></a> <h5><a href="portfolio-detail.html">Vituperatoribus</a></h5> <a href="#" class="img-categorie">Web design</a> </div> <img src="<?php echo $this->common->theme_link(); ?>img/gallery/380x380/img14.jpg" class="img-fullwidth" alt="" /> </div> </div> <!-- End Gallery 02 --> <!-- Start Gallery 03 --> <div data-filter="app" class="grid-item col-md-3 col-sm-6 col-xs-6"> <div class="img-wrapper"> <div class="img-caption capZoomIn"> <a href="img/gallery/zoom980x980.jpg" data-pretty="prettyPhoto" class="zoomer"><i class="fa fa-search"></i></a> <h5><a href="portfolio-detail.html">Persequeris</a></h5> <a href="#" class="img-categorie">App design</a> </div> <img src="<?php echo $this->common->theme_link(); ?>img/gallery/380x380/img15.jpg" class="img-fullwidth" alt="" /> </div> </div> <!-- End Gallery 03 --> <!-- Start Gallery 04 --> <div data-filter="logo" class="grid-item col-md-3 col-sm-6 col-xs-6"> <div class="img-wrapper"> <div class="img-caption capZoomIn"> <a href="img/gallery/zoom980x980.jpg" data-pretty="prettyPhoto" class="zoomer"><i class="fa fa-search"></i></a> <h5><a href="portfolio-detail.html">An ancillae</a></h5> <a href="#" class="img-categorie">logo design</a> </div> <img src="<?php echo $this->common->theme_link(); ?>img/gallery/380x380/img16.jpg" class="img-fullwidth" alt="" /> </div> </div> <!-- End Gallery 04 --> <!-- Start Gallery 05 --> <div data-filter="logo" class="grid-item col-md-3 col-sm-6 col-xs-6"> <div class="img-wrapper"> <div class="img-caption capZoomIn"> <a href="img/gallery/zoom980x980.jpg" data-pretty="prettyPhoto" class="zoomer"><i class="fa fa-search"></i></a> <h5><a href="portfolio-detail.html">Viris copiosae</a></h5> <a href="#" class="img-categorie">logo design</a> </div> <img src="<?php echo $this->common->theme_link(); ?>img/gallery/380x380/img17.jpg" class="img-fullwidth" alt="" /> </div> </div> <!-- End Gallery 05 --> <!-- Start Gallery 06 --> <div data-filter="web" class="grid-item col-md-3 col-sm-6 col-xs-6"> <div class="img-wrapper"> <div class="img-caption capZoomIn"> <a href="img/gallery/zoom980x980.jpg" data-pretty="prettyPhoto" class="zoomer"><i class="fa fa-search"></i></a> <h5><a href="portfolio-detail.html">Reprimique</a></h5> <a href="#" class="img-categorie">Web design</a> </div> <img src="<?php echo $this->common->theme_link(); ?>img/gallery/380x380/img18.jpg" class="img-fullwidth" alt="" /> </div> </div> <!-- End Gallery 06 --> <!-- Start Gallery 07 --> <div data-filter="graphic" class="grid-item col-md-3 col-sm-6 col-xs-6"> <div class="img-wrapper"> <div class="img-caption capZoomIn"> <a href="img/gallery/zoom980x980.jpg" data-pretty="prettyPhoto" class="zoomer"><i class="fa fa-search"></i></a> <h5><a href="portfolio-detail.html">Simul labitur</a></h5> <a href="#" class="img-categorie">Graphic design</a> </div> <img src="<?php echo $this->common->theme_link(); ?>img/gallery/380x380/img19.jpg" class="img-fullwidth" alt="" /> </div> </div> <!-- End Gallery 07 --> <!-- Start Gallery 08 --> <div data-filter="app" class="grid-item col-md-3 col-sm-6 col-xs-6"> <div class="img-wrapper"> <div class="img-caption capZoomIn"> <a href="img/gallery/zoom980x980.jpg" data-pretty="prettyPhoto" class="zoomer"><i class="fa fa-search"></i></a> <h5><a href="portfolio-detail.html">Consetetur</a></h5> <a href="#" class="img-categorie">App design</a> </div> <img src="<?php echo $this->common->theme_link(); ?>img/gallery/380x380/img20.jpg" class="img-fullwidth" alt="" /> </div> </div> <!-- End Gallery 08 --> </div> <div class="row"> <div class="col-md-12"> <a href="portfolio-alt1.html" class="btn btn-primary btn-lg btn-block">View more Gallery</a> </div> </div> </div> <!-- End Images Gallery --> <!-- End contain wrapp --> <div class="clearfix"></div> <!-- Start parallax --> <div class="parallax parallax-two bg3"> <div class="parallax-container padding-bot30"> <div class="container"> <div class="row"> <div class="col-md-8 col-md-offset-2 owl-column-wrapp"> <div id="testimoni" class="owl-carousel"> <div class="item"> <div class="testimoni-single"> <blockquote class="centered"> Kemampuan Alumni bosssignalfx Dalam Bekerja Tidak Perlu Diragukan Lagi Karena Selain Cekatan Juga Fast Learner, Saya Mencari Staf Yang Seperti Itu Dan Itulah Yang Dibutuhkan Industri Saat Ini. </blockquote> <span class="block"><a href="#">Tusan Aryasa</a> - Housekeeper Estate Como Shambhala Executive </span> <img src="<?php echo $this->common->theme_link(); ?>img/testimoni/tusan.jpg" class="img-circle testimoni-avatar" alt="" /> </div> </div> <div class="item"> <div class="testimoni-single"> <blockquote class="centered"> Saya Merekomendasi bosssignalfx Sebagai Tempat Anda Kuliah Perhotelan Karena Terbukti Dari Mahasiswa Yang On The Job Training Di Tempat Kami Menunjukkan Sikap Yang Loyal & Hardworker. </blockquote> <span class="block"><a href="#">Sukarmajaya</a> - Executive Chef The Villas, Seminyak </span> <img src="<?php echo $this->common->theme_link(); ?>img/testimoni/sukarmajaya.jpg" class="img-circle testimoni-avatar" alt="" /> </div> </div> <div class="item"> <div class="testimoni-single"> <blockquote class="centered"> Dari Berbagai Kampus Yang Mahasiswanya On The Job Trainng Di Tempat Kami bosssignalfx Selalu Memberikan Mahasiswa Yang Terbaik Dalam Hal Disiplin & Teamwork. Thank’s bosssignalfx. </blockquote> <span class="block"><a href="#">Ni Made Restiti</a> - Personnel Manager UN'S Hotel & Restaurant, Legian - Kuta</span> <img src="<?php echo $this->common->theme_link(); ?>img/testimoni/restiti.jpg" class="img-circle testimoni-avatar" alt="" /> </div> </div> <div class="item"> <div class="testimoni-single"> <blockquote class="centered"> Saya Ucapkan Terima Kasih Yang Banyak Kepada bosssignalfx Yang Telah Memberikan Tenaga Training Handal Dan Cepat Beradaptasi Dengan Pola Kerja High Speed Di Beach Club Kami. </blockquote> <span class="block"><a href="#"> I Made Dwi Artha Pradnya</a> - Asst. Restaurant Manager Potato Head Beach Club Seminyak- Kuta</span> <img src="<?php echo $this->common->theme_link(); ?>img/testimoni/dwi.jpg" class="img-circle testimoni-avatar" alt="" /> </div> </div> <div class="item"> <div class="testimoni-single"> <blockquote class="centered"> bosssignalfx Selalu Mensupport Untuk Tenaga Training Di Hotel Kami, Kami Pilih bosssignalfx Karena Tenaganya Siap Pakai, Disiplin & Memiliki Positive Attitude. </blockquote> <span class="block"><a href="#">I Made Wirta</a> - Executive Housekeeper Amarterra Villas Bali By Accor, Nusa Dua</span> <img src="<?php echo $this->common->theme_link(); ?>img/testimoni/wirta.jpg" class="img-circle testimoni-avatar" alt="" /> </div> </div> </div> </div> </div> </div> </div> </div> <!-- End parallax --> <div class="clearfix"></div> <!-- Start cta primary --> <div class="cta-wrapper cta-primary"> <div class="container"> <div class="row"> <div class="col-md-12"> <h4>Ayo Daftar Sekarang</h4> <p>Mari bergabung dengan ratusan alumni lain.</p> <a class="btn" href="#">Daftar Sekarang!</a> </div> </div> </div> </div> <!-- End cta primary --> <div class="clearfix"></div>
dodeagung/KLGH
public_html/application/views/frontpage/home_view.php
PHP
mit
24,501
<?php namespace AppBundle\Form; use AppBundle\AppBundle; use Symfony\Bridge\Doctrine\Form\Type\EntityType; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; class ProductType extends AbstractType { /** * {@inheritdoc} */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('name') ->add('price') ->add('productType') ; } /** * {@inheritdoc} */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults(array( 'data_class' => 'AppBundle\Entity\Product' )); } /** * {@inheritdoc} */ public function getBlockPrefix() { return 'appbundle_product'; } }
Bunkermaster/exosymfony
src/AppBundle/Form/ProductType.php
PHP
mit
885
#!/usr/bin/env python # -*- coding: utf-8 -*- import os from conans.model import Generator from conans.client.generators import VisualStudioGenerator from xml.dom import minidom from conans.util.files import load class VisualStudioMultiGenerator(Generator): template = """<?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <ImportGroup Label="PropertySheets" > </ImportGroup> <PropertyGroup Label="UserMacros" /> <PropertyGroup /> <ItemDefinitionGroup /> <ItemGroup /> </Project> """ @property def filename(self): pass @property def content(self): configuration = str(self.conanfile.settings.build_type) platform = {'x86': 'Win32', 'x86_64': 'x64'}.get(str(self.conanfile.settings.arch)) vsversion = str(self.settings.compiler.version) # there is also ClCompile.RuntimeLibrary, but it's handling is a bit complicated, so skipping for now condition = " '$(Configuration)' == '%s' And '$(Platform)' == '%s' And '$(VisualStudioVersion)' == '%s' "\ % (configuration, platform, vsversion + '.0') name_multi = 'conanbuildinfo_multi.props' name_current = ('conanbuildinfo_%s_%s_%s.props' % (configuration, platform, vsversion)).lower() multi_path = os.path.join(self.output_path, name_multi) if os.path.isfile(multi_path): content_multi = load(multi_path) else: content_multi = self.template dom = minidom.parseString(content_multi) import_node = dom.createElement('Import') import_node.setAttribute('Condition', condition) import_node.setAttribute('Project', name_current) import_group = dom.getElementsByTagName('ImportGroup')[0] children = import_group.getElementsByTagName("Import") for node in children: if name_current == node.getAttribute("Project") and condition == node.getAttribute("Condition"): break else: import_group.appendChild(import_node) content_multi = dom.toprettyxml() content_multi = "\n".join(line for line in content_multi.splitlines() if line.strip()) vs_generator = VisualStudioGenerator(self.conanfile) content_current = vs_generator.content return {name_multi: content_multi, name_current: content_current}
lasote/conan
conans/client/generators/visualstudio_multi.py
Python
mit
2,436
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class M_slider extends Main_model { function __construct() { parent::__construct(); $this->table = array( 'name' => 'tbl_slider', 'coloumn' => array( 'slider_id' => array('id'=>'slider_id', 'label'=>'ID', 'idkey'=>true, 'visible'=>false, 'field_visible'=>true, 'format'=>'HIDDEN'), 'slider_name' => array('id'=>'slider_name', 'label'=>'Slider Name', 'idkey'=>false, 'visible'=>true, 'field_visible'=>true, 'format'=>'TEXT'), 'slider_publish' => array('id'=>'slider_publish', 'label'=>'Date Publish', 'idkey'=>false, 'visible'=>true, 'field_visible'=>true, 'format'=>'TEXT'), 'slider_expire' => array('id'=>'slider_expire', 'label'=>'Date Expired', 'idkey'=>false, 'visible'=>true, 'field_visible'=>true, 'format'=>'TEXT'), 'slider_images' => array('id'=>'slider_images', 'label'=>'Image', 'idkey'=>false, 'visible'=>false, 'field_visible'=>true, 'format'=>'FILE'), ), 'join' =>array( ), 'where' => array(), 'keys' => 'slider_id', 'option_name' => '' ); } function fields() { $data = array(); return $data; } function getlist($params) { $list = $this->getListData($params); $nomor = $params['start']; $data['records'] = array(); foreach($list['records']->result() as $row): $actions = ''; $actions .= '<a data-id="'.$row->slider_id.'" data-target="form_modal_slider" data-toggle="modal" class="btn btn-xs btn-success btn-editable"><i class="glyphicon glyphicon-edit"></i>Ubah</a>'; $actions .= '<a data-id="'.$row->slider_id.'" class="btn btn-xs btn-danger btn-removable"><i class="glyphicon glyphicon-trash"></i>Hapus</a>'; $data['records'][] = array( $nomor+1, $row->slider_name, $row->slider_publish, $row->slider_expire, $actions ); $nomor++; endforeach; $data['total'] = $list['total']; $data['total_filter'] = $list['total_filter']; return $data; } }
dwivivagoal/KuizMilioner
application/modules/webadmin/models/M_slider.php
PHP
mit
2,465
package org.katlas.JavaKh.rows; import org.katlas.JavaKh.utils.RedBlackIntegerTree; public class RedBlackIntegerMap<F> extends RedBlackIntegerTree<F> implements MatrixRow<F> { /** * */ private static final long serialVersionUID = 5885667469881867107L; public void compact() { } public void putLast(int key, F f) { put(key, f); } @Override public void put(int key, F value) { if(value == null) { remove(key); } else { super.put(key, value); } } }
craigfreilly/masters-project-submission
src/KnotTheory/JavaKh-v2/src/org/katlas/JavaKh/rows/RedBlackIntegerMap.java
Java
mit
518
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.mediaservices.v2018_07_01; import com.fasterxml.jackson.annotation.JsonProperty; /** * The ListEdgePoliciesInput model. */ public class ListEdgePoliciesInput { /** * Unique identifier of the edge device. */ @JsonProperty(value = "deviceId") private String deviceId; /** * Get unique identifier of the edge device. * * @return the deviceId value */ public String deviceId() { return this.deviceId; } /** * Set unique identifier of the edge device. * * @param deviceId the deviceId value to set * @return the ListEdgePoliciesInput object itself. */ public ListEdgePoliciesInput withDeviceId(String deviceId) { this.deviceId = deviceId; return this; } }
selvasingh/azure-sdk-for-java
sdk/mediaservices/mgmt-v2018_07_01/src/main/java/com/microsoft/azure/management/mediaservices/v2018_07_01/ListEdgePoliciesInput.java
Java
mit
1,044
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * jkl */ package com.microsoft.azure.management.apimanagement.v2019_12_01.implementation; import com.microsoft.azure.arm.model.implementation.WrapperImpl; import com.microsoft.azure.management.apimanagement.v2019_12_01.Loggers; import rx.Completable; import rx.functions.Func1; import rx.Observable; import com.microsoft.azure.Page; import com.microsoft.azure.management.apimanagement.v2019_12_01.LoggerContract; class LoggersImpl extends WrapperImpl<LoggersInner> implements Loggers { private final ApiManagementManager manager; LoggersImpl(ApiManagementManager manager) { super(manager.inner().loggers()); this.manager = manager; } public ApiManagementManager manager() { return this.manager; } @Override public LoggerContractImpl define(String name) { return wrapModel(name); } private LoggerContractImpl wrapModel(LoggerContractInner inner) { return new LoggerContractImpl(inner, manager()); } private LoggerContractImpl wrapModel(String name) { return new LoggerContractImpl(name, this.manager()); } @Override public Observable<LoggerContract> listByServiceAsync(final String resourceGroupName, final String serviceName) { LoggersInner client = this.inner(); return client.listByServiceAsync(resourceGroupName, serviceName) .flatMapIterable(new Func1<Page<LoggerContractInner>, Iterable<LoggerContractInner>>() { @Override public Iterable<LoggerContractInner> call(Page<LoggerContractInner> page) { return page.items(); } }) .map(new Func1<LoggerContractInner, LoggerContract>() { @Override public LoggerContract call(LoggerContractInner inner) { return new LoggerContractImpl(inner, manager()); } }); } @Override public Completable getEntityTagAsync(String resourceGroupName, String serviceName, String loggerId) { LoggersInner client = this.inner(); return client.getEntityTagAsync(resourceGroupName, serviceName, loggerId).toCompletable(); } @Override public Observable<LoggerContract> getAsync(String resourceGroupName, String serviceName, String loggerId) { LoggersInner client = this.inner(); return client.getAsync(resourceGroupName, serviceName, loggerId) .map(new Func1<LoggerContractInner, LoggerContract>() { @Override public LoggerContract call(LoggerContractInner inner) { return new LoggerContractImpl(inner, manager()); } }); } @Override public Completable deleteAsync(String resourceGroupName, String serviceName, String loggerId, String ifMatch) { LoggersInner client = this.inner(); return client.deleteAsync(resourceGroupName, serviceName, loggerId, ifMatch).toCompletable(); } }
selvasingh/azure-sdk-for-java
sdk/apimanagement/mgmt-v2019_12_01/src/main/java/com/microsoft/azure/management/apimanagement/v2019_12_01/implementation/LoggersImpl.java
Java
mit
3,159
<?php /** * Created by PhpStorm. * User: jmannion * Date: 04/08/14 * Time: 22:17 */ namespace JamesMannion\ForumBundle\Form\User; use Symfony\Component\Form\FormBuilderInterface; use JamesMannion\ForumBundle\Constants\Label; use JamesMannion\ForumBundle\Constants\Button; use JamesMannion\ForumBundle\Constants\Validation; use Doctrine\ORM\EntityRepository; use Symfony\Component\Form\AbstractType; class UserCreateForm extends AbstractType { private $name = 'userCreateForm'; public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add( 'username', 'text', array( 'mapped' => true, 'required' => true, 'label' => Label::REGISTRATION_USERNAME, 'max_length' => 100, ) ) ->add( 'email', 'repeated', array( 'type' => 'email', 'mapped' => true, 'required' => true, 'max_length' => 100, 'invalid_message' => Validation::REGISTRATION_EMAIL_MATCH, 'first_options' => array( 'label' => Label::REGISTRATION_EMAIL, ), 'second_options' => array( 'label' => Label::REGISTRATION_REPEAT_EMAIL), ) ) ->add( 'password', 'repeated', array( 'mapped' => true, 'type' => 'password', 'required' => true, 'max_length' => 100, 'invalid_message' => Validation::REGISTRATION_PASSWORD_MATCH, 'first_options' => array('label' => Label::REGISTRATION_PASSWORD), 'second_options' => array('label' => Label::REGISTRATION_REPEAT_PASSWORD) ) ) ->add( 'memorableQuestion', 'entity', array( 'mapped' => true, 'required' => true, 'label' => Label::REGISTRATION_MEMORABLE_QUESTION, 'class' => 'JamesMannionForumBundle:MemorableQuestion', 'query_builder' => function(EntityRepository $er) { return $er->createQueryBuilder('q') ->orderBy('q.question', 'ASC'); } ) ) ->add( 'memorableAnswer', 'text', array( 'mapped' => true, 'required' => true, 'label' => Label::REGISTRATION_MEMORABLE_ANSWER, 'max_length' => 100, ) ) ->add( 'save', 'submit', array( 'label' => Button::REGISTRATION_SUBMIT ) ); } /** * @return string */ public function getName() { return $this->name; } }
mannion007/JamesMannionForum
src/JamesMannion/ForumBundle/Form/User/UserCreateForm.php
PHP
mit
3,204
/*! Slidebox.JS - v1.0 - 2013-11-30 * http://github.com/trevanhetzel/slidebox * * Copyright (c) 2013 Trevan Hetzel <trevan.co>; * Licensed under the MIT license */ slidebox = function (params) { // Carousel carousel = function () { var $carousel = $(params.container).children(".carousel"), $carouselItem = $(".carousel li"), $triggerLeft = $(params.leftTrigger), $triggerRight = $(params.rightTrigger), total = $carouselItem.length, current = 0; var moveLeft = function () { if ( current > 0 ) { $carousel.animate({ "left": "+=" + params.length + "px" }, params.speed ); current--; } }; var moveRight = function () { if ( current < total - 2 ) { $carousel.animate({ "left": "-=" + params.length + "px" }, params.speed ); current++; } }; // Initiliaze moveLeft on trigger click $triggerLeft.on("click", function () { moveLeft(); }); // Initiliaze moveRight on trigger click $triggerRight.on("click", function () { moveRight(); }); // Initiliaze moveLeft on left keypress $(document).keydown(function (e){ if (e.keyCode == 37) { moveLeft(); } }); // Initiliaze moveRight on right keypress $(document).keydown(function (e){ if (e.keyCode == 39) { moveRight(); } }); }, // Lightbox lightbox = function () { var trigger = ".carousel li a"; // Close lightbox when pressing esc key $(document).keydown(function (e){ if (e.keyCode == 27) { closeLightbox(); } }); $(document) // Close lightbox on any click .on("click", function () { closeLightbox(); }) // If clicked on a thumbnail trigger, proceed .on("click", trigger, function (e) { var $this = $(this); // Prevent from clicking through e.preventDefault(); e.stopPropagation(); // Grab the image URL dest = $this.attr("href"); // Grab the caption from data attribute capt = $this.children("img").data("caption"); enlarge(dest, capt); /* If clicked on an enlarged image, stop propagation so it doesn't get the close function */ $(document).on("click", ".lightbox img", function (e) { e.stopPropagation(); }); }); closeLightbox = function () { $(".lightbox-cont").remove(); $(".lightbox").remove(); }, enlarge = function (dest, capt) { // Create new DOM elements $("body").append("<div class='lightbox-cont'></div><div class='lightbox'></div>"); $(".lightbox").html(function () { return "<img src='" + dest + "'><div class='lightbox-caption'>" + capt + "</div>"; }); } } // Initialize functions carousel(); lightbox(); };
trevanhetzel/slidebox
slidebox.js
JavaScript
mit
3,369
<?php // ============================================================================= // VIEWS/ETHOS/_POST-CAROUSEL.PHP // ----------------------------------------------------------------------------- // Outputs the post carousel that appears at the top of the masthead. // ============================================================================= GLOBAL $post_carousel_entry_id; $post_carousel_entry_id = get_the_ID(); $is_enabled = x_get_option( 'x_ethos_post_carousel_enable', '' ) == '1'; $count = x_get_option( 'x_ethos_post_carousel_count' ); $display = x_get_option( 'x_ethos_post_carousel_display' ); switch ( $display ) { case 'most-commented' : $args = array( 'post_type' => 'post', 'posts_per_page' => $count, 'orderby' => 'comment_count', 'order' => 'DESC' ); break; case 'random' : $args = array( 'post_type' => 'post', 'posts_per_page' => $count, 'orderby' => 'rand' ); break; case 'featured' : $args = array( 'post_type' => 'post', 'posts_per_page' => $count, 'orderby' => 'date', 'meta_key' => '_x_ethos_post_carousel_display', 'meta_value' => 'on' ); break; } ?> <?php if ( $is_enabled ) : ?> <ul class="x-post-carousel unstyled"> <?php $wp_query = new WP_Query( $args ); ?> <?php if ( $wp_query->have_posts() ) : ?> <?php while ( $wp_query->have_posts() ) : $wp_query->the_post(); ?> <li class="x-post-carousel-item"> <?php x_ethos_entry_cover( 'post-carousel' ); ?> </li> <?php endwhile; ?> <?php endif; ?> <?php wp_reset_query(); ?> <script> jQuery(document).ready(function() { jQuery('.x-post-carousel').slick({ speed : 500, slide : 'li', slidesToShow : <?php echo x_get_option( 'x_ethos_post_carousel_display_count_extra_large' ); ?>, slidesToScroll : 1, responsive : [ { breakpoint : 1500, settings : { speed : 500, slide : 'li', slidesToShow : <?php echo x_get_option( 'x_ethos_post_carousel_display_count_large' ); ?> } }, { breakpoint : 1200, settings : { speed : 500, slide : 'li', slidesToShow : <?php echo x_get_option( 'x_ethos_post_carousel_display_count_medium' ); ?> } }, { breakpoint : 979, settings : { speed : 500, slide : 'li', slidesToShow : <?php echo x_get_option( 'x_ethos_post_carousel_display_count_small' ); ?> } }, { breakpoint : 550, settings : { speed : 500, slide : 'li', slidesToShow : <?php echo x_get_option( 'x_ethos_post_carousel_display_count_extra_small' ); ?> } } ] }); }); </script> </ul> <?php endif; ?>
whskyneat/element-wheels-blog
web/app/themes/x/framework/views/ethos/_post-carousel.php
PHP
mit
2,761
import test from 'ava'; import Server from '../../src/server'; import IO from '../../src/socket-io'; test.cb('mock socket invokes each handler with unique reference', t => { const socketUrl = 'ws://roomy'; const server = new Server(socketUrl); const socket = new IO(socketUrl); let handlerInvoked = 0; const handler3 = function handlerFunc() { t.true(true); handlerInvoked += 1; }; // Same functions but different scopes/contexts socket.on('custom-event', handler3.bind(Object.create(null))); socket.on('custom-event', handler3.bind(Object.create(null))); // Same functions with same scope/context (only one should be added) socket.on('custom-event', handler3); socket.on('custom-event', handler3); // not expected socket.on('connect', () => { socket.join('room'); server.to('room').emit('custom-event'); }); setTimeout(() => { t.is(handlerInvoked, 3, 'handler invoked too many times'); server.close(); t.end(); }, 500); }); test.cb('mock socket invokes each handler per socket', t => { const socketUrl = 'ws://roomy'; const server = new Server(socketUrl); const socketA = new IO(socketUrl); const socketB = new IO(socketUrl); let handlerInvoked = 0; const handler3 = function handlerFunc() { t.true(true); handlerInvoked += 1; }; // Same functions but different scopes/contexts socketA.on('custom-event', handler3.bind(socketA)); socketB.on('custom-event', handler3.bind(socketB)); // Same functions with same scope/context (only one should be added) socketA.on('custom-event', handler3); socketA.on('custom-event', handler3); // not expected socketB.on('custom-event', handler3.bind(socketB)); // expected because bind creates a new method socketA.on('connect', () => { socketA.join('room'); socketB.join('room'); server.to('room').emit('custom-event'); }); setTimeout(() => { t.is(handlerInvoked, 4, 'handler invoked too many times'); server.close(); t.end(); }, 500); });
thoov/mock-socket
tests/issues/65.test.js
JavaScript
mit
2,017
import React from 'react' import PropTypes from 'prop-types' import VelocityTrimControls from './VelocityTrimControls' import Instrument from '../../images/Instrument' import styles from '../../styles/velocityTrim' import { trimShape } from '../../reducers/velocityTrim' const handleKeyDown = (event, item, bank, userChangedTrimEnd) => { let delta = 0 event.nativeEvent.preventDefault() switch (event.key) { case 'ArrowUp': delta = 1 break case 'ArrowDown': delta = -1 break case 'PageUp': delta = 5 break case 'PageDown': delta = -5 break case 'Enter': delta = 100 break case 'Escape': delta = -100 break default: break } if (delta !== 0) { delta += item.trim if (delta < 0) delta = 0 if (delta > 100) delta = 100 userChangedTrimEnd(item.note, delta, bank) } } const VelocityTrim = (props) => { const { item, bank, selected, playNote, selectTrim, userChangedTrimEnd } = props const { note, trim, group, name } = item return ( <section tabIndex={note} onKeyDown={e => handleKeyDown(e, item, bank, userChangedTrimEnd)} onMouseUp={() => (selected ? null : selectTrim(note))} className={selected ? styles.selected : ''} role="presentation" > <div className={styles.header} onMouseUp={() => playNote(note, Math.round(127 * (trim / 100)), bank)} role="button" tabIndex={note} > <div>{note}</div> <div>{group}</div> <div>{Instrument(group)}</div> </div> <div className={styles.noteName} title={name} > {name} </div> <VelocityTrimControls {...props} /> </section> ) } VelocityTrim.propTypes = { item: trimShape.isRequired, selected: PropTypes.bool.isRequired, playNote: PropTypes.func.isRequired, selectTrim: PropTypes.func.isRequired, userChangedTrimEnd: PropTypes.func.isRequired, bank: PropTypes.number.isRequired, } export default VelocityTrim
dkadrios/zendrum-stompblock-client
src/components/trims/VelocityTrim.js
JavaScript
mit
2,066
class CreateTips < ActiveRecord::Migration[5.0] def change create_table :tips do |t| t.text :body t.timestamps end end end
agonzalez0515/Coco-app
db/migrate/20161220004643_create_tips.rb
Ruby
mit
148
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class MY_Controller extends CI_Controller { public function __construct() { parent::__construct(); $this->load->helper('url'); } } class Admin_Controller extends MY_Controller { public function __construct() { parent::__construct(); $this->is_logged_in(); } public function is_logged_in() { } }
bivinvinod/footballCrazy
application/core/MY_Controller.php
PHP
mit
439
/* * Copyright (c) 2014-2016, Santili Y-HRAH KRONG * All rights reserved. * * 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. * * 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 HOLDER 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. */ #include <sqlcreatetable.hpp> namespace cppsqlx { SQLCreateTable::SQLCreateTable(std::string tablename) { _objectname = tablename; _objecttype = "TABLE"; } std::string SQLCreateTable::toString() { std::string query; query = "CREATE "; query += _objecttype + " " + _objectname; if(_ds) { query += "(\n"; for(auto i = 1; i <= _ds->rowSize() ; i++) { query += _ds->at(i).name() + " " + _ds->at(i).type(); if(i != _ds->rowSize()) query += ",\n"; } query += "\n)"; } else { query += " AS\n"; query += _select; } switch(sqldialect_) { case DBPROVIDER::GREENPLUM : { query+= "\nDISTRIBUTED RANDOMLY"; break; } default: break; } return query; }; SQLCreateTable& SQLCreateTable::as(std::string select) { _select = select; return *this; } SQLCreateTable& SQLCreateTable::sameAs(std::shared_ptr<Dataset> ds) { _ds = ds; return *this; } };/*namespace cppsqlx*/
Santili/cppsqlx
source/sqlcreatetable.cpp
C++
mit
2,452
<?php /** * Link posts * * @package Start Here * @since Start Here 1.0.0 */ ?> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <header class="post-header"> <div class="header-metas"> <?php sh_post_format(); ?> <?php if( is_singular() ) { edit_post_link( __( 'Edit', 'textdomain' ), '<span class="edit-link">', '</span>' ); } ?> <span class="post-date"> <time class="published" datetime="<?php echo get_the_time('c'); ?>"><a title="<?php _e( 'Permalink to: ', 'textdomain' ); echo the_title(); ?>" href="<?php the_permalink(); ?>"><?php echo get_the_date(); ?></a></time> </span> <span class="post-author"> <?php _e( '- By ', 'textdomain' ); ?><a title="<?php _e('See other posts by ', 'textdomain'); the_author_meta( 'display_name' ); ?>" href="<?php echo get_author_posts_url( get_the_author_meta( 'ID' ) ); ?>"><?php the_author_meta( 'display_name' ); ?></a> </span> </div> </header> <div class="<?php if( is_single() ) { echo 'post-content'; } else { echo 'link-content'; } ?>"> <?php the_content(''); ?> </div> <?php if( !is_single() && has_excerpt() ) : ?> <?php the_excerpt(); ?> <a class="read-more" href="<?php the_permalink(); ?>" title="<?php echo _e( 'Read more', 'textdomain' ); ?>"><i class="g"></i><?php echo _e( 'Read more', 'textdomain' ); ?></a> <?php endif; ?> <?php if( is_single() ) : ?> <footer class="post-footer"> <ul class="taxo-metas"> <?php if( get_the_category() ) { ?><li class="category"><i class="gicn gicn-category"></i><?php the_category(' &#8226; '); ?></li><?php } ?> <li class="tag-links"><i class="gicn gicn-tag"></i><?php $tags_list = get_the_tag_list( '', __( ' ', 'textdomain' ) ); if ( $tags_list ) : printf( __( '%1$s', 'textdomain' ), $tags_list ); else : _e( 'No tags', 'textdomain' ); endif; ?> </li> </ul> </footer> <?php endif; ?> </article>
Manoz/start-here
start-here/templates/content-link.php
PHP
mit
2,213
# Scrapy settings for helloscrapy project # # For simplicity, this file contains only the most important settings by # default. All the other settings are documented here: # # http://doc.scrapy.org/en/latest/topics/settings.html # BOT_NAME = 'helloscrapy' SPIDER_MODULES = ['helloscrapy.spiders'] NEWSPIDER_MODULE = 'helloscrapy.spiders' # Crawl responsibly by identifying yourself (and your website) on the user-agent #USER_AGENT = 'helloscrapy (+http://www.yourdomain.com)' DOWNLOAD_DELAY = 3 ROBOTSTXT_OBEY = True
orangain/helloscrapy
helloscrapy/settings.py
Python
mit
525
""" Django settings for djangoApp project. Generated by 'django-admin startproject' using Django 1.10.5. For more information on this file, see https://docs.djangoproject.com/en/1.10/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.10/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'r&j)3lay4i$rm44n%h)bsv_q(9ysqhl@7@aibjm2b=1)0fag9n' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'djangoApp.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'djangoApp.wsgi.application' # Database # https://docs.djangoproject.com/en/1.10/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.10/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.10/howto/static-files/ STATIC_URL = '/static/'
reggieroby/devpack
frameworks/djangoApp/djangoApp/settings.py
Python
mit
3,105
namespace Engine.Contracts { public interface IAct { /// <summary> /// Makes an act (or try) and returns how much time it takes /// </summary> /// <param name="scene">Scene on which act plays</param> /// <returns>Time passed</returns> ActResult Do(IScene scene); string Name { get; set; } bool CanDo(IActor actor, IScene scene); } public class ActResult { public int TimePassed; public string Message; } }
sheix/GameEngine
Engine/Contracts/IAct.cs
C#
mit
482
/** * @fileoverview Rule to flag use of implied eval via setTimeout and setInterval * @author James Allardice */ "use strict"; //------------------------------------------------------------------------------ // Requirements //------------------------------------------------------------------------------ const astUtils = require("./utils/ast-utils"); const { getStaticValue } = require("eslint-utils"); //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ module.exports = { meta: { type: "suggestion", docs: { description: "disallow the use of `eval()`-like methods", category: "Best Practices", recommended: false, url: "https://eslint.org/docs/rules/no-implied-eval" }, schema: [], messages: { impliedEval: "Implied eval. Consider passing a function instead of a string." } }, create(context) { const EVAL_LIKE_FUNCS = Object.freeze(["setTimeout", "execScript", "setInterval"]); const GLOBAL_CANDIDATES = Object.freeze(["global", "window", "globalThis"]); /** * Checks whether a node is evaluated as a string or not. * @param {ASTNode} node A node to check. * @returns {boolean} True if the node is evaluated as a string. */ function isEvaluatedString(node) { if ( (node.type === "Literal" && typeof node.value === "string") || node.type === "TemplateLiteral" ) { return true; } if (node.type === "BinaryExpression" && node.operator === "+") { return isEvaluatedString(node.left) || isEvaluatedString(node.right); } return false; } /** * Checks whether a node is an Identifier node named one of the specified names. * @param {ASTNode} node A node to check. * @param {string[]} specifiers Array of specified name. * @returns {boolean} True if the node is a Identifier node which has specified name. */ function isSpecifiedIdentifier(node, specifiers) { return node.type === "Identifier" && specifiers.includes(node.name); } /** * Checks a given node is a MemberExpression node which has the specified name's * property. * @param {ASTNode} node A node to check. * @param {string[]} specifiers Array of specified name. * @returns {boolean} `true` if the node is a MemberExpression node which has * the specified name's property */ function isSpecifiedMember(node, specifiers) { return node.type === "MemberExpression" && specifiers.includes(astUtils.getStaticPropertyName(node)); } /** * Reports if the `CallExpression` node has evaluated argument. * @param {ASTNode} node A CallExpression to check. * @returns {void} */ function reportImpliedEvalCallExpression(node) { const [firstArgument] = node.arguments; if (firstArgument) { const staticValue = getStaticValue(firstArgument, context.getScope()); const isStaticString = staticValue && typeof staticValue.value === "string"; const isString = isStaticString || isEvaluatedString(firstArgument); if (isString) { context.report({ node, messageId: "impliedEval" }); } } } /** * Reports calls of `implied eval` via the global references. * @param {Variable} globalVar A global variable to check. * @returns {void} */ function reportImpliedEvalViaGlobal(globalVar) { const { references, name } = globalVar; references.forEach(ref => { const identifier = ref.identifier; let node = identifier.parent; while (isSpecifiedMember(node, [name])) { node = node.parent; } if (isSpecifiedMember(node, EVAL_LIKE_FUNCS)) { const parent = node.parent; if (parent.type === "CallExpression" && parent.callee === node) { reportImpliedEvalCallExpression(parent); } } }); } //-------------------------------------------------------------------------- // Public //-------------------------------------------------------------------------- return { CallExpression(node) { if (isSpecifiedIdentifier(node.callee, EVAL_LIKE_FUNCS)) { reportImpliedEvalCallExpression(node); } }, "Program:exit"() { const globalScope = context.getScope(); GLOBAL_CANDIDATES .map(candidate => astUtils.getVariableByName(globalScope, candidate)) .filter(globalVar => !!globalVar && globalVar.defs.length === 0) .forEach(reportImpliedEvalViaGlobal); } }; } };
pvamshi/eslint
lib/rules/no-implied-eval.js
JavaScript
mit
5,435
/* --------------------------------------------------------------------------- Open Asset Import Library (ASSIMP) --------------------------------------------------------------------------- Copyright (c) 2006-2010, ASSIMP Development Team All rights reserved. Redistribution and use of this software 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 the ASSIMP team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the ASSIMP Development Team. 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. --------------------------------------------------------------------------- */ #include "stdafx.h" #include "assimp_view.h" #include "RichEdit.h" namespace AssimpView { /* extern */ CLogWindow CLogWindow::s_cInstance; extern HKEY g_hRegistry; // header for the RTF log file static const char* AI_VIEW_RTF_LOG_HEADER = "{\\rtf1" "\\ansi" "\\deff0" "{" "\\fonttbl{\\f0 Courier New;}" "}" "{\\colortbl;" "\\red255\\green0\\blue0;" // red for errors "\\red255\\green120\\blue0;" // orange for warnings "\\red0\\green150\\blue0;" // green for infos "\\red0\\green0\\blue180;" // blue for debug messages "\\red0\\green0\\blue0;" // black for everything else "}}"; //------------------------------------------------------------------------------- // Message procedure for the log window //------------------------------------------------------------------------------- INT_PTR CALLBACK LogDialogProc(HWND hwndDlg,UINT uMsg, WPARAM wParam,LPARAM lParam) { lParam; switch (uMsg) { case WM_INITDIALOG: { return TRUE; } case WM_SIZE: { int x = LOWORD(lParam); int y = HIWORD(lParam); SetWindowPos(GetDlgItem(hwndDlg,IDC_EDIT1),NULL,0,0, x-10,y-12,SWP_NOMOVE|SWP_NOZORDER); return TRUE; } case WM_CLOSE: EndDialog(hwndDlg,0); CLogWindow::Instance().bIsVisible = false; return TRUE; }; return FALSE; } //------------------------------------------------------------------------------- void CLogWindow::Init () { this->hwnd = ::CreateDialog(g_hInstance,MAKEINTRESOURCE(IDD_LOGVIEW), NULL,&LogDialogProc); if (!this->hwnd) { CLogDisplay::Instance().AddEntry("[ERROR] Unable to create logger window", D3DCOLOR_ARGB(0xFF,0,0xFF,0)); } // setup the log text this->szText = AI_VIEW_RTF_LOG_HEADER;; this->szPlainText = ""; } //------------------------------------------------------------------------------- void CLogWindow::Show() { if (this->hwnd) { ShowWindow(this->hwnd,SW_SHOW); this->bIsVisible = true; // contents aren't updated while the logger isn't displayed this->Update(); } } //------------------------------------------------------------------------------- void CMyLogStream::write(const char* message) { CLogWindow::Instance().WriteLine(message); } //------------------------------------------------------------------------------- void CLogWindow::Clear() { this->szText = AI_VIEW_RTF_LOG_HEADER;; this->szPlainText = ""; this->Update(); } //------------------------------------------------------------------------------- void CLogWindow::Update() { if (this->bIsVisible) { SETTEXTEX sInfo; sInfo.flags = ST_DEFAULT; sInfo.codepage = CP_ACP; SendDlgItemMessage(this->hwnd,IDC_EDIT1, EM_SETTEXTEX,(WPARAM)&sInfo,( LPARAM)this->szText.c_str()); } } //------------------------------------------------------------------------------- void CLogWindow::Save() { char szFileName[MAX_PATH]; DWORD dwTemp = MAX_PATH; if(ERROR_SUCCESS != RegQueryValueEx(g_hRegistry,"LogDestination",NULL,NULL, (BYTE*)szFileName,&dwTemp)) { // Key was not found. Use C: strcpy(szFileName,""); } else { // need to remove the file name char* sz = strrchr(szFileName,'\\'); if (!sz)sz = strrchr(szFileName,'/'); if (!sz)*sz = 0; } OPENFILENAME sFilename1 = { sizeof(OPENFILENAME), g_hDlg,GetModuleHandle(NULL), "Log files\0*.txt", NULL, 0, 1, szFileName, MAX_PATH, NULL, 0, NULL, "Save log to file", OFN_OVERWRITEPROMPT | OFN_HIDEREADONLY | OFN_NOCHANGEDIR, 0, 1, ".txt", 0, NULL, NULL }; if(GetSaveFileName(&sFilename1) == 0) return; // Now store the file in the registry RegSetValueExA(g_hRegistry,"LogDestination",0,REG_SZ,(const BYTE*)szFileName,MAX_PATH); FILE* pFile = fopen(szFileName,"wt"); fprintf(pFile,this->szPlainText.c_str()); fclose(pFile); CLogDisplay::Instance().AddEntry("[INFO] The log file has been saved", D3DCOLOR_ARGB(0xFF,0xFF,0xFF,0)); } //------------------------------------------------------------------------------- void CLogWindow::WriteLine(const char* message) { this->szPlainText.append(message); this->szPlainText.append("\r\n"); if (0 != this->szText.length()) { this->szText.resize(this->szText.length()-1); } switch (message[0]) { case 'e': case 'E': this->szText.append("{\\pard \\cf1 \\b \\fs18 "); break; case 'w': case 'W': this->szText.append("{\\pard \\cf2 \\b \\fs18 "); break; case 'i': case 'I': this->szText.append("{\\pard \\cf3 \\b \\fs18 "); break; case 'd': case 'D': this->szText.append("{\\pard \\cf4 \\b \\fs18 "); break; default: this->szText.append("{\\pard \\cf5 \\b \\fs18 "); break; } std::string _message = message; for (unsigned int i = 0; i < _message.length();++i) { if ('\\' == _message[i] || '}' == _message[i] || '{' == _message[i]) { _message.insert(i++,"\\"); } } this->szText.append(_message); this->szText.append("\\par}}"); if (this->bIsVisible && this->bUpdate) { SETTEXTEX sInfo; sInfo.flags = ST_DEFAULT; sInfo.codepage = CP_ACP; SendDlgItemMessage(this->hwnd,IDC_EDIT1, EM_SETTEXTEX,(WPARAM)&sInfo,( LPARAM)this->szText.c_str()); } return; } }; //! AssimpView
mtwilliams/mojo
dependencies/assimp-2.0.863/tools/assimp_view/LogWindow.cpp
C++
mit
6,958
module Tasklist end
chaimedes/HanamiTaskList
lib/tasklist.rb
Ruby
mit
20
<?php defined('BASEPATH') OR exit('No direct script access allowed'); /** * Library to generate items for Sortable.js */ class Sortable { protected $CI; protected $mItems; protected $mPostName = 'sortable_ids'; public function __construct() { $this->CI =& get_instance(); $this->CI->load->library('parser'); $this->CI->load->library('system_message'); } // Get items to be sorted public function init($model, $order_field = 'pos') { $this->CI->load->model($model, 'm'); $ids = $this->CI->input->post($this->mPostName); // save to database if ( !empty($ids) ) { for ($i=0; $i<count($ids); $i++) { $updated = $this->CI->m->update($ids[$i], array($order_field => $i+1)); } // refresh page (interrupt other logic) $this->CI->system_message->set_success('Successfully updated sort order.'); refresh(); } // return all records in sorted order $this->CI->db->order_by($order_field, 'ASC'); $items = $this->CI->m->get_all(); $this->mItems = $items; return $this; } // Render template public function render($label_template = '{title}', $back_url = NULL) { if ( empty($this->mItems) ) { return '<p>No records are found.</p>'; } else { $html = box_open('Sort Order', 'primary'); // Render form with alert message $html.= '<form action="'.current_url().'" method="POST">'; $html.= $this->CI->system_message->render(); $html.= '<p>Drag and drop below items to sort them in ascending order:</p>'; // Generate item list by CodeIgniter Template Parser $template = '<ul class="sortable list-group"> {items} <li class="list-group-item"> <strong>'.$label_template.'</strong> <input type="hidden" name="'.$this->mPostName.'[]" value="{id}" /> </li> {/items} </ul>'; $data = array('items' => $this->mItems); $html.= $this->CI->parser->parse_string($template, $data, TRUE); if ($back_url!=NULL) $html.= btn('Back', $back_url, 'reply', 'bg-purple').' '; $html.= btn_submit('Save'); $html.= '</form>'; $html.= box_close(); return $html; } } }
jiji262/codeigniter_boilerplate
application/modules/admin/libraries/Sortable.php
PHP
mit
2,088
import NodeFunction from '../core/NodeFunction.js'; import NodeFunctionInput from '../core/NodeFunctionInput.js'; const declarationRegexp = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i; const propertiesRegexp = /[a-z_0-9]+/ig; const pragmaMain = '#pragma main'; const parse = ( source ) => { const pragmaMainIndex = source.indexOf( pragmaMain ); const mainCode = pragmaMainIndex !== - 1 ? source.substr( pragmaMainIndex + pragmaMain.length ) : source; const declaration = mainCode.match( declarationRegexp ); if ( declaration !== null && declaration.length === 5 ) { // tokenizer const inputsCode = declaration[ 4 ]; const propsMatches = []; let nameMatch = null; while ( ( nameMatch = propertiesRegexp.exec( inputsCode ) ) !== null ) { propsMatches.push( nameMatch ); } // parser const inputs = []; let i = 0; while ( i < propsMatches.length ) { const isConst = propsMatches[ i ][ 0 ] === 'const'; if ( isConst === true ) { i ++; } let qualifier = propsMatches[ i ][ 0 ]; if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) { i ++; } else { qualifier = ''; } const type = propsMatches[ i ++ ][ 0 ]; let count = Number.parseInt( propsMatches[ i ][ 0 ] ); if ( Number.isNaN( count ) === false ) i ++; else count = null; const name = propsMatches[ i ++ ][ 0 ]; inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) ); } // const blockCode = mainCode.substring( declaration[ 0 ].length ); const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : ''; const type = declaration[ 2 ]; const presicion = declaration[ 1 ] !== undefined ? declaration[ 1 ] : ''; const headerCode = pragmaMainIndex !== - 1 ? source.substr( 0, pragmaMainIndex ) : ''; return { type, inputs, name, presicion, inputsCode, blockCode, headerCode }; } else { throw new Error( 'FunctionNode: Function is not a GLSL code.' ); } }; class GLSLNodeFunction extends NodeFunction { constructor( source ) { const { type, inputs, name, presicion, inputsCode, blockCode, headerCode } = parse( source ); super( type, inputs, name, presicion ); this.inputsCode = inputsCode; this.blockCode = blockCode; this.headerCode = headerCode; } getCode( name = this.name ) { const headerCode = this.headerCode; const presicion = this.presicion; let declarationCode = `${ this.type } ${ name } ( ${ this.inputsCode.trim() } )`; if ( presicion !== '' ) { declarationCode = `${ presicion } ${ declarationCode }`; } return headerCode + declarationCode + this.blockCode; } } export default GLSLNodeFunction;
jpweeks/three.js
examples/jsm/renderers/nodes/parsers/GLSLNodeFunction.js
JavaScript
mit
2,740
"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var core_1 = require('@angular/core'); var router_1 = require('@angular/router'); var app_service_1 = require("./app-service"); var AppComponent = (function () { function AppComponent(breadCrumbSvc, _router) { this.breadCrumbSvc = breadCrumbSvc; this._router = _router; this.breadCrumbSvc.setBreadCrumb('Project Dashboard'); } AppComponent.prototype.navigateHome = function () { this._router.navigate(['home']); ; }; AppComponent = __decorate([ core_1.Component({ selector: 'ts-app', templateUrl: '/app/app-component.html' }), __metadata('design:paramtypes', [app_service_1.BreadcrumbService, router_1.Router]) ], AppComponent); return AppComponent; }()); exports.AppComponent = AppComponent;
mail2yugi/ProjectTodoList
src/app/app.component.js
JavaScript
mit
1,606
using Feria_Desktop.View.Usuario; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace Feria_Desktop.View.Mantenedor { /// <summary> /// Lógica de interacción para Bodega.xaml /// </summary> public partial class Bodega : Page { private vEditarBodega modEditarBodega; public Bodega() { InitializeComponent(); } private void btnNuevo_Click(object sender, RoutedEventArgs e) { modEditarBodega = new vEditarBodega(); modEditarBodega.ShowDialog(); } } }
lagrantorre/PortafolioTItulo
Feria Desktop/Feria Desktop/View/Mantenedor/Bodega.xaml.cs
C#
mit
912
/** * Copies the values of `source` to `array`. * * @private * @param {Array} source The array to copy values from. * @param {Array} [array=[]] The array to copy values to. * @returns {Array} Returns `array`. */ function arrayCopy(source, array) { var index = -1, length = source.length; array || (array = Array(length)); while (++i < length) { array[i] = source[i]; } return array; } module.exports = arrayCopy;
gdgzdar/2048
node_modules/karma/node_modules/lodash/internal/arrayCopy.js
JavaScript
mit
442
package de.uni.bremen.stummk.psp.calculation; import java.lang.reflect.InvocationTargetException; import java.util.List; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.action.Action; import org.eclipse.jface.dialogs.ProgressMonitorDialog; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.actions.ActionFactory.IWorkbenchAction; import de.uni.bremen.stummk.psp.control.BarChart; import de.uni.bremen.stummk.psp.control.LineChart; import de.uni.bremen.stummk.psp.control.PieChart; import de.uni.bremen.stummk.psp.data.PSPProject; import de.uni.bremen.stummk.psp.data.ScheduleEntry; import de.uni.bremen.stummk.psp.utility.CheckOperation; import de.uni.bremen.stummk.psp.utility.Constants; import de.uni.bremen.stummk.psp.utility.DataIO; import de.uni.bremen.stummk.psp.utility.FileHash; /** * Class represents an action of the toolbar in the editor * * @author Konstantin * */ public class EditorToolbarAction extends Action implements IWorkbenchAction { private EditorToolbarController etc; /** * Constructor * * @param id the Id of the Action * @param editorToolbarController the {@link EditorToolbarController} of the * {@link EditorToolbarAction} */ public EditorToolbarAction(String id, EditorToolbarController editorToolbarController) { setId(id); this.etc = editorToolbarController; } @Override public void run() { handleAction(getId()); } private void handleAction(String id) { // execute action depending on id switch (id) { case Constants.COMMAND_SYNC: exportData(); break; case Constants.COMMAND_PLAN_ACTUAL_DIAGRAM: new BarChart(etc.getProjectPlanSummary(), "Plan vs. Actual Values - " + etc.getProjectPlanSummary().getProject().getProjectName()); break; case Constants.COMMAND_TIME_IN_PHASE_PERCENTAGE: new PieChart(etc.getProjectPlanSummary(), Constants.KEY_TIME_IN_PHASE_IDX, "Distribution of time in phase - " + etc.getProjectPlanSummary().getProject().getProjectName()); break; case Constants.COMMAND_DEFECT_INJECTED_PERCENTAGE: new PieChart(etc.getProjectPlanSummary(), Constants.KEY_DEFECTS_INJECTED_IDX, "Distribution of injected defects - " + etc.getProjectPlanSummary().getProject().getProjectName()); break; case Constants.COMMAND_DEFECT_REMOVED_PERCENTAGE: new PieChart(etc.getProjectPlanSummary(), Constants.KEY_DEFECTS_REMOVED_IDX, "Distribution of removed defects - " + etc.getProjectPlanSummary().getProject().getProjectName()); break; case Constants.COMMAND_TIME_TRACKING: List<ScheduleEntry> entries = Manager.getInstance().getSchedulePlanning(etc.getProjectPlanSummary().getProject().getProjectName()); new LineChart("Time Progress in Project - " + etc.getProjectPlanSummary().getProject().getProjectName(), Constants.CHART_TIME, entries); break; case Constants.COMMAND_EARNED_VALUE_TRACKING: List<ScheduleEntry> e = Manager.getInstance().getSchedulePlanning(etc.getProjectPlanSummary().getProject().getProjectName()); new LineChart("Earned Value Tracking in Project - " + etc.getProjectPlanSummary().getProject().getProjectName(), Constants.CHART_VALUE, e); break; } } private void exportData() { // exports data to psp-file and create hash try { Shell activeShell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(); IRunnableWithProgress op = new IRunnableWithProgress() { @Override public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try { monitor.beginTask("Export data to psp.csv file", 2); PSPProject psp = Manager.getInstance().loadBackupProject(etc.getProjectPlanSummary().getProject().getProjectName()); if (psp != null && psp.getSummary() != null) { DataIO.saveToFile(etc.getProjectPlanSummary().getProject().getProjectName(), psp, null); } monitor.worked(1); if (psp != null && psp.getSummary() != null) { IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects(); for (IProject project : projects) { if (project.getName().equals(etc.getProjectPlanSummary().getProject().getProjectName())) { IFile file = CheckOperation.getProjectFile(project); String hash = FileHash.hash(file); try { file.setPersistentProperty(Constants.PROPERTY_HASH, hash); } catch (CoreException e) { e.printStackTrace(); } } } } monitor.worked(1); } finally { monitor.done(); } } }; new ProgressMonitorDialog(activeShell).run(true, true, op); } catch (InvocationTargetException | InterruptedException e) { e.printStackTrace(); } } @Override public void dispose() {} }
stummk/psp-eclipse
Source/de.uni.bremen.stummk.psp/src/de/uni/bremen/stummk/psp/calculation/EditorToolbarAction.java
Java
mit
5,479
/// This is the sensor class /// /// Sensor is a box2d fixture that is attached to a parent body /// Sensors are used to detect entities in an area. #pragma once #include <AFP/Scene/SceneNode.hpp> #include <AFP/Entity/Entity.hpp> #include <AFP/Entity/Character.hpp> namespace AFP { class Sensor : public SceneNode { public: enum Type { Foot, Surround, Vision, Jump }; /// Constructor /// /// Sensor(Entity* parent, Type type); /// Return sensor category /// /// Returns the sensor category based on the type virtual unsigned int getCategory() const; /// Create foot sensor /// /// Creates a foot sensor on feet void createFootSensor(float sizeX, float sizeY); /// Create vision sensor /// /// Creates a vision sensor for the entity. ///Takes radius in meters and the angle in degrees as parameters void createVisionSensor(float radius, float angle); /// Create surround sensor /// /// Creates a foot sensor on feet void createSurroundSensor(float radius); /// Create foot sensor /// /// Creates a foot sensor on feet void createJumpSensor(float sizeX, float sizeY); /// Begin contact /// /// Begin contact with an entity void beginContact(); /// Begin contact /// /// Begin contact with an character void beginContact(Character& character); /// End contact /// /// End contact with an entity void endContact(); /// End contact /// /// End contact with a character void endContact(Character& character); private: /// Update /// /// Update sensor data. virtual void updateCurrent(sf::Time dt, CommandQueue& commands); private: /// Sensor fixture /// /// Sensors fixture is linked to the body of the parent. b2Fixture* mFixture; /// Parent entity /// /// Entity on which the sensor is attached to Entity* mParent; /// Type /// /// Type of the sensor Type mType; }; }
Pinqvin/afp-game
include/AFP/Entity/Sensor.hpp
C++
mit
2,350
package insanityradio.insanityradio; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; public class PlayPauseReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { try { FragmentNowPlaying.getInstance().playPauseButtonTapped(false); } catch (NullPointerException e) { Intent startActivityIntent = new Intent(context.getApplicationContext(), MainActivity.class); startActivityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(startActivityIntent); } } }
dylanmaryk/InsanityRadio-Android
app/src/main/java/insanityradio/insanityradio/PlayPauseReceiver.java
Java
mit
663
import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ['HERTZ_SECRET_KEY'] # SECURITY WARNING: don't run with debug turned on in production! DEBUG = os.environ['HERTZ_DEBUG'] != 'False' ALLOWED_HOSTS = ['*' if DEBUG else os.environ['HERTZ_HOST']] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'widget_tweaks', 'attendance', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'hertz.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates'), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'hertz.wsgi.application' # Database if 'DATABASE_HOST' in os.environ: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': os.environ['POSTGRES_USER'], 'PASSWORD': os.environ['POSTGRES_PASSWORD'], 'HOST': os.environ['DATABASE_HOST'], 'PORT': 5432, } } else: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization LANGUAGE_CODE = 'en-us' TIME_ZONE = 'America/Sao_Paulo' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') # STATICFILES_DIRS = [ # os.path.join(BASE_DIR, 'static'), # ] LOGIN_REDIRECT_URL = '/' LOGIN_URL = '/login'
seccom-ufsc/hertz
hertz/settings.py
Python
mit
3,237
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Robot - Robot")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Robot - Robot")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("960726e6-c6b1-4271-8c7e-94110f97ad98")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
phristov/CSharp.DesignPatterns
Builder - Robot/Properties/AssemblyInfo.cs
C#
mit
1,402
<?php /* FOSUserBundle:Resetting:request_content.html.twig */ class __TwigTemplate_16fccc8b4081822ba4c49543c44f48b24850d6b4ad9846152c39968be5b4e7c7 extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); $this->parent = false; $this->blocks = array( ); } protected function doDisplay(array $context, array $blocks = array()) { // line 2 echo " <form action=\""; // line 3 echo $this->env->getExtension('routing')->getPath("fos_user_resetting_send_email"); echo "\" method=\"POST\" class=\"fos_user_resetting_request\"> <div> "; // line 5 if (array_key_exists("invalid_username", $context)) { // line 6 echo " <p>"; echo twig_escape_filter($this->env, $this->env->getExtension('translator')->trans("resetting.request.invalid_username", array("%username%" => (isset($context["invalid_username"]) ? $context["invalid_username"] : $this->getContext($context, "invalid_username"))), "FOSUserBundle"), "html", null, true); echo "</p> "; } // line 8 echo " <label for=\"username\">"; echo twig_escape_filter($this->env, $this->env->getExtension('translator')->trans("resetting.request.username", array(), "FOSUserBundle"), "html", null, true); echo "</label> <input type=\"text\" id=\"username\" name=\"username\" required=\"required\" /> </div> <div> <input type=\"submit\" value=\""; // line 12 echo twig_escape_filter($this->env, $this->env->getExtension('translator')->trans("resetting.request.submit", array(), "FOSUserBundle"), "html", null, true); echo "\" /> </div> </form> "; } public function getTemplateName() { return "FOSUserBundle:Resetting:request_content.html.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 43 => 12, 35 => 8, 29 => 6, 27 => 5, 22 => 3, 19 => 2,); } }
thecoons/thecoontube
app/cache/dev/twig/16/fc/cc8b4081822ba4c49543c44f48b24850d6b4ad9846152c39968be5b4e7c7.php
PHP
mit
2,146
export default (callback) => { setTimeout(() => { callback(); setTimeout(() => { callback(); }, 3000); }, 3000); }
csxiaoyaojianxian/JavaScriptStudy
13-自动化测试&mock数据/01-jest入门/09-mock-timer.js
JavaScript
mit
158
import re import warnings import ctds from .base import TestExternalDatabase from .compat import PY3, PY36, unicode_ class TestTdsParameter(TestExternalDatabase): def test___doc__(self): self.assertEqual( ctds.Parameter.__doc__, '''\ Parameter(value, output=False) Explicitly define a parameter for :py:meth:`.callproc`, :py:meth:`.execute`, or :py:meth:`.executemany`. This is necessary to indicate whether a parameter is *SQL* `OUTPUT` or `INPUT/OUTPUT` parameter. :param object value: The parameter's value. :param bool output: Is the parameter an output parameter. ''' ) def test_parameter(self): param1 = ctds.Parameter(b'123', output=True) self.assertEqual(param1.value, b'123') self.assertTrue(isinstance(param1, ctds.Parameter)) param2 = ctds.Parameter(b'123') self.assertEqual(param1.value, b'123') self.assertEqual(type(param1), type(param2)) self.assertTrue(isinstance(param2, ctds.Parameter)) def test___repr__(self): for parameter, expected in ( ( ctds.Parameter(b'123', output=True), "ctds.Parameter(b'123', output=True)" if PY3 else "ctds.Parameter('123', output=True)" ), ( ctds.Parameter(unicode_('123'), output=False), "ctds.Parameter('123')" if PY3 else "ctds.Parameter(u'123')" ), ( ctds.Parameter(None), "ctds.Parameter(None)" ), ( ctds.Parameter(ctds.SqlVarBinary(b'4321', size=10)), "ctds.Parameter(ctds.SqlVarBinary(b'4321', size=10))" if PY3 else "ctds.Parameter(ctds.SqlVarBinary('4321', size=10))" ) ): self.assertEqual(repr(parameter), expected) def _test__cmp__(self, __cmp__, expected, oper): cases = ( (ctds.Parameter(b'1234'), ctds.Parameter(b'123')), (ctds.Parameter(b'123'), ctds.Parameter(b'123')), (ctds.Parameter(b'123'), ctds.Parameter(b'123', output=True)), (ctds.Parameter(b'123'), ctds.Parameter(b'1234')), (ctds.Parameter(b'123'), b'123'), (ctds.Parameter(b'123'), ctds.Parameter(123)), (ctds.Parameter(b'123'), unicode_('123')), (ctds.Parameter(b'123'), ctds.SqlBinary(None)), (ctds.Parameter(b'123'), 123), (ctds.Parameter(b'123'), None), ) for index, args in enumerate(cases): operation = '[{0}]: {1} {2} {3}'.format(index, repr(args[0]), oper, repr(args[1])) if expected[index] == TypeError: try: __cmp__(*args) except TypeError as ex: regex = ( r"'{0}' not supported between instances of '[^']+' and '[^']+'".format(oper) if not PY3 or PY36 else r'unorderable types: \S+ {0} \S+'.format(oper) ) self.assertTrue(re.match(regex, str(ex)), ex) else: self.fail('{0} did not fail as expected'.format(operation)) # pragma: nocover else: self.assertEqual(__cmp__(*args), expected[index], operation) def test___cmp__eq(self): self._test__cmp__( lambda left, right: left == right, ( False, True, True, False, True, False, not PY3, False, False, False, ), '==' ) def test___cmp__ne(self): self._test__cmp__( lambda left, right: left != right, ( True, False, False, True, False, True, PY3, True, True, True, ), '!=' ) def test___cmp__lt(self): self._test__cmp__( lambda left, right: left < right, ( False, False, False, True, False, TypeError if PY3 else False, TypeError if PY3 else False, TypeError if PY3 else False, TypeError if PY3 else False, TypeError if PY3 else False, ), '<' ) def test___cmp__le(self): self._test__cmp__( lambda left, right: left <= right, ( False, True, True, True, True, TypeError if PY3 else False, TypeError if PY3 else True, TypeError if PY3 else False, TypeError if PY3 else False, TypeError if PY3 else False, ), '<=' ) def test___cmp__gt(self): self._test__cmp__( lambda left, right: left > right, ( True, False, False, False, False, TypeError if PY3 else True, TypeError if PY3 else False, TypeError if PY3 else True, TypeError if PY3 else True, TypeError if PY3 else True, ), '>' ) def test___cmp__ge(self): self._test__cmp__( lambda left, right: left >= right, ( True, True, True, False, True, TypeError if PY3 else True, TypeError if PY3 else True, TypeError if PY3 else True, TypeError if PY3 else True, TypeError if PY3 else True, ), '>=' ) def test_typeerror(self): for case in (None, object(), 123, 'foobar'): self.assertRaises(TypeError, ctds.Parameter, case, b'123') self.assertRaises(TypeError, ctds.Parameter) self.assertRaises(TypeError, ctds.Parameter, output=False) for case in (None, object(), 123, 'foobar'): self.assertRaises(TypeError, ctds.Parameter, b'123', output=case) def test_reuse(self): with self.connect() as connection: with connection.cursor() as cursor: for value in ( None, 123456, unicode_('hello world'), b'some bytes', ): for output in (True, False): parameter = ctds.Parameter(value, output=output) for _ in range(0, 2): # Ignore warnings generated due to output parameters # used with result sets. with warnings.catch_warnings(record=True): cursor.execute( ''' SELECT :0 ''', (parameter,) ) self.assertEqual( [tuple(row) for row in cursor.fetchall()], [(value,)] )
zillow/ctds
tests/test_tds_parameter.py
Python
mit
7,779
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; namespace HolisticWare.Ph4ct3x.Server.Pages.Ph4ct3x.Communication { public class InstantMessagingChatModel : PageModel { public void OnGet() { } } }
moljac/Ph4ct3x
samples/Clients/HolisticWare.Ph4ct3x.Server.ASPnet.UI.RazorPages.shared/Pages/Ph4ct3x/Communication/InstantMessagingChat.cshtml.cs
C#
mit
361
#include "Renderer.h" #include "Core/Windows/Window.h" #include <Resources/ResourceCache.h> namespace uut { UUT_MODULE_IMPLEMENT(Renderer) {} Renderer::Renderer() : _screenSize(0) { } Renderer::~Renderer() { } ////////////////////////////////////////////////////////////////////////////// bool Renderer::OnInit() { if (!Super::OnInit()) return false; ModuleInstance<ResourceCache> cache; cache->AddResource(CreateMonoTexture(Color32::White), "white"); cache->AddResource(CreateMonoTexture(Color32::Black), "black"); return true; } void Renderer::OnDone() { } SharedPtr<Texture2D> Renderer::CreateMonoTexture(const Color32& color) { auto tex = CreateTexture(Vector2i(1), TextureAccess::Static); uint32_t* buf = static_cast<uint32_t*>(tex->Lock()); if (buf == nullptr) return nullptr; buf[0] = color.ToInt(); tex->Unlock(); return tex; } }
kolyden/uut-engine
UUT/Video/Renderer.cpp
C++
mit
896
package jnt.scimark2; public class kernel { // each measurement returns approx Mflops public static double measureFFT(int N, double mintime, Random R) { // initialize FFT data as complex (N real/img pairs) double x[] = RandomVector(2*N, R); double oldx[] = NewVectorCopy(x); long cycles = 1; Stopwatch Q = new Stopwatch(); while(true) { Q.start(); for (int i=0; i<cycles; i++) { FFT.transform(x); // forward transform FFT.inverse(x); // backward transform } Q.stop(); if (Q.read() >= mintime) break; cycles *= 2; } // approx Mflops final double EPS = 1.0e-10; if ( FFT.test(x) / N > EPS ) return 0.0; return FFT.num_flops(N)*cycles/ Q.read() * 1.0e-6; } // public static double measureSOR(int N, double min_time, Random R) // { // double G[][] = RandomMatrix(N, N, R); // // //Stopwatch Q = new Stopwatch(); // int cycles=1; // //while(true) // while(cycles <= 32768) // { // //Q.start(); // SOR.execute(1.25, G, cycles); // //Q.stop(); // //if (Q.read() >= min_time) break; // // cycles *= 2; // } // // approx Mflops // //return SOR.num_flops(N, N, cycles) / Q.read() * 1.0e-6; // return SOR.num_flops(N, N, cycles); // } public static double measureSOR(int N, double min_time, Random R) { double G[][] = RandomMatrix(N, N, R); int rep = 10; // 11s @ 594MHz //rep = 75; // 42.5s @ 1026MHz //rep = 150; // 68s @ 1026MHz, this just fully melts PCM, at end of benchmark //rep = 250; // 113s @ 1026MHz //rep = 300; // 126s @ 1026MHz, using this setting in my house, PCM melts fully rep = 75; // 75 short duration // 300 medium duration // 400 long duration int cycles = 2048; for (int i = 0; i < rep; i++) { SOR.execute(1.25, G, cycles); } return SOR.num_flops(N, N, cycles); } public static double measureMonteCarlo(double min_time, Random R) { Stopwatch Q = new Stopwatch(); int cycles=1; while(true) { Q.start(); MonteCarlo.integrate(cycles); Q.stop(); if (Q.read() >= min_time) break; cycles *= 2; } // approx Mflops return MonteCarlo.num_flops(cycles) / Q.read() * 1.0e-6; } public static double measureSparseMatmult(int N, int nz, double min_time, Random R) { // initialize vector multipliers and storage for result // y = A*y; double x[] = RandomVector(N, R); double y[] = new double[N]; // initialize square sparse matrix // // for this test, we create a sparse matrix wit M/nz nonzeros // per row, with spaced-out evenly between the begining of the // row to the main diagonal. Thus, the resulting pattern looks // like // +-----------------+ // +* + // +*** + // +* * * + // +** * * + // +** * * + // +* * * * + // +* * * * + // +* * * * + // +-----------------+ // // (as best reproducible with integer artihmetic) // Note that the first nr rows will have elements past // the diagonal. int nr = nz/N; // average number of nonzeros per row int anz = nr *N; // _actual_ number of nonzeros double val[] = RandomVector(anz, R); int col[] = new int[anz]; int row[] = new int[N+1]; row[0] = 0; for (int r=0; r<N; r++) { // initialize elements for row r int rowr = row[r]; row[r+1] = rowr + nr; int step = r/ nr; if (step < 1) step = 1; // take at least unit steps for (int i=0; i<nr; i++) col[rowr+i] = i*step; } //Stopwatch Q = new Stopwatch(); int cycles = 2048; //while(true) //while(cycles <= 65536) // about 20 seconds //while(cycles <= 1048576) // about 200 seconds int rep = 30; // 14 sec @ 594 for (int i = 0; i < rep; i++) { //Q.start(); SparseCompRow.matmult(y, val, row, col, x, cycles); //Q.stop(); //if (Q.read() >= min_time) break; //cycles *= 2; } // approx Mflops //return SparseCompRow.num_flops(N, nz, cycles) / Q.read() * 1.0e-6; return SparseCompRow.num_flops(N, nz, cycles); } public static double measureLU(int N, double min_time, Random R) { // compute approx Mlfops, or O if LU yields large errors double A[][] = RandomMatrix(N, N, R); double lu[][] = new double[N][N]; int pivot[] = new int[N]; //Stopwatch Q = new Stopwatch(); //while(true) //while (cycles <= 8192) //while (cycles <= 2048) // approx 20 sec //while (cycles <= 6144) // approx 30 sec @ 1242MHz //while (cycles <= 12288) // approx 60 sec @ 1242MHz //while (cycles <= 14336) // approx 70 sec @ 1242MHz //while (cycles <= 16384) // approx 80 sec @ 1242MHz int cycles = 2048; // 14 sec @ 594Hz for (int j = 0; j < cycles; j++) { //Q.start(); //for (int i=0; i<cycles; i++) //{ CopyMatrix(lu, A); LU.factor(lu, pivot); //} //Q.stop(); //if (Q.read() >= min_time) break; //cycles *= 2; } // verify that LU is correct double b[] = RandomVector(N, R); double x[] = NewVectorCopy(b); LU.solve(lu, pivot, x); final double EPS = 1.0e-12; if ( normabs(b, matvec(A,x)) / N > EPS ) return 0.0; // else return approx Mflops // //return LU.num_flops(N) * cycles / Q.read() * 1.0e-6; return LU.num_flops(N) * cycles; } private static double[] NewVectorCopy(double x[]) { int N = x.length; double y[] = new double[N]; for (int i=0; i<N; i++) y[i] = x[i]; return y; } private static void CopyVector(double B[], double A[]) { int N = A.length; for (int i=0; i<N; i++) B[i] = A[i]; } private static double normabs(double x[], double y[]) { int N = x.length; double sum = 0.0; for (int i=0; i<N; i++) sum += Math.abs(x[i]-y[i]); return sum; } public static void CopyMatrix(double B[][], double A[][]) { int M = A.length; int N = A[0].length; int remainder = N & 3; // N mod 4; for (int i=0; i<M; i++) { double Bi[] = B[i]; double Ai[] = A[i]; for (int j=0; j<remainder; j++) Bi[j] = Ai[j]; for (int j=remainder; j<N; j+=4) { Bi[j] = Ai[j]; Bi[j+1] = Ai[j+1]; Bi[j+2] = Ai[j+2]; Bi[j+3] = Ai[j+3]; } } } public static double[][] RandomMatrix(int M, int N, Random R) { double A[][] = new double[M][N]; for (int i=0; i<N; i++) for (int j=0; j<N; j++) A[i][j] = R.nextDouble(); return A; } public static double[] RandomVector(int N, Random R) { double A[] = new double[N]; for (int i=0; i<N; i++) A[i] = R.nextDouble(); return A; } private static double[] matvec(double A[][], double x[]) { int N = x.length; double y[] = new double[N]; matvec(A, x, y); return y; } private static void matvec(double A[][], double x[], double y[]) { int M = A.length; int N = A[0].length; for (int i=0; i<M; i++) { double sum = 0.0; double Ai[] = A[i]; for (int j=0; j<N; j++) sum += Ai[j] * x[j]; y[i] = sum; } } }
BU-PCM-Testbed/ThermalProfiler
app/src/main/java/jnt/scimark2/kernel.java
Java
mit
7,529
'use strict' const reduce = Function.bind.call(Function.call, Array.prototype.reduce); const isEnumerable = Function.bind.call(Function.call, Object.prototype.propertyIsEnumerable); const concat = Function.bind.call(Function.call, Array.prototype.concat); const keys = Reflect.ownKeys; if (!Object.values) { Object.values = (O) => reduce(keys(O), (v, k) => concat(v, typeof k === 'string' && isEnumerable(O, k) ? [O[k]] : []), []); } if (!Object.entries) { Object.entries = (O) => reduce(keys(O), (e, k) => concat(e, typeof k === 'string' && isEnumerable(O, k) ? [ [k, O[k]] ] : []), []); } //from //https://medium.com/@_jh3y/throttling-and-debouncing-in-javascript-b01cad5c8edf#.jlqokoxtu //or //https://remysharp.com/2010/07/21/throttling-function-calls function debounce(callback, delay) { let timeout; return function() { const context = this, args = arguments; clearTimeout(timeout); timeout = setTimeout(() => callback.apply(context, args), delay); }; }; function throttle(func, limit) { let inThrottle, lastFunc, throttleTimer; return function() { const context = this, args = arguments; if (inThrottle) { clearTimeout(lastFunc); return lastFunc = setTimeout(function() { func.apply(context, args); inThrottle = false; }, limit); } else { func.apply(context, args); inThrottle = true; return throttleTimer = setTimeout(() => inThrottle = false, limit); } }; }; /*END POLIFILL*/
vitaliiznak/game-fluky_colors
polifill.js
JavaScript
mit
1,634
class Admin::DashboardController < AdminAreaController def index #You are entering an area where no project is concerned, so forget about your current project session[:project] = nil end end
atoulme/collaboa-clone
app/controllers/admin/dashboard_controller.rb
Ruby
mit
207
<?php use History\Entities\Models\Company; use History\Entities\Models\Question; use History\Entities\Models\Request; use History\Entities\Models\Threads\Comment; use History\Entities\Models\Threads\Thread; use History\Entities\Models\User; use History\Entities\Models\Vote; use League\FactoryMuffin\FactoryMuffin; use League\FactoryMuffin\Faker\Facade; use League\FactoryMuffin\Faker\Faker; /* @var FactoryMuffin $fm */ /** @var Faker $faker */ $faker = Facade::instance(); if (!function_exists('random')) { /** * @param string $class * * @return Closure */ function random($class) { if (!$class::count()) { return 'factory|'.$class; } return function () use ($class) { return $class::pluck('id')->shuffle()->first(); }; } } $fm->define(User::class)->setDefinitions([ 'name' => $faker->userName(), 'full_name' => $faker->name(), 'email' => $faker->email(), 'contributions' => $faker->sentence(), 'company_id' => random(Company::class), 'no_votes' => $faker->randomNumber(1), 'yes_votes' => $faker->randomNumber(1), 'total_votes' => $faker->randomNumber(1), 'approval' => $faker->randomFloat(null, 0, 1), 'success' => $faker->randomFloat(null, 0, 1), 'hivemind' => $faker->randomFloat(null, 0, 1), 'created_at' => $faker->dateTimeThisYear(), 'updated_at' => $faker->dateTimeThisYear(), ]); $fm->define(Request::class)->setDefinitions([ 'name' => $faker->sentence(), 'contents' => $faker->paragraph(), 'link' => $faker->url(), 'condition' => $faker->boolean(2 / 3), 'approval' => $faker->randomFloat(null, 0, 1), 'status' => $faker->numberBetween(0, 5), 'created_at' => $faker->dateTimeThisDecade(), 'updated_at' => $faker->dateTimeThisDecade(), ])->setCallback(function (Request $request) { $users = User::pluck('id')->shuffle()->take(2); $request->authors()->sync($users->all()); }); $fm->define(Thread::class)->setDefinitions([ 'name' => $faker->sentence(), 'user_id' => random(User::class), 'request_id' => random(Request::class), 'created_at' => $faker->dateTimeThisDecade(), 'updated_at' => $faker->dateTimeThisDecade(), ]); $fm->define(Comment::class)->setDefinitions([ 'name' => $faker->sentence(), 'contents' => $faker->paragraph(), 'xref' => $faker->randomNumber(1), 'created_at' => $faker->dateTimeThisYear(), 'updated_at' => $faker->dateTimeThisYear(), 'user_id' => random(User::class), 'thread_id' => random(Thread::class), ]); $fm->define(Question::class)->setDefinitions([ 'name' => $faker->sentence(), 'choices' => ['Yes', 'No'], 'approval' => $faker->randomFloat(null, 0, 1), 'passed' => $faker->boolean(), 'request_id' => random(Request::class), 'created_at' => $faker->dateTimeThisYear(), 'updated_at' => $faker->dateTimeThisYear(), ]); $fm->define(Vote::class)->setDefinitions([ 'choice' => $faker->numberBetween(1, 2), 'question_id' => random(Question::class), 'user_id' => random(User::class), 'created_at' => $faker->dateTimeThisYear(), 'updated_at' => $faker->dateTimeThisYear(), ]); $fm->define(Company::class)->setDefinitions([ 'name' => $faker->word(), 'representation' => $faker->randomNumber(1), ]);
madewithlove/why-cant-we-have-nice-things
resources/factories/factories.php
PHP
mit
3,327
import {Routes} from '@angular/router'; import {JournalComponent} from '../journal/journal.component'; export const LUOO_APP_ROUTERS: Routes = [ {path: 'journal', component: JournalComponent} ]
Tneciv/Poseidon
frontend/src/app/common/routers.ts
TypeScript
mit
197
// This file is part of SWGANH which is released under the MIT license. // See file LICENSE or go to http://swganh.com/LICENSE #include "swganh_core/gamesystems/gamesystems_service_binding.h" BOOST_PYTHON_MODULE(py_gamesystems) { docstring_options local_docstring_options(true, true, false); exportGameSystemsService(); }
anhstudios/swganh
src/swganh_core/GameSystems/GameSystems_service_binding.cc
C++
mit
332
var htmlparser = require('htmlparser2'); var _ = require('lodash'); var ent = require('ent'); module.exports = sanitizeHtml; function sanitizeHtml(html, options) { var result = ''; if (!options) { options = sanitizeHtml.defaults; } else { _.defaults(options, sanitizeHtml.defaults); } // Tags that contain something other than HTML. If we are not allowing // these tags, we should drop their content too. For other tags you would // drop the tag but keep its content. var nonTextTagsMap = { script: true, style: true }; var allowedTagsMap = {}; _.each(options.allowedTags, function(tag) { allowedTagsMap[tag] = true; }); var selfClosingMap = {}; _.each(options.selfClosing, function(tag) { selfClosingMap[tag] = true; }); var allowedAttributesMap = {}; _.each(options.allowedAttributes, function(attributes, tag) { allowedAttributesMap[tag] = {}; _.each(attributes, function(name) { allowedAttributesMap[tag][name] = true; }); }); var depth = 0; var skipMap = {}; var skipText = false; var parser = new htmlparser.Parser({ onopentag: function(name, attribs) { var skip = false; if (!_.has(allowedTagsMap, name)) { skip = true; if (_.has(nonTextTagsMap, name)) { skipText = true; } skipMap[depth] = true; } depth++; if (skip) { // We want the contents but not this tag return; } result += '<' + name; if (_.has(allowedAttributesMap, name)) { _.each(attribs, function(value, a) { if (_.has(allowedAttributesMap[name], a)) { result += ' ' + a; if ((a === 'href') || (a === 'src')) { if (naughtyHref(value)) { return; } } if (value.length) { // Values are ALREADY escaped, calling escapeHtml here // results in double escapes result += '="' + value + '"'; } } }); } if (_.has(selfClosingMap, name)) { result += " />"; } else { result += ">"; } }, ontext: function(text) { if (skipText) { return; } // It is NOT actually raw text, entities are already escaped. // If we call escapeHtml here we wind up double-escaping. result += text; }, onclosetag: function(name) { skipText = false; depth--; if (skipMap[depth]) { delete skipMap[depth]; return; } if (_.has(selfClosingMap, name)) { // Already output /> return; } result += "</" + name + ">"; } }); parser.write(html); parser.end(); return result; function escapeHtml(s) { if (s === 'undefined') { s = ''; } if (typeof(s) !== 'string') { s = s + ''; } return s.replace(/\&/g, '&amp;').replace(/</g, '&lt;').replace(/\>/g, '&gt;').replace(/\"/g, '&quot;'); } function naughtyHref(href) { // So we don't get faked out by a hex or decimal escaped javascript URL #1 href = ent.decode(href); // Browsers ignore character codes of 32 (space) and below in a surprising // number of situations. Start reading here: // https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet#Embedded_tab href = href.replace(/[\x00-\x20]+/, ''); // Case insensitive so we don't get faked out by JAVASCRIPT #1 var matches = href.match(/^([a-zA-Z]+)\:/); if (!matches) { // No scheme = no way to inject js (right?) return false; } var scheme = matches[1].toLowerCase(); return (!_.contains(['http', 'https', 'ftp', 'mailto' ], scheme)); } } // Defaults are accessible to you so that you can use them as a starting point // programmatically if you wish sanitizeHtml.defaults = { allowedTags: [ 'h3', 'h4', 'h5', 'h6', 'blockquote', 'p', 'a', 'ul', 'ol', 'nl', 'li', 'b', 'i', 'strong', 'em', 'strike', 'code', 'hr', 'br', 'div', 'table', 'thead', 'caption', 'tbody', 'tr', 'th', 'td', 'pre' ], allowedAttributes: { a: [ 'href', 'name', 'target' ], // We don't currently allow img itself by default, but this // would make sense if we did img: [ 'src' ] }, // Lots of these won't come up by default because we don't allow them selfClosing: [ 'img', 'br', 'hr', 'area', 'base', 'basefont', 'input', 'link', 'meta' ] };
effello/cms
node_modules/apostrophe/node_modules/sanitize-html/index.js
JavaScript
mit
4,431
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { ExtendComponent } from './src/components/extend.component'; import { SubExtendComponent } from './src/components/sub-extend.component'; const extendRoutes: Routes = [ { path: '', component: ExtendComponent, }, { path: 'main', component: ExtendComponent, }, { path: 'sub', component: SubExtendComponent }, ]; @NgModule({ imports: [ RouterModule.forChild(extendRoutes) ], exports: [ RouterModule ] }) export class ExtendRoutingModule {}
seveves/ng2-lib-test
@lib-test/extend/extend.routes.ts
TypeScript
mit
595
(function(){ 'use strict' angular .module("jobDetail") .service("jobDetailService",jobDetailService); jobDetailService.$inject = ['apiService','apiOptions']; function jobDetailService(apiService,apiOptions) { var jobId; this.getJobDetail=function(jobId) { // return "ok"; return apiService.get("job/"+jobId); }; }; })();
dozgunyal/ang-oboy
app/job-detail/job-detail.service.js
JavaScript
mit
351
/** * Copyright MaDgIK Group 2010 - 2015. */ package madgik.exareme.worker.art.container.job; import madgik.exareme.worker.art.container.ContainerJob; import madgik.exareme.worker.art.container.ContainerJobType; import madgik.exareme.worker.art.executionEngine.session.PlanSessionReportID; /** * @author heraldkllapi */ public class TableTransferJob implements ContainerJob { public final PlanSessionReportID sessionReportID; public TableTransferJob(PlanSessionReportID sessionReportID) { this.sessionReportID = sessionReportID; } @Override public ContainerJobType getType() { return ContainerJobType.dataTransfer; } }
madgik/exareme
Exareme-Docker/src/exareme/exareme-worker/src/main/java/madgik/exareme/worker/art/container/job/TableTransferJob.java
Java
mit
667
<?xml version="1.0" ?><!DOCTYPE TS><TS language="pt_BR" version="2.0"> <defaultcodec>UTF-8</defaultcodec> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About SwansonCoin</source> <translation>Sobre o SwansonCoin</translation> </message> <message> <location line="+39"/> <source>&lt;b&gt;SwansonCoin&lt;/b&gt; version</source> <translation>Versão do &lt;b&gt;SwansonCoin&lt;/b&gt;</translation> </message> <message> <location line="+57"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source> <translation>⏎ Este é um software experimental.⏎ ⏎ Distribuido sob a licença de software MIT/X11, veja o arquivo anexo COPYING ou http://www.opensource.org/licenses/mit-license.php.⏎ ⏎ Este produto inclui software desenvolvido pelo Projeto OpenSSL para uso no OpenSSL Toolkit (http://www.openssl.org/), software de criptografia escrito por Eric Young (eay@cryptsoft.com) e sofware UPnP escrito por Thomas Bernard.</translation> </message> <message> <location filename="../aboutdialog.cpp" line="+14"/> <source>Copyright</source> <translation>Copyright</translation> </message> <message> <location line="+0"/> <source>The SwansonCoin developers</source> <translation>Desenvolvedores do SwansonCoin</translation> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation>Catálogo de endereços</translation> </message> <message> <location line="+19"/> <source>Double-click to edit address or label</source> <translation>Clique duas vezes para editar o endereço ou o etiqueta</translation> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>Criar um novo endereço</translation> </message> <message> <location line="+14"/> <source>Copy the currently selected address to the system clipboard</source> <translation>Copie o endereço selecionado para a área de transferência do sistema</translation> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation>&amp;Novo endereço</translation> </message> <message> <location filename="../addressbookpage.cpp" line="+63"/> <source>These are your SwansonCoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation>Estes são os seus endereços SwansonCoin para receber pagamentos. Você pode querer enviar um endereço diferente para cada remetente, para acompanhar quem está pagando.</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>&amp;Copy Address</source> <translation>&amp;Copiar Endereço</translation> </message> <message> <location line="+11"/> <source>Show &amp;QR Code</source> <translation>Mostrar &amp;QR Code</translation> </message> <message> <location line="+11"/> <source>Sign a message to prove you own a SwansonCoin address</source> <translation>Assine uma mensagem para provar que você é dono de um endereço SwansonCoin</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation>&amp;Assinar Mensagem</translation> </message> <message> <location line="+25"/> <source>Delete the currently selected address from the list</source> <translation>Excluir os endereços selecionados da lista</translation> </message> <message> <location line="+27"/> <source>Export the data in the current tab to a file</source> <translation>Exportar os dados na aba atual para um arquivo</translation> </message> <message> <location line="+3"/> <source>&amp;Export</source> <translation>&amp;Exportar</translation> </message> <message> <location line="-44"/> <source>Verify a message to ensure it was signed with a specified SwansonCoin address</source> <translation>Verificar mensagem para se assegurar que ela foi assinada pelo dono de um endereço SwansonCoin específico.</translation> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation>&amp;Verificar Mensagem</translation> </message> <message> <location line="+14"/> <source>&amp;Delete</source> <translation>&amp;Excluir</translation> </message> <message> <location filename="../addressbookpage.cpp" line="-5"/> <source>These are your SwansonCoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation>Estes são os seus endereços SwansonCoin para receber pagamentos. Você pode querer enviar um endereço diferente para cada remetente, para acompanhar quem está pagando.</translation> </message> <message> <location line="+13"/> <source>Copy &amp;Label</source> <translation>Copiar &amp;Etiqueta</translation> </message> <message> <location line="+1"/> <source>&amp;Edit</source> <translation>&amp;Editar</translation> </message> <message> <location line="+1"/> <source>Send &amp;Coins</source> <translation>Enviar bit&amp;coins</translation> </message> <message> <location line="+260"/> <source>Export Address Book Data</source> <translation>Exportar Catálogo de Endereços</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Arquivo separado por vírgulas (*. csv)</translation> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation>Erro ao exportar</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Não foi possível gravar no arquivo %1.</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+144"/> <source>Label</source> <translation>Rótulo</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Endereço</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(Sem rótulo)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation>Janela da Frase de Segurança</translation> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>Digite a frase de segurança</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>Nova frase de segurança</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>Repita a nova frase de segurança</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+33"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation>Digite a nova frase de seguraça da sua carteira. &lt;br/&gt; Por favor, use uma frase de &lt;b&gt;10 ou mais caracteres aleatórios,&lt;/b&gt; ou &lt;b&gt;oito ou mais palavras.&lt;/b&gt;</translation> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation>Criptografar carteira</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>Esta operação precisa de sua frase de segurança para desbloquear a carteira.</translation> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>Desbloquear carteira</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>Esta operação precisa de sua frase de segurança para descriptografar a carteira.</translation> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation>Descriptografar carteira</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>Alterar frase de segurança</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>Digite a frase de segurança antiga e nova para a carteira.</translation> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation>Confirmar criptografia da carteira</translation> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR SWANSONCOINS&lt;/b&gt;!</source> <translation>Aviso: Se você criptografar sua carteira e perder sua senha, você vai &lt;b&gt;perder todos os seus SWANSONCOINS!&lt;/b&gt;</translation> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation>Tem certeza de que deseja criptografar sua carteira?</translation> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation>IMPORTANTE: Qualquer backup prévio que você tenha feito do seu arquivo wallet deve ser substituído pelo novo e encriptado arquivo wallet gerado. Por razões de segurança, qualquer backup do arquivo wallet não criptografado se tornará inútil assim que você começar a usar uma nova carteira criptografada.</translation> </message> <message> <location line="+100"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation>Cuidado: A tecla Caps Lock está ligada!</translation> </message> <message> <location line="-130"/> <location line="+58"/> <source>Wallet encrypted</source> <translation>Carteira criptografada</translation> </message> <message> <location line="-56"/> <source>SwansonCoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your swansoncoins from being stolen by malware infecting your computer.</source> <translation>O SwansonCoin irá fechar agora para finalizar o processo de encriptação. Lembre-se de que encriptar sua carteira não protege totalmente suas swansoncoins de serem roubadas por malwares que tenham infectado o seu computador.</translation> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+42"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>A criptografia da carteira falhou</translation> </message> <message> <location line="-54"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>A criptografia da carteira falhou devido a um erro interno. Sua carteira não estava criptografada.</translation> </message> <message> <location line="+7"/> <location line="+48"/> <source>The supplied passphrases do not match.</source> <translation>A frase de segurança fornecida não confere.</translation> </message> <message> <location line="-37"/> <source>Wallet unlock failed</source> <translation>A abertura da carteira falhou</translation> </message> <message> <location line="+1"/> <location line="+11"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>A frase de segurança digitada para a descriptografia da carteira estava incorreta.</translation> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation>A descriptografia da carteira falhou</translation> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation>A frase de segurança da carteira foi alterada com êxito.</translation> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+233"/> <source>Sign &amp;message...</source> <translation>&amp;Assinar Mensagem...</translation> </message> <message> <location line="+280"/> <source>Synchronizing with network...</source> <translation>Sincronizando com a rede...</translation> </message> <message> <location line="-349"/> <source>&amp;Overview</source> <translation>&amp;Visão geral</translation> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation>Mostrar visão geral da carteira</translation> </message> <message> <location line="+20"/> <source>&amp;Transactions</source> <translation>&amp;Transações</translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>Navegar pelo histórico de transações</translation> </message> <message> <location line="+7"/> <source>Edit the list of stored addresses and labels</source> <translation>Editar a lista de endereços e rótulos</translation> </message> <message> <location line="-14"/> <source>Show the list of addresses for receiving payments</source> <translation>Mostrar a lista de endereços para receber pagamentos</translation> </message> <message> <location line="+31"/> <source>E&amp;xit</source> <translation>S&amp;air</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>Sair da aplicação</translation> </message> <message> <location line="+4"/> <source>Show information about SwansonCoin</source> <translation>Mostrar informação sobre SwansonCoin</translation> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation>Sobre &amp;Qt</translation> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation>Mostrar informações sobre o Qt</translation> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>&amp;Opções...</translation> </message> <message> <location line="+6"/> <source>&amp;Encrypt Wallet...</source> <translation>&amp;Criptografar Carteira...</translation> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation>&amp;Backup Carteira...</translation> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation>&amp;Mudar frase de segurança...</translation> </message> <message> <location line="+285"/> <source>Importing blocks from disk...</source> <translation>Importando blocos do disco...</translation> </message> <message> <location line="+3"/> <source>Reindexing blocks on disk...</source> <translation>Reindexando blocos no disco...</translation> </message> <message> <location line="-347"/> <source>Send coins to a SwansonCoin address</source> <translation>Enviar moedas para um endereço swansoncoin</translation> </message> <message> <location line="+49"/> <source>Modify configuration options for SwansonCoin</source> <translation>Modificar opções de configuração para swansoncoin</translation> </message> <message> <location line="+9"/> <source>Backup wallet to another location</source> <translation>Fazer cópia de segurança da carteira para uma outra localização</translation> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation>Mudar a frase de segurança utilizada na criptografia da carteira</translation> </message> <message> <location line="+6"/> <source>&amp;Debug window</source> <translation>Janela de &amp;Depuração</translation> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation>Abrir console de depuração e diagnóstico</translation> </message> <message> <location line="-4"/> <source>&amp;Verify message...</source> <translation>&amp;Verificar mensagem...</translation> </message> <message> <location line="-165"/> <location line="+530"/> <source>SwansonCoin</source> <translation>SwansonCoin</translation> </message> <message> <location line="-530"/> <source>Wallet</source> <translation>Carteira</translation> </message> <message> <location line="+101"/> <source>&amp;Send</source> <translation>&amp;Enviar</translation> </message> <message> <location line="+7"/> <source>&amp;Receive</source> <translation>&amp;Receber</translation> </message> <message> <location line="+14"/> <source>&amp;Addresses</source> <translation>&amp;Endereços</translation> </message> <message> <location line="+22"/> <source>&amp;About SwansonCoin</source> <translation>&amp;Sobre o SwansonCoin</translation> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation>&amp;Exibir/Ocultar</translation> </message> <message> <location line="+1"/> <source>Show or hide the main Window</source> <translation>Mostrar ou esconder a Janela Principal.</translation> </message> <message> <location line="+3"/> <source>Encrypt the private keys that belong to your wallet</source> <translation>Criptografar as chaves privadas que pertencem à sua carteira</translation> </message> <message> <location line="+7"/> <source>Sign messages with your SwansonCoin addresses to prove you own them</source> <translation>Assine mensagems com seus endereços SwansonCoin para provar que você é dono deles</translation> </message> <message> <location line="+2"/> <source>Verify messages to ensure they were signed with specified SwansonCoin addresses</source> <translation>Verificar mensagens para se assegurar que elas foram assinadas pelo dono de Endereços SwansonCoin específicos</translation> </message> <message> <location line="+28"/> <source>&amp;File</source> <translation>&amp;Arquivo</translation> </message> <message> <location line="+7"/> <source>&amp;Settings</source> <translation>&amp;Configurações</translation> </message> <message> <location line="+6"/> <source>&amp;Help</source> <translation>&amp;Ajuda</translation> </message> <message> <location line="+9"/> <source>Tabs toolbar</source> <translation>Barra de ferramentas</translation> </message> <message> <location line="+17"/> <location line="+10"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> <message> <location line="+47"/> <source>SwansonCoin client</source> <translation>Cliente SwansonCoin</translation> </message> <message numerus="yes"> <location line="+141"/> <source>%n active connection(s) to SwansonCoin network</source> <translation><numerusform>%n conexão ativa na rede SwansonCoin</numerusform><numerusform>%n conexões ativas na rede SwansonCoin</numerusform></translation> </message> <message> <location line="+22"/> <source>No block source available...</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Processed %1 of %2 (estimated) blocks of transaction history.</source> <translation>Processado %1 de %2 blocos (estimado) de histórico de transações.</translation> </message> <message> <location line="+4"/> <source>Processed %1 blocks of transaction history.</source> <translation>Processado %1 blocos do histórico de transações.</translation> </message> <message numerus="yes"> <location line="+20"/> <source>%n hour(s)</source> <translation><numerusform>%n hora</numerusform><numerusform>%n horas</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation><numerusform>%n dia</numerusform><numerusform>%n dias</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n week(s)</source> <translation><numerusform>%n semana</numerusform><numerusform>%n semanas</numerusform></translation> </message> <message> <location line="+4"/> <source>%1 behind</source> <translation>%1 atrás</translation> </message> <message> <location line="+14"/> <source>Last received block was generated %1 ago.</source> <translation>Último bloco recebido foi gerado %1 atrás.</translation> </message> <message> <location line="+2"/> <source>Transactions after this will not yet be visible.</source> <translation>Transações após isso ainda não estão visíveis.</translation> </message> <message> <location line="+22"/> <source>Error</source> <translation>Erro</translation> </message> <message> <location line="+3"/> <source>Warning</source> <translation>Cuidado</translation> </message> <message> <location line="+3"/> <source>Information</source> <translation>Informação</translation> </message> <message> <location line="+70"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation>A transação está acima do tamanho limite. Você ainda enviar ela com uma taxa de %1, que vai para os nós processam sua transação e ajuda a manter a rede. Você quer pagar a taxa?</translation> </message> <message> <location line="-140"/> <source>Up to date</source> <translation>Atualizado</translation> </message> <message> <location line="+31"/> <source>Catching up...</source> <translation>Recuperando o atraso ...</translation> </message> <message> <location line="+113"/> <source>Confirm transaction fee</source> <translation>Confirmar taxa de transação</translation> </message> <message> <location line="+8"/> <source>Sent transaction</source> <translation>Transação enviada</translation> </message> <message> <location line="+0"/> <source>Incoming transaction</source> <translation>Transação recebida</translation> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>Data: %1 Quantidade: %2 Tipo: %3 Endereço: %4</translation> </message> <message> <location line="+33"/> <location line="+23"/> <source>URI handling</source> <translation>Manipulação de URI</translation> </message> <message> <location line="-23"/> <location line="+23"/> <source>URI can not be parsed! This can be caused by an invalid SwansonCoin address or malformed URI parameters.</source> <translation>URI não pode ser decodificado! Isso pode ter sido causado por um endereço SwansonCoin inválido ou por parâmetros URI malformados.</translation> </message> <message> <location line="+17"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>Carteira está &lt;b&gt;criptografada&lt;/b&gt; e atualmente &lt;b&gt;desbloqueada&lt;/b&gt;</translation> </message> <message> <location line="+8"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>Carteira está &lt;b&gt;criptografada&lt;/b&gt; e atualmente &lt;b&gt;bloqueada&lt;/b&gt;</translation> </message> <message> <location filename="../bitcoin.cpp" line="+111"/> <source>A fatal error occurred. SwansonCoin can no longer continue safely and will quit.</source> <translation>Um erro fatal ocorreu. SwansonCoin não pode continuar em segurança e irá fechar.</translation> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+104"/> <source>Network Alert</source> <translation>Alerta da Rede</translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation>Editar Endereço</translation> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation>&amp;Etiqueta</translation> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation>A etiqueta associada a esse endereço do catálogo</translation> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation>&amp;Endereço</translation> </message> <message> <location line="+10"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation>O endereço associado à essa entrada do seu catálogo de endereços. Isso só pode ser modificado para endereço de envio.</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="+21"/> <source>New receiving address</source> <translation>Novo endereço de recebimento</translation> </message> <message> <location line="+4"/> <source>New sending address</source> <translation>Novo endereço de envio</translation> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation>Editar endereço de recebimento</translation> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation>Editar endereço de envio</translation> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>O endereço digitado &quot;%1&quot; já se encontra no catálogo de endereços.</translation> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid SwansonCoin address.</source> <translation>O endereço digitado &quot;%1&quot; não é um endereço SwansonCoin válido.</translation> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation>Não foi possível destravar a carteira.</translation> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation>A geração de nova chave falhou.</translation> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+424"/> <location line="+12"/> <source>SwansonCoin-Qt</source> <translation>SwansonCoin-Qt</translation> </message> <message> <location line="-12"/> <source>version</source> <translation>versão</translation> </message> <message> <location line="+2"/> <source>Usage:</source> <translation>Uso:</translation> </message> <message> <location line="+1"/> <source>command-line options</source> <translation>opções da linha de comando</translation> </message> <message> <location line="+4"/> <source>UI options</source> <translation>opções da UI</translation> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation>Escolher língua, por exemplo &quot;de_DE&quot; (padrão: localização do sistema)</translation> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation>Inicializar minimizado</translation> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation>Mostrar tela inicial ao ligar (padrão: 1)</translation> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation>Opções</translation> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation>Principal</translation> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation>Pagar taxa de &amp;transação</translation> </message> <message> <location line="+31"/> <source>Automatically start SwansonCoin after logging in to the system.</source> <translation>Iniciar SwansonCoin automaticamente após se logar no sistema.</translation> </message> <message> <location line="+3"/> <source>&amp;Start SwansonCoin on system login</source> <translation>Iniciar SwansonCoin no login do sistema</translation> </message> <message> <location line="+35"/> <source>Reset all client options to default.</source> <translation>Redefinir todas as opções do cliente para opções padrão.</translation> </message> <message> <location line="+3"/> <source>&amp;Reset Options</source> <translation>&amp;Redefinir opções</translation> </message> <message> <location line="+13"/> <source>&amp;Network</source> <translation>Rede</translation> </message> <message> <location line="+6"/> <source>Automatically open the SwansonCoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation>Abrir as portas do cliente SwansonCoin automaticamente no roteador. Isto só funcionará se seu roteador suportar UPnP e esta função estiver habilitada.</translation> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation>Mapear porta usando &amp;UPnP</translation> </message> <message> <location line="+7"/> <source>Connect to the SwansonCoin network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation>Conectar à rede SwansonCoin através de um proxy SOCKS (ex. quando estiver usando através do Tor)</translation> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation>&amp;Conectar através de um proxy SOCKS:</translation> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation>&amp;IP do proxy:</translation> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation>Endereço &amp;IP do proxy (ex. 127.0.0.1)</translation> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation>&amp;Porta:</translation> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation>Porta do serviço de proxy (ex. 9050)</translation> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation>&amp;Versão do SOCKS:</translation> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation>Versão do proxy SOCKS (ex. 5)</translation> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation>&amp;Janela</translation> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation>Mostrar apenas um ícone na bandeja ao minimizar a janela.</translation> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation>&amp;Minimizar para a bandeja em vez da barra de tarefas.</translation> </message> <message> <location line="+7"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation>Minimizar em vez de sair do aplicativo quando a janela for fechada. Quando esta opção é escolhida, o aplicativo só será fechado selecionando Sair no menu Arquivo.</translation> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation>M&amp;inimizar ao sair</translation> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation>&amp;Mostrar</translation> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation>&amp;Língua da interface com usuário:</translation> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting SwansonCoin.</source> <translation>A língua da interface com usuário pode ser escolhida aqui. Esta configuração só surtirá efeito após reiniciar o SwansonCoin.</translation> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation>&amp;Unidade usada para mostrar quantidades:</translation> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation>Escolha a unidade padrão de subdivisão para interface mostrar quando enviar swansoncoins.</translation> </message> <message> <location line="+9"/> <source>Whether to show SwansonCoin addresses in the transaction list or not.</source> <translation>Mostrar ou não endereços SwansonCoin na lista de transações.</translation> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation>Mostrar en&amp;dereços na lista de transações</translation> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation>&amp;OK</translation> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation>&amp;Cancelar</translation> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation>&amp;Aplicar</translation> </message> <message> <location filename="../optionsdialog.cpp" line="+53"/> <source>default</source> <translation>padrão</translation> </message> <message> <location line="+130"/> <source>Confirm options reset</source> <translation>Confirmar redefinição de opções</translation> </message> <message> <location line="+1"/> <source>Some settings may require a client restart to take effect.</source> <translation>Algumas configurações requerem reinicialização para surtirem efeito.</translation> </message> <message> <location line="+0"/> <source>Do you want to proceed?</source> <translation>Você quer continuar?</translation> </message> <message> <location line="+42"/> <location line="+9"/> <source>Warning</source> <translation>Cuidado</translation> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting SwansonCoin.</source> <translation>Esta configuração surtirá efeito após reinicializar o aplicativo SwansonCoin</translation> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation>O endereço proxy fornecido é inválido.</translation> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation>Formulário</translation> </message> <message> <location line="+50"/> <location line="+166"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the SwansonCoin network after a connection is established, but this process has not completed yet.</source> <translation>A informação mostrada pode estar desatualizada. Sua carteira sincroniza automaticamente com a rede SwansonCoin depois que a conexão é estabelecida, mas este processo pode não estar completo ainda.</translation> </message> <message> <location line="-124"/> <source>Balance:</source> <translation>Saldo:</translation> </message> <message> <location line="+29"/> <source>Unconfirmed:</source> <translation>Não confirmadas:</translation> </message> <message> <location line="-78"/> <source>Wallet</source> <translation>Carteira</translation> </message> <message> <location line="+107"/> <source>Immature:</source> <translation>Imaturo:</translation> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation>Saldo minerado que ainda não maturou</translation> </message> <message> <location line="+46"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;Transações recentes&lt;/b&gt;</translation> </message> <message> <location line="-101"/> <source>Your current balance</source> <translation>Seu saldo atual</translation> </message> <message> <location line="+29"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation>Total de transações ainda não confirmadas, e que ainda não contam no saldo atual</translation> </message> <message> <location filename="../overviewpage.cpp" line="+116"/> <location line="+1"/> <source>out of sync</source> <translation>fora de sincronia</translation> </message> </context> <context> <name>PaymentServer</name> <message> <location filename="../paymentserver.cpp" line="+107"/> <source>Cannot start swansoncoin: click-to-pay handler</source> <translation>Não foi possível iniciar swansoncoin: manipulador clique-para-pagar</translation> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation>Janela do código QR</translation> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation>Requisitar Pagamento</translation> </message> <message> <location line="+56"/> <source>Amount:</source> <translation>Quantia:</translation> </message> <message> <location line="-44"/> <source>Label:</source> <translation>Etiqueta:</translation> </message> <message> <location line="+19"/> <source>Message:</source> <translation>Mensagem:</translation> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation>&amp;Salvar como...</translation> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation>Erro ao codigicar o URI em código QR</translation> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation>A quantidade digitada é inválida, favor verificar.</translation> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation>URI resultante muito longa. Tente reduzir o texto do rótulo ou da mensagem.</translation> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation>Salvar código QR</translation> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation>Imagens PNG (*.png)</translation> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation>Nome do cliente</translation> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <location line="+23"/> <location filename="../rpcconsole.cpp" line="+339"/> <source>N/A</source> <translation>N/A</translation> </message> <message> <location line="-217"/> <source>Client version</source> <translation>Versão do cliente</translation> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation>&amp;Informação</translation> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation>Usando OpenSSL versão</translation> </message> <message> <location line="+49"/> <source>Startup time</source> <translation>Horário de inicialização</translation> </message> <message> <location line="+29"/> <source>Network</source> <translation>Rede</translation> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation>Número de conexões</translation> </message> <message> <location line="+23"/> <source>On testnet</source> <translation>Na rede de teste</translation> </message> <message> <location line="+23"/> <source>Block chain</source> <translation>Corrente de blocos</translation> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation>Quantidade atual de blocos</translation> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation>Total estimado de blocos</translation> </message> <message> <location line="+23"/> <source>Last block time</source> <translation>Horário do último bloco</translation> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation>&amp;Abrir</translation> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation>Opções da linha de comando</translation> </message> <message> <location line="+7"/> <source>Show the SwansonCoin-Qt help message to get a list with possible SwansonCoin command-line options.</source> <translation>Mostrar mensagem de ajuda do SwansonCoin-Qt para obter uma lista com possíveis opções da linha de comando do SwansonCoin.</translation> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation>&amp;Mostrar</translation> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation>&amp;Console</translation> </message> <message> <location line="-260"/> <source>Build date</source> <translation>Data do &apos;build&apos;</translation> </message> <message> <location line="-104"/> <source>SwansonCoin - Debug window</source> <translation>SwansonCoin - Janela de Depuração</translation> </message> <message> <location line="+25"/> <source>SwansonCoin Core</source> <translation>Núcleo SwansonCoin</translation> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation>Arquivo de log de Depuração</translation> </message> <message> <location line="+7"/> <source>Open the SwansonCoin debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation>Abrir o arquivo de log de depuração do SwansonCoin do diretório atual de dados. Isso pode levar alguns segundos para arquivos de log grandes.</translation> </message> <message> <location line="+102"/> <source>Clear console</source> <translation>Limpar console</translation> </message> <message> <location filename="../rpcconsole.cpp" line="-30"/> <source>Welcome to the SwansonCoin RPC console.</source> <translation>Bem-vindo ao console SwansonCoin RPC.</translation> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation>Use as setas para cima e para baixo para navegar pelo histórico, e &lt;b&gt;Ctrl-L&lt;/b&gt; para limpar a tela.</translation> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation>Digite &lt;b&gt;help&lt;/b&gt; para uma visão geral dos comandos disponíveis.</translation> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+124"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation>Enviar dinheiro</translation> </message> <message> <location line="+50"/> <source>Send to multiple recipients at once</source> <translation>Enviar para vários destinatários de uma só vez</translation> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation>Adicionar destinatário</translation> </message> <message> <location line="+20"/> <source>Remove all transaction fields</source> <translation>Remover todos os campos da transação</translation> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation>Limpar Tudo</translation> </message> <message> <location line="+22"/> <source>Balance:</source> <translation>Saldo:</translation> </message> <message> <location line="+10"/> <source>123.456 BTC</source> <translation>123.456 BTC</translation> </message> <message> <location line="+31"/> <source>Confirm the send action</source> <translation>Confirmar o envio</translation> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation>Enviar</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-59"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation>&lt;b&gt;%1&lt;/b&gt; para %2 (%3)</translation> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation>Confirmar envio de dinheiro</translation> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation>Você tem certeza que deseja enviar %1?</translation> </message> <message> <location line="+0"/> <source> and </source> <translation>e</translation> </message> <message> <location line="+23"/> <source>The recipient address is not valid, please recheck.</source> <translation>O endereço do destinatário não é válido, favor verificar.</translation> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation>A quantidade a ser paga precisa ser maior que 0.</translation> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation>A quantidade excede seu saldo.</translation> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation>O total excede seu saldo quando uma taxa de transação de %1 é incluída.</translation> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation>Endereço duplicado: pode-se enviar para cada endereço apenas uma vez por transação.</translation> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed!</source> <translation>Erro: Criação da transação falhou!</translation> </message> <message> <location line="+5"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation>Erro: A transação foi rejeitada. Isso pode acontecer se alguns dos swansoncoins de sua carteira já haviam sido gastos, por exemplo se você usou uma cópia do arquivo wallet.dat e alguns swansoncoins foram gastos na cópia mas não foram marcados como gastos aqui.</translation> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation>Formulário</translation> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation>Q&amp;uantidade:</translation> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation>Pagar &amp;Para:</translation> </message> <message> <location line="+34"/> <source>The address to send the payment to (e.g. RC74svrUSLCmjPGQrc4sYvAxzse7tpA7hE)</source> <translation>O endereço para onde enviar o pagamento (ex. RC74svrUSLCmjPGQrc4sYvAxzse7tpA7hE)</translation> </message> <message> <location line="+60"/> <location filename="../sendcoinsentry.cpp" line="+26"/> <source>Enter a label for this address to add it to your address book</source> <translation>Digite uma etiqueta para este endereço para adicioná-lo ao catálogo de endereços</translation> </message> <message> <location line="-78"/> <source>&amp;Label:</source> <translation>&amp;Etiqueta:</translation> </message> <message> <location line="+28"/> <source>Choose address from address book</source> <translation>Escolha um endereço do seu catálogo</translation> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation>Colar o endereço da área de transferência</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+7"/> <source>Remove this recipient</source> <translation>Remover este destinatário</translation> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a SwansonCoin address (e.g. RC74svrUSLCmjPGQrc4sYvAxzse7tpA7hE)</source> <translation>Digite um endereço SwansonCoin (exemplo: RC74svrUSLCmjPGQrc4sYvAxzse7tpA7hE)</translation> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation>Assinaturas - Assinar / Verificar uma mensagem</translation> </message> <message> <location line="+13"/> <source>&amp;Sign Message</source> <translation>&amp;Assinar Mensagem</translation> </message> <message> <location line="+6"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation>Você pode assinar mensagens com seus endereços para provar que você é o dono deles. Seja cuidadoso para não assinar algo vago, pois ataques de pishing podem tentar te enganar para dar sua assinatura de identidade para eles. Apenas assine afirmações completamente detalhadas com as quais você concorda.</translation> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. RC74svrUSLCmjPGQrc4sYvAxzse7tpA7hE)</source> <translation>Endereço a ser usado para assinar a mensagem (e.g. RC74svrUSLCmjPGQrc4sYvAxzse7tpA7hE)</translation> </message> <message> <location line="+10"/> <location line="+213"/> <source>Choose an address from the address book</source> <translation>Escolha um endereço do catálogo</translation> </message> <message> <location line="-203"/> <location line="+213"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="-203"/> <source>Paste address from clipboard</source> <translation>Colar o endereço da área de transferência</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation>Entre a mensagem que você quer assinar aqui</translation> </message> <message> <location line="+7"/> <source>Signature</source> <translation>Assinatura</translation> </message> <message> <location line="+27"/> <source>Copy the current signature to the system clipboard</source> <translation>Copiar a assinatura para a área de transferência do sistema</translation> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this SwansonCoin address</source> <translation>Assinar mensagem para provar que você é dono deste endereço SwansonCoin</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation>Assinar &amp;Mensagem</translation> </message> <message> <location line="+14"/> <source>Reset all sign message fields</source> <translation>Limpar todos os campos de assinatura da mensagem</translation> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation>Limpar Tudo</translation> </message> <message> <location line="-87"/> <source>&amp;Verify Message</source> <translation>&amp;Verificar Mensagem</translation> </message> <message> <location line="+6"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation>Forneça o endereço da assinatura, a mensagem (se assegure que você copiou quebras de linha, espaços, tabs, etc. exatamente) e a assinatura abaixo para verificar a mensagem. Cuidado para não ler mais na assinatura do que está escrito na mensagem propriamente, para evitar ser vítima de uma ataque do tipo &quot;man-in-the-middle&quot;.</translation> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. RC74svrUSLCmjPGQrc4sYvAxzse7tpA7hE)</source> <translation>O endereço usado para assinar a mensagem (ex. RC74svrUSLCmjPGQrc4sYvAxzse7tpA7hE)</translation> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified SwansonCoin address</source> <translation>Verificar mensagem para se assegurar que ela foi assinada pelo dono de um endereço SwansonCoin específico.</translation> </message> <message> <location line="+3"/> <source>Verify &amp;Message</source> <translation>Verificar %Mensagem</translation> </message> <message> <location line="+14"/> <source>Reset all verify message fields</source> <translation>Limpar todos os campos de assinatura da mensagem</translation> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a SwansonCoin address (e.g. RC74svrUSLCmjPGQrc4sYvAxzse7tpA7hE)</source> <translation>Digite um endereço SwansonCoin (exemplo: RC74svrUSLCmjPGQrc4sYvAxzse7tpA7hE)</translation> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation>Clique em &quot;Assinar Mensagem&quot; para gerar a assinatura</translation> </message> <message> <location line="+3"/> <source>Enter SwansonCoin signature</source> <translation>Entre com a assinatura SwansonCoin</translation> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation>O endereço fornecido é inválido.</translation> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation>Por favor, verifique o endereço e tente novamente.</translation> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation>O endereço fornecido não se refere a uma chave.</translation> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation>Destravamento da Carteira foi cancelado.</translation> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation>A chave privada para o endereço fornecido não está disponível.</translation> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation>Assinatura da mensagem falhou.</translation> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation>Mensagem assinada.</translation> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation>A assinatura não pode ser decodificada.</translation> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation>Por favor, verifique a assinatura e tente novamente.</translation> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation>A assinatura não corresponde ao &quot;resumo da mensagem&quot;.</translation> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation>Verificação da mensagem falhou.</translation> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation>Mensagem verificada.</translation> </message> </context> <context> <name>SplashScreen</name> <message> <location filename="../splashscreen.cpp" line="+22"/> <source>The SwansonCoin developers</source> <translation>Desenvolvedores do SwansonCoin</translation> </message> <message> <location line="+1"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+20"/> <source>Open until %1</source> <translation>Aberto até %1</translation> </message> <message> <location line="+6"/> <source>%1/offline</source> <translation>%1/offline</translation> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation>%1/não confirmadas</translation> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation>%1 confirmações</translation> </message> <message> <location line="+18"/> <source>Status</source> <translation>Status</translation> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation><numerusform>, difundir atráves de %n nó</numerusform><numerusform>, difundir atráves de %n nós</numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>Data</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation>Fonte</translation> </message> <message> <location line="+0"/> <source>Generated</source> <translation>Gerados</translation> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation>De</translation> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation>Para</translation> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation>seu próprio endereço</translation> </message> <message> <location line="-2"/> <source>label</source> <translation>etiqueta</translation> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation>Crédito</translation> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation><numerusform>matura em mais %n bloco</numerusform><numerusform>matura em mais %n blocos</numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation>não aceito</translation> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation>Débito</translation> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation>Taxa de transação</translation> </message> <message> <location line="+16"/> <source>Net amount</source> <translation>Valor líquido</translation> </message> <message> <location line="+6"/> <source>Message</source> <translation>Mensagem</translation> </message> <message> <location line="+2"/> <source>Comment</source> <translation>Comentário</translation> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation>ID da transação</translation> </message> <message> <location line="+3"/> <source>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation>SwansonCoins gerados precisam maturar por 120 blocos antes de serem gastos. Quando você gera este bloco, ele é difundido na rede para ser adicionado ao blockchain. Se ele falhar ao ser acrescentado no blockchain, seu estado mudará para &quot;não aceito&quot; e não poderá ser gasto. Isso pode ocasionamente acontecer se outro nó gerou um bloco poucos segundos antes do seu.</translation> </message> <message> <location line="+7"/> <source>Debug information</source> <translation>Informação de depuração</translation> </message> <message> <location line="+8"/> <source>Transaction</source> <translation>Transação</translation> </message> <message> <location line="+3"/> <source>Inputs</source> <translation>Entradas</translation> </message> <message> <location line="+23"/> <source>Amount</source> <translation>Quantidade</translation> </message> <message> <location line="+1"/> <source>true</source> <translation>verdadeiro</translation> </message> <message> <location line="+0"/> <source>false</source> <translation>falso</translation> </message> <message> <location line="-209"/> <source>, has not been successfully broadcast yet</source> <translation>, ainda não foi propagada na rede com sucesso.</translation> </message> <message numerus="yes"> <location line="-35"/> <source>Open for %n more block(s)</source> <translation><numerusform>Abrir para mais %n bloco</numerusform><numerusform>Abrir para mais %n blocos</numerusform></translation> </message> <message> <location line="+70"/> <source>unknown</source> <translation>desconhecido</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation>Detalhes da transação</translation> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation>Este painel mostra uma descrição detalhada da transação</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+225"/> <source>Date</source> <translation>Data</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation>Tipo</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Endereço</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>Quantidade</translation> </message> <message numerus="yes"> <location line="+57"/> <source>Open for %n more block(s)</source> <translation><numerusform>Abrir para mais %n bloco</numerusform><numerusform>Abrir para mais %n blocos</numerusform></translation> </message> <message> <location line="+3"/> <source>Open until %1</source> <translation>Aberto até %1</translation> </message> <message> <location line="+3"/> <source>Offline (%1 confirmations)</source> <translation>Offline (%1 confirmações)</translation> </message> <message> <location line="+3"/> <source>Unconfirmed (%1 of %2 confirmations)</source> <translation>Não confirmado (%1 of %2 confirmações)</translation> </message> <message> <location line="+3"/> <source>Confirmed (%1 confirmations)</source> <translation>Confirmado (%1 confirmações)</translation> </message> <message numerus="yes"> <location line="+8"/> <source>Mined balance will be available when it matures in %n more block(s)</source> <translation><numerusform>Saldo minerado vai estar disponível quando ele maturar em mais %n bloco</numerusform><numerusform>Saldo minerado vai estar disponível quando ele maturar em mais %n blocos</numerusform></translation> </message> <message> <location line="+5"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>Este bloco não foi recebido por nenhum outro participante da rede e provavelmente não será aceito!</translation> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation>Gerado mas não aceito</translation> </message> <message> <location line="+43"/> <source>Received with</source> <translation>Recebido por</translation> </message> <message> <location line="+2"/> <source>Received from</source> <translation>Recebido de</translation> </message> <message> <location line="+3"/> <source>Sent to</source> <translation>Enviado para</translation> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation>Pagamento para você mesmo</translation> </message> <message> <location line="+2"/> <source>Mined</source> <translation>Minerado</translation> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation>(n/a)</translation> </message> <message> <location line="+199"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>Status da transação. Passe o mouse sobre este campo para mostrar o número de confirmações.</translation> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation>Data e hora em que a transação foi recebida.</translation> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation>Tipo de transação.</translation> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation>Endereço de destino da transação.</translation> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation>Quantidade debitada ou creditada ao saldo.</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+52"/> <location line="+16"/> <source>All</source> <translation>Todos</translation> </message> <message> <location line="-15"/> <source>Today</source> <translation>Hoje</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation>Esta semana</translation> </message> <message> <location line="+1"/> <source>This month</source> <translation>Este mês</translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>Mês passado</translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>Este ano</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation>Intervalo...</translation> </message> <message> <location line="+11"/> <source>Received with</source> <translation>Recebido por</translation> </message> <message> <location line="+2"/> <source>Sent to</source> <translation>Enviado para</translation> </message> <message> <location line="+2"/> <source>To yourself</source> <translation>Para você mesmo</translation> </message> <message> <location line="+1"/> <source>Mined</source> <translation>Minerado</translation> </message> <message> <location line="+1"/> <source>Other</source> <translation>Outro</translation> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation>Procure um endereço ou etiqueta</translation> </message> <message> <location line="+7"/> <source>Min amount</source> <translation>Quantidade mínima</translation> </message> <message> <location line="+34"/> <source>Copy address</source> <translation>Copiar endereço</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>Copiar etiqueta</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>Copiar quantia</translation> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation>Copiar ID da transação</translation> </message> <message> <location line="+1"/> <source>Edit label</source> <translation>Editar etiqueta</translation> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation>Mostrar detalhes da transação</translation> </message> <message> <location line="+139"/> <source>Export Transaction Data</source> <translation>Exportar Dados das Transações</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Arquivo separado por vírgulas (*. csv)</translation> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation>Confirmado</translation> </message> <message> <location line="+1"/> <source>Date</source> <translation>Data</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation>Tipo</translation> </message> <message> <location line="+1"/> <source>Label</source> <translation>Etiqueta</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>Endereço</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation>Quantidade</translation> </message> <message> <location line="+1"/> <source>ID</source> <translation>ID</translation> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation>Erro ao exportar</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Não foi possível gravar no arquivo %1.</translation> </message> <message> <location line="+100"/> <source>Range:</source> <translation>Intervalo: </translation> </message> <message> <location line="+8"/> <source>to</source> <translation>para</translation> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+193"/> <source>Send Coins</source> <translation>Send Coins</translation> </message> </context> <context> <name>WalletView</name> <message> <location filename="../walletview.cpp" line="+42"/> <source>&amp;Export</source> <translation>&amp;Exportar</translation> </message> <message> <location line="+1"/> <source>Export the data in the current tab to a file</source> <translation>Exportar os dados na aba atual para um arquivo</translation> </message> <message> <location line="+193"/> <source>Backup Wallet</source> <translation>Fazer cópia de segurança da Carteira</translation> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation>Dados da Carteira (*.dat)</translation> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation>Cópia de segurança Falhou</translation> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation>Houve um erro ao tentar salvar os dados da carteira para uma nova localização.</translation> </message> <message> <location line="+4"/> <source>Backup Successful</source> <translation>Backup feito com sucesso</translation> </message> <message> <location line="+0"/> <source>The wallet data was successfully saved to the new location.</source> <translation>Os dados da carteira foram salvos com sucesso na nova localização</translation> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+94"/> <source>SwansonCoin version</source> <translation>Versão do SwansonCoin</translation> </message> <message> <location line="+102"/> <source>Usage:</source> <translation>Uso:</translation> </message> <message> <location line="-29"/> <source>Send command to -server or swansoncoind</source> <translation>Enviar comando para -server ou swansoncoind</translation> </message> <message> <location line="-23"/> <source>List commands</source> <translation>Lista de comandos</translation> </message> <message> <location line="-12"/> <source>Get help for a command</source> <translation>Obtenha ajuda sobre um comando</translation> </message> <message> <location line="+24"/> <source>Options:</source> <translation>Opções:</translation> </message> <message> <location line="+24"/> <source>Specify configuration file (default: swansoncoin.conf)</source> <translation>Especifique um arquivo de configurações (padrão: swansoncoin.conf)</translation> </message> <message> <location line="+3"/> <source>Specify pid file (default: swansoncoind.pid)</source> <translation>Especifique um arquivo de pid (padrão: swansoncoind.pid)</translation> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation>Especificar diretório de dados</translation> </message> <message> <location line="-9"/> <source>Set database cache size in megabytes (default: 25)</source> <translation>Definir o tamanho do cache do banco de dados em megabytes (padrão: 25)</translation> </message> <message> <location line="-28"/> <source>Listen for connections on &lt;port&gt; (default: 9333 or testnet: 19333)</source> <translation>Procurar por conexões em &lt;port&gt; (padrão: 9333 ou testnet:19333)</translation> </message> <message> <location line="+5"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>Manter no máximo &lt;n&gt; conexões aos peers (padrão: 125)</translation> </message> <message> <location line="-48"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation>Conectar a um nó para receber endereços de participantes, e desconectar.</translation> </message> <message> <location line="+82"/> <source>Specify your own public address</source> <translation>Especificar seu próprio endereço público</translation> </message> <message> <location line="+3"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation>Limite para desconectar peers mal comportados (padrão: 100)</translation> </message> <message> <location line="-134"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation>Número de segundos para impedir que peers mal comportados reconectem (padrão: 86400)</translation> </message> <message> <location line="-29"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation>Um erro ocorreu ao configurar a porta RPC %u para escuta em IPv4: %s</translation> </message> <message> <location line="+27"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 9332 or testnet: 19332)</source> <translation>Escutar conexões JSON-RPC na porta &lt;porta&gt; (padrão: 9332 ou testnet: 19332)</translation> </message> <message> <location line="+37"/> <source>Accept command line and JSON-RPC commands</source> <translation>Aceitar linha de comando e comandos JSON-RPC</translation> </message> <message> <location line="+76"/> <source>Run in the background as a daemon and accept commands</source> <translation>Rodar em segundo plano como serviço e aceitar comandos</translation> </message> <message> <location line="+37"/> <source>Use the test network</source> <translation>Usar rede de teste</translation> </message> <message> <location line="-112"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation>Aceitar conexões externas (padrão: 1 se opções -proxy ou -connect não estiverem presentes)</translation> </message> <message> <location line="-80"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=swansoncoinrpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;SwansonCoin Alert&quot; admin@foo.com </source> <translation>%s, você deve especificar uma senha rpcpassword no arquivo de configuração:⏎ %s⏎ É recomendado que você use a seguinte senha aleatória:⏎ rpcuser=swansoncoinrpc⏎ rpcpassword=%s⏎ (você não precisa lembrar esta senha)⏎ O nome de usuário e a senha NÃO PODEM ser os mesmos.⏎ Se o arquivo não existir, crie um com permissão de leitura apenas para o dono.⏎ É recomendado também definir um alertnotify para que você seja notificado de problemas;⏎ por exemplo: alertnotify=echo %%s | mail -s &quot;SwansonCoin Alert&quot; admin@foo.com⏎ </translation> </message> <message> <location line="+17"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation>Um erro ocorreu ao configurar a porta RPC %u para escuta em IPv6, voltando ao IPv4: %s</translation> </message> <message> <location line="+3"/> <source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source> <translation>Vincular ao endereço fornecido e sempre escutar nele. Use a notação [host]:port para IPv6</translation> </message> <message> <location line="+3"/> <source>Cannot obtain a lock on data directory %s. SwansonCoin is probably already running.</source> <translation>Não foi possível obter exclusividade de escrita no endereço %s. O SwansonCoin provavelmente já está rodando.</translation> </message> <message> <location line="+3"/> <source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation>Erro: A transação foi rejeitada. Isso pode acontecer se alguns dos swansoncoins de sua carteira já haviam sido gastos, por exemplo se você usou uma cópia do arquivo wallet.dat e alguns swansoncoins foram gastos na cópia mas não foram marcados como gastos aqui.</translation> </message> <message> <location line="+4"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source> <translation>Erro: Esta transação requer uma taxa de transação de pelo menos %s, por causa sua quantidade, complexidade ou uso de dinheiro recebido recentemente.</translation> </message> <message> <location line="+3"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation>Executar comando quando um alerta relevante for recebido (%s no comando será substituído pela mensagem)</translation> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation>Executar comando quando uma transação da carteira mudar (%s no comando será substituído por TxID)</translation> </message> <message> <location line="+11"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation>Determinar tamanho máximo de transações de alta-prioridade/baixa-taxa em bytes (padrão: 27000)</translation> </message> <message> <location line="+6"/> <source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source> <translation>Este pode ser um build de teste pré-lançamento - use por sua conta e risco - não use para mineração ou aplicações de comércio.</translation> </message> <message> <location line="+5"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation>Cuidado: valor de -paytxfee escolhido é muito alto! Este é o valor da taxa de transação que você irá pagar se enviar a transação.</translation> </message> <message> <location line="+3"/> <source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source> <translation>Cuidado: Transações mostradas podem não estar corretas! Você pode precisar atualizar, ou outros nós podem precisar atualizar o cliente.</translation> </message> <message> <location line="+3"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong SwansonCoin will not work properly.</source> <translation>Cuidado: Por favor, verifique que a data e hora do seu computador estão corretas! If o seu relógio estiver errado, o SwansonCoin não irá funcionar corretamente.</translation> </message> <message> <location line="+3"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation>Cuidado: erro ao ler arquivo wallet.dat! Todas as chaves foram lidas corretamente, mas dados transações e do catálogo de endereços podem estar faltando ou estar incorretas.</translation> </message> <message> <location line="+3"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation>Aviso: wallet.dat corrompido, dados recuperados! Arquivo wallet.dat original salvo como wallet.{timestamp}.bak em %s; se seu saldo ou transações estiverem incorretos, você deve restauras o backup.</translation> </message> <message> <location line="+14"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation>Tentar recuperar chaves privadas de um arquivo wallet.dat corrompido</translation> </message> <message> <location line="+2"/> <source>Block creation options:</source> <translation>Opções de criação de blocos:</translation> </message> <message> <location line="+5"/> <source>Connect only to the specified node(s)</source> <translation>Conectar apenas a nó(s) específico(s)</translation> </message> <message> <location line="+3"/> <source>Corrupted block database detected</source> <translation>Detectado Banco de dados de blocos corrompido</translation> </message> <message> <location line="+1"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation>Descobrir os próprios endereços IP (padrão: 1 quando no modo listening e opção -externalip não estiver presente)</translation> </message> <message> <location line="+1"/> <source>Do you want to rebuild the block database now?</source> <translation>Você quer reconstruir o banco de dados de blocos agora?</translation> </message> <message> <location line="+2"/> <source>Error initializing block database</source> <translation>Erro ao inicializar banco de dados de blocos</translation> </message> <message> <location line="+1"/> <source>Error initializing wallet database environment %s!</source> <translation>Erro ao inicializar ambiente de banco de dados de carteira %s!</translation> </message> <message> <location line="+1"/> <source>Error loading block database</source> <translation>Erro ao carregar banco de dados de blocos</translation> </message> <message> <location line="+4"/> <source>Error opening block database</source> <translation>Erro ao abrir banco de dados de blocos</translation> </message> <message> <location line="+2"/> <source>Error: Disk space is low!</source> <translation>Erro: Espaço em disco insuficiente!</translation> </message> <message> <location line="+1"/> <source>Error: Wallet locked, unable to create transaction!</source> <translation>Erro: Carteira travada, impossível criar transação!</translation> </message> <message> <location line="+1"/> <source>Error: system error: </source> <translation>Erro: erro de sistema</translation> </message> <message> <location line="+1"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation>Falha ao escutar em qualquer porta. Use -listen=0 se você quiser isso.</translation> </message> <message> <location line="+1"/> <source>Failed to read block info</source> <translation>Falha ao ler informação de bloco</translation> </message> <message> <location line="+1"/> <source>Failed to read block</source> <translation>Falha ao ler bloco</translation> </message> <message> <location line="+1"/> <source>Failed to sync block index</source> <translation>Falha ao sincronizar índice de blocos</translation> </message> <message> <location line="+1"/> <source>Failed to write block index</source> <translation>Falha ao escrever índice de blocos</translation> </message> <message> <location line="+1"/> <source>Failed to write block info</source> <translation>Falha ao escrever informações de bloco</translation> </message> <message> <location line="+1"/> <source>Failed to write block</source> <translation>Falha ao escrever bloco</translation> </message> <message> <location line="+1"/> <source>Failed to write file info</source> <translation>Falha ao escrever informções de arquivo</translation> </message> <message> <location line="+1"/> <source>Failed to write to coin database</source> <translation>Falha ao escrever banco de dados de moedas</translation> </message> <message> <location line="+1"/> <source>Failed to write transaction index</source> <translation>Falha ao escrever índice de transações</translation> </message> <message> <location line="+1"/> <source>Failed to write undo data</source> <translation>Falha ao escrever dados para desfazer ações</translation> </message> <message> <location line="+2"/> <source>Find peers using DNS lookup (default: 1 unless -connect)</source> <translation>Procurar pares usando consulta de DNS (padrão: 1 a menos que a opção -connect esteja presente)</translation> </message> <message> <location line="+1"/> <source>Generate coins (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 288, 0 = all)</source> <translation>Quantos blocos checar ao inicializar (padrão: 288, 0 = todos)</translation> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-4, default: 3)</source> <translation>Quão minuciosa é a verificação dos blocos (0-4, padrão: 3)</translation> </message> <message> <location line="+19"/> <source>Not enough file descriptors available.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Rebuild block chain index from current blk000??.dat files</source> <translation>Reconstruir índice de blockchain a partir dos arquivos atuais blk000??.dat</translation> </message> <message> <location line="+16"/> <source>Set the number of threads to service RPC calls (default: 4)</source> <translation>Defina o número de threads de script de verificação. (Padrão: 4)</translation> </message> <message> <location line="+26"/> <source>Verifying blocks...</source> <translation>Verificando blocos...</translation> </message> <message> <location line="+1"/> <source>Verifying wallet...</source> <translation>Verificando carteira...</translation> </message> <message> <location line="-69"/> <source>Imports blocks from external blk000??.dat file</source> <translation>Importar blocos de um arquivo externo blk000??.dat</translation> </message> <message> <location line="-76"/> <source>Set the number of script verification threads (up to 16, 0 = auto, &lt;0 = leave that many cores free, default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+77"/> <source>Information</source> <translation>Informação</translation> </message> <message> <location line="+3"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation>Endereço -tor inválido: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount for -minrelaytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount for -mintxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Maintain a full transaction index (default: 0)</source> <translation>Manter índice completo de transações (padrão: 0)</translation> </message> <message> <location line="+2"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation>Buffer máximo de recebimento por conexão, &lt;n&gt;*1000 bytes (padrão: 5000)</translation> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation>Buffer máximo de envio por conexão, &lt;n&gt;*1000 bytes (padrão: 1000)</translation> </message> <message> <location line="+2"/> <source>Only accept block chain matching built-in checkpoints (default: 1)</source> <translation>Apenas aceitar cadeia de blocos correspondente a marcas de verificação internas (padrão: 1)</translation> </message> <message> <location line="+1"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation>Apenas conectar em nós na rede &lt;net&gt; (IPv4, IPv6, ou Tor)</translation> </message> <message> <location line="+2"/> <source>Output extra debugging information. Implies all other -debug* options</source> <translation>Mostrar informações extras de depuração. Implica em outras opções -debug*</translation> </message> <message> <location line="+1"/> <source>Output extra network debugging information</source> <translation>Mostrar informações extras de depuração da rede</translation> </message> <message> <location line="+2"/> <source>Prepend debug output with timestamp</source> <translation>Pré anexar a saída de debug com estampa de tempo</translation> </message> <message> <location line="+5"/> <source>SSL options: (see the SwansonCoin Wiki for SSL setup instructions)</source> <translation>Opções SSL: (veja a Wiki do SwansonCoin para instruções de configuração SSL)</translation> </message> <message> <location line="+1"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation>Escolher versão do proxy socks a ser usada (4-5, padrão: 5)</translation> </message> <message> <location line="+3"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation>Mandar informação de trace/debug para o console em vez de para o arquivo debug.log</translation> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation>Mandar informação de trace/debug para o debugger</translation> </message> <message> <location line="+5"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation>Determinar tamanho máximo de bloco em bytes (padrão: 250000)</translation> </message> <message> <location line="+1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation>Determinar tamanho mínimo de bloco em bytes (padrão: 0)</translation> </message> <message> <location line="+2"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation>Encolher arquivo debug.log ao iniciar o cliente (padrão 1 se opção -debug não estiver presente)</translation> </message> <message> <location line="+1"/> <source>Signing transaction failed</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation>Especifique o tempo limite (timeout) da conexão em milissegundos (padrão: 5000) </translation> </message> <message> <location line="+4"/> <source>System error: </source> <translation>Erro de sistema:</translation> </message> <message> <location line="+4"/> <source>Transaction amount too small</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction amounts must be positive</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction too large</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation>Usar UPnP para mapear porta de escuta (padrão: 0)</translation> </message> <message> <location line="+1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation>Usar UPnP para mapear porta de escuta (padrão: 1 quando estiver escutando)</translation> </message> <message> <location line="+1"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation>Usar proxy para alcançar serviços escondidos (padrão: mesmo que -proxy)</translation> </message> <message> <location line="+2"/> <source>Username for JSON-RPC connections</source> <translation>Nome de usuário para conexões JSON-RPC</translation> </message> <message> <location line="+4"/> <source>Warning</source> <translation>Cuidado</translation> </message> <message> <location line="+1"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation>Cuidado: Esta versão está obsoleta, atualização exigida!</translation> </message> <message> <location line="+1"/> <source>You need to rebuild the databases using -reindex to change -txindex</source> <translation>Você precisa reconstruir os bancos de dados usando -reindex para mudar -txindex</translation> </message> <message> <location line="+1"/> <source>wallet.dat corrupt, salvage failed</source> <translation>wallet.dat corrompido, recuperação falhou</translation> </message> <message> <location line="-50"/> <source>Password for JSON-RPC connections</source> <translation>Senha para conexões JSON-RPC</translation> </message> <message> <location line="-67"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation>Permitir conexões JSON-RPC de endereços IP específicos</translation> </message> <message> <location line="+76"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>Enviar comando para nó rodando em &lt;ip&gt; (pardão: 127.0.0.1)</translation> </message> <message> <location line="-120"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation>Executar comando quando o melhor bloco mudar (%s no comando será substituído pelo hash do bloco)</translation> </message> <message> <location line="+147"/> <source>Upgrade wallet to latest format</source> <translation>Atualizar carteira para o formato mais recente</translation> </message> <message> <location line="-21"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation>Determinar tamanho do pool de endereços para &lt;n&gt; (padrão: 100)</translation> </message> <message> <location line="-12"/> <source>Rescan the block chain for missing wallet transactions</source> <translation>Re-escanear blocos procurando por transações perdidas da carteira</translation> </message> <message> <location line="+35"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>Usar OpenSSL (https) para conexões JSON-RPC</translation> </message> <message> <location line="-26"/> <source>Server certificate file (default: server.cert)</source> <translation>Arquivo de certificado do servidor (padrão: server.cert)</translation> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation>Chave privada do servidor (padrão: server.pem)</translation> </message> <message> <location line="-151"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation>Algoritmos de criptografia aceitos (padrão: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation> </message> <message> <location line="+165"/> <source>This help message</source> <translation>Esta mensagem de ajuda</translation> </message> <message> <location line="+6"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation>Impossível vincular a %s neste computador (bind retornou erro %d, %s)</translation> </message> <message> <location line="-91"/> <source>Connect through socks proxy</source> <translation>Conectar através de um proxy socks</translation> </message> <message> <location line="-10"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation>Permitir consultas DNS para -addnode, -seednode e -connect</translation> </message> <message> <location line="+55"/> <source>Loading addresses...</source> <translation>Carregando endereços...</translation> </message> <message> <location line="-35"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation>Erro ao carregar wallet.dat: Carteira corrompida</translation> </message> <message> <location line="+1"/> <source>Error loading wallet.dat: Wallet requires newer version of SwansonCoin</source> <translation>Erro ao carregar wallet.dat: Carteira requer uma versão mais nova do SwansonCoin</translation> </message> <message> <location line="+93"/> <source>Wallet needed to be rewritten: restart SwansonCoin to complete</source> <translation>A Carteira precisou ser reescrita: reinicie o SwansonCoin para completar</translation> </message> <message> <location line="-95"/> <source>Error loading wallet.dat</source> <translation>Erro ao carregar wallet.dat</translation> </message> <message> <location line="+28"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation>Endereço -proxy inválido: &apos;%s&apos;</translation> </message> <message> <location line="+56"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation>Rede desconhecida especificada em -onlynet: &apos;%s&apos;</translation> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation>Versão desconhecida do proxy -socks requisitada: %i</translation> </message> <message> <location line="-96"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation>Impossível encontrar o endereço -bind: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation>Impossível encontrar endereço -externalip: &apos;%s&apos;</translation> </message> <message> <location line="+44"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Quantidade inválida para -paytxfee=&lt;quantidade&gt;: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount</source> <translation>Quantidade inválida</translation> </message> <message> <location line="-6"/> <source>Insufficient funds</source> <translation>Saldo insuficiente</translation> </message> <message> <location line="+10"/> <source>Loading block index...</source> <translation>Carregando índice de blocos...</translation> </message> <message> <location line="-57"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation>Adicionar um nó com o qual se conectar e tentar manter a conexão ativa</translation> </message> <message> <location line="-25"/> <source>Unable to bind to %s on this computer. SwansonCoin is probably already running.</source> <translation>Impossível vincular a %s neste computador. O SwansonCoin provavelmente já está rodando.</translation> </message> <message> <location line="+64"/> <source>Fee per KB to add to transactions you send</source> <translation>Taxa por KB a ser acrescida nas transações que você enviar</translation> </message> <message> <location line="+19"/> <source>Loading wallet...</source> <translation>Carregando carteira...</translation> </message> <message> <location line="-52"/> <source>Cannot downgrade wallet</source> <translation>Não é possível fazer downgrade da carteira</translation> </message> <message> <location line="+3"/> <source>Cannot write default address</source> <translation>Não foi possível escrever no endereço padrão</translation> </message> <message> <location line="+64"/> <source>Rescanning...</source> <translation>Re-escaneando...</translation> </message> <message> <location line="-57"/> <source>Done loading</source> <translation>Carregamento terminado</translation> </message> <message> <location line="+82"/> <source>To use the %s option</source> <translation>Para usar a opção %s</translation> </message> <message> <location line="-74"/> <source>Error</source> <translation>Erro</translation> </message> <message> <location line="-31"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation>Você precisa especificar rpcpassword=&lt;senha&gt; no arquivo de configurações:⏎ %s⏎ Se o arquivo não existir, crie um com permissão de leitura apenas pelo dono</translation> </message> </context> </TS>
swansoncoin/swansoncoin
src/qt/locale/bitcoin_pt_BR.ts
TypeScript
mit
118,810
package com.twitter.meil_mitu.twitter4holo.api.help; import com.twitter.meil_mitu.twitter4holo.AbsGet; import com.twitter.meil_mitu.twitter4holo.AbsOauth; import com.twitter.meil_mitu.twitter4holo.ITwitterJsonConverter; import com.twitter.meil_mitu.twitter4holo.OauthType; import com.twitter.meil_mitu.twitter4holo.ResponseData; import com.twitter.meil_mitu.twitter4holo.data.TosResult; import com.twitter.meil_mitu.twitter4holo.exception.Twitter4HoloException; public class Tos extends AbsGet<ITwitterJsonConverter>{ public Tos(AbsOauth oauth, ITwitterJsonConverter json){ super(oauth, json); } @Override public String url(){ return "https://api.twitter.com/1.1/help/tos.json"; } @Override public int allowOauthType(){ return OauthType.Oauth1 | OauthType.Oauth2; } @Override public boolean isAuthorization(){ return true; } @Override public ResponseData<TosResult> call() throws Twitter4HoloException{ return Json.toTosResultResponseData(Oauth.get(this)); } }
MeilCli/Twitter4Holo
library/src/main/java/com/twitter/meil_mitu/twitter4holo/api/help/Tos.java
Java
mit
1,064
module Cranium::ImportStrategy autoload :Base, 'cranium/import_strategy/base' autoload :DeleteInsert, 'cranium/import_strategy/delete_insert' autoload :Delete, 'cranium/import_strategy/delete' autoload :TruncateInsert, 'cranium/import_strategy/truncate_insert' autoload :Delta, 'cranium/import_strategy/delta' autoload :Merge, 'cranium/import_strategy/merge' end
emartech/cranium
lib/cranium/import_strategy.rb
Ruby
mit
376
var STATE_START = 0; var STATE_END = 1; var STATE_GROUND = 2; var STATE_FOREST = 3; var STATE_WATER = 4; function Cell(col, row) { this.col = col; this.row = row; this.state = STATE_GROUND; } Cell.prototype.draw = function() { stroke(66); switch (this.state) { case STATE_START: Color.Material.light_green[5].fill(); break; case STATE_END: Color.Material.red[5].fill(); break; case STATE_GROUND: Color.Material.green[5].fill(); break; case STATE_FOREST: Color.Material.green[9].fill(); break; case STATE_WATER: Color.Material.light_blue[5].fill(); break; default: fill(255, 0, 0); } rect(this.col * scl, this.row * scl, scl, scl); }; Cell.prototype.incrementState = function(bool) { if (bool) { // Cycle from 0 to 1 this.state = (++this.state > 1) ? 0 : this.state; } else { // Cycle from 2 to 4 this.state = (++this.state < 2 || this.state > 4) ? 2 : this.state; } //this.state = (++this.state > 4) ? 0 : this.state; //loop(); };
dylandevalia/dylan.devalia.com
old/pathfinding/cell.js
JavaScript
mit
996
'use strict'; /* Services */ // Demonstrate how to register services // In this case it is a simple value service. angular.module('baApp.services', []). value('version', '0.1');
alnutile/drag-and-drop-page
app/js/services.js
JavaScript
mit
183
var fs = require('fs'); var join = require('path').join; var iconv = require('iconv-lite'); var debug = require('debug')('ip'); var util = require('util'); var EventEmitter = require('events').EventEmitter; var thunkify = require('thunkify-wrap'); function IpUtil(ipFile, encoding, isLoad) { if (typeof encoding === 'function') { isLoad = encoding; encoding = null; } this.ipFile = joinDirectory(process.cwd(), ipFile); this.ipList = []; if (encoding && encoding.toLowerCase().indexOf('utf') > -1) { this.filter = function(buf) { return buf.toString(); }; } else { this.filter = function(buf) { return iconv.decode(new Buffer(buf), 'gbk'); }; } this.isLoad = isLoad || function(){ return true; }; this.init(); } util.inherits(IpUtil, EventEmitter); IpUtil.prototype.init = function() { var that = this; var isLoad = this.isLoad; debug('begin parse ipfile %s', this.ipFile); if (!fs.existsSync(this.ipFile)) { debug('not found ip file!'); that.emit('error', 'ipfile_not_found'); return; } var ipMap = this.ipMap = {}; var ipList = this.ipList; var getLine = readLine(this.ipFile, this.filter); var result = getLine.next(); var line; var lineNum = 0; var counter = 1; var _readLine = function () { if (result.done) { that.emit('loaded'); return; } // 避免ip读取独占cpu. if (counter % 100000 === 0) { counter = 1; setImmediate(_readLine); return; } counter++; lineNum++; line = result.value; if (!line || !line.trim()) { result = getLine.next(); _readLine(); return; } var tokens = line.split(',', 6); if (tokens.length !== 6) { debug('第%d行格式不正确: %s', lineNum, line); result = getLine.next(); _readLine(); return; } var startIp = ip2Long(tokens[0]); var endIp = ip2Long(tokens[1]); if (!startIp || !endIp) { debug('第%d行格式不正确: %s', lineNum, line); result = getLine.next(); _readLine(); return; } var country = getValue(tokens[2]); var province = getValue(tokens[3]); var city = getValue(tokens[4]); var address = getValue(tokens[5]); // 针对国家、省份、城市解析的统一判空修改 // 首先对特殊值的解析 if ('IANA' === country) { country = 'IANA'; province = 'IANA'; city = 'IANA'; } if ('局域网' === country) { country = '局域网'; province = '局域网'; city = '局域网'; } if('国外' === country) { country = '国外'; province = '国外'; city = '国外'; } if('中国' === country && ('中国' === province || '中国' === city)) { country = '中国'; province = '中国'; city = '中国'; } if (!isLoad(country, province, city)) { result = getLine.next(); setImmediate(_readLine); return; } ipMap[startIp] = { startIp: startIp, endIp: endIp, country: country, province: province, city: city, address: address }; ipList.push(startIp); result = getLine.next(); setImmediate(_readLine); }; _readLine(); var sortIp = function () { //debug(this.ipMap) debug('完成IP库的载入. 共载入 %d 条IP纪录', ipList.length); ipList.sort(function(a, b) { return a - b; }); debug('ip 索引排序完成.'); that.emit('done'); }; this.on('loaded', sortIp); }; function getValue(val) { if (!val) { return null; } val = val.trim(); if (val === 'null') { return null; } return val; } IpUtil.prototype.getIpInfo = function(ip) { if (!isIp(ip)) { return null; } if (typeof ip === 'string') { ip = ip2Long(ip); } var ipStart = this.locatStartIP(ip); debug('开始获取 ip 信息: %d', ipStart); var ipInfo = this.ipMap[ipStart]; debug('查找IP, %s 成功.', long2IP(ip)); if (ipInfo.endIp < ip) { debug('在IP库中找不到IP[%s]', long2IP(ip)); return null; } return ipInfo; }; IpUtil.prototype.refreshData = function() { }; /** * 查找ip对应的开始IP地址。如果IP库中正好有以该ip开始的IP信息,那么就是返回这个ip。 * 如果没有,则应该是比这个ip小的最大的start * @param ip * @return */ IpUtil.prototype.locatStartIP = function(ip) { debug('开始查找IP: %d', ip); var centerIP = 0; var centerIndex = 0; // 当前指针位置 var startIndex = 0; // 起始位置 var endIndex = this.ipList.length - 1; // 结束位置 var count = 0; // 循环次数 while (true) { debug('%d. start = %d, end = %d', count++, startIndex, endIndex); // 中间位置 centerIndex = Math.floor((startIndex + endIndex) / 2); centerIP = this.ipList[centerIndex]; if (centerIP < ip) { // 如果中间位置的IP小于要查询的IP,那么下一次查找后半段 startIndex = centerIndex; } else if (centerIP > ip) { // 如果中间位置的IP大于要查询的IP,那么下一次查找前半段 endIndex = centerIndex; } else { // 如果相等,那么已经找到要查询的IP break; } if (startIndex + 1 === endIndex) { // 如果开始指针和结束指针相差只有1,那么说明IP库中没有正好以该ip开始的IP信息 // 只能返回IP信息的start ip比这个ip小的最大的那条IP信息的start ip if (centerIP > ip) { centerIP = this.ipList[centerIndex - 1]; } break; } } debug('对应的IP开始地址为: %d', centerIP, centerIndex); return centerIP; }; /** * a,b,c ==> a/b/c * a,b,/tmp ==> /tmp * /a/b, c ==> /a/b/c */ function joinDirectory() { var dirs = [].slice.call(arguments, 1); var dir; for (var i = 0, len = dirs.length; i < len; i++) { dir = dirs[i]; if (/^\//.test(dir)) { // 发现根目录, 直接返回. return dir; } } return join.apply(null, [].slice.call(arguments)); } function ip2Long(ip) { if (!isIp(ip)) { return 0; } var segs = ip.split('.'); var iplong =(parseInt(segs[0]) << 24 | parseInt(segs[1]) << 16 | parseInt(segs[2]) << 8 | parseInt(segs[3])) >>> 0; return iplong; } var IP_REGEXP = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/; function isIp(str) { if (!str) { return false; } str = str.trim(); return IP_REGEXP.test(str); /** var tokens = str.split('.'); if (tokens.length !== 4) { return false; } for (var i = 0, len = tokens.length; i < len; i++) { if (parseInt(tokens[i]) > 255 || parseInt(tokens[i]) < 0) { return false; } } return true; **/ } function long2IP(ipLong) { var ip = [ipLong >> 24]; ip.push((ipLong & 16711680) >> 16); ip.push((ipLong & 65280) >> 8); ip.push(ipLong & 255); return ip.join('.'); } function *readLine(file, filter) { var buffer = fs.readFileSync(file); var i = 0, len = 0 || buffer.length; debug('load file succ', len); // 换行符. var nl = require('os').EOL.charCodeAt(0); var buf = []; while(i < len) { if (buffer[i] !== nl) { buf.push(buffer[i]); } else { yield filter(new Buffer(buf)); buf = []; } i++; } } module.exports = IpUtil; module.exports.isIP = isIp; module.exports.ip2Long = ip2Long; module.exports.long2Ip = long2IP; module.exports.getIpUtil = function *(ipFile, encoding, ipFilter) { var iputil = new IpUtil(ipFile, encoding, ipFilter); var end = thunkify.event(iputil, ['done', 'error']); yield end(); return iputil; };
leoner/iputil
index.js
JavaScript
mit
7,755
using System; using CommandLine; using System.IO; using Nancy.Hosting.Self; using SeudoBuild.Core; using SeudoBuild.Core.FileSystems; using SeudoBuild.Pipeline; using SeudoBuild.Net; namespace SeudoBuild.Agent { class Program { private const string Header = @" _ _ _ _ _ ___ ___ _ _ _| |___| |_ _ _|_| |_| | |_ -| -_| | | . | . | . | | | | | . | |___|___|___|___|___|___|___|_|_|___| "; private static ILogger _logger; [Verb("build", HelpText = "Create a local build.")] private class BuildSubOptions { [Option('t', "build-target", HelpText = "Name of the build target as specified in the project configuration file. If no build target is specified, the first target will be used.")] public string BuildTarget { get; set; } [Option('o', "output-folder", HelpText = "Path to the build output folder.")] public string OutputPath { get; set; } [Value(0, MetaName = "project", HelpText = "Path to a project configuration file.", Required = true)] public string ProjectConfigPath { get; set; } } [Verb("scan", HelpText = "List build agents found on the local network.")] private class ScanSubOptions { } [Verb("submit", HelpText = "Submit a build request for a remote build agent to fulfill.")] private class SubmitSubOptions { [Option('p', "project-config", HelpText = "Path to a project configuration file.", Required = true)] public string ProjectConfigPath { get; set; } [Option('t', "build-target", HelpText = "Name of the target to build as specified in the project configuration file.")] public string BuildTarget { get; set; } [Option('a', "agent-name", HelpText = "The unique name of a specific build agent. If not set, the job will be broadcast to all available agents.")] public string AgentName { get; set; } } [Verb("queue", HelpText = "Queue build requests received over the network.")] private class QueueSubOptions { [Option('n', "agent-name", HelpText = "A unique name for the build agent. If not set, a name will be generated.")] public string AgentName { get; set; } [Option('p', "port", HelpText = "Port on which to listen for build queue messages.")] public int? Port { get; set; } } [Verb("deploy", HelpText = "Listen for deployment messages.")] private class DeploySubOptions { } [Verb("name", Hidden = true)] private class NameSubOptions { [Option('r', "random")] public bool Random { get; set; } } public static void Main(string[] args) { _logger = new Logger(); Console.Title = "SeudoBuild"; Parser.Default.ParseArguments<BuildSubOptions, ScanSubOptions, SubmitSubOptions, QueueSubOptions, DeploySubOptions, NameSubOptions>(args) .MapResult( (BuildSubOptions opts) => Build(opts), (ScanSubOptions opts) => Scan(opts), (SubmitSubOptions opts) => Submit(opts), (QueueSubOptions opts) => Queue(opts), (DeploySubOptions opts) => Deploy(opts), (NameSubOptions opts) => ShowAgentName(opts), errs => 1 ); } /// <summary> /// Build a single target, then exit. /// </summary> private static int Build(BuildSubOptions opts) { Console.Title = "SeudoBuild • Build"; Console.WriteLine(Header); // Load pipeline modules var factory = new ModuleLoaderFactory(); IModuleLoader moduleLoader = factory.Create(_logger); // Load project config ProjectConfig projectConfig = null; try { var fs = new WindowsFileSystem(); var serializer = new Serializer(fs); var converters = moduleLoader.Registry.GetJsonConverters(); projectConfig = serializer.DeserializeFromFile<ProjectConfig>(opts.ProjectConfigPath, converters); } catch (Exception e) { Console.WriteLine("Can't parse project config:"); Console.WriteLine(e.Message); return 1; } // Execute build var builder = new Builder(moduleLoader, _logger); var parentDirectory = opts.OutputPath; if (string.IsNullOrEmpty(parentDirectory)) { // Config file's directory parentDirectory = new FileInfo(opts.ProjectConfigPath).Directory?.FullName; } var pipeline = new PipelineRunner(new PipelineConfig { BaseDirectory = parentDirectory }, _logger); bool success = builder.Build(pipeline, projectConfig, opts.BuildTarget); return success ? 0 : 1; } /// <summary> /// Discover build agents on the network. /// </summary> private static int Scan(ScanSubOptions opts) { Console.Title = "SeudoBuild • Scan"; Console.WriteLine(Header); Console.WriteLine("Looking for build agents. Press any key to exit."); // FIXME fill in port from command line argument var locator = new AgentLocator(5511); try { locator.Start(); } catch { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Could not start build agent discovery client"); Console.ResetColor(); return 1; } // FIXME don't hard-code port locator.AgentFound += (agent) => { _logger.Write($"{agent.AgentName} ({agent.Address})", LogType.Bullet); }; locator.AgentLost += (agent) => { _logger.Write($"Lost agent: {agent.AgentName} ({agent.Address})", LogType.Bullet); }; Console.WriteLine(); Console.ReadKey(); return 0; } /// <summary> /// Submit a build job to another agent. /// </summary> private static int Submit(SubmitSubOptions opts) { Console.Title = "SeudoBuild • Submit"; Console.WriteLine(Header); string configJson = null; try { configJson = File.ReadAllText(opts.ProjectConfigPath); } catch { _logger.Write("Project could not be read from " + opts.ProjectConfigPath, LogType.Failure); return 1; } var buildSubmitter = new BuildSubmitter(_logger); try { // Find agent on the network, with timeout var discoveryClient = new UdpDiscoveryClient(); buildSubmitter.Submit(discoveryClient, configJson, opts.BuildTarget, opts.AgentName); } catch (Exception e) { _logger.Write("Could not submit job: " + e.Message, LogType.Failure); return 1; } return 0; } /// <summary> /// Receive build jobs from other agents or clients, queue them, and execute them. /// Continue listening until user exits. /// </summary> private static int Queue(QueueSubOptions opts) { Console.Title = "SeudoBuild • Queue"; Console.WriteLine(Header); //string agentName = string.IsNullOrEmpty(opts.AgentName) ? AgentName.GetUniqueAgentName() : opts.AgentName; // FIXME pull port from command line argument, and incorporate into ServerBeacon object int port = 5511; if (opts.Port.HasValue) { port = opts.Port.Value; } // Starting the Nancy server will automatically execute the Bootstrapper class var uri = new Uri($"http://localhost:{port}"); using (var host = new NancyHost(uri)) { _logger.Write(""); try { host.Start(); _logger.Write("Build Queue", LogType.Header); _logger.Write(""); _logger.Write("Started build agent server: " + uri, LogType.Bullet); try { // FIXME configure the port from a command line argument var serverInfo = new UdpDiscoveryBeacon { Port = 5511 }; var discovery = new UdpDiscoveryServer(serverInfo); discovery.Start(); _logger.Write("Build agent discovery beacon started", LogType.Bullet); } catch { _logger.Write("Could not initialize build agent discovery beacon", LogType.Alert); } } catch (Exception e) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Could not start build server: " + e.Message); Console.ResetColor(); return 1; } Console.WriteLine(""); Console.WriteLine("Press any key to exit."); Console.ReadKey(); } return 0; } /// <summary> /// Deploy a build product on the local machine. /// </summary> private static int Deploy(DeploySubOptions opts) { return 0; } /// <summary> /// Display the unique name for this agent. /// </summary> private static int ShowAgentName(NameSubOptions opts) { string name; name = opts.Random ? AgentName.GetRandomName() : AgentName.GetUniqueAgentName(); Console.WriteLine(); Console.WriteLine(name); Console.WriteLine(); return 0; } } }
mstevenson/SeudoBuild
SeudoBuild.Agent/Program.cs
C#
mit
10,540
/* Noble cread UART service example This example uses Sandeep Mistry's noble library for node.js to read and write from Bluetooth LE characteristics. It looks for a UART characteristic based on a proprietary UART service by Nordic Semiconductor. You can see this service implemented in Adafruit's BLEFriend library. created 30 Nov 2015 by Tom Igoe */ var noble = require('noble'); //noble library var util = require('util'); // utilities library // make an instance of the eventEmitter library: var EventEmitter = require('events').EventEmitter; // constructor function, so you can call new BleUart(): var BleUart = function (uuid) { var service = '6e400001b5a3f393e0a9e50e24dcca9e'; // the service you want var receive, transmit; // transmit and receive BLE characteristics var self = this; // reference to the instance of BleUart self.connected = false; // whether the remote peripheral's connected self.peripheral; // the remote peripheral as an object EventEmitter.call(self); // make a copy of EventEmitter so you can emit events if (uuid) { // if the constructor was called with a different UUID, service = uuid; // then set that as the service to search for } // The scanning function: function scan(state) { if (state === 'poweredOn') { // if the radio's on, scan for this service noble.startScanning([service], false); } // emit a 'scanning' event: self.emit('scanning', state); } // the connect function: self.connect = function(peripheral) { self.peripheral = peripheral; peripheral.connect(); // start connection attempts // the connect function. This is local to the discovery function // because it needs to know the peripheral to discover services: function discover() { // once you know you have a peripheral with the desired // service, you can stop scanning for others: noble.stopScanning(); // get the service you want on this peripheral: peripheral.discoverServices([service],explore); } // called only when the peripheral has the service you're looking for: peripheral.on('connect', discover); // when a peripheral disconnects, run disconnect: peripheral.on('disconnect', self.disconnect); } // the services and characteristics exploration function: // once you're connected, this gets run: function explore(error, services) { // this gets run by the for-loop at the end of the // explore function, below: function getCharacteristics(error, characteristics) { for (var c in characteristics) { // loop over the characteristics if (characteristics[c].notify) { // if one has the notify property receive = characteristics[c]; // then it's the receive characteristic receive.notify(true); // turn on notifications // whenever a notify event happens, get the result. // this handles repeated notifications: receive.on('data', function(data, notification) { if (notification) { // if you got a notification self.emit('data', String(data)); // emit a data event } }); } if (characteristics[c].write) { // if a characteristic has a write property transmit = characteristics[c]; // then it's the transmit characteristic } } // end of getCharacteristics() // if you've got a valid transmit and receive characteristic, // then you're truly connected. Emit a connected event: if (transmit && receive) { self.connected = true; self.emit('connected', self.connected); } } // iterate over the services discovered. If one matches // the UART service, look for its characteristics: for (var s in services) { if (services[s].uuid === service) { services[s].discoverCharacteristics([], getCharacteristics); return; } } } // the BLE write function. If there's a valid transmit characteristic, /// then write data out to it as a Buffer: self.write = function(data) { if (transmit) { transmit.write(new Buffer(data)); } } // the BLE disconnect function: self.disconnect = function() { self.connected = false; } // when the radio turns on, start scanning: noble.on('stateChange', scan); // if you discover a peripheral with the appropriate service, connect: noble.on('discover', self.connect); } util.inherits(BleUart, EventEmitter); // BleUart inherits all the EventEmitter properties module.exports = BleUart; // export BleUart
evejweinberg/SuperHeroAutoPilot
ble-uart.js
JavaScript
mit
4,710
class QuestionGroupTracker attr_reader :questions, :question_group_id, :question_group def initialize(question_group_id) @questions = Question.where('question_group_id=?', question_group_id) @counter = 0 @question_group_id = question_group_id @question_group = QuestionGroup.find(question_group_id) end def check_for_new_group(question) if question.question_group_id != @question_group_id || !defined?(@initial_check) initialize(question.question_group_id) @initial_check = true return true else return false end end end
weedySeaDragon/surveyor_gui
app/models/question_group_tracker.rb
Ruby
mit
588
import logging import requests from django.conf import settings from django.contrib.sites.models import Site from django.core.mail import EmailMultiAlternatives from django.template.loader import get_template from django.utils import timezone from invitations.models import Invitation logger = logging.getLogger('email') sentry = logging.getLogger('sentry') def send_invite(message): try: invite = Invitation.objects.get( id=message.get('id'), status__in=[Invitation.PENDING, Invitation.ERROR], ) except Invitation.DoesNotExist: sentry.error("Invitation to send not found", exc_info=True, extra={'message': message}) return invite.status = Invitation.PROCESSING invite.save() context = { 'invite': invite, 'domain': Site.objects.get_current().domain, } subject = "[ContactOtter] Invitation to join ContactOtter from %s" % (invite.sender) if invite.book: subject = "[ContactOtter] Invitation to share %s's contact book" % (invite.sender) txt = get_template('email/invitation.txt').render(context) html = get_template('email/invitation.html').render(context) try: message = EmailMultiAlternatives( subject=subject, body=txt, from_email="ContactOtter <invites@contactotter.com>", to=[invite.email,], ) message.attach_alternative(html, "text/html") message.send() invite.status = Invitation.SENT invite.sent = timezone.now() invite.save() except: sentry.exception('Problem sending invite', exc_info=True, extra={'invite_id': invite.id}) invite.status = Invitation.ERROR invite.save()
phildini/logtacts
invitations/consumers.py
Python
mit
1,739
/* ********************************************************************************************************** * The MIT License (MIT) * * * * Copyright (c) 2016 Hypermediasystems Ges. f. Software mbH * * Web: http://www.hypermediasystems.de * * This file is part of hmssp * * * * Permission is hereby granted, free of charge, to any person obtaining a copy * * of this software and associated documentation files (the "Software"), to deal * * in the Software without restriction, including without limitation the rights * * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * * copies of the Software, and to permit persons to whom the Software is * * furnished to do so, subject to the following conditions: * * * * The above copyright notice and this permission notice shall be included in * * all copies or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * * THE SOFTWARE. * ************************************************************************************************************ */ using System; using System.Collections.Generic; using System.Dynamic; using System.Reflection; using Newtonsoft.Json; namespace HMS.SP{ /// <summary> /// <para>https://msdn.microsoft.com/en-us/library/office/jj850797.aspx#properties</para> /// </summary> public class ServerSettings : SPBase{ [JsonProperty("__HMSError")] public HMS.Util.__HMSError __HMSError_ { set; get; } [JsonProperty("__status")] public SP.__status __status_ { set; get; } [JsonProperty("__deferred")] public SP.__deferred __deferred_ { set; get; } [JsonProperty("__metadata")] public SP.__metadata __metadata_ { set; get; } public Dictionary<string, string> __rest; // no properties found /// <summary> /// <para> Endpoints </para> /// </summary> static string[] endpoints = { }; public ServerSettings(ExpandoObject expObj) { try { var use_EO = ((dynamic)expObj).entry.content.properties; HMS.SP.SPUtil.expando2obj(use_EO, this, typeof(ServerSettings)); } catch (Exception ex) { } } // used by Newtonsoft.JSON public ServerSettings() { } public ServerSettings(string json) { if( json == String.Empty ) return; dynamic jobject = Newtonsoft.Json.JsonConvert.DeserializeObject(json); dynamic refObj = jobject; if (jobject.d != null) refObj = jobject.d; string errInfo = ""; if (refObj.results != null) { if (refObj.results.Count > 1) errInfo = "Result is Collection, only 1. entry displayed."; refObj = refObj.results[0]; } List<string> usedFields = new List<string>(); usedFields.Add("__HMSError"); HMS.SP.SPUtil.dyn_ValueSet("__HMSError", refObj, this); usedFields.Add("__deferred"); this.__deferred_ = new SP.__deferred(HMS.SP.SPUtil.dyn_toString(refObj.__deferred)); usedFields.Add("__metadata"); this.__metadata_ = new SP.__metadata(HMS.SP.SPUtil.dyn_toString(refObj.__metadata)); this.__rest = new Dictionary<string, string>(); var dyn = ((Newtonsoft.Json.Linq.JContainer)refObj).First; while (dyn != null) { string Name = ((Newtonsoft.Json.Linq.JProperty)dyn).Name; string Value = ((Newtonsoft.Json.Linq.JProperty)dyn).Value.ToString(); if ( !usedFields.Contains( Name )) this.__rest.Add( Name, Value); dyn = dyn.Next; } if( errInfo != "") this.__HMSError_.info = errInfo; } } }
helmuttheis/hmsspx
hmssp/SP.gen/ServerSettings.cs
C#
mit
4,781
//using System; //using System.Collections.Generic; //using System.Linq; //using System.Text; //using parser; // //namespace runic.lexer //{ // public class Lexer_Bootstrap_Old : Parser_Context // { // public Lexer_Bootstrap_Old(Definition definition) // : base(definition) // { // } // // public override object perform_action(string name, Pattern_Source data, Match match) // { // if (data.name == null) // data.name = name; // // var type = match.pattern.name; // switch (type) // { // case "string": // case "regex": // data = data.patterns[1]; // data.type = type; // return data; // // default: // // throw new Exception("Invalid parser method: " + name + "."); // } // // return data; // } // } //}
silentorb/runic
Runic/lexer/Lexer_Bootstrap_Old.cs
C#
mit
1,047
using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using StockExchangeYahooFinance.DbContext; namespace StockExchangeYahooFinance.Migrations { [DbContext(typeof(YahooFinanceDbContext))] [Migration("20170419132834_updateExAddCountry")] partial class updateExAddCountry { protected override void BuildTargetModel(ModelBuilder modelBuilder) { modelBuilder .HasAnnotation("ProductVersion", "1.1.1") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("StockExchangeYahooFinance.Data.Models.Companies", b => { b.Property<string>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ADR_TSO"); b.Property<string>("ExchangeId"); b.Property<string>("IPOyear"); b.Property<string>("IndustryId"); b.Property<string>("LastSale"); b.Property<string>("MarketCap"); b.Property<string>("Name"); b.Property<string>("RegionId"); b.Property<string>("SectorId"); b.Property<string>("Symbol"); b.Property<string>("Type"); b.HasKey("Id"); b.HasIndex("ExchangeId"); b.HasIndex("IndustryId"); b.HasIndex("RegionId"); b.HasIndex("SectorId"); b.ToTable("Companies"); }); modelBuilder.Entity("StockExchangeYahooFinance.Data.Models.Country", b => { b.Property<string>("Id") .ValueGeneratedOnAdd(); b.Property<string>("CountryCode"); b.Property<string>("Name"); b.HasKey("Id"); b.ToTable("Country"); }); modelBuilder.Entity("StockExchangeYahooFinance.Data.Models.Currencies", b => { b.Property<string>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Code"); b.Property<string>("Currency"); b.Property<string>("Entity"); b.Property<string>("MinorUnit"); b.Property<int>("NumericCode"); b.HasKey("Id"); b.ToTable("Currencies"); }); modelBuilder.Entity("StockExchangeYahooFinance.Data.Models.Exchange", b => { b.Property<string>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClosingTimeLocal"); b.Property<string>("DataProvider"); b.Property<string>("Delay"); b.Property<string>("Name"); b.Property<string>("OpeningTimeLocal"); b.Property<string>("RegionId"); b.Property<string>("StockExchangeId"); b.Property<string>("Suffix"); b.Property<string>("TradingDays"); b.Property<string>("UtcOffsetStandardTime"); b.HasKey("Id"); b.HasIndex("RegionId"); b.ToTable("Exchange"); }); modelBuilder.Entity("StockExchangeYahooFinance.Data.Models.FinanceModel", b => { b.Property<string>("Id") .ValueGeneratedOnAdd(); b.Property<string>("AfterHoursChangeRealtime"); b.Property<string>("AnnualizedGain"); b.Property<string>("Ask"); b.Property<string>("AskRealtime"); b.Property<string>("AverageDailyVolume"); b.Property<string>("Bid"); b.Property<string>("BidRealtime"); b.Property<string>("BookValue"); b.Property<string>("Change"); b.Property<string>("ChangeFromFiftydayMovingAverage"); b.Property<string>("ChangeFromTwoHundreddayMovingAverage"); b.Property<string>("ChangeFromYearHigh"); b.Property<string>("ChangeFromYearLow"); b.Property<string>("ChangePercentRealtime"); b.Property<string>("ChangeRealtime"); b.Property<string>("Change_PercentChange"); b.Property<string>("ChangeinPercent"); b.Property<string>("Commission"); b.Property<string>("CompaniesId"); b.Property<string>("CurencyId"); b.Property<string>("CurrenciesId"); b.Property<string>("Currency"); b.Property<string>("Date"); b.Property<string>("DaysHigh"); b.Property<string>("DaysLow"); b.Property<string>("DaysRange"); b.Property<string>("DaysRangeRealtime"); b.Property<string>("DaysValueChange"); b.Property<string>("DaysValueChangeRealtime"); b.Property<string>("DividendPayDate"); b.Property<string>("DividendShare"); b.Property<string>("DividendYield"); b.Property<string>("EBITDA"); b.Property<string>("EPSEstimateCurrentYear"); b.Property<string>("EPSEstimateNextQuarter"); b.Property<string>("EPSEstimateNextYear"); b.Property<string>("EarningsShare"); b.Property<string>("ErrorIndicationreturnedforsymbolchangedinvalid"); b.Property<string>("ExDividendDate"); b.Property<string>("FiftydayMovingAverage"); b.Property<string>("HighLimit"); b.Property<string>("HoldingsGain"); b.Property<string>("HoldingsGainPercent"); b.Property<string>("HoldingsGainPercentRealtime"); b.Property<string>("HoldingsGainRealtime"); b.Property<string>("HoldingsValue"); b.Property<string>("HoldingsValueRealtime"); b.Property<string>("LastTradeDate"); b.Property<string>("LastTradePriceOnly"); b.Property<string>("LastTradeRealtimeWithTime"); b.Property<string>("LastTradeTime"); b.Property<string>("LastTradeWithTime"); b.Property<string>("LowLimit"); b.Property<string>("MarketCapRealtime"); b.Property<string>("MarketCapitalization"); b.Property<string>("MoreInfo"); b.Property<string>("Name"); b.Property<string>("Notes"); b.Property<string>("OneyrTargetPrice"); b.Property<string>("Open"); b.Property<string>("OrderBookRealtime"); b.Property<string>("PEGRatio"); b.Property<string>("PERatio"); b.Property<string>("PERatioRealtime"); b.Property<string>("PercebtChangeFromYearHigh"); b.Property<string>("PercentChange"); b.Property<string>("PercentChangeFromFiftydayMovingAverage"); b.Property<string>("PercentChangeFromTwoHundreddayMovingAverage"); b.Property<string>("PercentChangeFromYearLow"); b.Property<string>("PreviousClose"); b.Property<string>("PriceBook"); b.Property<string>("PriceEPSEstimateCurrentYear"); b.Property<string>("PriceEPSEstimateNextYear"); b.Property<string>("PricePaid"); b.Property<string>("PriceSales"); b.Property<string>("Rate"); b.Property<string>("SharesOwned"); b.Property<string>("ShortRatio"); b.Property<string>("StockExchange"); b.Property<string>("Symbol"); b.Property<string>("TickerTrend"); b.Property<string>("Time"); b.Property<string>("TradeDate"); b.Property<string>("TwoHundreddayMovingAverage"); b.Property<string>("Volume"); b.Property<string>("YearHigh"); b.Property<string>("YearLow"); b.Property<string>("YearRange"); b.HasKey("Id"); b.HasIndex("CompaniesId"); b.HasIndex("CurrenciesId"); b.ToTable("FinanceModel"); }); modelBuilder.Entity("StockExchangeYahooFinance.Data.Models.Industry", b => { b.Property<string>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Name"); b.HasKey("Id"); b.ToTable("Industrie"); }); modelBuilder.Entity("StockExchangeYahooFinance.Data.Models.Region", b => { b.Property<string>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Name"); b.HasKey("Id"); b.ToTable("Region"); }); modelBuilder.Entity("StockExchangeYahooFinance.Data.Models.Sector", b => { b.Property<string>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Name"); b.HasKey("Id"); b.ToTable("Sector"); }); modelBuilder.Entity("StockExchangeYahooFinance.Data.Models.Companies", b => { b.HasOne("StockExchangeYahooFinance.Data.Models.Exchange", "Exchange") .WithMany() .HasForeignKey("ExchangeId"); b.HasOne("StockExchangeYahooFinance.Data.Models.Industry", "Industry") .WithMany() .HasForeignKey("IndustryId"); b.HasOne("StockExchangeYahooFinance.Data.Models.Region", "Region") .WithMany() .HasForeignKey("RegionId"); b.HasOne("StockExchangeYahooFinance.Data.Models.Sector", "Sector") .WithMany() .HasForeignKey("SectorId"); }); modelBuilder.Entity("StockExchangeYahooFinance.Data.Models.Exchange", b => { b.HasOne("StockExchangeYahooFinance.Data.Models.Region", "Region") .WithMany() .HasForeignKey("RegionId"); }); modelBuilder.Entity("StockExchangeYahooFinance.Data.Models.FinanceModel", b => { b.HasOne("StockExchangeYahooFinance.Data.Models.Companies", "Companies") .WithMany() .HasForeignKey("CompaniesId"); b.HasOne("StockExchangeYahooFinance.Data.Models.Currencies", "Currencies") .WithMany() .HasForeignKey("CurrenciesId"); }); } } }
error505/YahooFinanceApi
StockExchangeYahooFinance/Migrations/20170419132834_updateExAddCountry.Designer.cs
C#
mit
12,032
'use strict'; const util = require('util'); const colors = require('colors/safe'); Object.entries({ info: colors.blue, warn: colors.yellow, error: colors.red }).map(([method, color]) => { const _ = global.console[method]; global.console[method] = (...args) => { if (args.length) { let msg = args.shift(); if ('string' == typeof msg) { msg = color(msg); } args.unshift(msg); } _(...args); }; });
cravler/whaler
lib/console.js
JavaScript
mit
509
require.ensure([], function(require) { require("./73.async.js"); require("./147.async.js"); require("./294.async.js"); require("./588.async.js"); }); module.exports = 589;
skeiter9/javascript-para-todo_demo
webapp/node_modules/webpack/benchmark/fixtures/589.async.js
JavaScript
mit
171
<rtl code> var m = function (){ function T(){ this.a = []; } var r = new T(); var a = RTL$.makeArray(3, 0); var dynamicInt = []; var dynamicString = []; var dynamicChar = []; var dynamicByte = []; var dynamicRecord = []; var dynamicArrayOfStaticArrayInt = []; var i = 0; var s = ''; var byte = 0; function assignDynamicArrayFromStatic(){ var static$ = RTL$.makeArray(3, 0); var dynamic = []; Array.prototype.splice.apply(dynamic, [0, Number.MAX_VALUE].concat(static$)); } function returnOuterArray(){ return a.slice(); } function passArrayBeRef(a/*VAR ARRAY * OF INTEGER*/){ var static$ = RTL$.makeArray(3, 0); a[0] = 1; a[0] = a[1]; Array.prototype.splice.apply(a, [0, Number.MAX_VALUE].concat(static$)); Array.prototype.splice.apply(a, [0, Number.MAX_VALUE].concat(dynamicInt)); } function passArrayOfRecordsByRef(a/*VAR ARRAY * OF T*/){ var result = []; RTL$.copy(result, a, {array: {record: {a: {array: null}}}}); } function passArrayOfArraysByRef(a/*VAR ARRAY *, 3 OF INTEGER*/){ var result = []; RTL$.copy(result, a, {array: {array: null}}); } function arrayOfRecords(){ var $scope1 = $scope + ".arrayOfRecords"; function T(){ } var a = []; a.push(new T()); } function arrayOfArrays(){ var aa = []; function f(){ var a = []; return a; } aa.push(f()); } function optimizeTemporartArrayReturn(){ function f(){ var a = []; return a; } return f(); } function optimizeLocalArrayReturn(){ var a = []; return a; } function optimizeLocalArrayReturnWhenStatic(){ var a = RTL$.makeArray(3, 0); return a; } function cannotOptimizeArgArrayReturn(a/*ARRAY OF INTEGER*/){ return a.slice(); } function cannotOptimizeVarArgArrayReturn(a/*VAR ARRAY OF INTEGER*/){ return a.slice(); } function cannotOptimizeVarArgDynamicArrayReturn(a/*VAR ARRAY * OF INTEGER*/){ return a.slice(); } function arrayOfMaps(){ var aa = []; function f(){ var a = {}; return a; } aa.push(f()); } dynamicInt.push(3); dynamicInt.push(i); dynamicInt.push(byte); dynamicString.push("abc"); dynamicString.push("\""); dynamicString.push(s); dynamicChar.push(34); dynamicByte.push(byte); dynamicByte.push(i & 0xFF); dynamicRecord.push(RTL$.clone(r, {record: {a: {array: null}}}, T)); dynamicArrayOfStaticArrayInt.push(a.slice()); RTL$.assert(dynamicInt.indexOf(i) != -1); RTL$.assert(dynamicChar.indexOf(34) != -1); dynamicInt.splice(i, 1); dynamicInt.splice(0, Number.MAX_VALUE); passArrayBeRef(dynamicInt); passArrayOfRecordsByRef(dynamicRecord); passArrayOfArraysByRef(dynamicArrayOfStaticArrayInt); }();
vladfolts/oberonjs
test/expected/eberon/dynamic_array.js
JavaScript
mit
2,536
def burrows_wheeler(text): """Calculates the burrows wheeler transform of <text>. returns the burrows wheeler string and the suffix array indices The text is assumed to not contain the character $""" text += "$" all_permutations = [] for i in range(len(text)): all_permutations.append((text[i:] + text[:i],i)) all_permutations.sort() bw_l = [] # burrows wheeler as list sa_i = [] # suffix array indices for w,j in all_permutations: bw_l.append(w[-1]) sa_i.append(j) return "".join(bw_l), sa_i
alneberg/sillymap
sillymap/burrows_wheeler.py
Python
mit
567
using System.ComponentModel.Composition; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure; using Microsoft.Azure.Management.Resources; using Microsoft.Azure.Management.Resources.Models; using Microsoft.Deployment.Common.ActionModel; using Microsoft.Deployment.Common.Actions; using Microsoft.Deployment.Common.Enums; using Microsoft.Deployment.Common.ErrorCode; using Microsoft.Deployment.Common.Helpers; using Microsoft.Deployment.Common.Model; using Newtonsoft.Json.Linq; namespace Microsoft.Deployment.Actions.AzureCustom.HCL { [Export(typeof(IAction))] public class CreateAzureMLWorkspace : BaseAction { public override async Task<ActionResponse> ExecuteActionAsync(ActionRequest request) { var azureToken = request.DataStore.GetJson("AzureToken")["access_token"].ToString(); var subscription = request.DataStore.GetJson("SelectedSubscription")["SubscriptionId"].ToString(); var resourceGroup = request.DataStore.GetValue("SelectedResourceGroup"); var location = request.DataStore.GetJson("SelectedLocation")["Name"].ToString(); var deploymentName = request.DataStore.GetValue("DeploymentName"); var mlWorkspaceName = request.DataStore.GetValue("mlWorkspaceName"); //var storageAccountName = request.DataStore.GetValue("storageAccountName"); var tagName_mlWorkspaceName = request.DataStore.GetValue("tagName_mlWorkspaceName"); var storageAccountName = request.DataStore.GetValue("storageAccountName"); var storageAccountType = request.DataStore.GetValue("storageAccountType"); var encryptionEnabled = request.DataStore.GetValue("storageAccountEncryptionEnabled"); var tagName_storageAccountName = request.DataStore.GetValue("tagName_storageAccountName"); foreach (var item in ListDeployedItems) { if (item.ToString() == deploymentName) return new ActionResponse(ActionStatus.Success); } SubscriptionCloudCredentials creds = new TokenCloudCredentials(subscription, azureToken); ResourceManagementClient client = new ResourceManagementClient(creds); var param = new AzureArmParameterGenerator(); param.AddStringParam("mlWorkspaceName", mlWorkspaceName); param.AddStringParam("storageAccountName", storageAccountName); param.AddStringParam("subscription", subscription); param.AddStringParam("resourceGroup", resourceGroup); param.AddStringParam("encryptionEnabled", encryptionEnabled); param.AddStringParam("location", location); param.AddStringParam("storageAccountType", storageAccountType); var armTemplate = JsonUtility.GetJObjectFromJsonString(System.IO.File.ReadAllText(Path.Combine(request.Info.App.AppFilePath, "Service/AzureML/MLWorkspace.json"))); var armParamTemplate = JsonUtility.GetJObjectFromObject(param.GetDynamicObject()); armTemplate.Remove("parameters"); armTemplate.Add("parameters", armParamTemplate["parameters"]); var deployment = new Azure.Management.Resources.Models.Deployment() { Properties = new DeploymentPropertiesExtended() { Template = armTemplate.ToString(), Parameters = JsonUtility.GetEmptyJObject().ToString() } }; var validate = await client.Deployments.ValidateAsync(resourceGroup, deploymentName, deployment, new CancellationToken()); if (!validate.IsValid) { return new ActionResponse(ActionStatus.Failure, JsonUtility.GetJObjectFromObject(validate), null, DefaultErrorCodes.DefaultErrorCode, $"Azure:{validate.Error.Message} Details:{validate.Error.Details}"); } var deploymentItem = await client.Deployments.CreateOrUpdateAsync(resourceGroup, deploymentName, deployment, new CancellationToken()); request.DataStore.AddToDataStore(tagName_mlWorkspaceName, mlWorkspaceName); request.DataStore.AddToDataStore(tagName_storageAccountName, storageAccountName); ListDeployedItems.Add(deploymentName); return new ActionResponse(ActionStatus.Success, deploymentItem); } } }
mayankon24/d-final
Source/Actions/Microsoft.Deployment.Actions.AzureCustom/HCL/CreateAzureMLWorkspace.cs
C#
mit
4,495
package com.example.dao; import com.example.model.Publisher; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Select; import java.util.List; @Mapper public interface PublisherMapper { @Select("SELECT *, PHONE as phoneNumber from PUBLISHERS") //SQL List<Publisher> findAll(); // === DB === // CREATE TABLE IF NOT EXISTS PUBLISHERS ( // ID INT NOT NULL AUTO_INCREMENT PRIMARY KEY // ,NAME VARCHAR(255) NOT NULL CONSTRAINT PUBLISHERS_NAME_UC UNIQUE // ,PHONE VARCHAR(30)); // === Model === // public class Publisher { // private Integer id ; // private String name; // private String phoneNumber; }
doubleirish/mybatis-spring-boot
src/main/java/com/example/dao/PublisherMapper.java
Java
mit
683
<?php while (have_posts()) : the_post(); ?> <article <?php post_class(); ?>> <div class="entry-content content-medicina-prepagada"> <header class="menu-med-prep text-center"> <ul class="list-inline"> <?php $loop = new WP_Query( array( 'post_type' => 'aps', 'order' => 'ASC', 'category_name'=> 'link'));?> <?php while ( $loop->have_posts() ) : $loop->the_post(); $slug = get_post_field( 'post_name', get_post() ); ?> <li class="boton-aps"><a href="<?php the_permalink();?>"><span class="aps-title-menu text-uppercase texto<?php echo $slug; ?>"><?php the_title(); ?></span></a></li> <?php endwhile; wp_reset_query(); ?> </ul> </header> <?php $slug = get_post_field( 'post_name', get_post() ); ?> <div class="row"> <div class="col-sm-12"> <div class="title-big-aps"> <div class="row"> <div class="col-sm-6"> <div class="aps-text-big"> <h2><span class="titulo-plan-big titulo-aps-big">Plan </span><span class="text-uppercase titulo-plan titulo-aps fondo<?php echo $slug; ?>"><?php the_title(); ?></span></h2> </div> </div> <div class="col-sm-6"> <img src="<?php the_post_thumbnail_url('full'); ?>" class="img-responsive"> </div> </div> </div> <div class="wrapper-aps"><?php the_content(); ?></div> <div class="wrapper-botones"> <?php $id_empresarial=get_category_by_slug( 'empresarial' ); $category=get_the_category(); if ($category[0]->name === 'empresarial') { if( get_adjacent_post(true, '', true, 'category') ) { $post_previo=get_adjacent_post(true, '', true, 'category'); if((in_category('empresarial', $post_previo))){ $post_previo_slug=get_post_field( 'post_name', $post_previo ); $post_previo_slug=str_replace("-", " ", $post_previo_slug); echo '<div class="texto-azul pull-left boton-nav">'; previous_post_link('%link', '<span class="glyphicon glyphicon-chevron-left"></span>'.$post_previo_slug); echo "</div>"; } else { $first = new WP_Query( array( 'post_type' => 'aps', 'order' => 'DESC', 'category__in'=> $id_empresarial->term_id)); $first->the_post(); $post_previo_slug=get_post_field( 'post_name' ); $post_previo_slug=str_replace("-", " ", $post_previo_slug); echo '<div class="texto-azul pull-left boton-nav"><a href="' . get_permalink() . '"><span class="glyphicon glyphicon-chevron-left"></span>'.$post_previo_slug.'</a></div>'; wp_reset_query(); }; }; if( get_adjacent_post(true, '', false, 'category') ) { $post_sig=get_adjacent_post(true, '', false, 'category'); $post_sig_slug=get_post_field( 'post_name', $post_sig ); echo '<div class="texto-azul pull-right boton-nav">'; next_post_link('%link', $post_sig_slug.'<span class="glyphicon glyphicon-chevron-right"></span></div>'); } else { $last = new WP_Query( array( 'post_type' => 'aps', 'order' => 'ASC', 'category__in'=> $id_empresarial->term_id)); $last->the_post(); $post_sig_slug=get_post_field( 'post_name' ); $post_sig_slug=str_replace("-", " ", $post_sig_slug); // $post_sig_slug=get_post_field( 'post_name', $post_sig ); echo '<div class="texto-azul pull-right boton-nav"><a href="' . get_permalink() . '"><span class="textobotonnav">'.$post_sig_slug.'</span><span class="glyphicon glyphicon-chevron-right"></span></a></div>'; wp_reset_query(); }; } else{?> <div class="wrapper-botones text-center"> <a href="#" class="boton-med-prep">Cotización Familiar</a> <a href="#" class="boton-med-prep">Cotizar Empresa</a> </div> <?php }?> </div> </div> </div> </div> </div> </article> <?php endwhile; ?>
nedilio/rescarven-wp-theme
templates/content-single-aps.php
PHP
mit
4,240
package wikimediaparser import ( "fmt" "github.com/golang/glog" "strings" ) // Node as it is emitted by the parser // - contains a NodeType for clear identification // - a string val Val // - a list of named parameters which are actually Node Lists // -a list of anonymous parameters, a Node list again type Node struct { Typ nodeType Val string NamedParams map[string]Nodes Params []Nodes } // Return the Node text content, without any decoration func (n *Node) StringRepresentation() string { glog.V(7).Infof("stringRepresentation for %+v", n) switch n.Typ { case NodeText, NodeInvalid: return n.Val case NodeLink, NodeELink: if len(n.Params) > 0 { return n.Params[0].StringRepresentation() } else { return n.StringParamOrEmpty("link") } case NodeTemplate: if len(n.Params) > 0 { return n.Params[0].StringRepresentation() } else { return "" } default: return "" } } func (n *Node) String() string { switch n.Typ { case NodeText, NodeInvalid: return fmt.Sprintf("%q", n.Val) } o := fmt.Sprintf("%s: %s", n.Typ.String(), n.Val) for ix, p := range n.Params { o += fmt.Sprintf("\t%d: %s\n", ix, p.String()) } for k, v := range n.NamedParams { o += fmt.Sprintf("\t%s: %s\n", k, v.String()) } return o } // StringParam returns the string value of a given named parameter func (n *Node) StringParam(k string) string { param, ok := n.NamedParams[k] if !ok { glog.V(2).Infof("Unable to extract parameter \"%s\" for node %s", k, n.String()) } else { return param.StringRepresentation() } return "" } func (n *Node) StringParamOrEmpty(k string) string { glog.V(2).Infof("StringParamOrEmpty for %s", k) v, ok := n.NamedParams[k] if ok { ret := v.StringRepresentation() return strings.Trim(ret, " \n") } return "" } func EmptyNode() Node { return Node{Typ: NodeEmpty} } type nodeType int const ( NodeInvalid = nodeType(iota) NodeText NodeTitle NodeLink NodeELink NodeTemplate NodePlaceholder NodeEq NodeUnknown NodeEmpty ) func (n nodeType) String() string { switch n { case NodeText: return "Text" case NodeLink: return "Link" case NodeELink: return "ELink" case NodeTemplate: return "Template" case NodeEq: return " EQ " case NodeTitle: return " Title " case NodePlaceholder: return " Placeholder " case NodeUnknown: return "UNK" case NodeInvalid: return " INV " default: return "????" } }
octplane/wikiquote-parser
node.go
GO
mit
2,562
import Vue from 'vue'; import VueForm from 'vue-form'; Vue.use(VueForm, { validators: { 'step': function(value, stepValue) { return stepValue === `any` || Number(value) % Number(stepValue) === 0; }, 'data-exclusive-minimum': function(value, exclusiveMinimum) { return Number(value) > Number(exclusiveMinimum); }, 'data-exclusive-maximum': function(value, exclusiveMaximum) { return Number(value) < Number(exclusiveMaximum); }, 'complete-range': function(range) { return range === null || (range[0] !== null && range[1] !== null); }, 'valid-range': function(range) { if (range === null) { // allowed range return true; } if (range[0] === null || range[1] === null) { // let complete-range validator handle this return true; } if (Number.isNaN(range[0]) || Number.isNaN(range[1])) { // let number validator handle this return true; } return range[0] <= range[1]; }, 'categories-not-empty': function(categories) { return categories.length > 0; }, 'complete-dimensions': function(dimensions) { return dimensions === null || (dimensions[0] !== null && dimensions[1] !== null && dimensions[2] !== null); }, 'start-with-uppercase-or-number': function(value) { return /^[\dA-Z]/.test(value); }, 'no-mode-name': function(value) { return !/\bmode\b/i.test(value); }, 'no-fine-channel-name': function(value) { if (/\bfine\b|\d+[\s_-]*bit/i.test(value)) { return false; } return !/\bLSB\b|\bMSB\b/.test(value); }, 'entity-complete': function(value, attributeValue, vnode) { const component = vnode.componentInstance; if (component.hasNumber) { return component.selectedNumber !== `` && component.selectedNumber !== null; } return true; }, 'entities-have-same-units': function(value, attributeValue, vnode) { return vnode.componentInstance.hasSameUnit; }, 'valid-color-hex-list': function(value) { return /^\s*#[\da-f]{6}(?:\s*,\s*#[\da-f]{6})*\s*$/i.test(value); }, 'max-file-size': function(file, attributeValue) { if (typeof file === `object`) { let maxSize = Number.parseInt(attributeValue, 10); if (attributeValue.includes(`M`)) { maxSize *= 1000 * 1000; } else if (attributeValue.includes(`k`)) { maxSize *= 1000; } return file.size <= maxSize; } return true; }, }, });
FloEdelmann/open-fixture-library
ui/plugins/vue-form.js
JavaScript
mit
2,583
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Post extends Application { /** * Index Page for this controller. * * Maps to the following URL * http://example.com/index.php/welcome * - or - * http://example.com/index.php/welcome/index * - or - * Since this controller is set as the default controller in * config/routes.php, it's displayed at http://example.com/ * * So any other public methods not prefixed with an underscore will * map to /index.php/welcome/<method_name> * @see http://codeigniter.com/user_guide/general/urls.html */ public function index() { $this->data['pagetitle'] = 'News title - Zerotype Website Template'; $this->data['pagebody'] = 'post'; $this->render(); } } /* End of file welcome.php */ /* Location: ./application/controllers/welcome.php */
ericytsang/comp4711.lab2.partB.local
application/controllers/Post.php
PHP
mit
939
var resources = require('jest'), util = require('util'), models = require('../../models'), async = require('async'), common = require('./../common'), calc_thresh = require('../../tools/calc_thresh.js'), GradeActionSuggestion = require('./grade_action_suggestion_resource.js'), ActionSuggestion = require('./ActionSuggestionResource.js'), og_action = require('../../og/og.js').doAction; //Authorization var Authoriztion = function() {}; util.inherits(Authoriztion,resources.Authorization); //Authorization.prototype.edit_object = function(req,object,callback){ // //check if user already grade this action // var flag = false; // // models.GradeAction.find({"action_id": object.action_id}, function(err, objects){ // if (err){ // callback(err, null); // }else{ // for (var i = 0; i < objects.length; i++){ // if(req.session.user_id == objects[i].user_id){ // flag = true; // break; // } // } // if (flag){ // callback({message:"user already grade this action",code:401}, null); // }else{ // callback(null, object); // } // } // }) //}; var GradeActionResource = module.exports = common.GamificationMongooseResource.extend({ init:function(){ this._super(models.GradeAction,'grade_action', null); // GradeResource.super_.call(this,models.Grade); this.allowed_methods = ["get", "put", "post"]; this.authorization = new Authoriztion(); this.authentication = new common.SessionAuthentication(); this.filtering = {action_id: { exact:null, in:null }}; }, create_obj:function(req,fields,callback) { var self = this; var g_grade_obj; var new_grade = null; var counter = 0; var threshold; var admin_threshold; var action_thresh; var action_obj; var proxy_power = req.user.num_of_given_mandates ? 1 + req.user.num_of_given_mandates * 1/9 : 1; var base = self._super; fields.proxy_power = proxy_power; fields.user_id = req.user._id; async.waterfall([ function(cbk){ base.call(self, req, fields, cbk); }, //find actions function(grade_obj, cbk){ g_grade_obj = grade_obj; models.Action.findById(grade_obj.action_id, cbk); }, // 2) calculate action grade + set notifications for all users of proxy function(action, cbk){ action_obj = action; async.parallel([ //2.1 set notifications for all users of proxy function(cbk1){ cbk1(null, null); }, // 2.2 calculate action grade function(cbk1){ //cant grade your own action action_thresh = Number(action.admin_threshold_for_accepting_change_suggestions) || action.threshold_for_accepting_change_suggestions admin_threshold = action.admin_threshold_for_accepting_change_suggestions; calculateActionGrade(g_grade_obj.action_id, function(err, _new_grade, evaluate_counter, _threshold){ new_grade = _new_grade; counter = evaluate_counter; threshold = _threshold cbk1(err, threshold); }); }, //2.3 add user to be part of the action function(cbk1){ if (! _.any(action.users, function(user){ return user.user_id + "" == req.user.id})){ var new_user = {user_id: req.user._id, join_date: Date.now()}; models.Action.update({_id: action._id}, {$addToSet:{users: new_user}}, function(err, num){cbk1(err, num)}); }else{ cbk1(null, null); } } ],function(err, args){ cbk(err, args[1]); }) }, // 3) find suggestion object //calculate all change suggestion all over again and check if they approved function(threshold, cbk){ models.ActionSuggestion.find({action_id: g_grade_obj.action_id}, {"_id":1}, function(err, results) { cbk(err, results); }); }, // 4) calculate suggestion grades function(suggestions, cbk){ var real_threshold async.forEach(suggestions, function(suggestion, itr_cbk){ GradeActionSuggestion.calculateActionSuggestionGrade(suggestion._id, g_grade_obj.action_id, null, null, action_thresh, null, null,function(err, obj){ //check if suggestion is over the threshold real_threshold = Number(suggestion.admin_threshold_for_accepting_the_suggestion) || suggestion.threshold_for_accepting_the_suggestion; if(suggestion.agrees && suggestion.agrees.length > real_threshold){ //approveSuggestion.exec() ActionSuggestion.approveSuggestion(suggestion._id, function(err, obj1){ itr_cbk(err, obj1); }) }else itr_cbk(err, obj); });} , function(err){ cbk(err); }); }, // 5) publish to facebook function (cbk) { og_action({ action: 'rank', object_name:'action', object_url : '/actions/' + action_obj.id, fid : req.user.facebook_id, access_token:req.user.access_token, user:req.user }); cbk(); }, // update actions done by user function(cbk){ models.User.update({_id:user._id},{$set: {"actions_done_by_user.grade_object": true}}, function(err){ cbk(err); }); } ], // Final) set gamification details, return object function(err, args){ req.gamification_type = "grade_action"; req.token_price = common.getGamificationTokenPrice('grade_action') > -1 ? common.getGamificationTokenPrice('grade_action') : 0; callback(err, {new_grade: new_grade, evaluate_counter: counter, grade_id: g_grade_obj._id || 0}); }) }, update_obj: function(req, object, callback){ var g_grade; var self = this; var suggestions = []; var action_thresh; var proxy_power = req.user.num_of_given_mandates ? 1 + req.user.num_of_given_mandates * 1/9 : 1; var iterator = function(suggestion, itr_cbk){ GradeActionSuggestion.calculateActionSuggestionGrade(suggestion._id, object.action_id, null, null, action_thresh, null, null,function(err, sugg_new_grade, sugg_total_counter){ if(!err){ suggestions.push({ _id: suggestion._id, grade: sugg_new_grade, evaluators_counter: sugg_total_counter }) } itr_cbk(err, 0); }); } object.proxy_power = proxy_power; self._super(req, object, function(err, grade_object){ if(err){ callback(err, null); }else{ var new_grade, evaluate_counter; async.waterfall([ function(cbk){ g_grade = grade_object; calculateActionGrade(object.action_id, function(err, _new_grade, _evaluate_counter){ new_grade = _new_grade; evaluate_counter = _evaluate_counter; cbk(err, 0); }); }, //get action threshold so i can update every suggestion threshold function(obj, cbk){ models.Action.findById(object.action_id, function(err, result){ cbk(err, result) }); }, function(action_obj,cbk){ async.parallel([ //set notifications for all users of proxy function(cbk1){ //Todo - set notifications // models.User.find({"proxy.user_id": req.user._id}, function(err, slaves_users){ // async.forEach(slaves_users, function(slave, itr_cbk){ // notifications.create_user_proxy_vote_or_grade_notification("proxy_graded_discussion", // discussion_obj._id, slave._id, req.user._id, // null, null, g_grade.evaluation_grade, // function(err){ // itr_cbk(err); // }) // }, function(err){ // cbk1(err); // }) // }) cbk1(null); }, //calculate all change suggestion all over again function(cbk1){ action_thresh = Number(action_obj.admin_threshold_for_accepting_change_suggestions) || action_obj.threshold_for_accepting_change_suggestions; models.ActionSuggestion.find({action_id: grade_object.action_id}, {"_id":1}, function(err, results) { cbk1(err, results); }); } ], function(err, args){ cbk(err, args[1]); } ) }, function(suggestions, cbk){ async.forEach(suggestions, iterator, cbk); } ], function(err){ callback(err, {new_grade: new_grade, evaluate_counter: evaluate_counter, suggestions: suggestions,grade_id: g_grade._id || 0}) }) } }); } }); function calculateActionGrade(action_id, callback){ var count; var grade_sum; var new_grade; var threshold; async.waterfall([ function(cbk){ models.GradeAction.find({action_id: action_id}, {"evaluation_grade":1, "proxy_power":1}, cbk); }, function(grades, cbk){ count = grades.length; if(count){ //calculate grade_sum with take proxy power in consideration grade_sum = _.reduce(grades, function(memo, grade){return memo + Number(grade.evaluation_grade * (grade.proxy_power || 1)); }, 0); //calculate count with take proxy power in consideration count = _.reduce(grades, function(memo, grade){return memo + Number(grade.proxy_power || 1)}, 0); new_grade = grade_sum / count; //calculate threshhold here threshold = calc_thresh.calculating_thresh(count, new_grade) || 50; models.Action.update({_id: action_id}, {$set: {grade: new_grade, evaluate_counter: count, threshold_for_accepting_change_suggestions: threshold}}, cbk); }else{ cbk({message: "you have to grade before changing the grade" , code: 401}); } } ],function(err, args){ callback(err, new_grade, count, threshold); }) }
saarsta/sheatufim
api/actions/GradeActionResource.js
JavaScript
mit
12,565
module Sample VERSION = '1.2' end
pavolzbell/bump
spec/fixtures/inputs/gem-2-version-numbers.rb
Ruby
mit
36
using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; namespace CameraModifications { public class LookButton : MonoBehaviour { public bool isHead; public H_Scene h_scene; public H_EditsUIControl controls; private GameObject buttonPrefab; public KocchiMitePlugin watchDog; private Toggle m_toggle; private UI_ShowCanvasGroup group; private int currentValue = -1; private Dictionary<LookAtRotator.TYPE, Toggle> toggles; private bool initialShutup = true; private void Start() { // Make buttons m_toggle = GetComponent<Toggle>(); m_toggle.onValueChanged.AddListener(HandleClick); controls.GetComponent<ToggleGroup>().RegisterToggle(m_toggle); try { MakeGroup(); } catch (Exception e) { Console.WriteLine(e); } } public int CurrentMode { get { return isHead ? watchDog.currentHeadType : watchDog.currentType; } } private void Update() { if (CurrentMode != currentValue) { currentValue = CurrentMode; toggles[(LookAtRotator.TYPE)currentValue].isOn = true; } initialShutup = false; } private void HandleClick(bool isOn) { try { if (isOn) { m_toggle.image.color = Color.blue; // Show h_scene.GC.SystemSE.Play_Click(); } else { m_toggle.image.color = Color.white; // Hide h_scene.GC.SystemSE.Play_Cancel(); } group.Show(isOn); Console.WriteLine(isOn); } catch (Exception e) { Console.WriteLine(e); } } private void MakeGroup() { var container = controls.transform.FindChild("EditStep2"); Console.WriteLine("C {0}", container); var exampleGroup = container.GetChild(0); Console.WriteLine("E {0}", exampleGroup); buttonPrefab = GameObject.Instantiate(container.GetComponentInChildren<Toggle>().gameObject) as GameObject; buttonPrefab.SetActive(false); group = new GameObject().AddComponent<CanvasGroup>().gameObject.AddComponent<UI_ShowCanvasGroup>(); group.gameObject.layer = LayerMask.NameToLayer("UI"); group.gameObject.AddComponent<ToggleGroup>().allowSwitchOff = false; group.gameObject.AddComponent<RectTransform>(exampleGroup.GetComponent<RectTransform>()); group.gameObject.AddComponent<VerticalLayoutGroup>(exampleGroup.GetComponent<VerticalLayoutGroup>()).childForceExpandHeight = false; group.transform.SetParent(container, false); //group.GetComponent<RectTransform>().GetCopyOf(exampleGroup.GetComponent<RectTransform>()); // Make buttons toggles = new Dictionary<LookAtRotator.TYPE, Toggle>() { { LookAtRotator.TYPE.NO, MakeButton(watchDog.useEnglish ? "None" : "無設定", LookAtRotator.TYPE.NO) }, { LookAtRotator.TYPE.AWAY, MakeButton(watchDog.useEnglish ? "Away" : "あっち向け", LookAtRotator.TYPE.AWAY)}, { LookAtRotator.TYPE.FORWARD, MakeButton(watchDog.useEnglish ? "Forward" : "正面向け", LookAtRotator.TYPE.FORWARD)}, { LookAtRotator.TYPE.TARGET, MakeButton(watchDog.useEnglish ? "Camera" : "こっち向け", LookAtRotator.TYPE.TARGET)} }; foreach (var button in toggles.Values) { button.transform.SetParent(group.transform, false); } //group.gameObject.AddComponent<Image>().color = Color.red; } private Toggle MakeButton(string text, LookAtRotator.TYPE type) { var buttonObj = Instantiate(buttonPrefab) as GameObject; buttonObj.SetActive(true); GameObject.DestroyImmediate(buttonObj.GetComponent<global::UI_ShowCanvasGroup>()); buttonObj.AddComponent<UI_ShowCanvasGroup>(); var buttonEl = buttonObj.GetComponent<Toggle>(); Console.WriteLine(buttonEl.group); buttonEl.onValueChanged = new Toggle.ToggleEvent(); buttonEl.group = group.GetComponent<ToggleGroup>(); // set text Console.WriteLine(buttonPrefab.name); buttonEl.GetComponentInChildren<Text>().text = text; //buttonEl.GetComponentInChildren<Text>().resizeTextForBestFit = true; //buttonEl.GetComponentInChildren<Text>().resizeTextMinSize = 1; buttonEl.onValueChanged.AddListener((state) => { if (state) { if(!initialShutup) h_scene.GC.SystemSE.Play_Click(); if (isHead) { watchDog.currentHeadType = (int)type; if(!initialShutup) watchDog.oldHeadLook.IsChecked = false; } else { watchDog.currentType = (int)type; if (!initialShutup) watchDog.oldEyeLook.IsChecked = false; } currentValue = (int)type; buttonEl.image.color = Color.blue; } else { buttonEl.image.color = Color.white; } }); return buttonEl; } } }
Eusth/Illusion-Plugins
CameraModifications/LookButton.cs
C#
mit
6,055
/** * This Control enables to render a Scene with a Screen Space Ambient Occlusion (SSAO) effect. * * @namespace GIScene * @class Control.SSAO * @constructor * @extends GIScene.Control */ GIScene.Control.SSAO = function() { //inherit GIScene.Control.call(this); var scenePass; var ssaoEffect; var fxaaEffect; var depthTarget; var depthShader; var depthUniforms; var depthMaterial; var depthCam; var activeCam; var updateDepthCam = function() { // if(depthCam !== undefined && depthCam.parent !== undefined){ // this.scene.camera.remove(depthCam); // } //depthCam activeCam = (this.scene.camera instanceof THREE.CombinedCamera)? ( (this.scene.camera.inPerspectiveMode)? this.scene.camera.cameraP : this.scene.camera.cameraO ) : this.scene.camera; depthCam = activeCam.clone(); this.scene.camera.add(depthCam); // depthCam = new THREE.PerspectiveCamera(); // //POSITION // depthCam.fov = activeCam.fov; // depthCam.aspect = activeCam.aspect; depthCam.near = 0.1; depthCam.far = 1000; depthCam.updateProjectionMatrix(); //console.log(depthCam); //updateSsaoUniforms();//mca }.bind(this); var updateSsaoUniforms = function() { ssaoEffect.uniforms[ 'tDepth' ].value = depthTarget; ssaoEffect.uniforms[ 'size' ].value.x = this.scene.canvas.width; ssaoEffect.uniforms[ 'size' ].value.y = this.scene.canvas.height; ssaoEffect.uniforms[ 'cameraNear' ].value = depthCam.near; ssaoEffect.uniforms[ 'cameraFar' ].value = depthCam.far; }.bind(this); var onBeforeRender = function() { // activeCam = (this.scene.camera instanceof THREE.CombinedCamera)? // ( (this.scene.camera.inPerspectiveMode)? this.scene.camera.cameraP : this.scene.camera.cameraO ) // : // this.scene.camera; // activeCam = this.scene.camera.cameraP.clone(); // this.scene.root.overrideMaterial = depthMaterial;//new THREE.MeshDepthMaterial({blending: THREE.NoBlending}); // activeCam.near = 0.1; // activeCam.far = 1500; // activeCam.updateProjectionMatrix(); this.scene.renderer.clearTarget(depthTarget,true, true, false); //color, depth, stencil this.scene.renderer.render(this.scene.root, depthCam, depthTarget); // activeCam.near = this.scene.config.near; // activeCam.far = this.scene.config.far; // activeCam.updateProjectionMatrix(); this.scene.root.overrideMaterial = null; // // this.scene.root.overrideMaterial = null; }.bind(this); var onChangedProjection = function(event) { console.log("chPrj2",activeCam); updateDepthCam(); }; var onResize = function() { updateDepthCam(); depthTarget = new THREE.WebGLRenderTarget( this.scene.canvas.width, this.scene.canvas.height, { minFilter: THREE.NearestFilter, magFilter: THREE.NearestFilter, format: THREE.RGBAFormat } ); updateSsaoUniforms(); fxaaEffect.uniforms[ 'resolution' ].value.set( 1 / this.scene.canvas.width, 1 / this.scene.canvas.height ); }.bind(this); this.activate_ = function() { if(!this.isActive){ scenePass = new THREE.RenderPass( this.scene.root, this.scene.camera ); ssaoEffect = new THREE.ShaderPass( THREE.SSAOShader ); depthTarget = new THREE.WebGLRenderTarget( this.scene.canvas.width, this.scene.canvas.height, { minFilter: THREE.NearestFilter, magFilter: THREE.NearestFilter, format: THREE.RGBAFormat } ); depthShader = THREE.ShaderLib[ "depthRGBA" ]; depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms ); depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } ); depthMaterial.blending = THREE.NoBlending; this.scene.addEventListener('beforeRender', onBeforeRender); // function(){ // // this.scene.root.overrideMaterial = depthMaterial;//new THREE.MeshDepthMaterial({blending: THREE.NoBlending}); // this.scene.camera.cameraP.near = 0.1; // this.scene.camera.cameraP.far = 1500; // this.scene.camera.cameraP.updateProjectionMatrix(); // this.scene.renderer.clearTarget(depthTarget,true, true, true); // this.scene.renderer.render(this.scene.root, this.scene.camera, depthTarget); // // this.scene.camera.cameraP.near = this.scene.config.near; // this.scene.camera.cameraP.far = this.scene.config.far; // this.scene.camera.cameraP.updateProjectionMatrix(); // this.scene.root.overrideMaterial = null; // // }.bind(this) // ); ssaoEffect.uniforms[ 'tDepth' ].value = depthTarget; ssaoEffect.uniforms[ 'size' ].value.x = this.scene.canvas.width; ssaoEffect.uniforms[ 'size' ].value.y = this.scene.canvas.height; ssaoEffect.uniforms[ 'cameraNear' ].value = this.scene.camera.near; ssaoEffect.uniforms[ 'cameraFar' ].value = this.scene.camera.far; ssaoEffect.uniforms[ 'onlyAO' ].value = 1; ssaoEffect.renderToScreen = true; this.scene.effectComposer.addPass(scenePass); this.scene.effectComposer.addPass(ssaoEffect); } //call super class method GIScene.Control.prototype.activate.call(this); }; this.activate = function() { if(!this.isActive){ //depth map depthTarget = new THREE.WebGLRenderTarget( this.scene.canvas.width, this.scene.canvas.height, { minFilter: THREE.NearestFilter, magFilter: THREE.NearestFilter, format: THREE.RGBAFormat } ); depthShader = THREE.ShaderLib[ "depthRGBA" ]; depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms ); depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } ); depthMaterial.blending = THREE.NoBlending; //depthCam updateDepthCam(); //define passes scenePass = new THREE.RenderPass( this.scene.root, this.scene.camera ); ssaoEffect = new THREE.ShaderPass( THREE.SSAOShader ); fxaaEffect = new THREE.ShaderPass( THREE.FXAAShader ); updateSsaoUniforms(); ssaoEffect.renderToScreen = true; fxaaEffect.uniforms[ 'resolution' ].value.set( 1 / this.scene.canvas.width, 1 / this.scene.canvas.height ); fxaaEffect.renderToScreen = false; //add beforeRender Event this.scene.addEventListener('beforeRender2', onBeforeRender); //be sure, there are no other passes active //add passes this.scene.effectComposer.passes = [scenePass, fxaaEffect, ssaoEffect]; // this.scene.effectComposer.addPass(scenePass); // this.scene.effectComposer.addPass(ssaoEffect); //add other events window.addEventListener('resize', onResize, false); this.scene.camera.addEventListener('changedProjection', onChangedProjection); //call super class method GIScene.Control.prototype.activate.call(this); } }; this.deactivate = function() { if(this.isActive){ //remove passes this.scene.effectComposer.passes = []; //remove depthCam this.scene.camera.remove(depthCam); //remove Events this.scene.removeEventListener('beforeRender2', onBeforeRender); window.removeEventListener('resize', onResize, false); this.scene.camera.removeEventListener('changedProjection', onChangedProjection); //call super class method GIScene.Control.prototype.deactivate.call(this); } }; }; GIScene.Control.SSAO.prototype = Object.create(GIScene.Control.prototype);
GIScience/GIScene.js
lib/GIScene/Control/SSAO.js
JavaScript
mit
7,334
package com.cnpc.framework.utils; import com.cnpc.framework.base.pojo.GenerateSetting; import freemarker.template.Configuration; import freemarker.template.DefaultObjectWrapper; import freemarker.template.Template; import freemarker.template.TemplateException; import org.springframework.core.io.Resource; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.core.io.support.ResourcePatternResolver; import java.io.*; public class FreeMarkerUtil { /** * 获取模板路径 * * @param templateName * 模板名称(含后缀名) * @return * @throws IOException */ public static String getTemplatePath(String templateName) throws IOException { Resource res = FreeMarkerUtil.getResource(templateName); return res.getFile().getPath(); } /** * 获取模板资源 * * @param templateName * 模板名称(含后缀名) * @return Resource */ public static Resource getResource(String templateName) { ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); Resource res = resolver.getResource("/template/" + templateName); return res; } /** * 获取模板 * * @param templateName * 模板名称(含后缀名) * @return Template * @throws IOException */ public static Template getTemplate(String templateName) throws IOException { Configuration cfg = new Configuration(); Template temp = null; File tmpRootFile = getResource(templateName).getFile().getParentFile(); if (tmpRootFile == null) { throw new RuntimeException("无法取得模板根路径!"); } try { cfg.setDefaultEncoding("utf-8"); cfg.setOutputEncoding("utf-8"); cfg.setDirectoryForTemplateLoading(tmpRootFile); /* cfg.setDirectoryForTemplateLoading(getResourceURL()); */ cfg.setObjectWrapper(new DefaultObjectWrapper()); temp = cfg.getTemplate(templateName); } catch (IOException e) { e.printStackTrace(); } return temp; } /** * 根据freemark模板生成文件 * * @param templateName * 模板名称(含后缀名) * @param filePath * 生成文件路径 * @param setting * 参数 */ public static void generateFile(String templateName, String filePath, GenerateSetting setting) throws TemplateException, IOException { Writer writer = null; Template template = getTemplate(templateName); // Windows/Linux // String dir = filePath.substring(0, filePath.lastIndexOf("\\")); String dir = filePath.substring(0, filePath.lastIndexOf("/")); File fdir = new File(dir); if (!fdir.exists()) { if (!fdir.mkdirs()) { System.out.println("创建目录" + fdir.getAbsolutePath() + "失败"); return; } } File file = new File(filePath); if(file.exists()) file.delete(); writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "utf-8")); template.setEncoding("utf-8"); template.process(setting, writer); writer.flush(); writer.close(); } }
XilongPei/Openparts
Openparts-framework/src/main/java/com/cnpc/framework/utils/FreeMarkerUtil.java
Java
mit
3,038
<?php /* @SRVDVServer/Registration/checkEmail.html.twig */ class __TwigTemplate_b7388a253fe83dce0c06be9794c45a140b6b7d51b0d7f4393b8bb6ea03bbb2f5 extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); // line 1 $this->parent = $this->loadTemplate("FOSUserBundle::layout.html.twig", "@SRVDVServer/Registration/checkEmail.html.twig", 1); $this->blocks = array( 'fos_user_content' => array($this, 'block_fos_user_content'), ); } protected function doGetParent(array $context) { return "FOSUserBundle::layout.html.twig"; } protected function doDisplay(array $context, array $blocks = array()) { $this->parent->display($context, array_merge($this->blocks, $blocks)); } // line 6 public function block_fos_user_content($context, array $blocks = array()) { // line 7 echo " <p>"; echo twig_escape_filter($this->env, $this->env->getExtension('Symfony\Bridge\Twig\Extension\TranslationExtension')->trans("registration.check_email", array("%email%" => $this->getAttribute((isset($context["user"]) ? $context["user"] : null), "email", array())), "FOSUserBundle"), "html", null, true); echo "</p> "; } public function getTemplateName() { return "@SRVDVServer/Registration/checkEmail.html.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 31 => 7, 28 => 6, 11 => 1,); } /** @deprecated since 1.27 (to be removed in 2.0). Use getSourceContext() instead */ public function getSource() { @trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getSourceContext() instead.', E_USER_DEPRECATED); return $this->getSourceContext()->getCode(); } public function getSourceContext() { return new Twig_Source("", "@SRVDVServer/Registration/checkEmail.html.twig", "C:\\wamp64\\www\\serveurDeVoeuxOmar\\src\\SRVDV\\ServerBundle\\Resources\\views\\Registration\\checkEmail.html.twig"); } }
youcefboukersi/serveurdevoeux
app/cache/prod/twig/26/2661d52b18638f3c0557a97abe21ab4f663d0577907552ec42ba9fb1790acde1.php
PHP
mit
2,198
import * as b from "bobril"; import { IRouteWithNavDefinition } from "../../../../common/routing"; import { Anchor } from "../../../../common/Anchor"; import { Example } from "../../../../common/Example"; import { Col, Form, margin, Row } from "../../../../../index"; import { Code } from "../../../../common/Code"; import { Lead } from "../../../../common/Lead"; export const formControlsRoute: IRouteWithNavDefinition = { url: "form-controls", name: "form-controls", label: "Form controls", handler: () => <FormsDoc />, subs: [ { url: "example", name: "form-controls-example", label: "Example", subs: [], }, { url: "sizing", name: "form-controls-sizing", label: "Sizing", subs: [], }, { url: "readonly", name: "form-controls-readonly", label: "Readonly", subs: [], }, { url: "readonly-plain-text", name: "form-controls-readonly-plain-text", label: "Readonly plain text", subs: [], }, { url: "file-input", name: "form-controls-file-input", label: "File input", subs: [], }, { url: "color", name: "form-controls-color", label: "Color", subs: [], }, { url: "datalist", name: "form-controls-datalist", label: "Datalist", subs: [], }, ], }; export function FormsDoc(): b.IBobrilNode { return ( <> <Anchor name="form-controls"> <h1>Form controls</h1> </Anchor> <Lead> Give textual form controls like <code>{`<Form.Input>`}</code>s, <code>{`<Form.Select>`}</code>s, and{" "} <code>{`<Form.Textarea>`}</code>s an upgrade with custom styles, sizing, focus states, and more. </Lead> <Anchor name="form-controls-example"> <h2>Form controls</h2> </Anchor> <Example> <Form> <div style={margin("b", 3)}> <Form.Label for="exampleFormControlInput1">Email address</Form.Label> <Form.Input type="email" id="exampleFormControlInput1" placeholder="name@example.com" /> </div> <div style={margin("b", 3)}> <Form.Label for="exampleFormControlTextarea1">Example textarea</Form.Label> <Form.Textarea id="exampleFormControlTextarea1" rows="3" /> </div> </Form> </Example> <Code language="tsx">{` <Form> <div style={margin("b", 3)}> <Form.Label for="exampleFormControlInput1">Email address</Form.Label> <Form.Input type="email" id="exampleFormControlInput1" placeholder="name@example.com" /> </div> <div style={margin("b", 3)}> <Form.Label for="exampleFormControlTextarea1">Example textarea</Form.Label> <Form.Textarea id="exampleFormControlTextarea1" rows="3" /> </div> </Form>`}</Code> <Anchor name="form-controls-sizing"> <h3>Sizing</h3> </Anchor> <p> Set <code>size</code> prop. </p> <Example> <Form.Input type="text" size="lg" placeholder="lg" /> <Form.Input type="text" placeholder="Default input" /> <Form.Input type="text" size="sm" placeholder="sm" /> </Example> <Code language="tsx">{`<Form.Input type="text" size="lg" placeholder="lg" /> <Form.Input type="text" placeholder="Default input" /> <Form.Input type="text" size="sm" placeholder="sm" />`}</Code> <Anchor name="form-controls-readonly"> <h3>Readonly</h3> </Anchor> <p> Add the <code>readonly</code> boolean prop on an input to prevent modification of the input’s value. Read-only inputs appear lighter (just like disabled inputs), but retain the standard cursor. </p> <Example> <Form.Input type="text" placeholder="Readonly input here..." readonly /> </Example> <Code language="tsx">{`<Form.Input type="text" placeholder="Readonly input here..." readonly />`}</Code> <Anchor name="form-controls-readonly-plain-text"> <h3>Readonly plain text</h3> </Anchor> <p> If you want to have <code>readonly</code> elements in your form styled as plain text, use the <code>plain-text</code> prop to remove the default form field styling and preserve the correct margin and padding. </p> <Example> <Form> <Row style={margin("b", 3)}> <Form.Label col sm={2} for="staticEmail"> Email </Form.Label> <Col sm={10}> <Form.Input type="text" readonly plain-text id="staticEmail" value="email@example.com" /> </Col> </Row> <Row style={margin("b", 3)}> <Form.Label col sm={2} for="inputPassword"> Password </Form.Label> <Col sm={10}> <Form.Input type="password" id="inputPassword" /> </Col> </Row> </Form> </Example> <Code language="tsx">{`<Form> <Row style={margin("b", 3)}> <Form.Label col sm={2} for="staticEmail"> Email </Form.Label> <Col sm={10}> <Form.Input type="text" readonly plain-text id="staticEmail" value="email@example.com" /> </Col> </Row> <Row style={margin("b", 3)}> <Form.Label col sm={2} for="inputPassword"> Password </Form.Label> <Col sm={10}> <Form.Input type="password" id="inputPassword" /> </Col> </Row> </Form>`}</Code> <Anchor name="form-controls-file-input"> <h3>File input</h3> </Anchor> <Example> <div style={margin("b", 3)}> <Form.Label for="formFile">Default file input example</Form.Label> <Form.Input type="file" id="formFile" /> </div> <div style={margin("b", 3)}> <Form.Label for="formFileMultiple">Multiple files input example</Form.Label> <Form.Input type="file" id="formFileMultiple" multiple /> </div> <div style={margin("b", 3)}> <Form.Label for="formFileDisabled">Disabled file input example</Form.Label> <Form.Input type="file" id="formFileDisabled" disabled /> </div> <div style={margin("b", 3)}> <Form.Label for="formFileSm">Small file input example</Form.Label> <Form.Input size="sm" id="formFileSm" type="file" /> </div> <div> <Form.Label for="formFileLg">Large file input example</Form.Label> <Form.Input size="lg" id="formFileLg" type="file" /> </div> </Example> <Code language="tsx">{`<div style={margin("b", 3)}> <Form.Label for="formFile">Default file input example</Form.Label> <Form.Input type="file" id="formFile" /> </div> <div style={margin("b", 3)}> <Form.Label for="formFileMultiple">Multiple files input example</Form.Label> <Form.Input type="file" id="formFileMultiple" multiple /> </div> <div style={margin("b", 3)}> <Form.Label for="formFileDisabled">Disabled file input example</Form.Label> <Form.Input type="file" id="formFileDisabled" disabled /> </div> <div style={margin("b", 3)}> <Form.Label for="formFileSm"> Small file input example </Form.Label> <Form.Input size="sm" id="formFileSm" type="file" /> </div> <div> <Form.Label for="formFileLg">Large file input example</Form.Label> <Form.Input size="lg" id="formFileLg" type="file" /> </div>`}</Code> <Anchor name="form-controls-color"> <h3>Color</h3> </Anchor> <Example> <Form.Label for="exampleColorInput">Color picker</Form.Label> <Form.Input type="color" id="exampleColorInput" value="#563d7c" title="Choose your color" /> </Example> <Code language="tsx">{`<Form.Label for="exampleColorInput">Color picker</Form.Label> <Form.Input type="color" id="exampleColorInput" value="#563d7c" title="Choose your color" />`}</Code> <Anchor name="form-controls-datalist"> <h3>Datalist</h3> </Anchor> <p> Datalists allow you to create a group of <code>{`<Form.Option>`}</code>s that can be accessed (and autocompleted) from within an <code>{`<Form.Input>`}</code>. These are similar to <code>{`<Form.Select>`}</code>s, but come with more menu styling limitations and differences. While most browsers and operating systems include some support for{" "} <code>{`<Form.Datalist>`}</code>s, their styling is inconsistent at best. </p> <Example> <Form.Label for="exampleDataList">Datalist example</Form.Label> <Form.Input type="datalist" list="datalistOptions" id="exampleDataList" placeholder="Type to search..." /> <Form.Datalist id="datalistOptions"> <Form.Option value="San Francisco" /> <Form.Option value="New York" /> <Form.Option value="Seattle" /> <Form.Option value="Los Angeles" /> <Form.Option value="Chicago" /> </Form.Datalist> </Example> <Code language="tsx">{`<Form.Label for="exampleDataList">Datalist example</Form.Label> <Form.Input type="datalist" list="datalistOptions" id="exampleDataList" placeholder="Type to search..." /> <Form.Datalist id="datalistOptions"> <Form.Option value="San Francisco" /> <Form.Option value="New York" /> <Form.Option value="Seattle" /> <Form.Option value="Los Angeles" /> <Form.Option value="Chicago" /> </Form.Datalist>`}</Code> </> ); }
keeema/bobrilstrap
example/documentation/content/forms/parts/FormsControls.tsx
TypeScript
mit
10,921
package easyauth import ( "context" "crypto/rand" "encoding/base64" "fmt" "html/template" "log" "net/http" "strings" "time" "github.com/gorilla/mux" ) //Role is a number representing a permission level. //Specific roles will be defined by the host application. //It is intended to be a bitmask. //Each user will have a certain permission level associated, as can any endpoint or content. //If the user permissions and the content requirement have any common bits (user & content != 0), then access will be granted. type Role uint32 type User struct { Username string Access Role Method string Data interface{} } //AuthProvider is any source of user authentication. These core methods must be implemented by all providers. type AuthProvider interface { //Retreive a user from the current http request if present. GetUser(r *http.Request) (*User, error) } //FormProvider is a provider that accepts login info from an html form. type FormProvider interface { AuthProvider GetRequiredFields() []string HandlePost(http.ResponseWriter, *http.Request) } //HTTPProvider is a provider that provides an http handler form managing its own login endpoints, for example oauth. //Will receive all calls to /{providerName}/* type HTTPProvider interface { AuthProvider http.Handler } type Logoutable interface { //Logout allows the provider to delete any relevant cookies or session data in order to log the user out. //The provider should not otherwise write to the response, or redirect Logout(w http.ResponseWriter, r *http.Request) } type AuthManager interface { AddProvider(string, AuthProvider) LoginHandler() http.Handler Wrapper(required Role) func(http.Handler) http.Handler Wrap(next http.Handler, required Role) http.Handler WrapFunc(next http.HandlerFunc, required Role) http.Handler } type namedProvider struct { Name string Provider AuthProvider } type namedFormProvider struct { Name string Provider FormProvider } type namedHTTPProvider struct { Name string Provider HTTPProvider } type authManager struct { Providers []namedProvider FormProviders []namedFormProvider HTTPProviders []namedHTTPProvider names map[string]bool cookie *CookieManager loginTemplate *template.Template } func New(opts ...Option) (AuthManager, error) { var mgr = &authManager{ names: map[string]bool{}, cookie: &CookieManager{ duration: int(time.Hour * 24 * 30), }, } for _, opt := range opts { if err := opt(mgr); err != nil { return nil, err } } if mgr.loginTemplate == nil { mgr.loginTemplate = template.Must(template.New("login").Parse(loginTemplate)) } return mgr, nil } func (m *authManager) AddProvider(name string, p AuthProvider) { if _, ok := m.names[name]; ok { panic(fmt.Errorf("Auth provider %s registered multiple times", name)) } m.names[name] = true m.Providers = append(m.Providers, namedProvider{name, p}) if form, ok := p.(FormProvider); ok { m.FormProviders = append(m.FormProviders, namedFormProvider{name, form}) } if httpp, ok := p.(HTTPProvider); ok { m.HTTPProviders = append(m.HTTPProviders, namedHTTPProvider{name, httpp}) } } func (m *authManager) LoginHandler() http.Handler { mx := mux.NewRouter() mx.Path("/").Methods("GET").HandlerFunc(m.loginPage) mx.Path("/out").Methods("GET").HandlerFunc(m.logout) mx.Path("/deny").Methods("GET").HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("<html><body><h1>Access denied</h1>You do not have access to the requested content.")) }) for _, form := range m.FormProviders { mx.Path(fmt.Sprintf("/%s", form.Name)).Methods("POST").HandlerFunc(func(w http.ResponseWriter, r *http.Request) { m.postForm(w, r, form.Provider) }) } for _, httpp := range m.HTTPProviders { mx.PathPrefix(fmt.Sprintf("/%s/", httpp.Name)).HandlerFunc(func(w http.ResponseWriter, r *http.Request) { m.delegateHTTP(w, r, httpp.Provider) }) } return mx } func (m *authManager) buildContext(w http.ResponseWriter, r *http.Request) *http.Request { ctx := context.WithValue(r.Context(), cookieContextKey, m.cookie) ctx = context.WithValue(ctx, redirectContextKey, func() { m.redirect(w, r) }) return r.WithContext(ctx) } //Wrapper returns a middleware constructor for the given auth level. This function can be used with middleware chains //or by itself to create new handlers in the future func (m *authManager) Wrapper(required Role) func(http.Handler) http.Handler { return func(h http.Handler) http.Handler { return m.Wrap(h, required) } } func (m *authManager) Wrap(next http.Handler, required Role) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { orig := r r = m.buildContext(w, r) var u *User var err error for _, p := range m.Providers { u, err = p.Provider.GetUser(r) if err != nil { log.Println(err) continue } if u != nil { r = orig //don't send intenral context to real handler r = r.WithContext(context.WithValue(r.Context(), userContextKey, u)) break } } if required == 0 { //no permission needed next.ServeHTTP(w, r) } else if u == nil { //logged out. redir to login if strings.Contains(r.Header.Get("Accept"), "html") { m.cookie.SetCookiePlain(w, redirCookirName, 10*60, r.URL.String()) http.Redirect(w, r, "/login/", http.StatusFound) //todo: configure this } else { http.Error(w, "Access Denied", http.StatusForbidden) } } else if u.Access&required == 0 { //denied for permissions if strings.Contains(r.Header.Get("Accept"), "html") { m.cookie.SetCookiePlain(w, redirCookirName, 10*60, r.URL.String()) http.Redirect(w, r, "/login/deny", http.StatusFound) } else { http.Error(w, "Access Denied", http.StatusForbidden) } } else { //has permission next.ServeHTTP(w, r) } }) } func (m *authManager) WrapFunc(next http.HandlerFunc, required Role) http.Handler { return m.Wrap(next, required) } const ( errMsgCookieName = "errMsg" redirCookirName = "redirTo" ) func (m *authManager) loginPage(w http.ResponseWriter, r *http.Request) { msg, err := m.cookie.ReadCookiePlain(r, errMsgCookieName) if err == nil { m.cookie.ClearCookie(w, errMsgCookieName) } var ctx = map[string]interface{}{ "Auth": m, "Message": msg, } if err := m.loginTemplate.Execute(w, ctx); err != nil { log.Printf("Error executing login template: %s", err) } } func (m *authManager) logout(w http.ResponseWriter, r *http.Request) { r = m.buildContext(w, r) for _, p := range m.Providers { if lo, ok := p.Provider.(Logoutable); ok { lo.Logout(w, r) } } http.Redirect(w, r, "/", 302) } type contextKeyType int const ( cookieContextKey contextKeyType = iota redirectContextKey userContextKey ) func (m *authManager) delegateHTTP(w http.ResponseWriter, r *http.Request, h HTTPProvider) { r = m.buildContext(w, r) h.ServeHTTP(w, r) } func (m *authManager) redirect(w http.ResponseWriter, r *http.Request) { path := "/" stored, err := m.cookie.ReadCookiePlain(r, redirCookirName) if err == nil { path = stored m.cookie.ClearCookie(w, redirCookirName) } http.Redirect(w, r, path, http.StatusFound) } func (m *authManager) postForm(w http.ResponseWriter, r *http.Request, p FormProvider) { defer func() { if rc := recover(); rc != nil { //set short-lived cookie with message and redirect to login page m.cookie.SetCookiePlain(w, errMsgCookieName, 60, fmt.Sprint(rc)) http.Redirect(w, r, r.Header.Get("Referer"), http.StatusFound) } }() r = m.buildContext(w, r) p.HandlePost(w, r) } func GetCookieManager(r *http.Request) *CookieManager { return r.Context().Value(cookieContextKey).(*CookieManager) } func GetRedirector(r *http.Request) func() { return r.Context().Value(redirectContextKey).(func()) } func GetUser(r *http.Request) *User { u := r.Context().Value(userContextKey) if u == nil { return nil } return u.(*User) } //RandomString returns a random string of bytes length long, base64 encoded. func RandomString(length int) string { var dat = make([]byte, length) rand.Read(dat) return base64.StdEncoding.EncodeToString(dat) }
alienth/bosun
vendor/github.com/captncraig/easyauth/auth.go
GO
mit
8,164
import { h } from 'omi'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon(h("path", { d: "M20 15H4c-.55 0-1 .45-1 1s.45 1 1 1h16c.55 0 1-.45 1-1s-.45-1-1-1zm0-5H4c-.55 0-1 .45-1 1v1c0 .55.45 1 1 1h16c.55 0 1-.45 1-1v-1c0-.55-.45-1-1-1zm0-6H4c-.55 0-1 .45-1 1v2c0 .55.45 1 1 1h16c.55 0 1-.45 1-1V5c0-.55-.45-1-1-1zm.5 15h-17c-.28 0-.5.22-.5.5s.22.5.5.5h17c.28 0 .5-.22.5-.5s-.22-.5-.5-.5z" }), 'LineWeightRounded');
AlloyTeam/Nuclear
components/icon/esm/line-weight-rounded.js
JavaScript
mit
447
using ENode.EQueue; using ENode.Eventing; namespace ENode.Tests { public class EventTopicProvider : AbstractTopicProvider<IDomainEvent> { public override string GetTopic(IDomainEvent source) { return "EventTopic"; } } }
ouraspnet/ENode.Standard
test/ENode.Test/Providers/EventTopicProvider.cs
C#
mit
272
#!/usr/bin/env python # coding: utf-8 import os,sys import ctypes import numpy as np from .hmatrix import _C_HMatrix, HMatrix class _C_MultiHMatrix(ctypes.Structure): """Holder for the raw data from the C++ code.""" pass class AbstractMultiHMatrix: """Common code for the two actual MultiHMatrix classes below.""" ndim = 2 # To mimic a numpy 2D array def __init__(self, c_data: _C_MultiHMatrix, **params): # Users should use one of the two constructors below. self.c_data = c_data self.shape = (self.lib.multi_nbrows(c_data), self.lib.multi_nbcols(c_data)) self.size = self.lib.nbhmats(c_data) self.lib.getHMatrix.restype=ctypes.POINTER(_C_HMatrix) self.lib.getHMatrix.argtypes=[ctypes.POINTER(_C_MultiHMatrix), ctypes.c_int] self.hmatrices = [] for l in range(0,self.size): c_data_hmatrix = self.lib.getHMatrix(self.c_data,l) self.hmatrices.append(HMatrix(c_data_hmatrix,**params)) self.params = params.copy() @classmethod def from_coefs(cls, getcoefs, nm, points_target, points_source=None, **params): """Construct an instance of the class from a evaluation function. Parameters ---------- getcoefs: Callable A function evaluating an array of matrices at given coordinates. points_target: np.ndarray of shape (N, 3) The coordinates of the target points. If points_source=None, also the coordinates of the target points points_source: np.ndarray of shape (N, 3) If not None; the coordinates of the source points. epsilon: float, keyword-only, optional Tolerance of the Adaptive Cross Approximation eta: float, keyword-only, optional Criterion to choose the blocks to compress minclustersize: int, keyword-only, optional Minimum shape of a block maxblocksize: int, keyword-only, optional Maximum number of coefficients in a block Returns ------- MultiHMatrix or ComplexMultiHMatrix """ # Set params. cls._set_building_params(**params) # Boilerplate code for Python/C++ interface. _getcoefs_func_type = ctypes.CFUNCTYPE(None, ctypes.c_int, ctypes.c_int, ctypes.POINTER(ctypes.c_double)) if points_source is None: cls.lib.MultiHMatrixCreateSym.restype = ctypes.POINTER(_C_MultiHMatrix) cls.lib.MultiHMatrixCreateSym.argtypes = [ np.ctypeslib.ndpointer(dtype=np.float64, ndim=2, flags='C_CONTIGUOUS'), ctypes.c_int, _getcoefs_func_type, ctypes.c_int ] # Call the C++ backend. c_data = cls.lib.MultiHMatrixCreateSym(points_target, points_target.shape[0], _getcoefs_func_type(getcoefs),nm) else: cls.lib.MultiHMatrixCreate.restype = ctypes.POINTER(_C_MultiHMatrix) cls.lib.MultiHMatrixCreate.argtypes = [ np.ctypeslib.ndpointer(dtype=np.float64, ndim=2, flags='C_CONTIGUOUS'), ctypes.c_int, np.ctypeslib.ndpointer(dtype=np.float64, ndim=2, flags='C_CONTIGUOUS'), ctypes.c_int, _getcoefs_func_type, ctypes.c_int ] # Call the C++ backend. c_data = cls.lib.MultiHMatrixCreate(points_target,points_target.shape[0],points_source, points_source.shape[0], _getcoefs_func_type(getcoefs),nm) return cls(c_data, **params) @classmethod def from_submatrices(cls, getsubmatrix, nm, points_target, points_source=None, **params): """Construct an instance of the class from a evaluation function. Parameters ---------- points: np.ndarray of shape (N, 3) The coordinates of the points. getsubmatrix: Callable A function evaluating the matrix in a given range. epsilon: float, keyword-only, optional Tolerance of the Adaptive Cross Approximation eta: float, keyword-only, optional Criterion to choose the blocks to compress minclustersize: int, keyword-only, optional Minimum shape of a block maxblocksize: int, keyword-only, optional Maximum number of coefficients in a block Returns ------- HMatrix or ComplexHMatrix """ # Set params. cls._set_building_params(**params) # Boilerplate code for Python/C++ interface. _getsumatrix_func_type = ctypes.CFUNCTYPE( None, ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_int), ctypes.c_int, ctypes.c_int, ctypes.POINTER(ctypes.c_double) ) if points_source is None: cls.lib.MultiHMatrixCreatewithsubmatSym.restype = ctypes.POINTER(_C_MultiHMatrix) cls.lib.MultiHMatrixCreatewithsubmatSym.argtypes = [ np.ctypeslib.ndpointer(dtype=np.float64, ndim=2, flags='C_CONTIGUOUS'), ctypes.c_int, _getsumatrix_func_type, ctypes.c_int ] # Call the C++ backend. c_data = cls.lib.MultiHMatrixCreatewithsubmatSym(points_target, points_target.shape[0], _getsumatrix_func_type(getsubmatrix),nm) else: cls.lib.MultiHMatrixCreatewithsubmat.restype = ctypes.POINTER(_C_MultiHMatrix) cls.lib.MultiHMatrixCreatewithsubmat.argtypes = [ np.ctypeslib.ndpointer(dtype=np.float64, ndim=2, flags='C_CONTIGUOUS'), ctypes.c_int, np.ctypeslib.ndpointer(dtype=np.float64, ndim=2, flags='C_CONTIGUOUS'), ctypes.c_int, _getsumatrix_func_type, ctypes.c_int ] # Call the C++ backend. c_data = cls.lib.MultiHMatrixCreatewithsubmat(points_target,points_target.shape[0],points_source, points_source.shape[0], _getsumatrix_func_type(getsubmatrix),nm) return cls(c_data, **params) @classmethod def _set_building_params(cls, *, eta=None, minclustersize=None, epsilon=None, maxblocksize=None): """Put the parameters in the C++ backend.""" if epsilon is not None: cls.lib.setepsilon.restype = None cls.lib.setepsilon.argtypes = [ ctypes.c_double ] cls.lib.setepsilon(epsilon) if eta is not None: cls.lib.seteta.restype = None cls.lib.seteta.argtypes = [ ctypes.c_double ] cls.lib.seteta(eta) if minclustersize is not None: cls.lib.setminclustersize.restype = None cls.lib.setminclustersize.argtypes = [ ctypes.c_int ] cls.lib.setminclustersize(minclustersize) if maxblocksize is not None: cls.lib.setmaxblocksize.restype = None cls.lib.setmaxblocksize.argtypes = [ ctypes.c_int ] cls.lib.setmaxblocksize(maxblocksize) def __str__(self): return f"{self.__class__.__name__}(shape={self.shape})" def __getitem__(self, key): # self.lib.getHMatrix.restype=ctypes.POINTER(_C_HMatrix) # self.lib.getHMatrix.argtypes=[ctypes.POINTER(_C_MultiHMatrix), ctypes.c_int] # c_data_hmatrix = self.lib.getHMatrix(self.c_data,key) # return HMatrix(c_data_hmatrix,**self.params) return self.hmatrices[key] def matvec(self, l , vector): """Matrix-vector product (interface for scipy iterative solvers).""" assert self.shape[1] == vector.shape[0], "Matrix-vector product of matrices of wrong shapes." # Boilerplate for Python/C++ interface self.lib.MultiHMatrixVecProd.argtypes = [ ctypes.POINTER(_C_MultiHMatrix), ctypes.c_int, np.ctypeslib.ndpointer(self.dtype, flags='C_CONTIGUOUS'), np.ctypeslib.ndpointer(self.dtype, flags='C_CONTIGUOUS') ] # Initialize vector result = np.zeros((self.shape[0],), dtype=self.dtype) # Call C++ backend self.lib.MultiHMatrixVecProd(self.c_data,l , vector, result) return result class MultiHMatrix(AbstractMultiHMatrix): """A real-valued hierarchical matrix based on htool C++ library. Create with HMatrix.from_coefs or HMatrix.from_submatrices. Attributes ---------- c_data: Pointer to the raw data used by the C++ library. shape: Tuple[int, int] Shape of the matrix. nb_dense_blocks: int Number of dense blocks in the hierarchical matrix. nb_low_rank_blocks: int Number of sparse blocks in the hierarchical matrix. nb_blocks: int Total number of blocks in the decomposition. params: dict The parameters that have been used to build the matrix. """ libfile = os.path.join(os.path.dirname(__file__), '../libhtool_shared') if 'linux' in sys.platform: lib = ctypes.cdll.LoadLibrary(libfile+'.so') elif sys.platform == 'darwin': lib = ctypes.cdll.LoadLibrary(libfile+'.dylib') elif sys.platform == 'win32': lib = ctypes.cdll.LoadLibrary(libfile+'.dll') dtype = ctypes.c_double class ComplexMultiHMatrix(AbstractMultiHMatrix): """A complex-valued hierarchical matrix based on htool C++ library. Create with ComplexHMatrix.from_coefs or ComplexHMatrix.from_submatrices. Attributes ---------- c_data: Pointer to the raw data used by the C++ library. shape: Tuple[int, int] Shape of the matrix. nb_dense_blocks: int Number of dense blocks in the hierarchical matrix. nb_low_rank_blocks: int Number of sparse blocks in the hierarchical matrix. nb_blocks: int Total number of blocks in the decomposition. params: dict The parameters that have been used to build the matrix. """ libfile = os.path.join(os.path.dirname(__file__), '../libhtool_shared_complex') if 'linux' in sys.platform: lib = ctypes.cdll.LoadLibrary(libfile+'.so') elif sys.platform == 'darwin': lib = ctypes.cdll.LoadLibrary(libfile+'.dylib') elif sys.platform == 'win32': lib = ctypes.cdll.LoadLibrary(libfile+'.dll') dtype = np.complex128
PierreMarchand20/htool
interface/htool/multihmatrix.py
Python
mit
10,354
public class Grid { public Tile array[][] = new Tile[10][8]; public Grid() { // for(int y = 0; y < getHeight(); y++) { for(int x = 0; x < getWidth(); x++) { array[x][y] = new Tile(); } } } public int getWidth() { return 9; } public int getHeight() { return 7; } public Tile getTile(int x, int y) { Tile mytile = new Tile(); try { //System.out.println("Actual tile returned"); mytile = array[x][y]; } catch(ArrayIndexOutOfBoundsException e) { //System.out.println("Out of bounds tile"); } finally { //System.out.println("Returning false tile"); return mytile; } } public void makeHole() { for(int y = 0; y < getHeight(); y++) { for(int x = 0; x < getWidth(); x++) { if(((y == 1) || (y == 5)) && (x>=3) && (x<=6)) { array[x][y].visible = false; } if(((y == 2) || (y == 4)) && (x>=2) && (x<=6)) { array[x][y].visible = false; } if((y == 3) && (x>=2) && (x<=7)) { array[x][y].visible = false; } } } } public void makeHolierHole() { for(int y = 0; y < getHeight(); y++) { for(int x = 0; x < getWidth(); x++) { if((x >= 1+y%2) && (x <= 5+y%2)) { array[x][y].visible = false; } } } } }
Caaz/danmaku-class-project
Grid.java
Java
mit
1,391
import {normalize, resolve} from "path"; import {existsSync, readFileSync} from "fs"; import {sys, ScriptSnapshot, resolveModuleName, getDefaultLibFilePath} from "typescript"; export function createServiceHost(options, filenames, cwd) { const normalizePath = (path) => resolve(normalize(path)); const moduleResolutionHost = createModuleResolutionHost(); const files = {}; // normalized filename => {version, snap, text} filenames.forEach(filename => files[normalizePath(filename)] = null); return { getDirectories: sys.getDirectories, directoryExists: sys.directoryExists, readDirectory: sys.readDirectory, getDefaultLibFileName: getDefaultLibFilePath, fileExists(filename) { filename = normalizePath(filename); return filename in files || sys.fileExists(filename); }, readFile(filename) { return readFileSync(normalizePath(filename), "utf-8"); }, getCompilationSettings() { return options; }, getCurrentDirectory() { return cwd; }, getScriptFileNames() { return Object.keys(files); }, getScriptVersion(filename) { const f = files[normalizePath(filename)]; return f ? f.version.toString() : ""; }, getScriptSnapshot(filename) { let f = files[normalizePath(filename)]; if(!f) { f = this.addFile(filename, this.readFile(filename)); } return f.snap; }, resolveModuleNames(moduleNames, containingFile) { return moduleNames.map(name => this.resolveModuleName(name, containingFile)); }, getNewLine() { return options.newLine || sys.newLine; }, // additional methods containsFile(filename) { return normalizePath(filename) in files; }, resolveModuleName(moduleName, containingFile) { const {resolvedModule} = resolveModuleName(moduleName, containingFile, options, moduleResolutionHost); if(resolvedModule) { resolvedModule.resolvedFileName = normalizePath(resolvedModule.resolvedFileName); resolvedModule.originalFileName = resolvedModule.resolvedFileName; } return resolvedModule; }, addFile(filename, text) { filename = normalizePath(filename); const snap = ScriptSnapshot.fromString(text); snap.getChangeRange = () => {}; let file = files[filename]; if(!file) { file = {version: 0}; files[filename] = file; } ++file.version; file.snap = snap; file.text = text; return file; }, }; } function createModuleResolutionHost() { return { fileExists(filename) { return existsSync(filename); }, readFile(filename) { return readFileSync(filename, "utf-8") }, }; }
tsne/rollup-plugin-tsc
src/servicehost.js
JavaScript
mit
2,558
package main import ( "fmt" "log" ) type ListCommand struct { All bool `short:"a" long:"available" description:"also prints all available version for installation"` } type InitCommand struct{} type InstallCommand struct { Use bool `short:"u" long:"use" description:"force use of this new version after installation"` } type UseCommand struct{} type Interactor struct { archive WebotsArchive manager WebotsInstanceManager templates TemplateManager } func NewInteractor() (*Interactor, error) { res := &Interactor{} var err error res.archive, err = NewWebotsHttpArchive("http://www.cyberbotics.com/archive/") if err != nil { return nil, err } manager, err := NewSymlinkManager(res.archive) if err != nil { return nil, err } res.manager = manager res.templates = manager.templates return res, nil } func (x *ListCommand) Execute(args []string) error { xx, err := NewInteractor() if err != nil { return err } installed := xx.manager.Installed() if len(installed) == 0 { fmt.Printf("No webots version installed.\n") } else { for _, v := range installed { if xx.manager.IsUsed(v) == true { fmt.Printf(" -* %s\n", v) } else { fmt.Printf(" - %s\n", v) } } } if x.All { fmt.Println("List of all available versions:") for _, v := range xx.archive.AvailableVersions() { fmt.Printf(" - %s\n", v) } } else { vers := xx.archive.AvailableVersions() if len(vers) == 0 { return fmt.Errorf("No version are available") } fmt.Printf("Last available version is %s\n", vers[len(vers)-1]) } return nil } func (x *InitCommand) Execute(args []string) error { return SymlinkManagerSystemInit() } func (x *InstallCommand) Execute(args []string) error { if len(args) != 1 { return fmt.Errorf("Missing version to install") } v, err := ParseWebotsVersion(args[0]) if err != nil { return err } xx, err := NewInteractor() if err != nil { return err } err = xx.manager.Install(v) if err != nil { return err } notUsed := true for _, vv := range xx.manager.Installed() { if xx.manager.IsUsed(vv) { notUsed = false break } } if notUsed || x.Use { err = xx.manager.Use(v) if err != nil { return err } log.Printf("Using now version %s", v) } return nil } func (x *UseCommand) Execute(args []string) error { if len(args) != 1 { return fmt.Errorf("Missing version to use") } v, err := ParseWebotsVersion(args[0]) if err != nil { return err } xx, err := NewInteractor() if err != nil { return err } return xx.manager.Use(v) } type AddTemplateCommand struct { Only []string `short:"o" long:"only" description:"apply template only for these versions"` Except []string `short:"e" long:"except" description:"do not apply template on these versions"` } func (x *AddTemplateCommand) Execute(args []string) error { if len(args) != 2 { return fmt.Errorf("Need file to read and where to install") } var white, black []WebotsVersion for _, w := range x.Only { v, err := ParseWebotsVersion(w) if err != nil { return err } white = append(white, v) } for _, w := range x.Except { v, err := ParseWebotsVersion(w) if err != nil { return err } black = append(black, v) } xx, err := NewInteractor() if err != nil { return err } err = xx.templates.RegisterTemplate(args[0], args[1]) if err != nil { return err } err = xx.templates.WhiteList(args[1], white) if err != nil { return err } err = xx.templates.BlackList(args[1], black) if err != nil { return err } return xx.manager.ApplyAllTemplates() } type RemoveTemplateCommand struct{} func (x *RemoveTemplateCommand) Execute(args []string) error { if len(args) != 1 { return fmt.Errorf("Need install path to remove template from") } xx, err := NewInteractor() if err != nil { return err } err = xx.templates.RemoveTemplate(args[0]) if err != nil { return err } return xx.manager.ApplyAllTemplates() } func init() { parser.AddCommand("list", "Prints all the available version of webots", "Prints all installed version, and current version in use. Can also prinst all available version for installation", &ListCommand{}) parser.AddCommand("init", "Initialiaze the system for webots_manager", "Initialiaze the system with all requirement for webots_manager", &InitCommand{}) parser.AddCommand("install", "Install a new webots version on the system", "Installs a new webots version on the system", &InstallCommand{}) parser.AddCommand("use", "Use a webots version on the system", "Use a webots version on the system. If it is not installed, it will first install it", &UseCommand{}) parser.AddCommand("add-template", "Adds a template file to all version", "Install a file to all version of webots. -o and -e can be used to explicitely whitelist or blacklist a version", &AddTemplateCommand{}) parser.AddCommand("remove-template", "Removes a template file from all version", "Removes a previously installed template from all version of webots.", &RemoveTemplateCommand{}) }
biorob/webots-manager
commands.go
GO
mit
5,064
/* * $Id: Perl5Matcher.java,v 1.27 2003/11/07 20:16:25 dfs Exp $ * * ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2000 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. 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. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Apache" and "Apache Software Foundation", "Jakarta-Oro" * must not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache" * or "Jakarta-Oro", nor may "Apache" or "Jakarta-Oro" appear in their * name, without prior written permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ package org.apache.oro.text.regex; import java.util.Stack; /** * The Perl5Matcher class is used to match regular expressions (conforming to * the Perl5 regular expression syntax) generated by Perl5Compiler. * <p> * Perl5Compiler and Perl5Matcher are designed with the intent that you use a * separate instance of each per thread to avoid the overhead of both * synchronization and concurrent access (e.g., a match that takes a long time * in one thread will block the progress of another thread with a shorter * match). If you want to use a single instance of each in a concurrent program, * you must appropriately protect access to the instances with critical * sections. If you want to share Perl5Pattern instances between concurrently * executing instances of Perl5Matcher, you must compile the patterns with * {@link Perl5Compiler#READ_ONLY_MASK}. * * @since 1.0 * @see PatternMatcher * @see Perl5Compiler */ public final class Perl5Matcher implements PatternMatcher { private static final char __EOS = Character.MAX_VALUE; private static final int __INITIAL_NUM_OFFSETS = 20; private final boolean __multiline = false; private boolean __lastSuccess = false; private boolean __caseInsensitive = false; private char __previousChar, __input[], __originalInput[]; private Perl5Repetition __currentRep; private int __numParentheses, __bol, __eol, __currentOffset, __endOffset; private char[] __program; private int __expSize, __inputOffset, __lastParen; private int[] __beginMatchOffsets, __endMatchOffsets; private final Stack<int[]> __stack = new Stack<int[]>(); private Perl5MatchResult __lastMatchResult = null; private static boolean __compare(final char[] s1, final int s1off, final char[] s2, final int s2off, final int n) { int s2Offs = s2off; int s1Offs = s1off; int cnt; for (cnt = 0; cnt < n; cnt++, s1Offs++, s2Offs++) { if (s1Offs >= s1.length) { return false; } if (s2Offs >= s2.length) { return false; } if (s1[s1Offs] != s2[s2Offs]) { return false; } } return true; } private static int __findFirst(final char[] input, final int curr, final int endOffset, final char[] mustString) { int current = curr; int count, saveCurrent; char ch; if (input.length == 0) { return endOffset; } ch = mustString[0]; // Find the offset of the first character of the must string while (current < endOffset) { if (ch == input[current]) { saveCurrent = current; count = 0; while (current < endOffset && count < mustString.length) { if (mustString[count] != input[current]) { break; } ++count; ++current; } current = saveCurrent; if (count >= mustString.length) { break; } } ++current; } return current; } private void __pushState(final int parenFloor) { int[] state; int stateEntries, paren; stateEntries = 3 * (this.__expSize - parenFloor); if (stateEntries <= 0) { state = new int[3]; } else { state = new int[stateEntries + 3]; } state[0] = this.__expSize; state[1] = this.__lastParen; state[2] = this.__inputOffset; for (paren = this.__expSize; paren > parenFloor; --paren, stateEntries -= 3) { state[stateEntries] = this.__endMatchOffsets[paren]; state[stateEntries + 1] = this.__beginMatchOffsets[paren]; state[stateEntries + 2] = paren; } this.__stack.push(state); } private void __popState() { int[] state; int entry, paren; state = this.__stack.pop(); this.__expSize = state[0]; this.__lastParen = state[1]; this.__inputOffset = state[2]; for (entry = 3; entry < state.length; entry += 3) { paren = state[entry + 2]; this.__beginMatchOffsets[paren] = state[entry + 1]; if (paren <= this.__lastParen) { this.__endMatchOffsets[paren] = state[entry]; } } for (paren = this.__lastParen + 1; paren <= this.__numParentheses; paren++) { if (paren > this.__expSize) { this.__beginMatchOffsets[paren] = OpCode._NULL_OFFSET; } this.__endMatchOffsets[paren] = OpCode._NULL_OFFSET; } } // Initialize globals needed before calling __tryExpression for first time private void __initInterpreterGlobals(final Perl5Pattern expression, final char[] input, final int beginOffset, final int endOff, final int currentOffset) { int endOffset = endOff; // Remove this hack after more efficient case-folding and unicode // character classes are implemented this.__caseInsensitive = expression._isCaseInsensitive; this.__input = input; this.__endOffset = endOffset; this.__currentRep = new Perl5Repetition(); this.__currentRep._numInstances = 0; this.__currentRep._lastRepetition = null; this.__program = expression._program; this.__stack.setSize(0); // currentOffset should always be >= beginOffset and should // always be equal to zero when beginOffset equals 0, but we // make a weak attempt to protect against a violation of this // precondition if (currentOffset == beginOffset || currentOffset <= 0) { this.__previousChar = '\n'; } else { this.__previousChar = input[currentOffset - 1]; if (!this.__multiline && this.__previousChar == '\n') { this.__previousChar = '\0'; } } this.__numParentheses = expression._numParentheses; this.__currentOffset = currentOffset; this.__bol = beginOffset; this.__eol = endOffset; // Ok, here we're using endOffset as a temporary variable. endOffset = this.__numParentheses + 1; if (this.__beginMatchOffsets == null || endOffset > this.__beginMatchOffsets.length) { if (endOffset < __INITIAL_NUM_OFFSETS) { endOffset = __INITIAL_NUM_OFFSETS; } this.__beginMatchOffsets = new int[endOffset]; this.__endMatchOffsets = new int[endOffset]; } } // Set the match result information. Only call this if we successfully // matched. private void __setLastMatchResult() { int offs, maxEndOffs = 0; // endOffset+=dontTry; this.__lastMatchResult = new Perl5MatchResult(this.__numParentheses + 1); // This can happen when using Perl5StreamInput if (this.__endMatchOffsets[0] > this.__originalInput.length) { throw new ArrayIndexOutOfBoundsException(); } this.__lastMatchResult._matchBeginOffset = this.__beginMatchOffsets[0]; while (this.__numParentheses >= 0) { offs = this.__beginMatchOffsets[this.__numParentheses]; if (offs >= 0) { this.__lastMatchResult._beginGroupOffset[this.__numParentheses] = offs - this.__lastMatchResult._matchBeginOffset; } else { this.__lastMatchResult._beginGroupOffset[this.__numParentheses] = OpCode._NULL_OFFSET; } offs = this.__endMatchOffsets[this.__numParentheses]; if (offs >= 0) { this.__lastMatchResult._endGroupOffset[this.__numParentheses] = offs - this.__lastMatchResult._matchBeginOffset; if (offs > maxEndOffs && offs <= this.__originalInput.length) { maxEndOffs = offs; } } else { this.__lastMatchResult._endGroupOffset[this.__numParentheses] = OpCode._NULL_OFFSET; } --this.__numParentheses; } this.__lastMatchResult._match = new String(this.__originalInput, this.__beginMatchOffsets[0], maxEndOffs - this.__beginMatchOffsets[0]); // Free up for garbage collection this.__originalInput = null; } // Expects to receive a valid regular expression program. No checking // is done to ensure validity. // __originalInput must be set before calling this method for // __lastMatchResult to be set correctly. // beginOffset marks the beginning of the string // currentOffset marks where to start the pattern search private boolean __interpret(final Perl5Pattern expression, final char[] input, final int beginOffset, final int endOff, final int currentOffset) { int endOffset = endOff; boolean success; int minLength = 0, dontTry = 0, offset; char ch, mustString[]; __initInterpreterGlobals(expression, input, beginOffset, endOffset, currentOffset); success = false; mustString = expression._mustString; _mainLoop: while (true) { if (mustString != null && ((expression._anchor & Perl5Pattern._OPT_ANCH) == 0 || (this.__multiline || (expression._anchor & Perl5Pattern._OPT_ANCH_MBOL) != 0) && expression._back >= 0)) { this.__currentOffset = __findFirst(this.__input, this.__currentOffset, endOffset, mustString); if (this.__currentOffset >= endOffset) { if ((expression._options & Perl5Compiler.READ_ONLY_MASK) == 0) { expression._mustUtility++; } success = false; break _mainLoop; } else if (expression._back >= 0) { this.__currentOffset -= expression._back; if (this.__currentOffset < currentOffset) { this.__currentOffset = currentOffset; } minLength = expression._back + mustString.length; } else if (!expression._isExpensive && (expression._options & Perl5Compiler.READ_ONLY_MASK) == 0 && --expression._mustUtility < 0) { // Be careful! The preceding logical expression is // constructed // so that mustUtility is only decremented if the expression // is // compiled without READ_ONLY_MASK. mustString = expression._mustString = null; this.__currentOffset = currentOffset; } else { this.__currentOffset = currentOffset; minLength = mustString.length; } } if ((expression._anchor & Perl5Pattern._OPT_ANCH) != 0) { if (this.__currentOffset == beginOffset && __tryExpression(beginOffset)) { success = true; break _mainLoop; } else if (this.__multiline || (expression._anchor & Perl5Pattern._OPT_ANCH_MBOL) != 0 || (expression._anchor & Perl5Pattern._OPT_IMPLICIT) != 0) { if (minLength > 0) { dontTry = minLength - 1; } endOffset -= dontTry; if (this.__currentOffset > currentOffset) { --this.__currentOffset; } while (this.__currentOffset < endOffset) { if (this.__input[this.__currentOffset++] == '\n') { if (this.__currentOffset < endOffset && __tryExpression(this.__currentOffset)) { success = true; break _mainLoop; } } } } break _mainLoop; } if (expression._startString != null) { mustString = expression._startString; if ((expression._anchor & Perl5Pattern._OPT_SKIP) != 0) { ch = mustString[0]; while (this.__currentOffset < endOffset) { if (ch == this.__input[this.__currentOffset]) { if (__tryExpression(this.__currentOffset)) { success = true; break _mainLoop; } ++this.__currentOffset; while (this.__currentOffset < endOffset && this.__input[this.__currentOffset] == ch) { ++this.__currentOffset; } } ++this.__currentOffset; } } else { while ((this.__currentOffset = __findFirst(this.__input, this.__currentOffset, endOffset, mustString)) < endOffset) { if (__tryExpression(this.__currentOffset)) { success = true; break _mainLoop; } ++this.__currentOffset; } } break _mainLoop; } if ((offset = expression._startClassOffset) != OpCode._NULL_OFFSET) { boolean doEvery, tmp; char op; doEvery = (expression._anchor & Perl5Pattern._OPT_SKIP) == 0; if (minLength > 0) { dontTry = minLength - 1; } endOffset -= dontTry; tmp = true; switch (op = this.__program[offset]) { case OpCode._ANYOF: offset = OpCode._getOperand(offset); while (this.__currentOffset < endOffset) { ch = this.__input[this.__currentOffset]; if (ch < 256 && (this.__program[offset + (ch >> 4)] & 1 << (ch & 0xf)) == 0) { if (tmp && __tryExpression(this.__currentOffset)) { success = true; break _mainLoop; } tmp = doEvery; } else { tmp = true; } ++this.__currentOffset; } break; case OpCode._ANYOFUN: case OpCode._NANYOFUN: offset = OpCode._getOperand(offset); while (this.__currentOffset < endOffset) { ch = this.__input[this.__currentOffset]; if (__matchUnicodeClass(ch, this.__program, offset, op)) { if (tmp && __tryExpression(this.__currentOffset)) { success = true; break _mainLoop; } tmp = doEvery; } else { tmp = true; } ++this.__currentOffset; } break; case OpCode._BOUND: if (minLength > 0) { ++dontTry; --endOffset; } if (this.__currentOffset != beginOffset) { ch = this.__input[this.__currentOffset - 1]; tmp = OpCode._isWordCharacter(ch); } else { tmp = OpCode._isWordCharacter(this.__previousChar); } while (this.__currentOffset < endOffset) { ch = this.__input[this.__currentOffset]; if (tmp != OpCode._isWordCharacter(ch)) { tmp = !tmp; if (__tryExpression(this.__currentOffset)) { success = true; break _mainLoop; } } ++this.__currentOffset; } if ((minLength > 0 || tmp) && __tryExpression(this.__currentOffset)) { success = true; break _mainLoop; } break; case OpCode._NBOUND: if (minLength > 0) { ++dontTry; --endOffset; } if (this.__currentOffset != beginOffset) { ch = this.__input[this.__currentOffset - 1]; tmp = OpCode._isWordCharacter(ch); } else { tmp = OpCode._isWordCharacter(this.__previousChar); } while (this.__currentOffset < endOffset) { ch = this.__input[this.__currentOffset]; if (tmp != OpCode._isWordCharacter(ch)) { tmp = !tmp; } else if (__tryExpression(this.__currentOffset)) { success = true; break _mainLoop; } ++this.__currentOffset; } if ((minLength > 0 || !tmp) && __tryExpression(this.__currentOffset)) { success = true; break _mainLoop; } break; case OpCode._ALNUM: while (this.__currentOffset < endOffset) { ch = this.__input[this.__currentOffset]; if (OpCode._isWordCharacter(ch)) { if (tmp && __tryExpression(this.__currentOffset)) { success = true; break _mainLoop; } tmp = doEvery; } else { tmp = true; } ++this.__currentOffset; } break; case OpCode._NALNUM: while (this.__currentOffset < endOffset) { ch = this.__input[this.__currentOffset]; if (!OpCode._isWordCharacter(ch)) { if (tmp && __tryExpression(this.__currentOffset)) { success = true; break _mainLoop; } tmp = doEvery; } else { tmp = true; } ++this.__currentOffset; } break; case OpCode._SPACE: while (this.__currentOffset < endOffset) { if (Character .isWhitespace(this.__input[this.__currentOffset])) { if (tmp && __tryExpression(this.__currentOffset)) { success = true; break _mainLoop; } tmp = doEvery; } else { tmp = true; } ++this.__currentOffset; } break; case OpCode._NSPACE: while (this.__currentOffset < endOffset) { if (!Character .isWhitespace(this.__input[this.__currentOffset])) { if (tmp && __tryExpression(this.__currentOffset)) { success = true; break _mainLoop; } tmp = doEvery; } else { tmp = true; } ++this.__currentOffset; } break; case OpCode._DIGIT: while (this.__currentOffset < endOffset) { if (Character .isDigit(this.__input[this.__currentOffset])) { if (tmp && __tryExpression(this.__currentOffset)) { success = true; break _mainLoop; } tmp = doEvery; } else { tmp = true; } ++this.__currentOffset; } break; case OpCode._NDIGIT: while (this.__currentOffset < endOffset) { if (!Character .isDigit(this.__input[this.__currentOffset])) { if (tmp && __tryExpression(this.__currentOffset)) { success = true; break _mainLoop; } tmp = doEvery; } else { tmp = true; } ++this.__currentOffset; } break; default: break; } // end switch } else { if (minLength > 0) { dontTry = minLength - 1; } endOffset -= dontTry; do { if (__tryExpression(this.__currentOffset)) { success = true; break _mainLoop; } } while (this.__currentOffset++ < endOffset); } break _mainLoop; } // end while this.__lastSuccess = success; this.__lastMatchResult = null; return success; } private boolean __matchUnicodeClass(final char code, final char __program1[], final int off, final char opcode) { int offset = off; boolean isANYOF = opcode == OpCode._ANYOFUN; while (__program1[offset] != OpCode._END) { if (__program1[offset] == OpCode._RANGE) { offset++; if (code >= __program1[offset] && code <= __program1[offset + 1]) { return isANYOF; } offset += 2; } else if (__program1[offset] == OpCode._ONECHAR) { offset++; if (__program1[offset++] == code) { return isANYOF; } } else { isANYOF = __program1[offset] == OpCode._OPCODE ? isANYOF : !isANYOF; offset++; switch (__program1[offset++]) { case OpCode._ALNUM: if (OpCode._isWordCharacter(code)) { return isANYOF; } break; case OpCode._NALNUM: if (!OpCode._isWordCharacter(code)) { return isANYOF; } break; case OpCode._SPACE: if (Character.isWhitespace(code)) { return isANYOF; } break; case OpCode._NSPACE: if (!Character.isWhitespace(code)) { return isANYOF; } break; case OpCode._DIGIT: if (Character.isDigit(code)) { return isANYOF; } break; case OpCode._NDIGIT: if (!Character.isDigit(code)) { return isANYOF; } break; case OpCode._ALNUMC: if (Character.isLetterOrDigit(code)) { return isANYOF; } break; case OpCode._ALPHA: if (Character.isLetter(code)) { return isANYOF; } break; case OpCode._BLANK: if (Character.isSpaceChar(code)) { return isANYOF; } break; case OpCode._CNTRL: if (Character.isISOControl(code)) { return isANYOF; } break; case OpCode._LOWER: if (Character.isLowerCase(code)) { return isANYOF; } // Remove this hack after more efficient case-folding and // unicode // character classes are implemented if (this.__caseInsensitive && Character.isUpperCase(code)) { return isANYOF; } break; case OpCode._UPPER: if (Character.isUpperCase(code)) { return isANYOF; } // Remove this hack after more efficient case-folding and // unicode // character classes are implemented if (this.__caseInsensitive && Character.isLowerCase(code)) { return isANYOF; } break; case OpCode._PRINT: if (Character.isSpaceChar(code)) { return isANYOF; } // Fall through to check if the character is alphanumeric, // or a punctuation mark. Printable characters are either // alphanumeric, punctuation marks, or spaces. //$FALL-THROUGH$ case OpCode._GRAPH: if (Character.isLetterOrDigit(code)) { return isANYOF; } // Fall through to check if the character is a punctuation // mark. // Graph characters are either alphanumeric or punctuation. //$FALL-THROUGH$ case OpCode._PUNCT: switch (Character.getType(code)) { case Character.DASH_PUNCTUATION: case Character.START_PUNCTUATION: case Character.END_PUNCTUATION: case Character.CONNECTOR_PUNCTUATION: case Character.OTHER_PUNCTUATION: case Character.MATH_SYMBOL: case Character.CURRENCY_SYMBOL: case Character.MODIFIER_SYMBOL: return isANYOF; default: break; } break; case OpCode._XDIGIT: if (code >= '0' && code <= '9' || code >= 'a' && code <= 'f' || code >= 'A' && code <= 'F') { return isANYOF; } break; case OpCode._ASCII: if (code < 0x80) { return isANYOF; } break; default: return !isANYOF; } } } return !isANYOF; } private boolean __tryExpression(final int offset) { int count; this.__inputOffset = offset; this.__lastParen = 0; this.__expSize = 0; if (this.__numParentheses > 0) { for (count = 0; count <= this.__numParentheses; count++) { this.__beginMatchOffsets[count] = OpCode._NULL_OFFSET; this.__endMatchOffsets[count] = OpCode._NULL_OFFSET; } } if (__match(1)) { this.__beginMatchOffsets[0] = offset; this.__endMatchOffsets[0] = this.__inputOffset; return true; } return false; } private int __repeat(final int offset, final int max) { int scan, eol, operand, ret; char ch; char op; scan = this.__inputOffset; eol = this.__eol; if (max != Character.MAX_VALUE && max < eol - scan) { eol = scan + max; } operand = OpCode._getOperand(offset); switch (op = this.__program[offset]) { case OpCode._ANY: while (scan < eol && this.__input[scan] != '\n') { ++scan; } break; case OpCode._SANY: scan = eol; break; case OpCode._EXACTLY: ++operand; while (scan < eol && this.__program[operand] == this.__input[scan]) { ++scan; } break; case OpCode._ANYOF: if (scan < eol && (ch = this.__input[scan]) < 256) { while (ch < 256 && (this.__program[operand + (ch >> 4)] & 1 << (ch & 0xf)) == 0) { if (++scan < eol) { ch = this.__input[scan]; } else { break; } } } break; case OpCode._ANYOFUN: case OpCode._NANYOFUN: if (scan < eol) { ch = this.__input[scan]; while (__matchUnicodeClass(ch, this.__program, operand, op)) { if (++scan < eol) { ch = this.__input[scan]; } else { break; } } } break; case OpCode._ALNUM: while (scan < eol && OpCode._isWordCharacter(this.__input[scan])) { ++scan; } break; case OpCode._NALNUM: while (scan < eol && !OpCode._isWordCharacter(this.__input[scan])) { ++scan; } break; case OpCode._SPACE: while (scan < eol && Character.isWhitespace(this.__input[scan])) { ++scan; } break; case OpCode._NSPACE: while (scan < eol && !Character.isWhitespace(this.__input[scan])) { ++scan; } break; case OpCode._DIGIT: while (scan < eol && Character.isDigit(this.__input[scan])) { ++scan; } break; case OpCode._NDIGIT: while (scan < eol && !Character.isDigit(this.__input[scan])) { ++scan; } break; default: break; } ret = scan - this.__inputOffset; this.__inputOffset = scan; return ret; } private boolean __match(final int offset) { char nextChar, op; int scan, next, input, maxScan, current, line, arg; boolean inputRemains = true, minMod = false; Perl5Repetition rep; input = this.__inputOffset; inputRemains = input < this.__endOffset; nextChar = inputRemains ? this.__input[input] : __EOS; scan = offset; maxScan = this.__program.length; while (scan < maxScan /* && scan > 0 */) { next = OpCode._getNext(this.__program, scan); switch (op = this.__program[scan]) { case OpCode._BOL: if (input == this.__bol ? this.__previousChar == '\n' : this.__multiline) { break; } return false; case OpCode._MBOL: if (input == this.__bol ? this.__previousChar == '\n' : (inputRemains || input < this.__eol) && this.__input[input - 1] == '\n') { break; } return false; case OpCode._SBOL: if (input == this.__bol && this.__previousChar == '\n') { break; } return false; case OpCode._GBOL: if (input == this.__bol) { break; } return true; case OpCode._EOL: if ((inputRemains || input < this.__eol) && nextChar != '\n') { return false; } if (!this.__multiline && this.__eol - input > 1) { return false; } break; case OpCode._MEOL: if ((inputRemains || input < this.__eol) && nextChar != '\n') { return false; } break; case OpCode._SEOL: if ((inputRemains || input < this.__eol) && nextChar != '\n') { return false; } if (this.__eol - input > 1) { return false; } break; case OpCode._SANY: if (!inputRemains && input >= this.__eol) { return false; } inputRemains = ++input < this.__endOffset; nextChar = inputRemains ? this.__input[input] : __EOS; break; case OpCode._ANY: if (!inputRemains && input >= this.__eol || nextChar == '\n') { return false; } inputRemains = ++input < this.__endOffset; nextChar = inputRemains ? this.__input[input] : __EOS; break; case OpCode._EXACTLY: current = OpCode._getOperand(scan); line = this.__program[current++]; if (this.__program[current] != nextChar) { return false; } if (this.__eol - input < line) { return false; } if (line > 1 && !__compare(this.__program, current, this.__input, input, line)) { return false; } input += line; inputRemains = input < this.__endOffset; nextChar = inputRemains ? this.__input[input] : __EOS; break; case OpCode._ANYOF: current = OpCode._getOperand(scan); if (nextChar == __EOS && inputRemains) { nextChar = this.__input[input]; } if (nextChar >= 256 || (this.__program[current + (nextChar >> 4)] & 1 << (nextChar & 0xf)) != 0) { return false; } if (!inputRemains && input >= this.__eol) { return false; } inputRemains = ++input < this.__endOffset; nextChar = inputRemains ? this.__input[input] : __EOS; break; case OpCode._ANYOFUN: case OpCode._NANYOFUN: current = OpCode._getOperand(scan); if (nextChar == __EOS && inputRemains) { nextChar = this.__input[input]; } if (!__matchUnicodeClass(nextChar, this.__program, current, op)) { return false; } if (!inputRemains && input >= this.__eol) { return false; } inputRemains = ++input < this.__endOffset; nextChar = inputRemains ? this.__input[input] : __EOS; break; case OpCode._ALNUM: if (!inputRemains) { return false; } if (!OpCode._isWordCharacter(nextChar)) { return false; } inputRemains = ++input < this.__endOffset; nextChar = inputRemains ? this.__input[input] : __EOS; break; case OpCode._NALNUM: if (!inputRemains && input >= this.__eol) { return false; } if (OpCode._isWordCharacter(nextChar)) { return false; } inputRemains = ++input < this.__endOffset; nextChar = inputRemains ? this.__input[input] : __EOS; break; case OpCode._NBOUND: case OpCode._BOUND: boolean a, b; if (input == this.__bol) { a = OpCode._isWordCharacter(this.__previousChar); } else { a = OpCode._isWordCharacter(this.__input[input - 1]); } b = OpCode._isWordCharacter(nextChar); if (a == b == (this.__program[scan] == OpCode._BOUND)) { return false; } break; case OpCode._SPACE: if (!inputRemains && input >= this.__eol) { return false; } if (!Character.isWhitespace(nextChar)) { return false; } inputRemains = ++input < this.__endOffset; nextChar = inputRemains ? this.__input[input] : __EOS; break; case OpCode._NSPACE: if (!inputRemains) { return false; } if (Character.isWhitespace(nextChar)) { return false; } inputRemains = ++input < this.__endOffset; nextChar = inputRemains ? this.__input[input] : __EOS; break; case OpCode._DIGIT: if (!Character.isDigit(nextChar)) { return false; } inputRemains = ++input < this.__endOffset; nextChar = inputRemains ? this.__input[input] : __EOS; break; case OpCode._NDIGIT: if (!inputRemains && input >= this.__eol) { return false; } if (Character.isDigit(nextChar)) { return false; } inputRemains = ++input < this.__endOffset; nextChar = inputRemains ? this.__input[input] : __EOS; break; case OpCode._REF: arg = OpCode._getArg1(this.__program, scan); current = this.__beginMatchOffsets[arg]; if (current == OpCode._NULL_OFFSET) { return false; } if (this.__endMatchOffsets[arg] == OpCode._NULL_OFFSET) { return false; } if (current == this.__endMatchOffsets[arg]) { break; } if (this.__input[current] != nextChar) { return false; } line = this.__endMatchOffsets[arg] - current; if (input + line > this.__eol) { return false; } if (line > 1 && !__compare(this.__input, current, this.__input, input, line)) { return false; } input += line; inputRemains = input < this.__endOffset; nextChar = inputRemains ? this.__input[input] : __EOS; break; case OpCode._NOTHING: break; case OpCode._BACK: break; case OpCode._OPEN: arg = OpCode._getArg1(this.__program, scan); this.__beginMatchOffsets[arg] = input; if (arg > this.__expSize) { this.__expSize = arg; } break; case OpCode._CLOSE: arg = OpCode._getArg1(this.__program, scan); this.__endMatchOffsets[arg] = input; if (arg > this.__lastParen) { this.__lastParen = arg; } break; case OpCode._CURLYX: rep = new Perl5Repetition(); rep._lastRepetition = this.__currentRep; this.__currentRep = rep; rep._parenFloor = this.__lastParen; rep._numInstances = -1; rep._min = OpCode._getArg1(this.__program, scan); rep._max = OpCode._getArg2(this.__program, scan); rep._scan = OpCode._getNextOperator(scan) + 2; rep._next = next; rep._minMod = minMod; // Must initialize to -1 because if we initialize to 0 and are // at the beginning of the input the OpCode._WHILEM case will // not work right. rep._lastLocation = -1; this.__inputOffset = input; // use minMod as temporary minMod = __match(OpCode._getPrevOperator(next)); // leave scope call not pertinent? this.__currentRep = rep._lastRepetition; return minMod; case OpCode._WHILEM: rep = this.__currentRep; arg = rep._numInstances + 1; this.__inputOffset = input; if (input == rep._lastLocation) { this.__currentRep = rep._lastRepetition; line = this.__currentRep._numInstances; if (__match(rep._next)) { return true; } this.__currentRep._numInstances = line; this.__currentRep = rep; return false; } if (arg < rep._min) { rep._numInstances = arg; rep._lastLocation = input; if (__match(rep._scan)) { return true; } rep._numInstances = arg - 1; return false; } if (rep._minMod) { this.__currentRep = rep._lastRepetition; line = this.__currentRep._numInstances; if (__match(rep._next)) { return true; } this.__currentRep._numInstances = line; this.__currentRep = rep; if (arg >= rep._max) { return false; } this.__inputOffset = input; rep._numInstances = arg; rep._lastLocation = input; if (__match(rep._scan)) { return true; } rep._numInstances = arg - 1; return false; } if (arg < rep._max) { __pushState(rep._parenFloor); rep._numInstances = arg; rep._lastLocation = input; if (__match(rep._scan)) { return true; } __popState(); this.__inputOffset = input; } this.__currentRep = rep._lastRepetition; line = this.__currentRep._numInstances; if (__match(rep._next)) { return true; } rep._numInstances = line; this.__currentRep = rep; rep._numInstances = arg - 1; return false; case OpCode._BRANCH: if (this.__program[next] != OpCode._BRANCH) { next = OpCode._getNextOperator(scan); } else { int lastParen; lastParen = this.__lastParen; do { this.__inputOffset = input; if (__match(OpCode._getNextOperator(scan))) { return true; } for (arg = this.__lastParen; arg > lastParen; --arg) { // __endMatchOffsets[arg] = 0; this.__endMatchOffsets[arg] = OpCode._NULL_OFFSET; } this.__lastParen = arg; scan = OpCode._getNext(this.__program, scan); } while (scan != OpCode._NULL_OFFSET && this.__program[scan] == OpCode._BRANCH); return false; } break; case OpCode._MINMOD: minMod = true; break; case OpCode._CURLY: case OpCode._STAR: case OpCode._PLUS: if (op == OpCode._CURLY) { line = OpCode._getArg1(this.__program, scan); arg = OpCode._getArg2(this.__program, scan); scan = OpCode._getNextOperator(scan) + 2; } else if (op == OpCode._STAR) { line = 0; arg = Character.MAX_VALUE; scan = OpCode._getNextOperator(scan); } else { line = 1; arg = Character.MAX_VALUE; scan = OpCode._getNextOperator(scan); } if (this.__program[next] == OpCode._EXACTLY) { nextChar = this.__program[OpCode._getOperand(next) + 1]; current = 0; } else { nextChar = __EOS; current = -1000; } this.__inputOffset = input; if (minMod) { minMod = false; if (line > 0 && __repeat(scan, line) < line) { return false; } while (arg >= line || arg == Character.MAX_VALUE && line > 0) { // there may be a bug here with respect to // __inputOffset >= __endOffset, but it seems to be // right for // now. the issue is with __inputOffset being reset // later. // is this test really supposed to happen here? if (current == -1000 || this.__inputOffset >= this.__endOffset || this.__input[this.__inputOffset] == nextChar) { if (__match(next)) { return true; } } this.__inputOffset = input + line; if (__repeat(scan, 1) != 0) { ++line; this.__inputOffset = input + line; } else { return false; } } } else { arg = __repeat(scan, arg); if (line < arg && OpCode._opType[this.__program[next]] == OpCode._EOL && (!this.__multiline && this.__program[next] != OpCode._MEOL || this.__program[next] == OpCode._SEOL)) { line = arg; } while (arg >= line) { // there may be a bug here with respect to // __inputOffset >= __endOffset, but it seems to be // right for // now. the issue is with __inputOffset being reset // later. // is this test really supposed to happen here? if (current == -1000 || this.__inputOffset >= this.__endOffset || this.__input[this.__inputOffset] == nextChar) { if (__match(next)) { return true; } } --arg; this.__inputOffset = input + arg; } } return false; case OpCode._SUCCEED: case OpCode._END: this.__inputOffset = input; // This enforces the rule that two consecutive matches cannot // have // the same end offset. if (this.__inputOffset == this.__lastMatchInputEndOffset) { return false; } return true; case OpCode._IFMATCH: this.__inputOffset = input; scan = OpCode._getNextOperator(scan); if (!__match(scan)) { return false; } break; case OpCode._UNLESSM: this.__inputOffset = input; scan = OpCode._getNextOperator(scan); if (__match(scan)) { return false; } break; default: // todo: Need to throw an exception here. } // end switch // scan = (next > 0 ? next : 0); scan = next; } // end while scan return false; } static char[] _toLower(final char[] in) { char[] input = in.clone(); int current; char[] inp; // todo: // Certainly not the best way to do case insensitive matching. // Must definitely change this in some way, but for now we // do what Perl does and make a copy of the input, converting // it all to lowercase. This is truly better handled in the // compilation phase. inp = new char[input.length]; System.arraycopy(input, 0, inp, 0, input.length); input = inp; // todo: Need to inline toLowerCase() for (current = 0; current < input.length; current++) { if (Character.isUpperCase(input[current])) { input[current] = Character.toLowerCase(input[current]); } } return input; } /** * Determines if a prefix of a string (represented as a char[]) matches a * given pattern, starting from a given offset into the string. If a prefix * of the string matches the pattern, a MatchResult instance representing * the match is made accesible via {@link #getMatch()}. * <p> * This method is useful for certain common token identification tasks that * are made more difficult without this functionality. * <p> * * @param in * The char[] to test for a prefix match. * @param pattern * The Pattern to be matched. * @param offset * The offset at which to start searching for the prefix. * @return True if input matches pattern, false otherwise. */ @Override public boolean matchesPrefix(final char[] in, final Pattern pattern, final int offset) { char[] input = in.clone(); final Perl5Pattern expression = (Perl5Pattern) pattern; this.__originalInput = input; if (expression._isCaseInsensitive) { input = _toLower(input); } __initInterpreterGlobals(expression, input, 0, input.length, offset); this.__lastSuccess = __tryExpression(offset); this.__lastMatchResult = null; return this.__lastSuccess; } /** * Determines if a prefix of a string (represented as a char[]) matches a * given pattern. If a prefix of the string matches the pattern, a * MatchResult instance representing the match is made accesible via * {@link #getMatch()}. * <p> * This method is useful for certain common token identification tasks that * are made more difficult without this functionality. * <p> * * @param input * The char[] to test for a prefix match. * @param pattern * The Pattern to be matched. * @return True if input matches pattern, false otherwise. */ @Override public boolean matchesPrefix(final char[] input, final Pattern pattern) { return matchesPrefix(input, pattern, 0); } /** * Determines if a prefix of a string matches a given pattern. If a prefix * of the string matches the pattern, a MatchResult instance representing * the match is made accesible via {@link #getMatch()}. * <p> * This method is useful for certain common token identification tasks that * are made more difficult without this functionality. * <p> * * @param input * The String to test for a prefix match. * @param pattern * The Pattern to be matched. * @return True if input matches pattern, false otherwise. */ @Override public boolean matchesPrefix(final String input, final Pattern pattern) { return matchesPrefix(input.toCharArray(), pattern, 0); } /** * Determines if a prefix of a PatternMatcherInput instance matches a given * pattern. If there is a match, a MatchResult instance representing the * match is made accesible via {@link #getMatch()}. Unlike the * {@link #contains(PatternMatcherInput, Pattern)} method, the current * offset of the PatternMatcherInput argument is not updated. However, * unlike the {@link #matches matches(PatternMatcherInput, Pattern)} method, * matchesPrefix() will start its search from the current offset rather than * the begin offset of the PatternMatcherInput. * <p> * This method is useful for certain common token identification tasks that * are made more difficult without this functionality. * <p> * * @param input * The PatternMatcherInput to test for a prefix match. * @param pattern * The Pattern to be matched. * @return True if input matches pattern, false otherwise. */ @Override public boolean matchesPrefix(final PatternMatcherInput input, final Pattern pattern) { char[] inp; Perl5Pattern expression; expression = (Perl5Pattern) pattern; this.__originalInput = input._originalBuffer; if (expression._isCaseInsensitive) { if (input._toLowerBuffer == null) { input._toLowerBuffer = _toLower(this.__originalInput); } inp = input._toLowerBuffer; } else { inp = this.__originalInput; } __initInterpreterGlobals(expression, inp, input._beginOffset, input._endOffset, input._currentOffset); this.__lastSuccess = __tryExpression(input._currentOffset); this.__lastMatchResult = null; return this.__lastSuccess; } /** * Determines if a string (represented as a char[]) exactly matches a given * pattern. If there is an exact match, a MatchResult instance representing * the match is made accesible via {@link #getMatch()}. The pattern must be * a Perl5Pattern instance, otherwise a ClassCastException will be thrown. * You are not required to, and indeed should NOT try to (for performance * reasons), catch a ClassCastException because it will never be thrown as * long as you use a Perl5Pattern as the pattern parameter. * <p> * <b>Note:</b> matches() is not the same as sticking a ^ in front of your * expression and a $ at the end of your expression in Perl5 and using the * =~ operator, even though in many cases it will be equivalent. matches() * literally looks for an exact match according to the rules of Perl5 * expression matching. Therefore, if you have a pattern <em>foo|foot</em> * and are matching the input <em>foot</em> it will not produce an exact * match. But <em>foot|foo</em> will produce an exact match for either * <em>foot</em> or <em>foo</em>. Remember, Perl5 regular expressions do not * match the longest possible match. From the perlre manpage: <blockquote> * Alternatives are tried from left to right, so the first alternative found * for which the entire expression matches, is the one that is chosen. This * means that alternatives are not necessarily greedy. For example: when * matching foo|foot against "barefoot", only the "foo" part will match, as * that is the first alternative tried, and it successfully matches the * target string. </blockquote> * <p> * * @param in * The char[] to test for an exact match. * @param pattern * The Perl5Pattern to be matched. * @return True if input matches pattern, false otherwise. * @exception ClassCastException * If a Pattern instance other than a Perl5Pattern is passed * as the pattern parameter. */ @Override public boolean matches(final char[] in, final Pattern pattern) { char[] input = in.clone(); final Perl5Pattern expression = (Perl5Pattern) pattern; this.__originalInput = input; if (expression._isCaseInsensitive) { input = _toLower(input); } __initInterpreterGlobals(expression, input, 0, input.length, 0); this.__lastSuccess = __tryExpression(0) && this.__endMatchOffsets[0] == input.length; this.__lastMatchResult = null; return this.__lastSuccess; } /** * Determines if a string exactly matches a given pattern. If there is an * exact match, a MatchResult instance representing the match is made * accesible via {@link #getMatch()}. The pattern must be a Perl5Pattern * instance, otherwise a ClassCastException will be thrown. You are not * required to, and indeed should NOT try to (for performance reasons), * catch a ClassCastException because it will never be thrown as long as you * use a Perl5Pattern as the pattern parameter. * <p> * <b>Note:</b> matches() is not the same as sticking a ^ in front of your * expression and a $ at the end of your expression in Perl5 and using the * =~ operator, even though in many cases it will be equivalent. matches() * literally looks for an exact match according to the rules of Perl5 * expression matching. Therefore, if you have a pattern <em>foo|foot</em> * and are matching the input <em>foot</em> it will not produce an exact * match. But <em>foot|foo</em> will produce an exact match for either * <em>foot</em> or <em>foo</em>. Remember, Perl5 regular expressions do not * match the longest possible match. From the perlre manpage: <blockquote> * Alternatives are tried from left to right, so the first alternative found * for which the entire expression matches, is the one that is chosen. This * means that alternatives are not necessarily greedy. For example: when * matching foo|foot against "barefoot", only the "foo" part will match, as * that is the first alternative tried, and it successfully matches the * target string. </blockquote> * <p> * * @param input * The String to test for an exact match. * @param pattern * The Perl5Pattern to be matched. * @return True if input matches pattern, false otherwise. * @exception ClassCastException * If a Pattern instance other than a Perl5Pattern is passed * as the pattern parameter. */ @Override public boolean matches(final String input, final Pattern pattern) { return matches(input.toCharArray(), pattern); } /** * Determines if the contents of a PatternMatcherInput instance exactly * matches a given pattern. If there is an exact match, a MatchResult * instance representing the match is made accesible via {@link #getMatch()} * . Unlike the {@link #contains(PatternMatcherInput, Pattern)} method, the * current offset of the PatternMatcherInput argument is not updated. You * should remember that the region between the begin (NOT the current) and * end offsets of the PatternMatcherInput will be tested for an exact match. * <p> * The pattern must be a Perl5Pattern instance, otherwise a * ClassCastException will be thrown. You are not required to, and indeed * should NOT try to (for performance reasons), catch a ClassCastException * because it will never be thrown as long as you use a Perl5Pattern as the * pattern parameter. * <p> * <b>Note:</b> matches() is not the same as sticking a ^ in front of your * expression and a $ at the end of your expression in Perl5 and using the * =~ operator, even though in many cases it will be equivalent. matches() * literally looks for an exact match according to the rules of Perl5 * expression matching. Therefore, if you have a pattern <em>foo|foot</em> * and are matching the input <em>foot</em> it will not produce an exact * match. But <em>foot|foo</em> will produce an exact match for either * <em>foot</em> or <em>foo</em>. Remember, Perl5 regular expressions do not * match the longest possible match. From the perlre manpage: <blockquote> * Alternatives are tried from left to right, so the first alternative found * for which the entire expression matches, is the one that is chosen. This * means that alternatives are not necessarily greedy. For example: when * matching foo|foot against "barefoot", only the "foo" part will match, as * that is the first alternative tried, and it successfully matches the * target string. </blockquote> * <p> * * @param input * The PatternMatcherInput to test for a match. * @param pattern * The Perl5Pattern to be matched. * @return True if input matches pattern, false otherwise. * @exception ClassCastException * If a Pattern instance other than a Perl5Pattern is passed * as the pattern parameter. */ @Override public boolean matches(final PatternMatcherInput input, final Pattern pattern) { char[] inp; Perl5Pattern expression; expression = (Perl5Pattern) pattern; this.__originalInput = input._originalBuffer; if (expression._isCaseInsensitive) { if (input._toLowerBuffer == null) { input._toLowerBuffer = _toLower(this.__originalInput); } inp = input._toLowerBuffer; } else { inp = this.__originalInput; } __initInterpreterGlobals(expression, inp, input._beginOffset, input._endOffset, input._beginOffset); this.__lastMatchResult = null; if (__tryExpression(input._beginOffset)) { if (this.__endMatchOffsets[0] == input._endOffset || input.length() == 0 || input._beginOffset == input._endOffset) { this.__lastSuccess = true; return true; } } this.__lastSuccess = false; return false; } /** * Determines if a string contains a pattern. If the pattern is matched by * some substring of the input, a MatchResult instance representing the <b> * first </b> such match is made acessible via {@link #getMatch()}. If you * want to access subsequent matches you should either use a * PatternMatcherInput object or use the offset information in the * MatchResult to create a substring representing the remaining input. Using * the MatchResult offset information is the recommended method of obtaining * the parts of the string preceeding the match and following the match. * <p> * The pattern must be a Perl5Pattern instance, otherwise a * ClassCastException will be thrown. You are not required to, and indeed * should NOT try to (for performance reasons), catch a ClassCastException * because it will never be thrown as long as you use a Perl5Pattern as the * pattern parameter. * <p> * * @param input * The String to test for a match. * @param pattern * The Perl5Pattern to be matched. * @return True if the input contains a pattern match, false otherwise. * @exception ClassCastException * If a Pattern instance other than a Perl5Pattern is passed * as the pattern parameter. */ @Override public boolean contains(final String input, final Pattern pattern) { return contains(input.toCharArray(), pattern); } /** * Determines if a string (represented as a char[]) contains a pattern. If * the pattern is matched by some substring of the input, a MatchResult * instance representing the <b> first </b> such match is made acessible via * {@link #getMatch()}. If you want to access subsequent matches you should * either use a PatternMatcherInput object or use the offset information in * the MatchResult to create a substring representing the remaining input. * Using the MatchResult offset information is the recommended method of * obtaining the parts of the string preceeding the match and following the * match. * <p> * The pattern must be a Perl5Pattern instance, otherwise a * ClassCastException will be thrown. You are not required to, and indeed * should NOT try to (for performance reasons), catch a ClassCastException * because it will never be thrown as long as you use a Perl5Pattern as the * pattern parameter. * <p> * * @param in * The char[] to test for a match. * @param pattern * The Perl5Pattern to be matched. * @return True if the input contains a pattern match, false otherwise. * @exception ClassCastException * If a Pattern instance other than a Perl5Pattern is passed * as the pattern parameter. */ @Override public boolean contains(final char[] in, final Pattern pattern) { char[] input = in.clone(); final Perl5Pattern expression = (Perl5Pattern) pattern; this.__originalInput = input; if (expression._isCaseInsensitive) { input = _toLower(input); } return __interpret(expression, input, 0, input.length, 0); } private static final int __DEFAULT_LAST_MATCH_END_OFFSET = -100; private int __lastMatchInputEndOffset = __DEFAULT_LAST_MATCH_END_OFFSET; /** * Determines if the contents of a PatternMatcherInput, starting from the * current offset of the input contains a pattern. If a pattern match is * found, a MatchResult instance representing the <b>first</b> such match is * made acessible via {@link #getMatch()}. The current offset of the * PatternMatcherInput is set to the offset corresponding to the end of the * match, so that a subsequent call to this method will continue searching * where the last call left off. You should remember that the region between * the begin and end offsets of the PatternMatcherInput are considered the * input to be searched, and that the current offset of the * PatternMatcherInput reflects where a search will start from. Matches * extending beyond the end offset of the PatternMatcherInput will not be * matched. In other words, a match must occur entirely between the begin * and end offsets of the input. See <code>PatternMatcherInput</code> for * more details. * <p> * As a side effect, if a match is found, the PatternMatcherInput match * offset information is updated. See the * <code>PatternMatcherInput.setMatchOffsets(int, int)</code> method for * more details. * <p> * The pattern must be a Perl5Pattern instance, otherwise a * ClassCastException will be thrown. You are not required to, and indeed * should NOT try to (for performance reasons), catch a ClassCastException * because it will never be thrown as long as you use a Perl5Pattern as the * pattern parameter. * <p> * This method is usually used in a loop as follows: <blockquote> * * <pre> * PatternMatcher matcher; * PatternCompiler compiler; * Pattern pattern; * PatternMatcherInput input; * MatchResult result; * * compiler = new Perl5Compiler(); * matcher = new Perl5Matcher(); * * try { * pattern = compiler.compile(somePatternString); * } catch (MalformedPatternException e) { * System.err.println(&quot;Bad pattern.&quot;); * System.err.println(e.getMessage()); * return; * } * * input = new PatternMatcherInput(someStringInput); * * while (matcher.contains(input, pattern)) { * result = matcher.getMatch(); * // Perform whatever processing on the result you want. * } * * </pre> * * </blockquote> * <p> * * @param input * The PatternMatcherInput to test for a match. * @param pattern * The Pattern to be matched. * @return True if the input contains a pattern match, false otherwise. * @exception ClassCastException * If a Pattern instance other than a Perl5Pattern is passed * as the pattern parameter. */ @Override public boolean contains(final PatternMatcherInput input, final Pattern pattern) { char[] inp; Perl5Pattern expression; boolean matchFound; // if(input.length() > 0) { // We want to allow a null string to match at the end of the input // which is why we don't check endOfInput. Not sure if this is a // safe thing to do or not. if (input._currentOffset > input._endOffset) { return false; } // } /* * else if(input._endOfInput()) return false; */ expression = (Perl5Pattern) pattern; this.__originalInput = input._originalBuffer; // Todo: // Really should only reduce to lowercase that part of the // input that is necessary, instead of the whole thing. // Adjust MatchResult offsets accordingly. Actually, pass an adjustment // value to __interpret. this.__originalInput = input._originalBuffer; if (expression._isCaseInsensitive) { if (input._toLowerBuffer == null) { input._toLowerBuffer = _toLower(this.__originalInput); } inp = input._toLowerBuffer; } else { inp = this.__originalInput; } this.__lastMatchInputEndOffset = input.getMatchEndOffset(); matchFound = __interpret(expression, inp, input._beginOffset, input._endOffset, input._currentOffset); if (matchFound) { input.setCurrentOffset(this.__endMatchOffsets[0]); input.setMatchOffsets(this.__beginMatchOffsets[0], this.__endMatchOffsets[0]); } else { input.setCurrentOffset(input._endOffset + 1); } // Restore so it doesn't interfere with other unrelated matches. this.__lastMatchInputEndOffset = __DEFAULT_LAST_MATCH_END_OFFSET; return matchFound; } /** * Fetches the last match found by a call to a matches() or contains() * method. If you plan on modifying the original search input, you must call * this method BEFORE you modify the original search input, as a lazy * evaluation technique is used to create the MatchResult. This reduces the * cost of pattern matching when you don't care about the actual match and * only care if the pattern occurs in the input. Otherwise, a MatchResult * would be created for every match found, whether or not the MatchResult * was later used by a call to getMatch(). * <p> * * @return A MatchResult instance containing the pattern match found by the * last call to any one of the matches() or contains() methods. If * no match was found by the last call, returns null. */ @Override public MatchResult getMatch() { if (!this.__lastSuccess) { return null; } if (this.__lastMatchResult == null) { __setLastMatchResult(); } return this.__lastMatchResult; } }
venanciolm/afirma-ui-miniapplet_x_x
afirma_ui_miniapplet/src/main/java/org/apache/oro/text/regex/Perl5Matcher.java
Java
mit
62,090
import path from 'path'; import {runScheduler} from './scheduler'; import logger from '../util/logger'; import dotenv from 'dotenv'; import {loadConfig} from '../../config'; import {initQueue} from './pipeline.queue'; logger.info(" _____ _ _ _ _ _ _ _ _ "); logger.info("| | |_|___| | | |_| |_|_|"); logger.info("| --| | | | | | | | '_| |"); logger.info("|_____|_|_|_|_|_____|_|_,_|_|"); logger.info('ClinWiki data pipeline starting...'); const envPath = path.resolve(process.cwd()+'/../', '.env'); logger.info('Loading .env from '+envPath); dotenv.config({ path: envPath }); loadConfig(); logger.info('Initializing pipeline queue'); initQueue(); logger.info('Running...'); runScheduler();
clinwiki-org/clinwiki
api/src/pipeline/worker.js
JavaScript
mit
747
<?php /* Unsafe sample input : get the field userData from the variable $_GET via an object Uses a special_chars_filter via filter_var function construction : use of sprintf via a %s with simple quote */ /*Copyright 2015 Bertrand STIVALET Permission is hereby granted, without written agreement or royalty fee, to use, copy, modify, and distribute this software and its documentation for any purpose, provided that the above copyright notice and the following three paragraphs appear in all copies of this software. IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.*/ class Input{ private $input; public function getInput(){ return $this->input; } public function __construct(){ $this->input = $_GET['UserData'] ; } } $temp = new Input(); $tainted = $temp->getInput(); $sanitized = filter_var($tainted, FILTER_SANITIZE_SPECIAL_CHARS); $tainted = $sanitized ; $query = sprintf("cat '%s'", $tainted); //flaw $ret = system($query); ?>
stivalet/PHP-Vulnerability-test-suite
Injection/CWE_78/unsafe/CWE_78__object-classicGet__func_FILTER-CLEANING-special_chars_filter__cat-sprintf_%s_simple_quote.php
PHP
mit
1,514
describe VagrantHyperV do it 'should have a version number' do VagrantHyperV::VERSION.should_not be_nil end it 'should do something useful' do false.should be_true end end
tehgeekmeister/VagrantHyperV
spec/VagrantHyperV_spec.rb
Ruby
mit
189
import primes as py def lcm(a, b): return a * b / gcd(a, b) def gcd(a, b): while b != 0: (a, b) = (b, a % b) return a # Returns two integers x, y such that gcd(a, b) = ax + by def egcd(a, b): if a == 0: return (0, 1) else: y, x = egcd(b % a, a) return (x - (b // a) * y, y) # Returns an integer x such that ax = 1(mod m) def modInverse(a, m): x, y = egcd(a, m) if gcd(a, m) == 1: return x % m # Reduces linear congruence to form x = b(mod m) def reduceCongr(a, b, m): gcdAB = gcd(a, b) a /= gcdAB b /= gcdAB m /= gcd(gcdAB, m) modinv = modInverse(a, m) b *= modinv return (1, b, m) # Returns the incongruent solutions to the linear congruence ax = b(mod m) def linCongr(a, b, m): solutions = set() if (b % gcd(a, m) == 0): numSols = gcd(a, m) sol = (b * egcd(a, m)[0] / numSols) % m for i in xrange(0, numSols): solutions.add((sol + m * i / numSols) % m) return solutions # Uses the Chinese Remainder Theorem to solve a system of linear congruences def crt(congruences): x = 0 M = 1 for i in xrange(len(congruences)): M *= congruences[i][2] congruences[i] = reduceCongr(congruences[i][0], congruences[i][1], congruences[i][2]) for j in xrange(len(congruences)): m = congruences[j][2] if gcd(m, M/m) != 1: return None x += congruences[j][1] * modInverse(M/m, m) * M / m return x % M # Returns the incongruent solution to any system of linear congruences def linCongrSystem(congruences): newCongruences = [] for i in xrange(len(congruences)): congruences[i] = reduceCongr(congruences[i][0], congruences[i][1], congruences[i][2]) # Tests to see whether the system is solvable for j in xrange(len(congruences)): if congruences[i] != congruences[j]: if (congruences[i][1] - congruences[j][1]) % gcd(congruences[i][2], congruences[j][2]) != 0: return None # Splits moduli into prime powers pFactor = py.primeFactorization(congruences[i][2]) for term in pFactor: newCongruences.append((1, congruences[i][1], term[0] ** term[1])) # Discards redundant congruences newCongruences = sorted(newCongruences, key=lambda x: x[2], reverse = True) finalCongruences = [] for k in xrange(len(newCongruences)): isRedundant = False for l in xrange(0, k): if newCongruences[l][2] % newCongruences[k][2] == 0: isRedundant = True if not isRedundant: finalCongruences.append(newCongruences[k]) return crt(finalCongruences) # Returns incongruents solutions to a polynomial congruence def polyCongr(coefficients, m): solutions = [] for i in xrange(m): value = 0 for degree in xrange(len(coefficients)): value += coefficients[degree] * (i ** (len(coefficients) - degree - 1)) if value % m == 0: solutions.append(i) return solutions
ioguntol/NumTy
numty/congruences.py
Python
mit
3,551
package com.aokyu.service; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
aoq/resident-background-service
app/src/androidTest/java/com/aokyu/service/ApplicationTest.java
Java
mit
348
using System; using System.Collections.Generic; using System.Linq; using System.IO; using System.Data.SqlTypes; using Microsoft.SqlServer.Server; using PowerLib.System; using PowerLib.System.Collections; using PowerLib.System.IO; using PowerLib.System.IO.Streamed.Typed; using PowerLib.System.Numerics; using PowerLib.System.Data.SqlTypes.Numerics; namespace PowerLib.System.Data.SqlTypes.Collections { [SqlUserDefinedType(Format.UserDefined, Name = "GradAngleCollection", IsByteOrdered = true, IsFixedLength = false, MaxByteSize = -1)] public sealed class SqlGradAngleCollection : INullable, IBinarySerialize { private List<GradAngle?> _list; #region Contructors public SqlGradAngleCollection() { _list = null; } public SqlGradAngleCollection(IEnumerable<GradAngle?> coll) { _list = coll != null ? new List<GradAngle?>(coll) : null; } private SqlGradAngleCollection(List<GradAngle?> list) { _list = list; } #endregion #region Properties public List<GradAngle?> List { get { return _list; } set { _list = value; } } public static SqlGradAngleCollection Null { get { return new SqlGradAngleCollection(); } } public bool IsNull { get { return _list == null; } } public SqlInt32 Count { get { return _list != null ? _list.Count : SqlInt32.Null; } } #endregion #region Methods public static SqlGradAngleCollection Parse(SqlString s) { if (s.IsNull) return Null; return new SqlGradAngleCollection(SqlFormatting.ParseCollection<GradAngle?>(s.Value, t => !t.Equals(SqlFormatting.NullText, StringComparison.InvariantCultureIgnoreCase) ? SqlGradAngle.Parse(t).Value : default(GradAngle?))); } public override String ToString() { return SqlFormatting.Format(_list, t => (t.HasValue ? new SqlGradAngle(t.Value) : SqlGradAngle.Null).ToString()); } [SqlMethod(IsMutator = true)] public void Clear() { _list.Clear(); } [SqlMethod(IsMutator = true)] public void AddItem(SqlGradAngle value) { _list.Add(value.IsNull ? default(GradAngle?) : value.Value); } [SqlMethod(IsMutator = true)] public void InsertItem(SqlInt32 index, SqlGradAngle value) { _list.Insert(index.IsNull ? _list.Count : index.Value, value.IsNull ? default(GradAngle?) : value.Value); } [SqlMethod(IsMutator = true)] public void RemoveItem(SqlGradAngle value) { _list.Remove(value.IsNull ? default(GradAngle?) : value.Value); } [SqlMethod(IsMutator = true)] public void RemoveAt(SqlInt32 index) { if (index.IsNull) return; _list.RemoveAt(index.Value); } [SqlMethod(IsMutator = true)] public void SetItem(SqlInt32 index, SqlGradAngle value) { if (index.IsNull) return; _list[index.Value] = value.IsNull ? default(GradAngle?) : value.Value; } [SqlMethod(IsMutator = true)] public void AddRange(SqlGradAngleCollection coll) { if (coll.IsNull) return; _list.AddRange(coll._list); } [SqlMethod(IsMutator = true)] public void AddRepeat(SqlGradAngle value, SqlInt32 count) { if (count.IsNull) return; _list.AddRepeat(value.IsNull ? default(GradAngle?) : value.Value, count.Value); } [SqlMethod(IsMutator = true)] public void InsertRange(SqlInt32 index, SqlGradAngleCollection coll) { if (coll.IsNull) return; int indexValue = !index.IsNull ? index.Value : _list.Count; _list.InsertRange(indexValue, coll._list); } [SqlMethod(IsMutator = true)] public void InsertRepeat(SqlInt32 index, SqlGradAngle value, SqlInt32 count) { if (count.IsNull) return; int indexValue = !index.IsNull ? index.Value : _list.Count; _list.InsertRepeat(indexValue, value.IsNull ? default(GradAngle?) : value.Value, count.Value); } [SqlMethod(IsMutator = true)] public void SetRange(SqlInt32 index, SqlGradAngleCollection range) { if (range.IsNull) return; int indexValue = index.IsNull ? _list.Count - Comparable.Min(_list.Count, range._list.Count) : index.Value; _list.SetRange(indexValue, range.List); } [SqlMethod(IsMutator = true)] public void SetRepeat(SqlInt32 index, SqlGradAngle value, SqlInt32 count) { int indexValue = !index.IsNull ? index.Value : count.IsNull ? 0 : _list.Count - count.Value; int countValue = !count.IsNull ? count.Value : index.IsNull ? 0 : _list.Count - index.Value; _list.SetRepeat(indexValue, value.IsNull ? default(GradAngle?) : value.Value, countValue); } [SqlMethod(IsMutator = true)] public void RemoveRange(SqlInt32 index, SqlInt32 count) { int indexValue = !index.IsNull ? index.Value : count.IsNull ? 0 : _list.Count - count.Value; int countValue = !count.IsNull ? count.Value : index.IsNull ? 0 : _list.Count - index.Value; _list.RemoveRange(indexValue, countValue); } [SqlMethod] public SqlGradAngle GetItem(SqlInt32 index) { return !index.IsNull && _list[index.Value].HasValue ? _list[index.Value].Value : SqlGradAngle.Null; } [SqlMethod] public SqlGradAngleCollection GetRange(SqlInt32 index, SqlInt32 count) { int indexValue = !index.IsNull ? index.Value : count.IsNull ? 0 : _list.Count - count.Value; int countValue = !count.IsNull ? count.Value : index.IsNull ? 0 : _list.Count - index.Value; return new SqlGradAngleCollection(_list.GetRange(indexValue, countValue)); } [SqlMethod] public SqlGradAngleArray ToArray() { return new SqlGradAngleArray(_list); } #endregion #region Operators public static implicit operator byte[] (SqlGradAngleCollection coll) { using (var ms = new MemoryStream()) using (new NulInt32StreamedCollection(ms, SizeEncoding.B4, true, coll._list.Select(t => t.HasValue ? t.Value.Units : default(Int32?)).Counted(coll._list.Count), true, false)) return ms.ToArray(); } public static explicit operator SqlGradAngleCollection(byte[] buffer) { using (var ms = new MemoryStream(buffer)) using (var sa = new NulInt32StreamedArray(ms, true, false)) return new SqlGradAngleCollection(sa.Select(t => t.HasValue ? new GradAngle(t.Value) : default(GradAngle?)).ToList()); } #endregion #region IBinarySerialize implementation public void Read(BinaryReader rd) { using (var sa = new NulInt32StreamedArray(rd.BaseStream, true, false)) _list = sa.Select(t => !t.HasValue ? default(GradAngle?) : new GradAngle(t.Value)).ToList(); } public void Write(BinaryWriter wr) { using (var ms = new MemoryStream()) using (var sa = new NulInt32StreamedArray(ms, SizeEncoding.B4, true, _list.Select(t => t.HasValue ? t.Value.Units : default(Int32?)).Counted(_list.Count), true, false)) wr.Write(ms.GetBuffer(), 0, (int)ms.Length); } #endregion } }
vaseug/PowerLib
PowerLib.System.Data.SqlTypes/Collections/SqlGradAngleCollection.cs
C#
mit
7,128
require 'spec_helper' describe Pagerage::IncidentsParser do before(:each) do Pagerage::Incident.delete end let(:incidents_json) { File.read(File.dirname(__FILE__) + '/incidents_sample.json') } let(:incidents_data) { JSON.parse(incidents_json) } let(:parser) { Pagerage::IncidentsParser.new(incidents_json) } it 'should set data attr when created' do parser.data.should eq(incidents_data) end it 'should generate two incidents from the sample data' do parser.run! Pagerage::Incident.count.should eq(2) end end
gorsuch/pagerage
spec/pagerage/incidents_parser_spec.rb
Ruby
mit
546
a = a # e 4 a = 1 # 0 int l = [a] # 0 [int] d = {a:l} # 0 {int:[int]} s = "abc" c = ord(s[2].lower()[0]) # 0 int # 4 (str) -> int l2 = [range(i) for i in d] # 0 [[int]] y = [(a,b) for a,b in {1:'2'}.iteritems()] # 0 [(int,str)] b = 1 # 0 int if 0: b = '' # 4 str else: b = str(b) # 4 str # 12 int r = 0 # 0 int if r: # 3 int r = str(r) # 4 str # 12 int r # 0 <int|str> l = range(5) # 0 [int] l2 = l[2:3] # 0 [int] x = l2[1] # 0 int k = 1() # 0 <unknown> # e 4 del k k # e 0 l = [] # 0 [int] x = 1 # 0 int while x: # 6 int l = [] # 4 [int] l.append(1) # 0 [int] # 2 (int) -> None l = [1, 2] # 0 [int] l2 = [x for x in l] # 0 [<int|str>] l2.append('') # 0 [<int|str>] s = str() # 0 str s2 = str(s) # 0 str s3 = repr() # e 5 # 0 str s4 = repr(s) # 0 str x = 1 if [] else '' # 0 <int|str> l = [1] # 0 [<int|str>] l2 = [''] # 0 [str] l[:] = l2 # 0 [<int|str>] b = 1 < 2 < 3 # 0 bool l = sorted(range(5), key=lambda x:-x) # 0 [int] d = {} # 0 {<bool|int>:<int|str>} d1 = {1:''} # 0 {int:str} d.update(d1) d[True] = 1 d # 0 {<bool|int>:<int|str>} l = [] # 0 [int] l1 = [] # 0 [<unknown>] l.extend(l1) l.append(2) l = [] # 0 [<[str]|int>] l1 = [[]] # 0 [[str]] l.extend(l1) l[0].append('') # e 0 l.append(1) l = [] # 0 [[<int|str>]] l2 = [1] # 0 [int] l3 = [''] # 0 [str] l.append(l2) l.append(l3) for i, s in enumerate("aoeu"): # 4 int # 7 str pass x = 1 # 0 int y = x + 1.0 # 0 float y << 1 # e 0 l = [1, 1.0] # 0 [float] 1.0 in [1] # e 0 x = `1` # 0 str def f(): x = `1` # 4 str d = dict(a=1) # 0 {str:int} l = list() # 0 [<unknown>] i = int(1) # 0 int i = int(1.2) # 0 int i = abs(1) # 0 int i = abs(1.0) # 0 float d = dict() # 0 {int:int} d[1] = 2 d2 = dict(d) # 0 {<int|str>:<int|str>} d2[''] = '' d3 = dict([(1,2)]) # 0 {int:int} d4 = dict(a=1) # 0 {str:int}
kmod/icbd
icbd/type_analyzer/tests/basic.py
Python
mit
1,818
<?php //var_dump($games) ?> <?php $this->load->view('includes/tables-head') ?> <body class="fixed-header" ng-app="app" ng-controller="gameCtrl"> <?php $this->load->view('admin/admin-nav') ?> <div class="page-container"> <?php $this->load->view('admin/admin-header') ?> <div class="page-content-wrapper "> <div class="content "> <div class="jumbotron" data-pages="parallax"> <div class="container-fluid container-fixed-lg sm-p-l-20 sm-p-r-20"> <div class="inner"> <ul class="breadcrumb"> <li><p>Dashboard</p></li> <li><a href="#" class="active">Game</a></li> <li><a href="#" class="active">New</a></li> </ul> </div> </div> </div> <div class="container-fluid container-fixed-lg"> <div class="panel"> <ul class="nav nav-tabs nav-tabs-linetriangle" data-init-reponsive-tabs="dropdownfx"> <li class="active"> <a data-toggle="tab" href="#new"><span>New Game</span></a> </li> <li> <a data-toggle="tab" href="#game"><span>This Week Game</span></a> </li> </ul> <div class="tab-content"> <div class="tab-pane slide-left active" id="new"> <!-- View Branches Table start --> <div class="conatiner"> <div class="row"> <div class="col-lg-12 col-md-12"> <div class="clearfix"></div> <?php echo validation_errors(); ?> <table class="table"> <thead> <tr> <td>NUMBER</td> <td>HOME</td> <td>AWAY</td> <td>DEADLINE <small>format: (2016-04-18 11:24:00)</small></td> </tr> </thead> <tbody> <form role="form" method="post" action="<?=site_url('admin/game/create') ?>"> <?php for($i = 1; $i<=49; $i++){ ?> <tr> <td> <?=$i; ?> <input type="hidden" name="data[<?=$i; ?>][number]" value="<?=$i; ?>" /> </td> <td> <input id="home" type="text" name="data[<?=$i ?>][home]" class="form-control" required /> </td> <td> <input id="away" type="text" name="data[<?=$i ?>][away]" class="form-control" required /> </td> <td> <input type="date" class="input-sm form-control" name="data[<?=$i ?>][deadline]" placeholder="2016-04-18 11:24:00" required/> </td> </tr> <?php } ?> <?php $csrf = array( 'name' => $this->security->get_csrf_token_name(), 'hash' => $this->security->get_csrf_hash()); ?> <input type="hidden" name="<?=$csrf['name'];?>" value="<?=$csrf['hash'];?>" /> <tr> <td> <label for="number">Week Number <small>e.g. 34</small></label> <input type="number" name="week_number" class="form-control" required placeholder="0"> </td> <td> <label for="week_start_date">Week Start Date (<small>format: 2016-04-18</small>)</label> <input type="date" name="week_start_date" class="form-control" required placeholder="2016-04-18"> </td> <td> <label for="week_start_date">Week End Date (<small>format: 2016-04-18</small>)</label> <input type="date" name="week_end_date" class="form-control" required placeholder="2016-04-18"> </td> <td> <label for="submit">Submit All Entries</label><br /> <input id="sumbit" type="submit" name="submit" value="Submit" class="btn btn-sm btn-primary"> </td> </tr> </form> </tbody> </table> <br /> </div> </div> </div> <!-- Veiw Branches Table end --> </div> <div class="tab-pane slide-left" id="game"> <!-- View Branches Table start --> <div class="conatiner"> <div class="row"> <div class="col-lg-12 col-md-12"> <div class="clearfix"></div> <table class="table table-responsive"> <thead> <tr> <td>NUMBER</td> <td >DEADLINE</td> <td>TOGGLE</td> </tr> </thead> <?php if($games): ?> <tbody> <?php foreach ($games as $row): ?> <tr> <td><?=$row->number; ?></td> <td><?=$row->deadline ?></td> <td> <?php if ($row->status == 'active'){ ?> <input type="checkbox" ng-click="toggleGame(<?=$row->number; ?>, <?=$row->week_number ?>)" id="<?=$row->number ?>"checked/> <?php }else{ ?> <input type="checkbox" disabled id="<?=$row->number ?>" /> <?php } ?> </td> </tr> <?php endforeach; ?> </tbody> <?php endif; ?> </table> </div> </div> </div> <!-- Veiw Branches Table end --> </div> </div> </div> </div> <?php $this->load->view('includes/footer-note') ?> </div> </div> <?php $this->load->view('includes/tables-footer') ?>
massivebrains/poolapp
application/views/admin/admin-game-new.php
PHP
mit
5,597