repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
i-am-a-kernel/angular-global | src/app/pages/new-course/new-course.routes.ts | 505 | import { Routes, RouterModule } from '@angular/router';
import { NewCourse } from './new-course.component';
import { LoggedInGuard } from "../../core/services/index";
// Route Configuration
const newCourseRouter: Routes = [
{ path: 'courses/new', component: NewCourse, canActivate: [LoggedInGuard], data: {breadcrumb:"New course"} },
{ path: 'courses/:id', component: NewCourse, canActivate: [LoggedInGuard], data:{breadcrumb:"Edit"} },
];
export const routes = RouterModule.forChild(newCourseRouter); | mit |
intrepion/ember-2015-tdd-by-example | app/controllers/todos.js | 614 | import Ember from 'ember';
export default Ember.Controller.extend({
needs: 'application',
isActiveRoute: Ember.computed.equal('controllers.application.currentRouteName', 'todos.index'),
actions: {
assign: function(todo) {
todo.set('status_code', 2);
}
},
unassigned: function() {
return this.get('model').filter(function(model) {
return 1 === model.status_code;
});
}.property('model.@each.status_code'),
assigned: function() {
return this.get('model').filter(function(model) {
return 2 === model.status_code;
});
}.property('model.@each.status_code')
}); | mit |
syonfox/PixelPlanetSandbox | haxe/export/linux64/cpp/obj/src/openfl/display3D/textures/TextureBase.cpp | 7955 | #include <hxcpp.h>
#ifndef INCLUDED_openfl__legacy_events_EventDispatcher
#include <openfl/_legacy/events/EventDispatcher.h>
#endif
#ifndef INCLUDED_openfl__legacy_events_IEventDispatcher
#include <openfl/_legacy/events/IEventDispatcher.h>
#endif
#ifndef INCLUDED_openfl__legacy_gl_GLFramebuffer
#include <openfl/_legacy/gl/GLFramebuffer.h>
#endif
#ifndef INCLUDED_openfl__legacy_gl_GLObject
#include <openfl/_legacy/gl/GLObject.h>
#endif
#ifndef INCLUDED_openfl__legacy_gl_GLTexture
#include <openfl/_legacy/gl/GLTexture.h>
#endif
#ifndef INCLUDED_openfl_display3D_Context3D
#include <openfl/display3D/Context3D.h>
#endif
#ifndef INCLUDED_openfl_display3D_textures_TextureBase
#include <openfl/display3D/textures/TextureBase.h>
#endif
namespace openfl{
namespace display3D{
namespace textures{
Void TextureBase_obj::__construct(::openfl::display3D::Context3D context,::openfl::_legacy::gl::GLTexture glTexture,hx::Null< int > __o_width,hx::Null< int > __o_height)
{
HX_STACK_FRAME("openfl.display3D.textures.TextureBase","new",0x670078a1,"openfl.display3D.textures.TextureBase.new","openfl/display3D/textures/TextureBase.hx",19,0x7b0f92ae)
HX_STACK_THIS(this)
HX_STACK_ARG(context,"context")
HX_STACK_ARG(glTexture,"glTexture")
HX_STACK_ARG(__o_width,"width")
HX_STACK_ARG(__o_height,"height")
int width = __o_width.Default(0);
int height = __o_height.Default(0);
{
HX_STACK_LINE(21)
super::__construct(null());
HX_STACK_LINE(23)
this->context = context;
HX_STACK_LINE(24)
this->width = width;
HX_STACK_LINE(25)
this->height = height;
HX_STACK_LINE(26)
this->glTexture = glTexture;
}
;
return null();
}
//TextureBase_obj::~TextureBase_obj() { }
Dynamic TextureBase_obj::__CreateEmpty() { return new TextureBase_obj; }
hx::ObjectPtr< TextureBase_obj > TextureBase_obj::__new(::openfl::display3D::Context3D context,::openfl::_legacy::gl::GLTexture glTexture,hx::Null< int > __o_width,hx::Null< int > __o_height)
{ hx::ObjectPtr< TextureBase_obj > _result_ = new TextureBase_obj();
_result_->__construct(context,glTexture,__o_width,__o_height);
return _result_;}
Dynamic TextureBase_obj::__Create(hx::DynamicArray inArgs)
{ hx::ObjectPtr< TextureBase_obj > _result_ = new TextureBase_obj();
_result_->__construct(inArgs[0],inArgs[1],inArgs[2],inArgs[3]);
return _result_;}
Void TextureBase_obj::dispose( ){
{
HX_STACK_FRAME("openfl.display3D.textures.TextureBase","dispose",0xa678dd60,"openfl.display3D.textures.TextureBase.dispose","openfl/display3D/textures/TextureBase.hx",31,0x7b0f92ae)
HX_STACK_THIS(this)
HX_STACK_LINE(33)
::openfl::display3D::Context3D tmp = this->context; HX_STACK_VAR(tmp,"tmp");
HX_STACK_LINE(33)
tmp->__deleteTexture(hx::ObjectPtr<OBJ_>(this));
}
return null();
}
HX_DEFINE_DYNAMIC_FUNC0(TextureBase_obj,dispose,(void))
TextureBase_obj::TextureBase_obj()
{
}
void TextureBase_obj::__Mark(HX_MARK_PARAMS)
{
HX_MARK_BEGIN_CLASS(TextureBase);
HX_MARK_MEMBER_NAME(context,"context");
HX_MARK_MEMBER_NAME(height,"height");
HX_MARK_MEMBER_NAME(frameBuffer,"frameBuffer");
HX_MARK_MEMBER_NAME(glTexture,"glTexture");
HX_MARK_MEMBER_NAME(width,"width");
::openfl::_legacy::events::EventDispatcher_obj::__Mark(HX_MARK_ARG);
HX_MARK_END_CLASS();
}
void TextureBase_obj::__Visit(HX_VISIT_PARAMS)
{
HX_VISIT_MEMBER_NAME(context,"context");
HX_VISIT_MEMBER_NAME(height,"height");
HX_VISIT_MEMBER_NAME(frameBuffer,"frameBuffer");
HX_VISIT_MEMBER_NAME(glTexture,"glTexture");
HX_VISIT_MEMBER_NAME(width,"width");
::openfl::_legacy::events::EventDispatcher_obj::__Visit(HX_VISIT_ARG);
}
Dynamic TextureBase_obj::__Field(const ::String &inName,hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 5:
if (HX_FIELD_EQ(inName,"width") ) { return width; }
break;
case 6:
if (HX_FIELD_EQ(inName,"height") ) { return height; }
break;
case 7:
if (HX_FIELD_EQ(inName,"context") ) { return context; }
if (HX_FIELD_EQ(inName,"dispose") ) { return dispose_dyn(); }
break;
case 9:
if (HX_FIELD_EQ(inName,"glTexture") ) { return glTexture; }
break;
case 11:
if (HX_FIELD_EQ(inName,"frameBuffer") ) { return frameBuffer; }
}
return super::__Field(inName,inCallProp);
}
Dynamic TextureBase_obj::__SetField(const ::String &inName,const Dynamic &inValue,hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 5:
if (HX_FIELD_EQ(inName,"width") ) { width=inValue.Cast< int >(); return inValue; }
break;
case 6:
if (HX_FIELD_EQ(inName,"height") ) { height=inValue.Cast< int >(); return inValue; }
break;
case 7:
if (HX_FIELD_EQ(inName,"context") ) { context=inValue.Cast< ::openfl::display3D::Context3D >(); return inValue; }
break;
case 9:
if (HX_FIELD_EQ(inName,"glTexture") ) { glTexture=inValue.Cast< ::openfl::_legacy::gl::GLTexture >(); return inValue; }
break;
case 11:
if (HX_FIELD_EQ(inName,"frameBuffer") ) { frameBuffer=inValue.Cast< ::openfl::_legacy::gl::GLFramebuffer >(); return inValue; }
}
return super::__SetField(inName,inValue,inCallProp);
}
void TextureBase_obj::__GetFields(Array< ::String> &outFields)
{
outFields->push(HX_HCSTRING("context","\xef","\x95","\x77","\x19"));
outFields->push(HX_HCSTRING("height","\xe7","\x07","\x4c","\x02"));
outFields->push(HX_HCSTRING("frameBuffer","\x0d","\x89","\xdc","\xae"));
outFields->push(HX_HCSTRING("glTexture","\x36","\x55","\x9b","\x6c"));
outFields->push(HX_HCSTRING("width","\x06","\xb6","\x62","\xca"));
super::__GetFields(outFields);
};
#if HXCPP_SCRIPTABLE
static hx::StorageInfo sMemberStorageInfo[] = {
{hx::fsObject /*::openfl::display3D::Context3D*/ ,(int)offsetof(TextureBase_obj,context),HX_HCSTRING("context","\xef","\x95","\x77","\x19")},
{hx::fsInt,(int)offsetof(TextureBase_obj,height),HX_HCSTRING("height","\xe7","\x07","\x4c","\x02")},
{hx::fsObject /*::openfl::_legacy::gl::GLFramebuffer*/ ,(int)offsetof(TextureBase_obj,frameBuffer),HX_HCSTRING("frameBuffer","\x0d","\x89","\xdc","\xae")},
{hx::fsObject /*::openfl::_legacy::gl::GLTexture*/ ,(int)offsetof(TextureBase_obj,glTexture),HX_HCSTRING("glTexture","\x36","\x55","\x9b","\x6c")},
{hx::fsInt,(int)offsetof(TextureBase_obj,width),HX_HCSTRING("width","\x06","\xb6","\x62","\xca")},
{ hx::fsUnknown, 0, null()}
};
static hx::StaticInfo *sStaticStorageInfo = 0;
#endif
static ::String sMemberFields[] = {
HX_HCSTRING("context","\xef","\x95","\x77","\x19"),
HX_HCSTRING("height","\xe7","\x07","\x4c","\x02"),
HX_HCSTRING("frameBuffer","\x0d","\x89","\xdc","\xae"),
HX_HCSTRING("glTexture","\x36","\x55","\x9b","\x6c"),
HX_HCSTRING("width","\x06","\xb6","\x62","\xca"),
HX_HCSTRING("dispose","\x9f","\x80","\x4c","\xbb"),
::String(null()) };
static void sMarkStatics(HX_MARK_PARAMS) {
HX_MARK_MEMBER_NAME(TextureBase_obj::__mClass,"__mClass");
};
#ifdef HXCPP_VISIT_ALLOCS
static void sVisitStatics(HX_VISIT_PARAMS) {
HX_VISIT_MEMBER_NAME(TextureBase_obj::__mClass,"__mClass");
};
#endif
hx::Class TextureBase_obj::__mClass;
void TextureBase_obj::__register()
{
hx::Static(__mClass) = new hx::Class_obj();
__mClass->mName = HX_HCSTRING("openfl.display3D.textures.TextureBase","\x2f","\x94","\x15","\xbc");
__mClass->mSuper = &super::__SGetClass();
__mClass->mConstructEmpty = &__CreateEmpty;
__mClass->mConstructArgs = &__Create;
__mClass->mGetStaticField = &hx::Class_obj::GetNoStaticField;
__mClass->mSetStaticField = &hx::Class_obj::SetNoStaticField;
__mClass->mMarkFunc = sMarkStatics;
__mClass->mStatics = hx::Class_obj::dupFunctions(0 /* sStaticFields */);
__mClass->mMembers = hx::Class_obj::dupFunctions(sMemberFields);
__mClass->mCanCast = hx::TCanCast< TextureBase_obj >;
#ifdef HXCPP_VISIT_ALLOCS
__mClass->mVisitFunc = sVisitStatics;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mMemberStorageInfo = sMemberStorageInfo;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mStaticStorageInfo = sStaticStorageInfo;
#endif
hx::RegisterClass(__mClass->mName, __mClass);
}
} // end namespace openfl
} // end namespace display3D
} // end namespace textures
| mit |
achrafYne/restaurants-guide | src/Application/Sonata/MediaBundle/Entity/Media.php | 1413 | <?php
/**
* This file is part of the <name> project.
*
* (c) <yourname> <youremail>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Application\Sonata\MediaBundle\Entity;
use Sonata\MediaBundle\Entity\BaseMedia as BaseMedia;
/**
* This file has been generated by the Sonata EasyExtends bundle ( http://sonata-project.org/bundles/easy-extends )
*
* References :
* working with object : http://www.doctrine-project.org/projects/orm/2.0/docs/reference/working-with-objects/en
*
* @author <yourname> <youremail>
*/
class Media extends BaseMedia
{
/**
* @var integer $id
*/
protected $id;
/**
* Get id
*
* @return integer $id
*/
public function getId()
{
return $this->id;
}
/**
* @var \Sahadina\RestaurantBundle\Entity\Restaurant
*/
private $restaurant;
public function getRestaurant() {
return $this->restaurant;
}
/**
*
* @param \Sahadina\RestaurantBundle\Entity\Restaurant $restaurant
* @return \Application\Sonata\MediaBundle\Entity\Media
*/
public function setRestaurant($restaurant) {
$this->restaurant = $restaurant;
return $this;
}
public function addRestaurant(\Sahadina\RestaurantBundle\Entity\Restaurant $restaurant){
$this->restaurant = $restaurant;
return $this;
}
} | mit |
kelastutorial/kelastutorial-web-app | application/views/tutorials/html/left_sidebar.php | 7801 |
<div class="tutorial-wall"></div>
<div class="container" style="height:auto;width:100%;padding-top:30px;">
<div class="row">
<div class="col s12 m12 l3 hide-on-tablet">
<div class="left-sidebar-container">
<div class="grey lighten-3 left-sidebar">
<span class="subtutorial">Pendahuluan</span><br/>
<a href="<?php echo site_url('html/pengertian-html.html'); ?>" class="subtutorial-list">HTML - Pengertian</a><br/>
<a href="<?php echo site_url('html/sejarah-html.html'); ?>" class="subtutorial-list">HTML - Sejarah</a><br/>
<a href="<?php echo site_url('html/versi-html.html'); ?>" class="subtutorial-list">HTML - Versi</a><br/>
</div>
<div class="grey lighten-3 left-sidebar">
<span class="subtutorial">HTML Dasar</span><br/>
<a href="<?php echo site_url('html/syntax-dasar-html.html'); ?>" class="subtutorial-list">HTML - Syntax Dasar</a><br/>
<a href="<?php echo site_url('html/elemen-html.html'); ?>" class="subtutorial-list">HTML - Elemen</a><br/>
<a href="<?php echo site_url('html/atribut-html.html'); ?>" class="subtutorial-list">HTML - Atribut</a><br/>
<a href="<?php echo site_url('html/atribut-khusus-html.html'); ?>" class="subtutorial-list">HTML - Atribut Khusus</a><br/>
<a href="<?php echo site_url('html/event-html.html'); ?>" class="subtutorial-list">HTML - Event</a><br/>
<a href="<?php echo site_url('html/form-html.html'); ?>" class="subtutorial-list">HTML - Form</a><br/>
<a href="<?php echo site_url('html/svg-html.html'); ?>" class="subtutorial-list">HTML - SVG</a><br/>
<a href="<?php echo site_url('html/layout-html.html'); ?>" class="subtutorial-list">HTML - Layout</a><br/>
<a href="<?php echo site_url('html/audio-html.html'); ?>" class="subtutorial-list">HTML - Audio</a><br/>
<a href="<?php echo site_url('html/video-html.html'); ?>" class="subtutorial-list">HTML - Video</a><br/>
</div>
<div class="grey lighten-3 left-sidebar">
<span class="subtutorial">HTML Tingkat Lanjut</span><br/>
<a href="<?php echo site_url('html/geolocation-html.html'); ?>" class="subtutorial-list">HTML - Geolocation</a><br/>
<a href="<?php echo site_url('html/microdata-html.html'); ?>" class="subtutorial-list">HTML - Microdata</a><br/>
<a href="<?php echo site_url('html/drag-drop-html.html'); ?>" class="subtutorial-list">HTML - Drag & Drop</a><br/>
<a href="<?php echo site_url('html/layout-responsive-html.html'); ?>" class="subtutorial-list">HTML - Layout Responsive</a><br/>
</div>
</div>
</div>
<!-- Mobile Navigation -->
<div class="mobile-navigation">
<ul class="side-nav" id="mobile-demo" style="width:70%;z-index:1000;">
<div class="header-mobile grey lighten-3" style="height:110px;padding:33px 5px 0 0;text-align:center">
<a href="<?php echo site_url(); ?>"><img alt="logo-kelastutorial" src="<?php echo site_url('images/kelastutorial-logo.svg'); ?>" height="38px"/></a>
</div>
<li style="border-bottom:1px solid #e0e0e0"><a href="<?php echo site_url('tutorials'); ?>">Semua Tutorial</a></li>
<li class="no-padding">
<ul class='collapsible collapsible-accordion'>
<li><a class='collapsible-header waves-effect'>Pendahuluan</a>
<div class='collapsible-body'>
<ul>
<li><a href='<?php echo site_url('html/pengertian-html.html'); ?>'>Pengertian HTML</a></li>
<li><a href='<?php echo site_url('html/sejarah-html.html'); ?>'>Sejarah HTML</a></li>
<li><a href='<?php echo site_url('html/versi-html.html'); ?>'>Versi HTML</a></li>
</ul>
</div>
</li>
</ul>
</li>
<li class="no-padding">
<ul class='collapsible collapsible-accordion'>
<li><a class='collapsible-header waves-effect'>HTML Dasar</a>
<div class='collapsible-body'>
<ul>
<li><a href='<?php echo site_url('html/syntax-dasar-html.html'); ?>'>Syntax Dasar HTML</a></li>
<li><a href='<?php echo site_url('html/elemen-html.html'); ?>'>Elemen HTML</a></li>
<li><a href='<?php echo site_url('html/atribut-html.html'); ?>'>Atribut HTML</a></li>
<li><a href='<?php echo site_url('html/atribut-khusus-html.html'); ?>'>Atribut Khusus HTML</a></li>
<li><a href='<?php echo site_url('html/event-html.html'); ?>'>Event HTML</a></li>
<li><a href='<?php echo site_url('html/form-html.html'); ?>'>Form HTML</a></li>
<li><a href='<?php echo site_url('html/svg-html.html'); ?>'>SVG HTML</a></li>
<li><a href='<?php echo site_url('html/layout-html.html'); ?>'>Layout HTML</a></li>
<li><a href='<?php echo site_url('html/audio-html.html'); ?>'>Audio HTML</a></li>
<li><a href='<?php echo site_url('html/video-html.html'); ?>'>Video HTML</a></li>
</ul>
</div>
</li>
</ul>
</li>
<li class="no-padding">
<ul class='collapsible collapsible-accordion'>
<li><a class='collapsible-header waves-effect'>HTML Tingkat Lanjut</a>
<div class='collapsible-body'>
<ul>
<li><a href='<?php echo site_url('html/geolocation-html.html'); ?>'>Geolocation HTML</a></li>
<li><a href='<?php echo site_url('html/microdata-html.html'); ?>'>Microdata HTML</a></li>
<li><a href='<?php echo site_url('html/drag-drop-html.html'); ?>'>Drag & Drop HTML</a></li>
<li><a href='<?php echo site_url('html/layout-responsive-html.html'); ?>'>Layout Responsive HTML</a></li>
</ul>
</div>
</li>
</ul>
</li>
</ul>
</div><!-- End Mobile Navigation --> | mit |
jenavarro/AllRules | packages/custom/rules/server/models/rule.js | 1875 | 'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
/**
* Rule Schema
*/
var RuleSchema = new Schema({
created: {
type: Date,
default: Date.now
},
name: {
type: String,
required: true,
trim: true
},
execWhenKey: {
type: String,
default: '',
required: true,
trim: true
},
execIf: {
type: String,
default: '',
required: true,
trim: true
},
execThen: {
type: String,
default: '',
required: true,
trim: true
},
execElse: {
type: String,
default: '',
required: false,
trim: true
},
enabled: {
type: Boolean,
required: true,
default: true
},
group: {
type: Schema.ObjectId,
ref: 'Group',
required: false
},
user: {
type: Schema.ObjectId,
ref: 'User',
required: true
},
validFrom: {
type: Date
},
validTo: {
type: Date
},
execOrder: {
type: Number,
default:0,
required: true
},
permissions: {
type: Array
},
updated: {
type: Array
}
});
/**
* Validations
*/
RuleSchema.path('name').validate(function(name) {
return !!name;
}, 'Name cannot be blank');
RuleSchema.path('validFrom').validate(function(validFrom) {
return !!validFrom;
}, 'Valid From date cannot be blank');
RuleSchema.path('validTo').validate(function(validTo) {
return !!validTo;
}, 'Valid To date cannot be blank');
/**
* Statics
*/
RuleSchema.statics.load = function(id, cb) {
this.findOne({
_id: id
})
.populate('user', 'name username')
.populate('group', 'name groupname')
.exec(cb);
};
/*
RuleSchema.statics.load = function(id, cb) {
this.findOne({
_id: id
}).populate('group', 'name groupname').exec(cb);
};
*/
mongoose.model('Rule', RuleSchema);
| mit |
RNanoware/robsonwebsite | actions/editsettings.php | 926 | <?php
require '../config.php';
require 'passwordHash.php';
if (isset($_FILES['avatar']['size']) && !empty($_FILES['avatar']['size'])) {
list($width, $height) = getimagesize($_FILES['avatar']['tmp_name']);
if ($_FILES['avatar']['type'] == "image/gif"
&& $_FILES['avatar']['size'] / 1024 < 15
&& $width == "50"
&& $height == "50") {
move_uploaded_file($_FILES['avatar']['tmp_name'], "/var/www/website/assets/images/" . $_SESSION['id'] . "/" . $_SESSION['id'] . ".gif");
}
}
$data = array();
$data['color_id'] = $_POST['style'];
$data['email'] = $_POST['email'];
if (isset($_POST['password']) && !empty($_POST['password']) && $_POST['password'] === $_POST['verify']) {
$data['password'] = passwordHash($_POST['password']);
}
$_SESSION['user']->__construct($data);
$_SESSION['user']->update();
$_SESSION['user']->updateAbout($_POST['about']);
header("Location: /index.php?page=settings")
?> | mit |
ArcherSys/ArcherSys | Producktiviti/owncloud/lib/public/iservercontainer.php | 4620 | <?php
/**
* ownCloud
*
* @author Thomas Müller
* @copyright 2013 Thomas Müller deepdiver@owncloud.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
* License as published by the Free Software Foundation; either
* version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU AFFERO GENERAL PUBLIC LICENSE for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
*/
/**
* Public interface of ownCloud for apps to use.
* Server container interface
*
*/
// use OCP namespace for all classes that are considered public.
// This means that they should be used by apps instead of the internal ownCloud classes
namespace OCP;
/**
* Class IServerContainer
* @package OCP
*
* This container holds all ownCloud services
*/
interface IServerContainer {
/**
* The contacts manager will act as a broker between consumers for contacts information and
* providers which actual deliver the contact information.
*
* @return \OCP\Contacts\IManager
*/
function getContactsManager();
/**
* The current request object holding all information about the request currently being processed
* is returned from this method.
* In case the current execution was not initiated by a web request null is returned
*
* @return \OCP\IRequest|null
*/
function getRequest();
/**
* Returns the preview manager which can create preview images for a given file
*
* @return \OCP\IPreview
*/
function getPreviewManager();
/**
* Returns the tag manager which can get and set tags for different object types
*
* @see \OCP\ITagManager::load()
* @return \OCP\ITagManager
*/
function getTagManager();
/**
* Returns the root folder of ownCloud's data directory
*
* @return \OCP\Files\Folder
*/
function getRootFolder();
/**
* Returns a view to ownCloud's files folder
*
* @param string $userId user ID
* @return \OCP\Files\Folder
*/
function getUserFolder($userId = null);
/**
* Returns an app-specific view in ownClouds data directory
*
* @return \OCP\Files\Folder
*/
function getAppFolder();
/**
* Returns a user manager
*
* @return \OCP\IUserManager
*/
function getUserManager();
/**
* Returns a group manager
*
* @return \OCP\IGroupManager
*/
function getGroupManager();
/**
* Returns the user session
*
* @return \OCP\IUserSession
*/
function getUserSession();
/**
* Returns the navigation manager
*
* @return \OCP\INavigationManager
*/
function getNavigationManager();
/**
* Returns the config manager
*
* @return \OCP\IConfig
*/
function getConfig();
/**
* Returns an instance of the db facade
* @return \OCP\IDb
*/
function getDb();
/**
* Returns the app config manager
*
* @return \OCP\IAppConfig
*/
function getAppConfig();
/**
* get an L10N instance
* @param string $app appid
* @return \OCP\IL10N
*/
function getL10N($app);
/**
* Returns the URL generator
*
* @return \OCP\IURLGenerator
*/
function getURLGenerator();
/**
* Returns the Helper
*
* @return \OCP\IHelper
*/
function getHelper();
/**
* Returns an ICache instance
*
* @return \OCP\ICache
*/
function getCache();
/**
* Returns an \OCP\CacheFactory instance
*
* @return \OCP\ICacheFactory
*/
function getMemCacheFactory();
/**
* Returns the current session
*
* @return \OCP\ISession
*/
function getSession();
/**
* Returns the activity manager
*
* @return \OCP\Activity\IManager
*/
function getActivityManager();
/**
* Returns the current session
*
* @return \OCP\IDBConnection
*/
function getDatabaseConnection();
/**
* Returns an avatar manager, used for avatar functionality
*
* @return \OCP\IAvatarManager
*/
function getAvatarManager();
/**
* Returns an job list for controlling background jobs
*
* @return \OCP\BackgroundJob\IJobList
*/
function getJobList();
/**
* Returns a router for generating and matching urls
*
* @return \OCP\Route\IRouter
*/
function getRouter();
/**
* Returns a search instance
*
* @return \OCP\ISearch
*/
function getSearch();
/**
* Returns an instance of the HTTP helper class
* @return \OC\HTTPHelper
*/
function getHTTPHelper();
}
| mit |
PauliNiva/Sotechat | src/main/webapp/services/connectToServer.srvc.js | 1805 | /**
* Palvelu huolehtii websocket-yhteyden muodostuspyynnosta
* palvelimeen ja pitaa yhteyden elossa
* kontrollerien valilla liikuessa.
*/
angular.module('commonMod')
.service('connectToServer', ['stompSocket', '$timeout', '$window',
function (stompSocket, $timeout, $window) {
/** Serverin mappaukset */
var WEBSOCKETURL = '/toServer';
/** Yhteyden tila */
var connectionStatus = false;
var reconnectMulti = 1;
/** Yhteyden muodostamis pyyntö
* Parametrina functio jota kutsutaan
* kun yhteys muodostettu
*/
function connect(answer) {
if (!connectionStatus) {
stompSocket.init(WEBSOCKETURL);
stompSocket.connect(function () {
connectionStatus = true;
answer();
}, function () {
connectionStatus = false;
reconnectMulti *= 2 ;
$timeout(function() {
connect(function() {
$window.location.reload();
});
}, 10000 * reconnectMulti);
});
} else {
answer();
}
}
/**
* Funtio jolta voidaan pyytaa kanavan tilaamista.
* Parametrina kavanosoite seka functio jota kutsutaan
* kun viesteja saapuu kanavalta.
*/
function subscribe(destination, answerFunction) {
return stompSocket.subscribe(destination, function (response) {
answerFunction(response);
});
}
var socket = {
connect: connect,
subscribe: subscribe,
};
return socket;
}]); | mit |
inanimatt/shufti | src/Shufti/DataBundle/Entity/DetailRepository.php | 261 | <?php
namespace Shufti\DataBundle\Entity;
use Doctrine\ORM\EntityRepository;
/**
* DetailRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class DetailRepository extends EntityRepository
{
}
| mit |
migrap/Migrap.AspNet.Multitenant | src/Migrap.AspNet.Multitenant/BuilderExtensions.cs | 698 | using Microsoft.AspNet.Builder;
namespace Migrap.AspNet.Multitenant {
public static class BuilderExtensions {
public static IApplicationBuilder UseMultitenant(this IApplicationBuilder builder) {
return builder.UseMiddleware<MultitenantMiddleware>();
}
#if OPTIONS
private static IApplicationBuilder UseMultitenant(this IApplicationBuilder builder, Action<MultitenantOptions> configureOptions = null, string optionsName = "") {
return builder.UseMiddleware<MultitenantMiddleware>(new ConfigureOptions<MultitenantOptions>(configureOptions ?? (o => { })) {
Name = optionsName
});
}
#endif
}
} | mit |
Maplenormandy/list-62x | python/dataProcessing/linearPlots.py | 522 | import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
data = pd.read_csv(open('optimalPointsWmask_16s.csv'))
data['Exposure 0'] = data['Shutter 0']*data['Gain 0']/16.0
data['Exposure 1'] = data['Shutter 1']*data['Gain 1']/16.0
data['Exposure 1 Pred'] = np.clip(111.2148 + 0.6940*data['Exposure 0'] - 2.7011*data['Mean 0'] + 2.6972*data['Mean 1'], 0.0, 2000.0)
plt.scatter(data['Exposure 1'], data['Exposure 1 Pred'] - data['Exposure 1'])
plt.xlabel('Best Exposure')
plt.ylabel('Residual')
plt.show()
| mit |
CarpeDiemCoin/CarpeDiemLaunch | src/qt/locale/bitcoin_ru.ts | 135474 | <?xml version="1.0" ?><!DOCTYPE TS><TS language="ru" version="2.0">
<defaultcodec>UTF-8</defaultcodec>
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About Carpediemcoin</source>
<translation>&О Carpediemcoin</translation>
</message>
<message>
<location line="+39"/>
<source><b>Carpediemcoin</b> version</source>
<translation><b>Carpediemcoin</b> версия</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>
Это экспериментальная программа.
Распространяется на правах лицензии MIT/X11, см. файл license.txt или http://www.opensource.org/licenses/mit-license.php.
Этот продукт включает ПО, разработанное OpenSSL Project для использования в OpenSSL Toolkit (http://www.openssl.org/) и криптографическое ПО, написанное Eric Young (eay@cryptsoft.com) и ПО для работы с UPnP, написанное Thomas Bernard.</translation>
</message>
<message>
<location filename="../aboutdialog.cpp" line="+14"/>
<source>Copyright</source>
<translation>Все права защищены</translation>
</message>
<message>
<location line="+0"/>
<source>The Carpediemcoin developers</source>
<translation>Разработчики Carpediemcoin</translation>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation>&Адресная книга</translation>
</message>
<message>
<location line="+19"/>
<source>Double-click to edit address or label</source>
<translation>Для того, чтобы изменить адрес или метку, дважды кликните по изменяемому объекту</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>Создать новый адрес</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Копировать текущий выделенный адрес в буфер обмена</translation>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation>&Новый адрес</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+63"/>
<source>These are your Carpediemcoin 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>Это Ваши адреса для получения платежей. Вы можете дать разные адреса отправителям, чтобы отслеживать, кто именно вам платит.</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>&Copy Address</source>
<translation>&Копировать адрес</translation>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation>Показать &QR код</translation>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a Carpediemcoin address</source>
<translation>Подписать сообщение, чтобы доказать владение адресом Carpediemcoin</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>&Подписать сообщение</translation>
</message>
<message>
<location line="+25"/>
<source>Delete the currently selected address from the list</source>
<translation>Удалить выбранный адрес из списка</translation>
</message>
<message>
<location line="+27"/>
<source>Export the data in the current tab to a file</source>
<translation>Экспортировать данные из вкладки в файл</translation>
</message>
<message>
<location line="+3"/>
<source>&Export</source>
<translation>&Экспорт</translation>
</message>
<message>
<location line="-44"/>
<source>Verify a message to ensure it was signed with a specified Carpediemcoin address</source>
<translation>Проверить сообщение, чтобы убедиться, что оно было подписано указанным адресом Carpediemcoin</translation>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation>&Проверить сообщение</translation>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>&Удалить</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="-5"/>
<source>These are your Carpediemcoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source>
<translation>Ваши адреса для получения средств. Совет: проверьте сумму и адрес назначения перед переводом.</translation>
</message>
<message>
<location line="+13"/>
<source>Copy &Label</source>
<translation>Копировать &метку</translation>
</message>
<message>
<location line="+1"/>
<source>&Edit</source>
<translation>&Правка</translation>
</message>
<message>
<location line="+1"/>
<source>Send &Coins</source>
<translation>&Отправить монеты</translation>
</message>
<message>
<location line="+260"/>
<source>Export Address Book Data</source>
<translation>Экспортировать адресную книгу</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Текст, разделённый запятыми (*.csv)</translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation>Ошибка экспорта</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Невозможно записать в файл %1.</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation>Метка</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Адрес</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>[нет метки]</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation>Диалог ввода пароля</translation>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>Введите пароль</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>Новый пароль</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>Повторите новый пароль</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+33"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.</source>
<translation>Введите новый пароль для бумажника. <br/> Пожалуйста, используйте фразы из <b>10 или более случайных символов,</b> или <b>восьми и более слов.</b></translation>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation>Зашифровать бумажник</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>Для выполнения операции требуется пароль вашего бумажника.</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>Разблокировать бумажник</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>Для выполнения операции требуется пароль вашего бумажника.</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>Расшифровать бумажник</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>Сменить пароль</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Введите старый и новый пароль для бумажника.</translation>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation>Подтвердите шифрование бумажника</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR BITCOINS</b>!</source>
<translation>Внимание: если вы зашифруете бумажник и потеряете пароль, вы <b>ПОТЕРЯЕТЕ ВСЕ ВАШИ БИТКОИНЫ</b>!</translation>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>Вы уверены, что хотите зашифровать ваш бумажник?</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>ВАЖНО: все предыдущие резервные копии вашего кошелька должны быть заменены новым зашифрованным файлом. В целях безопасности предыдущие резервные копии нешифрованного кошелька станут бесполезны, как только вы начнёте использовать новый шифрованный кошелёк.</translation>
</message>
<message>
<location line="+100"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation>Внимание: Caps Lock включен!</translation>
</message>
<message>
<location line="-130"/>
<location line="+58"/>
<source>Wallet encrypted</source>
<translation>Бумажник зашифрован</translation>
</message>
<message>
<location line="-56"/>
<source>Carpediemcoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your carpediemcoins from being stolen by malware infecting your computer.</source>
<translation>Сейчас программа закроется для завершения процесса шифрования. Помните, что шифрование вашего бумажника не может полностью защитить ваши биткоины от кражи с помощью инфицирования вашего компьютера вредоносным ПО.</translation>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+42"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>Не удалось зашифровать бумажник</translation>
</message>
<message>
<location line="-54"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Шифрование бумажника не удалось из-за внутренней ошибки. Ваш бумажник не был зашифрован.</translation>
</message>
<message>
<location line="+7"/>
<location line="+48"/>
<source>The supplied passphrases do not match.</source>
<translation>Введённые пароли не совпадают.</translation>
</message>
<message>
<location line="-37"/>
<source>Wallet unlock failed</source>
<translation>Разблокировка бумажника не удалась</translation>
</message>
<message>
<location line="+1"/>
<location line="+11"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>Указанный пароль не подходит.</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>Расшифрование бумажника не удалось</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation>Пароль бумажника успешно изменён.</translation>
</message>
</context>
<context>
<name>CarpediemcoinGUI</name>
<message>
<location filename="../carpediemcoingui.cpp" line="+233"/>
<source>Sign &message...</source>
<translation>&Подписать сообщение...</translation>
</message>
<message>
<location line="+280"/>
<source>Synchronizing with network...</source>
<translation>Синхронизация с сетью...</translation>
</message>
<message>
<location line="-349"/>
<source>&Overview</source>
<translation>О&бзор</translation>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation>Показать общий обзор действий с бумажником</translation>
</message>
<message>
<location line="+20"/>
<source>&Transactions</source>
<translation>&Транзакции</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>Показать историю транзакций</translation>
</message>
<message>
<location line="+7"/>
<source>Edit the list of stored addresses and labels</source>
<translation>Изменить список сохранённых адресов и меток к ним</translation>
</message>
<message>
<location line="-14"/>
<source>Show the list of addresses for receiving payments</source>
<translation>Показать список адресов для получения платежей</translation>
</message>
<message>
<location line="+31"/>
<source>E&xit</source>
<translation>В&ыход</translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>Закрыть приложение</translation>
</message>
<message>
<location line="+4"/>
<source>Show information about Carpediemcoin</source>
<translation>Показать информацию о Carpediemcoin'е</translation>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation>О &Qt</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation>Показать информацию о Qt</translation>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>Оп&ции...</translation>
</message>
<message>
<location line="+6"/>
<source>&Encrypt Wallet...</source>
<translation>&Зашифровать бумажник...</translation>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation>&Сделать резервную копию бумажника...</translation>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation>&Изменить пароль...</translation>
</message>
<message>
<location line="+285"/>
<source>Importing blocks from disk...</source>
<translation>Импортируются блоки с диска...</translation>
</message>
<message>
<location line="+3"/>
<source>Reindexing blocks on disk...</source>
<translation>Идёт переиндексация блоков на диске...</translation>
</message>
<message>
<location line="-347"/>
<source>Send coins to a Carpediemcoin address</source>
<translation>Отправить монеты на указанный адрес Carpediemcoin</translation>
</message>
<message>
<location line="+49"/>
<source>Modify configuration options for Carpediemcoin</source>
<translation>Изменить параметры конфигурации Carpediemcoin</translation>
</message>
<message>
<location line="+9"/>
<source>Backup wallet to another location</source>
<translation>Сделать резервную копию бумажника в другом месте</translation>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>Изменить пароль шифрования бумажника</translation>
</message>
<message>
<location line="+6"/>
<source>&Debug window</source>
<translation>&Окно отладки</translation>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation>Открыть консоль отладки и диагностики</translation>
</message>
<message>
<location line="-4"/>
<source>&Verify message...</source>
<translation>&Проверить сообщение...</translation>
</message>
<message>
<location line="-165"/>
<location line="+530"/>
<source>Carpediemcoin</source>
<translation>Биткоин</translation>
</message>
<message>
<location line="-530"/>
<source>Wallet</source>
<translation>Бумажник</translation>
</message>
<message>
<location line="+101"/>
<source>&Send</source>
<translation>&Отправить</translation>
</message>
<message>
<location line="+7"/>
<source>&Receive</source>
<translation>&Получить</translation>
</message>
<message>
<location line="+14"/>
<source>&Addresses</source>
<translation>&Адреса</translation>
</message>
<message>
<location line="+22"/>
<source>&About Carpediemcoin</source>
<translation>&О Carpediemcoin</translation>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation>&Показать / Скрыть</translation>
</message>
<message>
<location line="+1"/>
<source>Show or hide the main Window</source>
<translation>Показать или скрыть главное окно</translation>
</message>
<message>
<location line="+3"/>
<source>Encrypt the private keys that belong to your wallet</source>
<translation>Зашифровать приватные ключи, принадлежащие вашему бумажнику</translation>
</message>
<message>
<location line="+7"/>
<source>Sign messages with your Carpediemcoin addresses to prove you own them</source>
<translation>Подписать сообщения вашим адресом Carpediemcoin, чтобы доказать, что вы им владеете</translation>
</message>
<message>
<location line="+2"/>
<source>Verify messages to ensure they were signed with specified Carpediemcoin addresses</source>
<translation>Проверить сообщения, чтобы удостовериться, что они были подписаны определённым адресом Carpediemcoin</translation>
</message>
<message>
<location line="+28"/>
<source>&File</source>
<translation>&Файл</translation>
</message>
<message>
<location line="+7"/>
<source>&Settings</source>
<translation>&Настройки</translation>
</message>
<message>
<location line="+6"/>
<source>&Help</source>
<translation>&Помощь</translation>
</message>
<message>
<location line="+9"/>
<source>Tabs toolbar</source>
<translation>Панель вкладок</translation>
</message>
<message>
<location line="+17"/>
<location line="+10"/>
<source>[testnet]</source>
<translation>[тестовая сеть]</translation>
</message>
<message>
<location line="+47"/>
<source>Carpediemcoin client</source>
<translation>Carpediemcoin клиент</translation>
</message>
<message numerus="yes">
<location line="+141"/>
<source>%n active connection(s) to Carpediemcoin network</source>
<translation><numerusform>%n активное соединение с сетью</numerusform><numerusform>%n активных соединений с сетью</numerusform><numerusform>%n активных соединений с сетью</numerusform></translation>
</message>
<message>
<location line="+22"/>
<source>No block source available...</source>
<translation>Источник блоков недоступен...</translation>
</message>
<message>
<location line="+12"/>
<source>Processed %1 of %2 (estimated) blocks of transaction history.</source>
<translation>Обработано %1 из %2 (примерно) блоков истории транзакций.</translation>
</message>
<message>
<location line="+4"/>
<source>Processed %1 blocks of transaction history.</source>
<translation>Обработано %1 блоков истории транзакций.</translation>
</message>
<message numerus="yes">
<location line="+20"/>
<source>%n hour(s)</source>
<translation><numerusform>%n час</numerusform><numerusform>%n часа</numerusform><numerusform>%n часов</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation><numerusform>%n день</numerusform><numerusform>%n дня</numerusform><numerusform>%n дней</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n week(s)</source>
<translation><numerusform>%n неделя</numerusform><numerusform>%n недели</numerusform><numerusform>%n недель</numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>%1 behind</source>
<translation>%1 позади</translation>
</message>
<message>
<location line="+14"/>
<source>Last received block was generated %1 ago.</source>
<translation>Последний полученный блок был сгенерирован %1 назад.</translation>
</message>
<message>
<location line="+2"/>
<source>Transactions after this will not yet be visible.</source>
<translation>Транзакции после этой пока не будут видны.</translation>
</message>
<message>
<location line="+22"/>
<source>Error</source>
<translation>Ошибка</translation>
</message>
<message>
<location line="+3"/>
<source>Warning</source>
<translation>Внимание</translation>
</message>
<message>
<location line="+3"/>
<source>Information</source>
<translation>Информация</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>Транзакция превышает максимальный размер. Вы можете провести её, заплатив комиссию %1, которая достанется узлам, обрабатывающим эту транзакцию, и поможет работе сети. Вы действительно хотите заплатить комиссию?</translation>
</message>
<message>
<location line="-140"/>
<source>Up to date</source>
<translation>Синхронизировано</translation>
</message>
<message>
<location line="+31"/>
<source>Catching up...</source>
<translation>Синхронизируется...</translation>
</message>
<message>
<location line="+113"/>
<source>Confirm transaction fee</source>
<translation>Подтвердите комиссию</translation>
</message>
<message>
<location line="+8"/>
<source>Sent transaction</source>
<translation>Исходящая транзакция</translation>
</message>
<message>
<location line="+0"/>
<source>Incoming transaction</source>
<translation>Входящая транзакция</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>Дата: %1
Количество: %2
Тип: %3
Адрес: %4
</translation>
</message>
<message>
<location line="+33"/>
<location line="+23"/>
<source>URI handling</source>
<translation>Обработка URI</translation>
</message>
<message>
<location line="-23"/>
<location line="+23"/>
<source>URI can not be parsed! This can be caused by an invalid Carpediemcoin address or malformed URI parameters.</source>
<translation>Не удалось обработать URI! Это может быть связано с неверным адресом Carpediemcoin или неправильными параметрами URI.</translation>
</message>
<message>
<location line="+17"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>Бумажник <b>зашифрован</b> и в настоящее время <b>разблокирован</b></translation>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>Бумажник <b>зашифрован</b> и в настоящее время <b>заблокирован</b></translation>
</message>
<message>
<location filename="../carpediemcoin.cpp" line="+111"/>
<source>A fatal error occurred. Carpediemcoin can no longer continue safely and will quit.</source>
<translation>Произошла неисправимая ошибка. Carpediemcoin не может безопасно продолжать работу и будет закрыт.</translation>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+104"/>
<source>Network Alert</source>
<translation>Сетевая Тревога</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>Изменить адрес</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation>&Метка</translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation>Метка, связанная с данной записью</translation>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>&Адрес</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>Адрес, связанный с данной записью.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+21"/>
<source>New receiving address</source>
<translation>Новый адрес для получения</translation>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation>Новый адрес для отправки</translation>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation>Изменение адреса для получения</translation>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation>Изменение адреса для отправки</translation>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>Введённый адрес «%1» уже находится в адресной книге.</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid Carpediemcoin address.</source>
<translation>Введённый адрес "%1" не является правильным Carpediemcoin-адресом.</translation>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation>Не удается разблокировать бумажник.</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>Генерация нового ключа не удалась.</translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+424"/>
<location line="+12"/>
<source>Carpediemcoin-Qt</source>
<translation>Carpediemcoin-Qt</translation>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation>версия</translation>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation>Использование:</translation>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation>параметры командной строки</translation>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation>Опции интерфейса</translation>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation>Выберите язык, например "de_DE" (по умолчанию: как в системе)</translation>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation>Запускать свёрнутым</translation>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation>Показывать сплэш при запуске (по умолчанию: 1)</translation>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation>Опции</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation>&Главная</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>Необязательная комиссия за каждый КБ транзакции, которая ускоряет обработку Ваших транзакций. Большинство транзакций занимают 1КБ.</translation>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation>Заплатить ко&миссию</translation>
</message>
<message>
<location line="+31"/>
<source>Automatically start Carpediemcoin after logging in to the system.</source>
<translation>Автоматически запускать Carpediemcoin после входа в систему</translation>
</message>
<message>
<location line="+3"/>
<source>&Start Carpediemcoin on system login</source>
<translation>&Запускать Carpediemcoin при входе в систему</translation>
</message>
<message>
<location line="+35"/>
<source>Reset all client options to default.</source>
<translation>Сбросить все опции клиента на значения по умолчанию.</translation>
</message>
<message>
<location line="+3"/>
<source>&Reset Options</source>
<translation>&Сбросить опции</translation>
</message>
<message>
<location line="+13"/>
<source>&Network</source>
<translation>&Сеть</translation>
</message>
<message>
<location line="+6"/>
<source>Automatically open the Carpediemcoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation>Автоматически открыть порт для Carpediemcoin-клиента на роутере. Работает только если Ваш роутер поддерживает UPnP, и данная функция включена.</translation>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation>Пробросить порт через &UPnP</translation>
</message>
<message>
<location line="+7"/>
<source>Connect to the Carpediemcoin network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation>Подключаться к сети Carpediemcoin через прокси SOCKS (например, при подключении через Tor).</translation>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation>&Подключаться через SOCKS прокси:</translation>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation>&IP Прокси: </translation>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation>IP-адрес прокси (например 127.0.0.1)</translation>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation>По&рт: </translation>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation>Порт прокси-сервера (например, 9050)</translation>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation>&Версия SOCKS:</translation>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation>Версия SOCKS-прокси (например, 5)</translation>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation>&Окно</translation>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation>Показывать только иконку в системном лотке после сворачивания окна.</translation>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>&Cворачивать в системный лоток вместо панели задач</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>Сворачивать вместо закрытия. Если данная опция будет выбрана — приложение закроется только после выбора соответствующего пункта в меню.</translation>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation>С&ворачивать при закрытии</translation>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation>О&тображение</translation>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation>&Язык интерфейса:</translation>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting Carpediemcoin.</source>
<translation>Здесь можно выбрать язык интерфейса. Настройки вступят в силу после перезапуска Carpediemcoin.</translation>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation>&Отображать суммы в единицах: </translation>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation>Выберите единицу измерения монет при отображении и отправке.</translation>
</message>
<message>
<location line="+9"/>
<source>Whether to show Carpediemcoin addresses in the transaction list or not.</source>
<translation>Показывать ли адреса Carpediemcoin в списке транзакций.</translation>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation>&Показывать адреса в списке транзакций</translation>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation>О&К</translation>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation>&Отмена</translation>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation>&Применить</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+53"/>
<source>default</source>
<translation>по умолчанию</translation>
</message>
<message>
<location line="+130"/>
<source>Confirm options reset</source>
<translation>Подтвердите сброс опций</translation>
</message>
<message>
<location line="+1"/>
<source>Some settings may require a client restart to take effect.</source>
<translation>Некоторые настройки могут потребовать перезапуск клиента, чтобы вступить в силу.</translation>
</message>
<message>
<location line="+0"/>
<source>Do you want to proceed?</source>
<translation>Желаете продолжить?</translation>
</message>
<message>
<location line="+42"/>
<location line="+9"/>
<source>Warning</source>
<translation>Внимание</translation>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting Carpediemcoin.</source>
<translation>Эта настройка вступит в силу после перезапуска Carpediemcoin</translation>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation>Адрес прокси неверен.</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation>Форма</translation>
</message>
<message>
<location line="+50"/>
<location line="+166"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the Carpediemcoin network after a connection is established, but this process has not completed yet.</source>
<translation>Отображаемая информация может быть устаревшей. Ваш бумажник автоматически синхронизируется с сетью Carpediemcoin после подключения, но этот процесс пока не завершён.</translation>
</message>
<message>
<location line="-124"/>
<source>Balance:</source>
<translation>Баланс:</translation>
</message>
<message>
<location line="+29"/>
<source>Unconfirmed:</source>
<translation>Не подтверждено:</translation>
</message>
<message>
<location line="-78"/>
<source>Wallet</source>
<translation>Бумажник</translation>
</message>
<message>
<location line="+107"/>
<source>Immature:</source>
<translation>Незрелые:</translation>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation>Баланс добытых монет, который ещё не созрел</translation>
</message>
<message>
<location line="+46"/>
<source><b>Recent transactions</b></source>
<translation><b>Последние транзакции</b></translation>
</message>
<message>
<location line="-101"/>
<source>Your current balance</source>
<translation>Ваш текущий баланс</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>Общая сумма всех транзакций, которые до сих пор не подтверждены, и до сих пор не учитываются в текущем балансе</translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="+116"/>
<location line="+1"/>
<source>out of sync</source>
<translation>не синхронизировано</translation>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<location filename="../paymentserver.cpp" line="+107"/>
<source>Cannot start carpediemcoin: click-to-pay handler</source>
<translation>Не удаётся запустить carpediemcoin: обработчик click-to-pay</translation>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation>Диалог QR-кода</translation>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation>Запросить платёж</translation>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation>Количество:</translation>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation>Метка:</translation>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation>Сообщение:</translation>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation>&Сохранить как...</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation>Ошибка кодирования URI в QR-код</translation>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation>Введено неверное количество, проверьте ещё раз.</translation>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation>Получившийся URI слишком длинный, попробуйте сократить текст метки / сообщения.</translation>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation>Сохранить QR-код</translation>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation>PNG Изображения (*.png)</translation>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation>Имя клиента</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>Н/Д</translation>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation>Версия клиента</translation>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation>&Информация</translation>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation>Используется версия OpenSSL</translation>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation>Время запуска</translation>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation>Сеть</translation>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation>Число подключений</translation>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation>В тестовой сети</translation>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation>Цепь блоков</translation>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation>Текущее число блоков</translation>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation>Расчётное число блоков</translation>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation>Время последнего блока</translation>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation>&Открыть</translation>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation>Параметры командной строки</translation>
</message>
<message>
<location line="+7"/>
<source>Show the Carpediemcoin-Qt help message to get a list with possible Carpediemcoin command-line options.</source>
<translation>Показать помощь по Carpediemcoin-Qt, чтобы получить список доступных параметров командной строки.</translation>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation>&Показать</translation>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation>Консоль</translation>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation>Дата сборки</translation>
</message>
<message>
<location line="-104"/>
<source>Carpediemcoin - Debug window</source>
<translation>Carpediemcoin - Окно отладки</translation>
</message>
<message>
<location line="+25"/>
<source>Carpediemcoin Core</source>
<translation>Ядро Carpediemcoin</translation>
</message>
<message>
<location line="+279"/>
<source>Debug log file</source>
<translation>Отладочный лог-файл</translation>
</message>
<message>
<location line="+7"/>
<source>Open the Carpediemcoin debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation>Открыть отладочный лог-файл Carpediemcoin из текущего каталога данных. Это может занять несколько секунд для больших лог-файлов.</translation>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation>Очистить консоль</translation>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-30"/>
<source>Welcome to the Carpediemcoin RPC console.</source>
<translation>Добро пожаловать в RPC-консоль Carpediemcoin.</translation>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation>Используйте стрелки вверх и вниз для просмотра истории и <b>Ctrl-L</b> для очистки экрана.</translation>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation>Напишите <b>help</b> для просмотра доступных команд.</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>Отправка</translation>
</message>
<message>
<location line="+50"/>
<source>Send to multiple recipients at once</source>
<translation>Отправить нескольким получателям одновременно</translation>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation>&Добавить получателя</translation>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation>Удалить все поля транзакции</translation>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation>Очистить &всё</translation>
</message>
<message>
<location line="+22"/>
<source>Balance:</source>
<translation>Баланс:</translation>
</message>
<message>
<location line="+10"/>
<source>123.456 CDC</source>
<translation>123.456 CDC</translation>
</message>
<message>
<location line="+31"/>
<source>Confirm the send action</source>
<translation>Подтвердить отправку</translation>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation>&Отправить</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-59"/>
<source><b>%1</b> to %2 (%3)</source>
<translation><b>%1</b> адресату %2 (%3)</translation>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation>Подтвердите отправку монет</translation>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation>Вы уверены, что хотите отправить %1?</translation>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation> и </translation>
</message>
<message>
<location line="+23"/>
<source>The recipient address is not valid, please recheck.</source>
<translation>Адрес получателя неверный, пожалуйста, перепроверьте.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation>Количество монет для отправки должно быть больше 0.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation>Количество отправляемых монет превышает Ваш баланс</translation>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation>Сумма превысит Ваш баланс, если комиссия в размере %1 будет добавлена к транзакции</translation>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation>Обнаружен дублирующийся адрес. Отправка на один и тот же адрес возможна только один раз за одну операцию отправки</translation>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed!</source>
<translation>Ошибка: не удалось создать транзакцию!</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>Ошибка: В транзакции отказано. Такое может произойти, если некоторые монеты уже были потрачены, например, если Вы используете одну копию файла wallet.dat, а монеты были потрачены из другой копии, но не были отмечены как потраченные в этой.</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation>Форма</translation>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation>Ко&личество:</translation>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation>Полу&чатель:</translation>
</message>
<message>
<location line="+34"/>
<source>The address to send the payment to (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation>Адрес, на который будет выслан платёж (например 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</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>Введите метку для данного адреса (для добавления в адресную книгу)</translation>
</message>
<message>
<location line="-78"/>
<source>&Label:</source>
<translation>&Метка:</translation>
</message>
<message>
<location line="+28"/>
<source>Choose address from address book</source>
<translation>Выберите адрес из адресной книги</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>Вставить адрес из буфера обмена</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>Удалить этого получателя</translation>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a Carpediemcoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation>Введите Carpediemcoin-адрес (например 1LA5FtQhnnWnkK6zjFfutR7Stiit4wKd63)</translation>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation>Подписи - подписать/проверить сообщение</translation>
</message>
<message>
<location line="+13"/>
<source>&Sign Message</source>
<translation>&Подписать сообщение</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>Вы можете подписывать сообщения своими адресами, чтобы доказать владение ими. Будьте осторожны, не подписывайте что-то неопределённое, так как фишинговые атаки могут обманным путём заставить вас подписать нежелательные сообщения. Подписывайте только те сообщения, с которыми вы согласны вплоть до мелочей.</translation>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation>Адрес, которым вы хотите подписать сообщение (напр. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation>
</message>
<message>
<location line="+10"/>
<location line="+213"/>
<source>Choose an address from the address book</source>
<translation>Выберите адрес из адресной книги</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>Вставить адрес из буфера обмена</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>Введите сообщение для подписи</translation>
</message>
<message>
<location line="+7"/>
<source>Signature</source>
<translation>Подпись</translation>
</message>
<message>
<location line="+27"/>
<source>Copy the current signature to the system clipboard</source>
<translation>Скопировать текущую подпись в системный буфер обмена</translation>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this Carpediemcoin address</source>
<translation>Подписать сообщение, чтобы доказать владение адресом Carpediemcoin</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>Подписать &Сообщение</translation>
</message>
<message>
<location line="+14"/>
<source>Reset all sign message fields</source>
<translation>Сбросить значения всех полей подписывания сообщений</translation>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation>Очистить &всё</translation>
</message>
<message>
<location line="-87"/>
<source>&Verify Message</source>
<translation>&Проверить сообщение</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>Введите ниже адрес для подписи, сообщение (убедитесь, что переводы строк, пробелы, табы и т.п. в точности скопированы) и подпись, чтобы проверить сообщение. Убедитесь, что не скопировали лишнего в подпись, по сравнению с самим подписываемым сообщением, чтобы не стать жертвой атаки "man-in-the-middle".</translation>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation>Адрес, которым было подписано сообщение (напр. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified Carpediemcoin address</source>
<translation>Проверить сообщение, чтобы убедиться, что оно было подписано указанным адресом Carpediemcoin</translation>
</message>
<message>
<location line="+3"/>
<source>Verify &Message</source>
<translation>Проверить &Сообщение</translation>
</message>
<message>
<location line="+14"/>
<source>Reset all verify message fields</source>
<translation>Сбросить все поля проверки сообщения</translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a Carpediemcoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation>Введите адрес Carpediemcoin (напр. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation>Нажмите "Подписать сообщение" для создания подписи</translation>
</message>
<message>
<location line="+3"/>
<source>Enter Carpediemcoin signature</source>
<translation>Введите подпись Carpediemcoin</translation>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation>Введённый адрес неверен</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>Пожалуйста, проверьте адрес и попробуйте ещё раз.</translation>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation>Введённый адрес не связан с ключом</translation>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation>Разблокировка бумажника была отменена.</translation>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation>Для введённого адреса недоступен закрытый ключ</translation>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation>Не удалось подписать сообщение</translation>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation>Сообщение подписано</translation>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation>Подпись не может быть раскодирована.</translation>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation>Пожалуйста, проверьте подпись и попробуйте ещё раз.</translation>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation>Подпись не соответствует отпечатку сообщения.</translation>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation>Проверка сообщения не удалась.</translation>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation>Сообщение проверено.</translation>
</message>
</context>
<context>
<name>SplashScreen</name>
<message>
<location filename="../splashscreen.cpp" line="+22"/>
<source>The Carpediemcoin developers</source>
<translation>Разработчики Carpediemcoin</translation>
</message>
<message>
<location line="+1"/>
<source>[testnet]</source>
<translation>[тестовая сеть]</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+20"/>
<source>Open until %1</source>
<translation>Открыто до %1</translation>
</message>
<message>
<location line="+6"/>
<source>%1/offline</source>
<translation>%1/отключен</translation>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1/не подтверждено</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>%1 подтверждений</translation>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation>Статус</translation>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation><numerusform>, разослано через %n узел</numerusform><numerusform>, разослано через %n узла</numerusform><numerusform>, разослано через %n узлов</numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>Дата</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation>Источник</translation>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation>Сгенерированно</translation>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation>От</translation>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation>Для</translation>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation>свой адрес</translation>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation>метка</translation>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation>Кредит</translation>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation><numerusform>будет доступно через %n блок</numerusform><numerusform>будет доступно через %n блока</numerusform><numerusform>будет доступно через %n блоков</numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation>не принято</translation>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation>Дебет</translation>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation>Комиссия</translation>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation>Чистая сумма</translation>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation>Сообщение</translation>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation>Комментарий:</translation>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation>ID транзакции</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 "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation>Сгенерированные монеты должны подождать 120 блоков, прежде чем они могут быть потрачены. Когда Вы сгенерировали этот блок, он был отправлен в сеть для добавления в цепочку блоков. Если данная процедура не удастся, статус изменится на «не подтверждено», и монеты будут недействительны. Это иногда происходит в случае, если другой узел сгенерирует блок на несколько секунд раньше вас.</translation>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation>Отладочная информация</translation>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation>Транзакция</translation>
</message>
<message>
<location line="+3"/>
<source>Inputs</source>
<translation>Входы</translation>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation>Количество</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation>истина</translation>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation>ложь</translation>
</message>
<message>
<location line="-209"/>
<source>, has not been successfully broadcast yet</source>
<translation>, ещё не было успешно разослано</translation>
</message>
<message numerus="yes">
<location line="-35"/>
<source>Open for %n more block(s)</source>
<translation><numerusform>Открыто для ещё %n блока</numerusform><numerusform>Открыто для ещё %n блоков</numerusform><numerusform>Открыто для ещё %n блоков</numerusform></translation>
</message>
<message>
<location line="+70"/>
<source>unknown</source>
<translation>неизвестно</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>Детали транзакции</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>Данный диалог показывает детализированную статистику по выбранной транзакции</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+225"/>
<source>Date</source>
<translation>Дата</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>Тип</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Адрес</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>Количество</translation>
</message>
<message numerus="yes">
<location line="+57"/>
<source>Open for %n more block(s)</source>
<translation><numerusform>Открыто для ещё %n блока</numerusform><numerusform>Открыто для ещё %n блоков</numerusform><numerusform>Открыто для ещё %n блоков</numerusform></translation>
</message>
<message>
<location line="+3"/>
<source>Open until %1</source>
<translation>Открыто до %1</translation>
</message>
<message>
<location line="+3"/>
<source>Offline (%1 confirmations)</source>
<translation>Оффлайн (%1 подтверждений)</translation>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed (%1 of %2 confirmations)</source>
<translation>Не подтверждено (%1 из %2 подтверждений)</translation>
</message>
<message>
<location line="+3"/>
<source>Confirmed (%1 confirmations)</source>
<translation>Подтверждено (%1 подтверждений)</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>Добытыми монетами можно будет воспользоваться через %n блок</numerusform><numerusform>Добытыми монетами можно будет воспользоваться через %n блока</numerusform><numerusform>Добытыми монетами можно будет воспользоваться через %n блоков</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>Этот блок не был получен другими узлами и, возможно, не будет принят!</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>Сгенерированно, но не подтверждено</translation>
</message>
<message>
<location line="+43"/>
<source>Received with</source>
<translation>Получено</translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation>Получено от</translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>Отправлено</translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation>Отправлено себе</translation>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation>Добыто</translation>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation>[не доступно]</translation>
</message>
<message>
<location line="+199"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>Статус транзакции. Подведите курсор к нужному полю для того, чтобы увидеть количество подтверждений.</translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>Дата и время, когда транзакция была получена.</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>Тип транзакции.</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>Адрес назначения транзакции.</translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>Сумма, добавленная, или снятая с баланса.</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+52"/>
<location line="+16"/>
<source>All</source>
<translation>Все</translation>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation>Сегодня</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation>На этой неделе</translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation>В этом месяце</translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation>За последний месяц</translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation>В этом году</translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation>Промежуток...</translation>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation>Получено на</translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>Отправлено на</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>Отправленные себе</translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation>Добытые</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation>Другое</translation>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation>Введите адрес или метку для поиска</translation>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation>Мин. сумма</translation>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation>Копировать адрес</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Копировать метку</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Скопировать сумму</translation>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation>Скопировать ID транзакции</translation>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation>Изменить метку</translation>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation>Показать подробности транзакции</translation>
</message>
<message>
<location line="+139"/>
<source>Export Transaction Data</source>
<translation>Экспортировать данные транзакций</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Текст, разделённый запятыми (*.csv)</translation>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation>Подтверждено</translation>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>Дата</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>Тип</translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>Метка</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>Адрес</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation>Количество</translation>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation>ID</translation>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation>Ошибка экспорта</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Невозможно записать в файл %1.</translation>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation>Промежуток от:</translation>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation>до</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+193"/>
<source>Send Coins</source>
<translation>Отправка</translation>
</message>
</context>
<context>
<name>WalletView</name>
<message>
<location filename="../walletview.cpp" line="+42"/>
<source>&Export</source>
<translation>&Экспорт</translation>
</message>
<message>
<location line="+1"/>
<source>Export the data in the current tab to a file</source>
<translation>Экспортировать данные из вкладки в файл</translation>
</message>
<message>
<location line="+193"/>
<source>Backup Wallet</source>
<translation>Сделать резервную копию бумажника</translation>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation>Данные бумажника (*.dat)</translation>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation>Резервное копирование не удалось</translation>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation>При попытке сохранения данных бумажника в новое место произошла ошибка.</translation>
</message>
<message>
<location line="+4"/>
<source>Backup Successful</source>
<translation>Резервное копирование успешно завершено</translation>
</message>
<message>
<location line="+0"/>
<source>The wallet data was successfully saved to the new location.</source>
<translation>Данные бумажника успешно сохранены в новое место.</translation>
</message>
</context>
<context>
<name>carpediemcoin-core</name>
<message>
<location filename="../carpediemcoinstrings.cpp" line="+94"/>
<source>Carpediemcoin version</source>
<translation>Версия</translation>
</message>
<message>
<location line="+102"/>
<source>Usage:</source>
<translation>Использование:</translation>
</message>
<message>
<location line="-29"/>
<source>Send command to -server or carpediemcoind</source>
<translation>Отправить команду на -server или carpediemcoind</translation>
</message>
<message>
<location line="-23"/>
<source>List commands</source>
<translation>Список команд
</translation>
</message>
<message>
<location line="-12"/>
<source>Get help for a command</source>
<translation>Получить помощь по команде</translation>
</message>
<message>
<location line="+24"/>
<source>Options:</source>
<translation>Опции:</translation>
</message>
<message>
<location line="+24"/>
<source>Specify configuration file (default: carpediemcoin.conf)</source>
<translation>Указать конфигурационный файл (по умолчанию: carpediemcoin.conf)</translation>
</message>
<message>
<location line="+3"/>
<source>Specify pid file (default: carpediemcoind.pid)</source>
<translation>Задать pid-файл (по умолчанию: carpediemcoin.pid)</translation>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation>Задать каталог данных</translation>
</message>
<message>
<location line="-9"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation>Установить размер кэша базы данных в мегабайтах (по умолчанию: 25)</translation>
</message>
<message>
<location line="-28"/>
<source>Listen for connections on <port> (default: 6480 or testnet: 16480)</source>
<translation>Принимать входящие подключения на <port> (по умолчанию: 6480 или 16480 в тестовой сети)</translation>
</message>
<message>
<location line="+5"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>Поддерживать не более <n> подключений к узлам (по умолчанию: 125)</translation>
</message>
<message>
<location line="-48"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation>Подключиться к узлу, чтобы получить список адресов других участников и отключиться</translation>
</message>
<message>
<location line="+82"/>
<source>Specify your own public address</source>
<translation>Укажите ваш собственный публичный адрес</translation>
</message>
<message>
<location line="+3"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation>Порог для отключения неправильно ведущих себя узлов (по умолчанию: 100)</translation>
</message>
<message>
<location line="-134"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation>Число секунд блокирования неправильно ведущих себя узлов (по умолчанию: 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>Произошла ошибка при открытии RPC-порта %u для прослушивания на IPv4: %s</translation>
</message>
<message>
<location line="+27"/>
<source>Listen for JSON-RPC connections on <port> (default: 6479 or testnet: 16479)</source>
<translation>Прослушивать подключения JSON-RPC на <порту> (по умолчанию: 6479 или для testnet: 16479)</translation>
</message>
<message>
<location line="+37"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>Принимать командную строку и команды JSON-RPC</translation>
</message>
<message>
<location line="+76"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>Запускаться в фоне как демон и принимать команды</translation>
</message>
<message>
<location line="+37"/>
<source>Use the test network</source>
<translation>Использовать тестовую сеть</translation>
</message>
<message>
<location line="-112"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation>Принимать подключения извне (по умолчанию: 1, если не используется -proxy или -connect)</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=carpediemcoinrpc
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 "Carpediemcoin Alert" admin@foo.com
</source>
<translation>%s, вы должны установить опцию rpcpassword в конфигурационном файле:
%s
Рекомендуется использовать следующий случайный пароль:
rpcuser=carpediemcoinrpc
rpcpassword=%s
(вам не нужно запоминать этот пароль)
Имя и пароль ДОЛЖНЫ различаться.
Если файл не существует, создайте его и установите права доступа только для владельца, только для чтения.
Также рекомендуется включить alertnotify для оповещения о проблемах;
Например: alertnotify=echo %%s | mail -s "Carpediemcoin Alert" 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>Произошла ошибка при открытии на прослушивание IPv6 RCP-порта %u, возвращаемся к 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>Привязаться к указанному адресу и всегда прослушивать только его. Используйте [хост]:порт для IPv6</translation>
</message>
<message>
<location line="+3"/>
<source>Cannot obtain a lock on data directory %s. Carpediemcoin is probably already running.</source>
<translation>Не удаётся установить блокировку на каталог данных %s. Возможно, Carpediemcoin уже работает.</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>Ошибка: транзакция была отклонена! Это могло произойти в случае, если некоторые монеты в вашем бумажнике уже были потрачены, например, если вы используете копию wallet.dat, и монеты были использованы в копии, но не отмечены как потраченные здесь.</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>Ошибка: эта транзакция требует комиссию как минимум %s из-за суммы, сложности или использования недавно полученных средств!</translation>
</message>
<message>
<location line="+3"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation>Выполнить команду, когда приходит сообщение о тревоге (%s в команде заменяется на сообщение)</translation>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation>Выполнить команду, когда меняется транзакция в бумажнике (%s в команде заменяется на TxID)</translation>
</message>
<message>
<location line="+11"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation>Максимальный размер высокоприоритетных/низкокомиссионных транзакций в байтах (по умолчанию: 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>Это пре-релизная тестовая сборка - используйте на свой страх и риск - не используйте для добычи или торговых приложений</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>Внимание: установлено очень большое значение -paytxfee. Это комиссия, которую вы заплатите при проведении транзакции.</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>Внимание: отображаемые транзакции могут быть некорректны! Вам или другим узлам, возможно, следует обновиться.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong Carpediemcoin will not work properly.</source>
<translation>Внимание: убедитесь, что дата и время на Вашем компьютере выставлены верно. Если Ваши часы идут неправильно, Carpediemcoin будет работать некорректно.</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>Внимание: ошибка чтения wallet.dat! Все ключи прочитаны верно, но данные транзакций или записи адресной книги могут отсутствовать или быть неправильными.</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>Внимание: wallet.dat повреждён, данные спасены! Оригинальный wallet.dat сохранён как wallet.{timestamp}.bak в %s; если ваш баланс или транзакции некорректны, вы должны восстановить файл из резервной копии.</translation>
</message>
<message>
<location line="+14"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation>Попытаться восстановить приватные ключи из повреждённого wallet.dat</translation>
</message>
<message>
<location line="+2"/>
<source>Block creation options:</source>
<translation>Параметры создания блоков:</translation>
</message>
<message>
<location line="+5"/>
<source>Connect only to the specified node(s)</source>
<translation>Подключаться только к указанному узлу(ам)</translation>
</message>
<message>
<location line="+3"/>
<source>Corrupted block database detected</source>
<translation>БД блоков повреждена</translation>
</message>
<message>
<location line="+1"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation>Определить свой IP (по умолчанию: 1 при прослушивании и если не используется -externalip)</translation>
</message>
<message>
<location line="+1"/>
<source>Do you want to rebuild the block database now?</source>
<translation>Пересобрать БД блоков прямо сейчас?</translation>
</message>
<message>
<location line="+2"/>
<source>Error initializing block database</source>
<translation>Ошибка инициализации БД блоков</translation>
</message>
<message>
<location line="+1"/>
<source>Error initializing wallet database environment %s!</source>
<translation>Ошибка инициализации окружения БД бумажника %s!</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading block database</source>
<translation>Ошибка чтения базы данных блоков</translation>
</message>
<message>
<location line="+4"/>
<source>Error opening block database</source>
<translation>Не удалось открыть БД блоков</translation>
</message>
<message>
<location line="+2"/>
<source>Error: Disk space is low!</source>
<translation>Ошибка: мало места на диске!</translation>
</message>
<message>
<location line="+1"/>
<source>Error: Wallet locked, unable to create transaction!</source>
<translation>Ошибка: бумажник заблокирован, невозможно создать транзакцию!</translation>
</message>
<message>
<location line="+1"/>
<source>Error: system error: </source>
<translation>Ошибка: системная ошибка:</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation>Не удалось начать прослушивание на порту. Используйте -listen=0 если вас это устраивает.</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to read block info</source>
<translation>Не удалось прочитать информацию блока</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to read block</source>
<translation>Не удалось прочитать блок</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to sync block index</source>
<translation>Не удалось синхронизировать индекс блоков</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write block index</source>
<translation>Не удалось записать индекс блоков</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write block info</source>
<translation>Не удалось записать информацию блока</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write block</source>
<translation>Не удалось записать блок</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write file info</source>
<translation>Не удалось записать информацию файла</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write to coin database</source>
<translation>Не удалось записать БД монет</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write transaction index</source>
<translation>Не удалось записать индекс транзакций</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write undo data</source>
<translation>Не удалось записать данные для отмены</translation>
</message>
<message>
<location line="+2"/>
<source>Find peers using DNS lookup (default: 1 unless -connect)</source>
<translation>Искать узлы с помощью DNS (по умолчанию: 1, если не указан -connect)</translation>
</message>
<message>
<location line="+1"/>
<source>Generate coins (default: 0)</source>
<translation>Включить добычу монет (по умолчанию: 0)</translation>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 288, 0 = all)</source>
<translation>Сколько блоков проверять при запуске (по умолчанию: 288, 0 = все)</translation>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-4, default: 3)</source>
<translation>Насколько тщательно проверять блок (0-4, по умолчанию: 3)</translation>
</message>
<message>
<location line="+19"/>
<source>Not enough file descriptors available.</source>
<translation>Недостаточно файловых дескрипторов.</translation>
</message>
<message>
<location line="+8"/>
<source>Rebuild block chain index from current blk000??.dat files</source>
<translation>Перестроить индекс цепи блоков из текущих файлов blk000??.dat</translation>
</message>
<message>
<location line="+16"/>
<source>Set the number of threads to service RPC calls (default: 4)</source>
<translation>Задать число потоков выполнения(по умолчанию: 4)</translation>
</message>
<message>
<location line="+26"/>
<source>Verifying blocks...</source>
<translation>Проверка блоков...</translation>
</message>
<message>
<location line="+1"/>
<source>Verifying wallet...</source>
<translation>Проверка бумажника...</translation>
</message>
<message>
<location line="-69"/>
<source>Imports blocks from external blk000??.dat file</source>
<translation>Импортировать блоки из внешнего файла blk000??.dat</translation>
</message>
<message>
<location line="-76"/>
<source>Set the number of script verification threads (up to 16, 0 = auto, <0 = leave that many cores free, default: 0)</source>
<translation>Задать число потоков проверки скрипта (вплоть до 16, 0=авто, <0 = оставить столько ядер свободными, по умолчанию: 0)</translation>
</message>
<message>
<location line="+77"/>
<source>Information</source>
<translation>Информация</translation>
</message>
<message>
<location line="+3"/>
<source>Invalid -tor address: '%s'</source>
<translation>Неверный адрес -tor: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -minrelaytxfee=<amount>: '%s'</source>
<translation>Неверное количество в параметре -minrelaytxfee=<кол-во>: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -mintxfee=<amount>: '%s'</source>
<translation>Неверное количество в параметре -mintxfee=<кол-во>: '%s'</translation>
</message>
<message>
<location line="+8"/>
<source>Maintain a full transaction index (default: 0)</source>
<translation>Держать полный индекс транзакций (по умолчанию: 0)</translation>
</message>
<message>
<location line="+2"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation>Максимальный размер буфера приёма на соединение, <n>*1000 байт (по умолчанию: 5000)</translation>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation>Максимальный размер буфера отправки на соединение, <n>*1000 байт (по умолчанию: 1000)</translation>
</message>
<message>
<location line="+2"/>
<source>Only accept block chain matching built-in checkpoints (default: 1)</source>
<translation>Принимать цепь блоков, только если она соответствует встроенным контрольным точкам (по умолчанию: 1)</translation>
</message>
<message>
<location line="+1"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation>Подключаться только к узлам из сети <net> (IPv4, IPv6 или Tor)</translation>
</message>
<message>
<location line="+2"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation>Выводить больше отладочной информации. Включает все остальные опции -debug*</translation>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation>Выводить дополнительную сетевую отладочную информацию</translation>
</message>
<message>
<location line="+2"/>
<source>Prepend debug output with timestamp</source>
<translation>Дописывать отметки времени к отладочному выводу</translation>
</message>
<message>
<location line="+5"/>
<source>SSL options: (see the Carpediemcoin Wiki for SSL setup instructions)</source>
<translation>
Параметры SSL: (см. Carpediemcoin Wiki для инструкций по настройке SSL)</translation>
</message>
<message>
<location line="+1"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation>Выбрать версию SOCKS-прокси (4-5, по умолчанию: 5)</translation>
</message>
<message>
<location line="+3"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>Выводить информацию трассировки/отладки на консоль вместо файла debug.log</translation>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation>Отправлять информацию трассировки/отладки в отладчик</translation>
</message>
<message>
<location line="+5"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation>Максимальный размер блока в байтах (по умолчанию: 250000)</translation>
</message>
<message>
<location line="+1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation>Минимальный размер блока в байтах (по умолчанию: 0)</translation>
</message>
<message>
<location line="+2"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation>Сжимать файл debug.log при запуске клиента (по умолчанию: 1, если нет -debug)</translation>
</message>
<message>
<location line="+1"/>
<source>Signing transaction failed</source>
<translation>Не удалось подписать транзакцию</translation>
</message>
<message>
<location line="+2"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation>Таймаут соединения в миллисекундах (по умолчанию: 5000)</translation>
</message>
<message>
<location line="+4"/>
<source>System error: </source>
<translation>Системная ошибка:</translation>
</message>
<message>
<location line="+4"/>
<source>Transaction amount too small</source>
<translation>Объём транзакции слишком мал</translation>
</message>
<message>
<location line="+1"/>
<source>Transaction amounts must be positive</source>
<translation>Объём транзакции должен быть положителен</translation>
</message>
<message>
<location line="+1"/>
<source>Transaction too large</source>
<translation>Транзакция слишком большая</translation>
</message>
<message>
<location line="+7"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation>Использовать UPnP для проброса порта (по умолчанию: 0)</translation>
</message>
<message>
<location line="+1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation>Использовать UPnP для проброса порта (по умолчанию: 1, если используется прослушивание)</translation>
</message>
<message>
<location line="+1"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation>Использовать прокси для скрытых сервисов (по умолчанию: тот же, что и в -proxy)</translation>
</message>
<message>
<location line="+2"/>
<source>Username for JSON-RPC connections</source>
<translation>Имя для подключений JSON-RPC</translation>
</message>
<message>
<location line="+4"/>
<source>Warning</source>
<translation>Внимание</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation>Внимание: эта версия устарела, требуется обновление!</translation>
</message>
<message>
<location line="+1"/>
<source>You need to rebuild the databases using -reindex to change -txindex</source>
<translation>Вам необходимо пересобрать базы данных с помощью -reindex, чтобы изменить -txindex</translation>
</message>
<message>
<location line="+1"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation>wallet.dat повреждён, спасение данных не удалось</translation>
</message>
<message>
<location line="-50"/>
<source>Password for JSON-RPC connections</source>
<translation>Пароль для подключений JSON-RPC</translation>
</message>
<message>
<location line="-67"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>Разрешить подключения JSON-RPC с указанного IP</translation>
</message>
<message>
<location line="+76"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>Посылать команды узлу, запущенному на <ip> (по умолчанию: 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>Выполнить команду, когда появляется новый блок (%s в команде заменяется на хэш блока)</translation>
</message>
<message>
<location line="+147"/>
<source>Upgrade wallet to latest format</source>
<translation>Обновить бумажник до последнего формата</translation>
</message>
<message>
<location line="-21"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>Установить размер запаса ключей в <n> (по умолчанию: 100)</translation>
</message>
<message>
<location line="-12"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>Перепроверить цепь блоков на предмет отсутствующих в бумажнике транзакций</translation>
</message>
<message>
<location line="+35"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>Использовать OpenSSL (https) для подключений JSON-RPC</translation>
</message>
<message>
<location line="-26"/>
<source>Server certificate file (default: server.cert)</source>
<translation>Файл серверного сертификата (по умолчанию: server.cert)</translation>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation>Приватный ключ сервера (по умолчанию: server.pem)</translation>
</message>
<message>
<location line="-151"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation>Разрешённые алгоритмы (по умолчанию: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation>
</message>
<message>
<location line="+165"/>
<source>This help message</source>
<translation>Эта справка</translation>
</message>
<message>
<location line="+6"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation>Невозможно привязаться к %s на этом компьютере (bind вернул ошибку %d, %s)</translation>
</message>
<message>
<location line="-91"/>
<source>Connect through socks proxy</source>
<translation>Подключаться через socks прокси</translation>
</message>
<message>
<location line="-10"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation>Разрешить поиск в DNS для -addnode, -seednode и -connect</translation>
</message>
<message>
<location line="+55"/>
<source>Loading addresses...</source>
<translation>Загрузка адресов...</translation>
</message>
<message>
<location line="-35"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>Ошибка загрузки wallet.dat: Бумажник поврежден</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat: Wallet requires newer version of Carpediemcoin</source>
<translation>Ошибка загрузки wallet.dat: бумажник требует более новую версию Carpediemcoin</translation>
</message>
<message>
<location line="+93"/>
<source>Wallet needed to be rewritten: restart Carpediemcoin to complete</source>
<translation>Необходимо перезаписать бумажник, перезапустите Carpediemcoin для завершения операции.</translation>
</message>
<message>
<location line="-95"/>
<source>Error loading wallet.dat</source>
<translation>Ошибка при загрузке wallet.dat</translation>
</message>
<message>
<location line="+28"/>
<source>Invalid -proxy address: '%s'</source>
<translation>Неверный адрес -proxy: '%s'</translation>
</message>
<message>
<location line="+56"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation>В параметре -onlynet указана неизвестная сеть: '%s'</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation>В параметре -socks запрошена неизвестная версия: %i</translation>
</message>
<message>
<location line="-96"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation>Не удаётся разрешить адрес в параметре -bind: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation>Не удаётся разрешить адрес в параметре -externalip: '%s'</translation>
</message>
<message>
<location line="+44"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation>Неверное количество в параметре -paytxfee=<кол-во>: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount</source>
<translation>Неверное количество</translation>
</message>
<message>
<location line="-6"/>
<source>Insufficient funds</source>
<translation>Недостаточно монет</translation>
</message>
<message>
<location line="+10"/>
<source>Loading block index...</source>
<translation>Загрузка индекса блоков...</translation>
</message>
<message>
<location line="-57"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>Добавить узел для подключения и пытаться поддерживать соединение открытым</translation>
</message>
<message>
<location line="-25"/>
<source>Unable to bind to %s on this computer. Carpediemcoin is probably already running.</source>
<translation>Невозможно привязаться к %s на этом компьютере. Возможно, Carpediemcoin уже работает.</translation>
</message>
<message>
<location line="+64"/>
<source>Fee per KB to add to transactions you send</source>
<translation>Комиссия на килобайт, добавляемая к вашим транзакциям</translation>
</message>
<message>
<location line="+19"/>
<source>Loading wallet...</source>
<translation>Загрузка бумажника...</translation>
</message>
<message>
<location line="-52"/>
<source>Cannot downgrade wallet</source>
<translation>Не удаётся понизить версию бумажника</translation>
</message>
<message>
<location line="+3"/>
<source>Cannot write default address</source>
<translation>Не удаётся записать адрес по умолчанию</translation>
</message>
<message>
<location line="+64"/>
<source>Rescanning...</source>
<translation>Сканирование...</translation>
</message>
<message>
<location line="-57"/>
<source>Done loading</source>
<translation>Загрузка завершена</translation>
</message>
<message>
<location line="+82"/>
<source>To use the %s option</source>
<translation>Чтобы использовать опцию %s</translation>
</message>
<message>
<location line="-74"/>
<source>Error</source>
<translation>Ошибка</translation>
</message>
<message>
<location line="-31"/>
<source>You must set rpcpassword=<password> in the configuration file:
%s
If the file does not exist, create it with owner-readable-only file permissions.</source>
<translation>Вы должны установить rpcpassword=<password> в конфигурационном файле:
%s
Если файл не существует, создайте его и установите права доступа только для владельца.</translation>
</message>
</context>
</TS> | mit |
jkbaumohl/kb_PRINSEQ | lib/src/us/kbase/kbprinseq/InputPRINSEQ.java | 4922 |
package us.kbase.kbprinseq;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
/**
* <p>Original spec-file type: inputPRINSEQ</p>
* <pre>
* execPRINSEQ and execReadLibraryPRINSEQ input
* input_reads_ref : may be KBaseFile.PairedEndLibrary or KBaseFile.SingleEndLibrary
* output_ws : workspace to write to
* output_reads_name : obj_name to create
* lc_method : Low complexity method - value must be "dust" or "entropy"
* lc_entropy_threshold : Low complexity threshold - Value must be an integer between 0 and 100.
* Note a higher lc_entropy_threshold in entropy is more stringent.
* lc_dust_threshold : Low complexity threshold - Value must be an integer between 0 and 100.
* Note a lower lc_entropy_threshold is less stringent with dust
* </pre>
*
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
@Generated("com.googlecode.jsonschema2pojo")
@JsonPropertyOrder({
"input_reads_ref",
"output_ws",
"output_reads_name",
"lc_method",
"lc_entropy_threshold",
"lc_dust_threshold"
})
public class InputPRINSEQ {
@JsonProperty("input_reads_ref")
private String inputReadsRef;
@JsonProperty("output_ws")
private String outputWs;
@JsonProperty("output_reads_name")
private String outputReadsName;
@JsonProperty("lc_method")
private String lcMethod;
@JsonProperty("lc_entropy_threshold")
private Long lcEntropyThreshold;
@JsonProperty("lc_dust_threshold")
private Long lcDustThreshold;
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
@JsonProperty("input_reads_ref")
public String getInputReadsRef() {
return inputReadsRef;
}
@JsonProperty("input_reads_ref")
public void setInputReadsRef(String inputReadsRef) {
this.inputReadsRef = inputReadsRef;
}
public InputPRINSEQ withInputReadsRef(String inputReadsRef) {
this.inputReadsRef = inputReadsRef;
return this;
}
@JsonProperty("output_ws")
public String getOutputWs() {
return outputWs;
}
@JsonProperty("output_ws")
public void setOutputWs(String outputWs) {
this.outputWs = outputWs;
}
public InputPRINSEQ withOutputWs(String outputWs) {
this.outputWs = outputWs;
return this;
}
@JsonProperty("output_reads_name")
public String getOutputReadsName() {
return outputReadsName;
}
@JsonProperty("output_reads_name")
public void setOutputReadsName(String outputReadsName) {
this.outputReadsName = outputReadsName;
}
public InputPRINSEQ withOutputReadsName(String outputReadsName) {
this.outputReadsName = outputReadsName;
return this;
}
@JsonProperty("lc_method")
public String getLcMethod() {
return lcMethod;
}
@JsonProperty("lc_method")
public void setLcMethod(String lcMethod) {
this.lcMethod = lcMethod;
}
public InputPRINSEQ withLcMethod(String lcMethod) {
this.lcMethod = lcMethod;
return this;
}
@JsonProperty("lc_entropy_threshold")
public Long getLcEntropyThreshold() {
return lcEntropyThreshold;
}
@JsonProperty("lc_entropy_threshold")
public void setLcEntropyThreshold(Long lcEntropyThreshold) {
this.lcEntropyThreshold = lcEntropyThreshold;
}
public InputPRINSEQ withLcEntropyThreshold(Long lcEntropyThreshold) {
this.lcEntropyThreshold = lcEntropyThreshold;
return this;
}
@JsonProperty("lc_dust_threshold")
public Long getLcDustThreshold() {
return lcDustThreshold;
}
@JsonProperty("lc_dust_threshold")
public void setLcDustThreshold(Long lcDustThreshold) {
this.lcDustThreshold = lcDustThreshold;
}
public InputPRINSEQ withLcDustThreshold(Long lcDustThreshold) {
this.lcDustThreshold = lcDustThreshold;
return this;
}
@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
@JsonAnySetter
public void setAdditionalProperties(String name, Object value) {
this.additionalProperties.put(name, value);
}
@Override
public String toString() {
return ((((((((((((((("InputPRINSEQ"+" [inputReadsRef=")+ inputReadsRef)+", outputWs=")+ outputWs)+", outputReadsName=")+ outputReadsName)+", lcMethod=")+ lcMethod)+", lcEntropyThreshold=")+ lcEntropyThreshold)+", lcDustThreshold=")+ lcDustThreshold)+", additionalProperties=")+ additionalProperties)+"]");
}
}
| mit |
wangyanxing/Demi3D | src/tools/HonViewer/ViewerHelper.cpp | 971 | /**********************************************************************
This source file is a part of Demi3D
__ ___ __ __ __
| \|_ |\/|| _)| \
|__/|__| || __)|__/
Copyright (c) 2013-2014 Demi team
https://github.com/wangyanxing/Demi3D
Released under the MIT License
https://github.com/wangyanxing/Demi3D/blob/master/License.txt
***********************************************************************/
#include "ViewerPch.h"
#include "ViewerHelper.h"
namespace tools
{
ViewerHelper::ViewerHelper() :
Dialog("Helper.layout"),
mButtonOk(nullptr)
{
assignWidget(mButtonOk, "Ok");
mButtonOk->eventMouseButtonClick += MyGUI::newDelegate(this, &ViewerHelper::notifyOk);
mMainWidget->setVisible(false);
}
ViewerHelper::~ViewerHelper()
{
}
void ViewerHelper::notifyOk(MyGUI::Widget* _sender)
{
eventEndDialog(this, true);
endModal();
}
} // tools
| mit |
acrogame/acro | models/Game.ts | 2738 | /**
* Game.ts
*
* Any classes, enums, or interfaces related to a Game.
*
*/
import {IRoundVM, IRound, Round, ROUND} from './Round';
/**
* GAME_STATUS
*
* An enum representing the Game's status. It should be used as a flag for
* whether or not a Game is:
*
* 1. INACTIVE, meaning there aren't enough people engaged to start a Game
* 2. READY, meaning the Game is Inactive, but ready to start
* 3. ACTIVE, meaning there is a Game in progress
*
*/
export enum GAME_STATUS {
INACTIVE, // Not enough engaged players to start a game
READY, // Waiting to start a game
ACTIVE // Actively playing a game
}
/**
* IGame
*
* Interface for Game objects
*
*/
export interface IGame {
roomId: string;
status: GAME_STATUS;
roundTracker: IRound;
updateCallback();
nextRoundCallback();
start();
getData();
}
/**
* IGameVM
*
* Interface for Game ViewModel objects. This is reserved for
* data that will be persisted in Firebase. No Functions.
*
*/
export interface IGameVM {
roomId: string;
status: GAME_STATUS;
round: IRoundVM;
}
/**
* Game
*
* A Game tracking object. Responsible for tracking all game-related data
* including its associated Room, its status (GAME_STATUS), its round information,
* the players involved in the Game.
*
* Constructor:
*
* @param {string} roomId - The id of the Room the Game is associated with
* @param {Function} updateCallback - A callback function to handle updating Firebase when data changes
* @param {Function} nextRoundCallback - A callback function to handle advancing to the next Round
*
* Properties:
*
* @prop {string} roomId - The id of the Room the Game is associated with
* @prop {GAME_STATUS} status - The Game's status
* @prop {IRound} roundTracker - Tracks the state of the Game's Rounds
*
* Methods:
*
* @method start(): void - Start the Game
* @method getData(): IGameVM - Get a snapshot of the Game's data
*
*/
export class Game implements IGame {
roomId: string;
status: GAME_STATUS;
roundTracker: IRound;
updateCallback: any;
nextRoundCallback: any;
constructor(roomId: string, updateCallback: Function, nextRoundCallback: Function) {
this.roomId = roomId;
this.status = GAME_STATUS.INACTIVE;
this.updateCallback = updateCallback;
this.nextRoundCallback = nextRoundCallback;
this.roundTracker = new Round(this.updateCallback, this.nextRoundCallback);
}
// Start the Game!
start(): void {
this.roundTracker.start(30);
}
// Get the ViewModel version of the Game in its current state
getData(): IGameVM {
return {
roomId: this.roomId,
status: this.status,
round: this.roundTracker.getRoundViewModel()
};
}
} | mit |
kony/OAuthSample | visualizer code/KonySampleOAuth/studioactions/mobile/AS_Button_2f8c25a88a484dddbbc4890a9131bc3c.js | 99 | function AS_Button_2f8c25a88a484dddbbc4890a9131bc3c(eventobject) {
return fbLogin.call(this);
} | mit |
kdzwinel/betwixt | src/dt/cm/overlay.js | 3049 | // CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
// Utility function that allows modes to be combined. The mode given
// as the base argument takes care of most of the normal mode
// functionality, but a second (typically simple) mode is used, which
// can override the style of text. Both modes get to parse all of the
// text, but when both assign a non-null style to a piece of code, the
// overlay wins, unless the combine argument was true and not overridden,
// or state.overlay.combineTokens was true, in which case the styles are
// combined.
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../src/lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
CodeMirror.overlayMode = function(base, overlay, combine) {
return {
startState: function() {
return {
base: CodeMirror.startState(base),
overlay: CodeMirror.startState(overlay),
basePos: 0, baseCur: null,
overlayPos: 0, overlayCur: null,
lineSeen: null
};
},
copyState: function(state) {
return {
base: CodeMirror.copyState(base, state.base),
overlay: CodeMirror.copyState(overlay, state.overlay),
basePos: state.basePos, baseCur: null,
overlayPos: state.overlayPos, overlayCur: null
};
},
token: function(stream, state) {
if (stream.sol() || stream.string != state.lineSeen ||
Math.min(state.basePos, state.overlayPos) < stream.start) {
state.lineSeen = stream.string;
state.basePos = state.overlayPos = stream.start;
}
if (stream.start == state.basePos) {
state.baseCur = base.token(stream, state.base);
state.basePos = stream.pos;
}
if (stream.start == state.overlayPos) {
stream.pos = stream.start;
state.overlayCur = overlay.token(stream, state.overlay);
state.overlayPos = stream.pos;
}
stream.pos = Math.min(state.basePos, state.overlayPos);
// state.overlay.combineTokens always takes precedence over combine,
// unless set to null
if (state.overlayCur == null) return state.baseCur;
else if (state.baseCur != null &&
state.overlay.combineTokens ||
combine && state.overlay.combineTokens == null)
return state.baseCur + " " + state.overlayCur;
else return state.overlayCur;
},
indent: base.indent && function(state, textAfter) {
return base.indent(state.base, textAfter);
},
electricChars: base.electricChars,
innerMode: function(state) { return {state: state.base, mode: base}; },
blankLine: function(state) {
if (base.blankLine) base.blankLine(state.base);
if (overlay.blankLine) overlay.blankLine(state.overlay);
}
};
};
});
| mit |
MrAsimov/architecture-styles-patterns | builder/src/main/java/com/design/builder/Animal.java | 1263 | /*
* MIT License
*
* Copyright (c) 2017 Andy Holst
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.design.builder;
public interface Animal {
String getAnimalType();
void setAnimalType(String animalType);
}
| mit |
dgoldman916/nyu-python | class1/session_6/while_loop.py | 272 | #!/usr/bin/env python3
import sys
def conditional():
a = int(sys.argv[1])
b = int(sys.argv[2])
if ( a > b ):
print("a > b")
elif ( a < b ):
print("a < b")
else:
print("a = b")
if __name__ == '__main__':
conditional()
| mit |
gjb7/is217-unit-test | js/main.js | 1260 | (function(global) {
var $ = global.$,
QUnit = global.QUnit;
QUnit.test("prettyDate.format", function() {
function date(then, expected) {
QUnit.equal(prettyDate.format("2008/01/28 22:25:00", then), expected);
}
date("2008/01/28 22:24:30", "just now");
date("2008/01/28 22:25:30", "just now");
date("2008/01/28 22:23:30", "1 min ago");
date("2008/01/28 22:26:30", "in 1 min");
date("2008/01/28 21:23:30", "1 hr ago");
date("2008/01/28 23:25:30", "in 1 hr");
date("2008/01/27 22:23:30", "yesterday");
date("2008/01/29 22:25:30", "tomorrow");
date("2008/01/26 22:23:30", "2 days ago");
date("2008/01/30 22:25:30", "in 2 days");
date("2007/01/26 22:23:30", null);
});
function domTest(name, now, first, second) {
QUnit.test(name, function() {
var links = $('#qunit-fixture .time a')
QUnit.equal(links[0].innerHTML, "January 28th, 2008");
QUnit.equal(links[1].innerHTML, "January 27th, 2008");
prettyDate.update(now);
QUnit.equal(links[0].innerHTML, first);
QUnit.equal(links[1].innerHTML, second);
});
}
domTest("prettyDate.update", "2008-01-28T22:25:00Z", "2 hrs ago", "yesterday");
domTest("prettyDate.update, one day later", "2008/01/29 22:25:00", "yesterday", "2 days ago");
})(window);
| mit |
MarcinMilewski/sqap | sqap-auth/src/main/java/com/sqap/auth/domain/UserRepository.java | 237 | package com.sqap.auth.domain;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Repository;
public interface UserRepository {
UserDetails loadUserByUsername(String username);
}
| mit |
reutnagar/plastic-tableware | app/controllers/email.controller.js | 2108 | var nodemailer = require("nodemailer");
var Order = require('../models/Order');
var qs = require('querystring');
module.exports = {
sendEmailserver: sendEmailserver,
};
function sendEmailserver(req, res) {
console.log("send Mail");
var body = '';
req.on('data', function (data) {
body += data;
if (body.length > 1e6) {
// FLOOD ATTACK OR FAULTY CLIENT, NUKE REQUEST
req.connection.destroy();
}
});
req.on('end', function () {
var POST = qs.parse(body);
var email = POST.email;
if (POST.type == "order") {
var text = 'שלום וברכה!' + "\n" + "אנו שמחים שקניתה אצלינו" + "\n" + "הזמנתך תגיע בעוד כשלושה ימים" + "\n" + "נשמח לעמוד לשירותך תמיד" + "\n" + "צוות plastictableware";
console.log(text);
var mailOptions = {
from: 'plastictableware.cs@gmail.com', // sender address
to: email,
subject: 'הזמנתך התקבלה', // Subject line
text: text //, // plaintext body
};
} else {
var mailOptions = {
from: 'plastictableware.cs@gmail.com', // sender address
to: 'plastictableware.cs@gmail.com',
subject: ' מ פניה ' + email, // Subject line
text: POST.content //, // plaintext body
};
}
console.log("mailOptions~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~", mailOptions);
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'plastictableware.cs@gmail.com', // Your email id
pass: 'plastictableware' // Your password
}
});
transporter.sendMail(mailOptions, function (error, info) {
if (error) {
return console.log(error);
}
console.log('Message sent: ' + info.response);
});
res.send('הזמנתך התקבלה!');
});
} | mit |
saraswatisc/seminar | application/views/peserta/sidebar.php | 2982 | <aside class="main-sidebar">
<!-- sidebar: style can be found in sidebar.less -->
<section class="sidebar">
<!-- Sidebar user panel -->
<div class="user-panel">
<div class="pull-left">
<!--
<?php
//echo $this->session->userdata('foto');
if ($this->session->userdata('foto')=="") { ?>
<img src="<?php echo base_url('uploads/peserta/peserta.jpg')?>" class="img-circle" width="50" height="50">
<?php
} else {
?>
<img src="<?php echo base_url('uploads/peserta/').$this->session->userdata('foto');?>" class="img-circle" width="50" height="50">
<?php
}
?>
<?php //echo base_url('uploads/panitia/').$this->session->userdata('foto');?>-->
<img src="<?php echo base_url('uploads/peserta/').$this->session->userdata('foto');?>" class="img-circle" width="50" height="50">
</div>
<div class="pull-left info">
<p><?php echo $this->session->userdata('nama_panggilan'); ?></p>
<a><i class="fa fa-circle text-success"></i> Online</a>
</div>
</div>
<!-- search form -->
<!--
<form action="#" method="get" class="sidebar-form">
<div class="input-group">
<input type="text" name="q" class="form-control" placeholder="Search...">
<span class="input-group-btn">
<button type="submit" name="search" id="search-btn" class="btn btn-flat"><i class="fa fa-search"></i></button>
</span>
</div>
</form>
-->
<!-- /.search form -->
<!-- sidebar menu: : style can be found in sidebar.less -->
<ul class="sidebar-menu">
<li class="header">MENU</li>
<li class="treeview">
<a href="<?php echo site_url('peserta');?>">
<i class="fa fa-file-o"></i> <span>Seminar Saya</span>
</a>
</li>
<li class="treeview">
<a href="<?php echo site_url('peserta/lihatSemuaSeminar');?>">
<i class="fa fa-file"></i> <span>Semua Seminar</span>
</a>
</li>
<li class="treeview">
<a href="<?php echo site_url('peserta/profilPeserta');?>">
<i class="fa fa-user"></i>
<span>Profil</span>
</a>
</li>
<li class="treeview">
<a href="<?php echo site_url('peserta/logoutPeserta');?>">
<i class="fa fa-sign-out"></i>
<span>Logout</span>
<!--<span class="label label-primary pull-right">4</span>-->
</a>
</li>
</section>
<!-- /.sidebar -->
</aside> | mit |
mkoitzu/uc2-poc | src/client/app/+dragndrop/index.ts | 158 | /**
* This barrel file provides the export for the lazy loaded HomeComponent.
*/
export * from './dragndrop.component';
export * from './dragndrop.routes';
| mit |
dollarshaveclub/furan | vendor/github.com/jackc/pgx/v4/pgxpool/stat.go | 768 | package pgxpool
import (
"time"
"github.com/jackc/puddle"
)
type Stat struct {
s *puddle.Stat
}
func (s *Stat) AcquireCount() int64 {
return s.s.AcquireCount()
}
func (s *Stat) AcquireDuration() time.Duration {
return s.s.AcquireDuration()
}
func (s *Stat) AcquiredConns() int32 {
return s.s.AcquiredResources()
}
func (s *Stat) CanceledAcquireCount() int64 {
return s.s.CanceledAcquireCount()
}
func (s *Stat) ConstructingConns() int32 {
return s.s.ConstructingResources()
}
func (s *Stat) EmptyAcquireCount() int64 {
return s.s.EmptyAcquireCount()
}
func (s *Stat) IdleConns() int32 {
return s.s.IdleResources()
}
func (s *Stat) MaxConns() int32 {
return s.s.MaxResources()
}
func (s *Stat) TotalConns() int32 {
return s.s.TotalResources()
}
| mit |
ilogue/scrolls | test/viewtestcase.py | 1306 | from pyramid import testing
from test.ditestcase import DITestCase
from test.redirectioncontextmanager import RedirectionContextManager
from mock import Mock
class ViewTestCase(DITestCase):
def setUp(self):
super(ViewTestCase, self).setUp()
self.pyramidconfig = testing.setUp()
self.request = testing.DummyRequest()
self.request.user_logged_in = False
self.request.context = Mock()
def route_url(route, **kwargs):
return route, kwargs
self.request.route_url = route_url
def resource_url(ctx, *elem, **kwargs):
return ctx, elem, kwargs
self.request.resource_url = resource_url
self.request.matchdict = {'iam': 'the matchdict'}
self.request.POST = {'iam': 'the POST dict'}
self.request.params = {'iam': 'the PARAMS dict'}
self.request.dependencies = self.dependencies
def tearDown(self):
testing.tearDown()
def assertRedirectsToRoute(self, route, **kwargs):
loc = self.request.route_url(route, **kwargs)
return RedirectionContextManager(self, loc)
def assertRedirectsToContext(self, *elem, **kwargs):
loc = self.request.resource_url(self.request.context, *elem, **kwargs)
return RedirectionContextManager(self, loc)
| mit |
quekshuy/go-sg-cinema-scraper | data/types.go | 403 |
package data
type Movie struct {
Duration int // in mins
Description string
Title string
CinemaName string
ShowTimes []string
}
type Cinema struct {
Name string
Movies []*Movie
}
// URL, context for this current URL (basically a nest hierarchy),
// channel for cinemas, channel for movies
type ScraperStrategy func(string, interface{}, chan<- []*Cinema, chan<- []*Movie)
| mit |
ryfeus/lambda-packs | HDF4_H5_NETCDF/source2.7/Cython/Build/Dependencies.py | 43610 | from __future__ import absolute_import, print_function
import cython
from .. import __version__
import os
import shutil
import hashlib
import subprocess
import collections
import re, sys, time
from glob import iglob
from io import open as io_open
from os.path import relpath as _relpath
from distutils.extension import Extension
from distutils.util import strtobool
try:
import gzip
gzip_open = gzip.open
gzip_ext = '.gz'
except ImportError:
gzip_open = open
gzip_ext = ''
try:
import pythran
import pythran.config
PythranAvailable = True
except:
PythranAvailable = False
from .. import Utils
from ..Utils import (cached_function, cached_method, path_exists,
safe_makedirs, copy_file_to_dir_if_newer, is_package_dir)
from ..Compiler.Main import Context, CompilationOptions, default_options
join_path = cached_function(os.path.join)
copy_once_if_newer = cached_function(copy_file_to_dir_if_newer)
safe_makedirs_once = cached_function(safe_makedirs)
if sys.version_info[0] < 3:
# stupid Py2 distutils enforces str type in list of sources
_fs_encoding = sys.getfilesystemencoding()
if _fs_encoding is None:
_fs_encoding = sys.getdefaultencoding()
def encode_filename_in_py2(filename):
if not isinstance(filename, bytes):
return filename.encode(_fs_encoding)
return filename
else:
def encode_filename_in_py2(filename):
return filename
basestring = str
def _make_relative(file_paths, base=None):
if not base:
base = os.getcwd()
if base[-1] != os.path.sep:
base += os.path.sep
return [_relpath(path, base) if path.startswith(base) else path
for path in file_paths]
def extended_iglob(pattern):
if '{' in pattern:
m = re.match('(.*){([^}]+)}(.*)', pattern)
if m:
before, switch, after = m.groups()
for case in switch.split(','):
for path in extended_iglob(before + case + after):
yield path
return
if '**/' in pattern:
seen = set()
first, rest = pattern.split('**/', 1)
if first:
first = iglob(first+'/')
else:
first = ['']
for root in first:
for path in extended_iglob(join_path(root, rest)):
if path not in seen:
seen.add(path)
yield path
for path in extended_iglob(join_path(root, '*', '**/' + rest)):
if path not in seen:
seen.add(path)
yield path
else:
for path in iglob(pattern):
yield path
def nonempty(it, error_msg="expected non-empty iterator"):
empty = True
for value in it:
empty = False
yield value
if empty:
raise ValueError(error_msg)
@cached_function
def file_hash(filename):
path = os.path.normpath(filename.encode("UTF-8"))
prefix = (str(len(path)) + ":").encode("UTF-8")
m = hashlib.md5(prefix)
m.update(path)
f = open(filename, 'rb')
try:
data = f.read(65000)
while data:
m.update(data)
data = f.read(65000)
finally:
f.close()
return m.hexdigest()
def parse_list(s):
"""
>>> parse_list("")
[]
>>> parse_list("a")
['a']
>>> parse_list("a b c")
['a', 'b', 'c']
>>> parse_list("[a, b, c]")
['a', 'b', 'c']
>>> parse_list('a " " b')
['a', ' ', 'b']
>>> parse_list('[a, ",a", "a,", ",", ]')
['a', ',a', 'a,', ',']
"""
if len(s) >= 2 and s[0] == '[' and s[-1] == ']':
s = s[1:-1]
delimiter = ','
else:
delimiter = ' '
s, literals = strip_string_literals(s)
def unquote(literal):
literal = literal.strip()
if literal[0] in "'\"":
return literals[literal[1:-1]]
else:
return literal
return [unquote(item) for item in s.split(delimiter) if item.strip()]
transitive_str = object()
transitive_list = object()
bool_or = object()
distutils_settings = {
'name': str,
'sources': list,
'define_macros': list,
'undef_macros': list,
'libraries': transitive_list,
'library_dirs': transitive_list,
'runtime_library_dirs': transitive_list,
'include_dirs': transitive_list,
'extra_objects': list,
'extra_compile_args': transitive_list,
'extra_link_args': transitive_list,
'export_symbols': list,
'depends': transitive_list,
'language': transitive_str,
'np_pythran': bool_or
}
def update_pythran_extension(ext):
if not PythranAvailable:
raise RuntimeError("You first need to install Pythran to use the np_pythran directive.")
pythran_ext = pythran.config.make_extension()
ext.include_dirs.extend(pythran_ext['include_dirs'])
ext.extra_compile_args.extend(pythran_ext['extra_compile_args'])
ext.extra_link_args.extend(pythran_ext['extra_link_args'])
ext.define_macros.extend(pythran_ext['define_macros'])
ext.undef_macros.extend(pythran_ext['undef_macros'])
ext.library_dirs.extend(pythran_ext['library_dirs'])
ext.libraries.extend(pythran_ext['libraries'])
ext.language = 'c++'
# These options are not compatible with the way normal Cython extensions work
for bad_option in ["-fwhole-program", "-fvisibility=hidden"]:
try:
ext.extra_compile_args.remove(bad_option)
except ValueError:
pass
@cython.locals(start=cython.Py_ssize_t, end=cython.Py_ssize_t)
def line_iter(source):
if isinstance(source, basestring):
start = 0
while True:
end = source.find('\n', start)
if end == -1:
yield source[start:]
return
yield source[start:end]
start = end+1
else:
for line in source:
yield line
class DistutilsInfo(object):
def __init__(self, source=None, exn=None):
self.values = {}
if source is not None:
for line in line_iter(source):
line = line.lstrip()
if not line:
continue
if line[0] != '#':
break
line = line[1:].lstrip()
kind = next((k for k in ("distutils:","cython:") if line.startswith(k)), None)
if not kind is None:
key, _, value = [s.strip() for s in line[len(kind):].partition('=')]
type = distutils_settings.get(key, None)
if line.startswith("cython:") and type is None: continue
if type in (list, transitive_list):
value = parse_list(value)
if key == 'define_macros':
value = [tuple(macro.split('=', 1))
if '=' in macro else (macro, None)
for macro in value]
if type is bool_or:
value = strtobool(value)
self.values[key] = value
elif exn is not None:
for key in distutils_settings:
if key in ('name', 'sources','np_pythran'):
continue
value = getattr(exn, key, None)
if value:
self.values[key] = value
def merge(self, other):
if other is None:
return self
for key, value in other.values.items():
type = distutils_settings[key]
if type is transitive_str and key not in self.values:
self.values[key] = value
elif type is transitive_list:
if key in self.values:
# Change a *copy* of the list (Trac #845)
all = self.values[key][:]
for v in value:
if v not in all:
all.append(v)
value = all
self.values[key] = value
elif type is bool_or:
self.values[key] = self.values.get(key, False) | value
return self
def subs(self, aliases):
if aliases is None:
return self
resolved = DistutilsInfo()
for key, value in self.values.items():
type = distutils_settings[key]
if type in [list, transitive_list]:
new_value_list = []
for v in value:
if v in aliases:
v = aliases[v]
if isinstance(v, list):
new_value_list += v
else:
new_value_list.append(v)
value = new_value_list
else:
if value in aliases:
value = aliases[value]
resolved.values[key] = value
return resolved
def apply(self, extension):
for key, value in self.values.items():
type = distutils_settings[key]
if type in [list, transitive_list]:
value = getattr(extension, key) + list(value)
setattr(extension, key, value)
@cython.locals(start=cython.Py_ssize_t, q=cython.Py_ssize_t,
single_q=cython.Py_ssize_t, double_q=cython.Py_ssize_t,
hash_mark=cython.Py_ssize_t, end=cython.Py_ssize_t,
k=cython.Py_ssize_t, counter=cython.Py_ssize_t, quote_len=cython.Py_ssize_t)
def strip_string_literals(code, prefix='__Pyx_L'):
"""
Normalizes every string literal to be of the form '__Pyx_Lxxx',
returning the normalized code and a mapping of labels to
string literals.
"""
new_code = []
literals = {}
counter = 0
start = q = 0
in_quote = False
hash_mark = single_q = double_q = -1
code_len = len(code)
quote_type = quote_len = None
while True:
if hash_mark < q:
hash_mark = code.find('#', q)
if single_q < q:
single_q = code.find("'", q)
if double_q < q:
double_q = code.find('"', q)
q = min(single_q, double_q)
if q == -1:
q = max(single_q, double_q)
# We're done.
if q == -1 and hash_mark == -1:
new_code.append(code[start:])
break
# Try to close the quote.
elif in_quote:
if code[q-1] == u'\\':
k = 2
while q >= k and code[q-k] == u'\\':
k += 1
if k % 2 == 0:
q += 1
continue
if code[q] == quote_type and (
quote_len == 1 or (code_len > q + 2 and quote_type == code[q+1] == code[q+2])):
counter += 1
label = "%s%s_" % (prefix, counter)
literals[label] = code[start+quote_len:q]
full_quote = code[q:q+quote_len]
new_code.append(full_quote)
new_code.append(label)
new_code.append(full_quote)
q += quote_len
in_quote = False
start = q
else:
q += 1
# Process comment.
elif -1 != hash_mark and (hash_mark < q or q == -1):
new_code.append(code[start:hash_mark+1])
end = code.find('\n', hash_mark)
counter += 1
label = "%s%s_" % (prefix, counter)
if end == -1:
end_or_none = None
else:
end_or_none = end
literals[label] = code[hash_mark+1:end_or_none]
new_code.append(label)
if end == -1:
break
start = q = end
# Open the quote.
else:
if code_len >= q+3 and (code[q] == code[q+1] == code[q+2]):
quote_len = 3
else:
quote_len = 1
in_quote = True
quote_type = code[q]
new_code.append(code[start:q])
start = q
q += quote_len
return "".join(new_code), literals
# We need to allow spaces to allow for conditional compilation like
# IF ...:
# cimport ...
dependency_regex = re.compile(r"(?:^\s*from +([0-9a-zA-Z_.]+) +cimport)|"
r"(?:^\s*cimport +([0-9a-zA-Z_.]+(?: *, *[0-9a-zA-Z_.]+)*))|"
r"(?:^\s*cdef +extern +from +['\"]([^'\"]+)['\"])|"
r"(?:^\s*include +['\"]([^'\"]+)['\"])", re.M)
def normalize_existing(base_path, rel_paths):
return normalize_existing0(os.path.dirname(base_path), tuple(set(rel_paths)))
@cached_function
def normalize_existing0(base_dir, rel_paths):
"""
Given some base directory ``base_dir`` and a list of path names
``rel_paths``, normalize each relative path name ``rel`` by
replacing it by ``os.path.join(base, rel)`` if that file exists.
Return a couple ``(normalized, needed_base)`` where ``normalized``
if the list of normalized file names and ``needed_base`` is
``base_dir`` if we actually needed ``base_dir``. If no paths were
changed (for example, if all paths were already absolute), then
``needed_base`` is ``None``.
"""
normalized = []
needed_base = None
for rel in rel_paths:
if os.path.isabs(rel):
normalized.append(rel)
continue
path = join_path(base_dir, rel)
if path_exists(path):
normalized.append(os.path.normpath(path))
needed_base = base_dir
else:
normalized.append(rel)
return (normalized, needed_base)
def resolve_depends(depends, include_dirs):
include_dirs = tuple(include_dirs)
resolved = []
for depend in depends:
path = resolve_depend(depend, include_dirs)
if path is not None:
resolved.append(path)
return resolved
@cached_function
def resolve_depend(depend, include_dirs):
if depend[0] == '<' and depend[-1] == '>':
return None
for dir in include_dirs:
path = join_path(dir, depend)
if path_exists(path):
return os.path.normpath(path)
return None
@cached_function
def package(filename):
dir = os.path.dirname(os.path.abspath(str(filename)))
if dir != filename and is_package_dir(dir):
return package(dir) + (os.path.basename(dir),)
else:
return ()
@cached_function
def fully_qualified_name(filename):
module = os.path.splitext(os.path.basename(filename))[0]
return '.'.join(package(filename) + (module,))
@cached_function
def parse_dependencies(source_filename):
# Actual parsing is way too slow, so we use regular expressions.
# The only catch is that we must strip comments and string
# literals ahead of time.
fh = Utils.open_source_file(source_filename, error_handling='ignore')
try:
source = fh.read()
finally:
fh.close()
distutils_info = DistutilsInfo(source)
source, literals = strip_string_literals(source)
source = source.replace('\\\n', ' ').replace('\t', ' ')
# TODO: pure mode
cimports = []
includes = []
externs = []
for m in dependency_regex.finditer(source):
cimport_from, cimport_list, extern, include = m.groups()
if cimport_from:
cimports.append(cimport_from)
elif cimport_list:
cimports.extend(x.strip() for x in cimport_list.split(","))
elif extern:
externs.append(literals[extern])
else:
includes.append(literals[include])
return cimports, includes, externs, distutils_info
class DependencyTree(object):
def __init__(self, context, quiet=False):
self.context = context
self.quiet = quiet
self._transitive_cache = {}
def parse_dependencies(self, source_filename):
if path_exists(source_filename):
source_filename = os.path.normpath(source_filename)
return parse_dependencies(source_filename)
@cached_method
def included_files(self, filename):
# This is messy because included files are textually included, resolving
# cimports (but not includes) relative to the including file.
all = set()
for include in self.parse_dependencies(filename)[1]:
include_path = join_path(os.path.dirname(filename), include)
if not path_exists(include_path):
include_path = self.context.find_include_file(include, None)
if include_path:
if '.' + os.path.sep in include_path:
include_path = os.path.normpath(include_path)
all.add(include_path)
all.update(self.included_files(include_path))
elif not self.quiet:
print("Unable to locate '%s' referenced from '%s'" % (filename, include))
return all
@cached_method
def cimports_externs_incdirs(self, filename):
# This is really ugly. Nested cimports are resolved with respect to the
# includer, but includes are resolved with respect to the includee.
cimports, includes, externs = self.parse_dependencies(filename)[:3]
cimports = set(cimports)
externs = set(externs)
incdirs = set()
for include in self.included_files(filename):
included_cimports, included_externs, included_incdirs = self.cimports_externs_incdirs(include)
cimports.update(included_cimports)
externs.update(included_externs)
incdirs.update(included_incdirs)
externs, incdir = normalize_existing(filename, externs)
if incdir:
incdirs.add(incdir)
return tuple(cimports), externs, incdirs
def cimports(self, filename):
return self.cimports_externs_incdirs(filename)[0]
def package(self, filename):
return package(filename)
def fully_qualified_name(self, filename):
return fully_qualified_name(filename)
@cached_method
def find_pxd(self, module, filename=None):
is_relative = module[0] == '.'
if is_relative and not filename:
raise NotImplementedError("New relative imports.")
if filename is not None:
module_path = module.split('.')
if is_relative:
module_path.pop(0) # just explicitly relative
package_path = list(self.package(filename))
while module_path and not module_path[0]:
try:
package_path.pop()
except IndexError:
return None # FIXME: error?
module_path.pop(0)
relative = '.'.join(package_path + module_path)
pxd = self.context.find_pxd_file(relative, None)
if pxd:
return pxd
if is_relative:
return None # FIXME: error?
return self.context.find_pxd_file(module, None)
@cached_method
def cimported_files(self, filename):
if filename[-4:] == '.pyx' and path_exists(filename[:-4] + '.pxd'):
pxd_list = [filename[:-4] + '.pxd']
else:
pxd_list = []
for module in self.cimports(filename):
if module[:7] == 'cython.' or module == 'cython':
continue
pxd_file = self.find_pxd(module, filename)
if pxd_file is not None:
pxd_list.append(pxd_file)
elif not self.quiet:
print("%s: cannot find cimported module '%s'" % (filename, module))
return tuple(pxd_list)
@cached_method
def immediate_dependencies(self, filename):
all = set([filename])
all.update(self.cimported_files(filename))
all.update(self.included_files(filename))
return all
def all_dependencies(self, filename):
return self.transitive_merge(filename, self.immediate_dependencies, set.union)
@cached_method
def timestamp(self, filename):
return os.path.getmtime(filename)
def extract_timestamp(self, filename):
return self.timestamp(filename), filename
def newest_dependency(self, filename):
return max([self.extract_timestamp(f) for f in self.all_dependencies(filename)])
def transitive_fingerprint(self, filename, extra=None):
try:
m = hashlib.md5(__version__.encode('UTF-8'))
m.update(file_hash(filename).encode('UTF-8'))
for x in sorted(self.all_dependencies(filename)):
if os.path.splitext(x)[1] not in ('.c', '.cpp', '.h'):
m.update(file_hash(x).encode('UTF-8'))
if extra is not None:
m.update(str(extra).encode('UTF-8'))
return m.hexdigest()
except IOError:
return None
def distutils_info0(self, filename):
info = self.parse_dependencies(filename)[3]
kwds = info.values
cimports, externs, incdirs = self.cimports_externs_incdirs(filename)
basedir = os.getcwd()
# Add dependencies on "cdef extern from ..." files
if externs:
externs = _make_relative(externs, basedir)
if 'depends' in kwds:
kwds['depends'] = list(set(kwds['depends']).union(externs))
else:
kwds['depends'] = list(externs)
# Add include_dirs to ensure that the C compiler will find the
# "cdef extern from ..." files
if incdirs:
include_dirs = list(kwds.get('include_dirs', []))
for inc in _make_relative(incdirs, basedir):
if inc not in include_dirs:
include_dirs.append(inc)
kwds['include_dirs'] = include_dirs
return info
def distutils_info(self, filename, aliases=None, base=None):
return (self.transitive_merge(filename, self.distutils_info0, DistutilsInfo.merge)
.subs(aliases)
.merge(base))
def transitive_merge(self, node, extract, merge):
try:
seen = self._transitive_cache[extract, merge]
except KeyError:
seen = self._transitive_cache[extract, merge] = {}
return self.transitive_merge_helper(
node, extract, merge, seen, {}, self.cimported_files)[0]
def transitive_merge_helper(self, node, extract, merge, seen, stack, outgoing):
if node in seen:
return seen[node], None
deps = extract(node)
if node in stack:
return deps, node
try:
stack[node] = len(stack)
loop = None
for next in outgoing(node):
sub_deps, sub_loop = self.transitive_merge_helper(next, extract, merge, seen, stack, outgoing)
if sub_loop is not None:
if loop is not None and stack[loop] < stack[sub_loop]:
pass
else:
loop = sub_loop
deps = merge(deps, sub_deps)
if loop == node:
loop = None
if loop is None:
seen[node] = deps
return deps, loop
finally:
del stack[node]
_dep_tree = None
def create_dependency_tree(ctx=None, quiet=False):
global _dep_tree
if _dep_tree is None:
if ctx is None:
ctx = Context(["."], CompilationOptions(default_options))
_dep_tree = DependencyTree(ctx, quiet=quiet)
return _dep_tree
# If this changes, change also docs/src/reference/compilation.rst
# which mentions this function
def default_create_extension(template, kwds):
if 'depends' in kwds:
include_dirs = kwds.get('include_dirs', []) + ["."]
depends = resolve_depends(kwds['depends'], include_dirs)
kwds['depends'] = sorted(set(depends + template.depends))
t = template.__class__
ext = t(**kwds)
metadata = dict(distutils=kwds, module_name=kwds['name'])
return (ext, metadata)
# This may be useful for advanced users?
def create_extension_list(patterns, exclude=None, ctx=None, aliases=None, quiet=False, language=None,
exclude_failures=False):
if language is not None:
print('Please put "# distutils: language=%s" in your .pyx or .pxd file(s)' % language)
if exclude is None:
exclude = []
if patterns is None:
return [], {}
elif isinstance(patterns, basestring) or not isinstance(patterns, collections.Iterable):
patterns = [patterns]
explicit_modules = set([m.name for m in patterns if isinstance(m, Extension)])
seen = set()
deps = create_dependency_tree(ctx, quiet=quiet)
to_exclude = set()
if not isinstance(exclude, list):
exclude = [exclude]
for pattern in exclude:
to_exclude.update(map(os.path.abspath, extended_iglob(pattern)))
module_list = []
module_metadata = {}
# workaround for setuptools
if 'setuptools' in sys.modules:
Extension_distutils = sys.modules['setuptools.extension']._Extension
Extension_setuptools = sys.modules['setuptools'].Extension
else:
# dummy class, in case we do not have setuptools
Extension_distutils = Extension
class Extension_setuptools(Extension): pass
# if no create_extension() function is defined, use a simple
# default function.
create_extension = ctx.options.create_extension or default_create_extension
for pattern in patterns:
if isinstance(pattern, str):
filepattern = pattern
template = Extension(pattern, []) # Fake Extension without sources
name = '*'
base = None
ext_language = language
elif isinstance(pattern, (Extension_distutils, Extension_setuptools)):
cython_sources = [s for s in pattern.sources
if os.path.splitext(s)[1] in ('.py', '.pyx')]
if cython_sources:
filepattern = cython_sources[0]
if len(cython_sources) > 1:
print("Warning: Multiple cython sources found for extension '%s': %s\n"
"See http://cython.readthedocs.io/en/latest/src/userguide/sharing_declarations.html "
"for sharing declarations among Cython files." % (pattern.name, cython_sources))
else:
# ignore non-cython modules
module_list.append(pattern)
continue
template = pattern
name = template.name
base = DistutilsInfo(exn=template)
ext_language = None # do not override whatever the Extension says
else:
msg = str("pattern is not of type str nor subclass of Extension (%s)"
" but of type %s and class %s" % (repr(Extension),
type(pattern),
pattern.__class__))
raise TypeError(msg)
for file in nonempty(sorted(extended_iglob(filepattern)), "'%s' doesn't match any files" % filepattern):
if os.path.abspath(file) in to_exclude:
continue
module_name = deps.fully_qualified_name(file)
if '*' in name:
if module_name in explicit_modules:
continue
elif name:
module_name = name
if module_name == 'cython':
raise ValueError('cython is a special module, cannot be used as a module name')
if module_name not in seen:
try:
kwds = deps.distutils_info(file, aliases, base).values
except Exception:
if exclude_failures:
continue
raise
if base is not None:
for key, value in base.values.items():
if key not in kwds:
kwds[key] = value
kwds['name'] = module_name
sources = [file] + [m for m in template.sources if m != filepattern]
if 'sources' in kwds:
# allow users to add .c files etc.
for source in kwds['sources']:
source = encode_filename_in_py2(source)
if source not in sources:
sources.append(source)
kwds['sources'] = sources
if ext_language and 'language' not in kwds:
kwds['language'] = ext_language
np_pythran = kwds.pop('np_pythran', False)
# Create the new extension
m, metadata = create_extension(template, kwds)
m.np_pythran = np_pythran or getattr(m, 'np_pythran', False)
if m.np_pythran:
update_pythran_extension(m)
module_list.append(m)
# Store metadata (this will be written as JSON in the
# generated C file but otherwise has no purpose)
module_metadata[module_name] = metadata
if file not in m.sources:
# Old setuptools unconditionally replaces .pyx with .c/.cpp
target_file = os.path.splitext(file)[0] + ('.cpp' if m.language == 'c++' else '.c')
try:
m.sources.remove(target_file)
except ValueError:
# never seen this in the wild, but probably better to warn about this unexpected case
print("Warning: Cython source file not found in sources list, adding %s" % file)
m.sources.insert(0, file)
seen.add(name)
return module_list, module_metadata
# This is the user-exposed entry point.
def cythonize(module_list, exclude=None, nthreads=0, aliases=None, quiet=False, force=False, language=None,
exclude_failures=False, **options):
"""
Compile a set of source modules into C/C++ files and return a list of distutils
Extension objects for them.
As module list, pass either a glob pattern, a list of glob patterns or a list of
Extension objects. The latter allows you to configure the extensions separately
through the normal distutils options.
When using glob patterns, you can exclude certain module names explicitly
by passing them into the 'exclude' option.
To globally enable C++ mode, you can pass language='c++'. Otherwise, this
will be determined at a per-file level based on compiler directives. This
affects only modules found based on file names. Extension instances passed
into cythonize() will not be changed.
For parallel compilation, set the 'nthreads' option to the number of
concurrent builds.
For a broad 'try to compile' mode that ignores compilation failures and
simply excludes the failed extensions, pass 'exclude_failures=True'. Note
that this only really makes sense for compiling .py files which can also
be used without compilation.
Additional compilation options can be passed as keyword arguments.
"""
if exclude is None:
exclude = []
if 'include_path' not in options:
options['include_path'] = ['.']
if 'common_utility_include_dir' in options:
if options.get('cache'):
raise NotImplementedError("common_utility_include_dir does not yet work with caching")
safe_makedirs(options['common_utility_include_dir'])
pythran_options = None
if PythranAvailable:
pythran_options = CompilationOptions(**options)
pythran_options.cplus = True
pythran_options.np_pythran = True
c_options = CompilationOptions(**options)
cpp_options = CompilationOptions(**options); cpp_options.cplus = True
ctx = c_options.create_context()
options = c_options
module_list, module_metadata = create_extension_list(
module_list,
exclude=exclude,
ctx=ctx,
quiet=quiet,
exclude_failures=exclude_failures,
language=language,
aliases=aliases)
deps = create_dependency_tree(ctx, quiet=quiet)
build_dir = getattr(options, 'build_dir', None)
def copy_to_build_dir(filepath, root=os.getcwd()):
filepath_abs = os.path.abspath(filepath)
if os.path.isabs(filepath):
filepath = filepath_abs
if filepath_abs.startswith(root):
# distutil extension depends are relative to cwd
mod_dir = join_path(build_dir,
os.path.dirname(_relpath(filepath, root)))
copy_once_if_newer(filepath_abs, mod_dir)
modules_by_cfile = collections.defaultdict(list)
to_compile = []
for m in module_list:
if build_dir:
for dep in m.depends:
copy_to_build_dir(dep)
cy_sources = [
source for source in m.sources
if os.path.splitext(source)[1] in ('.pyx', '.py')]
if len(cy_sources) == 1:
# normal "special" case: believe the Extension module name to allow user overrides
full_module_name = m.name
else:
# infer FQMN from source files
full_module_name = None
new_sources = []
for source in m.sources:
base, ext = os.path.splitext(source)
if ext in ('.pyx', '.py'):
if m.np_pythran:
c_file = base + '.cpp'
options = pythran_options
elif m.language == 'c++':
c_file = base + '.cpp'
options = cpp_options
else:
c_file = base + '.c'
options = c_options
# setup for out of place build directory if enabled
if build_dir:
c_file = os.path.join(build_dir, c_file)
dir = os.path.dirname(c_file)
safe_makedirs_once(dir)
if os.path.exists(c_file):
c_timestamp = os.path.getmtime(c_file)
else:
c_timestamp = -1
# Priority goes first to modified files, second to direct
# dependents, and finally to indirect dependents.
if c_timestamp < deps.timestamp(source):
dep_timestamp, dep = deps.timestamp(source), source
priority = 0
else:
dep_timestamp, dep = deps.newest_dependency(source)
priority = 2 - (dep in deps.immediate_dependencies(source))
if force or c_timestamp < dep_timestamp:
if not quiet and not force:
if source == dep:
print("Compiling %s because it changed." % source)
else:
print("Compiling %s because it depends on %s." % (source, dep))
if not force and options.cache:
extra = m.language
fingerprint = deps.transitive_fingerprint(source, extra)
else:
fingerprint = None
to_compile.append((
priority, source, c_file, fingerprint, quiet,
options, not exclude_failures, module_metadata.get(m.name),
full_module_name))
new_sources.append(c_file)
modules_by_cfile[c_file].append(m)
else:
new_sources.append(source)
if build_dir:
copy_to_build_dir(source)
m.sources = new_sources
if options.cache:
if not os.path.exists(options.cache):
os.makedirs(options.cache)
to_compile.sort()
# Drop "priority" component of "to_compile" entries and add a
# simple progress indicator.
N = len(to_compile)
progress_fmt = "[{0:%d}/{1}] " % len(str(N))
for i in range(N):
progress = progress_fmt.format(i+1, N)
to_compile[i] = to_compile[i][1:] + (progress,)
if N <= 1:
nthreads = 0
if nthreads:
# Requires multiprocessing (or Python >= 2.6)
try:
import multiprocessing
pool = multiprocessing.Pool(
nthreads, initializer=_init_multiprocessing_helper)
except (ImportError, OSError):
print("multiprocessing required for parallel cythonization")
nthreads = 0
else:
# This is a bit more involved than it should be, because KeyboardInterrupts
# break the multiprocessing workers when using a normal pool.map().
# See, for example:
# http://noswap.com/blog/python-multiprocessing-keyboardinterrupt
try:
result = pool.map_async(cythonize_one_helper, to_compile, chunksize=1)
pool.close()
while not result.ready():
try:
result.get(99999) # seconds
except multiprocessing.TimeoutError:
pass
except KeyboardInterrupt:
pool.terminate()
raise
pool.join()
if not nthreads:
for args in to_compile:
cythonize_one(*args)
if exclude_failures:
failed_modules = set()
for c_file, modules in modules_by_cfile.items():
if not os.path.exists(c_file):
failed_modules.update(modules)
elif os.path.getsize(c_file) < 200:
f = io_open(c_file, 'r', encoding='iso8859-1')
try:
if f.read(len('#error ')) == '#error ':
# dead compilation result
failed_modules.update(modules)
finally:
f.close()
if failed_modules:
for module in failed_modules:
module_list.remove(module)
print("Failed compilations: %s" % ', '.join(sorted([
module.name for module in failed_modules])))
if options.cache:
cleanup_cache(options.cache, getattr(options, 'cache_size', 1024 * 1024 * 100))
# cythonize() is often followed by the (non-Python-buffered)
# compiler output, flush now to avoid interleaving output.
sys.stdout.flush()
return module_list
if os.environ.get('XML_RESULTS'):
compile_result_dir = os.environ['XML_RESULTS']
def record_results(func):
def with_record(*args):
t = time.time()
success = True
try:
try:
func(*args)
except:
success = False
finally:
t = time.time() - t
module = fully_qualified_name(args[0])
name = "cythonize." + module
failures = 1 - success
if success:
failure_item = ""
else:
failure_item = "failure"
output = open(os.path.join(compile_result_dir, name + ".xml"), "w")
output.write("""
<?xml version="1.0" ?>
<testsuite name="%(name)s" errors="0" failures="%(failures)s" tests="1" time="%(t)s">
<testcase classname="%(name)s" name="cythonize">
%(failure_item)s
</testcase>
</testsuite>
""".strip() % locals())
output.close()
return with_record
else:
def record_results(func):
return func
# TODO: Share context? Issue: pyx processing leaks into pxd module
@record_results
def cythonize_one(pyx_file, c_file, fingerprint, quiet, options=None,
raise_on_failure=True, embedded_metadata=None, full_module_name=None,
progress=""):
from ..Compiler.Main import compile_single, default_options
from ..Compiler.Errors import CompileError, PyrexError
if fingerprint:
if not os.path.exists(options.cache):
safe_makedirs(options.cache)
# Cython-generated c files are highly compressible.
# (E.g. a compression ratio of about 10 for Sage).
fingerprint_file = join_path(
options.cache, "%s-%s%s" % (os.path.basename(c_file), fingerprint, gzip_ext))
if os.path.exists(fingerprint_file):
if not quiet:
print("%sFound compiled %s in cache" % (progress, pyx_file))
os.utime(fingerprint_file, None)
g = gzip_open(fingerprint_file, 'rb')
try:
f = open(c_file, 'wb')
try:
shutil.copyfileobj(g, f)
finally:
f.close()
finally:
g.close()
return
if not quiet:
print("%sCythonizing %s" % (progress, pyx_file))
if options is None:
options = CompilationOptions(default_options)
options.output_file = c_file
options.embedded_metadata = embedded_metadata
any_failures = 0
try:
result = compile_single(pyx_file, options, full_module_name=full_module_name)
if result.num_errors > 0:
any_failures = 1
except (EnvironmentError, PyrexError) as e:
sys.stderr.write('%s\n' % e)
any_failures = 1
# XXX
import traceback
traceback.print_exc()
except Exception:
if raise_on_failure:
raise
import traceback
traceback.print_exc()
any_failures = 1
if any_failures:
if raise_on_failure:
raise CompileError(None, pyx_file)
elif os.path.exists(c_file):
os.remove(c_file)
elif fingerprint:
f = open(c_file, 'rb')
try:
g = gzip_open(fingerprint_file, 'wb')
try:
shutil.copyfileobj(f, g)
finally:
g.close()
finally:
f.close()
def cythonize_one_helper(m):
import traceback
try:
return cythonize_one(*m)
except Exception:
traceback.print_exc()
raise
def _init_multiprocessing_helper():
# KeyboardInterrupt kills workers, so don't let them get it
import signal
signal.signal(signal.SIGINT, signal.SIG_IGN)
def cleanup_cache(cache, target_size, ratio=.85):
try:
p = subprocess.Popen(['du', '-s', '-k', os.path.abspath(cache)], stdout=subprocess.PIPE)
res = p.wait()
if res == 0:
total_size = 1024 * int(p.stdout.read().strip().split()[0])
if total_size < target_size:
return
except (OSError, ValueError):
pass
total_size = 0
all = []
for file in os.listdir(cache):
path = join_path(cache, file)
s = os.stat(path)
total_size += s.st_size
all.append((s.st_atime, s.st_size, path))
if total_size > target_size:
for time, size, file in reversed(sorted(all)):
os.unlink(file)
total_size -= size
if total_size < target_size * ratio:
break
| mit |
eapearson/kbase-ui | src/plugins/narrativemanager/modules/views/NewNarrative.js | 5501 | define([
'preact',
'htm',
'../reactComponents/OpenNarrative',
'../narrativeManager',
'../reactComponents/Loading',
'../reactComponents/ErrorAlert',
'bootstrap'
], (
preact,
htm,
OpenNarrative,
NarrativeManagerService,
Loading,
ErrorAlert
) => {
const { h, Component } = preact;
const html = htm.bind(h);
// app: params.app,
// method: params.method,
// copydata: params.copydata,
// appparam: params.appparam,
// markdown: params.markdown
class NewNarrativeMain extends Component {
constructor(props) {
super(props);
this.state = {
status: null,
data: null,
error: null
};
}
componentDidMount() {
this.props.runtime.send('ui', 'setTitle', 'Creating and Opening New Narrative...');
this.setState({
status: 'creating'
});
this.createNewNarrative()
.then((result) => {
this.setState({
status: 'success',
data: result
});
})
.catch((ex) => {
this.setState({
status: 'error',
error: {
message: ex.message
}
});
});
}
makeNarrativePath(workspaceID) {
return `https://${window.location.host}/narrative/${workspaceID}`;
}
createNewNarrative() {
return Promise.resolve()
.then(() => {
if (this.props.params.app && this.props.params.method) {
throw new Error('Must provide no more than one of the app or method params');
}
let appData, tmp, i;
const newNarrativeParams = {};
if (this.props.params.copydata) {
newNarrativeParams.importData = this.props.params.copydata.split(';');
}
// Note that these are exclusive cell creation options.
if (this.props.params.app || this.props.params.method) {
newNarrativeParams.method = this.props.params.app || this.props.params.method;
if (this.props.params.appparam) {
/* TODO: convert to forEach */
tmp = this.props.params.appparam.split(';');
appData = [];
for (i = 0; i < tmp.length; i += 1) {
appData[i] = tmp[i].split(',');
if (appData[i].length !== 3) {
throw new Error(
'Illegal app parameter set, expected 3 parameters separated by commas: ' + tmp[i]
);
}
/* TODO: use standard lib for math and string->number conversions) */
appData[i][0] = parseInt(appData[i][0], 10);
if (isNaN(appData[i][0]) || appData[i][0] < 1) {
throw new Error(
'Illegal app parameter set, first item in set must be an integer > 0: ' + tmp[i]
);
}
}
newNarrativeParams.appData = appData;
}
} else if (this.props.params.markdown) {
newNarrativeParams.markdown = this.props.params.markdown;
}
const narrativeManager = new NarrativeManagerService({ runtime: this.props.runtime });
return narrativeManager.createTempNarrative(newNarrativeParams)
.then((info) => {
return {
url: this.makeNarrativePath(info.narrativeInfo.wsid)
};
});
});
}
render() {
switch (this.state.status) {
case 'creating':
return html`
<${Loading} message="Creating and opening a new narrative..." detectSlow=${true} />
`;
case 'error':
return html`
<${ErrorAlert} title="Error">
<p>
Sorry, there was an error creating or opening a new narrative:
</p>
<p>
${this.state.error.message}
</p>
<//>
`;
case 'success':
var props = {
runtime: this.props.runtime,
url: this.state.data.url
};
return html`<${OpenNarrative} ...${props} />`;
default:
return html`
<${ErrorAlert}>
Unexpected status: ${this.state.status}
<//>`;
}
}
}
return NewNarrativeMain;
});
| mit |
jotaelesalinas/php-rwgen | src/Writers/ConsoleVarDump.php | 246 | <?php
namespace JLSalinas\RWGen\Writers;
use JLSalinas\RWGen\Writer;
class ConsoleVarDump extends Writer
{
protected function outputGenerator()
{
while (($data = yield) !== null) {
var_dump($data);
}
}
}
| mit |
stagedhomes/iahsp-2017 | assets/js/angular/controllers.js | 2768 | (function() {
angular.module("iahsp2017")
.controller("ctrlSendEmail", ["$scope", "$http", "factorySendEmail", "vcRecaptchaService", function($scope, $http, factorySendEmail, vcRecaptchaService){
$scope.contactDetails = factorySendEmail.contact;
var btnSubmit = document.getElementById("submit");
/* ==================================================================
Form Functions
==================================================================*/
$scope.fnClearForm = function() {
$scope.contactDetails = {
"name": null,
"email": null,
"subject": null,
"message": null
}; // contact
btnSubmit.innerHTML = "Send Message";
btnSubmit.classList.remove("btn-success");
btnSubmit.classList.remove("btn-danger");
btnSubmit.classList.add("btn-primary");
}; // clearForm()
$scope.fnSendForm = function() {
if(vcRecaptchaService.getResponse() === "") { //if string is empty
$("#submit").text("reCaptcha Problem. Please fix.");
} else {
// add response from reCAPTCHA
$scope.contactDetails.googleResponse = vcRecaptchaService.getResponse();
// Put up some sort of loading sign.
btnSubmit.innerHTML = "Please Wait...";
btnSubmit.classList.remove("btn-primary");
btnSubmit.classList.add("btn-info");
btnSubmit.disabled = true;
// send POST data
$http.post("https://www.leemtek.com/forms/stagedhomes/iahsp2017", $scope.contactDetails)
.then(function successCallback(response) {
if(response.data.sent === "yes") {
// update submit button to indicate success
factorySendEmail.fnSendSuccessDOM();
} else {
// update submit button to indicate an error
factorySendEmail.fnSendErrorDOM();
} // if
}, function errorCallback(response) {
// update submit button to indicate an error
factorySendEmail.fnSendErrorDOM();
}) // .then
; // $http.post
} // if
}; // fnSendForm()
}]) // .controller("ctrlSendEmail")
; // angular.module("getredbox")
})(); // function()
| mit |
pinax/django-mailer | src/mailer/management/commands/purge_mail_log.py | 929 | import logging
from django.core.management.base import BaseCommand
from mailer.models import MessageLog, RESULT_SUCCESS, RESULT_FAILURE
RESULT_CODES = {
'success': [RESULT_SUCCESS],
'failure': [RESULT_FAILURE],
'all': [RESULT_SUCCESS, RESULT_FAILURE]
}
logger = logging.getLogger(__name__)
class Command(BaseCommand):
help = "Delete mailer log"
def add_arguments(self, parser):
parser.add_argument('days', type=int)
parser.add_argument('-r', '--result', choices=RESULT_CODES.keys(),
help='Delete logs of messages with the given result code(s) '
'(default: success)')
def handle(self, *args, **options):
days = options['days']
result_codes = RESULT_CODES.get(options['result'])
count = MessageLog.objects.purge_old_entries(days, result_codes)
logger.info("%s log entries deleted " % count)
| mit |
HonzaMikula/masivnipostele | vendor/passwordlib/passwordlib/test/Unit/Password/Implementation/JoomlaTest.php | 5275 | <?php
use PasswordLib\Core\Strength\Medium as MediumStrength;
use PasswordLibTest\Mocks\Random\Generator as MockGenerator;
use PasswordLib\Password\Implementation\Joomla;
require_once 'Password_TestCase.php';
class Unit_Hash_Implementation_JoomlaTest extends Unit_Password_Implementation_Password_TestCase {
protected $class = 'PasswordLib\Password\Implementation\Joomla';
public static function provideTestDetect() {
return array(
array('$P$', false),
array('$S$', false),
array('$S$ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz./ABCDEFGHIJKLMNOPQRSTUVWXYZ01234', false),
array('abcabcabcabcabcfabcabcabcabcabcf:abcdefghijklmnopabcdefghijklmnop', true),
array('abcabcabcabcabcfabcabcabcabcabcf:abcdefghijk mnopabcdefghijklmnop', false),
);
}
public static function provideTestCreate() {
return array(
array('foo', 'f29e73e26c48d3963a8574f176b1be84:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'),
array('bar', 'f04ba934aba654a2e1a3221744bc76ad:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'),
array('baz', '0367f792547d80b71027b9e07994aa0f:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'),
);
}
public static function provideTestVerifyFail() {
return array(
array('foo', 'f29e73e26c48d3963a8574f176b1be84:aAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'),
array('bar', 'f04bA934aba654a2e1a3221744bc76ad:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'),
array('biz', '0367f792547d80b71027b9e07994aa0f:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'),
);
}
public static function provideTestVerifyFailException() {
return array(
array('foo', '$S$A........u9PH9ZMowV1f3sR2VX.YMyU5IvKjn8XsQOo6AIIJDbKnT3bdYztQdz2R1/P7YLxxsaAoK2aM.DlN8BoZV3.Fa0'),
array('bar', 'abcabcabcabcabcfabcabcabcabcabcf:abcdefghijk mnopabcdefghijklmnop'),
);
}
/**
* @covers PasswordLib\Password\Implementation\Joomla
* @dataProvider provideTestDetect
*/
public function testDetect($from, $expect) {
$this->assertEquals($expect, Joomla::detect($from));
}
/**
* @covers PasswordLib\Password\Implementation\Joomla
*/
public function testLoadFromHash() {
$test = Joomla::loadFromHash('f29e73e26c48d3963a8574f176b1be84:aAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA');
$this->assertTrue($test instanceof Joomla);
}
/**
* @covers PasswordLib\Password\Implementation\Joomla
* @expectedException InvalidArgumentException
*/
public function testLoadFromHashFail() {
Joomla::loadFromHash('foo');
}
/**
* @covers PasswordLib\Password\Implementation\Joomla
*/
public function testGetPrefix() {
$this->assertFalse(Joomla::getPrefix());
}
/**
* @covers PasswordLib\Password\Implementation\Joomla
*/
public function testConstruct() {
$hash = new Joomla();
$this->assertTrue($hash instanceof Joomla);
}
/**
* @covers PasswordLib\Password\Implementation\Joomla
*/
public function testConstructArgs() {
$iterations = 10;
$gen = $this->getRandomGenerator(function($size) {});
$apr = new Joomla($gen);
$this->assertTrue($apr instanceof Joomla);
}
/**
* @covers PasswordLib\Password\Implementation\Joomla
*/
public function testCreateAndVerify() {
$hash = new Joomla();
$test = $hash->create('Foobar');
$this->assertTrue($hash->verify('Foobar', $test));
}
/**
* @covers PasswordLib\Password\Implementation\Joomla
* @dataProvider provideTestCreate
*/
public function testCreate($pass, $expect) {
$apr = $this->getJoomlaMockInstance();
$this->assertEquals($expect, $apr->create($pass));
}
/**
* @covers PasswordLib\Password\Implementation\Joomla
* @dataProvider provideTestCreate
*/
public function testVerify($pass, $expect) {
$apr = $this->getJoomlaMockInstance();
$this->assertTrue($apr->verify($pass, $expect));
}
/**
* @covers PasswordLib\Password\Implementation\Joomla
* @dataProvider provideTestVerifyFail
*/
public function testVerifyFail($pass, $expect) {
$apr = $this->getJoomlaMockInstance();
$this->assertFalse($apr->verify($pass, $expect));
}
/**
* @covers PasswordLib\Password\Implementation\Joomla
* @dataProvider provideTestVerifyFailException
* @expectedException InvalidArgumentException
*/
public function testVerifyFailException($pass, $expect) {
$apr = $this->getJoomlaMockInstance();
$apr->verify($pass, $expect);
}
protected function getJoomlaMockInstance() {
$gen = $this->getRandomGenerator(function($size) {
return str_repeat('A', $size);
});
return new Joomla($gen);
}
protected function getJoomlaInstance($evaluate, $hmac, $generate) {
$generator = $this->getRandomGenerator($generate);
return new Joomla($generator);
}
protected function getRandomGenerator($generate) {
return new MockGenerator(array(
'generateString' => $generate
));
}
}
| mit |
westoncolemanl/tabbr-web | src/containers/Asians/TabControls/PreliminaryRounds/CreateRooms/5_AdjudicatorAllocationSetting/MinimumRelevantAdjudicatorPointChartControls/index.js | 1610 | import React, { PureComponent } from 'react'
import Card, {
CardContent
} from 'material-ui/Card'
import { NumberInput } from 'components'
export default class extends PureComponent {
constructor () {
super()
this.state = {
adjudicatorPoint: '',
error: false
}
}
componentWillMount () {
const {
minimumRelevantAdjudicatorPoint
} = this.props
if (minimumRelevantAdjudicatorPoint !== 0) {
this.setState({ adjudicatorPoint: minimumRelevantAdjudicatorPoint })
}
}
render () {
const {
onChangeMinimumRelevantAdjudicatorPoint
} = this.props
const {
adjudicatorPoint,
error
} = this.state
const min = 0
const max = 10
return (
<Card>
<CardContent>
<NumberInput
label={'Minimum relevant adjudicator point'}
value={adjudicatorPoint}
onChange={(e) => this.setState({ adjudicatorPoint: e })}
helperText={error || `Relevant score range: ${min} - ${max}`}
error={Boolean(error)}
onBlur={() => {
if (Number(adjudicatorPoint) < min) {
this.setState({ error: `Must be greater than or equal to ${min}` })
} else if (Number(adjudicatorPoint) > max) {
this.setState({ error: `Must be less than or equal to ${max}` })
} else {
this.setState({ error: false })
onChangeMinimumRelevantAdjudicatorPoint(adjudicatorPoint)
}
}}
/>
</CardContent>
</Card>
)
}
}
| mit |
mind0n/hive | Cache/Libs/net46/ndp/fx/src/commonui/System/Drawing/Advanced/StringAlignment.cs | 1996 | //------------------------------------------------------------------------------
// <copyright file="StringAlignment.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Drawing {
using System.Drawing;
using System;
/**
* used for both vertical and horizontal alignment.
*/
/// <include file='doc\StringAlignment.uex' path='docs/doc[@for="StringAlignment"]/*' />
/// <devdoc>
/// Specifies the alignment of a text string
/// relative to its layout rectangle.
/// </devdoc>
public enum StringAlignment
{
// left or top in English
/// <include file='doc\StringAlignment.uex' path='docs/doc[@for="StringAlignment.Near"]/*' />
/// <devdoc>
/// Specifies the text be aligned near the
/// layout. In a left-to-right layout, the near position is left. In a right-to-left
/// layout, the near position is right.
/// </devdoc>
Near = 0,
/// <include file='doc\StringAlignment.uex' path='docs/doc[@for="StringAlignment.Center"]/*' />
/// <devdoc>
/// Specifies that text is aligned in the
/// center of the layout rectangle.
/// </devdoc>
Center = 1,
// NO ALTERNATE SPELLINGS!
// Centre = 1,
// right or bottom in English
/// <include file='doc\StringAlignment.uex' path='docs/doc[@for="StringAlignment.Far"]/*' />
/// <devdoc>
/// Specifies that text is aligned far from the
/// origin position of the layout rectangle. In a left-to-right layout, the far
/// position is right. In a right-to-left layout, the far position is left.
/// </devdoc>
Far = 2
}
}
| mit |
constantcontact/open-performance-platform | opp-service/src/main/java/com/opp/dto/ux/CustomUserTimingsAgg.java | 759 | package com.opp.dto.ux;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by ctobe on 6/13/17.
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public class CustomUserTimingsAgg extends WptTrendMetric.UserTimingMetric {
private long timePeriod;
public long getTimePeriod() {
return timePeriod;
}
public void setTimePeriod(long timePeriod) {
this.timePeriod = timePeriod;
}
public CustomUserTimingsAgg(Integer min, Integer max, Integer median, Double average, String name, long timePeriod) {
super(min, max, median, average, name);
this.timePeriod = timePeriod;
}
}
| mit |
FubarDevelopment/WebDavServer | test/FubarDev.WebDavServer.Tests/Support/ServiceBuilders/ILockServices.cs | 336 | // <copyright file="ILockServices.cs" company="Fubar Development Junker">
// Copyright (c) Fubar Development Junker. All rights reserved.
// </copyright>
using System;
namespace FubarDev.WebDavServer.Tests.Support.ServiceBuilders
{
public interface ILockServices
{
IServiceProvider ServiceProvider { get; }
}
}
| mit |
fgreinacher/corefx | src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.Ssl.cs | 12683 | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates;
using Microsoft.Win32.SafeHandles;
internal static partial class Interop
{
internal static partial class Ssl
{
internal const int SSL_TLSEXT_ERR_OK = 0;
internal const int OPENSSL_NPN_NEGOTIATED = 1;
internal const int SSL_TLSEXT_ERR_NOACK = 3;
internal delegate int SslCtxSetVerifyCallback(int preverify_ok, IntPtr x509_ctx);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EnsureLibSslInitialized")]
internal static extern void EnsureLibSslInitialized();
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslV2_3Method")]
internal static extern IntPtr SslV2_3Method();
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslCreate")]
internal static extern SafeSslHandle SslCreate(SafeSslContextHandle ctx);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetError")]
internal static extern SslErrorCode SslGetError(SafeSslHandle ssl, int ret);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetError")]
internal static extern SslErrorCode SslGetError(IntPtr ssl, int ret);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslSetQuietShutdown")]
internal static extern void SslSetQuietShutdown(SafeSslHandle ssl, int mode);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslDestroy")]
internal static extern void SslDestroy(IntPtr ssl);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslSetConnectState")]
internal static extern void SslSetConnectState(SafeSslHandle ssl);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslSetAcceptState")]
internal static extern void SslSetAcceptState(SafeSslHandle ssl);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetVersion")]
private static extern IntPtr SslGetVersion(SafeSslHandle ssl);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGet0AlpnSelected")]
internal static extern void SslGetAlpnSelected(SafeSslHandle ssl, out IntPtr protocol, out int len);
internal static byte[] SslGetAlpnSelected(SafeSslHandle ssl)
{
IntPtr protocol;
int len;
SslGetAlpnSelected(ssl, out protocol, out len);
if (len == 0)
return null;
byte[] result = new byte[len];
Marshal.Copy(protocol, result, 0, len);
return result;
}
internal static string GetProtocolVersion(SafeSslHandle ssl)
{
return Marshal.PtrToStringAnsi(SslGetVersion(ssl));
}
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_GetSslConnectionInfo")]
internal static extern bool GetSslConnectionInfo(
SafeSslHandle ssl,
out int dataCipherAlg,
out int keyExchangeAlg,
out int dataHashAlg,
out int dataKeySize,
out int hashKeySize);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslWrite")]
internal static extern unsafe int SslWrite(SafeSslHandle ssl, byte* buf, int num);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslRead")]
internal static extern unsafe int SslRead(SafeSslHandle ssl, byte* buf, int num);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_IsSslRenegotiatePending")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool IsSslRenegotiatePending(SafeSslHandle ssl);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslShutdown")]
internal static extern int SslShutdown(IntPtr ssl);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslShutdown")]
internal static extern int SslShutdown(SafeSslHandle ssl);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslSetBio")]
internal static extern void SslSetBio(SafeSslHandle ssl, SafeBioHandle rbio, SafeBioHandle wbio);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslDoHandshake")]
internal static extern int SslDoHandshake(SafeSslHandle ssl);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_IsSslStateOK")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool IsSslStateOK(SafeSslHandle ssl);
// NOTE: this is just an (unsafe) overload to the BioWrite method from Interop.Bio.cs.
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_BioWrite")]
internal static extern unsafe int BioWrite(SafeBioHandle b, byte* data, int len);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetPeerCertificate")]
internal static extern SafeX509Handle SslGetPeerCertificate(SafeSslHandle ssl);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetPeerCertChain")]
internal static extern SafeSharedX509StackHandle SslGetPeerCertChain(SafeSslHandle ssl);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetPeerFinished")]
internal static extern int SslGetPeerFinished(SafeSslHandle ssl, IntPtr buf, int count);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetFinished")]
internal static extern int SslGetFinished(SafeSslHandle ssl, IntPtr buf, int count);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslSessionReused")]
internal static extern bool SslSessionReused(SafeSslHandle ssl);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslAddExtraChainCert")]
internal static extern bool SslAddExtraChainCert(SafeSslHandle ssl, SafeX509Handle x509);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetClientCAList")]
private static extern SafeSharedX509NameStackHandle SslGetClientCAList_private(SafeSslHandle ssl);
internal static SafeSharedX509NameStackHandle SslGetClientCAList(SafeSslHandle ssl)
{
Crypto.CheckValidOpenSslHandle(ssl);
SafeSharedX509NameStackHandle handle = SslGetClientCAList_private(ssl);
if (!handle.IsInvalid)
{
handle.SetParent(ssl);
}
return handle;
}
internal static bool AddExtraChainCertificates(SafeSslHandle sslContext, X509Chain chain)
{
Debug.Assert(chain != null, "X509Chain should not be null");
Debug.Assert(chain.ChainElements.Count > 0, "chain.Build should have already been called");
for (int i = chain.ChainElements.Count - 2; i > 0; i--)
{
SafeX509Handle dupCertHandle = Crypto.X509UpRef(chain.ChainElements[i].Certificate.Handle);
Crypto.CheckValidOpenSslHandle(dupCertHandle);
if (!SslAddExtraChainCert(sslContext, dupCertHandle))
{
dupCertHandle.Dispose(); // we still own the safe handle; clean it up
return false;
}
dupCertHandle.SetHandleAsInvalid(); // ownership has been transferred to sslHandle; do not free via this safe handle
}
return true;
}
internal static class SslMethods
{
internal static readonly IntPtr SSLv23_method = SslV2_3Method();
}
internal enum SslErrorCode
{
SSL_ERROR_NONE = 0,
SSL_ERROR_SSL = 1,
SSL_ERROR_WANT_READ = 2,
SSL_ERROR_WANT_WRITE = 3,
SSL_ERROR_SYSCALL = 5,
SSL_ERROR_ZERO_RETURN = 6,
// NOTE: this SslErrorCode value doesn't exist in OpenSSL, but
// we use it to distinguish when a renegotiation is pending.
// Choosing an arbitrarily large value that shouldn't conflict
// with any actual OpenSSL error codes
SSL_ERROR_RENEGOTIATE = 29304
}
}
}
namespace Microsoft.Win32.SafeHandles
{
internal sealed class SafeSslHandle : SafeHandle
{
private SafeBioHandle _readBio;
private SafeBioHandle _writeBio;
private bool _isServer;
private bool _handshakeCompleted = false;
private GCHandle _alpnHandle;
public GCHandle AlpnHandle { set => _alpnHandle = value; }
public bool IsServer
{
get { return _isServer; }
}
public SafeBioHandle InputBio
{
get
{
return _readBio;
}
}
public SafeBioHandle OutputBio
{
get
{
return _writeBio;
}
}
internal void MarkHandshakeCompleted()
{
_handshakeCompleted = true;
}
public static SafeSslHandle Create(SafeSslContextHandle context, bool isServer)
{
SafeBioHandle readBio = Interop.Crypto.CreateMemoryBio();
SafeBioHandle writeBio = Interop.Crypto.CreateMemoryBio();
SafeSslHandle handle = Interop.Ssl.SslCreate(context);
if (readBio.IsInvalid || writeBio.IsInvalid || handle.IsInvalid)
{
readBio.Dispose();
writeBio.Dispose();
handle.Dispose(); // will make IsInvalid==true if it's not already
return handle;
}
handle._isServer = isServer;
// SslSetBio will transfer ownership of the BIO handles to the SSL context
try
{
readBio.TransferOwnershipToParent(handle);
writeBio.TransferOwnershipToParent(handle);
handle._readBio = readBio;
handle._writeBio = writeBio;
Interop.Ssl.SslSetBio(handle, readBio, writeBio);
}
catch (Exception exc)
{
// The only way this should be able to happen without thread aborts is if we hit OOMs while
// manipulating the safe handles, in which case we may leak the bio handles.
Debug.Fail("Unexpected exception while transferring SafeBioHandle ownership to SafeSslHandle", exc.ToString());
throw;
}
if (isServer)
{
Interop.Ssl.SslSetAcceptState(handle);
}
else
{
Interop.Ssl.SslSetConnectState(handle);
}
return handle;
}
public override bool IsInvalid
{
get { return handle == IntPtr.Zero; }
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_readBio?.Dispose();
_writeBio?.Dispose();
}
if (_alpnHandle.IsAllocated)
{
_alpnHandle.Free();
}
base.Dispose(disposing);
}
protected override bool ReleaseHandle()
{
if (_handshakeCompleted)
{
Disconnect();
}
IntPtr h = handle;
SetHandle(IntPtr.Zero);
Interop.Ssl.SslDestroy(h); // will free the handles underlying _readBio and _writeBio
return true;
}
private void Disconnect()
{
Debug.Assert(!IsInvalid, "Expected a valid context in Disconnect");
int retVal = Interop.Ssl.SslShutdown(handle);
// Here, we are ignoring checking for <0 return values from Ssl_Shutdown,
// since the underlying memory bio is already disposed, we are not
// interested in reading or writing to it.
if (retVal == 0)
{
// Do a bi-directional shutdown.
retVal = Interop.Ssl.SslShutdown(handle);
}
}
private SafeSslHandle() : base(IntPtr.Zero, true)
{
}
internal SafeSslHandle(IntPtr validSslPointer, bool ownsHandle) : base(IntPtr.Zero, ownsHandle)
{
handle = validSslPointer;
}
}
}
| mit |
Driftrock/chronos | spec/lib/chronos/worker_spec.rb | 4801 | require 'spec_helper'
require './lib/chronos/worker'
require './lib/chronos/errors'
module Chronos
RSpec.describe Worker do
let(:job_type) { 'test_job_type' }
let(:scope) { 'this_is_a_scope' }
before do
stub_const 'DummyWorker', Class.new
DummyWorker.class_eval do
include Chronos::Worker
end
stub_const 'Chronos::Job', Class.new
Chronos::Job.class_eval do
class << self
def not_errored; self; end
def retrieve_last(*args); end
end
end
end
subject { DummyWorker.new }
let(:chronos_job) do
double(:chronos_job, running!: true)
end
context 'with a job' do
before do
allow(subject).to receive(:current_chronos_job).and_return(chronos_job)
end
describe '#chronos_increment_percentage!' do
let(:percent) { 10 }
it 'should update the percentage on the job' do
expect(chronos_job).to receive(:increment_percentage!).with(percent)
subject.chronos_increment_percentage!(percent)
end
end
describe '#chronos_job_data!' do
let(:data) { 'some_data' }
it 'should update the data on the job' do
expect(chronos_job).to receive(:update_attributes).with(
data: data
)
subject.chronos_job_data!(data)
end
end
describe '#chronos_error!' do
let(:error) { 'blah' }
it 'should update the error on the job' do
expect(chronos_job).to receive(:error!).with(error)
subject.chronos_error!(error)
end
end
describe '#chronos_finished!' do
it 'should mark the job as finished' do
expect(chronos_job).to receive(:finished!)
subject.chronos_finished!
end
end
describe '#for_chronos' do
before do
allow(subject).to receive(:chronos_job_data!)
allow(subject).to receive(:chronos_finished!)
end
let(:data) { { test: 'thing' } }
it 'should call finished' do
expect(subject).to receive(:chronos_finished!)
subject.for_chronos {}
end
it 'should set the data with the result of the block' do
allow(subject).to receive(:chronos_job_data!).with(data)
subject.for_chronos { data }
end
context 'on error' do
let(:message) { 'rargh' }
let(:error) { StandardError.new(message) }
let(:block) { proc { raise error } }
before do
allow(subject).to receive(:chronos_error!)
end
it 'should call the on_chronos_error method' do
expect(subject).to receive(:on_chronos_error).with(error)
subject.for_chronos(&block) rescue nil
end
it 'should call the error the job' do
expect(subject).to receive(:chronos_error!).with(message)
subject.for_chronos(&block) rescue nil
end
it 'should raise the error' do
expect do
subject.for_chronos(&block)
end.to raise_error
end
end
end
end
describe '#current_chronos_job' do
before do
allow(Chronos::Job).to receive(:retrieve_last).and_return(chronos_job)
end
context 'when not found' do
before do
allow(Chronos::Job).to receive(:retrieve_last).and_return(nil)
end
it 'should raise a job not found error' do
expect do
subject.current_chronos_job
end.to raise_error(Errors::ChronosJobNotFoundError)
end
end
context 'with a job type' do
before do
DummyWorker.chronos_job_type(job_type)
end
it 'should send the correct job type' do
expect(Chronos::Job).to receive(:retrieve_last).with(
job_type, job_key: anything,
scope_context: anything, scope: anything
).and_return(chronos_job)
subject.current_chronos_job
end
end
context 'with a scope' do
before do
DummyWorker.chronos_scope(scope)
end
it 'should try and get the job for that scope' do
expect(Chronos::Job).to receive(:retrieve_last).with(
anything, job_key: anything,
scope_context: anything, scope: scope
).and_return(chronos_job)
subject.current_chronos_job
end
it 'should pass self as the scope context' do
expect(Chronos::Job).to receive(:retrieve_last).with(
anything, job_key: anything,
scope_context: subject, scope: anything
).and_return(chronos_job)
subject.current_chronos_job
end
end
end
end
end
| mit |
xaxa89/mitmproxy | mitmproxy/ctx.py | 150 | import mitmproxy.master # noqa
import mitmproxy.log # noqa
master = None # type: "mitmproxy.master.Master"
log = None # type: "mitmproxy.log.Log"
| mit |
aloisdeniel/Microcharts | Sources/Microcharts.Samples.iOS/ViewController.cs | 3154 | using System;
using UIKit;
using Microcharts.iOS;
using System.Linq;
namespace Microcharts.Samples.iOS
{
public partial class ViewController : UIViewController
{
protected ViewController(IntPtr handle) : base(handle)
{
// Note: this .ctor should not contain any initialization logic.
}
private UIView CreateChartCard(Chart chart)
{
var view = new ChartView()
{
AutoresizingMask = UIViewAutoresizing.FlexibleWidth,
Chart = chart,
};
view.HeightAnchor.ConstraintEqualTo(160).Active = true;
view.Layer.CornerRadius = 5;
stackView.AddArrangedSubview(view);
return view;
}
public override void ViewDidAppear(bool animated)
{
base.ViewDidAppear(animated);
//this.PresentViewController(new QuickstartViewController(), true, () => { });
}
private void Reload(object sender, EventArgs e)
{
while (this.stackView.Subviews.Length > 1)
{
this.stackView.RemoveArrangedSubview(this.stackView.Subviews.Last());
this.stackView.Subviews.Last().RemoveFromSuperview();
}
var hasPositiveValues = this.hasPositiveValuesSwitch.On;
var hasNegativeValues = this.hasNegativeValuesSwitch.On;
var hasSingleColor = this.hasSignleColorSwitch.On;
var hasLabels = this.hasLabelsSwitch.On;
var hasValueLabels = this.hasValueLabelsSwitch.On;
var pointSize = pointSizeSlider.Value;
var areaAlpha = (byte)(int)(255 * this.areaAlphaSlider.Value);
var lineMode = this.hasSplinesSwitch.On ? LineMode.Spline : LineMode.Straight;
var entries = Data.CreateEntries((int)this.valuesSlider.Value, hasPositiveValues, hasNegativeValues, hasLabels, hasValueLabels, hasSingleColor);
CreateChartCard(new BarChart { Entries = entries, BarAreaAlpha = areaAlpha });
CreateChartCard(new PointChart { Entries = entries, PointAreaAlpha = areaAlpha, PointSize = pointSize });
CreateChartCard(new LineChart { Entries = entries, LineAreaAlpha = areaAlpha, PointMode = PointMode.Square, PointSize = pointSize, LineSize = lineSizeSlider.Value, LineMode = lineMode });
CreateChartCard(new RadialGaugeChart { Entries = entries, LineAreaAlpha = areaAlpha, MaxValue = entries.Max(x => Math.Abs(x.Value) + 100) });
CreateChartCard(new RadarChart { Entries = entries, MaxValue = entries.Max(x => Math.Abs(x.Value) + 100) });
if (!hasSingleColor)
{
CreateChartCard(new DonutChart { Entries = entries, HoleRadius = holeSlider.Value });
}
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
this.Reload(null, null);
// Listeners
this.hasPositiveValuesSwitch.ValueChanged += Reload;
this.hasNegativeValuesSwitch.ValueChanged += Reload;
this.hasSignleColorSwitch.ValueChanged += Reload;
this.hasLabelsSwitch.ValueChanged += Reload;
this.hasValueLabelsSwitch.ValueChanged += Reload;
this.valuesSlider.ValueChanged += Reload;
this.areaAlphaSlider.ValueChanged += Reload;
this.holeSlider.ValueChanged += Reload;
this.lineSizeSlider.ValueChanged += Reload;
this.pointSizeSlider.ValueChanged += Reload;
this.hasSplinesSwitch.ValueChanged += Reload;
this.View.BackgroundColor = UIColor.FromWhiteAlpha(0.95f, 1);
}
}
}
| mit |
jbaldwin/project_euler | lib/permutations.php | 418 | <?php
function permutate($str) {
$permutations = array();
_permutate("", $str, $permutations);
return $permutations;
}
function _permutate($prefix, $str, &$permutations) {
$len = strlen($str);
if($len == 0) {
array_push($permutations, $prefix);
} else {
for($i = 0; $i < $len; $i++) {
_permutate($prefix . $str[$i],
substr($str, 0, $i) . substr($str, $i + 1, $len),
$permutations);
}
}
}
?>
| mit |
hoovercj/vscode | extensions/css-language-features/client/src/cssClient.ts | 6766 | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { commands, CompletionItem, CompletionItemKind, ExtensionContext, languages, Position, Range, SnippetString, TextEdit, window, TextDocument, CompletionContext, CancellationToken, ProviderResult, CompletionList } from 'vscode';
import { Disposable, LanguageClientOptions, ProvideCompletionItemsSignature, NotificationType, CommonLanguageClient } from 'vscode-languageclient';
import * as nls from 'vscode-nls';
import { getCustomDataSource } from './customData';
import { RequestService, serveFileSystemRequests } from './requests';
namespace CustomDataChangedNotification {
export const type: NotificationType<string[]> = new NotificationType('css/customDataChanged');
}
const localize = nls.loadMessageBundle();
export type LanguageClientConstructor = (name: string, description: string, clientOptions: LanguageClientOptions) => CommonLanguageClient;
export interface Runtime {
TextDecoder: { new(encoding?: string): { decode(buffer: ArrayBuffer): string; } };
fs?: RequestService;
}
export function startClient(context: ExtensionContext, newLanguageClient: LanguageClientConstructor, runtime: Runtime) {
const customDataSource = getCustomDataSource(context.subscriptions);
let documentSelector = ['css', 'scss', 'less'];
// Options to control the language client
let clientOptions: LanguageClientOptions = {
documentSelector,
synchronize: {
configurationSection: ['css', 'scss', 'less']
},
initializationOptions: {
handledSchemas: ['file']
},
middleware: {
provideCompletionItem(document: TextDocument, position: Position, context: CompletionContext, token: CancellationToken, next: ProvideCompletionItemsSignature): ProviderResult<CompletionItem[] | CompletionList> {
// testing the replace / insert mode
function updateRanges(item: CompletionItem) {
const range = item.range;
if (range instanceof Range && range.end.isAfter(position) && range.start.isBeforeOrEqual(position)) {
item.range = { inserting: new Range(range.start, position), replacing: range };
}
}
function updateLabel(item: CompletionItem) {
if (item.kind === CompletionItemKind.Color) {
item.label2 = {
name: item.label,
type: (item.documentation as string)
};
}
}
// testing the new completion
function updateProposals(r: CompletionItem[] | CompletionList | null | undefined): CompletionItem[] | CompletionList | null | undefined {
if (r) {
(Array.isArray(r) ? r : r.items).forEach(updateRanges);
(Array.isArray(r) ? r : r.items).forEach(updateLabel);
}
return r;
}
const isThenable = <T>(obj: ProviderResult<T>): obj is Thenable<T> => obj && (<any>obj)['then'];
const r = next(document, position, context, token);
if (isThenable<CompletionItem[] | CompletionList | null | undefined>(r)) {
return r.then(updateProposals);
}
return updateProposals(r);
}
}
};
// Create the language client and start the client.
let client = newLanguageClient('css', localize('cssserver.name', 'CSS Language Server'), clientOptions);
client.registerProposedFeatures();
client.onReady().then(() => {
client.sendNotification(CustomDataChangedNotification.type, customDataSource.uris);
customDataSource.onDidChange(() => {
client.sendNotification(CustomDataChangedNotification.type, customDataSource.uris);
});
serveFileSystemRequests(client, runtime);
});
let disposable = client.start();
// Push the disposable to the context's subscriptions so that the
// client can be deactivated on extension deactivation
context.subscriptions.push(disposable);
let indentationRules = {
increaseIndentPattern: /(^.*\{[^}]*$)/,
decreaseIndentPattern: /^\s*\}/
};
languages.setLanguageConfiguration('css', {
wordPattern: /(#?-?\d*\.\d\w*%?)|(::?[\w-]*(?=[^,{;]*[,{]))|(([@#.!])?[\w-?]+%?|[@#!.])/g,
indentationRules: indentationRules
});
languages.setLanguageConfiguration('less', {
wordPattern: /(#?-?\d*\.\d\w*%?)|(::?[\w-]+(?=[^,{;]*[,{]))|(([@#.!])?[\w-?]+%?|[@#!.])/g,
indentationRules: indentationRules
});
languages.setLanguageConfiguration('scss', {
wordPattern: /(#?-?\d*\.\d\w*%?)|(::?[\w-]*(?=[^,{;]*[,{]))|(([@$#.!])?[\w-?]+%?|[@#!$.])/g,
indentationRules: indentationRules
});
client.onReady().then(() => {
context.subscriptions.push(initCompletionProvider());
});
function initCompletionProvider(): Disposable {
const regionCompletionRegExpr = /^(\s*)(\/(\*\s*(#\w*)?)?)?$/;
return languages.registerCompletionItemProvider(documentSelector, {
provideCompletionItems(doc: TextDocument, pos: Position) {
let lineUntilPos = doc.getText(new Range(new Position(pos.line, 0), pos));
let match = lineUntilPos.match(regionCompletionRegExpr);
if (match) {
let range = new Range(new Position(pos.line, match[1].length), pos);
let beginProposal = new CompletionItem('#region', CompletionItemKind.Snippet);
beginProposal.range = range; TextEdit.replace(range, '/* #region */');
beginProposal.insertText = new SnippetString('/* #region $1*/');
beginProposal.documentation = localize('folding.start', 'Folding Region Start');
beginProposal.filterText = match[2];
beginProposal.sortText = 'za';
let endProposal = new CompletionItem('#endregion', CompletionItemKind.Snippet);
endProposal.range = range;
endProposal.insertText = '/* #endregion */';
endProposal.documentation = localize('folding.end', 'Folding Region End');
endProposal.sortText = 'zb';
endProposal.filterText = match[2];
return [beginProposal, endProposal];
}
return null;
}
});
}
commands.registerCommand('_css.applyCodeAction', applyCodeAction);
function applyCodeAction(uri: string, documentVersion: number, edits: TextEdit[]) {
let textEditor = window.activeTextEditor;
if (textEditor && textEditor.document.uri.toString() === uri) {
if (textEditor.document.version !== documentVersion) {
window.showInformationMessage(`CSS fix is outdated and can't be applied to the document.`);
}
textEditor.edit(mutator => {
for (let edit of edits) {
mutator.replace(client.protocol2CodeConverter.asRange(edit.range), edit.newText);
}
}).then(success => {
if (!success) {
window.showErrorMessage('Failed to apply CSS fix to the document. Please consider opening an issue with steps to reproduce.');
}
});
}
}
}
| mit |
erikdesjardins/slack-irc | test/username-decorator.test.js | 1279 | import chai from 'chai';
import { highlightUsername } from '../lib/helpers';
chai.should();
describe('Bare Slack Username Replacement', () => {
it('should replace `username` with `@username`', () => {
const message = 'hey username, check this out';
const expected = 'hey @username, check this out';
const result = highlightUsername('username', message);
result.should.equal(expected);
});
it('should replace when followed by a character', () => {
const message = 'username: go check this out';
const expected = '@username: go check this out';
const result = highlightUsername('username', message);
result.should.equal(expected);
});
it('should not replace `username` in a url with a protocol', () => {
const message = 'the repo is https://github.com/username/foo';
highlightUsername('username', message).should.equal(message);
});
it('should not replace `username` in a url without a protocol', () => {
const message = 'the repo is github.com/username/foo';
highlightUsername('username', message).should.equal(message);
});
it('should not replace a @-prefixed username', () => {
const message = 'hey @username, check this out';
highlightUsername('username', message).should.equal(message);
});
});
| mit |
FlexPress/plugin-bitly | src/FlexPress/Plugins/Bitly/Bitly.php | 561 | <?php
namespace FlexPress\Plugins\Bitly;
use FlexPress\Components\Hooks\Hooker;
use FlexPress\Plugins\AbstractPlugin;
class Bitly extends AbstractPlugin
{
/**
* @var \FlexPress\Components\Hooks\Hooker
*/
protected $hooker;
public function __construct(Hooker $hooker)
{
$this->hooker = $hooker;
}
/**
*
* Used to setup the hooker
*
* @param $file
* @author Tim Perry
*
*/
public function init($file)
{
parent::init($file);
$this->hooker->hookUp();
}
}
| mit |
HEXA-UA/supervisor-manager | components/gridView/views/gridTemplate.php | 1162 | <div class="box lteGridTemplate">
<?php if ($this->context->tableTitle):?>
<div class="box-header">
<h3 class="box-title"><?php echo $this->context->tableTitle;?></h3>
<div class="box-tools pull-right"></div>
</div>
<?php endif;?>
<!-- /.box-header -->
<div class="box-body">
<div class="dataTables_wrapper dt-bootstrap">
<div class="row">
<div class="col-sm-6"></div>
<div class="col-sm-6"></div>
</div>
<?php echo $this->context->beforeItems ?>
<br>
<div class="row">
<div class="col-sm-12">{items}</div>
</div>
<div class="row options">
<div class="col-sm-8 paginationBlock">
<div class="dataTables_paginate paging_simple_numbers">{pager}</div>
</div>
<div class="col-sm-4 summary">
<div class="dataTables_info" role="status" aria-live="polite">{summary}</div>
</div>
</div>
</div>
</div>
<!-- /.box-body -->
</div>
<!-- /.box -->
| mit |
bbondy/brightray | browser/net/devtools_network_transaction.cc | 9698 | // Copyright (c) 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-CHROMIUM file.
#include "browser/net/devtools_network_transaction.h"
#include "browser/net/devtools_network_controller.h"
#include "browser/net/devtools_network_upload_data_stream.h"
#include "net/base/load_timing_info.h"
#include "net/base/net_errors.h"
#include "net/base/upload_progress.h"
#include "net/http/http_network_transaction.h"
#include "net/http/http_request_info.h"
#include "net/socket/connection_attempts.h"
namespace brightray {
// static
const char
DevToolsNetworkTransaction::kDevToolsEmulateNetworkConditionsClientId[] =
"X-DevTools-Emulate-Network-Conditions-Client-Id";
DevToolsNetworkTransaction::DevToolsNetworkTransaction(
DevToolsNetworkController* controller,
scoped_ptr<net::HttpTransaction> transaction)
: throttled_byte_count_(0),
controller_(controller),
transaction_(std::move(transaction)),
request_(nullptr),
failed_(false) {
DCHECK(controller);
}
DevToolsNetworkTransaction::~DevToolsNetworkTransaction() {
if (interceptor_ && !throttle_callback_.is_null())
interceptor_->StopThrottle(throttle_callback_);
}
void DevToolsNetworkTransaction::IOCallback(
const net::CompletionCallback& callback, bool start, int result) {
result = Throttle(callback, start, result);
if (result != net::ERR_IO_PENDING)
callback.Run(result);
}
int DevToolsNetworkTransaction::Throttle(
const net::CompletionCallback& callback, bool start, int result) {
if (failed_)
return net::ERR_INTERNET_DISCONNECTED;
if (!interceptor_ || result < 0)
return result;
base::TimeTicks send_end;
if (start) {
throttled_byte_count_ += transaction_->GetTotalReceivedBytes();
net::LoadTimingInfo load_timing_info;
if (GetLoadTimingInfo(&load_timing_info))
send_end = load_timing_info.send_end;
if (send_end.is_null())
send_end = base::TimeTicks::Now();
}
if (result > 0)
throttled_byte_count_ += result;
throttle_callback_ = base::Bind(&DevToolsNetworkTransaction::ThrottleCallback,
base::Unretained(this),
callback);
int rv = interceptor_->StartThrottle(result, throttled_byte_count_, send_end,
start, false, throttle_callback_);
if (rv != net::ERR_IO_PENDING)
throttle_callback_.Reset();
if (rv == net::ERR_INTERNET_DISCONNECTED)
Fail();
return rv;
}
void DevToolsNetworkTransaction::ThrottleCallback(
const net::CompletionCallback& callback, int result, int64_t bytes) {
DCHECK(!throttle_callback_.is_null());
throttle_callback_.Reset();
if (result == net::ERR_INTERNET_DISCONNECTED)
Fail();
throttled_byte_count_ = bytes;
callback.Run(result);
}
void DevToolsNetworkTransaction::Fail() {
DCHECK(request_);
DCHECK(!failed_);
failed_ = true;
transaction_->SetBeforeNetworkStartCallback(BeforeNetworkStartCallback());
if (interceptor_)
interceptor_.reset();
}
bool DevToolsNetworkTransaction::CheckFailed() {
if (failed_)
return true;
if (interceptor_ && interceptor_->IsOffline()) {
Fail();
return true;
}
return false;
}
int DevToolsNetworkTransaction::Start(
const net::HttpRequestInfo* request,
const net::CompletionCallback& callback,
const net::BoundNetLog& net_log) {
DCHECK(request);
request_ = request;
std::string client_id;
bool has_devtools_client_id = request_->extra_headers.HasHeader(
kDevToolsEmulateNetworkConditionsClientId);
if (has_devtools_client_id) {
custom_request_.reset(new net::HttpRequestInfo(*request_));
custom_request_->extra_headers.GetHeader(
kDevToolsEmulateNetworkConditionsClientId, &client_id);
custom_request_->extra_headers.RemoveHeader(
kDevToolsEmulateNetworkConditionsClientId);
if (request_->upload_data_stream) {
custom_upload_data_stream_.reset(
new DevToolsNetworkUploadDataStream(request_->upload_data_stream));
custom_request_->upload_data_stream = custom_upload_data_stream_.get();
}
request_ = custom_request_.get();
}
DevToolsNetworkInterceptor* interceptor = controller_->GetInterceptor(client_id);
if (interceptor) {
interceptor_ = interceptor->GetWeakPtr();
if (custom_upload_data_stream_)
custom_upload_data_stream_->SetInterceptor(interceptor);
}
if (CheckFailed())
return net::ERR_INTERNET_DISCONNECTED;
if (!interceptor_)
return transaction_->Start(request_, callback, net_log);
int result = transaction_->Start(request_,
base::Bind(&DevToolsNetworkTransaction::IOCallback,
base::Unretained(this), callback, true),
net_log);
return Throttle(callback, true, result);
}
int DevToolsNetworkTransaction::RestartIgnoringLastError(
const net::CompletionCallback& callback) {
if (CheckFailed())
return net::ERR_INTERNET_DISCONNECTED;
if (!interceptor_)
return transaction_->RestartIgnoringLastError(callback);
int result = transaction_->RestartIgnoringLastError(
base::Bind(&DevToolsNetworkTransaction::IOCallback,
base::Unretained(this), callback, true));
return Throttle(callback, true, result);
}
int DevToolsNetworkTransaction::RestartWithCertificate(
net::X509Certificate* client_cert,
net::SSLPrivateKey* client_private_key,
const net::CompletionCallback& callback) {
if (CheckFailed())
return net::ERR_INTERNET_DISCONNECTED;
if (!interceptor_) {
return transaction_->RestartWithCertificate(
client_cert, client_private_key, callback);
}
int result = transaction_->RestartWithCertificate(
client_cert, client_private_key,
base::Bind(&DevToolsNetworkTransaction::IOCallback,
base::Unretained(this), callback, true));
return Throttle(callback, true, result);
}
int DevToolsNetworkTransaction::RestartWithAuth(
const net::AuthCredentials& credentials,
const net::CompletionCallback& callback) {
if (CheckFailed())
return net::ERR_INTERNET_DISCONNECTED;
if (!interceptor_)
return transaction_->RestartWithAuth(credentials, callback);
int result = transaction_->RestartWithAuth(credentials,
base::Bind(&DevToolsNetworkTransaction::IOCallback,
base::Unretained(this), callback, true));
return Throttle(callback, true, result);
}
bool DevToolsNetworkTransaction::IsReadyToRestartForAuth() {
return transaction_->IsReadyToRestartForAuth();
}
int DevToolsNetworkTransaction::Read(
net::IOBuffer* buf,
int buf_len,
const net::CompletionCallback& callback) {
if (CheckFailed())
return net::ERR_INTERNET_DISCONNECTED;
if (!interceptor_)
return transaction_->Read(buf, buf_len, callback);
int result = transaction_->Read(buf, buf_len,
base::Bind(&DevToolsNetworkTransaction::IOCallback,
base::Unretained(this), callback, false));
// URLRequestJob relies on synchronous end-of-stream notification.
if (result == 0)
return result;
return Throttle(callback, false, result);
}
void DevToolsNetworkTransaction::StopCaching() {
transaction_->StopCaching();
}
bool DevToolsNetworkTransaction::GetFullRequestHeaders(
net::HttpRequestHeaders* headers) const {
return transaction_->GetFullRequestHeaders(headers);
}
int64_t DevToolsNetworkTransaction::GetTotalReceivedBytes() const {
return transaction_->GetTotalReceivedBytes();
}
int64_t DevToolsNetworkTransaction::GetTotalSentBytes() const {
return transaction_->GetTotalSentBytes();
}
void DevToolsNetworkTransaction::DoneReading() {
transaction_->DoneReading();
}
const net::HttpResponseInfo*
DevToolsNetworkTransaction::GetResponseInfo() const {
return transaction_->GetResponseInfo();
}
net::LoadState DevToolsNetworkTransaction::GetLoadState() const {
return transaction_->GetLoadState();
}
net::UploadProgress DevToolsNetworkTransaction::GetUploadProgress() const {
return transaction_->GetUploadProgress();
}
void DevToolsNetworkTransaction::SetQuicServerInfo(
net::QuicServerInfo* info) {
transaction_->SetQuicServerInfo(info);
}
bool DevToolsNetworkTransaction::GetLoadTimingInfo(
net::LoadTimingInfo* info) const {
return transaction_->GetLoadTimingInfo(info);
}
bool DevToolsNetworkTransaction::GetRemoteEndpoint(
net::IPEndPoint* endpoint) const {
return transaction_->GetRemoteEndpoint(endpoint);
}
void DevToolsNetworkTransaction::PopulateNetErrorDetails(
net::NetErrorDetails* details) const {
return transaction_->PopulateNetErrorDetails(details);
}
void DevToolsNetworkTransaction::SetPriority(net::RequestPriority priority) {
transaction_->SetPriority(priority);
}
void DevToolsNetworkTransaction::SetWebSocketHandshakeStreamCreateHelper(
net::WebSocketHandshakeStreamBase::CreateHelper* helper) {
transaction_->SetWebSocketHandshakeStreamCreateHelper(helper);
}
void DevToolsNetworkTransaction::SetBeforeNetworkStartCallback(
const BeforeNetworkStartCallback& callback) {
transaction_->SetBeforeNetworkStartCallback(callback);
}
void DevToolsNetworkTransaction::SetBeforeProxyHeadersSentCallback(
const BeforeProxyHeadersSentCallback& callback) {
transaction_->SetBeforeProxyHeadersSentCallback(callback);
}
int DevToolsNetworkTransaction::ResumeNetworkStart() {
if (CheckFailed())
return net::ERR_INTERNET_DISCONNECTED;
return transaction_->ResumeNetworkStart();
}
void DevToolsNetworkTransaction::GetConnectionAttempts(
net::ConnectionAttempts* out) const {
transaction_->GetConnectionAttempts(out);
}
} // namespace brightray
| mit |
d4l3k/ubc-course | server/config/environment/production.js | 586 | 'use strict';
// Production specific configuration
// =================================
module.exports = {
// Server IP
ip: process.env.OPENSHIFT_NODEJS_IP ||
process.env.IP ||
undefined,
// Server port
port: process.env.OPENSHIFT_NODEJS_PORT ||
process.env.PORT ||
8080,
// MongoDB connection options
mongo: {
uri: process.env.MONGOLAB_URI ||
process.env.MONGOHQ_URL ||
process.env.OPENSHIFT_MONGODB_DB_URL + process.env.OPENSHIFT_APP_NAME ||
'mongodb://localhost/ubccourse'
}
};
| mit |
TzuChieh/Photon-v2 | EngineTest/Source/Math/TMatrix3_test.cpp | 2844 | #include <Math/TMatrix3.h>
#include <gtest/gtest.h>
typedef ph::TMatrix3<float> Matrix;
namespace
{
void expect_all_zero(const Matrix& matrix)
{
EXPECT_EQ(matrix.m[0][0], 0.0f);
EXPECT_EQ(matrix.m[0][1], 0.0f);
EXPECT_EQ(matrix.m[0][2], 0.0f);
EXPECT_EQ(matrix.m[1][0], 0.0f);
EXPECT_EQ(matrix.m[1][1], 0.0f);
EXPECT_EQ(matrix.m[1][2], 0.0f);
EXPECT_EQ(matrix.m[2][0], 0.0f);
EXPECT_EQ(matrix.m[2][1], 0.0f);
EXPECT_EQ(matrix.m[2][2], 0.0f);
}
void expect_identity(const Matrix& matrix)
{
EXPECT_EQ(matrix.m[0][0], 1.0f);
EXPECT_EQ(matrix.m[0][1], 0.0f);
EXPECT_EQ(matrix.m[0][2], 0.0f);
EXPECT_EQ(matrix.m[1][0], 0.0f);
EXPECT_EQ(matrix.m[1][1], 1.0f);
EXPECT_EQ(matrix.m[1][2], 0.0f);
EXPECT_EQ(matrix.m[2][0], 0.0f);
EXPECT_EQ(matrix.m[2][1], 0.0f);
EXPECT_EQ(matrix.m[2][2], 1.0f);
}
}
TEST(TMatrix3Test, Construction)
{
Matrix mat1(0);
expect_all_zero(mat1);
Matrix mat2(Matrix::Elements{{
{1.0f, 2.0f, 3.0f},
{4.0f, 5.0f, 6.0f},
{7.0f, 8.0f, 9.0f}
}});
EXPECT_EQ(mat2.m[0][0], 1.0f);
EXPECT_EQ(mat2.m[0][1], 2.0f);
EXPECT_EQ(mat2.m[0][2], 3.0f);
EXPECT_EQ(mat2.m[1][0], 4.0f);
EXPECT_EQ(mat2.m[1][1], 5.0f);
EXPECT_EQ(mat2.m[1][2], 6.0f);
EXPECT_EQ(mat2.m[2][0], 7.0f);
EXPECT_EQ(mat2.m[2][1], 8.0f);
EXPECT_EQ(mat2.m[2][2], 9.0f);
}
TEST(TMatrix3Test, Multiplying)
{
Matrix mat1(Matrix::Elements{{
{1.0f, 2.0f, 3.0f},
{4.0f, 5.0f, 6.0f},
{7.0f, 8.0f, 9.0f}
}});
Matrix mat2( 0.0f);
Matrix mat3(-1.0f);
Matrix mat4 = mat1.mul(mat2);
Matrix mat5 = mat1.mul(mat3);
expect_all_zero(mat4);
EXPECT_EQ(mat5.m[0][0], -6.0f);
EXPECT_EQ(mat5.m[0][1], -6.0f);
EXPECT_EQ(mat5.m[0][2], -6.0f);
EXPECT_EQ(mat5.m[1][0], -15.0f);
EXPECT_EQ(mat5.m[1][1], -15.0f);
EXPECT_EQ(mat5.m[1][2], -15.0f);
EXPECT_EQ(mat5.m[2][0], -24.0f);
EXPECT_EQ(mat5.m[2][1], -24.0f);
EXPECT_EQ(mat5.m[2][2], -24.0f);
}
TEST(TMatrix3Test, CalcDeterminant)
{
Matrix mat1(Matrix::Elements{{
{1.0f, 2.0f, 3.0f},
{4.0f, 5.0f, 6.0f},
{7.0f, 8.0f, 9.0f}
}});
EXPECT_EQ(mat1.determinant(), 0.0f);
Matrix mat2(Matrix::Elements{{
{1.0f, 0.0f, 0.0f},
{0.0f, 1.0f, 0.0f},
{0.0f, 0.0f, 1.0f}
}});
EXPECT_EQ(mat2.determinant(), 1.0f);
}
TEST(TMatrix3Test, Inversing)
{
Matrix mat1(Matrix::Elements{{
{1.0f, 0.0f, 0.0f},
{0.0f, 1.0f, 0.0f},
{0.0f, 0.0f, 1.0f}
}});
expect_identity(mat1.inverse());
Matrix mat2(Matrix::Elements{{
{-1.0f, 2.0f, 3.0f},
{ 1.0f, -2.0f, 3.0f},
{ 1.0f, 2.0f, -3.0f}
}});
mat2 = mat2.inverse();
EXPECT_EQ(mat2.m[0][0], 0.0f);
EXPECT_EQ(mat2.m[0][1], 0.5f);
EXPECT_EQ(mat2.m[0][2], 0.5f);
EXPECT_EQ(mat2.m[1][0], 0.25f);
EXPECT_EQ(mat2.m[1][1], 0.0f);
EXPECT_EQ(mat2.m[1][2], 0.25f);
EXPECT_EQ(mat2.m[2][0], 0.16666666666666666f);
EXPECT_EQ(mat2.m[2][1], 0.16666666666666666f);
EXPECT_EQ(mat2.m[2][2], 0.0f);
} | mit |
annapowellsmith/openpresc | openprescribing/dmd/models.py | 7442 | """These models correspond with a subset of the tables whose schema is
implied by the raw D+MD XML.
There are no migrations for these models; the tables and their
contents are generated directly from raw XML files by the `import_dmd`
management command.
We use the `db_table` attribute to set table names to match the names
in the original XML. This allows easier cross-referencing with the
Data Model and Implementation Guides published by the NHS BSA:
* Data Model: docs/Data_Model_R2_v3.1_May_2015.pdf
* Implementation: docs/dmd_Implemention_Guide_%28Primary_Care%29_v1.0.pdf
Note that many other tables are imported but not necessarily modelled
here. For some examples of the kinds of query that are possible, see:
https://github.com/ebmdatalab/price-per-dose/blob/master/snomed-bnf-mapping.ipynb
"""
from __future__ import unicode_literals
from django.db import models
class AvailabilityRestriction(models.Model):
cd = models.IntegerField(primary_key=True)
desc = models.TextField()
def __str__(self):
return self.desc
class Meta:
db_table = 'dmd_lookup_availability_restriction'
class Prescribability(models.Model):
cd = models.IntegerField(primary_key=True)
desc = models.TextField()
def __str__(self):
return self.desc
class Meta:
db_table = 'dmd_lookup_virtual_product_pres_status'
class VMPNonAvailability(models.Model):
cd = models.IntegerField(primary_key=True)
desc = models.TextField()
def __str__(self):
return self.desc
class Meta:
db_table = 'dmd_lookup_virtual_product_non_avail'
class ControlledDrugCategory(models.Model):
cd = models.IntegerField(primary_key=True)
desc = models.TextField()
def __str__(self):
return self.desc
class Meta:
db_table = 'dmd_lookup_control_drug_category'
class TariffCategory(models.Model):
cd = models.IntegerField(primary_key=True)
desc = models.TextField()
def __str__(self):
return self.desc
class Meta:
db_table = 'dmd_lookup_dt_payment_category'
class DMDProduct(models.Model):
'''A model that combines AMPs and VPMs to make mapping to legacy BNF
codes easier, and to cache lookups on commonly-useful relations.
'''
dmdid = models.BigIntegerField(primary_key=True)
bnf_code = models.CharField(max_length=15, null=True, db_index=True)
vpid = models.BigIntegerField(db_index=True)
name = models.CharField(max_length=400)
full_name = models.TextField(null=True)
# requiring additional monitoring in accordance with the European
# Medicines Agency Additional Monitoring Scheme
ema = models.CharField(max_length=15, null=True)
prescribability = models.ForeignKey(
Prescribability, db_column='pres_statcd', null=True)
availability_restrictions = models.ForeignKey(
AvailabilityRestriction, db_column='avail_restrictcd', null=True)
vmp_non_availability = models.ForeignKey(
VMPNonAvailability, db_column='non_availcd', null=True)
# 1 = VMP, 2 = AMP
concept_class = models.IntegerField(db_index=True, null=True)
# 1 = Generic, 2 = brand, 3 = Mannufactured Generic
product_type = models.IntegerField(null=True)
# in the nurse prescribers' formulary?
is_in_nurse_formulary = models.NullBooleanField(db_column='nurse_f')
is_in_dentist_formulary = models.NullBooleanField(db_column='dent_f')
# Product order number - Order number of product within Drug Tariff
product_order_no = models.TextField(db_column='prod_order_no', null=True)
# indicates AMPs listed in part XVIIIA of the Drug Tariff
is_blacklisted = models.NullBooleanField(db_column='sched_1')
# Indicates items that are part of the Selected List Scheme
is_schedule_2 = models.NullBooleanField(db_column='sched_2')
# This flag indicates where a prescriber will receive a fee for
# administering an item. This is only applicable to NHS primary
# medical services contractors.
can_have_personal_administration_fee = models.NullBooleanField(
db_column='padm')
# Indicates items that can be prescribed in instalments on a FP10
# MDA form.
is_fp10 = models.NullBooleanField(db_column='fp10_mda')
# Borderline substances: foodstuffs and toiletries which can be
# prescribed
is_borderline_substance = models.NullBooleanField(db_column='acbs')
has_assorted_flavours = models.NullBooleanField(db_column='assort_flav')
controlled_drug_category = models.ForeignKey(
ControlledDrugCategory, db_column='catcd', null=True)
tariff_category = models.ForeignKey(
TariffCategory, db_column='tariff_category', null=True)
is_imported = models.NullBooleanField(db_column='flag_imported')
is_broken_bulk = models.NullBooleanField(db_column='flag_broken_bulk')
is_non_bioequivalent = models.NullBooleanField(
db_column='flag_non_bioequivalence')
is_special_container = models.NullBooleanField(
db_column='flag_special_containers')
class Meta:
db_table = 'dmd_product'
def __str__(self):
return self.full_name
@property
def amps(self):
return DMDProduct.objects.filter(
vpid=self.dmdid).filter(concept_class=2)
@property
def vmp(self):
if self.concept_class == 1:
raise DMDProduct.DoesNotExist("You can't find a VMP of a VMP")
vmp = DMDProduct.objects.filter(
dmdid=self.vpid, concept_class=1).exclude(vpid=self.dmdid)
assert len(vmp) < 2, "An AMP should only ever have one VMP"
return vmp[0]
class DMDVmpp(models.Model):
vppid = models.BigIntegerField(primary_key=True)
invalid = models.BigIntegerField(blank=True, null=True)
nm = models.TextField(blank=True, null=True)
abbrevnm = models.TextField(blank=True, null=True)
vpid = models.BigIntegerField(blank=True, null=True)
qtyval = models.FloatField(blank=True, null=True)
qty_uomcd = models.BigIntegerField(blank=True, null=True)
combpackcd = models.BigIntegerField(blank=True, null=True)
class Meta:
db_table = 'dmd_vmpp'
def __str__(self):
return self.nm
class NCSOConcession(models.Model):
vmpp = models.ForeignKey(DMDVmpp, null=True)
date = models.DateField(db_index=True)
drug = models.CharField(max_length=400)
pack_size = models.CharField(max_length=40)
price_concession_pence = models.IntegerField()
class Meta:
unique_together = ('date', 'vmpp')
class Manager(models.Manager):
def unreconciled(self):
return self.filter(vmpp__isnull=True)
objects = Manager()
@property
def drug_and_pack_size(self):
return u'{} {}'.format(self.drug, self.pack_size)
class TariffPrice(models.Model):
"""Price
"""
date = models.DateField(db_index=True)
vmpp = models.ForeignKey(DMDVmpp)
product = models.ForeignKey(DMDProduct)
# 1: Category A
# 3: Category C
# 11: Category M
tariff_category = models.ForeignKey(TariffCategory)
price_pence = models.IntegerField()
@property
def concession(self):
try:
concession = NCSOConcession.objects.get(
date=self.date, vmpp=self.vmpp)
except NCSOConcession.DoesNotExist:
concession = None
return concession
class Meta:
unique_together = ('date', 'vmpp',)
| mit |
kevinansfield/Ghost | core/server/web/well-known.js | 650 | const express = require('express');
const settings = require('../services/settings/cache');
const jose = require('node-jose');
const dangerousPrivateKey = settings.get('ghost_private_key');
const keyStore = jose.JWK.createKeyStore();
const keyStoreReady = keyStore.add(dangerousPrivateKey, 'pem');
const getSafePublicJWKS = async () => {
await keyStoreReady;
return keyStore.toJSON();
};
module.exports = function setupWellKnownApp() {
const wellKnownApp = express();
wellKnownApp.get('/jwks.json', async (req, res) => {
const jwks = await getSafePublicJWKS();
res.json(jwks);
});
return wellKnownApp;
};
| mit |
xml315xiao/MCodeigniter | application/modules/front/services/User_service.php | 120 | <?php
class User_service extends MY_Service
{
public function test()
{
echo '=================';
}
} | mit |
acumb/LatticeDNAOrigami | tests/src/test_random_gens.cpp | 5293 | #include <catch.hpp>
#define private public
#define protected public
#include "parser.h"
#include "nearest_neighbour.h"
#include "domain.h"
#include "files.h"
#include "simulation.h"
#include "test_origami_system.h"
using std::cout;
using namespace Parser;
using namespace Utility;
using namespace Files;
using namespace Origami;
using namespace DomainContainer;
using namespace Simulation;
using namespace Movetypes;
using namespace NearestNeighbour;
using namespace TestOrigamiSystem;
SCENARIO("Distributions are calculated for methods with random variables") {
double eps {0.01}; // Check values are within 1%
double temp {300};
double cation_M {1};
RandomGens random_gens {};
IdealRandomWalks ideal_random_walks {};
InputParameters params {};
OrigamiSystem origami {setup_two_domain_scaffold_origami(temp, cation_M)};
origami.add_chain(1);
// Easy reference
Domain& scaffold_d_1 {*origami.get_domain(0, 0)};
Domain& scaffold_d_2 {*origami.get_domain(0, 1)};
Domain& staple_d_1 {*origami.get_domain(1, 0)};
Domain& staple_d_2 {*origami.get_domain(1, 1)};
// Just need the shared movetype methods
IdentityMCMovetype movetype {origami, random_gens,
ideal_random_walks, params};
GIVEN("Uniform distribution for two domain one staple system domain selection.") {
unordered_map<pair<int, int>, double> exp_dist {
{{0, 0}, 0.25},
{{0, 1}, 0.25},
{{1, 0}, 0.25},
{{1, 1}, 0.25}};
// Estimate distribution from function
unordered_map<pair<int, int>, double> calc_dist {};
int num_iters {100000};
for (int i {0}; i != num_iters; i++) {
Domain* domain {movetype.select_random_domain()};
pair<int, int> key {domain->m_d, domain->m_c};
calc_dist[key] += 1./num_iters;
}
THEN("Distributions match (within 1%)") {
bool dists_match = true;
for (int d {0}; d != 2; d++) {
for (int c {0}; c != 2; c++) {
pair<int, int> key {d, c};
double calc_p {calc_dist[key]};
double exp_p {exp_dist[key]};
if (calc_p < (exp_p - eps) or calc_p > (exp_p + eps)) {
dists_match = false;
}
}
}
REQUIRE(dists_match == true);
}
}
GIVEN("Uniform distrubtion of positions around a previous") {
VectorThree p_prev {3, 4, 1};
double exp_p {1./6};
// Estimate distribution from function
vector<VectorThree> new_pos {
{4, 4, 1},
{2, 4, 1},
{3, 5, 1},
{3, 3, 1},
{3, 4, 2},
{3, 4, 0}};
unordered_map<VectorThree, double> calc_dist {};
int num_iters {100000};
for (int i {0}; i != num_iters; i++) {
VectorThree pos {movetype.select_random_position(p_prev)};
calc_dist[pos] += 1./num_iters;
}
THEN("Distributions match (within 1%)") {
bool dists_match = true;
for (auto pos: new_pos) {
double calc_p {calc_dist[pos]};
if (calc_p < (exp_p - eps) or calc_p > (exp_p + eps)) {
dists_match = false;
}
}
REQUIRE(dists_match == true);
}
}
GIVEN("A configuration for the origami system and very high T") {
origami.set_domain_config(scaffold_d_1, {0, 0, 0}, {0, -1, 0});
origami.set_domain_config(scaffold_d_2, {1, 0, 0}, {0, -1, 0});
origami.set_domain_config(staple_d_1, {0, 0, 0}, {0, 1, 0});
origami.set_domain_config(staple_d_2, {0, 1, 0}, {0, 1, 0});
// Over the simulation, all positions of d2 relative to d1 should be
// equally probable
// Could add a WHEN here, and in general to the whole test suite
double exp_p {1./6};
vector<VectorThree> new_pos {{1, 0, 0}, {-1, 0, 0}, {0, 1, 0},
{0, -1, 0}, {0, 0, 1}, {0, 0, -1}};
// Calculate the distribution of accepted positions for scaffold domain 2
unordered_map<VectorThree, double> calc_dist {};
int accepted_moves {0};
int num_iters {100000};
for (int i {0}; i != num_iters; i++) {
CTCBScaffoldRegrowthMCMovetype ct_movetype {origami, random_gens,
ideal_random_walks, params};
bool accepted {ct_movetype.attempt_move()};
if (not accepted) {
ct_movetype.reset_origami();
}
else {
origami.centre();
VectorThree pos {origami.get_domain(1, 1)->m_pos};
calc_dist[pos]++;
accepted_moves++;
}
}
THEN("Distributions match (within 1%)") {
bool dists_match = true;
for (auto pos: new_pos) {
double calc_p {calc_dist[pos] / accepted_moves};
if (calc_p < (exp_p - eps) or calc_p > (exp_p + eps)) {
dists_match = false;
}
}
REQUIRE(dists_match == true);
}
}
}
| mit |
portchris/NaturalRemedyCompany | src/app/code/core/Mage/Checkout/Model/Cart/Shipping/Api/V2.php | 1188 | <?php
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@magento.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magento.com for more information.
*
* @category Mage
* @package Mage_Checkout
* @copyright Copyright (c) 2006-2019 Magento, Inc. (http://www.magento.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
/**
* Shopping cart api
*
* @category Mage
* @package Mage_Checkout
* @author Magento Core Team <core@magentocommerce.com>
*/
class Mage_Checkout_Model_Cart_Shipping_Api_V2 extends Mage_Checkout_Model_Cart_Shipping_Api
{
}
| mit |
naudet/ARCHITECTURE_LOGICIEL_DEBOUT_NAUDET | LetterGame/src/main/java/fr/esiea/unique/binome/name/dictionary/Game.java | 3286 | package fr.esiea.unique.binome.name.dictionary;
public class Game {
public static Lettre potCommun[] = new Lettre [25];
Player joueur1 = new Player(false);
Player joueur2 = new Player(false);
public static void remplirLePotCommun (Lettre lettre) {
int flag=0;
for(int i = 0; i<potCommun.length; i++) {
if(potCommun[i] != null && potCommun[i].letter == lettre.letter && flag==0) {
potCommun[i].nombre++;
flag = 1;
}
else if(potCommun[i] == null && flag == 0) {
potCommun[i] = lettre;
potCommun[i].letter = lettre.letter;
potCommun[i].nombre = 1;
flag = 1;
}
}
}
public static int checkTheWordPotCommun(String word) {
word=word.toUpperCase();
int length = word.length();
int i, j;
boolean quit = false;
char result;
int count = 0;
for(i=0; i<length; i++) {
result = word.charAt(i);
for(j=0; j<25; j++) {
try {
if(potCommun[j] != null && potCommun[j].letter == result) {
count ++;
break;
}
}
catch (Exception e) {
System.out.println(e.toString());
}
}
if( quit) {
break;
}
}
if(count == length) {
return 1;
}
else {
System.out.println("Certaines lettres ne sont pas dans le pot commun");
return 0;
}
}
public static void updatePotCommun(String word) {
word=word.toUpperCase();
int length = word.length();
int i, j;
char result;
for(i=0; i<length; i++) {
result = word.charAt(i);
for(j=0; j<25; j++) {
try {
if(potCommun[j] != null && potCommun[j].letter == result) {
if(potCommun[j].nombre == 1) {
potCommun[j] = null;
break;
}
else {
potCommun[j].nombre --;
break;
}
}
}
catch (Exception e) {
System.out.println(e.toString());
}
}
}
}
public static void afficherLePotCommun () {
System.out.println("");
System.out.println("Voici le pot commun: ");
for(int i=0; i<25; i++) {
if(potCommun[i] != null) {
if(potCommun[i].nombre > 1) {
System.out.print(potCommun[i].letter +"x" + potCommun[i].nombre + " ");
}
else{
System.out.print(potCommun[i].letter +" ");
}
}
else{
System.out.print(" ");
}
}
}
public void main() {
Lettre lettre = new Lettre('n',1);
lettre.tableau();
DebutDuJeu debutDuJeu = new DebutDuJeu(joueur1, joueur2);
debutDuJeu.main();
while(joueur1.nbMot!=10) {
System.out.println("");
System.out.println("Joueur 1 ton score:" + joueur1.nbMot);
System.out.println("Joueur 2 ton score:" + joueur2.nbMot);
System.out.println("");
if(joueur1.tour==true) {
joueur1.tour = false;
joueur2.tour = true;
System.out.println("");
System.out.println("Joueur 2 à toi de jouer");
System.out.println("");
Piocher2Lettres.piocher2Lettres();
SaisirEtVerifierMot sevm = new SaisirEtVerifierMot(joueur1,joueur2);
sevm.saisirEtVerifierMot();
}
else {
joueur2.tour=false;
joueur1.tour = true;
System.out.println("");
System.out.println("Joueur 1 à toi de jouer");
System.out.println("");
Piocher2Lettres.piocher2Lettres();
SaisirEtVerifierMot sevm = new SaisirEtVerifierMot(joueur1,joueur2);
sevm.saisirEtVerifierMot();
}
}
}
}
| mit |
ccxt/ccxt | examples/ccxt.pro/py/many-exchanges-many-symbols-watch-trades.py | 1582 | # -*- coding: utf-8 -*-
import ccxtpro
from asyncio import gather, get_event_loop
async def symbol_loop(exchange, symbol):
print('Starting the', exchange.id, 'symbol loop with', symbol)
while True:
try:
trades = await exchange.watch_trades(symbol)
now = exchange.milliseconds()
print(exchange.iso8601(now), exchange.id, symbol, len(trades), trades[-1]['price'])
except Exception as e:
print(str(e))
# raise e # uncomment to break all loops in case of an error in any one of them
break # you can break just this one loop if it fails
async def exchange_loop(asyncio_loop, exchange_id, symbols):
print('Starting the', exchange_id, 'exchange loop with', symbols)
exchange = getattr(ccxtpro, exchange_id)({
'newUpdates': True, # https://github.com/ccxt/ccxt/wiki/ccxt.pro.manual#incremental-data-structures
'enableRateLimit': True, # https://github.com/ccxt/ccxt/wiki/Manual#rate-limit
'asyncio_loop': asyncio_loop,
})
loops = [symbol_loop(exchange, symbol) for symbol in symbols]
await gather(*loops)
await exchange.close()
async def main(asyncio_loop):
exchanges = {
'okex': ['BTC/USDT', 'ETH/BTC', 'ETH/USDT'],
'binance': ['BTC/USDT', 'ETH/BTC'],
}
loops = [exchange_loop(asyncio_loop, exchange_id, symbols) for exchange_id, symbols in exchanges.items()]
await gather(*loops)
if __name__ == '__main__':
asyncio_loop = get_event_loop()
asyncio_loop.run_until_complete(main(asyncio_loop))
| mit |
mgoeminne/github_etl | src/test/scala/gh/test/gh2013/model/GollumPageTest.scala | 710 | import gh2011.models.Repository
import gh2013.models.{GollumPage, PullRequest}
import net.liftweb.json._
import org.scalatest.{FlatSpec, Matchers}
class GollumPageTest extends FlatSpec with Matchers
{
"A valid GollumPage" must "be correctly parsed" in {
val json = parse(
"""
| {
| "title":"Home",
| "action":"edited",
| "html_url":"https://github.com/hudec/sql-processor/wiki/Home",
| "page_name":"Home",
| "sha":"b5cfd5f62ef7f76abc82495f5e9d3d146b6d7a4d",
| "summary":null
| }
""".stripMargin)
GollumPage(json) shouldBe 'defined
}
}
| mit |
Sukrat/dj-suggester | build/app/services/authentication.service.spec.js | 4184 | "use strict";
var testing_1 = require("@angular/core/testing");
var platform_browser_1 = require("@angular/platform-browser");
var app_export_models_1 = require("../app.export.models");
var app_export_services_1 = require("../app.export.services");
describe('AuthenticationService:', function () {
var authenticationService;
var document;
var database;
beforeEach(function () {
var mockDocument = {
cookie: ''
};
var MockDocumentService = (function () {
function MockDocumentService() {
this.addEvent = jasmine.createSpy('addEvent');
this.getEvent = jasmine.createSpy('getEvent');
}
return MockDocumentService;
}());
testing_1.TestBed.configureTestingModule({
providers: [
app_export_services_1.AuthenticationService,
{ provide: platform_browser_1.DOCUMENT, useValue: mockDocument },
{ provide: app_export_services_1.DatabaseService, useClass: MockDocumentService }
]
});
});
beforeEach(testing_1.async(testing_1.inject([app_export_services_1.AuthenticationService, platform_browser_1.DOCUMENT, app_export_services_1.DatabaseService], function (a, d, db) {
authenticationService = a;
document = d;
database = db;
})));
var mockUser = new app_export_models_1.UserModel('Sukrat', 'Test', app_export_models_1.TypeOfUser.DJ);
describe('isLoggedIn:', function () {
it('when user is not logged in', function () {
document.cookie = '';
var isLoggedIn = authenticationService.isLoggedIn();
expect(isLoggedIn).toBeFalsy();
});
it('when user is logged in', function () {
document.cookie = ''.concat('djSuggester=', JSON.stringify(mockUser), ';');
var isLoggedIn = authenticationService.isLoggedIn();
expect(isLoggedIn).toBeTruthy();
});
});
describe('logIn:', function () {
it('when remember me is false and user exist', testing_1.async(function () {
database.getEvent = jasmine.createSpy('getEvent').and.returnValue(Promise.resolve(new app_export_models_1.EventModel(mockUser.eventName, mockUser.secretKey)));
authenticationService.logIn(mockUser).then(function (loggedIn) {
expect(loggedIn).toBeTruthy();
expect(database.getEvent).toHaveBeenCalled();
expect(document.cookie).toEqual(''.concat('djSuggester=', JSON.stringify(mockUser), ';'));
});
}));
it('when remember me is false and user name or password is wrong', testing_1.async(function () {
database.getEvent = jasmine.createSpy('getEvent').and.returnValue(Promise.resolve(new app_export_models_1.EventModel(mockUser.eventName, mockUser.secretKey + 'not')));
authenticationService.logIn(mockUser).then(function () {
throw 'Test failed';
}).catch(function (error) {
expect(error.message).toEqual('Username or password incorrect!');
expect(database.getEvent).toHaveBeenCalled();
expect(document.cookie).toEqual('');
});
}));
});
describe('logOut:', function () {
it('when remember is false', function () {
var expectedExpiredData = new Date(0);
document.cookie = ''.concat('djSuggester=', JSON.stringify(mockUser), ';');
authenticationService.logOut();
expect(document.cookie).toEqual('djSuggester=');
});
});
describe('getUser:', function () {
it('when user is not logged in', function () {
document.cookie = '';
var user = authenticationService.getUser();
expect(user).toBeNull();
});
it('when user is logged in', function () {
document.cookie = ''.concat('djSuggester=', JSON.stringify(mockUser), ';');
var user = authenticationService.getUser();
expect(user).toEqual(mockUser);
});
});
});
//# sourceMappingURL=authentication.service.spec.js.map | mit |
Coyotealone/Coyote | html2pdf/lib/Html2Pdf/src/_tcpdf/fonts/utils/makefont.php | 16269 | <?php
//============================================================+
// File name : makefont.php
// Begin : 2004-12-31
// Last Update : 2010-03-19
// Version : 1.2.006
// License : GNU LGPL (http://www.gnu.org/copyleft/lesser.html)
// ----------------------------------------------------------------------------
// Copyright (C) 2008 Nicola Asuni - Tecnick.com S.r.l.
//
// This program 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 2.1 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
// See LICENSE.TXT file for more information.
// ----------------------------------------------------------------------------
//
// Description : Utility to generate font definition files fot TCPDF
//
// Authors: Nicola Asuni, Olivier Plathey, Steven Wittens
//
// (c) Copyright:
// Nicola Asuni
// Tecnick.com S.r.l.
// Via della Pace, 11
// 09044 Quartucciu (CA)
// ITALY
// www.tecnick.com
// info@tecnick.com
//============================================================+
/**
* Utility to generate font definition files fot TCPDF.
* @author Nicola Asuni, Olivier Plathey, Steven Wittens
* @copyright 2004-2008 Nicola Asuni - Tecnick.com S.r.l (www.tecnick.com) Via Della Pace, 11 - 09044 - Quartucciu (CA) - ITALY - www.tecnick.com - info@tecnick.com
* @package com.tecnick.tcpdf
* @link http://www.tcpdf.org
* @license http://www.gnu.org/copyleft/lesser.html LGPL
*/
/**
*
* @param string $fontfile path to font file (TTF, OTF or PFB).
* @param string $fmfile font metrics file (UFM or AFM).
* @param boolean $embedded Set to false to not embed the font, true otherwise (default).
* @param string $enc Name of the encoding table to use. Omit this parameter for TrueType Unicode, OpenType Unicode and symbolic fonts like Symbol or ZapfDingBats.
* @param array $patch Optional modification of the encoding
*/
protected function MakeFont($fontfile, $fmfile, $embedded=true, $enc='cp1252', $patch=array()) {
//Generate a font definition file
set_magic_quotes_runtime(0);
ini_set('auto_detect_line_endings', '1');
if (!file_exists($fontfile)) {
die('Error: file not found: '.$fontfile);
}
if (!file_exists($fmfile)) {
die('Error: file not found: '.$fmfile);
}
$cidtogidmap = '';
$map = array();
$diff = '';
$dw = 0; // default width
$ffext = strtolower(substr($fontfile, -3));
$fmext = strtolower(substr($fmfile, -3));
if ($fmext == 'afm') {
if (($ffext == 'ttf') OR ($ffext == 'otf')) {
$type = 'TrueType';
} elseif ($ffext == 'pfb') {
$type = 'Type1';
} else {
die('Error: unrecognized font file extension: '.$ffext);
}
if ($enc) {
$map = ReadMap($enc);
foreach ($patch as $cc => $gn) {
$map[$cc] = $gn;
}
}
$fm = ReadAFM($fmfile, $map);
if (isset($widths['.notdef'])) {
$dw = $widths['.notdef'];
}
if ($enc) {
$diff = MakeFontEncoding($map);
}
$fd = MakeFontDescriptor($fm, empty($map));
} elseif ($fmext == 'ufm') {
$enc = '';
if (($ffext == 'ttf') OR ($ffext == 'otf')) {
$type = 'TrueTypeUnicode';
} else {
die('Error: not a TrueType font: '.$ffext);
}
$fm = ReadUFM($fmfile, $cidtogidmap);
$dw = $fm['MissingWidth'];
$fd = MakeFontDescriptor($fm, false);
}
//Start generation
$s = '<?php'."\n";
$s .= '$type=\''.$type."';\n";
$s .= '$name=\''.$fm['FontName']."';\n";
$s .= '$desc='.$fd.";\n";
if (!isset($fm['UnderlinePosition'])) {
$fm['UnderlinePosition'] = -100;
}
if (!isset($fm['UnderlineThickness'])) {
$fm['UnderlineThickness'] = 50;
}
$s .= '$up='.$fm['UnderlinePosition'].";\n";
$s .= '$ut='.$fm['UnderlineThickness'].";\n";
if ($dw <= 0) {
if (isset($fm['Widths'][32]) AND ($fm['Widths'][32] > 0)) {
// assign default space width
$dw = $fm['Widths'][32];
} else {
$dw = 600;
}
}
$s .= '$dw='.$dw.";\n";
$w = MakeWidthArray($fm);
$s .= '$cw='.$w.";\n";
$s .= '$enc=\''.$enc."';\n";
$s .= '$diff=\''.$diff."';\n";
$basename = substr(basename($fmfile), 0, -4);
if ($embedded) {
//Embedded font
if (($type == 'TrueType') OR ($type == 'TrueTypeUnicode')) {
CheckTTF($fontfile);
}
$f = fopen($fontfile,'rb');
if (!$f) {
die('Error: Unable to open '.$fontfile);
}
$file = fread($f, filesize($fontfile));
fclose($f);
if ($type == 'Type1') {
//Find first two sections and discard third one
$header = (ord($file{0}) == 128);
if ($header) {
//Strip first binary header
$file = substr($file, 6);
}
$pos = strpos($file, 'eexec');
if (!$pos) {
die('Error: font file does not seem to be valid Type1');
}
$size1 = $pos + 6;
if ($header AND (ord($file{$size1}) == 128)) {
//Strip second binary header
$file = substr($file, 0, $size1).substr($file, $size1+6);
}
$pos = strpos($file, '00000000');
if (!$pos) {
die('Error: font file does not seem to be valid Type1');
}
$size2 = $pos - $size1;
$file = substr($file, 0, ($size1 + $size2));
}
$basename = strtolower($basename);
if (function_exists('gzcompress')) {
$cmp = $basename.'.z';
SaveToFile($cmp, gzcompress($file, 9), 'b');
$s .= '$file=\''.$cmp."';\n";
print "Font file compressed (".$cmp.")\n";
if (!empty($cidtogidmap)) {
$cmp = $basename.'.ctg.z';
SaveToFile($cmp, gzcompress($cidtogidmap, 9), 'b');
print "CIDToGIDMap created and compressed (".$cmp.")\n";
$s .= '$ctg=\''.$cmp."';\n";
}
} else {
$s .= '$file=\''.basename($fontfile)."';\n";
print "Notice: font file could not be compressed (zlib extension not available)\n";
if (!empty($cidtogidmap)) {
$cmp = $basename.'.ctg';
$f = fopen($cmp, 'wb');
fwrite($f, $cidtogidmap);
fclose($f);
print "CIDToGIDMap created (".$cmp.")\n";
$s .= '$ctg=\''.$cmp."';\n";
}
}
if($type == 'Type1') {
$s .= '$size1='.$size1.";\n";
$s .= '$size2='.$size2.";\n";
} else {
$s.='$originalsize='.filesize($fontfile).";\n";
}
} else {
//Not embedded font
$s .= '$file='."'';\n";
}
$s .= "?>";
SaveToFile($basename.'.php',$s);
print "Font definition file generated (".$basename.".php)\n";
}
/**
* Read the specified encoding map.
* @param string $enc map name (see /enc/ folder for valid names).
*/
public function ReadMap($enc) {
//Read a map file
$file = dirname(__FILE__).'/enc/'.strtolower($enc).'.map';
$a = file($file);
if (empty($a)) {
die('Error: encoding not found: '.$enc);
}
$cc2gn = array();
foreach ($a as $l) {
if ($l{0} == '!') {
$e = preg_split('/[ \\t]+/',rtrim($l));
$cc = hexdec(substr($e[0],1));
$gn = $e[2];
$cc2gn[$cc] = $gn;
}
}
for($i = 0; $i <= 255; $i++) {
if(!isset($cc2gn[$i])) {
$cc2gn[$i] = '.notdef';
}
}
return $cc2gn;
}
/**
* Read UFM file
*/
public function ReadUFM($file, &$cidtogidmap) {
//Prepare empty CIDToGIDMap
$cidtogidmap = str_pad('', (256 * 256 * 2), "\x00");
//Read a font metric file
$a = file($file);
if (empty($a)) {
die('File not found');
}
$widths = array();
$fm = array();
foreach($a as $l) {
$e = explode(' ',chop($l));
if(count($e) < 2) {
continue;
}
$code = $e[0];
$param = $e[1];
if($code == 'U') {
// U 827 ; WX 0 ; N squaresubnosp ; G 675 ;
//Character metrics
$cc = (int)$e[1];
if ($cc != -1) {
$gn = $e[7];
$w = $e[4];
$glyph = $e[10];
$widths[$cc] = $w;
if($cc == ord('X')) {
$fm['CapXHeight'] = $e[13];
}
// Set GID
if (($cc >= 0) AND ($cc < 0xFFFF) AND $glyph) {
$cidtogidmap{($cc * 2)} = chr($glyph >> 8);
$cidtogidmap{(($cc * 2) + 1)} = chr($glyph & 0xFF);
}
}
if((isset($gn) AND ($gn == '.notdef')) AND (!isset($fm['MissingWidth']))) {
$fm['MissingWidth'] = $w;
}
} elseif($code == 'FontName') {
$fm['FontName'] = $param;
} elseif($code == 'Weight') {
$fm['Weight'] = $param;
} elseif($code == 'ItalicAngle') {
$fm['ItalicAngle'] = (double)$param;
} elseif($code == 'Ascender') {
$fm['Ascender'] = (int)$param;
} elseif($code == 'Descender') {
$fm['Descender'] = (int)$param;
} elseif($code == 'UnderlineThickness') {
$fm['UnderlineThickness'] = (int)$param;
} elseif($code == 'UnderlinePosition') {
$fm['UnderlinePosition'] = (int)$param;
} elseif($code == 'IsFixedPitch') {
$fm['IsFixedPitch'] = ($param == 'true');
} elseif($code == 'FontBBox') {
$fm['FontBBox'] = array($e[1], $e[2], $e[3], $e[4]);
} elseif($code == 'CapHeight') {
$fm['CapHeight'] = (int)$param;
} elseif($code == 'StdVW') {
$fm['StdVW'] = (int)$param;
}
}
if(!isset($fm['MissingWidth'])) {
$fm['MissingWidth'] = 600;
}
if(!isset($fm['FontName'])) {
die('FontName not found');
}
$fm['Widths'] = $widths;
return $fm;
}
/**
* Read AFM file
*/
public function ReadAFM($file,&$map) {
//Read a font metric file
$a = file($file);
if(empty($a)) {
die('File not found');
}
$widths = array();
$fm = array();
$fix = array(
'Edot'=>'Edotaccent',
'edot'=>'edotaccent',
'Idot'=>'Idotaccent',
'Zdot'=>'Zdotaccent',
'zdot'=>'zdotaccent',
'Odblacute' => 'Ohungarumlaut',
'odblacute' => 'ohungarumlaut',
'Udblacute'=>'Uhungarumlaut',
'udblacute'=>'uhungarumlaut',
'Gcedilla'=>'Gcommaaccent'
,'gcedilla'=>'gcommaaccent',
'Kcedilla'=>'Kcommaaccent',
'kcedilla'=>'kcommaaccent',
'Lcedilla'=>'Lcommaaccent',
'lcedilla'=>'lcommaaccent',
'Ncedilla'=>'Ncommaaccent',
'ncedilla'=>'ncommaaccent',
'Rcedilla'=>'Rcommaaccent',
'rcedilla'=>'rcommaaccent',
'Scedilla'=>'Scommaaccent',
'scedilla'=>'scommaaccent',
'Tcedilla'=>'Tcommaaccent',
'tcedilla'=>'tcommaaccent',
'Dslash'=>'Dcroat',
'dslash'=>'dcroat',
'Dmacron'=>'Dcroat',
'dmacron'=>'dcroat',
'combininggraveaccent'=>'gravecomb',
'combininghookabove'=>'hookabovecomb',
'combiningtildeaccent'=>'tildecomb',
'combiningacuteaccent'=>'acutecomb',
'combiningdotbelow'=>'dotbelowcomb',
'dongsign'=>'dong'
);
foreach($a as $l) {
$e = explode(' ', rtrim($l));
if (count($e) < 2) {
continue;
}
$code = $e[0];
$param = $e[1];
if ($code == 'C') {
//Character metrics
$cc = (int)$e[1];
$w = $e[4];
$gn = $e[7];
if (substr($gn, -4) == '20AC') {
$gn = 'Euro';
}
if (isset($fix[$gn])) {
//Fix incorrect glyph name
foreach ($map as $c => $n) {
if ($n == $fix[$gn]) {
$map[$c] = $gn;
}
}
}
if (empty($map)) {
//Symbolic font: use built-in encoding
$widths[$cc] = $w;
} else {
$widths[$gn] = $w;
if($gn == 'X') {
$fm['CapXHeight'] = $e[13];
}
}
if($gn == '.notdef') {
$fm['MissingWidth'] = $w;
}
} elseif($code == 'FontName') {
$fm['FontName'] = $param;
} elseif($code == 'Weight') {
$fm['Weight'] = $param;
} elseif($code == 'ItalicAngle') {
$fm['ItalicAngle'] = (double)$param;
} elseif($code == 'Ascender') {
$fm['Ascender'] = (int)$param;
} elseif($code == 'Descender') {
$fm['Descender'] = (int)$param;
} elseif($code == 'UnderlineThickness') {
$fm['UnderlineThickness'] = (int)$param;
} elseif($code == 'UnderlinePosition') {
$fm['UnderlinePosition'] = (int)$param;
} elseif($code == 'IsFixedPitch') {
$fm['IsFixedPitch'] = ($param == 'true');
} elseif($code == 'FontBBox') {
$fm['FontBBox'] = array($e[1], $e[2], $e[3], $e[4]);
} elseif($code == 'CapHeight') {
$fm['CapHeight'] = (int)$param;
} elseif($code == 'StdVW') {
$fm['StdVW'] = (int)$param;
}
}
if (!isset($fm['FontName'])) {
die('FontName not found');
}
if (!empty($map)) {
if (!isset($widths['.notdef'])) {
$widths['.notdef'] = 600;
}
if (!isset($widths['Delta']) AND isset($widths['increment'])) {
$widths['Delta'] = $widths['increment'];
}
//Order widths according to map
for ($i = 0; $i <= 255; $i++) {
if (!isset($widths[$map[$i]])) {
print "Warning: character ".$map[$i]." is missing\n";
$widths[$i] = $widths['.notdef'];
} else {
$widths[$i] = $widths[$map[$i]];
}
}
}
$fm['Widths'] = $widths;
return $fm;
}
public function MakeFontDescriptor($fm, $symbolic=false) {
//Ascent
$asc = (isset($fm['Ascender']) ? $fm['Ascender'] : 1000);
$fd = "array('Ascent'=>".$asc;
//Descent
$desc = (isset($fm['Descender']) ? $fm['Descender'] : -200);
$fd .= ",'Descent'=>".$desc;
//CapHeight
if (isset($fm['CapHeight'])) {
$ch = $fm['CapHeight'];
} elseif (isset($fm['CapXHeight'])) {
$ch = $fm['CapXHeight'];
} else {
$ch = $asc;
}
$fd .= ",'CapHeight'=>".$ch;
//Flags
$flags = 0;
if (isset($fm['IsFixedPitch']) AND $fm['IsFixedPitch']) {
$flags += 1<<0;
}
if ($symbolic) {
$flags += 1<<2;
} else {
$flags += 1<<5;
}
if (isset($fm['ItalicAngle']) AND ($fm['ItalicAngle'] != 0)) {
$flags += 1<<6;
}
$fd .= ",'Flags'=>".$flags;
//FontBBox
if (isset($fm['FontBBox'])) {
$fbb = $fm['FontBBox'];
} else {
$fbb = array(0, ($desc - 100), 1000, ($asc + 100));
}
$fd .= ",'FontBBox'=>'[".$fbb[0].' '.$fbb[1].' '.$fbb[2].' '.$fbb[3]."]'";
//ItalicAngle
$ia = (isset($fm['ItalicAngle']) ? $fm['ItalicAngle'] : 0);
$fd .= ",'ItalicAngle'=>".$ia;
//StemV
if (isset($fm['StdVW'])) {
$stemv = $fm['StdVW'];
} elseif (isset($fm['Weight']) AND preg_match('/(bold|black)/i', $fm['Weight'])) {
$stemv = 120;
} else {
$stemv = 70;
}
$fd .= ",'StemV'=>".$stemv;
//MissingWidth
if(isset($fm['MissingWidth'])) {
$fd .= ",'MissingWidth'=>".$fm['MissingWidth'];
}
$fd .= ')';
return $fd;
}
public function MakeWidthArray($fm) {
//Make character width array
$s = 'array(';
$cw = $fm['Widths'];
$els = array();
$c = 0;
foreach ($cw as $i => $w) {
if (is_numeric($i)) {
$els[] = (((($c++)%10) == 0) ? "\n" : '').$i.'=>'.$w;
}
}
$s .= implode(',', $els);
$s .= ')';
return $s;
}
public function MakeFontEncoding($map) {
//Build differences from reference encoding
$ref = ReadMap('cp1252');
$s = '';
$last = 0;
for ($i = 32; $i <= 255; $i++) {
if ($map[$i] != $ref[$i]) {
if ($i != $last+1) {
$s .= $i.' ';
}
$last = $i;
$s .= '/'.$map[$i].' ';
}
}
return rtrim($s);
}
public function SaveToFile($file, $s, $mode='t') {
$f = fopen($file, 'w'.$mode);
if(!$f) {
die('Can\'t write to file '.$file);
}
fwrite($f, $s, strlen($s));
fclose($f);
}
public function ReadShort($f) {
$a = unpack('n1n', fread($f, 2));
return $a['n'];
}
public function ReadLong($f) {
$a = unpack('N1N', fread($f, 4));
return $a['N'];
}
public function CheckTTF($file) {
//Check if font license allows embedding
$f = fopen($file, 'rb');
if (!$f) {
die('Error: unable to open '.$file);
}
//Extract number of tables
fseek($f, 4, SEEK_CUR);
$nb = ReadShort($f);
fseek($f, 6, SEEK_CUR);
//Seek OS/2 table
$found = false;
for ($i = 0; $i < $nb; $i++) {
if (fread($f, 4) == 'OS/2') {
$found = true;
break;
}
fseek($f, 12, SEEK_CUR);
}
if (!$found) {
fclose($f);
return;
}
fseek($f, 4, SEEK_CUR);
$offset = ReadLong($f);
fseek($f, $offset, SEEK_SET);
//Extract fsType flags
fseek($f, 8, SEEK_CUR);
$fsType = ReadShort($f);
$rl = ($fsType & 0x02) != 0;
$pp = ($fsType & 0x04) != 0;
$e = ($fsType & 0x08) != 0;
fclose($f);
if($rl AND (!$pp) AND (!$e)) {
print "Warning: font license does not allow embedding\n";
}
}
$arg = $GLOBALS['argv'];
if (count($arg) >= 3) {
ob_start();
array_shift($arg);
if (sizeof($arg) == 3) {
$arg[3] = $arg[2];
$arg[2] = true;
} else {
if (!isset($arg[2])) {
$arg[2] = true;
}
if (!isset($arg[3])) {
$arg[3] = 'cp1252';
}
}
if (!isset($arg[4])) {
$arg[4] = array();
}
MakeFont($arg[0], $arg[1], $arg[2], $arg[3], $arg[4]);
$t = ob_get_clean();
print preg_replace('!<BR( /)?>!i', "\n", $t);
} else {
print "Usage: makefont.php <ttf/otf/pfb file> <afm/ufm file> <encoding> <patch>\n";
}
?>
| mit |
ConnorMac/stokvel.io | etc/base_image/server/fabric_tasks.py | 4446 | from fabric.api import env, local, run, cd
import dotenv
import os
# Load local .env file
from fabric.contrib.project import rsync_project, upload_project
from fabric.operations import sudo
env.local_dotenv_path = os.path.join(os.path.dirname(__file__), './.server.env')
env.local_dir = os.path.dirname(__file__)
dotenv.load_dotenv(env.local_dotenv_path)
# Set Fabric env
env.use_ssh_config = True
env.hosts = [os.environ.get('HOST_NAME', ''), ]
env.digital_ocean_token = os.environ.get('DIGITAL_OCEAN_TOKEN', '')
env.host_name = os.environ.get('HOST_NAME', '')
env.image_name = os.environ.get('IMAGE_NAME', '')
env.user_name = os.environ.get('SSH_USERNAME', 'ubuntu')
env.sshd_port = os.environ.get('SSH_PORT', '22')
env.key_file_private = os.environ.get('KEY_FILE_PRIVATE', '')
env.key_file_public = os.environ.get('KEY_FILE_PUBLIC', '')
env.docker_compose_version = os.environ.get('DOCKER_COMPOSE_VERSION', '1.5.2')
env.pptp_secret = os.environ.get('PPTP_SECRET', 'replace_with_real_password')
# How to create default deployment
def provision(provider='digitalocean'):
if provider=='digitalocean':
local('docker-machine create '
'--driver digitalocean '
'--digitalocean-region=ams2 '
'--digitalocean-size=1gb '
'--digitalocean-access-token={digital_ocean_token} '
'{host_name}'.format(digital_ocean_token=env.digital_ocean_token,
host_name=env.host_name))
# for gcloud, first install gcloud and do gcloud auth login
elif provider=='gcloud':
local('docker-machine create '
'--driver google '
'--google-project zapgo-1273 '
'--google-zone europe-west1-c '
'--google-machine-type n1-standard-1 '
'--google-disk-size 20 '
'--google-disk-type pd-standard '
'--google-username {user} '
'{host_name}'.format(host_name=env.host_name, user=env.user_name))
def add():
ip_address = local('docker-machine ip {host_name}'.format(host_name=env.host_name), capture=True)
keyfile = '~/.docker/machine/machines/{host_name}/id_rsa'.format(host_name=env.host_name)
ssh_config = env.ssh_config_template.format(
host_name=env.host_name,
ip=ip_address,
port=env.sshd_port,
user=env.user_name,
keyfile=keyfile,
)
local('echo "\nHost {host_name}\n\tHostName {ip}\n\tPort {ssh_port}\n\tUser {user}\n\tIdentityFile {keyfile}"'
'>> ~/.ssh/config'.format(host_name=env.host_name,
ip=ip_address,
ssh_port=env.sshd_port,
user=env.user_name,
keyfile=keyfile))
print(ssh_config)
env.ssh_config_template = """Host {host_name}
HostName {ip}
Port {port}
User {user}
IdentityFile {keyfile}
"""
def install(gcloud=True):
# Add user to sudo:
sudo('adduser {user} sudo'.format(user=env.user_name))
# Install Docker Compose:
sudo('curl -L '
'https://github.com/docker/compose/releases/download/{docker_compose_version}/'
'docker-compose-`uname -s`-`uname -m`'
' > /usr/local/bin/docker-compose'.format(docker_compose_version=env.docker_compose_version))
sudo('chmod +x /usr/local/bin/docker-compose')
# Add user to docker group:
sudo('gpasswd -a {user} docker'.format(user=env.user_name))
sudo('service docker restart')
# Create server directory structure:
sudo("mkdir -p /srv/certs /srv/config /srv/apps/default /srv/htdocs /srv/build")
sudo("chown -R %s:%s /srv/" % (env.user_name, env.user_name))
def gcloud():
sudo('export CLOUD_SDK_REPO="cloud-sdk-$(lsb_release -c -s)"')
run('echo "deb http://packages.cloud.google.com/apt $CLOUD_SDK_REPO main" | sudo tee -a /etc/apt/sources.list.d/google-cloud-sdk.list')
run('curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key add -')
run('sudo apt-get update && sudo apt-get install google-cloud-sdk')
def factory():
run('docker pull zapgo/wheel-factory')
with cd('/srv/build/'):
fp = 'docker-image-factory-master'
run('wget https://github.com/zapgo/docker-image-factory/archive/master.tar.gz')
run('tar -zxvf master.tar.gz '
'--strip=1'.format(fp=fp))
run('rm master.tar.gz') | mit |
HalcyonandHijinks/formBuilder | gulpfile.babel.js | 6867 | 'use strict';
import gulp from 'gulp';
import gulpPlugins from 'gulp-load-plugins';
import bsync from 'browser-sync';
import pkg from './package.json';
const files = pkg.config.files;
// Rather than manually defined each gulp plugin we need, gulpPlugins defines them for us.
var plugins = gulpPlugins(),
// for executing commands in the command line
exec = require('child_process').exec,
platform = process.platform,
/**
* Reusabled banner function for generated files.
*
* @return {stream} modified file back to the stream.
*/
banner = () => {
let buildDate = new Date();
let bannerTemplate = [
'/*',
'<%= pkg.name %> - <%= pkg.homepage %>',
'Version: <%= pkg.version %>',
'Author: <%= pkg.authors[0] %>',
'*/',
''
].join('\n');
return plugins.header(bannerTemplate, {
pkg: pkg,
now: buildDate
});
},
/**
* camelCase to hyphen-case renaming utility.
* Used when iterating though an object where the keys are used as filenames.
*
* @param {string} fileName
* @return {string} file-name
*/
rename = (fileName) => {
return String(fileName).replace(/([A-Z])/g, function($1) {
return '-' + $1.toLowerCase();
});
},
/**
* Opens the font-server defined in package.json
*
* @return {void} logs to terminal.
*/
fontEdit = () => {
let openFont = {
linux: `/opt/google/chrome/google-chrome --enable-plugins ${pkg.config.fontServer}/$(cat .fontello)`,
darwin: `open -a "Google Chrome" ${pkg.config.fontServer}/$(cat .fontello)`,
win32: `start chrome "${pkg.config.fontServer}/$(cat .fontello)"`
};
if (!openFont[platform]) {
return false;
}
// Connects to font server to get a fresh token for our editing session.
// sends current config in the process.
let getFontToken = `curl --silent --show-error --fail --output .fontello --form "config=@${files.formBuilder.fonts}/config.json" ${pkg.config.fontServer} \n`;
return exec(getFontToken + openFont[platform], function(err, stdout, stderr) {
console.log(stdout);
if (stderr) {
console.error(err, stderr);
}
});
},
/**
* Downloads and unpacks our updated font from the fontServer
*
* @return {void} logs operations to terminal.
*/
fontSave = () => {
var script = [
'if test ! $(which unzip); then echo "Unzip is installed"; exit 128; fi',
'rm -rf .fontello.src .fontello.zip',
`curl --silent --show-error --fail --output .fontello.zip ${pkg.config.fontServer}/$(cat .fontello)/get`,
'unzip .fontello.zip -d .fontello.src',
`rm -rf ${files.formBuilder.fonts}`,
`mv $(find ./.fontello.src -maxdepth 1 -name 'fontello-*') ${files.formBuilder.fonts}`,
'rm -rf .fontello.src .fontello.zip'
];
exec(script.join(' \n '), function(err, stdout, stderr) {
console.log(stdout);
return gulp.src([`${files.formBuilder.fonts}/css/form-builder-font.css`])
.pipe(plugins.base64())
.pipe(plugins.concat('_font.scss'))
.pipe(gulp.dest('src/sass/base/'));
if (stderr) {
console.error(err, stderr);
}
});
};
// Our watch task to monitor files for changes and run tasks when that change happens.
gulp.task('watch', function() {
gulp.watch(['src/**/*.js'], ['lint', 'js']);
gulp.watch('demo/index.html', bsync.reload);
gulp.watch('src/sass/*.scss', ['css']);
gulp.watch(files.demoSass, ['demoCss']);
});
// Compile the Sass to plain ol' css.
gulp.task('css', function() {
let sassFiles = new Map();
sassFiles.set('formBuilder', files.formBuilder.sass);
sassFiles.set('formRender', files.formRender.sass);
return sassFiles.forEach(function(sassFile, key) {
gulp.src(sassFile)
.pipe(plugins.sass())
.pipe(plugins.autoprefixer({
cascade: true
}))
.pipe(plugins.base64())
.pipe(banner())
.pipe(gulp.dest('demo/assets/css'))
.pipe(gulp.dest('dist/'))
.pipe(plugins.cssmin())
.pipe(banner())
.pipe(plugins.concat(rename(key) + '.min.css'))
.pipe(gulp.dest('demo/assets/css'))
.pipe(gulp.dest('dist/'))
.pipe(bsync.reload({
stream: true
}));
});
});
// Font editing tasks
gulp.task('font-edit', fontEdit);
gulp.task('font-save', fontSave);
// Demo specific css
gulp.task('demoCss', function() {
return gulp.src(files.demoSass)
.pipe(plugins.sass())
.pipe(plugins.autoprefixer({
cascade: true
}))
.pipe(plugins.cssmin())
.pipe(banner())
.pipe(gulp.dest('demo/assets/css'))
.pipe(bsync.reload({
stream: true
}));
});
// Stylish linting to ensure good JS
gulp.task('lint', function() {
let js = files.formBuilder.js.concat(files.formRender.js);
return gulp.src(js)
.pipe(plugins.jshint())
.pipe(plugins.jshint.reporter('jshint-stylish'));
});
// Compile the JS
gulp.task('js', function() {
let jsFiles = new Map();
jsFiles.set('formBuilder', files.formBuilder.js);
jsFiles.set('formRender', files.formRender.js);
return jsFiles.forEach(function(jsFileGlob, key) {
// Demo scripts
gulp.src(jsFileGlob)
.pipe(plugins.plumber({ errorHandler: false }))
.pipe(plugins.babel())
.pipe(plugins.concat(rename(key) + '.js'))
.pipe(banner())
.pipe(gulp.dest('demo/assets/js'));
// Demo scripts minified
gulp.src(jsFileGlob)
.pipe(plugins.plumber({ errorHandler: false }))
.pipe(plugins.sourcemaps.init())
.pipe(plugins.babel())
.pipe(plugins.concat(rename(key) + '.min.js'))
.pipe(plugins.uglify())
.pipe(banner())
.pipe(plugins.sourcemaps.write('/'))
.pipe(gulp.dest('demo/assets/js'));
// Plugin scripts
return gulp.src(jsFileGlob)
.pipe(plugins.plumber())
.pipe(plugins.babel())
.pipe(plugins.concat(rename(key) + '.js'))
.pipe(banner())
.pipe(gulp.dest('dist/'))
.pipe(plugins.uglify())
.pipe(banner())
.pipe(plugins.concat(rename(key) + '.min.js'))
.pipe(gulp.dest('dist/'))
.pipe(bsync.reload({
stream: true
}));
});
});
// BrowserSync server for local editing.
gulp.task('serve', function() {
bsync.init({
server: {
baseDir: './demo'
}
});
});
// Deploy the demo
gulp.task('deploy', () => {
var gitArgs = {
args: 'subtree push --prefix demo origin gh-pages'
};
plugins.git.exec(gitArgs, function(err) {
if (err) {
console.error('There was an error deploying the Demo to gh-pages.\n', err);
throw err;
} else {
console.log('Demo was successfully deployed!\n');
}
});
});
// Do a build after version bump to update all files.
gulp.task('build', ['js', 'css', 'demoCss']);
// Pretty self-explanatory
gulp.task('default', ['build', 'watch', 'serve']);
| mit |
plumer/codana | tomcat_files/6.0.0/StandardServiceMBean.java | 1989 | /*
* Copyright 1999,2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.catalina.mbeans;
import javax.management.MBeanException;
import javax.management.MBeanServer;
import javax.management.RuntimeOperationsException;
import org.apache.tomcat.util.modeler.BaseModelMBean;
/**
* <p>A <strong>ModelMBean</strong> implementation for the
* <code>org.apache.catalina.core.StandardService</code> component.</p>
*
* @author Amy Roh
* @version $Revision: 302726 $ $Date: 2004-02-27 15:59:07 +0100 (ven., 27 févr. 2004) $
*/
public class StandardServiceMBean extends BaseModelMBean {
/**
* The <code>MBeanServer</code> for this application.
*/
private static MBeanServer mserver = MBeanUtils.createServer();
// ----------------------------------------------------------- Constructors
/**
* Construct a <code>ModelMBean</code> with default
* <code>ModelMBeanInfo</code> information.
*
* @exception MBeanException if the initializer of an object
* throws an exception
* @exception RuntimeOperationsException if an IllegalArgumentException
* occurs
*/
public StandardServiceMBean()
throws MBeanException, RuntimeOperationsException {
super();
}
// ------------------------------------------------------------- Attributes
// ------------------------------------------------------------- Operations
}
| mit |
ofuangka/prop-messages | ui/src/app/app-routing.module.ts | 769 | import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { ConversationListComponent } from './conversation-list/conversation-list.component';
import { MessagesComponent } from './messages/messages.component';
import { PhoneCallComponent } from './phone-call/phone-call.component';
const routes: Routes = [
{ path: '', redirectTo: '/conversations', pathMatch: 'full' },
{ path: 'conversations', component: ConversationListComponent },
{ path: 'conversations/:conversationId', component: MessagesComponent },
{ path: 'phone-call/:conversationId', component: PhoneCallComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {
} | mit |
ProfilerTeam/Profiler | protected/vendors/Zend/CodeGenerator/Php/Method.php | 6300 | <?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_CodeGenerator
* @subpackage PHP
* @copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/**
* @see Zend_CodeGenerator_Php_Member_Abstract
*/
// require_once 'Zend/CodeGenerator/Php/Member/Abstract.php';
/**
* @see Zend_CodeGenerator_Php_Docblock
*/
// require_once 'Zend/CodeGenerator/Php/Docblock.php';
/**
* @see Zend_CodeGenerator_Php_Parameter
*/
// require_once 'Zend/CodeGenerator/Php/Parameter.php';
/**
* @category Zend
* @package Zend_CodeGenerator
* @copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_CodeGenerator_Php_Method extends Zend_CodeGenerator_Php_Member_Abstract
{
/**
* @var Zend_CodeGenerator_Php_Docblock
*/
protected $_docblock = null;
/**
* @var bool
*/
protected $_isFinal = false;
/**
* @var array
*/
protected $_parameters = array();
/**
* @var string
*/
protected $_body = null;
/**
* fromReflection()
*
* @param Zend_Reflection_Method $reflectionMethod
* @return Zend_CodeGenerator_Php_Method
*/
public static function fromReflection(Zend_Reflection_Method $reflectionMethod)
{
$method = new self();
$method->setSourceContent($reflectionMethod->getContents(false));
$method->setSourceDirty(false);
if ($reflectionMethod->getDocComment() != '') {
$method->setDocblock(Zend_CodeGenerator_Php_Docblock::fromReflection($reflectionMethod->getDocblock()));
}
$method->setFinal($reflectionMethod->isFinal());
if ($reflectionMethod->isPrivate()) {
$method->setVisibility(self::VISIBILITY_PRIVATE);
} elseif ($reflectionMethod->isProtected()) {
$method->setVisibility(self::VISIBILITY_PROTECTED);
} else {
$method->setVisibility(self::VISIBILITY_PUBLIC);
}
$method->setStatic($reflectionMethod->isStatic());
$method->setName($reflectionMethod->getName());
foreach ($reflectionMethod->getParameters() as $reflectionParameter) {
$method->setParameter(Zend_CodeGenerator_Php_Parameter::fromReflection($reflectionParameter));
}
$method->setBody($reflectionMethod->getBody());
return $method;
}
/**
* setFinal()
*
* @param bool $isFinal
*/
public function setFinal($isFinal)
{
$this->_isFinal = ($isFinal) ? true : false;
}
/**
* setParameters()
*
* @param array $parameters
* @return Zend_CodeGenerator_Php_Method
*/
public function setParameters(Array $parameters)
{
foreach ($parameters as $parameter) {
$this->setParameter($parameter);
}
return $this;
}
/**
* setParameter()
*
* @param Zend_CodeGenerator_Php_Parameter|array $parameter
* @return Zend_CodeGenerator_Php_Method
*/
public function setParameter($parameter)
{
if (is_array($parameter)) {
$parameter = new Zend_CodeGenerator_Php_Parameter($parameter);
$parameterName = $parameter->getName();
} elseif ($parameter instanceof Zend_CodeGenerator_Php_Parameter) {
$parameterName = $parameter->getName();
} else {
// require_once 'Zend/CodeGenerator/Php/Exception.php';
throw new Zend_CodeGenerator_Php_Exception('setParameter() expects either an array of method options or an instance of Zend_CodeGenerator_Php_Parameter');
}
$this->_parameters[$parameterName] = $parameter;
return $this;
}
/**
* getParameters()
*
* @return array Array of Zend_CodeGenerator_Php_Parameter
*/
public function getParameters()
{
return $this->_parameters;
}
/**
* setBody()
*
* @param string $body
* @return Zend_CodeGenerator_Php_Method
*/
public function setBody($body)
{
$this->_body = $body;
return $this;
}
/**
* getBody()
*
* @return string
*/
public function getBody()
{
return $this->_body;
}
/**
* generate()
*
* @return string
*/
public function generate()
{
$output = '';
$indent = $this->getIndentation();
if (($docblock = $this->getDocblock()) !== null) {
$docblock->setIndentation($indent);
$output .= $docblock->generate();
}
$output .= $indent;
if ($this->isAbstract()) {
$output .= 'abstract ';
} else {
$output .= (($this->isFinal()) ? 'final ' : '');
}
$output .= $this->getVisibility()
. (($this->isStatic()) ? ' static' : '')
. ' function ' . $this->getName() . '(';
$parameters = $this->getParameters();
if (!empty($parameters)) {
foreach ($parameters as $parameter) {
$parameterOuput[] = $parameter->generate();
}
$output .= implode(', ', $parameterOuput);
}
$output .= ')' . self::LINE_FEED . $indent . '{' . self::LINE_FEED;
if ($this->_body && $this->isSourceDirty()) {
$output .= ' '
. str_replace(self::LINE_FEED, self::LINE_FEED . $indent . $indent, trim($this->_body))
. self::LINE_FEED;
} elseif ($this->_body) {
$output .= $this->_body . self::LINE_FEED;
}
$output .= $indent . '}' . self::LINE_FEED;
return $output;
}
}
| mit |
Druwerd/http_mailer | spec/mandrill/mandrill_service_handler_spec.rb | 706 | require 'spec_helper'
describe HttpMailer::MandrillServiceHandler do
describe "#send_message" do
let(:settings){ {:host => "mandrillapp.com", :api_key => "1234567890"} }
let(:mailer){ HttpMailer::MandrillServiceHandler.new(settings) }
let(:from){ "papa@prose.com"}
let(:from_name){ "Ernest Hemingway"}
let(:to){ "jd@catcher.com" }
let(:to_name){ "JD Salinger"}
let(:subject){ "Hello" }
let(:email_body){ "Congratulations, you just sent an email with Mandrill! You are truly awesome!" }
it 'sends an email message' do
response = mailer.send_message(from, to, subject, email_body, from_name, to_name)
expect(response.code).to eq(200)
end
end
end | mit |
mark-rushakoff/influxdb | ui/src/variables/components/UpdateVariableOverlay.tsx | 7729 | // Libraries
import React, {PureComponent, FormEvent} from 'react'
import _ from 'lodash'
import {connect} from 'react-redux'
import {withRouter, WithRouterProps} from 'react-router'
// Components
import {
Form,
Input,
Button,
Grid,
Dropdown,
Columns,
Overlay,
} from '@influxdata/clockface'
import VariableArgumentsEditor from 'src/variables/components/VariableArgumentsEditor'
// Actions
import {updateVariable} from 'src/variables/actions'
// Utils
import {extractVariablesList} from 'src/variables/selectors'
// Constants
import {variableItemTypes} from 'src/variables/constants'
// Types
import {IVariable as Variable} from '@influxdata/influx'
import {
ButtonType,
ComponentColor,
ComponentStatus,
} from '@influxdata/clockface'
import {VariableArguments, AppState} from 'src/types'
interface State {
workingVariable: Variable
isNameValid: boolean
hasValidArgs: boolean
}
interface StateProps {
variables: Variable[]
startVariable: Variable
}
interface DispatchProps {
onUpdateVariable: typeof updateVariable
}
type Props = StateProps & DispatchProps & WithRouterProps
class UpdateVariableOverlay extends PureComponent<Props, State> {
public state: State = {
workingVariable: this.props.startVariable,
isNameValid: true,
hasValidArgs: true,
}
public render() {
const {workingVariable, hasValidArgs} = this.state
return (
<Overlay visible={true}>
<Overlay.Container maxWidth={1000}>
<Overlay.Header title="Edit Variable" onDismiss={this.handleClose} />
<Overlay.Body>
<Form onSubmit={this.handleSubmit}>
<Grid>
<Grid.Row>
<Grid.Column widthXS={Columns.Six}>
<div className="overlay-flux-editor--spacing">
<Form.Element
label="Name"
helpText="To rename your variable use the rename button. Renaming is not allowed here."
>
<Input
placeholder="Give your variable a name"
name="name"
autoFocus={true}
value={workingVariable.name}
status={ComponentStatus.Disabled}
/>
</Form.Element>
</div>
</Grid.Column>
<Grid.Column widthXS={Columns.Six}>
<Form.Element label="Type" required={true}>
<Dropdown
button={(active, onClick) => (
<Dropdown.Button active={active} onClick={onClick}>
{this.typeDropdownLabel}
</Dropdown.Button>
)}
menu={onCollapse => (
<Dropdown.Menu onCollapse={onCollapse}>
{variableItemTypes.map(v => (
<Dropdown.Item
key={v.type}
id={v.type}
value={v.type}
onClick={this.handleChangeType}
selected={
v.type === workingVariable.arguments.type
}
>
{v.label}
</Dropdown.Item>
))}
</Dropdown.Menu>
)}
/>
</Form.Element>
</Grid.Column>
</Grid.Row>
<Grid.Row>
<Grid.Column>
<VariableArgumentsEditor
onChange={this.handleChangeArgs}
onSelectMapDefault={this.handleSelectMapDefault}
selected={workingVariable.selected}
args={workingVariable.arguments}
/>
</Grid.Column>
</Grid.Row>
<Grid.Row>
<Grid.Column>
<Form.Footer>
<Button
text="Cancel"
color={ComponentColor.Danger}
onClick={this.handleClose}
/>
<Button
text="Submit"
type={ButtonType.Submit}
color={ComponentColor.Primary}
status={
hasValidArgs
? ComponentStatus.Default
: ComponentStatus.Disabled
}
/>
</Form.Footer>
</Grid.Column>
</Grid.Row>
</Grid>
</Form>
</Overlay.Body>
</Overlay.Container>
</Overlay>
)
}
private get typeDropdownLabel(): string {
const {workingVariable} = this.state
return variableItemTypes.find(
variable => variable.type === workingVariable.arguments.type
).label
}
private handleChangeType = (selectedType: string) => {
const {isNameValid, workingVariable} = this.state
const defaults = {hasValidArgs: false, isNameValid}
switch (selectedType) {
case 'query':
return this.setState({
...defaults,
workingVariable: {
...workingVariable,
arguments: {
type: 'query',
values: {
query: '',
language: 'flux',
},
},
selected: null,
},
})
case 'map':
return this.setState({
...defaults,
workingVariable: {
...workingVariable,
selected: null,
arguments: {
type: 'map',
values: {},
},
},
})
case 'constant':
return this.setState({
...defaults,
workingVariable: {
...workingVariable,
selected: null,
arguments: {
type: 'constant',
values: [],
},
},
})
}
}
private handleSelectMapDefault = (selected: string) => {
const {workingVariable} = this.state
this.setState({
workingVariable: {
...workingVariable,
selected: [selected],
},
})
}
private handleChangeArgs = ({
args,
isValid,
}: {
args: VariableArguments
isValid: boolean
}) => {
const {workingVariable} = this.state
this.setState({
workingVariable: {
...workingVariable,
arguments: args,
},
hasValidArgs: isValid,
})
}
private handleSubmit = (e: FormEvent): void => {
e.preventDefault()
const {workingVariable} = this.state
this.props.onUpdateVariable(workingVariable.id, workingVariable)
this.handleClose()
}
private handleClose = () => {
const {
router,
params: {orgID},
} = this.props
router.push(`/orgs/${orgID}/settings/variables`)
}
}
const mstp = (state: AppState, {params: {id}}: Props): StateProps => {
const variables = extractVariablesList(state)
const startVariable = variables.find(v => v.id === id)
return {variables, startVariable}
}
const mdtp: DispatchProps = {
onUpdateVariable: updateVariable,
}
export default withRouter(
connect<StateProps, DispatchProps>(
mstp,
mdtp
)(UpdateVariableOverlay)
)
| mit |
mattvv/hectorsharp | lib/Apache/Cassandra 0.6.0/InvalidRequestException.cs | 2166 | /**
* Autogenerated by Thrift
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Thrift;
using Thrift.Collections;
using Thrift.Protocol;
using Thrift.Transport;
namespace Apache.Cassandra
{
[Serializable]
public partial class InvalidRequestException : Exception, TBase
{
private string why;
public string Why
{
get
{
return why;
}
set
{
__isset.why = true;
this.why = value;
}
}
public Isset __isset;
[Serializable]
public struct Isset {
public bool why;
}
public InvalidRequestException() {
}
public void Read (TProtocol iprot)
{
TField field;
iprot.ReadStructBegin();
while (true)
{
field = iprot.ReadFieldBegin();
if (field.Type == TType.Stop) {
break;
}
switch (field.ID)
{
case 1:
if (field.Type == TType.String) {
this.why = iprot.ReadString();
this.__isset.why = true;
} else {
TProtocolUtil.Skip(iprot, field.Type);
}
break;
default:
TProtocolUtil.Skip(iprot, field.Type);
break;
}
iprot.ReadFieldEnd();
}
iprot.ReadStructEnd();
}
public void Write(TProtocol oprot) {
TStruct struc = new TStruct("InvalidRequestException");
oprot.WriteStructBegin(struc);
TField field = new TField();
if (this.why != null && __isset.why) {
field.Name = "why";
field.Type = TType.String;
field.ID = 1;
oprot.WriteFieldBegin(field);
oprot.WriteString(this.why);
oprot.WriteFieldEnd();
}
oprot.WriteFieldStop();
oprot.WriteStructEnd();
}
public override string ToString() {
StringBuilder sb = new StringBuilder("InvalidRequestException(");
sb.Append("why: ");
sb.Append(this.why);
sb.Append(")");
return sb.ToString();
}
}
}
| mit |
adaluo/SimonTan | RealEstate/app/listings/controllers.js | 1765 | /// <reference path="../_all.ts" />
'use strict';
var app;
(function (app) {
var listings;
(function (listings) {
var ListingsController = (function () {
function ListingsController(scope, accountService, logger, location, NotifyingCache, $i18next) {
var self = this;
self.logger = logger;
self.location = location;
self.notifyingCache = NotifyingCache;
self.i18next = $i18next;
self.items = [{ id: "1" }, { id: "2" }, { id: "3" }, { id: "4" }, { id: "5" }, { id: "6" }];
}
ListingsController.$inject = ['$scope', 'accountService', 'logger', '$location', 'NotifyingCache', '$i18next'];
return ListingsController;
})();
listings.ListingsController = ListingsController;
var ListingController = (function () {
function ListingController(scope, accountService, logger, location, NotifyingCache, $i18next) {
var self = this;
self.logger = logger;
self.location = location;
self.notifyingCache = NotifyingCache;
self.i18next = $i18next;
}
ListingController.$inject = ['$scope', 'accountService', 'logger', '$location', 'NotifyingCache', '$i18next'];
return ListingController;
})();
listings.ListingController = ListingController;
})(listings = app.listings || (app.listings = {}));
})(app || (app = {}));
angular.module('app.listings').controller('listingsController', app.listings.ListingsController);
angular.module('app.listings').controller('listingController', app.listings.ListingController);
//# sourceMappingURL=controllers.js.map | mit |
ivaylokanov/Java_OOP_Basics | c_inheritance/c_inheritance-lab/src/pr04_fragileBaseClass/Food.java | 54 | package pr04_fragileBaseClass;
public class Food {
}
| mit |
jesjens/jesdob | src/se/jesjens/jesdob/query/condition/HasNotAttributeCondition.java | 2085 | /**
* Copyright (C) 2012 - 2013 Jens Stääf
*
* JeSDOb (Jens Simple Dynamic Objects)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package se.jesjens.jesdob.query.condition;
import se.jesjens.jesdob.IDob;
/**
* Condition for checking if an IDob lacks a specific attribute or not.
*
* @author jenss
*/
public class HasNotAttributeCondition implements ICondition {
private final String attribute;
/**
* Constructor.
*
* @param attribute The attribute we want to check for.
*/
public HasNotAttributeCondition(String attribute) {
this.attribute = attribute;
}
/**
* This Condition will check if a Dob lacks a specific attribute or not.
*
* If the dob has the attribute, the condition will return false.
* If the dob has not the attribute, the condition will return true.
*
* @param dob The IDob to test.
* @return True or false, depending on if the condition is true for the
* IDob-object or not.
*/
@Override
public boolean isTrue(IDob dob) {
return !dob.hasAttr(attribute);
}
}
| mit |
dmsovetov/relight | src/relight/baker/IndirectLight.cpp | 2864 | /**************************************************************************
The MIT License (MIT)
Copyright (c) 2015 Dmitry Sovetov
https://github.com/dmsovetov
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 "../BuildCheck.h"
#include "IndirectLight.h"
#include "../Lightmap.h"
#include "../scene/Scene.h"
#include "../scene/Mesh.h"
#include "../rt/Tracer.h"
namespace relight {
namespace bake {
// ** IndirectLight::IndirectLight
IndirectLight::IndirectLight( const Scene* scene, Progress* progress, BakeIterator* iterator, int samples, float maxDistance, int radius, const Rgb& skyColor, const Rgb& ambientColor )
: Baker( scene, progress, iterator ), m_samples( samples ), m_maxDistance( maxDistance ), m_radius( radius ), m_skyColor( skyColor ), m_ambientColor( ambientColor )
{
}
// ** IndirectLight::bakeLumel
void IndirectLight::bakeLumel( Lumel& lumel )
{
Rgb gathered( 0, 0, 0 );
rt::ITracer* tracer = m_scene->tracer();
for( int k = 0; k < m_samples; k++ ) {
Vec3 dir = Vec3::randomHemisphereDirection( lumel.m_normal );
float influence = max2( lumel.m_normal * dir, 0.0f );
DC_BREAK_IF( influence > 1.0f );
rt::Hit hit = tracer->traceSegment( lumel.m_position, lumel.m_position + dir * m_maxDistance, rt::HitUv | rt::HitNormal );
if( !hit ) {
gathered += m_skyColor * influence + m_ambientColor;
continue;
}
if( dir * hit.m_normal >= 0.0f ) {
continue;
}
if( const Photonmap* photons = hit.m_mesh->photonmap() ) {
gathered += photons->lumel( hit.m_uv ).m_gathered * influence + m_ambientColor;
}
}
lumel.m_color += gathered / static_cast<float>( m_samples );
}
} // namespace bake
} // namespace relight | mit |
kushniryb/minfraud-api-v2 | lib/minfraud/model/email.rb | 1689 | # frozen_string_literal: true
require 'minfraud/model/abstract'
require 'minfraud/model/email_domain'
module Minfraud
module Model
# Model containing information about the email address.
class Email < Abstract
# An object containing information about the email domain.
#
# @return [Minfraud::Model::EmailDomain]
attr_reader :domain
# A date string (e.g. 2017-04-24) to identify the date an email address
# was first seen by MaxMind. This is expressed using the ISO 8601 date
# format.
#
# @return [String, nil]
attr_reader :first_seen
# Whether this email address is from a disposable email provider. The
# value will be nil when no email address or email domain has been passed
# as an input.
#
# @return [Boolean, nil]
attr_reader :is_disposable
# This property is true if MaxMind believes that this email is hosted by
# a free email provider such as Gmail or Yahoo! Mail.
#
# @return [Boolean, nil]
attr_reader :is_free
# This field is true if MaxMind believes that this email is likely to be
# used for fraud. Note that this is also factored into the overall
# risk_score in the response as well.
#
# @return [Boolean, nil]
attr_reader :is_high_risk
# @!visibility private
def initialize(record)
super(record)
@domain = Minfraud::Model::EmailDomain.new(get('domain'))
@first_seen = get('first_seen')
@is_disposable = get('is_disposable')
@is_free = get('is_free')
@is_high_risk = get('is_high_risk')
end
end
end
end
| mit |
Catgov/12_whitehall | test/test_helper.rb | 6180 | $:.unshift(File.dirname(__FILE__))
ENV["RAILS_ENV"] = "test"
require File.expand_path('../../config/environment', __FILE__)
if ENV["TEST_COVERAGE"]
Bundler.require(:test_coverage)
SimpleCov.start 'rails'
SimpleCov.formatter = SimpleCov::Formatter::RcovFormatter
end
require 'rails/test_help'
require 'mocha/setup'
require 'slimmer/test'
require 'factories'
require 'webmock/minitest'
require 'whitehall/not_quite_as_fake_search'
require 'sidekiq/testing/inline'
require 'govuk-content-schema-test-helpers/test_unit'
Dir[Rails.root.join('test/support/*.rb')].each { |f| require f }
Mocha::Configuration.prevent(:stubbing_non_existent_method)
GovukContentSchemaTestHelpers.configure do |config|
config.schema_type = 'publisher'
config.project_root = Rails.root
end
class ActiveSupport::TestCase
include FactoryGirl::Syntax::Methods
include ModelHelpers
include ModelStubbingHelpers
include HtmlAssertions
include I18nHelpers
include PanopticonTestHelpers
include PublishingApiTestHelpers
include GovukContentSchemaTestHelpers::TestUnit
extend GovspeakValidationTestHelper
setup do
Timecop.freeze(2011, 11, 11, 11, 11, 11)
Whitehall.search_backend = Whitehall::DocumentFilter::FakeSearch
VirusScanHelpers.erase_test_files
Sidekiq::Worker.clear_all
fake_whodunnit = FactoryGirl.build(:user)
fake_whodunnit.stubs(:id).returns(1000)
fake_whodunnit.stubs(:persisted?).returns(true)
Edition::AuditTrail.whodunnit = fake_whodunnit
end
teardown do
Edition::AuditTrail.whodunnit = nil
Timecop.return
end
def acting_as(actor, &block)
Edition::AuditTrail.acting_as(actor, &block)
end
def assert_same_elements(array1, array2)
assert_equal array1.to_set, array2.to_set, "Different elements in #{array1.inspect} and #{array2}.inspect"
end
def assert_all_requested(array)
array.each { |request| assert_requested request }
end
def count_queries
count = 0
subscriber = ActiveSupport::Notifications.subscribe("sql.active_record") do |*args|
count = count + 1
end
yield
count
ensure
ActiveSupport::Notifications.unsubscribe(subscriber)
end
def with_service(service_name, service, &block)
original_service = Whitehall.send(service_name)
Whitehall.send(:"#{service_name}=", service)
yield
ensure
Whitehall.send(:"#{service_name}=", original_service)
end
def with_content_api(content_api, &block)
with_service(:content_api, content_api, &block)
end
def routes_helper
@routes_helper ||= Whitehall::UrlMaker.new
end
def self.disable_database_queries
setup do
ActiveRecord::Base.connection.expects(:select).never
end
end
def self.class_for(document_type)
document_type.to_s.classify.constantize
end
def self.class_from_test_name
name.sub(/Test$/, '').constantize
end
def self.factory_name_from_test
name.sub(/Test$/, '').underscore.to_sym
end
def self.with_not_quite_as_fake_search
setup do
Whitehall::NotQuiteAsFakeSearch.stop_faking_it_quite_so_much!
end
teardown do
Whitehall::NotQuiteAsFakeSearch.start_faking_it_again!
end
end
def class_from_test_name
self.class.class_from_test_name
end
def factory_name_from_test
self.class.factory_name_from_test
end
def file_fixture(filename)
File.new(Rails.root.join('test/fixtures', filename))
end
def assert_file_content_identical(file1, file2)
FileUtils.compare_file(file1.path, file2.path)
end
def publish(edition)
publisher = EditionPublisher.new(edition)
unless publisher.perform!
raise "Could not publish edition: #{publisher.failure_reason}"
end
end
def force_publish(edition)
publisher = EditionForcePublisher.new(edition)
unless publisher.perform!
raise "Could not force publish edition: #{publisher.failure_reason}"
end
end
end
class ActionController::TestCase
include HtmlAssertions
include AdminControllerTestHelpers
include AdminEditionControllerTestHelpers
include AdminEditionControllerScheduledPublishingTestHelpers
include AdminEditionWorldLocationsBehaviour
include DocumentControllerTestHelpers
include ControllerTestHelpers
include ResourceTestHelpers
include AtomTestHelpers
include CacheControlTestHelpers
include ViewRendering
include ContentRegisterHelpers
include PublicDocumentRoutesHelper
include Admin::EditionRoutesHelper
attr_reader :current_user
setup do
request.env['warden'] = stub(authenticate!: false, authenticated?: false, user: nil)
stub_content_register_policies
stub_any_publishing_api_call
end
def login_as(role_or_user)
@current_user = role_or_user.is_a?(Symbol) ? create(role_or_user) : role_or_user
request.env['warden'] = stub(authenticate!: true, authenticated?: true, user: @current_user)
@previous_papertrail_whodunnit ||= Edition::AuditTrail.whodunnit
Edition::AuditTrail.whodunnit = @current_user
@current_user
end
def login_as_admin
login_as(create(:user, name: "user-name", email: "user@example.com"))
end
def assert_login_required
assert_redirected_to login_path
end
def json_response
ActiveSupport::JSON.decode(response.body)
end
end
class ActionDispatch::IntegrationTest
def login_as(user)
GDS::SSO.test_user = user
end
def login_as_admin
login_as(create(:user, name: "user-name", email: "user@example.com"))
end
teardown do
GDS::SSO.test_user = nil
end
end
class ActionMailer::TestCase
def self.enable_url_helpers
# See http://jakegoulding.com/blog/2011/02/26/using-named-routes-in-actionmailer-tests-with-rails-3/
include Rails.application.routes.url_helpers
Rails.application.routes.default_url_options[:host] = "example.com"
def default_url_options
Rails.application.routes.default_url_options
end
end
end
class ActionView::TestCase
def setup_view_context
@view_context = @controller.view_context
end
end
class PresenterTestCase < ActionView::TestCase
disable_database_queries
setup :setup_view_context
def stubs_helper_method(*args)
@view_context.stubs(*args)
end
end
| mit |
getcanal/boat | docs/src/components/app-marked/app-marked.tsx | 397 | import { Component, Prop, State } from '@stencil/core';
@Component({
tag: 'app-marked',
})
export class AppMarked {
@Prop() doc: any;
@State() content: any;
ionViewWillLoad() {
fetch(`/docs-content/${this.doc}`)
.then(response => response.text())
.then(data => this.content = data)
}
render() {
return (
<div innerHTML={this.content}>
</div>
)
}
}
| mit |
razsilev/TelerikAcademy_Homework | High-Quality_Code/21_Mocking with Moq and JustMock/Mocking with Moq and JustMock-Demos/Cars.Tests.JustMock/Mocks/JustMockCarsRepository.cs | 1255 | namespace Cars.Tests.JustMock.Mocks
{
using Cars.Contracts;
using Cars.Models;
using System.Linq;
using Telerik.JustMock;
public class JustMockCarsRepository : CarRepositoryMock, ICarsRepositoryMock
{
protected override void ArrangeCarsRepositoryMock()
{
this.CarsData = Mock.Create<ICarsRepository>();
Mock.Arrange(() => this.CarsData.Add(Arg.IsAny<Car>())).DoNothing();
Mock.Arrange(() => this.CarsData.All()).Returns(this.FakeCarCollection);
Mock.Arrange(() => this.CarsData.Search(Arg.AnyString)).Returns(this.FakeCarCollection.Where(c => c.Make == "BMW").ToList());
Mock.Arrange(() => this.CarsData.GetById(Arg.Matches<int>(id => id != -1))).Returns(this.FakeCarCollection.First());
Mock.Arrange(() => this.CarsData.GetById(Arg.Matches<int>(id => id == -1))).Returns((Car)null);
// add sort
Mock.Arrange(() => this.CarsData.SortedByMake()).Returns(this.FakeCarCollection);
Mock.Arrange(() => this.CarsData.SortedByYear()).Returns(this.FakeCarCollection.OrderBy(c => c.Year).ToList());
Mock.Arrange(() => this.CarsData.TotalCars).Returns(this.FakeCarCollection.Count);
}
}
}
| mit |
rezoh/Skeleton-Stylus | gulpfile.js | 515 | var gulp = require('gulp');
var stylus = require('gulp-stylus');
var sourcemaps = require('gulp-sourcemaps');
var skeletonStyl = './stylus/skeleton.styl';
gulp.task('stylus', function () {
gulp.src(skeletonStyl)
.pipe(sourcemaps.init())
.pipe(stylus({
compress: true
}))
.pipe(sourcemaps.write('./sourcemap'))
.pipe(gulp.dest('./css'));
});
gulp.task('watch', function () {
gulp.watch(skeletonStyl, function () {
gulp.run('stylus');
});
}); | mit |
jodier/tmpdddf | web/private/tine20/library/Zend/OpenId/Extension/Sreg.php | 8982 | <?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_OpenId
* @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Sreg.php 10020 2009-08-18 14:34:09Z j.fischer@metaways.de $
*/
/**
* @see Zend_OpenId_Extension
*/
require_once "Zend/OpenId/Extension.php";
/**
* 'Simple Refistration Extension' for Zend_OpenId
*
* @category Zend
* @package Zend_OpenId
* @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_OpenId_Extension_Sreg extends Zend_OpenId_Extension
{
/**
* SREG 1.1 namespace. All OpenID SREG 1.1 messages MUST contain variable
* openid.ns.sreg with its value.
*/
const NAMESPACE_1_1 = "http://openid.net/extensions/sreg/1.1";
private $_props;
private $_policy_url;
private $_version;
/**
* Creates SREG extension object
*
* @param array $props associative array of SREG variables
* @param string $policy_url SREG policy URL
* @param float $version SREG version
* @return array
*/
public function __construct(array $props=null, $policy_url=null, $version=1.0)
{
$this->_props = $props;
$this->_policy_url = $policy_url;
$this->_version = $version;
}
/**
* Returns associative array of SREG variables
*
* @return array
*/
public function getProperties() {
if (is_array($this->_props)) {
return $this->_props;
} else {
return array();
}
}
/**
* Returns SREG policy URL
*
* @return string
*/
public function getPolicyUrl() {
return $this->_policy_url;
}
/**
* Returns SREG protocol version
*
* @return float
*/
public function getVersion() {
return $this->_version;
}
/**
* Returns array of allowed SREG variable names.
*
* @return array
*/
public static function getSregProperties()
{
return array(
"nickname",
"email",
"fullname",
"dob",
"gender",
"postcode",
"country",
"language",
"timezone"
);
}
/**
* Adds additional SREG data to OpenId 'checkid_immediate' or
* 'checkid_setup' request.
*
* @param array &$params request's var/val pairs
* @return bool
*/
public function prepareRequest(&$params)
{
if (is_array($this->_props) && count($this->_props) > 0) {
foreach ($this->_props as $prop => $req) {
if ($req) {
if (isset($required)) {
$required .= ','.$prop;
} else {
$required = $prop;
}
} else {
if (isset($optional)) {
$optional .= ','.$prop;
} else {
$optional = $prop;
}
}
}
if ($this->_version >= 1.1) {
$params['openid.ns.sreg'] = Zend_OpenId_Extension_Sreg::NAMESPACE_1_1;
}
if (!empty($required)) {
$params['openid.sreg.required'] = $required;
}
if (!empty($optional)) {
$params['openid.sreg.optional'] = $optional;
}
if (!empty($this->_policy_url)) {
$params['openid.sreg.policy_url'] = $this->_policy_url;
}
}
return true;
}
/**
* Parses OpenId 'checkid_immediate' or 'checkid_setup' request,
* extracts SREG variables and sets ovject properties to corresponding
* values.
*
* @param array $params request's var/val pairs
* @return bool
*/
public function parseRequest($params)
{
if (isset($params['openid_ns_sreg']) &&
$params['openid_ns_sreg'] === Zend_OpenId_Extension_Sreg::NAMESPACE_1_1) {
$this->_version= 1.1;
} else {
$this->_version= 1.0;
}
if (!empty($params['openid_sreg_policy_url'])) {
$this->_policy_url = $params['openid_sreg_policy_url'];
} else {
$this->_policy_url = null;
}
$props = array();
if (!empty($params['openid_sreg_optional'])) {
foreach (explode(',', $params['openid_sreg_optional']) as $prop) {
$prop = trim($prop);
$props[$prop] = false;
}
}
if (!empty($params['openid_sreg_required'])) {
foreach (explode(',', $params['openid_sreg_required']) as $prop) {
$prop = trim($prop);
$props[$prop] = true;
}
}
$props2 = array();
foreach (self::getSregProperties() as $prop) {
if (isset($props[$prop])) {
$props2[$prop] = $props[$prop];
}
}
$this->_props = (count($props2) > 0) ? $props2 : null;
return true;
}
/**
* Adds additional SREG data to OpenId 'id_res' response.
*
* @param array &$params response's var/val pairs
* @return bool
*/
public function prepareResponse(&$params)
{
if (is_array($this->_props) && count($this->_props) > 0) {
if ($this->_version >= 1.1) {
$params['openid.ns.sreg'] = Zend_OpenId_Extension_Sreg::NAMESPACE_1_1;
}
foreach (self::getSregProperties() as $prop) {
if (!empty($this->_props[$prop])) {
$params['openid.sreg.' . $prop] = $this->_props[$prop];
}
}
}
return true;
}
/**
* Parses OpenId 'id_res' response and sets object's properties according
* to 'openid.sreg.*' variables in response
*
* @param array $params response's var/val pairs
* @return bool
*/
public function parseResponse($params)
{
if (isset($params['openid_ns_sreg']) &&
$params['openid_ns_sreg'] === Zend_OpenId_Extension_Sreg::NAMESPACE_1_1) {
$this->_version= 1.1;
} else {
$this->_version= 1.0;
}
$props = array();
foreach (self::getSregProperties() as $prop) {
if (!empty($params['openid_sreg_' . $prop])) {
$props[$prop] = $params['openid_sreg_' . $prop];
}
}
if (isset($this->_props) && is_array($this->_props)) {
foreach (self::getSregProperties() as $prop) {
if (isset($this->_props[$prop]) &&
$this->_props[$prop] &&
!isset($props[$prop])) {
return false;
}
}
}
$this->_props = (count($props) > 0) ? $props : null;
return true;
}
/**
* Addes SREG properties that are allowed to be send to consumer to
* the given $data argument.
*
* @param array &$data data to be stored in tusted servers database
* @return bool
*/
public function getTrustData(&$data)
{
$data[get_class()] = $this->getProperties();
return true;
}
/**
* Check if given $data contains necessury SREG properties to sutisfy
* OpenId request. On success sets SREG response properties from given
* $data and returns true, on failure returns false.
*
* @param array $data data from tusted servers database
* @return bool
*/
public function checkTrustData($data)
{
if (is_array($this->_props) && count($this->_props) > 0) {
$props = array();
$name = get_class();
if (isset($data[$name])) {
$props = $data[$name];
} else {
$props = array();
}
$props2 = array();
foreach ($this->_props as $prop => $req) {
if (empty($props[$prop])) {
if ($req) {
return false;
}
} else {
$props2[$prop] = $props[$prop];
}
}
$this->_props = (count($props2) > 0) ? $props2 : null;
}
return true;
}
}
| mit |
duivvv/points-to-vertices | __tests__/pointToVertex.test.js | 3907 | import pointToVertex from '../src/lib/pointToVertex';
describe(`returns the correct values`, () => {
it(`returns correct vertices (x, y, z)`, () => {
const point = {
x: 1,
y: 1,
z: 1
};
expect(pointToVertex(point, {color: false}))
.toEqual([1, 1, 1]);
});
it(`returns correct vertices (x, y, z, hex)`, () => {
const point = {
x: 1,
y: - 1,
z: 1,
color: `#0000FF`
};
expect(pointToVertex(point))
.toEqual([1, - 1, 1, 0, 0, 1, 1]);
});
it(`returns correct vertices (x, y, z, rgba)`, () => {
const point = {
x: - 1,
y: - 1,
z: - 1,
color: `rgba(255, 255, 0, .4)`
};
expect(pointToVertex(point))
.toEqual([- 1, - 1, - 1, 1, 1, 0, 0.4]);
});
it(`returns correct vertices (x, y, z, rgb)`, () => {
const point = {
x: 1,
y: - 1,
z: 1,
color: `rgb(0, 255, 0)`
};
expect(pointToVertex(point))
.toEqual([1, - 1, 1, 0, 1, 0, 1]);
});
});
describe(`uses correct defaults`, () => {
it(`defaults to the standard x (0)`, () => {
const point = {
y: 1,
z: 0
};
expect(pointToVertex(point, {color: false}))
.toEqual([0, 1, 0]);
});
it(`defaults to the standard y (0)`, () => {
const point = {
x: 0,
z: 0
};
expect(pointToVertex(point, {color: false}))
.toEqual([0, 0, 0]);
});
it(`defaults to the standard z (0)`, () => {
const point = {
x: 1,
y: 1
};
expect(pointToVertex(point, {color: false}))
.toEqual([1, 1, 0]);
});
it(`defaults to the standard color [0, 0, 0, 1]`, () => {
const point = {
x: 1,
y: 1,
z: 1
};
expect(pointToVertex(point))
.toEqual([1, 1, 1, 0, 0, 0, 1]);
});
});
describe(`normalizes points`, () => {
it(`normalizes negative x`, () => {
const point = {
x: - 2
};
expect(pointToVertex(point, {color: false}))
.toEqual([- 1, 0, 0]);
});
it(`normalizes positive x`, () => {
const point = {
x: 2
};
expect(pointToVertex(point, {color: false}))
.toEqual([1, 0, 0]);
});
it(`normalizes negative y`, () => {
const point = {
y: - 2
};
expect(pointToVertex(point, {color: false}))
.toEqual([0, - 1, 0]);
});
it(`normalizes positive y`, () => {
const point = {
y: 2
};
expect(pointToVertex(point, {color: false}))
.toEqual([0, 1, 0]);
});
it(`normalizes negative z`, () => {
const point = {
z: - 2
};
expect(pointToVertex(point, {color: false}))
.toEqual([0, 0, - 1]);
});
it(`normalizes positive z`, () => {
const point = {
z: 2
};
expect(pointToVertex(point, {color: false}))
.toEqual([0, 0, 1]);
});
});
describe(`uses correct defaults (user provided)`, () => {
it(`defaults to given x: 1`, () => {
const point = {
y: 1,
z: 0
};
expect(pointToVertex(point, {dx: 1, color: false}))
.toEqual([1, 1, 0]);
});
it(`defaults to y: -1`, () => {
const point = {
x: 1,
z: 0
};
expect(pointToVertex(point, {dy: - 1, color: false}))
.toEqual([1, - 1, 0]);
});
it(`defaults to z: 1`, () => {
const point = {
x: 1,
y: 1
};
expect(pointToVertex(point, {dz: 1, color: false}))
.toEqual([1, 1, 1]);
});
it(`defaults to color: #FF00FF`, () => {
const point = {
x: - 1,
y: 1,
z: 0
};
expect(pointToVertex(point, {dcolor: `#FF00FF`}))
.toEqual([- 1, 1, 0, 1, 0, 1, 1]);
});
it(`defaults to color: rgba(255, 0, 0, 0.4)`, () => {
const point = {
x: - 1,
y: 1,
z: 0
};
expect(pointToVertex(point, {dcolor: `rgba(255, 0, 0, 0.4)`}))
.toEqual([- 1, 1, 0, 1, 0, 0, 0.4]);
});
});
| mit |
bit0001/trajectory_tracking | src/twist.py | 400 | #!/usr/bin/env python
import rospy
from geometry_msgs.msg import Twist
publisher = None
def send_computed_control_actions(msg):
publisher.publish(msg)
if __name__ == '__main__':
rospy.init_node('twist')
subscriber = rospy.Subscriber('computed_control_actions', Twist, send_computed_control_actions)
publisher = rospy.Publisher('cmd_vel', Twist, queue_size=1)
rospy.spin()
| mit |
nodule/react-material-ui | AvMovie.js | 357 | module.exports = {
description: "",
ns: "react-material-ui",
type: "ReactNode",
dependencies: {
npm: {
"material-ui/svg-icons/av/movie": require('material-ui/svg-icons/av/movie')
}
},
name: "AvMovie",
ports: {
input: {},
output: {
component: {
title: "AvMovie",
type: "Component"
}
}
}
} | mit |
GNOME/mistelix | src/Core/XmlStorage.cs | 4736 | //
// Copyright (C) 2008-2009 Jordi Mas i Hernandez, jmas@softcatala.org
//
// 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.IO;
using System.Xml;
using System.Xml.Serialization;
using System.Collections.Generic;
using System.Collections;
using Mistelix.DataModel;
namespace Mistelix.Core
{
//
// Creates an XML to serialize objects
//
// The XML has the following format
//
// <?xml version="1.0"?>
// <rootelement>
// <object1> </object1>
// <object2> </object2>
// ...
// </rootelement>
//
//
public class XmlStorage
{
public XmlDocument xml_document;
public XmlStorage ()
{
xml_document = new XmlDocument ();
}
public void New (string rootNode)
{
xml_document.LoadXml ("<" + rootNode + "/>");
XmlDeclaration xmldecl = xml_document.CreateXmlDeclaration ("1.0", null, null);
XmlElement root = xml_document.DocumentElement;
xml_document.InsertBefore (xmldecl, root);
}
public void Load (string file)
{
try {
xml_document.Load (file);
}
catch (Exception e) {
Logger.Error (e.Message);
}
}
public void Save (string file)
{
xml_document.Save (file);
}
// Adds an element from the root document element
public void Add <T> (T item)
{
SetFromNode (item, xml_document.DocumentElement);
}
// Adds an element encapsulated in given node name
public void Add <T> (T item, string from_node)
{
Logger.Debug ("XmlStorage.Add. From node_name {0} {1}", item, from_node);
XmlNode new_node = xml_document.CreateElement (from_node);
XmlNode root = xml_document.DocumentElement;
root.AppendChild (new_node);
SetFromNode (item, new_node);
}
// Gets an element from the root document element
public bool Get <T> (ref T item)
{
XmlNode root;
string typename;
if (xml_document.ChildNodes.Count < 2)
return false;
root = xml_document.ChildNodes [1]; // <root> element
typename = GetTypeNodeName <T> (item);
foreach (XmlNode node in root.ChildNodes)
{
if (typename.Equals (node.Name) == false)
continue;
GetFromNode <T> (root, ref item);
return true;
}
return false;
}
public bool Get <T> (string from_node, ref T item)
{
XmlNode root;
Logger.Debug ("XmlStorage.Get. From node {0}", from_node);
if (xml_document.ChildNodes.Count < 2)
return false;
root = xml_document.ChildNodes [1]; // <root> element
foreach (XmlNode node in root.ChildNodes)
{
if (from_node.Equals (node.Name) == false)
continue;
GetFromNode <T> (node, ref item);
return true;
}
return false;
}
void SetFromNode <T> (T item, XmlNode from_node)
{
XmlSerializer bf = new XmlSerializer (typeof (T));
StringWriter writer = new StringWriter ();
bf.Serialize (writer, item);
XmlDocumentFragment fragment = xml_document.CreateDocumentFragment ();
fragment.InnerXml = writer.ToString ();
writer.Close ();
from_node.AppendChild (fragment);
}
// Obtains the node name used to serialize a item
string GetTypeNodeName <T> (T item)
{
XmlSerializer serializer = new XmlSerializer (typeof (T));
StringWriter writer = new StringWriter ();
serializer.Serialize (writer, item);
XmlDocumentFragment fragment = xml_document.CreateDocumentFragment ();
fragment.InnerXml = writer.ToString ();
writer.Close ();
return fragment.ChildNodes[0].Name;
}
public bool GetFromNode <T> (XmlNode from_node, ref T item)
{
XmlSerializer serializer = new XmlSerializer (typeof (T));
StringReader reader = new StringReader (from_node.InnerXml);
item = (T) serializer.Deserialize (reader);
reader.Close ();
return true;
}
}
}
| mit |
takkkun/langue-japanese | spec/langue/japanese/language_spec.rb | 4335 | require 'spec_helper'
require 'langue/japanese/language'
describe Langue::Japanese::Language do
it 'is an instance of Class' do
described_class.should be_an_instance_of(Class)
end
it 'extends Langue::Language' do
described_class.superclass.should == Langue::Language
end
end
describe Langue::Japanese::Language, '#parser' do
before do
@language = described_class.new(:key => 'value')
end
it 'calls Langue::Japanese::Parser.new with the options' do
parser_stub
Langue::Japanese::Parser.should_receive(:new).with(:key => 'value')
@language.parser
end
it 'returns an instance of Langue::Japanese::Parser' do
parser = parser_stub
@language.parser.should == parser
end
end
describe Langue::Japanese::Language, '#shaper' do
before do
@language = described_class.new(:key => 'value')
end
it 'calls Langue::Japanese::Shaper.new with the options' do
shaper_stub
Langue::Japanese::Shaper.should_receive(:new).with(:key => 'value')
@language.shaper
end
it 'returns an instance of Langue::Japanese::Shaper' do
shaper = shaper_stub
@language.shaper.should == shaper
end
end
describe Langue::Japanese::Language, '#structurer' do
before do
@language = described_class.new(:key => 'value')
end
it 'calls Langue::Japanese::Structurer.new with the options' do
structurer_stub
Langue::Japanese::Structurer.should_receive(:new).with(:key => 'value')
@language.structurer
end
it 'returns an instance of Langue::Japanese::Structurer' do
structurer = structurer_stub
@language.structurer.should == structurer
end
end
describe Langue::Japanese::Language, '#inflector' do
before do
@language = described_class.new(:key => 'value')
end
it 'calls Langue::Japanese::Inflector.new with the options' do
inflector_stub
Langue::Japanese::Inflector.should_receive(:new).with(:key => 'value')
@language.inflector
end
it 'returns an instance of Langue::Japanese::Inflector' do
inflector = inflector_stub
@language.inflector.should == inflector
end
end
describe Langue::Japanese::Language, '#parse' do
before do
@language = described_class.new(:key => 'value')
end
it 'calls parse method of parser with a text' do
parser_stub do |m|
m.should_receive(:parse).with('text')
end
@language.parse('text')
end
it 'returns the value returning from Langue::Japanese::Parser#parse' do
parser_stub
@language.parse('text').should == 'value returning from parse method'
end
end
describe Langue::Japanese::Language, '#shape_person_name' do
before do
@language = described_class.new(:key => 'value')
end
it 'calls shape_person_name method of shaper with morphemes' do
shaper_stub do |m|
m.should_receive(:shape_person_name).with('morphemes', 'Akane')
end
@language.shape_person_name('morphemes', 'Akane')
end
it 'returns the value returning from Langue::Japanese::Shaper#shape_person_name' do
shaper_stub
@language.shape_person_name('morphemes', 'Akane').should == 'value returning from shape_person_name method'
end
end
describe Langue::Japanese::Language, '#structure' do
before do
@language = described_class.new(:key => 'value')
end
it 'calls structure method of structurer with morphemes' do
structurer_stub do |m|
m.should_receive(:structure).with('morphemes')
end
@language.structure('morphemes')
end
it 'returns the value returning from Langue::Japanese::Structurer#structure' do
structurer_stub
@language.structure('morphemes').should == 'value returning from structure method'
end
end
describe Langue::Japanese::Language, '#inflect' do
before do
@language = described_class.new(:key => 'value')
end
it 'calls #inflect of the inflector with the inflectional classification, the word, the inflectional form and the options' do
inflector_stub do |m|
m.should_receive(:inflect).with('classification', 'word', 'form', :key => 'value')
end
@language.inflect('classification', 'word', 'form', :key => 'value')
end
it 'returns the value returning from Langue::Japanese::Inflector#inflect' do
inflector_stub
@language.inflect('classification', 'word', 'form', :key => 'value').should == 'value returning from #inflect'
end
end
| mit |
ilya1st/configuration-go | sysconfig.go | 3645 | package configuration
// IConfig is basic interface for all optional configuration structures
type IConfig interface {
// Set default config load settings. In case of file loader - filename
// if first argument is map object -build config from this map object
SetDefaultLoadSetting(sl ...interface{}) (err error)
// checks external configuration file and it's contents - for example for reload or restart purposes
CheckExternalConfig() (err error)
// (re)loads internal map
ReloadInternalMap() (err error)
// get variant type value
GetValue(path ...string) (i interface{}, err error)
// functions below will try make from this variant value typed value
// returns integer value by path
GetIntValue(path ...string) (i int, err error)
// returns string value or error by path
GetStringValue(path ...string) (s string, err error)
// returns boolean value
GetBooleanValue(path ...string) (b bool, err error)
// returns config interface or nil + error
GetSubconfig(path ...string) (c IConfig, err error)
}
// this map is intended for GetConfigInstance
var intConfigHash map[string]IConfig
func init() {
intConfigHash = map[string]IConfig{}
}
// GetConfigInstance get instans of config depending of wanted config format
// for now supported only HJSON format
// tag is intended not to load configuration files twice and store object hash map inside module
// thats done specially not to create config instance twice + get already created instance
// How to call: GetConfigInstance(tag, format, list_of_settings...)
// tag used not to load config twice. If you need reload them just use CheckExternalConfig() and ReloadInternalMap()
// format: for now HJSON|hjson|JSON|json
// this parameter added for future features(may be we would add other configuration formats there)
// if it was loaded from file.
// settings must contain config type as first argument and other parameters SetDefaultLoadSetting need
// For example.
// First call when we want load configuration file is:
// GetConfigInstance("mainconfig", "HJSON", "/etc/file.hjson")
// When you need get instance again, you just must call:
// GetConfigInstance("mainconfig") and you will get them from internal hash
// this all is intended not to put variable withyou configuration everywhere.
// if you do not want tagging and every time get new object, use nil tag
// e.g. GetConfigInstance(nil, "HJSON", "/etc/file.hjson")
func GetConfigInstance(settings ...interface{}) (config IConfig, err error) {
if len(settings) == 0 {
return nil, NewConfigUsageError("Wrong usage")
}
hasTag := false
tag := ""
tmp := interface{}(nil)
if len(settings) >= 1 {
tmp = settings[0]
if tmp == nil {
hasTag = false
} else {
switch v := tmp.(type) {
case string:
hasTag = true
tag = v
default:
return nil, NewConfigUsageError("Tag argument must be nil or string type")
}
}
}
if hasTag {
ic, ok := intConfigHash[tag]
if ok {
return ic, nil
}
}
if len(settings) < 2 {
return nil, NewConfigUsageError("While first tagged extraction we do need type of file")
}
tmp = settings[1]
cType := ""
switch v := tmp.(type) {
case string:
cType = v
default:
return nil, NewConfigUsageError("Wrong format of type of config")
}
switch cType {
case "HJSON":
fallthrough
case "hjson":
fallthrough
case "JSON":
fallthrough
case "json":
// all other arguments to constructor
config, err = NewHJSONConfig(settings[2:]...)
if err != nil {
return nil, err
}
if hasTag {
intConfigHash[tag] = config
}
return config, nil
default:
return nil, NewConfigUsageError("Unknown configuration format:" + cType)
}
}
| mit |
edbiler/BazaarCorner | module/facebook/include/plugin/theme_template_body__end.php | 107 | <?php
if (Phpfox::getParam('facebook.enable_facebook_connect'))
{
// echo '<div id="fb-root"></div>';
}
?> | mit |
smartive/generator-giuseppe | app/templates/src/app.ts | 574 | import * as bodyparser from 'body-parser';
import { Giuseppe } from 'giuseppe';
<% if(needAuth) { %>
import authentication from './authentication';
<% } %>
const giusi = new Giuseppe();
giusi.expressApp.use(bodyparser.json());
<% if(needAuth) { %>
giusi.expressApp.use(authentication.initialize());
<% } %>
giusi
.loadControllers('./build/controller/**/*.js')
.then(() => {
giusi.start(8080, '', undefined, () => {
console.log('Giuseppe is up and running on port 8080');
});
})
.catch(e => console.error('An error happend', e));
| mit |
MxMcG/validate-test | data.js | 542 | var goodUserData = {
email: 'test@mailinator.com',
phone: '7373737373',
first_name: 'test',
last_name: 'testtest',
address: '123mainstreet',
zip: '92008',
dob_month: '03',
dob_day: '23',
dob_year: '1990',
city: 'Carlsbad',
state: 'CA'
};
var badUserData = {
email: 'testmailinatorcom',
phone: '73+737-373073',
first_name: 't',
last_name: 't',
address: '123mainstreet++',
zip: '9200',
dob_month: '22',
dob_day: '2',
dob_year: '1800',
city: 'C',
state: 'CD'
};
module.exports = { good: goodUserData, bad: badUserData };
| mit |
paKanhu/replacer | Gruntfile.js | 3794 | module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
clean: {
dist: {
src: ['dist']
},
tmp: {
src: ['.tmp']
},
grunt: {
src: ['.grunt']
}
},
copy: {
dist: {
files: [{
src: 'src/index.html',
dest: 'dist/index.html'
}, {
src: 'LICENSE',
dest: 'dist/LICENSE.md'
}, {
src: 'README.md',
dest: 'dist/README.md'
}, {
src: 'src/favicon.ico',
dest: 'dist/favicon.ico'
}, {
src: 'src/apple-touch-icon-precomposed.png',
dest: 'dist/apple-touch-icon-precomposed.png'
}, {
expand: true,
cwd: 'src/fonts/',
src: ['**'],
dest: 'dist/fonts/'
}, {
expand: true,
cwd: 'src/js/vendor/',
src: ['**'],
dest: 'dist/js/vendor/'
}]
},
sitemap: {
files: [
{
src: 'src/sitemap.xml',
dest: 'dist/sitemap.xml'
}]
}
},
processhtml: {
dist: {
files: {
'dist/index.html': ['src/index.html']
}
}
},
htmlmin: {
dist: {
options: {
removeComments: true,
collapseWhitespace: true
},
files: {
'dist/index.html': 'dist/index.html'
}
}
},
uglify: {
options: {
banner: '/*! <%= pkg.name %> - v<%= pkg.version %> - ' +
'<%= grunt.template.today("yyyy-mm-dd") %> */\n\n',
compress: {
drop_console: true
},
preserveComments: 'some'
},
dist: {
files: {
'dist/js/script.min.js': ['src/js/bootstrap/*.js', 'src/js/*.js']
}
}
},
uncss: {
dist: {
options: {
ignore: ['.collapsing',
/\.((error)|(custom))?(m|M)odal[\w.>\- ]*/,
/#replacement-text-list[\w>:]*/,
'.col-xs-8',
'.col-sm-4',
'.col-sm-5',
'.col-md-2',
'.col-md-3',
'.col-md-5',
'.col-md-offset-3', // /\.col\-[\w-]+/
'kbd',
/\.no\-js [\w\-#>]*/,
/(.js )?#no-js[\w-]*/
]
},
files: {
'.tmp/css/style.css': ['src/index.html']
}
}
},
cssmin: {
options: {
banner: '/*! <%= pkg.name %> - v<%= pkg.version %> - ' +
'<%= grunt.template.today("yyyy-mm-dd") %> */\n'
},
dist: {
src: '.tmp/css/style.css',
dest: 'dist/css/style.min.css'
}
},
compress: {
dist: {
options: {
archive: 'dist/replacer.zip'
},
files: [{
expand: true,
cwd: 'dist/',
src: ['**', '!*.zip']
}]
}
},
'gh-pages': {
options: {
base: 'dist',
tag: 'v<%= pkg.version %>',
message: 'Update v<%= pkg.version %>'
},
src: ['**']
}
});
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-processhtml');
grunt.loadNpmTasks('grunt-contrib-htmlmin');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-uncss');
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-contrib-compress');
grunt.loadNpmTasks('grunt-gh-pages');
grunt.registerTask('default', [
'clean',
'copy:dist',
'processhtml',
'htmlmin',
'uglify',
'uncss',
'cssmin',
'compress',
'copy:sitemap',
'clean:tmp'
]);
grunt.registerTask('update', ['clean:grunt', 'gh-pages', 'clean:grunt']);
};
| mit |
Aprogiena/StratisBitcoinFullNode | src/Stratis.Bitcoin.Features.BlockStore.Tests/BlockStoreControllerTests.cs | 8951 | using System.ComponentModel.DataAnnotations;
using System.Threading.Tasks;
using FluentAssertions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Moq;
using NBitcoin;
using Stratis.Bitcoin.Base;
using Stratis.Bitcoin.Controllers.Models;
using Stratis.Bitcoin.Features.BlockStore.Controllers;
using Stratis.Bitcoin.Features.BlockStore.Models;
using Stratis.Bitcoin.Interfaces;
using Stratis.Bitcoin.Tests.Common;
using Stratis.Bitcoin.Tests.Wallet.Common;
using Stratis.Bitcoin.Utilities.JsonErrors;
using Xunit;
namespace Stratis.Bitcoin.Features.BlockStore.Tests
{
public class BlockStoreControllerTests
{
private const string ValidHash = "09d889192a45ba033d4fb886d7aa62bd19b36697211b3d02ac254cf47e2326b0";
private const string BlockAsHex =
"07000000867ccd8f8b21f48e1423d2217fdfe0ea5108dcd6f3371933d584e8f250f5c6600fdf4ccef23cbdb6d81e6bde" +
"a2f0f45aca69a35a9817590c60b5a4ce4a44d1cc30c644592060041a00000000020100000030c6445901000000000000" +
"0000000000000000000000000000000000000000000000000000ffffffff03029423ffffffff01000000000000000000" +
"000000000100000030c6445901795088bf033121a794ea35a11d39dbcd2495b64756e6de76d86944fdeea4ddbc020000" +
"00484730440220096615c8fdec79ecf477cea2104859f7db98ed883f242b08fef316e3abd41a30022070d82dd743eeed" +
"324e90cb3c168144031ba8c8b14a6af167b98253614be3d23c01ffffffff0300000000000000000000011f4a8b000000" +
"232102e89f4f5ac02d3e5f9114253470838ee73c9ba507262ba4db7f0b3f840cf0e1d3ac40432e4a8b000000232102e8" +
"9f4f5ac02d3e5f9114253470838ee73c9ba507262ba4db7f0b3f840cf0e1d3ac00000000463044022002efd3facb7bc9" +
"9407d0f7c6b9c8e80898608f63f3141b06371bbd5e762dd4ab02204f1a5e8cca1a70a5b6dee55746f100042e3479c291" +
"68dd9970c1b3147cbd6ed8";
private const string InvalidHash = "This hash is no good";
[Fact]
public void GetBlock_With_null_Hash_IsInvalid()
{
var requestWithNoHash = new SearchByHashRequest()
{
Hash = null,
OutputJson = true
};
var validationContext = new ValidationContext(requestWithNoHash);
Validator.TryValidateObject(requestWithNoHash, validationContext, null, true).Should().BeFalse();
}
[Fact]
public void GetBlock_With_empty_Hash_IsInvalid()
{
var requestWithNoHash = new SearchByHashRequest()
{
Hash = "",
OutputJson = false
};
var validationContext = new ValidationContext(requestWithNoHash);
Validator.TryValidateObject(requestWithNoHash, validationContext, null, true).Should().BeFalse();
}
[Fact]
public void GetBlock_With_good_Hash_IsValid()
{
var requestWithNoHash = new SearchByHashRequest()
{
Hash = "some good hash",
OutputJson = true
};
var validationContext = new ValidationContext(requestWithNoHash);
Validator.TryValidateObject(requestWithNoHash, validationContext, null, true).Should().BeTrue();
}
[Fact]
public void Get_Block_When_Hash_Is_Not_Found_Should_Return_Not_Found_Object_Result()
{
(Mock<IBlockStore> store, BlockStoreController controller) = GetControllerAndStore();
store.Setup(c => c.GetBlockAsync(It.IsAny<uint256>()))
.Returns(Task.FromResult((Block)null));
Task<IActionResult> response = controller.GetBlockAsync(new SearchByHashRequest()
{ Hash = ValidHash, OutputJson = true });
response.Result.Should().BeOfType<NotFoundObjectResult>();
var notFoundObjectResult = (NotFoundObjectResult)response.Result;
notFoundObjectResult.StatusCode.Should().Be(404);
notFoundObjectResult.Value.Should().Be("Block not found");
}
[Fact]
public void Get_Block_When_Hash_Is_Invalid_Should_Error_With_Explanation()
{
(Mock<IBlockStore> store, BlockStoreController controller) = GetControllerAndStore();
Task<IActionResult> response = controller.GetBlockAsync(new SearchByHashRequest()
{ Hash = InvalidHash, OutputJson = true });
response.Result.Should().BeOfType<ErrorResult>();
var notFoundObjectResult = (ErrorResult)response.Result;
notFoundObjectResult.StatusCode.Should().Be(400);
((ErrorResponse)notFoundObjectResult.Value).Errors[0]
.Description.Should().Contain("Invalid Hex String");
}
[Fact]
public void Get_Block_When_Block_Is_Found_And_Requesting_JsonOuput()
{
(Mock<IBlockStore> store, BlockStoreController controller) = GetControllerAndStore();
store.Setup(c => c.GetBlockAsync(It.IsAny<uint256>()))
.Returns(Task.FromResult(Block.Parse(BlockAsHex, KnownNetworks.StratisTest)));
Task<IActionResult> response = controller.GetBlockAsync(new SearchByHashRequest()
{Hash = ValidHash, OutputJson = true});
response.Result.Should().BeOfType<JsonResult>();
var result = (JsonResult) response.Result;
result.Value.Should().BeOfType<BlockModel>();
((BlockModel) result.Value).Hash.Should().Be(ValidHash);
((BlockModel) result.Value).MerkleRoot.Should()
.Be("ccd1444acea4b5600c5917985aa369ca5af4f0a2de6b1ed8b6bd3cf2ce4cdf0f");
}
[Fact]
public void Get_Block_When_Block_Is_Found_And_Requesting_Verbose_JsonOuput()
{
(Mock<IBlockStore> store, BlockStoreController controller) = GetControllerAndStore();
store.Setup(c => c.GetBlockAsync(It.IsAny<uint256>()))
.Returns(Task.FromResult(Block.Parse(BlockAsHex, KnownNetworks.StratisTest)));
Task<IActionResult> response = controller.GetBlockAsync(new SearchByHashRequest()
{ Hash = ValidHash, OutputJson = true, ShowTransactionDetails = true });
response.Result.Should().BeOfType<JsonResult>();
var result = (JsonResult)response.Result;
result.Value.Should().BeOfType<Models.BlockTransactionDetailsModel>();
((BlockTransactionDetailsModel)result.Value).Transactions.Should().HaveCountGreaterThan(1);
}
[Fact]
public void Get_Block_When_Block_Is_Found_And_Requesting_RawOuput()
{
(Mock<IBlockStore> store, BlockStoreController controller) = GetControllerAndStore();
store.Setup(c => c.GetBlockAsync(It.IsAny<uint256>()))
.Returns(Task.FromResult(Block.Parse(BlockAsHex, KnownNetworks.StratisTest)));
Task<IActionResult> response = controller.GetBlockAsync(new SearchByHashRequest()
{ Hash = ValidHash, OutputJson = false });
response.Result.Should().BeOfType<JsonResult>();
var result = (JsonResult)response.Result;
((Block)(result.Value)).ToHex(KnownNetworks.StratisTest).Should().Be(BlockAsHex);
}
[Fact]
public void GetBlockCount_ReturnsHeightFromChainState()
{
var logger = new Mock<ILoggerFactory>();
var store = new Mock<IBlockStore>();
var chainState = new Mock<IChainState>();
ConcurrentChain chain = WalletTestsHelpers.GenerateChainWithHeight(3, KnownNetworks.StratisTest);
logger.Setup(l => l.CreateLogger(It.IsAny<string>())).Returns(Mock.Of<ILogger>);
chainState.Setup(c => c.ConsensusTip)
.Returns(chain.GetBlock(2));
var controller = new BlockStoreController(KnownNetworks.StratisTest, logger.Object, store.Object, chainState.Object, chain);
var json = (JsonResult)controller.GetBlockCount();
int result = int.Parse(json.Value.ToString());
Assert.Equal(2, result);
}
private static (Mock<IBlockStore> store, BlockStoreController controller) GetControllerAndStore()
{
var logger = new Mock<ILoggerFactory>();
var store = new Mock<IBlockStore>();
var chainState = new Mock<IChainState>();
logger.Setup(l => l.CreateLogger(It.IsAny<string>())).Returns(Mock.Of<ILogger>);
var chain = new Mock<ConcurrentChain>();
Block block = Block.Parse(BlockAsHex, KnownNetworks.StratisTest);
chain.Setup(c => c.GetBlock(It.IsAny<uint256>())).Returns(new ChainedHeader(block.Header, block.Header.GetHash(), 1));
var controller = new BlockStoreController(KnownNetworks.StratisTest, logger.Object, store.Object, chainState.Object, chain.Object);
return (store, controller);
}
}
} | mit |
codyrobbins/syllabify | lib/cody_robbins/syllabify.rb | 9692 | # encoding: UTF-8
require('yaml')
module CodyRobbins
class Syllabify
# Create a new syllabified representation of an [IPA](http://en.wikipedia.org/wiki/International_Phonetic_Alphabet) transcription.
#
# @param language [Symbol, String] The [ISO 639](http://en.wikipedia.org/wiki/ISO_639) code of the language represented in the transcription. If the language has a two-letter [ISO 639-1](http://en.wikipedia.org/wiki/ISO_639-1) code, use that; otherwise, use the three-letter [ISO 639-3](http://en.wikipedia.org/wiki/ISO_639-3) code. This maps to the phoneme inventory definitions in the `languages` directory.
# @param transcription [String] An [IPA](http://en.wikipedia.org/wiki/International_Phonetic_Alphabet) transcription to syllabify. Any phonemes represented by digraphs must be combined with a tie as discussed in the {file:README}.
#
# @example
# transcription = CodyRobbins::Syllabify.new(:en, 'dɪˌsɔrgənəˈze͡ɪʃən')
#
# transcription.to_s #=> 'dɪ.ˌsɔr.gə.nə.ˈze͡ɪ.ʃən'
# transcription.syllables #=> [dɪ, ˌsɔr, gə, nə, ˈze͡ɪ, ʃən]
def initialize(language, transcription)
set_language(language)
set_transcription(transcription)
initialize_coda_and_onset
end
# Render a syllabified [IPA](http://en.wikipedia.org/wiki/International_Phonetic_Alphabet) transcription of the input transcription. Syllables are delimited by the IPA syllable delimiter.
#
# @return [String]
#
# @example
# CodyRobbins::Syllabify.new(:en, 'dɪˌsɔrgənəˈze͡ɪʃən').to_s #=> 'dɪ.ˌsɔr.gə.nə.ˈze͡ɪ.ʃən'
def to_s
syllables_as_strings.join(SYLLABLE_DELIMETER)
end
# Return the individual {Syllable} objects representing the transcription’s syllables.
#
# @return [Array] The {Syllable} objects representing each individual syllable.
#
# @example
# CodyRobbins::Syllabify.new(:en, 'dɪˌsɔrgənəˈze͡ɪʃən').syllables #=> [dɪ, ˌsɔr, gə, nə, ˈze͡ɪ, ʃən]
def syllables
@syllables ||= build_syllables
end
protected
attr_reader(:language,
:transcription,
:phoneme,
:stress,
:coda_and_onset,
:coda,
:onset)
# @private
SYLLABLE_DELIMETER = '.'
def set_language(language)
@language = language
end
def set_transcription(transcription)
@transcription = transcription
end
def initialize_coda_and_onset
@coda_and_onset = []
end
def syllables_as_strings
syllables.collect(&:to_s)
end
def join(array)
array.try(:join, '')
end
def phonemes
transcription.scan(transcription_tokenizing_regex)
end
def transcription_tokenizing_regex
Regexp.new("[ˈˌ]?(?:#{all_phonemes_disjunction})")
end
def all_phonemes_disjunction
all_phonemes.join('|')
end
def all_phonemes
phoneme_inventory[:consonants] + phoneme_inventory[:nuclei]
end
def phoneme_inventory
phoneme_inventory_yaml.with_indifferent_access
end
def phoneme_inventory_yaml
YAML.load_file(phoneme_inventory_file)
end
def phoneme_inventory_file
"#{this_directory}/../../languages/#{language}.yml"
end
def this_directory
File.dirname(this_file)
end
def this_file
__FILE__
end
def build_syllables
initialize_syllables
process_each_phoneme
process_remaining_coda_and_onset_if_present
return_syllables
end
def initialize_syllables
@syllables = []
end
def process_each_phoneme
phonemes.each do |phoneme|
set_phoneme(phoneme)
strip_phoneme_and_process
end
end
def strip_phoneme_and_process
strip_phoneme
process_phoneme_unless_blank
end
def set_phoneme(phoneme)
@phoneme = phoneme
end
def strip_phoneme
@phoneme.strip!
end
def process_phoneme_unless_blank
process_phoneme unless phoneme_blank?
end
def phoneme_blank?
phoneme.blank?
end
def process_phoneme
remove_stress_from_phoneme_if_stressed
categorize_phoneme
end
def initialize_stress
set_stress(nil)
end
def set_stress(stress)
@stress = stress
end
def remove_stress_from_phoneme_if_stressed
remove_stress_from_phoneme if phoneme_has_stress?
end
def phoneme_has_stress?
phoneme_has_primary_stress? || phoneme_has_secondary_stress?
end
def phoneme_has_primary_stress?
first_character_of_phoneme == PRIMARY_STRESS_MARKER
end
def phoneme_has_secondary_stress?
first_character_of_phoneme == SECONDARY_STRESS_MARKER
end
# @private
PRIMARY_STRESS_MARKER = 'ˈ'
# @private
SECONDARY_STRESS_MARKER = 'ˌ'
def first_character_of_phoneme
phoneme[0]
end
def remove_stress_from_phoneme
set_stress_to_first_character_of_phoneme
set_phoneme_to_remaining_characters_of_phoneme
end
def set_stress_to_first_character_of_phoneme
set_stress(first_character_of_phoneme)
end
def set_phoneme_to_remaining_characters_of_phoneme
set_phoneme(remaining_characters_of_phoneme)
end
def remaining_characters_of_phoneme
phoneme[1..-1]
end
def categorize_phoneme
if nucleus?
assemble_syllable
elsif not_consonant_or_syllable_delimeter?
raise_invalid_phoneme_exception
else
add_phoneme_to_coda_and_onset
end
end
def nucleus?
nuclei.include?(phoneme)
end
def nuclei
phoneme_inventory[:nuclei]
end
def assemble_syllable
split_coda_and_onset
append_coda_to_last_syllable_unless_no_syllables?
append_new_syllable
initialize_stress
initialize_coda_and_onset
end
def split_coda_and_onset
if coda_and_onset_include_syllable_delimeter?
split_coda_and_onset_at_syllable_delimeter
else
split_coda_and_onset_at_largest_valid_onset
end
end
def coda_and_onset_include_syllable_delimeter?
coda_and_onset.include?(SYLLABLE_DELIMETER)
end
def split_coda_and_onset_at_syllable_delimeter
split_coda_and_onset_at(coda_and_onset_syllable_delimiter_position)
end
def coda_and_onset_syllable_delimiter_position
coda_and_onset.index(SYLLABLE_DELIMETER)
end
def split_coda_and_onset_at(midpoint)
split_coda(midpoint)
split_onset(midpoint)
end
def split_coda(midpoint)
set_coda(join(coda_from_coda_and_onset(midpoint)))
end
def set_coda(coda)
@coda = coda
end
def coda_from_coda_and_onset(midpoint)
coda_and_onset[0, midpoint]
end
def split_onset(midpoint)
set_onset(join(onset_from_coda_and_onset(midpoint)))
end
def set_onset(onset)
@onset = onset
end
def onset_from_coda_and_onset(midpoint)
coda_and_onset[midpoint, coda_and_onset.length]
end
def split_coda_and_onset_at_largest_valid_onset
coda_and_onset_split_range.each do |midpoint|
split_coda_and_onset_at(midpoint)
break if onset_or_start_of_word?(onset)
end
end
def coda_and_onset_split_range
0..coda_and_onset_range_length
end
def coda_and_onset_range_length
coda_and_onset.length + 1
end
def onset_or_start_of_word?(onset)
onset?(onset) || start_of_word?
end
def onset?(string)
onsets.include?(string)
end
def onsets
phoneme_inventory[:onsets]
end
def no_syllables?
syllables.empty?
end
alias :start_of_word? :no_syllables?
def append_coda_to_last_syllable_unless_no_syllables?
append_coda_to_last_syllable unless no_syllables?
end
def append_coda_to_last_syllable
last_syllable.append_coda(coda)
end
def last_syllable
@syllables.last
end
def append_new_syllable
create_syllable(onset, phoneme)
end
def create_syllable(onset, nucleus = nil)
@syllables << new_syllable(onset, nucleus)
end
def new_syllable(onset, nucleus)
Syllable.new(stress,
onset,
nucleus)
end
def not_consonant_or_syllable_delimeter?
!consonant_or_syllable_delimeter?
end
def consonant_or_syllable_delimeter?
consonant? || syllable_delimeter?
end
def consonant?
consonants.include?(phoneme)
end
def consonants
phoneme_inventory[:consonants]
end
def syllable_delimeter?
phoneme == SYLLABLE_DELIMETER
end
def raise_invalid_phoneme_exception
raise(invalid_phoneme_error)
end
def invalid_phoneme_error
"Invalid phoneme: #{phoneme}"
end
def add_phoneme_to_coda_and_onset
@coda_and_onset << phoneme
end
def coda_and_onset_empty?
coda_and_onset.empty?
end
def create_syllable_from_coda_and_onset
create_syllable(coda_and_onset_joined)
end
def append_coda_and_onset_to_last_syllable
last_syllable.append_coda(coda_and_onset_joined)
end
def coda_and_onset_joined
join(coda_and_onset)
end
def process_remaining_coda_and_onset_if_present
process_remaining_coda_and_onset unless coda_and_onset_empty?
end
def process_remaining_coda_and_onset
if no_syllables?
create_syllable_from_coda_and_onset
else
append_coda_and_onset_to_last_syllable
end
end
def return_syllables
@syllables
end
end
end
| mit |
levilucio/SyVOLT | ECore_Copier_MM/transformation-Large/HereferencelefteOppositeSolveRefEReferenceEReferenceEReferenceEReference.py | 5055 |
from core.himesis import Himesis
class HereferencelefteOppositeSolveRefEReferenceEReferenceEReferenceEReference(Himesis):
def __init__(self):
"""
Creates the himesis graph representing the AToM3 model HereferencelefteOppositeSolveRefEReferenceEReferenceEReferenceEReference.
"""
# Flag this instance as compiled now
self.is_compiled = True
super(HereferencelefteOppositeSolveRefEReferenceEReferenceEReferenceEReference, self).__init__(name='HereferencelefteOppositeSolveRefEReferenceEReferenceEReferenceEReference', num_nodes=27, edges=[])
# Add the edges
self.add_edges([[0, 5], [5, 23], [0, 6], [6, 24], [1, 7], [7, 25], [1, 8], [8, 26], [23, 3], [3, 24], [25, 4], [4, 26], [25, 9], [9, 23], [26, 10], [10, 24], [25, 11], [11, 12], [13, 14], [14, 12], [13, 15], [15, 16], [26, 17], [17, 18], [19, 20], [20, 18], [19, 21], [21, 22], [0, 2], [2, 1]])
# Set the graph attributes
self["mm__"] = ['HimesisMM']
self["name"] = """ereferencelefteOppositeSolveRefEReferenceEReferenceEReferenceEReference"""
self["GUID__"] = 1680653252241126549
# Set the node attributes
self.vs[0]["mm__"] = """MatchModel"""
self.vs[0]["GUID__"] = 4813939850778365508
self.vs[1]["mm__"] = """ApplyModel"""
self.vs[1]["GUID__"] = 1340534108209521467
self.vs[2]["mm__"] = """paired_with"""
self.vs[2]["GUID__"] = 5368529414082140301
self.vs[3]["associationType"] = """eOpposite"""
self.vs[3]["mm__"] = """directLink_S"""
self.vs[3]["GUID__"] = 890712182803871215
self.vs[4]["associationType"] = """eOpposite"""
self.vs[4]["mm__"] = """directLink_T"""
self.vs[4]["GUID__"] = 485323146196667641
self.vs[5]["mm__"] = """match_contains"""
self.vs[5]["GUID__"] = 4980420102170504167
self.vs[6]["mm__"] = """match_contains"""
self.vs[6]["GUID__"] = 8040988157742893208
self.vs[7]["mm__"] = """apply_contains"""
self.vs[7]["GUID__"] = 3839473651887535352
self.vs[8]["mm__"] = """apply_contains"""
self.vs[8]["GUID__"] = 5258499036971823936
self.vs[9]["type"] = """ruleDef"""
self.vs[9]["mm__"] = """backward_link"""
self.vs[9]["GUID__"] = 49526625727431327
self.vs[10]["type"] = """ruleDef"""
self.vs[10]["mm__"] = """backward_link"""
self.vs[10]["GUID__"] = 7195197538877862446
self.vs[11]["mm__"] = """hasAttribute_T"""
self.vs[11]["GUID__"] = 3840806041632866841
self.vs[12]["name"] = """ApplyAttribute"""
self.vs[12]["mm__"] = """Attribute"""
self.vs[12]["Type"] = """'String'"""
self.vs[12]["GUID__"] = 1327628070380343518
self.vs[13]["name"] = """eq_"""
self.vs[13]["mm__"] = """Equation"""
self.vs[13]["GUID__"] = 5188550108506131741
self.vs[14]["mm__"] = """leftExpr"""
self.vs[14]["GUID__"] = 2784976126107907884
self.vs[15]["mm__"] = """rightExpr"""
self.vs[15]["GUID__"] = 2754486131294029836
self.vs[16]["name"] = """solveRef"""
self.vs[16]["mm__"] = """Constant"""
self.vs[16]["Type"] = """'String'"""
self.vs[16]["GUID__"] = 1809172722178263070
self.vs[17]["mm__"] = """hasAttribute_T"""
self.vs[17]["GUID__"] = 6858244855174105548
self.vs[18]["name"] = """ApplyAttribute"""
self.vs[18]["mm__"] = """Attribute"""
self.vs[18]["Type"] = """'String'"""
self.vs[18]["GUID__"] = 889940915458446142
self.vs[19]["name"] = """eq_"""
self.vs[19]["mm__"] = """Equation"""
self.vs[19]["GUID__"] = 572815508033277364
self.vs[20]["mm__"] = """leftExpr"""
self.vs[20]["GUID__"] = 2136724887486361101
self.vs[21]["mm__"] = """rightExpr"""
self.vs[21]["GUID__"] = 3315102593717476170
self.vs[22]["name"] = """solveRef"""
self.vs[22]["mm__"] = """Constant"""
self.vs[22]["Type"] = """'String'"""
self.vs[22]["GUID__"] = 8709978099890887096
self.vs[23]["name"] = """"""
self.vs[23]["classtype"] = """EReference"""
self.vs[23]["mm__"] = """EReference"""
self.vs[23]["cardinality"] = """+"""
self.vs[23]["GUID__"] = 6104067831463903659
self.vs[24]["name"] = """"""
self.vs[24]["classtype"] = """EReference"""
self.vs[24]["mm__"] = """EReference"""
self.vs[24]["cardinality"] = """+"""
self.vs[24]["GUID__"] = 7586685190329115484
self.vs[25]["name"] = """"""
self.vs[25]["classtype"] = """EReference"""
self.vs[25]["mm__"] = """EReference"""
self.vs[25]["cardinality"] = """1"""
self.vs[25]["GUID__"] = 4341769129045495054
self.vs[26]["name"] = """"""
self.vs[26]["classtype"] = """EReference"""
self.vs[26]["mm__"] = """EReference"""
self.vs[26]["cardinality"] = """1"""
self.vs[26]["GUID__"] = 3984646437279540842
| mit |
Aichifan/MiniWms | src/main/java/ndm/miniwms/vo/CompanyVO.java | 2013 | package ndm.miniwms.vo;
import java.util.Date;
public class CompanyVO {
private Integer id;
private String name;
private String anothername;
private String address;
private String description;
private String contactName;
private String contactTel;
private String contactFax;
private String contactEmail;
private String contactQq;
private String contactMsn;
private String contactDesc;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAnothername() {
return anothername;
}
public void setAnothername(String anothername) {
this.anothername = anothername;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getContactName() {
return contactName;
}
public void setContactName(String contactName) {
this.contactName = contactName;
}
public String getContactTel() {
return contactTel;
}
public void setContactTel(String contactTel) {
this.contactTel = contactTel;
}
public String getContactFax() {
return contactFax;
}
public void setContactFax(String contactFax) {
this.contactFax = contactFax;
}
public String getContactEmail() {
return contactEmail;
}
public void setContactEmail(String contactEmail) {
this.contactEmail = contactEmail;
}
public String getContactQq() {
return contactQq;
}
public void setContactQq(String contactQq) {
this.contactQq = contactQq;
}
public String getContactMsn() {
return contactMsn;
}
public void setContactMsn(String contactMsn) {
this.contactMsn = contactMsn;
}
public String getContactDesc() {
return contactDesc;
}
public void setContactDesc(String contactDesc) {
this.contactDesc = contactDesc;
}
}
| mit |
apo-j/Projects_Working | S/SOURCE/SOURCE.EspaceCandidature/SOURCE.EspaceCandidature.Web.ViewModels/ViewModels/Generated/ActionModeAffichageViewModel.cs | 809 | //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
//
// This code was auto-generated by AFNOR StoredProcedureSystem, version 1.0
//
using System.Runtime.Serialization;
using System;
namespace SOURCE.EspaceCandidature.Web.ViewModels.ViewModels
{
public partial class ActionModeAffichageViewModel
{
public long ID { get; set; }
public string Code { get; set; }
public string CodeEchange { get; set; }
public string Description { get; set; }
}
}
| mit |
gamelab/particle-pack-2-plugin | src/blue/flamethrowerblue.js | 1947 | /**
* ParticlePack2 Flamethrowerblue Effect.
* @method Flamethrowerblue
* @param state {Kiwi.State} Current state
* @param x {Number} X position
* @param y {Number} Y position
* @return Kiwi.Group
* @public
* @static
*/
Kiwi.Plugins.ParticlePack2.Flamethrowerblue = function( state, x, y ) {
this.config = {
"numParts": 25,
"posOffsetX": 0,
"posOffsetY": 0,
"posRadius": 5,
"posRadialStart": 0,
"posRadialEnd": 6.283185307179586,
"posWidth": 200,
"posHeight": 200,
"posConstrainRect": true,
"posAngle": 0,
"posLength": 200,
"posRandomLine": true,
"posConstrainRadial": false,
"posRandomRadial": true,
"posShape": "point",
"maxVel": 100,
"minVel": 70,
"velConstrainRect": true,
"velConstrainRadial": true,
"velRandomRadial": true,
"velShape": "point",
"velOffsetX": 300,
"velOffsetY": 0,
"velAngMin": -6,
"velAngMax": 6,
"velRadius": 20,
"velRadialStart": 0,
"velRadialEnd": 6.283185307179586,
"velWidth": 200,
"velHeight": 200,
"velAngle": 0.0004784919240787009,
"velLength": 200,
"velRandomLine": true,
"minStartTime": 0,
"maxStartTime": 0,
"minLifespan": 0.1,
"maxLifespan": 0.6,
"gravityX": 0,
"gravityY": 0,
"startSize": 5,
"endSize": 80,
"loop": true,
"colEnvKeyframes": [
0.2,
0.3
],
"alpha": 0.7,
"colEnv0": [
0.611764705882353,
0.9647058823529412,
0.9921568627450981
],
"colEnv1": [
0.4392156862745098,
0.7450980392156863,
0.9921568627450981
],
"colEnv2": [
0.10980392156862745,
0.38823529411764707,
0.9921568627450981
],
"colEnv3": [
0.06666666666666667,
0.2549019607843137,
0.9921568627450981
],
"alphaGradient": [
0,
1,
1,
0
],
"alphaStops": [
0.1,
0.5
],
"additive": true,
"cells": [
3,
4
],
"textureID": "_128x128"
};
return new Kiwi.GameObjects.StatelessParticles(
state, state.textures.particlePack2SpriteSheet, x, y,
this.config);
};
| mit |
layabox/layaair | src/samples/3d/LayaAir3D_Advance/CommandBufferDemo/GlassWithoutGrabMaterial.ts | 2646 | import { VertexMesh } from "laya/d3/graphics/Vertex/VertexMesh";
import { Shader3D } from "laya/d3/shader/Shader3D";
import { SubShader } from "laya/d3/shader/SubShader";
import { Material } from "laya/d3/core/material/Material";
import GlassShaderVS from "./GlassShader.vs";
import GlassShaderFS from "./GlassShader.fs";
import { RenderState } from "laya/d3/core/material/RenderState";
import { Vector4 } from "laya/d3/math/Vector4";
import { BaseTexture } from "laya/resource/BaseTexture";
export class GlassWithoutGrabMaterail extends Material{
static TINTTEXTURE:number = Shader3D.propertyNameToID("u_tintTexure");
static NORMALTEXTURE:number = Shader3D.propertyNameToID("u_normalTexture");
static TILINGOFFSET: number = Shader3D.propertyNameToID("u_TilingOffset");
static ALBEDOCOLOR: number = Shader3D.propertyNameToID("u_tintAmount");
static init(){
var attributeMap: any = {
'a_Position': VertexMesh.MESH_POSITION0,
'a_Normal': VertexMesh.MESH_NORMAL0,
'a_Texcoord0': VertexMesh.MESH_TEXTURECOORDINATE0,
'a_Tangent0': VertexMesh.MESH_TANGENT0,
};
var uniformMap = {
'u_tintTexure': Shader3D.PERIOD_MATERIAL,
'u_normalTexture': Shader3D.PERIOD_MATERIAL,
'u_tintAmount': Shader3D.PERIOD_MATERIAL,
'u_TilingOffset': Shader3D.PERIOD_MATERIAL,
'u_MvpMatrix': Shader3D.PERIOD_SPRITE
};
var stateMap = {
's_Cull': Shader3D.RENDER_STATE_CULL,
's_Blend': Shader3D.RENDER_STATE_BLEND,
's_BlendSrc': Shader3D.RENDER_STATE_BLEND_SRC,
's_BlendDst': Shader3D.RENDER_STATE_BLEND_DST,
's_DepthTest': Shader3D.RENDER_STATE_DEPTH_TEST,
's_DepthWrite': Shader3D.RENDER_STATE_DEPTH_WRITE
}
var shader: Shader3D = Shader3D.add("GlassShader", null, null,false);
var subShader: SubShader = new SubShader(attributeMap, uniformMap);
shader.addSubShader(subShader);
subShader.addShaderPass(GlassShaderVS, GlassShaderFS, stateMap, "Forward");
}
constructor(texture:BaseTexture){
super();
this.setShaderName("GlassShader");
this.renderModeSet();
this._shaderValues.setVector(GlassWithoutGrabMaterail.TILINGOFFSET,new Vector4(1,1,0,0));
this._shaderValues.setTexture(GlassWithoutGrabMaterail.TINTTEXTURE,texture);
}
//渲染模式
renderModeSet(){
this.alphaTest = false;//深度测试关闭
this.renderQueue = Material.RENDERQUEUE_TRANSPARENT;//渲染顺序放在后面
this.depthWrite = true;
this.cull = RenderState.CULL_BACK;
this.blend = RenderState.BLEND_DISABLE;
this.depthTest = RenderState.DEPTHTEST_LESS;
}
} | mit |
HudsonNicoletti/crm | apps/Manager/controllers/TasksController.php | 12129 | <?php
namespace Manager\Controllers;
use Manager\Models\Logs as Logs,
Manager\Models\Team as Team,
Manager\Models\Projects as Projects,
Manager\Models\Tasks as Tasks;
use Mustache_Engine as Mustache;
use Phalcon\Forms\Form,
Phalcon\Forms\Element\Text,
Phalcon\Forms\Element\Password,
Phalcon\Forms\Element\Textarea,
Phalcon\Forms\Element\Select,
Phalcon\Forms\Element\Hidden;
class TasksController extends ControllerBase
{
private $flags = [
'status' => true,
'title' => false,
'text' => false,
'redirect' => false,
'time' => false,
'target' => false
];
public function IndexAction()
{
$this->assets
->addCss("assets/manager/css/app/email.css")
->addCss('assets/manager/css/plugins/bootstrap-chosen/chosen.css')
->addJs("assets/manager/js/plugins/jquery.filtr.min.js")
->addJs('assets/manager/js/plugins/inputmask/jquery.inputmask.bundle.js')
->addJs("assets/manager/js/plugins/bootstrap-validator/bootstrapValidator.min.js")
->addJs("assets/manager/js/plugins/bootstrap-validator/bootstrapValidator-conf.js")
->addJs("assets/manager/js/plugins/bootstrap-chosen/chosen.jquery.js");
$uid = $this->session->get('secure_id');
$tasks = Tasks::query()
->columns([
'Manager\Models\Tasks._',
'Manager\Models\Tasks.title',
'Manager\Models\Tasks.description',
'Manager\Models\Tasks.deadline',
'Manager\Models\Tasks.created',
'Manager\Models\Tasks.completed',
'Manager\Models\Tasks.status',
'Manager\Models\Projects.title as project',
])
->leftJoin('Manager\Models\Projects', 'Manager\Models\Tasks.project = Manager\Models\Projects._')
->where("assigned = '{$uid}'")
->execute();
$form = new Form();
$form->add(new Hidden( "security" ,[
'name' => $this->security->getTokenKey(),
'value' => $this->security->getToken(),
]));
$this->view->form = $form;
$this->view->tasks = $tasks;
}
public function StatusAction()
{
$this->response->setContentType("application/json");
if(!$this->request->isPost()):
$this->flags['status'] = false ;
$this->flags['title'] = "Erro ao atualizar dados!";
$this->flags['text'] = "Metodo Inválido.";
endif;
if(!$this->security->checkToken()):
$this->flags['status'] = false ;
$this->flags['title'] = "Erro ao atualizar dados!!";
$this->flags['text'] = "Token de segurança inválido.";
endif;
if($this->flags['status']):
$task = Tasks::findFirst( $this->dispatcher->getParam("task") );
if( $this->dispatcher->getParam("method") == "close" )
{
$task->status = 2;
$task->completed = (new \DateTime())->format("Y-m-d H:i:s");
$this->flags['title'] = "Tarefa Concluída!";
$this->flags['text'] = "Tarefa foi concluída e homologada.";
$description = "Concluiu a tarefa ({$task->title}).";
}
else
{
$task->status = 1;
$task->completed = null;
$this->flags['title'] = "Tarefa Aberta!";
$this->flags['text'] = "Tarefa foi aberta e homologada.";
$description = "Abriu a tarefa ( {$task->title} )";
}
$task->save();
# Log What Happend
$this->logManager($this->logs->update,$description,$task->project);
$this->flags['redirect'] = "/tasks";
$this->flags['time'] = 1200;
endif;
return $this->response->setJsonContent([
"status" => $this->flags['status'],
"title" => $this->flags['title'],
"text" => $this->flags['text'],
"redirect" => $this->flags['redirect'],
"time" => $this->flags['time'] ,
"target" => $this->flags['target'] ,
]);
$this->response->send();
$this->view->setRenderLevel(View::LEVEL_ACTION_VIEW);
}
public function NewAction()
{
$this->response->setContentType("application/json");
$this->flags['target'] = "#createBox";
if(!$this->request->isPost()):
$this->flags['status'] = false ;
$this->flags['title'] = "Erro ao Cadastrar!";
$this->flags['text'] = "Metodo Inválido.";
endif;
if(!$this->security->checkToken()):
$this->flags['status'] = false ;
$this->flags['title'] = "Erro ao Cadastrar!";
$this->flags['text'] = "Token de segurança inválido.";
endif;
if($this->flags['status']):
$project = $this->request->getPost("project","int");
$title = $this->request->getPost('title','string');
$task = new Tasks;
$task->title = $title;
$task->description = $this->request->getPost("description","string");
$task->project = $this->request->getPost("project","int");
$task->created = (new \DateTime())->format("Y-m-d H:i:s");
$task->deadline = (new \DateTime($this->request->getPost("deadline","string")))->format("Y-m-d H:i:s");
$task->assigned = $project;
$task->status = 1;
$task->save();
# Log What Happend
$this->logManager($this->logs->create,"Adicionou uma nova tarefa ( {$title} )",$project);
$this->flags['title'] = "Cadastrado com Sucesso!";
$this->flags['text'] = "Tarefa cadastrada com sucesso!";
$this->flags['redirect'] = "/tasks";
$this->flags['time'] = 0;
endif;
return $this->response->setJsonContent([
"status" => $this->flags['status'],
"title" => $this->flags['title'],
"text" => $this->flags['text'],
"redirect" => $this->flags['redirect'],
"time" => $this->flags['time'] ,
"target" => $this->flags['target'] ,
]);
$this->response->send();
$this->view->setRenderLevel(View::LEVEL_ACTION_VIEW);
}
public function UpdateAction()
{
$this->response->setContentType("application/json");
$this->flags['target'] = "#updateBox";
if(!$this->request->isPost()):
$this->flags['status'] = false ;
$this->flags['title'] = "Erro ao Alterar!";
$this->flags['text'] = "Metodo Inválido.";
endif;
if(!$this->security->checkToken()):
$this->flags['status'] = false ;
$this->flags['title'] = "Erro ao Alterar!";
$this->flags['text'] = "Token de segurança inválido.";
endif;
if($this->flags['status']):
$project = $this->request->getPost("project","int");
$title = $this->request->getPost("title","string");
$task = Tasks::findFirst($this->dispatcher->getParam("task"));
$task->title = $title;
$task->description = $this->request->getPost("description","string");
$task->project = $project;
$task->deadline = (new \DateTime($this->request->getPost("deadline","string")))->format("Y-m-d H:i:s");
$task->assigned = $this->request->getPost("assigned","int");
$task->save();
# Log What Happend
$this->logManager($this->logs->create,"Alterou uma tarefa ( {$title} )",$project);
$this->flags['title'] = "Alterado com Sucesso!";
$this->flags['text'] = "Tarefa Alterada com sucesso!";
$this->flags['redirect'] = "/tasks";
$this->flags['time'] = 1200;
endif;
return $this->response->setJsonContent([
"status" => $this->flags['status'],
"title" => $this->flags['title'],
"text" => $this->flags['text'],
"redirect" => $this->flags['redirect'],
"time" => $this->flags['time'] ,
"target" => $this->flags['target'] ,
]);
$this->response->send();
$this->view->setRenderLevel(View::LEVEL_ACTION_VIEW);
}
public function ModalAction()
{
$this->response->setContentType("application/json");
if(!$this->request->isGet()):
$this->flags['status'] = false ;
$this->flags['title'] = "Erro ao Alterar!";
$this->flags['text'] = "Metodo Inválido.";
endif;
if($this->flags['status']):
$form = new Form();
$action = false;
$inputs = [];
$project = $this->dispatcher->getParam("project");
$task = $this->dispatcher->getParam("task");
# CREATING ELEMENTS
$element['project'] = new Select( "project" , Projects::find() ,[
'using' => ['_','title'],
'title' => "Projeto Associado",
'class' => "chosen-select form-control"
]);
$element['title'] = new Text( "title" ,[
'class' => "form-control",
'title' => "Título",
'data-validate' => true,
'data-empty' => "* Campo Obrigatório"
]);
$element['description'] = new Textarea( "description" ,[
'class' => "form-control",
'title' => "Observações",
'placeholder' => "Breve Descrição ..."
]);
$element['deadline'] = new Text( "deadline" ,[
'class' => "form-control inputmask",
'title' => "Deadline",
'data-validate' => true,
'data-empty' => "* Campo Obrigatório",
'placeholder' => "dd-mm-yyyy",
'data-inputmask'=> "'alias': 'dd-mm-yyyy'"
]);
$element['assigned'] = new Select( "assigned" , Team::find() ,[
'using' => ['uid','name'],
'title' => "Responsável",
'class' => "chosen-select form-control"
]);
$element['security'] = new Hidden( "security" ,[
'name' => $this->security->getTokenKey(),
'value' => $this->security->getToken(),
]);
# IF REQUEST IS TO CREATE JUST POPULATE WITH DEFAULT ELEMENTS
if( $this->dispatcher->getParam("method") == "create" ):
$action = "/task/new";
$template = "create";
foreach($element as $e)
{
$form->add($e);
}
# IF REQUEST IS TO UPDATE POPULATE WITH VALJUE TO ELEMENT
elseif ($this->dispatcher->getParam("method") == "modify"):
$task = Tasks::findFirst($this->dispatcher->getParam("task"));
$action = "/task/update/{$task->_}";
$template = "modify";
$element['project']->setAttribute("value",$task->project);
$element['title']->setAttribute("value",$task->title);
$element['description']->setAttribute("value",$task->description);
$element['deadline']->setAttribute("value",(new \DateTime($task->deadline))->format("d-m-Y"));
$element['assigned']->setAttribute("value",$task->assigned);
foreach($element as $e)
{
$form->add($e);
}
# IF REQUEST IS TO VIEW POPULATE WITH VALJUE TO ELEMENT
elseif ($this->dispatcher->getParam("method") == "view"):
$template = "view";
$task = Tasks::findFirst($this->dispatcher->getParam("task"));
$element['project']->setAttribute("disabled",true)->setAttribute("value",$task->project);
$element['title']->setAttribute("disabled",true)->setAttribute("value",$task->title);
$element['description']->setAttribute("disabled",true)->setAttribute("value",$task->description);
$element['deadline']->setAttribute("disabled",true)->setAttribute("value",(new \DateTime($task->deadline))->format("d-m-Y"));
$element['assigned']->setAttribute("disabled",true)->setAttribute("value",$task->assigned);
foreach($element as $e)
{
$form->add($e);
}
endif;
# POPULATE ARRAY WITH TITLE AND INPUTS FOR RENDERING
foreach($form as $f)
{
array_push($inputs,[ "title" => $f->getAttribute("title") , "input" => $f->render($f->getName()) ]);
}
# RENDER
$body = (new Mustache)->render(file_get_contents($_SERVER['DOCUMENT_ROOT']."/templates/modal.tpl"),[
$template => true,
"action" => $action,
"inputs" => $inputs
]);
endif;
return $this->response->setJsonContent([
"status" => $this->flags['status'],
"data" => [ "#{$template}" , $body ] # Modal Target , data
]);
$this->response->send();
$this->view->setRenderLevel(View::LEVEL_ACTION_VIEW);
}
}
| mit |
cellog/react-selection | .storybook/webpack.config.js | 829 | const path = require('path');
module.exports = {
resolve: {
extensions: ['', '.js', '.jsx']
},
module: {
loaders: [
{
test: /\.css?$/,
loaders: [ 'style', 'raw' ],
include: [
path.resolve(__dirname, '../')
]
},
{
test: /\.less?$/,
loader: 'style-loader!css-loader!less-loader',
include: [
path.resolve(__dirname, '../')
]
},
{test: /\.(woff|woff2)(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=10000&mimetype=application/font-woff'},
{test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=10000&mimetype=application/octet-stream'},
{test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: 'file'},
{test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=10000&mimetype=image/svg+xml'}
]
}
};
| mit |
lordmos/blink | Source/core/animation/InertAnimation.cpp | 2531 | /*
* Copyright (C) 2013 Google Inc. 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.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "core/animation/InertAnimation.h"
namespace WebCore {
PassRefPtr<InertAnimation> InertAnimation::create(PassRefPtr<AnimationEffect> effect, const Timing& timing, bool paused)
{
return adoptRef(new InertAnimation(effect, timing, paused));
}
InertAnimation::InertAnimation(PassRefPtr<AnimationEffect> effect, const Timing& timing, bool paused)
: TimedItem(timing)
, m_effect(effect)
, m_paused(paused)
{
}
PassOwnPtr<AnimationEffect::CompositableValueList> InertAnimation::sample()
{
updateInheritedTime(0);
if (!isInEffect())
return nullptr;
double iteration = currentIteration();
ASSERT(iteration >= 0);
// FIXME: Handle iteration values which overflow int.
return m_effect->sample(static_cast<int>(iteration), timeFraction());
}
double InertAnimation::calculateTimeToEffectChange(double, double) const
{
return std::numeric_limits<double>::infinity();
}
} // namespace WebCore
| mit |
apkoponen/jytkytin2015 | public/js/comp.js | 13232 | var defaultTrack, drum, instrumentNames, instruments, songs;
if (!window.btoa) {
window.btoa = function(str) {
return Base64.encode(str);
};
}
if (!window.atob) {
window.atob = function(str) {
return Base64.decode(str);
};
}
drum = angular.module('drum', ["mgcrea.ngStrap"]);
drum.filter('range', function() {
return function(val, range) {
var _i, _results;
range = parseInt(range) - 1;
return (function() {
_results = [];
for (var _i = 0; 0 <= range ? _i <= range : _i >= range; 0 <= range ? _i++ : _i--){ _results.push(_i); }
return _results;
}).apply(this);
};
});
drum.filter('trackJson', function() {
return function(object) {
if (!object) {
return '';
}
return JSON.stringify(object);
};
});
instruments = {
kick: [0, 420],
snare: [453, 434],
clap: [11383, 157],
cowbell: [908, 115],
hiTom: [1360, 602],
midTom: [1997, 851],
lowTom: [2894, 839],
hatOpen: [3756, 955],
hatClosed: [4734, 130],
ride: [4911, 962],
tamb: [5878, 277],
crash: [6830, 1267],
splash: [8127, 843],
china: [9578, 855],
hiAgogo: [10591, 433],
lowAgogo: [11095, 273],
jytkyIl: [11625, 547],
jytIl: [11625, 366],
kyIl: [11990, 191],
jytkyMas: [14235, 688],
jytMas: [14235, 369],
kyMas: [14604, 319],
jytkytetään: [11625, 1430],
tömähti: [13164, 1071],
kahenKilon: [15056, 892],
siika: [15948, 892],
hallitus: [17935, 840],
ha: [17935, 175],
kolmen: [16901, 892],
as: [17300, 366]
};
instrumentNames = Object.keys(instruments);
songs = {
"Californication - RHCP": {
"tempo": 190,
"beatCount": 8,
"channels": {
"snare": [0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1],
"kick": [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1],
"ride": [1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1],
"crash": [1],
"splash": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0]
}
}
};
defaultTrack = {
"tempo": 134,
"beatCount": 8,
"channels": {
"snare": [],
"clap": [0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0],
"kick": [1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1],
"hatClosed": [],
"hatOpen": [],
"jytkyIl": [1, 0, 0, 0, 0, 0, 0, 0, 1],
"jytIl": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1],
"kyIl": [],
"jytkyMas": [],
"jytMas": [],
"kyMas": [],
"jytkytetään": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
"tömähti": [],
"kahenKilon": [],
"siika": [],
"hallitus": [],
"ha": [],
"kolmen": [],
"as": []
}
};
drum.service("Storage", function() {
this.encode = function(track) {
return encodeURIComponent(btoa(JSON.stringify(track)));
};
this.decode = function(str) {
var e;
try {
return JSON.parse(atob(decodeURIComponent(str)));
} catch (_error) {
e = _error;
return null;
}
};
return this;
});
drum.factory("Track", function(Storage) {
var Track;
Track = function(encoded, trackData) {
var trackObj;
trackObj = null;
if (encoded) {
trackObj = Storage.decode(encoded);
if (!trackObj) {
this.invalidRawData = true;
trackObj = null;
}
} else if (trackData) {
trackObj = trackData;
}
if (trackObj == null) {
trackObj = defaultTrack;
}
this.tempo = trackObj.tempo || 120;
this.beatCount = trackObj.beatCount || 4;
this.channels = trackObj.channels || {};
return this;
};
Track.prototype.getPath = function() {
var that;
that = this;
return Storage.encode({
tempo: that.tempo,
beatCount: that.beatCount,
channels: that.channels
});
};
Track.prototype.len = function() {
return this.beatCount * 4;
};
Track.prototype.cleanup = function() {
var len, that;
that = this;
len = this.len();
return angular.forEach(this.channels, function(notes, inst) {
var n;
notes.splice(len);
return that.channels[inst] = (function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = notes.length; _i < _len; _i++) {
n = notes[_i];
_results.push(n ? n : 0);
}
return _results;
})();
});
};
return Track;
});
drum.service("Sound", function() {
var that;
this.h = new Howl({
urls: ['public/kit-hallitus.mp3', 'public/kit-hallitus.ogg'],
sprite: instruments,
volume: 1
});
that = this;
this.lastOpenHat = null;
this.play = function(name) {
return this.h.play(name, function(id) {
that.h.volume(1, id);
if (name === "hatOpen") {
return that.lastOpenHat = id;
} else if (name === "hatClosed" && that.lastOpenHat) {
that.h.stop(that.lastOpenHat);
return that.lastOpenHat = null;
}
});
};
return this;
});
drum.service("Keyboard", function() {
this.funcs = {};
this.register = function(keyCode, fn) {
return this.funcs[keyCode] = fn;
};
this.callFn = function(e) {
if (this.funcs[e.keyCode] && e.target.localName !== "input") {
e.preventDefault();
return this.funcs[e.keyCode]();
}
};
return this;
});
var tempoMs;
tempoMs = function(t) {
return ((60 / t) * 1000) / 4;
};
drum.controller("MainCtrl", function($scope, $interval, $location, $alert, Sound, Track, Keyboard) {
var lastDataGenerated, recalculate, strike, trackRawData;
$scope.instruments = instruments;
$scope.instrumentNames = instrumentNames;
trackRawData = $location.path().split("/")[1];
$scope.t = new Track(trackRawData);
if ($scope.t.invalidRawData) {
$location.path("");
$alert({
title: 'Error',
content: 'The track data in the url was invalid! (using default track instead)',
placement: 'top-right',
container: '#alerts',
type: 'danger',
duration: 8
});
}
$scope.nicenames = {
kick: 'Basari',
snare: 'Virveli',
clap: 'Läpsy',
cowbell: 'Lehmänkello',
hiTom: 'Pikku-Tommi',
midTom: 'Välimallin Tommi',
lowTom: 'Iso-Tommi',
hatOpen: 'Haikka (Auki)',
hatClosed: 'Haikka (Kiinni)',
ride: 'Ratsukko',
tamb: 'Tampuriini',
crash: 'Räiske',
splash: 'Mäiske',
china: 'Kinuski',
hiAgogo: 'Yläpihinä',
lowAgogo: 'Alapihinä',
jytkyIl: ':) JYTKY',
jytIl: ':) JYT-',
kyIl: ':) -KY',
jytkyMas: ':( JYTKY',
jytMas: ':( JYT-',
kyMas: ':( -KY',
jytkytetään: 'JYTKYTETÄÄN!',
tömähti: 'TÖMÄHTI',
kahenKilon: 'Kahen kilon',
siika: 'Siika',
hallitus: 'Hallitus',
ha: 'Ha-',
kolmen: 'Kolmen ässän',
as: 'Äs-'
};
$scope.setSong = function(name) {
$scope.t = new Track(null, songs[name]);
return ga('send', 'event', 'setSong', name);
};
$scope.chList = function() {
var list, unordered;
list = [];
unordered = Object.keys($scope.t.channels);
instrumentNames.forEach(function(i) {
if (unordered.indexOf(i) !== -1) {
return list.push(i);
}
});
return list;
};
$scope.deleteChannel = function(inst) {
return delete $scope.t.channels[inst];
};
strike = function() {
return angular.forEach($scope.t.channels, function(notes, inst) {
if (notes[$scope.seq.semi]) {
return Sound.play(inst);
}
});
};
Keyboard.register(80, strike);
$scope.seq = {
ticks: -1,
beat: -1,
semi: -1
};
$scope.advance = function() {
$scope.seq.ticks += 1;
recalculate();
return strike();
};
$scope.retreat = function() {
if ($scope.seq.ticks <= 0) {
$scope.seq.ticks = $scope.t.len();
}
$scope.seq.ticks -= 1;
recalculate();
return strike();
};
Keyboard.register(39, $scope.advance);
Keyboard.register(76, $scope.advance);
Keyboard.register(37, $scope.retreat);
Keyboard.register(72, $scope.retreat);
recalculate = function() {
$scope.seq.semi = $scope.seq.ticks % ($scope.t.beatCount * 4);
return $scope.seq.beat = Math.floor($scope.seq.semi / 4);
};
$scope.testPlay = function(inst) {
return Sound.play(inst);
};
lastDataGenerated = "";
$scope.generateRawData = function() {
var rawData;
$scope.t.cleanup();
rawData = $scope.t.getPath();
if (rawData === lastDataGenerated) {
return;
}
lastDataGenerated = rawData;
return ga('send', 'event', 'permalink', 'generate');
};
$scope.permalink = function() {
$location.path(lastDataGenerated);
$scope.permalinkNow = $location.absUrl();
return $location.absUrl();
};
$scope.keyPressed = function(e) {
return Keyboard.callFn(e);
};
return $scope.isEmpty = function(obj) {
return !obj || angular.equals({}, obj);
};
});
drum.controller("PlayCtrl", function($scope, $interval, Keyboard) {
$scope.heartbeat = null;
$scope.reset = function() {
$scope.off();
$scope.seq.ticks = -1;
$scope.seq.beat = -1;
return $scope.seq.semi = -1;
};
Keyboard.register(83, $scope.reset);
$scope.toggle = function() {
if ($scope.heartbeat) {
return $scope.off();
} else {
return $scope.on();
}
};
Keyboard.register(32, $scope.toggle);
$scope.on = function() {
if ($scope.heartbeat) {
return;
}
return $scope.heartbeat = $interval($scope.advance, tempoMs($scope.t.tempo));
};
$scope.off = function() {
if (!$scope.heartbeat) {
return;
}
$interval.cancel($scope.heartbeat);
return $scope.heartbeat = null;
};
$scope.addChannel = function(inst) {
if (!$scope.instruments[inst] || $scope.t.channels[inst]) {
return;
}
return $scope.t.channels[inst] = [0];
};
$scope.changeTempo = function(diff) {
if (diff) {
$scope.t.tempo += diff;
}
if ($scope.t.tempo < 1) {
$scope.t.tempo = 1;
}
if ($scope.t.tempo > 350) {
$scope.t.tempo = 350;
}
if ($scope.heartbeat) {
$scope.off();
$scope.on();
}
return false;
};
Keyboard.register(49, function() {
return $scope.changeTempo(-1);
});
Keyboard.register(50, function() {
return $scope.changeTempo(1);
});
$scope.changeBeatCount = function(diff) {
var n;
if (diff) {
n = $scope.t.beatCount;
n += diff;
} else {
n = $scope.beatCountBox;
}
$scope.editingBeatCount = null;
if (n < 1) {
n = 1;
}
if (n > 64) {
n = 64;
}
return $scope.t.beatCount = n;
};
Keyboard.register(51, function() {
return $scope.changeBeatCount(-1);
});
Keyboard.register(52, function() {
return $scope.changeBeatCount(1);
});
$scope.songNames = Object.keys(songs);
return $scope.useSong = function(name) {
$scope.reset();
return $scope.setSong(name);
};
});
drum.controller("GridCtrl", function($scope, Keyboard) {
var moveChannel;
$scope.curCh = {
num: -1,
name: ""
};
moveChannel = function(diff) {
var chList, newName, newNum;
chList = $scope.chList();
newNum = $scope.curCh.num + diff;
if (newNum >= chList.length) {
newNum = 0;
} else if (newNum <= -1) {
newNum = chList.length - 1;
}
newName = chList[newNum];
if ($scope.seq.semi === -1) {
$scope.seq.semi = 0;
$scope.seq.beat = 0;
$scope.seq.ticks = 0;
}
$scope.curCh.num = newNum;
$scope.curCh.name = newName;
if ($scope.t.channels[newName][$scope.seq.semi]) {
return $scope.testPlay(newName);
}
};
Keyboard.register(38, function() {
return moveChannel(-1);
});
Keyboard.register(75, function() {
return moveChannel(-1);
});
Keyboard.register(40, function() {
return moveChannel(1);
});
Keyboard.register(74, function() {
return moveChannel(1);
});
$scope.noteClasses = function(chan, beat, tick) {
var s, sq;
s = "";
sq = (beat * 4) + tick;
s += $scope.t.channels[chan][sq] ? "on" : "off";
if (sq === $scope.seq.semi) {
s += " active";
}
return s;
};
$scope.toggleNote = function(chan, sq) {
var a;
a = $scope.t.channels[chan];
return a[sq] = a[sq] === 1 ? 0 : 1;
};
return Keyboard.register(73, function() {
return $scope.toggleNote($scope.curCh.name, $scope.seq.semi);
});
});
drum.directive("focusMe", function($timeout, $parse) {
return {
link: function(scope, element, attrs) {
var model;
model = $parse(attrs.focusMe);
scope.$watch(model, function(value) {
if (value === true) {
return $timeout(function() {
return element[0].focus();
});
}
});
return element.bind("blur", function() {
return scope.$apply(model.assign(scope, false));
});
}
};
});
drum.directive("selectAllOnClick", function($timeout) {
return {
link: function(scope, element, attrs) {
return $timeout(function() {
element[0].focus();
return element[0].select();
});
}
};
});
| mit |
OctoLinker/browser-extension | packages/blob-reader/index.js | 1530 | import Blob from './blob';
import {
getBlobWrapper,
getPath,
readLines,
getParentSha,
isGist,
} from './helper';
function parseBlob(el) {
const path = getPath(el);
const lines = readLines(el);
if (!lines.length) {
return;
}
// Does not work if left side is empty (eg new files) https://github.com/OctoLinker/OctoLinker/commit/b97dfbfdbf3dee5f4836426e6dac6d6f473461db?diff=split#diff-e56633f72ecc521128b3db6586074d2c
const isDiff =
lines.filter(({ side }) => ['left', 'right'].includes(side)).length > 0;
if (isDiff) {
const diffLineFilter = (type) => ({ side, ...rest }) => {
if ([type, 'context'].includes(side)) {
return { ...rest };
}
};
const leftBlob = new Blob({
el,
path,
lines: lines.map(diffLineFilter('left')).filter(Boolean),
branch: getParentSha(),
type: 'diffLeft',
});
const rightBlob = new Blob({
el,
path,
lines: lines.map(diffLineFilter('right')).filter(Boolean),
type: 'diffRight',
});
return [leftBlob, rightBlob];
}
let type = isGist() ? 'gist' : 'full';
if (el.getElementsByTagName('pre').length) {
type = 'snippet';
}
return new Blob({ el, path, lines, type });
}
export default class BlobReader {
hasBlobs() {
return !!getBlobWrapper(document).length;
}
read(rootElement) {
return [].concat(
...getBlobWrapper(rootElement)
.map((el) => {
return parseBlob(el);
})
.filter(Boolean),
);
}
}
| mit |