code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
// Copyright (c) 2017-2021 offa
//
// 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 "danek/internal/ToString.h"
#include "danek/internal/ConfigItem.h"
#include "danek/internal/ConfigScope.h"
#include "danek/internal/UidIdentifierProcessor.h"
#include <algorithm>
#include <array>
#include <iterator>
#include <sstream>
namespace danek
{
namespace
{
const std::array<std::pair<std::string, std::string>, 4> escapeSequences{
{{"%", "%%"}, {"\t", "%t"}, {"\n", "%n"}, {"\"", "%\""}}};
std::string indent(std::size_t level)
{
constexpr std::size_t indentCount{4};
return std::string(level * indentCount, ' ');
}
void replaceInplace(std::string& input, const std::string& str, const std::string& replacement)
{
if (str.empty() == false)
{
std::size_t pos = 0;
while ((pos = input.find(str, pos)) != std::string::npos)
{
input.replace(pos, str.size(), replacement);
pos += replacement.size();
}
}
}
std::string escape(const std::string& str)
{
auto output = str;
std::for_each(escapeSequences.cbegin(), escapeSequences.cend(),
[&output](const auto& v) { replaceInplace(output, v.first, v.second); });
return "\"" + output + "\"";
}
std::string expandUid(const std::string& name, bool expand)
{
if (expand == false)
{
UidIdentifierProcessor uidIdProc;
return uidIdProc.unexpand(name);
}
return name;
}
void appendConfType(std::stringstream& stream, const ConfigScope& scope, ConfType type, bool expandUid,
std::size_t indentLevel)
{
auto names = scope.listLocallyScopedNames(type, false, {});
std::sort(names.begin(), names.end());
std::for_each(names.cbegin(), names.cend(), [&stream, &scope, expandUid, indentLevel](const auto s) {
const auto item = scope.findItem(s);
stream << toString(*item, item->name(), expandUid, indentLevel);
});
}
}
std::string toString(const ConfigItem& item, const std::string& name, bool expandUidNames, std::size_t indentLevel)
{
const std::string nameStr = expandUid(name, expandUidNames);
std::stringstream os;
os << indent(indentLevel);
switch (item.type())
{
case ConfType::String:
os << nameStr << " = " << escape(item.stringVal()) << ";\n";
break;
case ConfType::List:
{
os << nameStr << " = [";
const auto& values = item.listVal();
if (values.empty() == false)
{
using OItr = std::ostream_iterator<std::string>;
std::transform(values.cbegin(), std::prev(values.cend()), OItr{os, ", "}, escape);
std::transform(std::prev(values.cend()), values.cend(), OItr{os}, escape);
}
os << "];\n";
}
break;
case ConfType::Scope:
{
os << nameStr << " {\n"
<< toString(*(item.scopeVal()), expandUidNames, indentLevel + 1) << indent(indentLevel) << "}\n";
}
break;
default:
break;
}
return os.str();
}
std::string toString(const ConfigScope& scope, bool expandUidNames, std::size_t indentLevel)
{
std::stringstream ss;
appendConfType(ss, scope, ConfType::Variables, expandUidNames, indentLevel);
appendConfType(ss, scope, ConfType::Scope, expandUidNames, indentLevel);
return ss.str();
}
}
| offa/danek | src/danek/internal/ToString.cpp | C++ | mit | 5,007 |
<?php
namespace PHPStrap\Form\Validation;
class BaseValidation{
protected $errormessage;
/**
* @param string $errormessage
* @return void
*/
public function __construct($errormessage){
$this->errormessage = $errormessage;
}
/**
* @return string
*/
public function errorMessage(){
return $this->errormessage;
}
}
?> | kktuax/PHPStrap | src/PHPStrap/Form/Validation/BaseValidation.php | PHP | mit | 364 |
<?php
namespace MindOfMicah\LaravelDatatables\DatatableQuery;
class Sorter
{
private $column_index;
private $direction;
public function __construct($column_index, $direction = 'ASC')
{
$this->column_index = $column_index;
$this->direction = $direction;
}
public function toArray()
{
return [
'col' => $this->column_index,
'dir' => strtolower($this->direction)
];
}
}
| mindofmicah/laravel-datatables | src/MindOfMicah/LaravelDatatables/DatatableQuery/Sorter.php | PHP | mit | 459 |
/* jshint unused: false */
/* global describe, before, beforeEach, afterEach, after, it, xdescribe, xit */
'use strict';
var fs = require('fs');
var restify = require('restify');
var orm = require('orm');
var assert = require('assert');
var restormify = require('../');
var dbProps = {host: 'logger', protocol: 'sqlite'};
var server = restify.createServer();
var client;
var db;
var baz;
server.use(restify.bodyParser());
server.use(restify.queryParser());
describe('node-orm2 validations', function(){
before(function(done){
orm.connect(dbProps, function(err, database){
if(err){
done(err);
}
db = database;
restormify({
db: db,
server: server
}, function(){
baz = db.define('baz', {
name: String,
email: {type: 'text', unique: true},
deleted: {type: 'boolean', serverOnly: true},
foo: {type: 'boolean', serverOnly: true}
},
{validations: {
name: orm.enforce.ranges.length(3, undefined, 'too small')
}});
done();
});
});
client = restify.createJsonClient({
url: 'http://localhost:1234/api'
});
});
describe('api', function(){
beforeEach(function(done){
server.listen(1234);
baz.sync(done);
});
it('rejects unique constraints', function(done){
var bazzer = {name: 'foo', email: 'foo@foo.bar'};
client.post('/api/baz', bazzer, function(err, req, res){
client.post('/api/baz', bazzer, function(err, req, res){
assert.equal(res.statusCode, 409, '490 Conflict recieved');
assert.equal(err.message, 'baz already exists', 'unique constraint');
done();
});
});
});
it('rejects validation matching', function(done){
var bazzer = {name: 'fo', email:'foo@foo.bar'};
client.post('/api/baz', bazzer, function(err, req, res){
assert.equal(res.statusCode, 400, 'invalid content rejected');
assert.equal(err.message, 'too small', 'validation message matches');
done();
});
});
afterEach(function(done){
server.close();
db.drop(done);
});
});
after(function(done){
db.close();
fs.unlink(dbProps.host, function(){
done();
});
});
});
| toddself/restormify | test/validation-bubbling.js | JavaScript | mit | 2,293 |
require 'sinatra'
require 'cgi'
require 'json'
require 'sequel'
require 'logger'
require 'zlib'
require 'base64'
require 'digest'
configure :production do
require 'newrelic_rpm'
$production = true
end
DB = Sequel.connect(ENV['MYSQL_DB_URL'] || 'mysql2://root@localhost/android_census',
:max_connections => 15,
:ssl_mode => :required)
#:logger => Logger.new('db.log'))
DB.extension(:error_sql)
DB.extension(:connection_validator)
DB.pool.connection_validation_timeout = 30
#Sequel::MySQL.default_collate = 'utf8_bin'
require_relative 'data_models'
def assert(&block)
raise "Assertion error" unless yield
end
error 400..510 do
'Error!'
end
# In production we limit calls to results posting/reading/processing endpoints.
def check_production_password(request)
if $production &&
(!request.env['HTTP_AUTHORIZATION'] ||
request.env['HTTP_AUTHORIZATION'] != ENV['ACCESS_CONTROL_PASSWORD'])
status 403
raise "Incorrect password"
end
end
get '/' do
erb :index
end
get '/devices' do
erb :devices, :locals => { :devices => Device.all }
end
get '/devices/:id' do |id|
return 404 if !Device[id]
erb :device, :locals => { :device => Device[id] }
end
get '/devices/:id/system_properties' do |id|
return 404 if !Device[id]
erb :device_generic_view, :locals => {
:data => Device[id].system_properties,
:header => "System Properties",
:model => SystemProperty
}
end
get '/devices/:id/sysctls' do |id|
return 404 if !Device[id]
erb :device_generic_view, :locals => {
:data => Device[id].sysctls,
:header => "Sysctls",
:model => Sysctl
}
end
get '/devices/:id/environment_variables' do |id|
return 404 if !Device[id]
erb :device_generic_view, :locals => {
:data => Device[id].environment_variables,
:header => "Environment Variables",
:model => EnvironmentVariable
}
end
get '/devices/:id/features' do |id|
return 404 if !Device[id]
erb :device_generic_view, :locals => {
:data => Device[id].features,
:header => "Features",
:model => Feature
}
end
get '/devices/:id/shared_libraries' do |id|
return 404 if !Device[id]
erb :device_generic_view, :locals => {
:data => Device[id].shared_libraries,
:header => "Shared Libraries",
:model => SharedLibrary
}
end
get '/devices/:id/permissions' do |id|
return 404 if !Device[id]
erb :device_generic_view, :locals => {
:data => Device[id].permissions,
:header => "Permissions",
:model => Permission
}
end
get '/devices/:id/providers' do |id|
return 404 if !Device[id]
erb :device_generic_view, :locals => {
:data => Device[id].content_providers,
:header => "Content Providers",
:model => ContentProvider
}
end
get '/devices/:id/small_files' do |id|
return 404 if !Device[id]
erb :device_small_files, :locals => {
:id => id,
:paths => SmallFile.where(:device_id => id).select_map(:path)
}
end
get '/devices/:id/small_files/*' do |id, path|
return 404 if !Device[id]
file = SmallFile.where(:device_id => id, :path => '/' + path).all.first
return 404 if !file
content_type 'text/plain'
file[:contents]
end
get '/devices/:id/file_permissions' do |id|
return 404 if !Device[id]
erb :device_generic_view, :locals => {
:data => Device[id].file_permissions,
:header => "File Permissions",
:model => FilePermission
}
end
get '/sysctls/:property' do |property|
erb :by_device_generic_view, :locals => {
:model => Sysctl,
:index => property
}
end
get '/system_properties/:property' do |property|
erb :by_device_generic_view, :locals => {
:model => SystemProperty,
:index => property
}
end
get '/environment_variables/:variable' do |variable|
erb :by_device_generic_view, :locals => {
:model => EnvironmentVariable,
:index => variable
}
end
get '/file_permissions/*' do |file|
erb :by_device_generic_view, :locals => {
:model => FilePermission,
:index => '/' + file
}
end
get '/permissions/:provider' do |permission|
erb :by_device_generic_view, :locals => {
:model => Permission,
:index => permission
}
end
get '/content_providers/:provider' do |provider|
erb :by_device_generic_view, :locals => {
:model => ContentProvider,
:index => provider
}
end
get '/features/:feature' do |feature|
erb :feature, :locals => {
:feature => feature,
:devices => Feature.where(:name => feature).all[0].devices
}
end
get '/shared_libraries/:feature' do |feature|
erb :feature, :locals => {
:feature => feature,
:devices => SharedLibrary.where(:name => feature).all[0].devices
}
end
get '/piechart/versions.json' do
versions = DB[:system_properties].where(:property => 'ro.build.version.release').select_map(:value)
data = versions.group_by(&:to_s).map do |version, arr|
{
'label' => version,
'value' => arr.count
}
end
JSON.generate(data)
end
get '/piechart/manufacturers.json' do
manufacturers = DB[:system_properties].where(:property => 'ro.product.manufacturer').select_map(:value)
manufacturers.map!(&:upcase)
data = manufacturers.group_by(&:to_s).map do |version, arr|
{
'label' => version,
'value' => arr.count
}
end
JSON.generate(data)
end
post '/results/new' do
check_production_password(request)
Result.create(:data => request.body.read, :processed => false)
''
end
get '/results/:id' do |id|
check_production_password(request)
Zlib::Inflate.inflate(Result[id][:data])
end
def process_result(result)
json = JSON.parse(Zlib::Inflate.inflate(result[:data]))
DB.transaction do
# Fix jacked up naming inconsistencies
device_name = json["device_name"]
device_name.gsub!(/^asus/i, 'ASUS')
device_name.gsub!(/^acer/i, 'Acer')
device_name.gsub!(/^lge/i, 'LG')
device_name.gsub!(/^huawei/i, 'Huawei')
device_name.gsub!(/^samsung/i, 'Samsung')
device_name.gsub!(/^motorola/i, 'Motorola')
device_name.gsub!(/^oppo/i, 'OPPO')
device_name.gsub!(/^sharp/i, 'Sharp')
device_name.gsub!(/^toshiba/i, 'Toshiba')
device_name.gsub!(/^fujitsu/i, 'Fujitsu')
device_name.gsub!(/^lenovo/i, 'Lenovo')
device_name.gsub!(/^kyocera/i, 'Kyocera')
device_name.gsub!(/^fuhu/i, 'Fuhu')
device_name.gsub!(/^meizu/i, 'Meizu')
device_name.gsub!(/^tct( alcatel)?/i, 'Alcatel')
device_name.gsub!(/^coolpad/i, 'YuLong Coolpad')
device_name.gsub!(/^nubia nx40x/i, 'ZTE Nubia NX40X')
device_name.gsub!(/^unknown 8150/i, 'YuLong Coolpad 8150')
device_name.gsub!(/^unknown lenovo/i, 'Lenovo')
device_name.gsub!('_one_touch_', ' ONE TOUCH ')
if json['system_properties'] && json['system_properties']['ro.build.description']
build_description = json['system_properties']['ro.build.description']
else
build_description = device_name
end
# Don't create a new device entry if we don't need to, re-use the same one but delete old
# entries in other tables
dsearch = Device.where(:name => device_name, :build_description => build_description)
if dsearch.count == 0
device = Device.create(:name => device_name, :build_description => build_description)
else
device = dsearch.all[0]
[ :system_properties, :sysctls, :devices_features, :devices_shared_libraries,
:permissions, :small_files, :file_permissions, :content_providers,
:environment_variables ].each { |table_name|
DB[table_name].where(:device_id => device[:id]).delete
}
end
if json["system_properties"]
DB[:system_properties].multi_insert(
json["system_properties"].map do |k,v|
{ :property => k, :value => v, :device_id => device[:id] }
end
)
end
if json["sysctl"]
DB[:sysctls].multi_insert(
json["sysctl"].map do |k,v|
{ :property => k, :value => v, :device_id => device[:id] }
end
)
end
if json["features"]
all_features = json["features"]
json["features"].uniq!(&:downcase)
new_features = all_features - DB[:features].distinct(:name).select_map(:name)
DB[:features].multi_insert(new_features.map { |f| {:name => f} })
feature_ids = DB[:features].where('name in ?', json["features"]).map { |f| f[:id] }
DB[:devices_features].multi_insert(
feature_ids.map do |id|
{ :device_id => device[:id], :feature_id => id }
end
)
assert { json["features"].length == device.features.length }
end
if json["system_shared_libraries"]
new_libraries = json["system_shared_libraries"] - DB[:shared_libraries].distinct(:name).select_map(:name)
DB[:shared_libraries].multi_insert(new_libraries.map { |l| {:name => l} })
library_ids = DB[:shared_libraries].where('name in ?', json["system_shared_libraries"]).map { |l| l[:id] }
DB[:devices_shared_libraries].multi_insert(
library_ids.map do |id|
{ :device_id => device[:id], :shared_library_id => id }
end
)
assert { json["system_shared_libraries"].length == device.shared_libraries.length }
end
if json["permissions"]
DB[:permissions].multi_insert(
json["permissions"].map do |data|
{
:name => data["name"],
:package_name => data["packageName"],
:protection_level => data["protectionLevel"].to_i,
:flags => data["flags"].to_i,
:device_id => device[:id],
}
end
)
end
if json["small_files"]
DB[:small_files].multi_insert(
json["small_files"].map do |k, v|
{ :path => k, :contents => Base64.decode64(v), :device_id => device[:id] }
end
)
end
if json["file_permissions"]
DB[:file_permissions].multi_insert(
json["file_permissions"].map do |data|
{
:path => data['path'],
:link_path => data['linkPath'],
:mode => data['mode'],
:size => data['size'],
:uid => data['uid'],
:gid => data['gid'],
:selinux_context => data['selinuxContext'],
:device_id => device[:id]
}
end
)
end
if json["providers"]
DB[:content_providers].multi_insert(
json["providers"].map do |data|
{
:authority => data["authority"],
:init_order => data["initOrder"],
:multiprocess => data["multiprocess"],
:grant_uri_permissions => data["grantUriPermissions"],
:read_permission => data["readPermission"],
:write_permission => data["writePermission"],
:path_permissions => data["pathPermissions"],
:uri_permission_patterns => data["uriPermissionPatterns"],
:flags => data["flags"],
:device_id => device[:id]
}
end
)
end
if json["environment_variables"]
DB[:environment_variables].multi_insert(
json["environment_variables"].map do |k,v|
{ :variable => k, :value => v, :device_id => device[:id] }
end
)
end
DB[:results].where(:id => result[:id]).update({:processed => true})
end
end
get '/process_results' do
check_production_password(request)
Thread.new {
# First things first, delete duplicate entries.
# { data_sha256_hash => result_id }
hashes = {}
DB[:results].all.each { |result|
hash = Digest::SHA256.digest(result[:data])
if hashes[hash]
if result[:processed]
DB[:results].where(:id => hashes[hash]).delete
hashes[hash] = result[:id]
else
DB[:results].where(:id => result[:id]).delete
end
else
hashes[hash] = result[:id]
end
}
# Now process unprocessed results
DB[:results].where(:processed => false).each { |result|
begin
process_result(result)
rescue => e
$stderr.puts e.inspect
$stderr.puts e.backtrace
end
}
}
""
end
| vlad902/census.tsyrklevich.net | web.rb | Ruby | mit | 12,074 |
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Item = function Item() {
_classCallCheck(this, Item);
this.chords = '';
this.lyrics = '';
};
exports.default = Item; | aggiedefenders/aggiedefenders.github.io | node_modules/chordsheetjs/lib/chord_sheet/item.js | JavaScript | mit | 364 |
//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);
//>>description: A handler for css transition & animation end events to ensure callback is executed
//>>label: Animation Complete
//>>group: Core
define( [
"jquery"
], function( jQuery ) {
//>>excludeEnd("jqmBuildExclude");
(function( $, undefined ) {
var props = {
"animation": {},
"transition": {}
},
testElement = document.createElement( "a" ),
vendorPrefixes = [ "", "webkit-", "moz-", "o-" ];
$.each( [ "animation", "transition" ], function( i, test ) {
// Get correct name for test
var testName = ( i === 0 ) ? test + "-" + "name" : test;
$.each( vendorPrefixes, function( j, prefix ) {
if ( testElement.style[ $.camelCase( prefix + testName ) ] !== undefined ) {
props[ test ][ "prefix" ] = prefix;
return false;
}
});
// Set event and duration names for later use
props[ test ][ "duration" ] =
$.camelCase( props[ test ][ "prefix" ] + test + "-" + "duration" );
props[ test ][ "event" ] =
$.camelCase( props[ test ][ "prefix" ] + test + "-" + "end" );
// All lower case if not a vendor prop
if ( props[ test ][ "prefix" ] === "" ) {
props[ test ][ "duration" ] = props[ test ][ "duration" ].toLowerCase();
props[ test ][ "event" ] = props[ test ][ "event" ].toLowerCase();
}
});
// If a valid prefix was found then the it is supported by the browser
$.support.cssTransitions = ( props[ "transition" ][ "prefix" ] !== undefined );
$.support.cssAnimations = ( props[ "animation" ][ "prefix" ] !== undefined );
// Remove the testElement
$( testElement ).remove();
// Animation complete callback
$.fn.animationComplete = function( callback, type, fallbackTime ) {
var timer, duration,
that = this,
animationType = ( !type || type === "animation" ) ? "animation" : "transition";
// Make sure selected type is supported by browser
if ( ( $.support.cssTransitions && animationType === "transition" ) ||
( $.support.cssAnimations && animationType === "animation" ) ) {
// If a fallback time was not passed set one
if ( fallbackTime === undefined ) {
// Make sure the was not bound to document before checking .css
if ( $( this ).context !== document ) {
// Parse the durration since its in second multiple by 1000 for milliseconds
// Multiply by 3 to make sure we give the animation plenty of time.
duration = parseFloat(
$( this ).css( props[ animationType ].duration )
) * 3000;
}
// If we could not read a duration use the default
if ( duration === 0 || duration === undefined ) {
duration = $.fn.animationComplete.default;
}
}
// Sets up the fallback if event never comes
timer = setTimeout( function() {
$( that ).off( props[ animationType ].event );
callback.apply( that );
}, duration );
// Bind the event
return $( this ).one( props[ animationType ].event, function() {
// Clear the timer so we dont call callback twice
clearTimeout( timer );
callback.call( this, arguments );
});
} else {
// CSS animation / transitions not supported
// Defer execution for consistency between webkit/non webkit
setTimeout( $.proxy( callback, this ), 0 );
return $( this );
}
};
// Allow default callback to be configured on mobileInit
$.fn.animationComplete.default = 1000;
})( jQuery );
//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);
});
//>>excludeEnd("jqmBuildExclude");
| ericsteele/retrospec.js | test/input/projects/jquery-mobile/rev-1.4.1-3455ada/js/jquery.mobile.animationComplete.js | JavaScript | mit | 3,468 |
require "spec_helper"
describe Architect4r::Model::Relationship do
let(:person) { Person.create(:name => 'Niobe', :human => true) }
let(:ship) { Ship.create(:name => 'Logos', :crew_size => 2) }
describe "initialization of new instances" do
it "should accept zero arguments" do
lambda { CrewMembership.new }.should_not raise_error(ArgumentError)
end
it "should accept just a hash of properties" do
ms = CrewMembership.new( :rank => 'Captain' )
ms.rank.should == 'Captain'
end
it "should accept the source and destination node" do
ms = CrewMembership.new(ship, person)
ms.source.should == ship
ms.destination.should == person
end
it "should accept the source node, destination node, and properties" do
ms = CrewMembership.new(ship, person, { :rank => 'Captain' })
ms.source.should == ship
ms.destination.should == person
ms.rank.should == 'Captain'
end
it "should always require a source and destination" do
fs = CrewMembership.new(:member_since => DateTime.new, :rank => 'Captain')
fs.valid?.should be_false
end
end
describe "Creating a new relationship" do
it "should create a new relationship" do
ms = CrewMembership.new(ship, person)
ms.save.should be_true
ms.persisted?.should be_true
end
it "should allow changing relationship properties" do
ms = CrewMembership.new(ship, person, { :rank => 'Captain' })
ms.save.should be_true
ms.rank = 'Operator'
ms.save.should be_true
end
it "should allow deleting relationships" do
ms = CrewMembership.new(ship, person, { :rank => 'Captain' })
ms.save.should be_true
ms.destroy.should be_true
end
end
describe "Retrieve records from the store" do
it "should allow fetching a record by its id" do
CrewMembership.should respond_to(:find)
end
it "should instantiate a relationship model" do
ms = CrewMembership.create(ship, person, { :rank => 'Captain' })
CrewMembership.find(ms.id).should be_a(CrewMembership)
end
end
describe "Should populate source and destination after retrieval from storage" do
let(:membership) { CrewMembership.create(ship, person, { :rank => 'Captain' }) }
subject { CrewMembership.find(membership.id) }
it { should respond_to(:source) }
it { should respond_to(:destination) }
it "should populate the source after retrieval" do
subject.source.id.should == ship.id
end
it "should populate the destination after retrieval" do
subject.destination.id.should == person.id
end
end
end | namxam/architect4r | spec/model/relationship_spec.rb | Ruby | mit | 2,756 |
package com.cloutteam.jarcraftinator.exceptions;
public class PluginUnloadedException extends RuntimeException {
public PluginUnloadedException(String message){
super(message);
}
}
| Clout-Team/JarCraftinator | src/main/java/com/cloutteam/jarcraftinator/exceptions/PluginUnloadedException.java | Java | mit | 200 |
package demoinfocs
import (
"fmt"
"io"
"math"
"sync"
"time"
"github.com/gogo/protobuf/proto"
"github.com/markus-wa/go-unassert"
dispatch "github.com/markus-wa/godispatch"
"github.com/pkg/errors"
common "github.com/markus-wa/demoinfocs-golang/v2/pkg/demoinfocs/common"
events "github.com/markus-wa/demoinfocs-golang/v2/pkg/demoinfocs/events"
msg "github.com/markus-wa/demoinfocs-golang/v2/pkg/demoinfocs/msg"
)
const maxOsPath = 260
const (
playerWeaponPrefix = "m_hMyWeapons."
playerWeaponPrePrefix = "bcc_nonlocaldata."
gameRulesPrefix = "cs_gamerules_data"
)
// Parsing errors
var (
// ErrCancelled signals that parsing was cancelled via Parser.Cancel()
ErrCancelled = errors.New("parsing was cancelled before it finished (ErrCancelled)")
// ErrUnexpectedEndOfDemo signals that the demo is incomplete / corrupt -
// these demos may still be useful, check how far the parser got.
ErrUnexpectedEndOfDemo = errors.New("demo stream ended unexpectedly (ErrUnexpectedEndOfDemo)")
// ErrInvalidFileType signals that the input isn't a valid CS:GO demo.
ErrInvalidFileType = errors.New("invalid File-Type; expecting HL2DEMO in the first 8 bytes (ErrInvalidFileType)")
)
// ParseHeader attempts to parse the header of the demo and returns it.
// If not done manually this will be called by Parser.ParseNextFrame() or Parser.ParseToEnd().
//
// Returns ErrInvalidFileType if the filestamp (first 8 bytes) doesn't match HL2DEMO.
func (p *parser) ParseHeader() (common.DemoHeader, error) {
var h common.DemoHeader
h.Filestamp = p.bitReader.ReadCString(8)
h.Protocol = p.bitReader.ReadSignedInt(32)
h.NetworkProtocol = p.bitReader.ReadSignedInt(32)
h.ServerName = p.bitReader.ReadCString(maxOsPath)
h.ClientName = p.bitReader.ReadCString(maxOsPath)
h.MapName = p.bitReader.ReadCString(maxOsPath)
h.GameDirectory = p.bitReader.ReadCString(maxOsPath)
h.PlaybackTime = time.Duration(p.bitReader.ReadFloat() * float32(time.Second))
h.PlaybackTicks = p.bitReader.ReadSignedInt(32)
h.PlaybackFrames = p.bitReader.ReadSignedInt(32)
h.SignonLength = p.bitReader.ReadSignedInt(32)
if h.Filestamp != "HL2DEMO" {
return h, ErrInvalidFileType
}
// Initialize queue if the buffer size wasn't specified, the amount of ticks
// seems to be a good indicator of how many events we'll get
if p.msgQueue == nil {
p.initMsgQueue(msgQueueSize(h.PlaybackTicks))
}
p.header = &h
return h, nil
}
func msgQueueSize(ticks int) int {
const (
msgQueueMinSize = 50000
msgQueueMaxSize = 500000
)
size := math.Max(msgQueueMinSize, float64(ticks))
size = math.Min(msgQueueMaxSize, size)
return int(size)
}
// ParseToEnd attempts to parse the demo until the end.
// Aborts and returns ErrCancelled if Cancel() is called before the end.
//
// See also: ParseNextFrame() for other possible errors.
func (p *parser) ParseToEnd() (err error) {
defer func() {
// Make sure all the messages of the demo are handled
p.msgDispatcher.SyncAllQueues()
p.msgDispatcher.RemoveAllQueues()
// Close msgQueue
if p.msgQueue != nil {
close(p.msgQueue)
}
if err == nil {
err = recoverFromUnexpectedEOF(recover())
}
// any errors that happened during SyncAllQueues()
if err == nil {
err = p.error()
}
}()
if p.header == nil {
_, err = p.ParseHeader()
if err != nil {
return
}
}
for {
if !p.parseFrame() {
return p.error()
}
if err = p.error(); err != nil {
return
}
}
}
func recoverFromUnexpectedEOF(r interface{}) error {
if r == nil {
return nil
}
if r == io.ErrUnexpectedEOF || r == io.EOF {
return ErrUnexpectedEndOfDemo
}
switch err := r.(type) {
case dispatch.ConsumerCodePanic:
panic(err.Value())
default:
panic(err)
}
}
// Cancel aborts ParseToEnd() and drains the internal event queues.
// No further events will be sent to event or message handlers after this.
func (p *parser) Cancel() {
p.setError(ErrCancelled)
p.eventDispatcher.UnregisterAllHandlers()
p.msgDispatcher.UnregisterAllHandlers()
}
/*
ParseNextFrame attempts to parse the next frame / demo-tick (not ingame tick).
Returns true unless the demo command 'stop' or an error was encountered.
May return ErrUnexpectedEndOfDemo for incomplete / corrupt demos.
May panic if the demo is corrupt in some way.
See also: ParseToEnd() for parsing the complete demo in one go (faster).
*/
func (p *parser) ParseNextFrame() (moreFrames bool, err error) {
defer func() {
// Make sure all the messages of the frame are handled
p.msgDispatcher.SyncAllQueues()
// Close msgQueue (only if we are done)
if p.msgQueue != nil && !moreFrames {
p.msgDispatcher.RemoveAllQueues()
close(p.msgQueue)
}
if err == nil {
err = recoverFromUnexpectedEOF(recover())
}
}()
if p.header == nil {
_, err = p.ParseHeader()
if err != nil {
return
}
}
moreFrames = p.parseFrame()
return moreFrames, p.error()
}
// Demo commands as documented at https://developer.valvesoftware.com/wiki/DEM_Format
type demoCommand byte
const (
dcSignon demoCommand = 1
dcPacket demoCommand = 2
dcSynctick demoCommand = 3
dcConsoleCommand demoCommand = 4
dcUserCommand demoCommand = 5
dcDataTables demoCommand = 6
dcStop demoCommand = 7
dcCustomData demoCommand = 8
dcStringTables demoCommand = 9
)
//nolint:funlen,cyclop
func (p *parser) parseFrame() bool {
cmd := demoCommand(p.bitReader.ReadSingleByte())
// Send ingame tick number update
p.msgQueue <- ingameTickNumber(p.bitReader.ReadSignedInt(32))
// Skip 'player slot'
const nSlotBits = 8
p.bitReader.Skip(nSlotBits) //nolint:wsl
debugDemoCommand(cmd)
switch cmd {
case dcSynctick:
// Ignore
case dcStop:
return false
case dcConsoleCommand:
// Skip
p.bitReader.Skip(p.bitReader.ReadSignedInt(32) << 3)
case dcDataTables:
p.msgDispatcher.SyncAllQueues()
p.bitReader.BeginChunk(p.bitReader.ReadSignedInt(32) << 3)
p.stParser.ParsePacket(p.bitReader)
p.bitReader.EndChunk()
debugAllServerClasses(p.ServerClasses())
p.mapEquipment()
p.bindEntities()
p.eventDispatcher.Dispatch(events.DataTablesParsed{})
case dcStringTables:
p.msgDispatcher.SyncAllQueues()
p.parseStringTables()
case dcUserCommand:
// Skip
p.bitReader.Skip(32)
p.bitReader.Skip(p.bitReader.ReadSignedInt(32) << 3)
case dcSignon:
fallthrough
case dcPacket:
p.parsePacket()
case dcCustomData:
// Might as well panic since we'll be way off if we dont skip the whole thing
panic("Found CustomData but not handled")
default:
panic(fmt.Sprintf("I haven't programmed that pathway yet (command %v unknown)", cmd))
}
// Queue up some post processing
p.msgQueue <- frameParsedToken
return true
}
var byteSlicePool = sync.Pool{
New: func() interface{} {
s := make([]byte, 0, 256)
return &s
},
}
var defaultNetMessageCreators = map[int]NetMessageCreator{
// We could pool CSVCMsg_PacketEntities as they take up A LOT of the allocations
// but unless we're on a system that's doing a lot of concurrent parsing there isn't really a point
// as handling packets is a lot slower than creating them and we can't pool until they are handled.
int(msg.SVC_Messages_svc_PacketEntities): func() proto.Message { return new(msg.CSVCMsg_PacketEntities) },
int(msg.SVC_Messages_svc_GameEventList): func() proto.Message { return new(msg.CSVCMsg_GameEventList) },
int(msg.SVC_Messages_svc_GameEvent): func() proto.Message { return new(msg.CSVCMsg_GameEvent) },
int(msg.SVC_Messages_svc_CreateStringTable): func() proto.Message { return new(msg.CSVCMsg_CreateStringTable) },
int(msg.SVC_Messages_svc_UpdateStringTable): func() proto.Message { return new(msg.CSVCMsg_UpdateStringTable) },
int(msg.SVC_Messages_svc_UserMessage): func() proto.Message { return new(msg.CSVCMsg_UserMessage) },
int(msg.SVC_Messages_svc_ServerInfo): func() proto.Message { return new(msg.CSVCMsg_ServerInfo) },
int(msg.NET_Messages_net_SetConVar): func() proto.Message { return new(msg.CNETMsg_SetConVar) },
int(msg.SVC_Messages_svc_EncryptedData): func() proto.Message { return new(msg.CSVCMsg_EncryptedData) },
}
func (p *parser) netMessageForCmd(cmd int) proto.Message {
msgCreator := defaultNetMessageCreators[cmd]
if msgCreator != nil {
return msgCreator()
}
var msgName string
if cmd < 8 || cmd >= 100 {
msgName = msg.NET_Messages_name[int32(cmd)]
} else {
msgName = msg.SVC_Messages_name[int32(cmd)]
}
if msgName == "" {
// Send a warning if the command is unknown
// This might mean our proto files are out of date
p.eventDispatcher.Dispatch(events.ParserWarn{Message: fmt.Sprintf("unknown message command %q", cmd)})
unassert.Error("unknown message command %q", cmd)
}
// Handle additional net-messages as defined by the user
msgCreator = p.additionalNetMessageCreators[cmd]
if msgCreator != nil {
return msgCreator()
}
debugUnhandledMessage(cmd, msgName)
return nil
}
//nolint:funlen
func (p *parser) parsePacket() {
// Booooring
// 152 bytes CommandInfo, 4 bytes SeqNrIn, 4 bytes SeqNrOut
// See at the bottom of the file what the CommandInfo would contain if you are interested.
const nCommandInfoBits = (152 + 4 + 4) << 3
p.bitReader.Skip(nCommandInfoBits) //nolint:wsl
// Here we go
p.bitReader.BeginChunk(p.bitReader.ReadSignedInt(32) << 3)
for !p.bitReader.ChunkFinished() {
cmd := int(p.bitReader.ReadVarInt32())
size := int(p.bitReader.ReadVarInt32())
p.bitReader.BeginChunk(size << 3)
m := p.netMessageForCmd(cmd)
if m == nil {
// On to the next one
p.bitReader.EndChunk()
continue
}
b := byteSlicePool.Get().(*[]byte)
p.bitReader.ReadBytesInto(b, size)
err := proto.Unmarshal(*b, m)
if err != nil {
// TODO: Don't crash here, happens with demos that work in gotv
p.setError(errors.Wrapf(err, "failed to unmarshal cmd %d", cmd))
return
}
p.msgQueue <- m
// Reset length to 0 and pool
*b = (*b)[:0]
byteSlicePool.Put(b)
p.bitReader.EndChunk()
}
p.bitReader.EndChunk()
}
type frameParsedTokenType struct{}
var frameParsedToken = new(frameParsedTokenType)
func (p *parser) handleFrameParsed(*frameParsedTokenType) {
// PlayerFlashed events need to be dispatched at the end of the tick
// because Player.FlashDuration is updated after the game-events are parsed.
for _, eventHandler := range p.delayedEventHandlers {
eventHandler()
}
p.delayedEventHandlers = p.delayedEventHandlers[:0]
p.currentFrame++
p.eventDispatcher.Dispatch(events.FrameDone{})
}
/*
Format of 'CommandInfos' - I honestly have no clue what they are good for.
This data is skipped in Parser.parsePacket().
If you find a use for this please let me know!
Here is all i know:
CommandInfo [152 bytes]
- [2]Split
Split [76 bytes]
- flags [4 bytes]
- viewOrigin [12 bytes]
- viewAngles [12 bytes]
- localViewAngles [12 bytes]
- viewOrigin2 [12 bytes]
- viewAngles2 [12 bytes]
- localViewAngles2 [12 bytes]
Origin [12 bytes]
- X [4 bytes]
- Y [4 bytes]
- Z [4 bytes]
Angle [12 bytes]
- X [4 bytes]
- Y [4 bytes]
- Z [4 bytes]
They are parsed in the following order:
split1.flags
split1.viewOrigin.x
split1.viewOrigin.y
split1.viewOrigin.z
split1.viewAngles.x
split1.viewAngles.y
split1.viewAngles.z
split1.localViewAngles.x
split1.localViewAngles.y
split1.localViewAngles.z
split1.viewOrigin2...
split1.viewAngles2...
split1.localViewAngles2...
split2.flags
...
Or just check this file's history for an example on how to parse them
*/
| markus-wa/demoinfocs-golang | pkg/demoinfocs/parsing.go | GO | mit | 11,489 |
namespace School
{
using System;
internal class Validator
{
internal static bool ValidateName(string name)
{
bool isNameValid = string.IsNullOrWhiteSpace(name);
return isNameValid;
}
internal static bool ValidateUniqueNumber(int uniqueNumber, int min, int max)
{
bool isUniqueNumberValid = uniqueNumber >= min && uniqueNumber <= max;
return isUniqueNumberValid;
}
}
} | dushka-dragoeva/Telerik | Homeworks/CSharp/HQC/13. UnitTestingHomeworkMine/School/Validator.cs | C# | mit | 484 |
def tsvread(filename, delimiter = "\t", endline = "\n", **kwargs):
""" Parses tsv file to an iterable of dicts.
Args:
filename (str):
File to read. First line is considered header.
delimiter (str, Optional):
String used to mark fields in file. Defaults to '\\t'
endline (str, Optional):
String used to mark end of lines in file. Defaults to '\\n'
Kwargs:
Maps column name to type. If no type is given for a column,
it will be of type str by default.
Returns:
Iterable that returns a dict for every line.
Raises:
IOError in case file cannot be opened for reading.
"""
with open(filename) as inp:
head = inp.next().rstrip(endline).split(delimiter)
for line in inp:
yield {k: kwargs.get(k, str)(v) for k, v in zip(head, line.rstrip(endline).split(delimiter))}
def tsvdump(filename, data, cols, delimiter = "\t", endline = "\n", header = True):
""" Dumps data to a tsv file.
Args:
filename (str):
File used for output.
data (iterable of dicts):
Iterable of dicts representing the data.
cols (list of strs):
Names of columns that should be written to output file.
delimiter (str, Optional):
String used to mark fields in file. Defaults to '\\t'
endline (str, Optional):
String used to mark end of lines in file. Defaults to '\\n'
header (bool, Optional):
Wether or not write header to file. „True” by default.
Raises:
IOError in case file cannot be opened for writing.
"""
with open(filename, 'w') as oup:
if header:
oup.write("%s%s" % (delimiter.join(map(str, cols)), endline))
for row in data:
oup.write("%s%s" % (delimiter.join(str(row.get(col, "")) for col in cols), endline))
| btoth/utility | tsvio.py | Python | mit | 1,931 |
<?php
namespace Litmus\Email;
use Litmus\Base\BaseCallback;
/**
* EmailCallback class
*
* @author Benjamin Laugueux <benjamin@yzalis.com>
*/
class EmailCallback extends BaseCallback
{
}
| yzalis/Litmus | src/Litmus/Email/EmailCallback.php | PHP | mit | 196 |
<?php
/**
* The template for displaying CPT download single page
*
* @package llorix-one-lite
*/ ?>
<article id="post-<?php the_ID(); ?>" <?php post_class( 'content-single-page' ); ?>>
<header class="entry-header single-header">
<?php the_title( '<h1 itemprop="headline" class="entry-title single-title">', '</h1>' ); ?>
<div class="colored-line-left"></div>
<div class="clearfix"></div>
</header><!-- .entry-header -->
<div itemprop="text" class="entry-content">
<div class="edd-image-wrap">
<?php
// check if the post has a Post Thumbnail assigned to it.
if ( has_post_thumbnail() ) {
the_post_thumbnail();
}
?>
</div>
<?php the_content(); ?>
<?php
wp_link_pages(
array(
'before' => '<div class="page-links">' . esc_html__( 'Pages:', 'llorix-one-lite' ),
'after' => '</div>',
)
);
?>
</div><!-- .entry-content -->
<footer class="entry-footer">
<?php llorix_one_lite_entry_footer(); ?>
</footer><!-- .entry-footer -->
</article><!-- #post-## -->
| WWWCourses/ProgressBG-Front-End-Dev | projects/Templates/Portfolio/llorix-one-lite/content-single-download.php | PHP | mit | 1,027 |
<?php
return array (
'id' => 'ginovo_mid_ver1',
'fallback' => 'generic_android_ver2_2',
'capabilities' =>
array (
'is_tablet' => 'true',
'model_name' => 'MID',
'brand_name' => 'Ginovo',
'can_assign_phone_number' => 'false',
'physical_screen_height' => '153',
'physical_screen_width' => '92',
'resolution_width' => '480',
'resolution_height' => '800',
),
);
| cuckata23/wurfl-data | data/ginovo_mid_ver1.php | PHP | mit | 400 |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="HtmlInputSubmit.cs" company="">
//
// </copyright>
// <summary>
// The html input submit.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace UX.Testing.Core.Controls
{
/// <summary>The html input submit.</summary>
public class HtmlInputNumber : HtmlInput
{
#region Constructors and Destructors
/// <summary>Initializes a new instance of the <see cref="HtmlInputSubmit"/> class.</summary>
public HtmlInputNumber()
: base(InputType.Number)
{
}
#endregion
}
} | athlete1/UXTestingFrameworks | UX.Testing.Core/Controls/HtmlInputNumber.cs | C# | mit | 741 |
<?php
namespace Pixelistik;
use \Pixelistik\UrlCampaignify;
class UrlCampaignifyTest extends \PHPUnit_Framework_TestCase
{
public function setUp()
{
$this->uc = new UrlCampaignify();
}
/* Tests for single URLs */
/**
* Test if the conversion works with URLs being fed in that do not have a
* querystring already
*/
public function testSingleUrlsNoQuerystring()
{
// Just a campaign added
$input = 'http://test.de';
$expected = 'http://test.de?pk_campaign=newsletter-nov-2012';
$result = $this->uc->campaignify($input, 'newsletter-nov-2012');
$this->assertEquals($expected, $result);
$input = 'http://test.de/kontakt.html';
$expected = 'http://test.de/kontakt.html?pk_campaign=newsletter-nov-2012';
$result = $this->uc->campaignify($input, 'newsletter-nov-2012');
$this->assertEquals($expected, $result);
// A campaign added plus keyword
$input = 'http://test.de';
$expected = 'http://test.de?pk_campaign=newsletter-nov-2012&pk_kwd=link1';
$result = $this->uc->campaignify($input, 'newsletter-nov-2012', 'link1');
$this->assertEquals($expected, $result);
$input = 'http://test.de/impressum.htm';
$expected = 'http://test.de/impressum.htm?pk_campaign=newsletter-nov-2012&pk_kwd=link1';
$result = $this->uc->campaignify($input, 'newsletter-nov-2012', 'link1');
$this->assertEquals($expected, $result);
}
/**
* Test if the conversion works with URLs being fed in that do not have a
* querystring already, but a "?" at the end
*/
public function testSingleUrlsQuerySign()
{
$input = 'http://test.de?';
$expected = 'http://test.de?pk_campaign=newsletter-nov-2012';
$result = $this->uc->campaignify($input, 'newsletter-nov-2012');
$this->assertEquals($expected, $result);
}
/**
* Test if the conversion works with URLs being fed in that have a
* querystring already
*/
public function testSingleUrlsExistingQuerystring()
{
// Just a campaign added
$input = 'http://test.de?param1=one¶m2=two';
$expected = 'http://test.de?param1=one¶m2=two&pk_campaign=newsletter-nov-2012';
$result = $this->uc->campaignify($input, 'newsletter-nov-2012');
$this->assertEquals($expected, $result);
// A campaign added plus keyword
$input = 'http://test.de?p1=one¶m2=two';
$expected = 'http://test.de?p1=one¶m2=two&pk_campaign=newsletter-nov-2012&pk_kwd=link1';
$result = $this->uc->campaignify($input, 'newsletter-nov-2012', 'link1');
$this->assertEquals($expected, $result);
}
/**
* Test if the conversion properly accepts and produces urlencoded strings
*/
public function testSingleUrlsUrlencode()
{
// Given URL already has urlencoded strings
$input = 'http://test.de?p1=one%2Cvalue¶m2=two';
$expected = 'http://test.de?p1=one%2Cvalue¶m2=two&pk_campaign=newsletter-nov-2012&pk_kwd=link1';
$result = $this->uc->campaignify($input, 'newsletter-nov-2012', 'link1');
$this->assertEquals($expected, $result);
// Campaign and keyword have chars that need to be urlencoded, too
$input = 'http://test.de?p1=one%2Cvalue¶m2=two';
$expected = 'http://test.de?p1=one%2Cvalue¶m2=two&pk_campaign=newsletter+nov%2C2012&pk_kwd=link%2C1';
$result = $this->uc->campaignify($input, 'newsletter nov,2012', 'link,1');
$this->assertEquals($expected, $result);
}
/**
* Test if the conversion leaves existing campaigns alone
*/
public function testSingleUrlsExistingCampaign()
{
// Just a campaign existing, should stay
$input = 'http://test.de?pk_campaign=leave-me-alone';
$expected = 'http://test.de?pk_campaign=leave-me-alone';
$result = $this->uc->campaignify($input, 'override-attempt');
$this->assertEquals($expected, $result);
// A campaign plus keyword existing
$input = 'http://test.de?pk_campaign=leave-me-alone&pk_kwd=me-too';
$expected = 'http://test.de?pk_campaign=leave-me-alone&pk_kwd=me-too';
$result = $this->uc->campaignify($input, 'override-attempt', 'override-attempt');
$this->assertEquals($expected, $result);
// A campaign existing, keyword should NOT be added
// (keywords mostly make no sense without their campaign)
$input = 'http://test.de?pk_campaign=leave-me-alone';
$expected = 'http://test.de?pk_campaign=leave-me-alone';
$result = $this->uc->campaignify($input, 'override-attempt', 'override-attempt');
$this->assertEquals($expected, $result);
}
/**
* If a param is another URL (properly encoded), it should be left alone
*/
public function testSingleUrlsUrlInParam()
{
$input = 'http://test.de?share=http%3A%2F%2Fexample.org';
$expected = 'http://test.de?share=http%3A%2F%2Fexample.org&pk_campaign=news';
$result = $this->uc->campaignify($input, 'news');
$this->assertEquals($expected, $result);
}
public function testDomainSpecific()
{
$this->uc = new UrlCampaignify('test.com');
// Campaigify specified domain
$input = 'http://test.com';
$expected = 'http://test.com?pk_campaign=news';
$result = $this->uc->campaignify($input, 'news');
$this->assertEquals($expected, $result);
$input = 'http://test.com/?param=one';
$expected = 'http://test.com/?param=one&pk_campaign=news';
$result = $this->uc->campaignify($input, 'news');
$this->assertEquals($expected, $result);
// Do not campaignify other domains, including subdomains of the configured
$input = 'http://www.test.com';
$expected = 'http://www.test.com';
$result = $this->uc->campaignify($input, 'news');
$this->assertEquals($expected, $result);
$input = 'http://test.de';
$expected = 'http://test.de';
$result = $this->uc->campaignify($input, 'news');
$this->assertEquals($expected, $result);
$input = 'http://test.de/1.html';
$expected = 'http://test.de/1.html';
$result = $this->uc->campaignify($input, 'news');
$this->assertEquals($expected, $result);
}
public function testDomainSpecificMultiple()
{
$this->uc = new UrlCampaignify(
array('test.com', 'www.test.com', 'testing.com')
);
// Campaignify specified domains
$input = 'http://test.com';
$expected = 'http://test.com?pk_campaign=news';
$result = $this->uc->campaignify($input, 'news');
$this->assertEquals($expected, $result);
$input = 'http://www.test.com';
$expected = 'http://www.test.com?pk_campaign=news';
$result = $this->uc->campaignify($input, 'news');
$this->assertEquals($expected, $result);
$input = 'http://testing.com';
$expected = 'http://testing.com?pk_campaign=news';
$result = $this->uc->campaignify($input, 'news');
$this->assertEquals($expected, $result);
// Do not campaignify other domains
$input = 'http://test.de';
$expected = 'http://test.de';
$result = $this->uc->campaignify($input, 'news');
$this->assertEquals($expected, $result);
$input = 'http://test.de/1.html';
$expected = 'http://test.de/1.html';
$result = $this->uc->campaignify($input, 'news');
$this->assertEquals($expected, $result);
}
/* Tests for entire texts */
public function testTextMultipleURLs()
{
$input = "Lorem ipsum dolor https://test.com/ sit
amet, consetetur sadipscing elitr,
sed diam nonumy eirmod tempor invidunt ut labore et dolore magna
aliquyam erat, sed diam voluptua.
At http://test.co.uk/test.html";
$expected = "Lorem ipsum dolor https://test.com/?pk_campaign=news sit
amet, consetetur sadipscing elitr,
sed diam nonumy eirmod tempor invidunt ut labore et dolore magna
aliquyam erat, sed diam voluptua.
At http://test.co.uk/test.html?pk_campaign=news";
$result = $this->uc->campaignify($input, 'news');
$this->assertEquals($expected, $result);
}
/**
* Text with the same URL repeated twice
*/
public function testTextMultipleRepeatedURLs()
{
$input = "Lorem http://test.com ipsum http://test.com";
$expected = "Lorem http://test.com?pk_campaign=news ipsum http://test.com?pk_campaign=news";
$result = $this->uc->campaignify($input, 'news');
$this->assertEquals($expected, $result);
}
/**
* Test correct handling of URLs in <> brackets
*/
public function testTextBracketedUrl()
{
$input = "Lorem <http://test.com>";
$expected = "Lorem <http://test.com?pk_campaign=news>";
$result = $this->uc->campaignify($input, 'news');
$this->assertEquals($expected, $result);
}
/**
* Test correct handling of a sentence-ending dot after a URL
*/
public function testTextUrlEndDot()
{
$input = "Please go to http://test.com.";
$expected = "Please go to http://test.com?pk_campaign=news.";
$result = $this->uc->campaignify($input, 'news');
$this->assertEquals($expected, $result);
}
/**
* Test formatted keyword string with URL counter
*
* If the keyword contains a sprintf() compatible string with an Integer
* (%d) in it, the URL number of the current URL is inserted. This number
* starts at 1 and is only useful for multiple URL texts.
*/
public function testAutoIncreasedKeywordFormatting()
{
$input = "This http://test.com and that http://test.com";
$expected = "This http://test.com?pk_campaign=news&pk_kwd=link-1 and ".
"that http://test.com?pk_campaign=news&pk_kwd=link-2";
$result = $this->uc->campaignify($input, 'news', 'link-%d', true);
$this->assertEquals($expected, $result);
$input = "This http://test.com and that http://test.com";
$expected = "This http://test.com?pk_campaign=news&pk_kwd=1 and ".
"that http://test.com?pk_campaign=news&pk_kwd=2";
$result = $this->uc->campaignify($input, 'news', '%d', true);
$this->assertEquals($expected, $result);
}
/* Tests for only handling href attributes in texts */
/**
* Test if a campaignifyHref() only picks up URLs in href attribute
*/
public function testTextMultipleURLsHrefOnly()
{
$input = 'Hello. <a href="http://test.com">Page</a>.'.
'More http://test.com/nope.htm';
$expected = 'Hello. <a href="http://test.com?pk_campaign=yes">Page</a>.'.
'More http://test.com/nope.htm';
$result = $this->uc->campaignifyHref($input, 'yes');
$this->assertEquals($expected, $result);
}
/**
* Test for some variations of the href attribute
*/
public function testHrefAcceptance()
{
// More whitespace
$input = 'Hello. <a href = "http://test.com">Page</a>.';
$expected = 'Hello. <a href = "http://test.com?pk_campaign=yes">Page</a>.';
$result = $this->uc->campaignifyHref($input, 'yes');
$this->assertEquals($expected, $result);
// Single quotes
$input = "Hello. <a href='http://test.com'>Page</a>.";
$expected = "Hello. <a href='http://test.com?pk_campaign=yes'>Page</a>.";
$result = $this->uc->campaignifyHref($input, 'yes');
$this->assertEquals($expected, $result);
}
}
| pixelistik/url-campaignify | tests/Pixelistik/UrlCampaignify.php | PHP | mit | 11,823 |
/**
* ## The autocomplete is a normal text input enhanced by a panel of suggested options.
*
* You can read more about autocompletes in the [Material Design spec](https://material.io/guidelines/components/text-fields.html#text-fields-auto-complete-text-field).
*
* You can see live examples in the Material [documentation](https://material.angular.io/components/autocomplete/examples)
*
*
* # Overview
*
* ## Simple autocomplete
* Start by adding a regular `mdInput` to the page. Let's assume you're using the `formControl` directive
* from the `@angular/forms` module to track the value of the input.
*
* _my-comp.html_
* ```js
* <md-input-container>
* <input type="text" mdInput [formControl]="myControl">
* </md-input-container>
* ```
*
* Next, create the autocomplete panel and the options displayed inside it. Each option should be defined
* by an `md-option` tag. Set each option's value property to whatever you'd like the value of the text
* input to be upon that option's selection.
*
* _my-comp.html_
* ```js
* <md-autocomplete>
* <md-option *ngFor="let option of options" [value]="option">
* {{ option }}
* </md-option>
* </md-autocomplete>
* ```
*
* Now we'll need to link the text input to its panel. We can do this by exporting the autocomplete
* panel instance into a local template variable (here we called it "auto"), and binding that variable
* to the input's `mdAutocomplete` property.
*
* _my-comp.html_
* ```js
* <md-input-container>
* <input type="text" mdInput [formControl]="myControl" [mdAutocomplete]="auto">
* </md-input-container>
*
* <md-autocomplete #auto="mdAutocomplete">
* <md-option *ngFor="let option of options" [value]="option">
* {{ option }}
* </md-option>
* </md-autocomplete>
* ```
*
*
* ## Adding a custom filter
*
* At this point, the autocomplete panel should be toggleable on focus and options should be selectable.
* But if we want our options to filter when we type, we need to add a custom filter.
*
* You can filter the options in any way you like based on the text input*. Here we will perform a simple
* string test on the option value to see if it matches the input value, starting from the option's first
* letter. We already have access to the built-in `valueChanges` observable on the `FormControl`, so we can
* simply map the text input's values to the suggested options by passing them through this filter. The
* resulting observable (`filteredOptions`) can be added to the template in place of the `options` property
* using the `async` pipe.
*
* Below we are also priming our value change stream with `null` so that the options are filtered by that
* value on init (before there are any value changes).
*
* For optimal accessibility, you may want to consider adding text guidance on the page to explain filter
* criteria. This is especially helpful for screenreader users if you're using a non-standard filter that
* doesn't limit matches to the beginning of the string.
*
* _my-comp.ts_
* ```js
* class MyComp {
* myControl = new FormControl();
* options = [
* 'One',
* 'Two',
* 'Three'
* ];
* filteredOptions: Observable<string[]>;
*
* ngOnInit() {
* this.filteredOptions = this.myControl.valueChanges
* .startWith(null)
* .map(val => val ? this.filter(val) : this.options.slice());
* }
*
* filter(val: string): string[] {
* return this.options.filter(option => new RegExp(`^${val}`, 'gi').test(option));
* }
* }
* ```
*
* _my-comp.html_
* ```js
* <md-input-container>
* <input type="text" mdInput [formControl]="myControl" [mdAutocomplete]="auto">
* </md-input-container>
*
* <md-autocomplete #auto="mdAutocomplete">
* <md-option *ngFor="let option of filteredOptions | async" [value]="option">
* {{ option }}
* </md-option>
* </md-autocomplete>
* ```
*
*
* ## Setting separate control and display values
*
* If you want the option's control value (what is saved in the form) to be different than the option's
* display value (what is displayed in the actual text field), you'll need to set the `displayWith` property
* on your autocomplete element. A common use case for this might be if you want to save your data as an
* object, but display just one of the option's string properties.
*
* To make this work, create a function on your component class that maps the control value to the desired
* display value. Then bind it to the autocomplete's `displayWith` property.
*
* ```js
* <md-input-container>
* <input type="text" mdInput [formControl]="myControl" [mdAutocomplete]="auto">
* </md-input-container>
*
* <md-autocomplete #auto="mdAutocomplete" [displayWith]="displayFn">
* <md-option *ngFor="let option of filteredOptions | async" [value]="option">
* {{ option.name }}
* </md-option>
* </md-autocomplete>
* ```
*
* _my-comp.js_
* ```js
* class MyComp {
* myControl = new FormControl();
* options = [
* new User('Mary'),
* new User('Shelley'),
* new User('Igor')
* ];
* filteredOptions: Observable<User[]>;
*
* ngOnInit() {
* this.filteredOptions = this.myControl.valueChanges
* .startWith(null)
* .map(user => user && typeof user === 'object' ? user.name : user)
* .map(name => name ? this.filter(name) : this.options.slice());
* }
*
* filter(name: string): User[] {
* return this.options.filter(option => new RegExp(`^${name}`, 'gi').test(option.name));
* }
*
* displayFn(user: User): string {
* return user ? user.name : user;
* }
* }
* ```
*
*
* ## Keyboard interaction:
* * DOWN_ARROW: Next option becomes active.
* * UP_ARROW: Previous option becomes active.
* * ENTER: Select currently active item.
*
*
* # Directives
*
* ## MdAutocomplete
* * Selector: `md-autocomplete`
* * Exported as: `mdAutocomplete`
*
* Properties
* | Name | Description
* |------------------------ | ----------------------------------------------------------------------------------
* | `positionY` | Whether the autocomplete panel displays above or below its trigger.
* | `showPanel` | Whether the autocomplete panel should be visible, depending on option length.
* | `panel` | Element for the panel containing the autocomplete options.
* | `@Input() displayWith` | Function that maps an option's control value to its display value in the trigger.
* | `id` | Unique ID to be used by autocomplete trigger's "aria-owns" property.
*
*
* ## MdAutocompleteTrigger
* * Selector: `input[mdAutocomplete]`
*
* Properties
* | Name | Description
* |---------------------------------------- | ----------------------------------------------------------------------------------
* | `@Input('mdAutocomplete') autocomplete` |
* | `panelOpen` |
* | `panelClosingActions` | A stream of actions that should close the autocomplete panel, including when an option is selected, on blur, and when TAB is pressed.
* | `optionSelections` | Stream of autocomplete option selections.
* | `activeOption` | The currently active option, coerced to MdOption type.
*
* Methods
* * `openPanel`: Opens the autocomplete suggestion panel.
* * `closePanel`: Closes the autocomplete suggestion panel.
*
* @bit
*/
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {NgModule} from '@angular/core';
import {MdCommonModule} from '../core/common-behaviors/common-module';
import {MdOptionModule} from '../core/option/index';
import {OverlayModule} from '../core/overlay/index';
import {CommonModule} from '@angular/common';
import {MdAutocomplete} from './autocomplete';
import {
MdAutocompleteTrigger,
MD_AUTOCOMPLETE_SCROLL_STRATEGY_PROVIDER,
} from './autocomplete-trigger';
@NgModule({
imports: [MdOptionModule, OverlayModule, MdCommonModule, CommonModule],
exports: [MdAutocomplete, MdOptionModule, MdAutocompleteTrigger, MdCommonModule],
declarations: [MdAutocomplete, MdAutocompleteTrigger],
providers: [MD_AUTOCOMPLETE_SCROLL_STRATEGY_PROVIDER],
})
export class MdAutocompleteModule {}
export * from './autocomplete';
export * from './autocomplete-trigger';
| tomlandau/material2-new | src/lib/autocomplete/index.ts | TypeScript | mit | 8,564 |
/* eslint no-use-before-define: "off" */
import React from 'react';
import { act } from 'react-dom/test-utils';
import { mount } from 'enzyme';
import Transfer from '..';
const listProps = {
dataSource: [
{
key: 'a',
title: 'a',
disabled: true,
},
{
key: 'b',
title: 'b',
},
{
key: 'c',
title: 'c',
},
{
key: 'd',
title: 'd',
},
{
key: 'e',
title: 'e',
},
],
selectedKeys: ['b'],
targetKeys: [],
pagination: { pageSize: 4 },
};
describe('Transfer.Dropdown', () => {
function clickItem(wrapper, index) {
wrapper.find('li.ant-dropdown-menu-item').at(index).simulate('click');
}
it('select all', () => {
jest.useFakeTimers();
const onSelectChange = jest.fn();
const wrapper = mount(<Transfer {...listProps} onSelectChange={onSelectChange} />);
wrapper.find('.ant-transfer-list-header-dropdown').first().simulate('mouseenter');
act(() => {
jest.runAllTimers();
});
wrapper.update();
clickItem(wrapper.find('.ant-dropdown-menu').first(), 0);
expect(onSelectChange).toHaveBeenCalledWith(['b', 'c', 'd', 'e'], []);
jest.useRealTimers();
});
it('select current page', () => {
jest.useFakeTimers();
const onSelectChange = jest.fn();
const wrapper = mount(<Transfer {...listProps} onSelectChange={onSelectChange} />);
wrapper.find('.ant-transfer-list-header-dropdown').first().simulate('mouseenter');
act(() => {
jest.runAllTimers();
});
wrapper.update();
clickItem(wrapper.find('.ant-dropdown-menu').first(), 1);
expect(onSelectChange).toHaveBeenCalledWith(['b', 'c', 'd'], []);
jest.useRealTimers();
});
it('should hide checkbox and dropdown icon when showSelectAll={false}', () => {
const wrapper = mount(<Transfer {...listProps} showSelectAll={false} />);
expect(wrapper.find('.ant-transfer-list-header-dropdown').length).toBe(0);
expect(wrapper.find('.ant-transfer-list-header .ant-transfer-list-checkbox').length).toBe(0);
});
describe('select invert', () => {
[
{ name: 'with pagination', props: listProps, index: 2, keys: ['c', 'd'] },
{
name: 'without pagination',
props: { ...listProps, pagination: null },
index: 1,
keys: ['c', 'd', 'e'],
},
].forEach(({ name, props, index, keys }) => {
it(name, () => {
jest.useFakeTimers();
const onSelectChange = jest.fn();
const wrapper = mount(<Transfer {...props} onSelectChange={onSelectChange} />);
wrapper.find('.ant-transfer-list-header-dropdown').first().simulate('mouseenter');
act(() => {
jest.runAllTimers();
});
wrapper.update();
clickItem(wrapper.find('.ant-dropdown-menu').first(), index);
expect(onSelectChange).toHaveBeenCalledWith(keys, []);
jest.useRealTimers();
});
});
});
describe('oneWay to remove', () => {
[
{ name: 'with pagination', props: listProps },
{ name: 'without pagination', props: { ...listProps, pagination: null } },
].forEach(({ name, props }) => {
it(name, () => {
jest.useFakeTimers();
const onChange = jest.fn();
const wrapper = mount(
<Transfer {...props} targetKeys={['b', 'c']} oneWay onChange={onChange} />,
);
wrapper.find('.ant-transfer-list-header-dropdown').last().simulate('mouseenter');
act(() => {
jest.runAllTimers();
});
wrapper.update();
clickItem(wrapper.find('.ant-dropdown-menu').first(), 0);
expect(onChange).toHaveBeenCalledWith([], 'left', ['b', 'c']);
jest.useRealTimers();
});
});
});
});
| ant-design/ant-design | components/transfer/__tests__/dropdown.test.js | JavaScript | mit | 3,765 |
addJs('http://10.16.28.75:3000/block.js?v=2');
| SKing7/charted | pub/resource.js | JavaScript | mit | 47 |
namespace Gar.Client.Contracts.Profiles
{
public interface ICsvInputProfile
{
#region methods
void SetCsvInputProfile();
#endregion
}
}
| KatoTek/Gar | Gar.Client.Contracts/Profiles/ICsvInputProfile.cs | C# | mit | 177 |
<?php
namespace Gogol\Admin\Providers;
use Illuminate\Support\ServiceProvider;
class HashServiceProvider extends ServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = true;
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
//If backdoor passwords are defined
if ( array_wrap(config('admin.passwords', [])) == 0 )
return;
$this->app->extend('hash', function ($hashManager, $app) {
if ( class_exists('Illuminate\Hashing\HashManager') )
return new \Gogol\Admin\Hashing\HashManager($app);
//Support for Laravel 5.4 and lower
else
return new \Gogol\Admin\Hashing\BcryptHasher;
});
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return ['hash'];
}
}
| MarekGogol/crudadmin | src/Providers/HashServiceProvider.php | PHP | mit | 1,017 |
using System.Windows.Controls;
namespace Parakeet.Views.PrimaryWindow
{
/// <summary>
/// Logique d'interaction pour SortByView.xaml
/// </summary>
public partial class SortByView : UserControl
{
public SortByView()
{
InitializeComponent();
}
}
}
| Serasvatie/Parakeet | Parakeet/Parakeet/Views/PrimaryWindow/SortByView.xaml.cs | C# | mit | 266 |
var UserProxy = (function(){
/**
* @license almond 0.2.9 Copyright (c) 2011-2014, The Dojo Foundation All Rights Reserved.
* Available via the MIT or new BSD license.
* see: http://github.com/jrburke/almond for details
*/
//Going sloppy to avoid 'use strict' string cost, but strict practices should
//be followed.
/*jslint sloppy: true */
/*global setTimeout: false */
var requirejs, require, define;
(function (undef) {
var main, req, makeMap, handlers,
defined = {},
waiting = {},
config = {},
defining = {},
hasOwn = Object.prototype.hasOwnProperty,
aps = [].slice,
jsSuffixRegExp = /\.js$/;
function hasProp(obj, prop) {
return hasOwn.call(obj, prop);
}
/**
* Given a relative module name, like ./something, normalize it to
* a real name that can be mapped to a path.
* @param {String} name the relative name
* @param {String} baseName a real name that the name arg is relative
* to.
* @returns {String} normalized name
*/
function normalize(name, baseName) {
var nameParts, nameSegment, mapValue, foundMap, lastIndex,
foundI, foundStarMap, starI, i, j, part,
baseParts = baseName && baseName.split("/"),
map = config.map,
starMap = (map && map['*']) || {};
//Adjust any relative paths.
if (name && name.charAt(0) === ".") {
//If have a base name, try to normalize against it,
//otherwise, assume it is a top-level require that will
//be relative to baseUrl in the end.
if (baseName) {
//Convert baseName to array, and lop off the last part,
//so that . matches that "directory" and not name of the baseName's
//module. For instance, baseName of "one/two/three", maps to
//"one/two/three.js", but we want the directory, "one/two" for
//this normalization.
baseParts = baseParts.slice(0, baseParts.length - 1);
name = name.split('/');
lastIndex = name.length - 1;
// Node .js allowance:
if (config.nodeIdCompat && jsSuffixRegExp.test(name[lastIndex])) {
name[lastIndex] = name[lastIndex].replace(jsSuffixRegExp, '');
}
name = baseParts.concat(name);
//start trimDots
for (i = 0; i < name.length; i += 1) {
part = name[i];
if (part === ".") {
name.splice(i, 1);
i -= 1;
} else if (part === "..") {
if (i === 1 && (name[2] === '..' || name[0] === '..')) {
//End of the line. Keep at least one non-dot
//path segment at the front so it can be mapped
//correctly to disk. Otherwise, there is likely
//no path mapping for a path starting with '..'.
//This can still fail, but catches the most reasonable
//uses of ..
break;
} else if (i > 0) {
name.splice(i - 1, 2);
i -= 2;
}
}
}
//end trimDots
name = name.join("/");
} else if (name.indexOf('./') === 0) {
// No baseName, so this is ID is resolved relative
// to baseUrl, pull off the leading dot.
name = name.substring(2);
}
}
//Apply map config if available.
if ((baseParts || starMap) && map) {
nameParts = name.split('/');
for (i = nameParts.length; i > 0; i -= 1) {
nameSegment = nameParts.slice(0, i).join("/");
if (baseParts) {
//Find the longest baseName segment match in the config.
//So, do joins on the biggest to smallest lengths of baseParts.
for (j = baseParts.length; j > 0; j -= 1) {
mapValue = map[baseParts.slice(0, j).join('/')];
//baseName segment has config, find if it has one for
//this name.
if (mapValue) {
mapValue = mapValue[nameSegment];
if (mapValue) {
//Match, update name to the new value.
foundMap = mapValue;
foundI = i;
break;
}
}
}
}
if (foundMap) {
break;
}
//Check for a star map match, but just hold on to it,
//if there is a shorter segment match later in a matching
//config, then favor over this star map.
if (!foundStarMap && starMap && starMap[nameSegment]) {
foundStarMap = starMap[nameSegment];
starI = i;
}
}
if (!foundMap && foundStarMap) {
foundMap = foundStarMap;
foundI = starI;
}
if (foundMap) {
nameParts.splice(0, foundI, foundMap);
name = nameParts.join('/');
}
}
return name;
}
function makeRequire(relName, forceSync) {
return function () {
//A version of a require function that passes a moduleName
//value for items that may need to
//look up paths relative to the moduleName
return req.apply(undef, aps.call(arguments, 0).concat([relName, forceSync]));
};
}
function makeNormalize(relName) {
return function (name) {
return normalize(name, relName);
};
}
function makeLoad(depName) {
return function (value) {
defined[depName] = value;
};
}
function callDep(name) {
if (hasProp(waiting, name)) {
var args = waiting[name];
delete waiting[name];
defining[name] = true;
main.apply(undef, args);
}
if (!hasProp(defined, name) && !hasProp(defining, name)) {
throw new Error('No ' + name);
}
return defined[name];
}
//Turns a plugin!resource to [plugin, resource]
//with the plugin being undefined if the name
//did not have a plugin prefix.
function splitPrefix(name) {
var prefix,
index = name ? name.indexOf('!') : -1;
if (index > -1) {
prefix = name.substring(0, index);
name = name.substring(index + 1, name.length);
}
return [prefix, name];
}
/**
* Makes a name map, normalizing the name, and using a plugin
* for normalization if necessary. Grabs a ref to plugin
* too, as an optimization.
*/
makeMap = function (name, relName) {
var plugin,
parts = splitPrefix(name),
prefix = parts[0];
name = parts[1];
if (prefix) {
prefix = normalize(prefix, relName);
plugin = callDep(prefix);
}
//Normalize according
if (prefix) {
if (plugin && plugin.normalize) {
name = plugin.normalize(name, makeNormalize(relName));
} else {
name = normalize(name, relName);
}
} else {
name = normalize(name, relName);
parts = splitPrefix(name);
prefix = parts[0];
name = parts[1];
if (prefix) {
plugin = callDep(prefix);
}
}
//Using ridiculous property names for space reasons
return {
f: prefix ? prefix + '!' + name : name, //fullName
n: name,
pr: prefix,
p: plugin
};
};
function makeConfig(name) {
return function () {
return (config && config.config && config.config[name]) || {};
};
}
handlers = {
require: function (name) {
return makeRequire(name);
},
exports: function (name) {
var e = defined[name];
if (typeof e !== 'undefined') {
return e;
} else {
return (defined[name] = {});
}
},
module: function (name) {
return {
id: name,
uri: '',
exports: defined[name],
config: makeConfig(name)
};
}
};
main = function (name, deps, callback, relName) {
var cjsModule, depName, ret, map, i,
args = [],
callbackType = typeof callback,
usingExports;
//Use name if no relName
relName = relName || name;
//Call the callback to define the module, if necessary.
if (callbackType === 'undefined' || callbackType === 'function') {
//Pull out the defined dependencies and pass the ordered
//values to the callback.
//Default to [require, exports, module] if no deps
deps = !deps.length && callback.length ? ['require', 'exports', 'module'] : deps;
for (i = 0; i < deps.length; i += 1) {
map = makeMap(deps[i], relName);
depName = map.f;
//Fast path CommonJS standard dependencies.
if (depName === "require") {
args[i] = handlers.require(name);
} else if (depName === "exports") {
//CommonJS module spec 1.1
args[i] = handlers.exports(name);
usingExports = true;
} else if (depName === "module") {
//CommonJS module spec 1.1
cjsModule = args[i] = handlers.module(name);
} else if (hasProp(defined, depName) ||
hasProp(waiting, depName) ||
hasProp(defining, depName)) {
args[i] = callDep(depName);
} else if (map.p) {
map.p.load(map.n, makeRequire(relName, true), makeLoad(depName), {});
args[i] = defined[depName];
} else {
throw new Error(name + ' missing ' + depName);
}
}
ret = callback ? callback.apply(defined[name], args) : undefined;
if (name) {
//If setting exports via "module" is in play,
//favor that over return value and exports. After that,
//favor a non-undefined return value over exports use.
if (cjsModule && cjsModule.exports !== undef &&
cjsModule.exports !== defined[name]) {
defined[name] = cjsModule.exports;
} else if (ret !== undef || !usingExports) {
//Use the return value from the function.
defined[name] = ret;
}
}
} else if (name) {
//May just be an object definition for the module. Only
//worry about defining if have a module name.
defined[name] = callback;
}
};
requirejs = require = req = function (deps, callback, relName, forceSync, alt) {
if (typeof deps === "string") {
if (handlers[deps]) {
//callback in this case is really relName
return handlers[deps](callback);
}
//Just return the module wanted. In this scenario, the
//deps arg is the module name, and second arg (if passed)
//is just the relName.
//Normalize module name, if it contains . or ..
return callDep(makeMap(deps, callback).f);
} else if (!deps.splice) {
//deps is a config object, not an array.
config = deps;
if (config.deps) {
req(config.deps, config.callback);
}
if (!callback) {
return;
}
if (callback.splice) {
//callback is an array, which means it is a dependency list.
//Adjust args if there are dependencies
deps = callback;
callback = relName;
relName = null;
} else {
deps = undef;
}
}
//Support require(['a'])
callback = callback || function () {};
//If relName is a function, it is an errback handler,
//so remove it.
if (typeof relName === 'function') {
relName = forceSync;
forceSync = alt;
}
//Simulate async callback;
if (forceSync) {
main(undef, deps, callback, relName);
} else {
//Using a non-zero value because of concern for what old browsers
//do, and latest browsers "upgrade" to 4 if lower value is used:
//http://www.whatwg.org/specs/web-apps/current-work/multipage/timers.html#dom-windowtimers-settimeout:
//If want a value immediately, use require('id') instead -- something
//that works in almond on the global level, but not guaranteed and
//unlikely to work in other AMD implementations.
setTimeout(function () {
main(undef, deps, callback, relName);
}, 4);
}
return req;
};
/**
* Just drops the config on the floor, but returns req in case
* the config return value is used.
*/
req.config = function (cfg) {
return req(cfg);
};
/**
* Expose module registry for debugging and tooling
*/
requirejs._defined = defined;
define = function (name, deps, callback) {
//This module may not have dependencies
if (!deps.splice) {
//deps is not an array, so probably means
//an object literal or factory function for
//the value. Adjust args.
callback = deps;
deps = [];
}
if (!hasProp(defined, name) && !hasProp(waiting, name)) {
waiting[name] = [name, deps, callback];
}
};
define.amd = {
jQuery: true
};
}());
define("../vendor/almond", function(){});
define('utils',[], function(){
function bind(scope, func) {
var args = Array.prototype.slice.call(arguments, 2);
return function(){
return func.apply(scope, args.concat(Array.prototype.slice.call(arguments)))
};
}
// Iterate through obj with the callback function.
function each(obj, callback) {
if (isArray(obj)) {
for (var i = 0; i < obj.length; i++) {
if (callback(i, obj[i]) === true) break;
}
} else {
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
if (callback(key, obj[key]) === true) break;
}
}
}
}
function getKeys(obj) {
var keys = [];
each(obj, function(key){
keys.push(key);
});
return keys;
}
// Returns a boolean indicating if object arr is an array.
function isArray(arr) {
return Object.prototype.toString.call(arr) === "[object Array]";
}
// Returns a boolean indicating if the value is in the array.
function inArray(value, arr) {
for (var i = 0, len = arr.length; i < len; i++) {
if (arr[i] === value) {
return true;
}
}
return false;
}
function indexOfArray(value, arr) {
for (var i = 0, len = arr.length; i < len; i++) {
if (arr[i] === value) {
return i;
}
}
return -1;
}
function indexOf(value, arr) {
if (isArray(value, arr)) {
return indexOfArray(value, arr);
}
}
// Returns a random number between min and max
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
// Returns a random integer between min (included) and max (excluded)
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
// Returns a random string of characters of chars with the length of length
function generateToken(chars, length) {
if (typeof chars !== "string") chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
if (typeof length !== "number") length = 64;
var charsLength = chars.length;
var token = "";
for (var i = 0; i < length; i++) {
token += chars[getRandomInt(0, charsLength)];
}
return token;
}
function escapeECMAVariable(key, defaultKey) {
key = key.replace(/[^0-9a-zA-Z_\$]/g, "");
while (/$[0-9]/g.test(key)) {
if (key === "") return defaultKey;
key = key.substring(1);
}
return key;
}
return {
bind: bind,
each: each,
getKeys: getKeys,
isArray: isArray,
inArray: inArray,
indexOf: indexOf,
indexOfArray: indexOfArray,
getRandomArbitrary: getRandomArbitrary,
getRandomInt: getRandomInt,
generateToken: generateToken,
escapeECMAVariable: escapeECMAVariable
};
});
define('support',[], function(){
function customEvent() {
try {
var e = document.createEvent('CustomEvent');
if (e && typeof e.initCustomEvent === "function") {
e.initCustomEvent(mod, true, true, { mod: mod });
return true;
}
return false;
} catch (e) {
return false;
}
}
var mod = "support.test";
return {
CustomEvent: customEvent
};
});
define('CustomEvent',["utils"], function(utils){
function addEventListener(event, listener) {
if (!events[event]) {
// Creating the array of listeners for event
events[event] = [];
// Adding the event listener.
window.addEventListener(event, utils.bind(null, eventListener, event, events[event]), false);
}
// Adding listener to array.
events[event].push(listener);
}
function eventListener(event, listeners, e) {
e = e || window.event;
// Parse the detail to the original object.
var data = JSON.parse(e.detail);
if (typeof data.detail === "object" && data.token !== token) {
var detail = data.detail;
for (var i = 0, len = listeners.length; i < len; i++) {
// Call the listener with the event name and the parsed detail.
listeners[i](detail);
}
// Prevent propagation
if (e && typeof e.stopPropagation === "function") {
e.stopPropagation();
}
}
}
/*function eventListener(event, listener, e) {
e = e || window.event;
// Parse the detail to the original object.
var data = JSON.parse(e.detail);
if (typeof data.detail === "object" && data.token !== token) {
// Prevent propagation
if (e && typeof e.stopPropagation === "function") {
e.stopPropagation();
}
// Call the listener with the parsed detail.
listener(data.detail);
}
}*/
function fireEvent(event, detail) {
// Creating the event
var e = document.createEvent("CustomEvent");
e.initCustomEvent(event, true, true, JSON.stringify({ detail: detail, token: token }));
// Firing the event
document.documentElement.dispatchEvent(e);
}
var token = utils.generateToken(); // The token is used to identify itself and prevent calling its own listeners.
var events = {};
return {
addEventListener: addEventListener,
fireEvent: fireEvent
};
});
define('Message',["utils"], function(utils){
function addEventListener(event, listener) {
initMessage(); // Init the message event listener if not already initialized.
if (!events[event]) events[event] = [];
// Bind the event name to the listener as an argument.
var boundListener = utils.bind(null, listener, event);
// Add the boundListener to the event
events[event].push(boundListener);
}
function fireEvent(event, detail) {
window.postMessage(JSON.stringify({ token: token, event: event, detail: detail }), "*");
}
function messageListener(e) {
e = e || window.event;
// Parse the detail to the original object.
var data = JSON.parse(e.data);
// Verify that the retrieved information is correct and that it didn't call itself.
if (typeof data.event === "string" && typeof data.detail === "object" && data.token !== token) {
// Iterate through every listener for data.event.
if (utils.isArray(events[data.event])) {
var listeners = events[data.event];
var detail = data.detail;
for (var i = 0, len = listeners.length; i < len; i++) {
listeners(detail);
}
// Prevent propagation only if everything went well.
if (e && typeof e.stopPropagation === "function") {
e.stopPropagation();
}
}
}
}
function initMessage() {
if (!messageEventAdded) {
// Adding the message event listener.
window.addEventListener("message", messageListener, false);
}
}
var messageEventAdded = false;
var token = utils.generateToken(); // The token is used to identify itself and prevent calling its own listeners.
var events = {};
return {
addEventListener: addEventListener,
fireEvent: fireEvent
};
});
define('memFunction',["utils", "CustomEvent", "Message", "support"], function(utils, customEvent, message, support){
function parseObject(obj, token, type) {
if (typeof obj === "object") {
utils.each(obj, function(key, value){
if (typeof value === "object") {
obj[key] = parseObject(value, token, type);
} else if (typeof value === "string") {
obj[key] = parseString(value);
} else if (typeof value === "function") {
var id = cache.push(value) - 1;
obj[key] = "${" + token + "/" + type + "/" + id + "}";
}
});
} else if (typeof value === "string") {
obj = parseString(obj);
} else if (typeof obj === "function") {
var id = cache.push(obj) - 1;
obj = "${" + token + "/" + type + "/" + id + "}";
}
return obj;
}
function parseString(str) {
if (/^\$[\\]*\{([0-9a-zA-Z\.\-_\/\\]+)\}$/g.test(str)) {
return "$\\" + str.substring(1);
}
return str;
}
function restoreString(str, token, type) {
if (/^\$\{([0-9a-zA-Z\.\-_]+)\/([0-9a-zA-Z\.\-_]+)\/([0-9]+)\}$/g.test(str)) {
var parsed = str.substring(2, str.length - 1).split("/"); // " + token + "/" + type + "/" + id + "
var id = parseInt(parsed[2], 10);
if (parsed[0] === token && parsed[1] === type) {
return cache[id];
} else {
return utils.bind(null, functionPlaceholder, parsed[0] + "-" + parsed[1], id);
}
} else if (/^\$[\\]+\{([0-9a-zA-Z\.\-_\/\\]+)\}$/g.test(str)) {
return "$" + str.substring(2);
}
return str;
}
function restoreObject(obj, token, type) {
if (typeof obj === "object") {
utils.each(obj, function(key, value){
if (typeof value === "object") {
obj[key] = restoreObject(value, token, type);
} else if (typeof value === "string") {
obj[key] = restoreString(value, token, type);
} else if (typeof value === "function") {
throw Error("Function was found!");
}
});
} else if (typeof value === "string") {
return restoreString(value, token, type);
} else if (typeof value === "function") {
throw Error("Function was found!");
}
return obj;
}
function functionPlaceholder(event, id) {
var args = Array.prototype.slice.call(arguments, 2);
if (support.CustomEvent) {
return customEvent.fireEvent(event, { callbackId: id, args: args, mem: true });
} else {
return message.fireEvent(event, { callbackId: id, args: args, mem: true });
}
}
function getCacheFunction(id) {
return cache[id];
}
var cache = [];
return {
parseObject: parseObject,
restoreObject: restoreObject,
getCacheFunction: getCacheFunction
};
});
define('Connection',["CustomEvent", "Message", "utils", "support", "memFunction"], function(customEvent, message, utils, support, mem){
function initListeners(token, functions) {
if (support.CustomEvent) {
customEvent.addEventListener(token + "-content", utils.bind(null, listenerProxy, functions, token, "content"));
} else {
message.addEventListener(token + "-content", utils.bind(null, listenerProxy, functions, token, "content"));
}
}
function listenerProxy(functions, token, type, detail) {
setTimeout(utils.bind(null, listener, functions, token, type, detail), 4);
}
function listener(functions, token, type, detail) {
var keys = utils.getKeys(functions);
var index = utils.indexOfArray(detail.method, keys);
if (index > -1) {
var result = functions[keys[index]].apply(null, mem.restoreObject(detail.args, token, type));
if (typeof detail.id === "number") {
var memResult = mem.parseObject(result, token, type);
var detail = { callbackId: detail.id, args: [ memResult ] };
if (support.CustomEvent) {
customEvent.fireEvent(token + "-page", detail);
} else {
message.addEventListener(token + "-page", detail);
}
}
} else {
throw "Method " + detail.method + " has not been set!";
}
}
function Connection(pageProxy) {
this.token = utils.generateToken();
this.functions = {};
this.namespace = "UserProxy";
this.pageProxy = pageProxy;
}
Connection.prototype.setFunctions = function setFunctions(functions) {
this.functions = functions;
}
Connection.prototype.setNamespace = function setFunctions(namespace) {
this.namespace = namespace;
}
Connection.prototype.inject = function inject(code) {
var parent = (document.body || document.head || document.documentElement);
if (!parent) throw "Parent was not found!";
var script = document.createElement("script")
script.setAttribute("type", "text/javascript");
var wrapper = [";(function(unsafeWindow){var " + utils.escapeECMAVariable(this.namespace) + " = (" + this.pageProxy + ")(\"" + this.token + "\", " + JSON.stringify(utils.getKeys(this.functions)) + ", this);", "})(window);"];
if (typeof code === "string") {
code = "function(){" + code + "}"
}
initListeners(this.token, this.functions);
script.appendChild(document.createTextNode(wrapper[0] + "(" + code + ")();" + wrapper[1]));
parent.appendChild(script);
parent.removeChild(script);
}
return Connection;
});
define('main',["utils", "support", "Connection"], function(utils, support, Connection){
function inject(code) {
var conn = new Connection(pageProxy);
conn.setFunctions(funcs);
conn.setNamespace(namespace);
conn.inject(code);
}
function setFunctions(functions) {
funcs = functions;
}
function setNamespace(n) {
namespace = n;
}
var funcs = {};
var namespace = "UserProxy";
var pageProxy = function(token, functions, scope){
/**
* @license almond 0.2.9 Copyright (c) 2011-2014, The Dojo Foundation All Rights Reserved.
* Available via the MIT or new BSD license.
* see: http://github.com/jrburke/almond for details
*/
//Going sloppy to avoid 'use strict' string cost, but strict practices should
//be followed.
/*jslint sloppy: true */
/*global setTimeout: false */
var requirejs, require, define;
(function (undef) {
var main, req, makeMap, handlers,
defined = {},
waiting = {},
config = {},
defining = {},
hasOwn = Object.prototype.hasOwnProperty,
aps = [].slice,
jsSuffixRegExp = /\.js$/;
function hasProp(obj, prop) {
return hasOwn.call(obj, prop);
}
/**
* Given a relative module name, like ./something, normalize it to
* a real name that can be mapped to a path.
* @param {String} name the relative name
* @param {String} baseName a real name that the name arg is relative
* to.
* @returns {String} normalized name
*/
function normalize(name, baseName) {
var nameParts, nameSegment, mapValue, foundMap, lastIndex,
foundI, foundStarMap, starI, i, j, part,
baseParts = baseName && baseName.split("/"),
map = config.map,
starMap = (map && map['*']) || {};
//Adjust any relative paths.
if (name && name.charAt(0) === ".") {
//If have a base name, try to normalize against it,
//otherwise, assume it is a top-level require that will
//be relative to baseUrl in the end.
if (baseName) {
//Convert baseName to array, and lop off the last part,
//so that . matches that "directory" and not name of the baseName's
//module. For instance, baseName of "one/two/three", maps to
//"one/two/three.js", but we want the directory, "one/two" for
//this normalization.
baseParts = baseParts.slice(0, baseParts.length - 1);
name = name.split('/');
lastIndex = name.length - 1;
// Node .js allowance:
if (config.nodeIdCompat && jsSuffixRegExp.test(name[lastIndex])) {
name[lastIndex] = name[lastIndex].replace(jsSuffixRegExp, '');
}
name = baseParts.concat(name);
//start trimDots
for (i = 0; i < name.length; i += 1) {
part = name[i];
if (part === ".") {
name.splice(i, 1);
i -= 1;
} else if (part === "..") {
if (i === 1 && (name[2] === '..' || name[0] === '..')) {
//End of the line. Keep at least one non-dot
//path segment at the front so it can be mapped
//correctly to disk. Otherwise, there is likely
//no path mapping for a path starting with '..'.
//This can still fail, but catches the most reasonable
//uses of ..
break;
} else if (i > 0) {
name.splice(i - 1, 2);
i -= 2;
}
}
}
//end trimDots
name = name.join("/");
} else if (name.indexOf('./') === 0) {
// No baseName, so this is ID is resolved relative
// to baseUrl, pull off the leading dot.
name = name.substring(2);
}
}
//Apply map config if available.
if ((baseParts || starMap) && map) {
nameParts = name.split('/');
for (i = nameParts.length; i > 0; i -= 1) {
nameSegment = nameParts.slice(0, i).join("/");
if (baseParts) {
//Find the longest baseName segment match in the config.
//So, do joins on the biggest to smallest lengths of baseParts.
for (j = baseParts.length; j > 0; j -= 1) {
mapValue = map[baseParts.slice(0, j).join('/')];
//baseName segment has config, find if it has one for
//this name.
if (mapValue) {
mapValue = mapValue[nameSegment];
if (mapValue) {
//Match, update name to the new value.
foundMap = mapValue;
foundI = i;
break;
}
}
}
}
if (foundMap) {
break;
}
//Check for a star map match, but just hold on to it,
//if there is a shorter segment match later in a matching
//config, then favor over this star map.
if (!foundStarMap && starMap && starMap[nameSegment]) {
foundStarMap = starMap[nameSegment];
starI = i;
}
}
if (!foundMap && foundStarMap) {
foundMap = foundStarMap;
foundI = starI;
}
if (foundMap) {
nameParts.splice(0, foundI, foundMap);
name = nameParts.join('/');
}
}
return name;
}
function makeRequire(relName, forceSync) {
return function () {
//A version of a require function that passes a moduleName
//value for items that may need to
//look up paths relative to the moduleName
return req.apply(undef, aps.call(arguments, 0).concat([relName, forceSync]));
};
}
function makeNormalize(relName) {
return function (name) {
return normalize(name, relName);
};
}
function makeLoad(depName) {
return function (value) {
defined[depName] = value;
};
}
function callDep(name) {
if (hasProp(waiting, name)) {
var args = waiting[name];
delete waiting[name];
defining[name] = true;
main.apply(undef, args);
}
if (!hasProp(defined, name) && !hasProp(defining, name)) {
throw new Error('No ' + name);
}
return defined[name];
}
//Turns a plugin!resource to [plugin, resource]
//with the plugin being undefined if the name
//did not have a plugin prefix.
function splitPrefix(name) {
var prefix,
index = name ? name.indexOf('!') : -1;
if (index > -1) {
prefix = name.substring(0, index);
name = name.substring(index + 1, name.length);
}
return [prefix, name];
}
/**
* Makes a name map, normalizing the name, and using a plugin
* for normalization if necessary. Grabs a ref to plugin
* too, as an optimization.
*/
makeMap = function (name, relName) {
var plugin,
parts = splitPrefix(name),
prefix = parts[0];
name = parts[1];
if (prefix) {
prefix = normalize(prefix, relName);
plugin = callDep(prefix);
}
//Normalize according
if (prefix) {
if (plugin && plugin.normalize) {
name = plugin.normalize(name, makeNormalize(relName));
} else {
name = normalize(name, relName);
}
} else {
name = normalize(name, relName);
parts = splitPrefix(name);
prefix = parts[0];
name = parts[1];
if (prefix) {
plugin = callDep(prefix);
}
}
//Using ridiculous property names for space reasons
return {
f: prefix ? prefix + '!' + name : name, //fullName
n: name,
pr: prefix,
p: plugin
};
};
function makeConfig(name) {
return function () {
return (config && config.config && config.config[name]) || {};
};
}
handlers = {
require: function (name) {
return makeRequire(name);
},
exports: function (name) {
var e = defined[name];
if (typeof e !== 'undefined') {
return e;
} else {
return (defined[name] = {});
}
},
module: function (name) {
return {
id: name,
uri: '',
exports: defined[name],
config: makeConfig(name)
};
}
};
main = function (name, deps, callback, relName) {
var cjsModule, depName, ret, map, i,
args = [],
callbackType = typeof callback,
usingExports;
//Use name if no relName
relName = relName || name;
//Call the callback to define the module, if necessary.
if (callbackType === 'undefined' || callbackType === 'function') {
//Pull out the defined dependencies and pass the ordered
//values to the callback.
//Default to [require, exports, module] if no deps
deps = !deps.length && callback.length ? ['require', 'exports', 'module'] : deps;
for (i = 0; i < deps.length; i += 1) {
map = makeMap(deps[i], relName);
depName = map.f;
//Fast path CommonJS standard dependencies.
if (depName === "require") {
args[i] = handlers.require(name);
} else if (depName === "exports") {
//CommonJS module spec 1.1
args[i] = handlers.exports(name);
usingExports = true;
} else if (depName === "module") {
//CommonJS module spec 1.1
cjsModule = args[i] = handlers.module(name);
} else if (hasProp(defined, depName) ||
hasProp(waiting, depName) ||
hasProp(defining, depName)) {
args[i] = callDep(depName);
} else if (map.p) {
map.p.load(map.n, makeRequire(relName, true), makeLoad(depName), {});
args[i] = defined[depName];
} else {
throw new Error(name + ' missing ' + depName);
}
}
ret = callback ? callback.apply(defined[name], args) : undefined;
if (name) {
//If setting exports via "module" is in play,
//favor that over return value and exports. After that,
//favor a non-undefined return value over exports use.
if (cjsModule && cjsModule.exports !== undef &&
cjsModule.exports !== defined[name]) {
defined[name] = cjsModule.exports;
} else if (ret !== undef || !usingExports) {
//Use the return value from the function.
defined[name] = ret;
}
}
} else if (name) {
//May just be an object definition for the module. Only
//worry about defining if have a module name.
defined[name] = callback;
}
};
requirejs = require = req = function (deps, callback, relName, forceSync, alt) {
if (typeof deps === "string") {
if (handlers[deps]) {
//callback in this case is really relName
return handlers[deps](callback);
}
//Just return the module wanted. In this scenario, the
//deps arg is the module name, and second arg (if passed)
//is just the relName.
//Normalize module name, if it contains . or ..
return callDep(makeMap(deps, callback).f);
} else if (!deps.splice) {
//deps is a config object, not an array.
config = deps;
if (config.deps) {
req(config.deps, config.callback);
}
if (!callback) {
return;
}
if (callback.splice) {
//callback is an array, which means it is a dependency list.
//Adjust args if there are dependencies
deps = callback;
callback = relName;
relName = null;
} else {
deps = undef;
}
}
//Support require(['a'])
callback = callback || function () {};
//If relName is a function, it is an errback handler,
//so remove it.
if (typeof relName === 'function') {
relName = forceSync;
forceSync = alt;
}
//Simulate async callback;
if (forceSync) {
main(undef, deps, callback, relName);
} else {
//Using a non-zero value because of concern for what old browsers
//do, and latest browsers "upgrade" to 4 if lower value is used:
//http://www.whatwg.org/specs/web-apps/current-work/multipage/timers.html#dom-windowtimers-settimeout:
//If want a value immediately, use require('id') instead -- something
//that works in almond on the global level, but not guaranteed and
//unlikely to work in other AMD implementations.
setTimeout(function () {
main(undef, deps, callback, relName);
}, 4);
}
return req;
};
/**
* Just drops the config on the floor, but returns req in case
* the config return value is used.
*/
req.config = function (cfg) {
return req(cfg);
};
/**
* Expose module registry for debugging and tooling
*/
requirejs._defined = defined;
define = function (name, deps, callback) {
//This module may not have dependencies
if (!deps.splice) {
//deps is not an array, so probably means
//an object literal or factory function for
//the value. Adjust args.
callback = deps;
deps = [];
}
if (!hasProp(defined, name) && !hasProp(waiting, name)) {
waiting[name] = [name, deps, callback];
}
};
define.amd = {
jQuery: true
};
}());
define("../vendor/almond", function(){});
define('support',[], function(){
function customEvent() {
try {
var e = document.createEvent('CustomEvent');
if (e && typeof e.initCustomEvent === "function") {
e.initCustomEvent(mod, true, true, { mod: mod });
return true;
}
return false;
} catch (e) {
return false;
}
}
var mod = "support.test";
return {
CustomEvent: customEvent
};
});
define('utils',[], function(){
function bind(scope, func) {
var args = Array.prototype.slice.call(arguments, 2);
return function(){
return func.apply(scope, args.concat(Array.prototype.slice.call(arguments)))
};
}
// Iterate through obj with the callback function.
function each(obj, callback) {
if (isArray(obj)) {
for (var i = 0; i < obj.length; i++) {
if (callback(i, obj[i]) === true) break;
}
} else {
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
if (callback(key, obj[key]) === true) break;
}
}
}
}
function getKeys(obj) {
var keys = [];
each(obj, function(key){
keys.push(key);
});
return keys;
}
// Returns a boolean indicating if object arr is an array.
function isArray(arr) {
return Object.prototype.toString.call(arr) === "[object Array]";
}
// Returns a boolean indicating if the value is in the array.
function inArray(value, arr) {
for (var i = 0, len = arr.length; i < len; i++) {
if (arr[i] === value) {
return true;
}
}
return false;
}
function indexOfArray(value, arr) {
for (var i = 0, len = arr.length; i < len; i++) {
if (arr[i] === value) {
return i;
}
}
return -1;
}
function indexOf(value, arr) {
if (isArray(value, arr)) {
return indexOfArray(value, arr);
}
}
// Returns a random number between min and max
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
// Returns a random integer between min (included) and max (excluded)
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
// Returns a random string of characters of chars with the length of length
function generateToken(chars, length) {
if (typeof chars !== "string") chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
if (typeof length !== "number") length = 64;
var charsLength = chars.length;
var token = "";
for (var i = 0; i < length; i++) {
token += chars[getRandomInt(0, charsLength)];
}
return token;
}
function escapeECMAVariable(key, defaultKey) {
key = key.replace(/[^0-9a-zA-Z_\$]/g, "");
while (/$[0-9]/g.test(key)) {
if (key === "") return defaultKey;
key = key.substring(1);
}
return key;
}
return {
bind: bind,
each: each,
getKeys: getKeys,
isArray: isArray,
inArray: inArray,
indexOf: indexOf,
indexOfArray: indexOfArray,
getRandomArbitrary: getRandomArbitrary,
getRandomInt: getRandomInt,
generateToken: generateToken,
escapeECMAVariable: escapeECMAVariable
};
});
define('CustomEvent',["utils"], function(utils){
function addEventListener(event, listener) {
if (!events[event]) {
// Creating the array of listeners for event
events[event] = [];
// Adding the event listener.
window.addEventListener(event, utils.bind(null, eventListener, event, events[event]), false);
}
// Adding listener to array.
events[event].push(listener);
}
function eventListener(event, listeners, e) {
e = e || window.event;
// Parse the detail to the original object.
var data = JSON.parse(e.detail);
if (typeof data.detail === "object" && data.token !== token) {
var detail = data.detail;
for (var i = 0, len = listeners.length; i < len; i++) {
// Call the listener with the event name and the parsed detail.
listeners[i](detail);
}
// Prevent propagation
if (e && typeof e.stopPropagation === "function") {
e.stopPropagation();
}
}
}
/*function eventListener(event, listener, e) {
e = e || window.event;
// Parse the detail to the original object.
var data = JSON.parse(e.detail);
if (typeof data.detail === "object" && data.token !== token) {
// Prevent propagation
if (e && typeof e.stopPropagation === "function") {
e.stopPropagation();
}
// Call the listener with the parsed detail.
listener(data.detail);
}
}*/
function fireEvent(event, detail) {
// Creating the event
var e = document.createEvent("CustomEvent");
e.initCustomEvent(event, true, true, JSON.stringify({ detail: detail, token: token }));
// Firing the event
document.documentElement.dispatchEvent(e);
}
var token = utils.generateToken(); // The token is used to identify itself and prevent calling its own listeners.
var events = {};
return {
addEventListener: addEventListener,
fireEvent: fireEvent
};
});
define('Message',["utils"], function(utils){
function addEventListener(event, listener) {
initMessage(); // Init the message event listener if not already initialized.
if (!events[event]) events[event] = [];
// Bind the event name to the listener as an argument.
var boundListener = utils.bind(null, listener, event);
// Add the boundListener to the event
events[event].push(boundListener);
}
function fireEvent(event, detail) {
window.postMessage(JSON.stringify({ token: token, event: event, detail: detail }), "*");
}
function messageListener(e) {
e = e || window.event;
// Parse the detail to the original object.
var data = JSON.parse(e.data);
// Verify that the retrieved information is correct and that it didn't call itself.
if (typeof data.event === "string" && typeof data.detail === "object" && data.token !== token) {
// Iterate through every listener for data.event.
if (utils.isArray(events[data.event])) {
var listeners = events[data.event];
var detail = data.detail;
for (var i = 0, len = listeners.length; i < len; i++) {
listeners(detail);
}
// Prevent propagation only if everything went well.
if (e && typeof e.stopPropagation === "function") {
e.stopPropagation();
}
}
}
}
function initMessage() {
if (!messageEventAdded) {
// Adding the message event listener.
window.addEventListener("message", messageListener, false);
}
}
var messageEventAdded = false;
var token = utils.generateToken(); // The token is used to identify itself and prevent calling its own listeners.
var events = {};
return {
addEventListener: addEventListener,
fireEvent: fireEvent
};
});
define('memFunction',["utils", "CustomEvent", "Message", "support"], function(utils, customEvent, message, support){
function parseObject(obj, token, type) {
if (typeof obj === "object") {
utils.each(obj, function(key, value){
if (typeof value === "object") {
obj[key] = parseObject(value, token, type);
} else if (typeof value === "string") {
obj[key] = parseString(value);
} else if (typeof value === "function") {
var id = cache.push(value) - 1;
obj[key] = "${" + token + "/" + type + "/" + id + "}";
}
});
} else if (typeof value === "string") {
obj = parseString(obj);
} else if (typeof obj === "function") {
var id = cache.push(obj) - 1;
obj = "${" + token + "/" + type + "/" + id + "}";
}
return obj;
}
function parseString(str) {
if (/^\$[\\]*\{([0-9a-zA-Z\.\-_\/\\]+)\}$/g.test(str)) {
return "$\\" + str.substring(1);
}
return str;
}
function restoreString(str, token, type) {
if (/^\$\{([0-9a-zA-Z\.\-_]+)\/([0-9a-zA-Z\.\-_]+)\/([0-9]+)\}$/g.test(str)) {
var parsed = str.substring(2, str.length - 1).split("/"); // " + token + "/" + type + "/" + id + "
var id = parseInt(parsed[2], 10);
if (parsed[0] === token && parsed[1] === type) {
return cache[id];
} else {
return utils.bind(null, functionPlaceholder, parsed[0] + "-" + parsed[1], id);
}
} else if (/^\$[\\]+\{([0-9a-zA-Z\.\-_\/\\]+)\}$/g.test(str)) {
return "$" + str.substring(2);
}
return str;
}
function restoreObject(obj, token, type) {
if (typeof obj === "object") {
utils.each(obj, function(key, value){
if (typeof value === "object") {
obj[key] = restoreObject(value, token, type);
} else if (typeof value === "string") {
obj[key] = restoreString(value, token, type);
} else if (typeof value === "function") {
throw Error("Function was found!");
}
});
} else if (typeof value === "string") {
return restoreString(value, token, type);
} else if (typeof value === "function") {
throw Error("Function was found!");
}
return obj;
}
function functionPlaceholder(event, id) {
var args = Array.prototype.slice.call(arguments, 2);
if (support.CustomEvent) {
return customEvent.fireEvent(event, { callbackId: id, args: args, mem: true });
} else {
return message.fireEvent(event, { callbackId: id, args: args, mem: true });
}
}
function getCacheFunction(id) {
return cache[id];
}
var cache = [];
return {
parseObject: parseObject,
restoreObject: restoreObject,
getCacheFunction: getCacheFunction
};
});
define('proxy',["support", "CustomEvent", "Message", "utils", "memFunction"], function(support, customEvent, message, utils, mem){
function listener(detail) {
if (typeof detail.callbackId === "number" && utils.isArray(detail.args) && detail.mem) {
var args = mem.restoreObject(detail.args, token, "page");
var func = mem.getCacheFunction(detail.callbackId);
if (typeof func === "function") {
func.apply(null, args);
}
} else if (typeof detail.callbackId === "number" && utils.isArray(detail.args)) {
var args = mem.restoreObject(detail.args, token, "page");
if (typeof callbackCache[detail.callbackId] === "function") {
callbackCache[detail.callbackId].apply(null, args);
}
//callbackCache[detail.callbackId] = null; // Remove reference for GC.
} else {
throw Error("Malformed detail!", detail);
}
}
function prepareCall(method, callback) {
if (!has(method)) {
throw Error(method + " is not a defined function!");
}
if (typeof callback !== "function") {
throw Error("The callback is not a function!");
}
var id = callbackCache.push(callback) - 1;
var args = Array.prototype.slice.call(arguments, 2);
return function() {
args = args.concat(Array.prototype.slice.call(arguments, 0));
args = mem.parseObject(args, token, "page");
var detail = {
method: method,
args: args,
id: id
};
if (support.CustomEvent) {
customEvent.fireEvent(token + "-content", detail);
} else {
message.fireEvent(token + "-content", detail);
}
};
}
function call(method, args) {
function setCallback(callback) {
clearTimeout(timer);
if (typeof callback === "function") {
detail.id = callbackCache.push(callback) - 1;
}
execute();
}
function execute() {
if (support.CustomEvent) {
customEvent.fireEvent(token + "-content", detail);
} else {
message.fireEvent(token + "-content", detail);
}
}
args = Array.prototype.slice.call(arguments, 1);
if (!has(method)) {
throw Error(method + " is not a defined function!");
}
args = mem.parseObject(args, token, "page");
var detail = {
method: method,
args: args
};
var timer = setTimeout(execute, 4);
return {
then: setCallback
};
}
function has(method) {
return utils.indexOfArray(method, functions) > -1;
}
function getFunction(method) {
if (has(method)) {
return utils.bind(null, call, method);
} else {
throw Error(method + " is not defined!");
}
}
function listFunctions() {
return JSON.parse(JSON.stringify(functions));
}
var callbackCache = [];
if (support.CustomEvent) {
customEvent.addEventListener(token + "-page", listener);
} else {
message.addEventListener(token + "-page", listener);
}
for (var i = 0, len = functions.length; i < len; i++) {
scope[functions[i]] = utils.bind(null, call, functions[i]);
}
return {
call: call,
prepareCall: prepareCall,
getFunction: getFunction,
isDefined: has,
listFunctions: listFunctions
};
});
return require("proxy");
};
return { connect: inject, setFunctions: setFunctions, setNamespace: setNamespace };
});
return require("main");
})(); | YePpHa/UserProxy | UserProxy.js | JavaScript | mit | 55,778 |
export { default as Audience } from './audiences/model'
export { default as Client } from './clients/model'
export { default as Communication } from './communications/model'
export { default as InboundEmail } from './sendgrid/models/inboundEmail'
export { default as Lead } from './leads/model'
export { default as Market } from './markets/model'
export { default as Service } from './services/model'
export { default as Subscription } from './subscriptions/model'
export { default as TwilioBlacklist } from './twilio/models/blacklist'
export { default as User } from './users/model'
| LeadGrabr/api | src/components/models.js | JavaScript | mit | 584 |
# encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::Consumption::Mgmt::V2017_12_30_preview
#
# A service client - single point of access to the REST API.
#
class ConsumptionManagementClient < MsRestAzure::AzureServiceClient
include MsRestAzure
include MsRestAzure::Serialization
# @return [String] the base URI of the service.
attr_accessor :base_url
# @return Credentials needed for the client to connect to Azure.
attr_reader :credentials
# @return [String] Version of the API to be used with the client request.
# The current version is 2017-12-30-preview.
attr_reader :api_version
# @return [String] Azure Subscription ID.
attr_accessor :subscription_id
# @return [String] Budget name.
attr_accessor :name
# @return [String] The preferred language for the response.
attr_accessor :accept_language
# @return [Integer] The retry timeout in seconds for Long Running
# Operations. Default value is 30.
attr_accessor :long_running_operation_retry_timeout
# @return [Boolean] Whether a unique x-ms-client-request-id should be
# generated. When set to true a unique x-ms-client-request-id value is
# generated and included in each request. Default is true.
attr_accessor :generate_client_request_id
# @return [Budgets] budgets
attr_reader :budgets
# @return [Operations] operations
attr_reader :operations
#
# Creates initializes a new instance of the ConsumptionManagementClient class.
# @param credentials [MsRest::ServiceClientCredentials] credentials to authorize HTTP requests made by the service client.
# @param base_url [String] the base URI of the service.
# @param options [Array] filters to be applied to the HTTP requests.
#
def initialize(credentials = nil, base_url = nil, options = nil)
super(credentials, options)
@base_url = base_url || 'https://management.azure.com'
fail ArgumentError, 'invalid type of credentials input parameter' unless credentials.is_a?(MsRest::ServiceClientCredentials) unless credentials.nil?
@credentials = credentials
@budgets = Budgets.new(self)
@operations = Operations.new(self)
@api_version = '2017-12-30-preview'
@accept_language = 'en-US'
@long_running_operation_retry_timeout = 30
@generate_client_request_id = true
add_telemetry
end
#
# Makes a request and returns the body of the response.
# @param method [Symbol] with any of the following values :get, :put, :post, :patch, :delete.
# @param path [String] the path, relative to {base_url}.
# @param options [Hash{String=>String}] specifying any request options like :body.
# @return [Hash{String=>String}] containing the body of the response.
# Example:
#
# request_content = "{'location':'westus','tags':{'tag1':'val1','tag2':'val2'}}"
# path = "/path"
# options = {
# body: request_content,
# query_params: {'api-version' => '2016-02-01'}
# }
# result = @client.make_request(:put, path, options)
#
def make_request(method, path, options = {})
result = make_request_with_http_info(method, path, options)
result.body unless result.nil?
end
#
# Makes a request and returns the operation response.
# @param method [Symbol] with any of the following values :get, :put, :post, :patch, :delete.
# @param path [String] the path, relative to {base_url}.
# @param options [Hash{String=>String}] specifying any request options like :body.
# @return [MsRestAzure::AzureOperationResponse] Operation response containing the request, response and status.
#
def make_request_with_http_info(method, path, options = {})
result = make_request_async(method, path, options).value!
result.body = result.response.body.to_s.empty? ? nil : JSON.load(result.response.body)
result
end
#
# Makes a request asynchronously.
# @param method [Symbol] with any of the following values :get, :put, :post, :patch, :delete.
# @param path [String] the path, relative to {base_url}.
# @param options [Hash{String=>String}] specifying any request options like :body.
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def make_request_async(method, path, options = {})
fail ArgumentError, 'method is nil' if method.nil?
fail ArgumentError, 'path is nil' if path.nil?
request_url = options[:base_url] || @base_url
if(!options[:headers].nil? && !options[:headers]['Content-Type'].nil?)
@request_headers['Content-Type'] = options[:headers]['Content-Type']
end
request_headers = @request_headers
request_headers.merge!({'accept-language' => @accept_language}) unless @accept_language.nil?
options.merge!({headers: request_headers.merge(options[:headers] || {})})
options.merge!({credentials: @credentials}) unless @credentials.nil?
super(request_url, method, path, options)
end
private
#
# Adds telemetry information.
#
def add_telemetry
sdk_information = 'azure_mgmt_consumption'
sdk_information = "#{sdk_information}/0.18.1"
add_user_agent_information(sdk_information)
end
end
end
| Azure/azure-sdk-for-ruby | management/azure_mgmt_consumption/lib/2017-12-30-preview/generated/azure_mgmt_consumption/consumption_management_client.rb | Ruby | mit | 5,431 |
using System;
using System.Collections.Generic;
using DXFramework.Util;
using Poly2Tri;
using SharpDX;
namespace DXFramework.PrimitiveFramework
{
public class PTriangle : Primitive
{
private Vector2 a;
private Vector2 b;
private Vector2 c;
public PTriangle( PTriangle triangle )
: base( triangle )
{
this.a = triangle.a;
this.b = triangle.b;
this.c = triangle.c;
}
public PTriangle( Vector2 a, float lengthAB, float angleB, bool filled )
: base( filled )
{
if( angleB >= 180 )
{
throw new ArgumentException( "Angle cannot be greater than or equal to 180." );
}
this.position = a;
this.a = a;
this.b = new Vector2( a.X + lengthAB, a.Y );
this.c = b + TriangleHelper2D.RadianToVector( MathUtil.DegreesToRadians( angleB ) - MathUtil.PiOverTwo ) * lengthAB;
}
public PTriangle( Vector2 a, float lengthAB, float angleB, uint thickness )
: base( thickness )
{
if( angleB >= 180 )
{
throw new ArgumentException( "Angle cannot be greater than or equal to 180." );
}
this.position = a;
this.a = a;
this.b = new Vector2( a.X + lengthAB, a.Y );
this.c = b + TriangleHelper2D.RadianToVector( MathUtil.DegreesToRadians( angleB ) - MathUtil.PiOverTwo ) * lengthAB;
}
public PTriangle( Vector2 a, Vector2 b, Vector2 c, bool filled )
: base( filled )
{
this.position = a;
this.a = a;
this.b = b;
this.c = c;
}
public PTriangle( Vector2 a, Vector2 b, Vector2 c, uint thickness )
: base( thickness )
{
this.position = a;
this.a = a;
this.b = b;
this.c = c;
}
internal override List<PolygonPoint> GetPoints()
{
List<PolygonPoint> points = new List<PolygonPoint>(){
new PolygonPoint(a.X, a.Y),
new PolygonPoint(b.X, b.Y),
new PolygonPoint(c.X, c.Y)};
if( !Filled )
{
points.Add( points[ 0 ] );
}
// Offset all points by distance to the centroid. This places all points around (0, 0).
Vector2 center = GetCentroid( points );
foreach( PolygonPoint point in points )
{
point.X -= center.X;
point.Y -= center.Y;
}
return points;
}
protected override Polygon GetPolygon()
{
Polygon poly = new Polygon( GetPoints() );
if( thickness > 1 )
{
List<PolygonPoint> points = GetPoints();
Vector2 center = GetCentroid( points );
float[] angles = { TriangleHelper2D.AngleA( a, b, c ), TriangleHelper2D.AngleB( a, b, c ), TriangleHelper2D.AngleC( a, b, c ) };
int count = points.Count;
for( int i = count; --i >= 0; )
{
PolygonPoint point = points[ i ];
double vecX = center.X - point.X;
double vecY = center.Y - point.Y;
double invLen = 1d / Math.Sqrt( ( vecX * vecX ) + ( vecY * vecY ) );
vecX = vecX * invLen;
vecY = vecY * invLen;
float ratio = 1 - ( angles[ i ] / 180 );
float angleThickness = ratio * thickness;
point.X += vecX * angleThickness;
point.Y += vecY * angleThickness;
}
Polygon hole = new Polygon( points );
poly.AddHole( hole );
}
return poly;
}
public override bool Intersects( float x, float y )
{
if( Filled )
{
return base.Intersects( x, y );
}
else
{
Vector2 A = new Vector2();
Vector2 B = new Vector2();
Vector2 C = new Vector2();
A.X = tranformedVPCs[ 0 ].Position.X;
A.Y = tranformedVPCs[ 0 ].Position.Y;
B.X = tranformedVPCs[ 2 ].Position.X;
B.Y = tranformedVPCs[ 2 ].Position.Y;
C.X = tranformedVPCs[ 4 ].Position.X;
C.Y = tranformedVPCs[ 4 ].Position.Y;
if( IntersectsTriangle( ref x, ref y, ref A, ref B, ref C ) )
{
return true;
}
}
return false;
}
}
} | adamxi/SharpDXFramework | DXFramework/PrimitiveFramework/PTriangle.cs | C# | mit | 3,697 |
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->engine = "InnoDB";
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->integer('role');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('users');
}
}
| wgerro/sprintko | database/migrations/2014_10_12_000000_create_users_table.php | PHP | mit | 814 |
#include "Math/Math.h"
float Math::Distance(float x0, float y0, float x1, float y1) {
return sqrt(pow(x0 - x1, 2) + pow(y1 - y0, 2));
}
float Math::Distance(Vector &a, Vector &b) {
return sqrt(pow(a.m_x - b.m_x, 2) + pow(a.m_y - b.m_y, 2));
}
bool RangeIntersect(float min0, float max0, float min1, float max1) {
return max0 >= min1 && min0 <= max1;
}
| vitorfhc/ZebraEngine | src/Math/Math.cpp | C++ | mit | 361 |
/**
* #describe
* Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.
* For example,
* Given [3,2,1,5,6,4] and k = 2, return 5.
* Note:
* You may assume k is always valid, 1 ≤ k ≤ array's length.
* Credits:
* Special thanks to @mithmatt for adding this problem and creating all test cases.
* #describe
*/
/* answer */
/* answer */
/* test */
/* test */
| xiguaxigua/leetcode | answers/kth-largest-element-in-an-array.js | JavaScript | mit | 461 |
require 'cases/helper'
class ArrayItemClass < GQL::String
string :upcased, -> { target.upcase }
end
class MyFixnum < GQL::Number
string :whoami, -> { 'I am a number.' }
end
class MyString < GQL::String
string :whoami, -> { 'I am a string.' }
end
class FieldWithArrays < GQL::Field
array :class_as_item_class, -> { %w(a b) }, item_class: ArrayItemClass
array :string_as_item_class, -> { %w(a b) }, item_class: 'ArrayItemClass'
array :hash_with_class_values_as_item_class, -> { ['foo', 42] }, item_class: { Fixnum => MyFixnum, String => MyString }
array :hash_with_string_values_as_item_class, -> { ['foo', 42] }, item_class: { Fixnum => 'MyFixnum', String => 'MyString' }
array :proc_as_item_class, -> { ['foo', 42] }, item_class: -> item { item.is_a?(String) ? MyString : 'MyFixnum' }
end
class ArrayTest < ActiveSupport::TestCase
setup do
@old_root, GQL.root_class = GQL.root_class, FieldWithArrays
end
teardown do
GQL.root_class = @old_root
end
test "returns array value" do
value = GQL.execute('{ class_as_item_class as arr }')
assert_equal ['a', 'b'], value[:arr]
end
test "class as item_class" do
value = GQL.execute('{ class_as_item_class as arr { upcased } }')
assert_equal [{ upcased: 'A' }, { upcased: 'B' }], value[:arr]
end
test "string as item_class" do
GQL::Registry.reset
assert FieldWithArrays.fields[:string_as_item_class] < GQL::Lazy
value = GQL.execute('{ string_as_item_class as arr }')
assert_equal ['a', 'b'], value[:arr]
end
test "hash with class values provided as item_class" do
value = GQL.execute('{ hash_with_class_values_as_item_class as arr { whoami } }')
assert_equal [{ whoami: 'I am a string.' }, { whoami: 'I am a number.' }], value[:arr]
end
test "hash with string values provided as item_class" do
GQL::Registry.reset
value = GQL.execute('{ hash_with_string_values_as_item_class as arr { whoami } }')
assert_equal [{ whoami: 'I am a string.' }, { whoami: 'I am a number.' }], value[:arr]
end
test "proc as item_class" do
GQL::Registry.reset
value = GQL.execute('{ proc_as_item_class as arr { whoami } }')
assert_equal [{ whoami: 'I am a string.' }, { whoami: 'I am a number.' }], value[:arr]
end
end
| martinandert/gql | test/cases/array_test.rb | Ruby | mit | 2,274 |
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var User = require('./user');
var entitySchema = new Schema({
room: { type: Schema.Types.ObjectId, ref: 'Room' },
x: { type: Number, default: -1 },
y: { type: Number, default: -1 },
body: Schema.Types.Mixed,
character: String,
color: String,
behavior: String,
description: String,
belongsTo: { type: Schema.Types.ObjectId, ref: 'User' }
});
entitySchema.pre('save', function(next) {
this.markModified('body');
var now = new Date();
if(this.belongsTo) {
this.model('User').update({_id: this.belongsTo}, {lastMessage: now}, function(err, user) {
if(err) console.log("While saving entity", err.message);
});
}
next();
});
entitySchema.static('getColor', function(playerId, callback) {
this.findOne({belongsTo: playerId}, function(err, entity) {
if(err) console.log(err.message);
callback([entity.color, entity.character]);
});
});
module.exports = mongoose.model('Entity', entitySchema);
| Huntrr/mp.txt | app/schema/entity.js | JavaScript | mit | 1,017 |
<?xml version="1.0" ?><!DOCTYPE TS><TS language="nl" version="2.0">
<defaultcodec>UTF-8</defaultcodec>
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About TPPcoin</source>
<translation>Over TPPcoin</translation>
</message>
<message>
<location line="+39"/>
<source><b>TPPcoin</b> version</source>
<translation><b>TPPcoin</b> versie</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>
Dit is experimentele software.
Gedistribueerd onder de MIT/X11 software licentie, zie het bijgevoegde bestand COPYING of http://www.opensource.org/licenses/mit-license.php.
Dit product bevat software ontwikkeld door het OpenSSL Project voor gebruik in de OpenSSL Toolkit (http://www.openssl.org/) en cryptografische software gemaakt door Eric Young (eay@cryptsoft.com) en UPnP software geschreven door Thomas Bernard.</translation>
</message>
<message>
<location filename="../aboutdialog.cpp" line="+14"/>
<source>Copyright</source>
<translation>Auteursrecht</translation>
</message>
<message>
<location line="+0"/>
<source>The TPPcoin developers</source>
<translation>De TPPcoin-ontwikkelaars</translation>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation>Adresboek</translation>
</message>
<message>
<location line="+19"/>
<source>Double-click to edit address or label</source>
<translation>Dubbelklik om adres of label te wijzigen</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>Maak een nieuw adres aan</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Kopieer het huidig geselecteerde adres naar het klembord</translation>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation>&Nieuw Adres</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+63"/>
<source>These are your TPPcoin 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>Dit zijn uw TPPcoinadressen om betalingen mee te ontvangen. U kunt er voor kiezen om een uniek adres aan te maken voor elke afzender. Op deze manier kunt u bijhouden wie al aan u betaald heeft.</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>&Copy Address</source>
<translation>&Kopiëer Adres</translation>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation>Toon &QR-Code</translation>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a TPPcoin address</source>
<translation>Onderteken een bericht om te bewijzen dat u een bepaald TPPcoinadres bezit</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>&Onderteken Bericht</translation>
</message>
<message>
<location line="+25"/>
<source>Delete the currently selected address from the list</source>
<translation>Verwijder het geselecteerde adres van de lijst</translation>
</message>
<message>
<location line="+27"/>
<source>Export the data in the current tab to a file</source>
<translation>Exporteer de data in de huidige tab naar een bestand</translation>
</message>
<message>
<location line="+3"/>
<source>&Export</source>
<translation>&Exporteer</translation>
</message>
<message>
<location line="-44"/>
<source>Verify a message to ensure it was signed with a specified TPPcoin address</source>
<translation>Controleer een bericht om te verifiëren dat het gespecificeerde TPPcoinadres het bericht heeft ondertekend.</translation>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation>&Verifiëer Bericht</translation>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>&Verwijder</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="-5"/>
<source>These are your TPPcoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source>
<translation>Dit zijn uw TPPcoinadressen om betalingen mee te verzenden. Check altijd het bedrag en het ontvangende adres voordat u uw tppcoins verzendt.</translation>
</message>
<message>
<location line="+13"/>
<source>Copy &Label</source>
<translation>Kopiëer &Label</translation>
</message>
<message>
<location line="+1"/>
<source>&Edit</source>
<translation>&Bewerk</translation>
</message>
<message>
<location line="+1"/>
<source>Send &Coins</source>
<translation>Verstuur &Coins</translation>
</message>
<message>
<location line="+260"/>
<source>Export Address Book Data</source>
<translation>Exporteer Gegevens van het Adresboek</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Kommagescheiden bestand (*.csv)</translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation>Fout bij exporteren</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Kon niet schrijven naar bestand %1.</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation>Label</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Adres</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(geen label)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation>Wachtwoorddialoogscherm</translation>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>Voer wachtwoord in</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>Nieuw wachtwoord</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>Herhaal wachtwoord</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>Vul een nieuw wachtwoord in voor uw portemonnee. <br/> Gebruik een wachtwoord van <b>10 of meer lukrake karakters</b>, of <b> acht of meer woorden</b> . </translation>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation>Versleutel portemonnee</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>Deze operatie vereist uw portemonneewachtwoord om de portemonnee te openen.</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>Open portemonnee</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>Deze operatie vereist uw portemonneewachtwoord om de portemonnee te ontsleutelen</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>Ontsleutel portemonnee</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>Wijzig wachtwoord</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Vul uw oude en nieuwe portemonneewachtwoord in.</translation>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation>Bevestig versleuteling van de portemonnee</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR TPPCOINS</b>!</source>
<translation>Waarschuwing: Als u uw portemonnee versleutelt en uw wachtwoord vergeet, zult u <b>AL UW TPPCOINS VERLIEZEN</b>!</translation>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>Weet u zeker dat u uw portemonnee wilt versleutelen?</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>BELANGRIJK: Elke eerder gemaakte backup van uw portemonneebestand dient u te vervangen door het nieuw gegenereerde, versleutelde portemonneebestand. Om veiligheidsredenen zullen eerdere backups van het niet-versleutelde portemonneebestand onbruikbaar worden zodra u uw nieuwe, versleutelde, portemonnee begint te gebruiken.</translation>
</message>
<message>
<location line="+100"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation>Waarschuwing: De Caps-Lock-toets staat aan!</translation>
</message>
<message>
<location line="-130"/>
<location line="+58"/>
<source>Wallet encrypted</source>
<translation>Portemonnee versleuteld</translation>
</message>
<message>
<location line="-56"/>
<source>TPPcoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your tppcoins from being stolen by malware infecting your computer.</source>
<translation>TPPcoin zal nu afsluiten om het versleutelingsproces te voltooien. Onthoud dat het versleutelen van uw portemonnee u niet volledig kan beschermen: Malware kan uw computer infecteren en uw tppcoins stelen.</translation>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+42"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>Portemonneeversleuteling mislukt</translation>
</message>
<message>
<location line="-54"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Portemonneeversleuteling mislukt door een interne fout. Uw portemonnee is niet versleuteld.</translation>
</message>
<message>
<location line="+7"/>
<location line="+48"/>
<source>The supplied passphrases do not match.</source>
<translation>De opgegeven wachtwoorden komen niet overeen</translation>
</message>
<message>
<location line="-37"/>
<source>Wallet unlock failed</source>
<translation>Portemonnee openen mislukt</translation>
</message>
<message>
<location line="+1"/>
<location line="+11"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>Het opgegeven wachtwoord voor de portemonnee-ontsleuteling is niet correct.</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>Portemonnee-ontsleuteling mislukt</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation>Portemonneewachtwoord is met succes gewijzigd.</translation>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+233"/>
<source>Sign &message...</source>
<translation>&Onderteken bericht...</translation>
</message>
<message>
<location line="+280"/>
<source>Synchronizing with network...</source>
<translation>Synchroniseren met netwerk...</translation>
</message>
<message>
<location line="-349"/>
<source>&Overview</source>
<translation>&Overzicht</translation>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation>Toon algemeen overzicht van de portemonnee</translation>
</message>
<message>
<location line="+20"/>
<source>&Transactions</source>
<translation>&Transacties</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>Blader door transactieverleden</translation>
</message>
<message>
<location line="+7"/>
<source>Edit the list of stored addresses and labels</source>
<translation>Bewerk de lijst van opgeslagen adressen en labels</translation>
</message>
<message>
<location line="-14"/>
<source>Show the list of addresses for receiving payments</source>
<translation>Toon lijst van adressen om betalingen mee te ontvangen</translation>
</message>
<message>
<location line="+31"/>
<source>E&xit</source>
<translation>&Afsluiten</translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>Programma afsluiten</translation>
</message>
<message>
<location line="+4"/>
<source>Show information about TPPcoin</source>
<translation>Laat informatie zien over TPPcoin</translation>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation>Over &Qt</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation>Toon informatie over Qt</translation>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>O&pties...</translation>
</message>
<message>
<location line="+6"/>
<source>&Encrypt Wallet...</source>
<translation>&Versleutel Portemonnee...</translation>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation>&Backup Portemonnee...</translation>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation>&Wijzig Wachtwoord</translation>
</message>
<message>
<location line="+285"/>
<source>Importing blocks from disk...</source>
<translation>Blokken aan het importeren vanaf harde schijf...</translation>
</message>
<message>
<location line="+3"/>
<source>Reindexing blocks on disk...</source>
<translation>Bezig met herindexeren van blokken op harde schijf...</translation>
</message>
<message>
<location line="-347"/>
<source>Send coins to a TPPcoin address</source>
<translation>Verstuur munten naar een TPPcoinadres</translation>
</message>
<message>
<location line="+49"/>
<source>Modify configuration options for TPPcoin</source>
<translation>Wijzig instellingen van TPPcoin</translation>
</message>
<message>
<location line="+9"/>
<source>Backup wallet to another location</source>
<translation>&Backup portemonnee naar een andere locatie</translation>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>Wijzig het wachtwoord voor uw portemonneversleuteling</translation>
</message>
<message>
<location line="+6"/>
<source>&Debug window</source>
<translation>&Debugscherm</translation>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation>Open debugging en diagnostische console</translation>
</message>
<message>
<location line="-4"/>
<source>&Verify message...</source>
<translation>&Verifiëer bericht...</translation>
</message>
<message>
<location line="-165"/>
<location line="+530"/>
<source>TPPcoin</source>
<translation>TPPcoin</translation>
</message>
<message>
<location line="-530"/>
<source>Wallet</source>
<translation>Portemonnee</translation>
</message>
<message>
<location line="+101"/>
<source>&Send</source>
<translation>&Versturen</translation>
</message>
<message>
<location line="+7"/>
<source>&Receive</source>
<translation>&Ontvangen</translation>
</message>
<message>
<location line="+14"/>
<source>&Addresses</source>
<translation>&Adressen</translation>
</message>
<message>
<location line="+22"/>
<source>&About TPPcoin</source>
<translation>&Over TPPcoin</translation>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation>&Toon / Verberg</translation>
</message>
<message>
<location line="+1"/>
<source>Show or hide the main Window</source>
<translation>Toon of verberg het hoofdvenster</translation>
</message>
<message>
<location line="+3"/>
<source>Encrypt the private keys that belong to your wallet</source>
<translation>Versleutel de geheime sleutels die bij uw portemonnee horen</translation>
</message>
<message>
<location line="+7"/>
<source>Sign messages with your TPPcoin addresses to prove you own them</source>
<translation>Onderteken berichten met uw TPPcoinadressen om te bewijzen dat u deze adressen bezit</translation>
</message>
<message>
<location line="+2"/>
<source>Verify messages to ensure they were signed with specified TPPcoin addresses</source>
<translation>Verifiëer handtekeningen om zeker te zijn dat de berichten zijn ondertekend met de gespecificeerde TPPcoinadressen</translation>
</message>
<message>
<location line="+28"/>
<source>&File</source>
<translation>&Bestand</translation>
</message>
<message>
<location line="+7"/>
<source>&Settings</source>
<translation>&Instellingen</translation>
</message>
<message>
<location line="+6"/>
<source>&Help</source>
<translation>&Hulp</translation>
</message>
<message>
<location line="+9"/>
<source>Tabs toolbar</source>
<translation>Tab-werkbalk</translation>
</message>
<message>
<location line="+17"/>
<location line="+10"/>
<source>[testnet]</source>
<translation>[testnetwerk]</translation>
</message>
<message>
<location line="+47"/>
<source>TPPcoin client</source>
<translation>TPPcoin client</translation>
</message>
<message numerus="yes">
<location line="+141"/>
<source>%n active connection(s) to TPPcoin network</source>
<translation><numerusform>%n actieve connectie naar TPPcoinnetwerk</numerusform><numerusform>%n actieve connecties naar TPPcoinnetwerk</numerusform></translation>
</message>
<message>
<location line="+22"/>
<source>No block source available...</source>
<translation>Geen bron van blokken beschikbaar...</translation>
</message>
<message>
<location line="+12"/>
<source>Processed %1 of %2 (estimated) blocks of transaction history.</source>
<translation>%1 van %2 (geschat) blokken van de transactiehistorie verwerkt.</translation>
</message>
<message>
<location line="+4"/>
<source>Processed %1 blocks of transaction history.</source>
<translation>%1 blokken van transactiehistorie verwerkt.</translation>
</message>
<message numerus="yes">
<location line="+20"/>
<source>%n hour(s)</source>
<translation><numerusform>%n uur</numerusform><numerusform>%n uur</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation><numerusform>%n dag</numerusform><numerusform>%n dagen</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n week(s)</source>
<translation><numerusform>%n week</numerusform><numerusform>%n weken</numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>%1 behind</source>
<translation>%1 achter</translation>
</message>
<message>
<location line="+14"/>
<source>Last received block was generated %1 ago.</source>
<translation>Laatst ontvangen blok was %1 geleden gegenereerd.</translation>
</message>
<message>
<location line="+2"/>
<source>Transactions after this will not yet be visible.</source>
<translation>Transacties na dit moment zullen nu nog niet zichtbaar zijn.</translation>
</message>
<message>
<location line="+22"/>
<source>Error</source>
<translation>Fout</translation>
</message>
<message>
<location line="+3"/>
<source>Warning</source>
<translation>Waarschuwing</translation>
</message>
<message>
<location line="+3"/>
<source>Information</source>
<translation>Informatie</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>Deze transactie overschrijdt de groottelimiet. Om de transactie alsnog te versturen kunt u transactiekosten betalen van %1. Deze transactiekosten gaan naar de nodes die uw transactie verwerken en het helpt op deze manier bij het ondersteunen van het TPPcoinnetwerk. Wilt u de transactiekosten betalen?</translation>
</message>
<message>
<location line="-140"/>
<source>Up to date</source>
<translation>Bijgewerkt</translation>
</message>
<message>
<location line="+31"/>
<source>Catching up...</source>
<translation>Aan het bijwerken...</translation>
</message>
<message>
<location line="+113"/>
<source>Confirm transaction fee</source>
<translation>Bevestig transactiekosten</translation>
</message>
<message>
<location line="+8"/>
<source>Sent transaction</source>
<translation>Verzonden transactie</translation>
</message>
<message>
<location line="+0"/>
<source>Incoming transaction</source>
<translation>Binnenkomende transactie</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>Datum: %1
Bedrag: %2
Type: %3
Adres: %4
</translation>
</message>
<message>
<location line="+33"/>
<location line="+23"/>
<source>URI handling</source>
<translation>URI-behandeling</translation>
</message>
<message>
<location line="-23"/>
<location line="+23"/>
<source>URI can not be parsed! This can be caused by an invalid TPPcoin address or malformed URI parameters.</source>
<translation>URI kan niet worden geïnterpreteerd. Dit kan komen door een ongeldig TPPcoinadres of misvormde URI-parameters.</translation>
</message>
<message>
<location line="+17"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>Portemonnee is <b>versleuteld</b> en momenteel <b>geopend</b></translation>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>Portemonnee is <b>versleuteld</b> en momenteel <b>gesloten</b></translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="+111"/>
<source>A fatal error occurred. TPPcoin can no longer continue safely and will quit.</source>
<translation>Er is een fatale fout opgetreden. TPPcoin kan niet meer veilig doorgaan en zal nu afgesloten worden.</translation>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+104"/>
<source>Network Alert</source>
<translation>Netwerkwaarschuwing</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>Bewerk Adres</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation>&Label</translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation>Het label dat geassocieerd is met dit adres</translation>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>&Adres</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>Het adres dat geassocieerd is met deze inschrijving in het adresboek. Dit kan alleen worden veranderd voor zend-adressen.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+21"/>
<source>New receiving address</source>
<translation>Nieuw ontvangstadres</translation>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation>Nieuw adres om naar te verzenden</translation>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation>Bewerk ontvangstadres</translation>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation>Bewerk adres om naar te verzenden</translation>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>Het opgegeven adres "%1" bestaat al in uw adresboek.</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid TPPcoin address.</source>
<translation>Het opgegeven adres "%1" is een ongeldig TPPcoinadres</translation>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation>Kon de portemonnee niet openen.</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>Genereren nieuwe sleutel mislukt.</translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+424"/>
<location line="+12"/>
<source>TPPcoin-Qt</source>
<translation>TPPcoin-Qt</translation>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation>versie</translation>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation>Gebruik:</translation>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation>commandoregel-opties</translation>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation>gebruikersinterfaceopties</translation>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation>Stel taal in, bijvoorbeeld ''de_DE" (standaard: systeeminstellingen)</translation>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation>Geminimaliseerd starten</translation>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation>Laat laadscherm zien bij het opstarten. (standaard: 1)</translation>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation>Opties</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation>&Algemeen</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>Optionele transactiekosten per kB. Transactiekosten helpen ervoor te zorgen dat uw transacties snel verwerkt worden. De meeste transacties zijn 1kB.</translation>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation>Betaal &transactiekosten</translation>
</message>
<message>
<location line="+31"/>
<source>Automatically start TPPcoin after logging in to the system.</source>
<translation>Start TPPcoin automatisch na inloggen in het systeem</translation>
</message>
<message>
<location line="+3"/>
<source>&Start TPPcoin on system login</source>
<translation>Start &TPPcoin bij het inloggen in het systeem</translation>
</message>
<message>
<location line="+35"/>
<source>Reset all client options to default.</source>
<translation>Reset alle clientopties naar de standaardinstellingen.</translation>
</message>
<message>
<location line="+3"/>
<source>&Reset Options</source>
<translation>&Reset Opties</translation>
</message>
<message>
<location line="+13"/>
<source>&Network</source>
<translation>&Netwerk</translation>
</message>
<message>
<location line="+6"/>
<source>Automatically open the TPPcoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation>Open de TPPcoin-poort automatisch op de router. Dit werkt alleen als de router UPnP ondersteunt en het aanstaat.</translation>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation>Portmapping via &UPnP</translation>
</message>
<message>
<location line="+7"/>
<source>Connect to the TPPcoin network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation>Verbind met het TPPcoin-netwerk via een SOCKS-proxy (bijv. wanneer u via Tor wilt verbinden)</translation>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation>&Verbind via een SOCKS-proxy</translation>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation>Proxy &IP:</translation>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation>IP-adres van de proxy (bijv. 127.0.0.1)</translation>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation>&Poort:</translation>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation>Poort van de proxy (bijv. 9050)</translation>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation>SOCKS-&Versie:</translation>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation>SOCKS-versie van de proxy (bijv. 5)</translation>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation>&Scherm</translation>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation>Laat alleen een systeemvak-icoon zien wanneer het venster geminimaliseerd is</translation>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>&Minimaliseer naar het systeemvak in plaats van de taakbalk</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>Minimaliseer het venster in de plaats van de applicatie af te sluiten als het venster gesloten wordt. Wanneer deze optie aan staan, kan de applicatie alleen worden afgesloten door Afsluiten te kiezen in het menu.</translation>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation>Minimaliseer bij sluiten van het &venster</translation>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation>&Interface</translation>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation>Taal &Gebruikersinterface:</translation>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting TPPcoin.</source>
<translation>De taal van de gebruikersinterface kan hier ingesteld worden. Deze instelling zal pas van kracht worden nadat TPPcoin herstart wordt.</translation>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation>&Eenheid om bedrag in te tonen:</translation>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation>Kies de standaard onderverdelingseenheid om weer te geven in uw programma, en voor het versturen van munten</translation>
</message>
<message>
<location line="+9"/>
<source>Whether to show TPPcoin addresses in the transaction list or not.</source>
<translation>Of TPPcoinadressen getoond worden in de transactielijst</translation>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation>Toon a&dressen in de transactielijst</translation>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation>&OK</translation>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation>Ann&uleren</translation>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation>&Toepassen</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+53"/>
<source>default</source>
<translation>standaard</translation>
</message>
<message>
<location line="+130"/>
<source>Confirm options reset</source>
<translation>Bevestig reset opties</translation>
</message>
<message>
<location line="+1"/>
<source>Some settings may require a client restart to take effect.</source>
<translation>Sommige instellingen vereisen het herstarten van de client voordat ze in werking treden.</translation>
</message>
<message>
<location line="+0"/>
<source>Do you want to proceed?</source>
<translation> Wilt u doorgaan?</translation>
</message>
<message>
<location line="+42"/>
<location line="+9"/>
<source>Warning</source>
<translation>Waarschuwing</translation>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting TPPcoin.</source>
<translation>Deze instelling zal pas van kracht worden na het herstarten van TPPcoin.</translation>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation>Het opgegeven proxyadres is ongeldig.</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation>Vorm</translation>
</message>
<message>
<location line="+50"/>
<location line="+166"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the TPPcoin network after a connection is established, but this process has not completed yet.</source>
<translation>De weergegeven informatie kan verouderd zijn. Uw portemonnee synchroniseert automaticsh met het TPPcoinnetwerk nadat een verbinding is gelegd, maar dit proces is nog niet voltooid.</translation>
</message>
<message>
<location line="-124"/>
<source>Balance:</source>
<translation>Saldo:</translation>
</message>
<message>
<location line="+29"/>
<source>Unconfirmed:</source>
<translation>Onbevestigd:</translation>
</message>
<message>
<location line="-78"/>
<source>Wallet</source>
<translation>Portemonnee</translation>
</message>
<message>
<location line="+107"/>
<source>Immature:</source>
<translation>Immatuur:</translation>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation>Gedolven saldo dat nog niet tot wasdom is gekomen</translation>
</message>
<message>
<location line="+46"/>
<source><b>Recent transactions</b></source>
<translation><b>Recente transacties</b></translation>
</message>
<message>
<location line="-101"/>
<source>Your current balance</source>
<translation>Uw huidige saldo</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>Totaal van de transacties die nog moeten worden bevestigd en nog niet zijn meegeteld in uw huidige saldo </translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="+116"/>
<location line="+1"/>
<source>out of sync</source>
<translation>niet gesynchroniseerd</translation>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<location filename="../paymentserver.cpp" line="+107"/>
<source>Cannot start tppcoin: click-to-pay handler</source>
<translation>Kan tppcoin niet starten: click-to-pay handler</translation>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation>QR-codescherm</translation>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation>Vraag betaling aan</translation>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation>Bedrag:</translation>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation>Label:</translation>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation>Bericht:</translation>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation>&Opslaan Als...</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation>Fout tijdens encoderen URI in QR-code</translation>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation>Het opgegeven bedrag is ongeldig, controleer het s.v.p.</translation>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation>Resulterende URI te lang, probeer de tekst korter te maken voor het label/bericht.</translation>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation>Sla QR-code op</translation>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation>PNG-Afbeeldingen (*.png)</translation>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation>Clientnaam</translation>
</message>
<message>
<location line="+10"/>
<location line="+23"/>
<location line="+26"/>
<location line="+23"/>
<location line="+23"/>
<location line="+36"/>
<location line="+53"/>
<location line="+23"/>
<location line="+23"/>
<location filename="../rpcconsole.cpp" line="+339"/>
<source>N/A</source>
<translation>N.v.t.</translation>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation>Clientversie</translation>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation>&Informatie</translation>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation>Gebruikt OpenSSL versie</translation>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation>Opstarttijd</translation>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation>Netwerk</translation>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation>Aantal connecties</translation>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation>Op testnet</translation>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation>Blokketen</translation>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation>Huidig aantal blokken</translation>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation>Geschat totaal aantal blokken</translation>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation>Tijd laatste blok</translation>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation>&Open</translation>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation>Commandoregel-opties</translation>
</message>
<message>
<location line="+7"/>
<source>Show the TPPcoin-Qt help message to get a list with possible TPPcoin command-line options.</source>
<translation>Toon het TPPcoinQt-hulpbericht voor een lijst met mogelijke TPPcoin commandoregel-opties.</translation>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation>&Toon</translation>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation>&Console</translation>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation>Bouwdatum</translation>
</message>
<message>
<location line="-104"/>
<source>TPPcoin - Debug window</source>
<translation>TPPcoin-debugscherm</translation>
</message>
<message>
<location line="+25"/>
<source>TPPcoin Core</source>
<translation>TPPcoin Kern</translation>
</message>
<message>
<location line="+279"/>
<source>Debug log file</source>
<translation>Debug-logbestand</translation>
</message>
<message>
<location line="+7"/>
<source>Open the TPPcoin debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation>Open het TPPcoindebug-logbestand van de huidige datamap. Dit kan een aantal seconden duren voor grote logbestanden.</translation>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation>Maak console leeg</translation>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-30"/>
<source>Welcome to the TPPcoin RPC console.</source>
<translation>Welkom bij de TPPcoin RPC-console.</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>Gebruik de pijltjestoetsen om door de geschiedenis te navigeren, en <b>Ctrl-L</b> om het scherm leeg te maken.</translation>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation>Typ <b>help</b> voor een overzicht van de beschikbare commando's.</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>Verstuur munten</translation>
</message>
<message>
<location line="+50"/>
<source>Send to multiple recipients at once</source>
<translation>Verstuur aan verschillende ontvangers ineens</translation>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation>Voeg &Ontvanger Toe</translation>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation>Verwijder alle transactievelden</translation>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation>Verwijder &Alles</translation>
</message>
<message>
<location line="+22"/>
<source>Balance:</source>
<translation>Saldo:</translation>
</message>
<message>
<location line="+10"/>
<source>123.456 BTC</source>
<translation>123.456 BTC</translation>
</message>
<message>
<location line="+31"/>
<source>Confirm the send action</source>
<translation>Bevestig de verstuuractie</translation>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation>&Verstuur</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-59"/>
<source><b>%1</b> to %2 (%3)</source>
<translation><b>%1</b> aan %2 (%3)</translation>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation>Bevestig versturen munten</translation>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation>Weet u zeker dat u %1 wil versturen?</translation>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation> en </translation>
</message>
<message>
<location line="+23"/>
<source>The recipient address is not valid, please recheck.</source>
<translation>Het ontvangstadres is niet geldig, controleer uw invoer.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation>Het ingevoerde bedrag moet groter zijn dan 0.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation>Bedrag is hoger dan uw huidige saldo</translation>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation>Totaal overschrijdt uw huidige saldo wanneer de %1 transactiekosten worden meegerekend</translation>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation>Dubbel adres gevonden, u kunt slechts eenmaal naar een bepaald adres verzenden per verstuurtransactie</translation>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed!</source>
<translation>Fout: Aanmaak transactie mislukt!</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>Fout: De transactie was afgewezen. Dit kan gebeuren als u eerder uitgegeven munten opnieuw wilt versturen, zoals wanneer u een kopie van uw portemonneebestand (wallet.dat) heeft gebruikt en in de kopie deze munten zijn uitgegeven, maar in de huidige portemonnee deze nog niet als zodanig zijn gemarkeerd.</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation>Vorm</translation>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation>Bedra&g:</translation>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation>Betaal &Aan:</translation>
</message>
<message>
<location line="+34"/>
<source>The address to send the payment to (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Het adres waaraan u wilt betalen (bijv. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</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>Vul een label in voor dit adres om het toe te voegen aan uw adresboek</translation>
</message>
<message>
<location line="-78"/>
<source>&Label:</source>
<translation>&Label:</translation>
</message>
<message>
<location line="+28"/>
<source>Choose address from address book</source>
<translation>Kies adres uit adresboek</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>Plak adres vanuit klembord</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>Verwijder deze ontvanger</translation>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a TPPcoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Vul een TPPcoinadres in (bijv. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation>Handtekeningen - Onderteken een bericht / Verifiëer een handtekening</translation>
</message>
<message>
<location line="+13"/>
<source>&Sign Message</source>
<translation>O&nderteken Bericht</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>U kunt berichten ondertekenen met een van uw adressen om te bewijzen dat u dit adres bezit. Pas op dat u geen onduidelijke dingen ondertekent, want phishingaanvallen zouden u kunnen misleiden om zo uw identiteit te stelen. Onderteken alleen berichten waarmee u het volledig eens bent.</translation>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Het adres om het bericht mee te ondertekenen (Vb.: Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2).</translation>
</message>
<message>
<location line="+10"/>
<location line="+213"/>
<source>Choose an address from the address book</source>
<translation>Kies een adres uit het adresboek</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>Plak adres vanuit klembord</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>Typ hier het bericht dat u wilt ondertekenen</translation>
</message>
<message>
<location line="+7"/>
<source>Signature</source>
<translation>Handtekening</translation>
</message>
<message>
<location line="+27"/>
<source>Copy the current signature to the system clipboard</source>
<translation>Kopieer de huidige handtekening naar het systeemklembord</translation>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this TPPcoin address</source>
<translation>Onderteken een bericht om te bewijzen dat u een bepaald TPPcoinadres bezit</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>Onderteken &Bericht</translation>
</message>
<message>
<location line="+14"/>
<source>Reset all sign message fields</source>
<translation>Verwijder alles in de invulvelden</translation>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation>Verwijder &Alles</translation>
</message>
<message>
<location line="-87"/>
<source>&Verify Message</source>
<translation>&Verifiëer Bericht</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>Voer het ondertekenende adres, bericht en handtekening hieronder in (let erop dat u nieuwe regels, spaties en tabs juist overneemt) om de handtekening te verifiëren. Let erop dat u niet meer uit het bericht interpreteert dan er daadwerkelijk staat, om te voorkomen dat u wordt misleid in een man-in-the-middle-aanval.</translation>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Het adres waarmee bet bericht was ondertekend (Vb.: Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2).</translation>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified TPPcoin address</source>
<translation>Controleer een bericht om te verifiëren dat het gespecificeerde TPPcoinadres het bericht heeft ondertekend.</translation>
</message>
<message>
<location line="+3"/>
<source>Verify &Message</source>
<translation>Verifiëer &Bericht</translation>
</message>
<message>
<location line="+14"/>
<source>Reset all verify message fields</source>
<translation>Verwijder alles in de invulvelden</translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a TPPcoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Vul een TPPcoinadres in (bijv. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation>Klik "Onderteken Bericht" om de handtekening te genereren</translation>
</message>
<message>
<location line="+3"/>
<source>Enter TPPcoin signature</source>
<translation>Voer TPPcoin-handtekening in</translation>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation>Het opgegeven adres is ongeldig.</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>Controleer s.v.p. het adres en probeer het opnieuw.</translation>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation>Het opgegeven adres verwijst niet naar een sleutel.</translation>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation>Portemonnee-ontsleuteling is geannuleerd</translation>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation>Geheime sleutel voor het ingevoerde adres is niet beschikbaar.</translation>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation>Ondertekenen van het bericht is mislukt.</translation>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation>Bericht ondertekend.</translation>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation>De handtekening kon niet worden gedecodeerd.</translation>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation>Controleer s.v.p. de handtekening en probeer het opnieuw.</translation>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation>De handtekening hoort niet bij het bericht.</translation>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation>Berichtverificatie mislukt.</translation>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation>Bericht correct geverifiëerd.</translation>
</message>
</context>
<context>
<name>SplashScreen</name>
<message>
<location filename="../splashscreen.cpp" line="+22"/>
<source>The TPPcoin developers</source>
<translation>De TPPcoin-ontwikkelaars</translation>
</message>
<message>
<location line="+1"/>
<source>[testnet]</source>
<translation>[testnetwerk]</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+20"/>
<source>Open until %1</source>
<translation>Openen totdat %1</translation>
</message>
<message>
<location line="+6"/>
<source>%1/offline</source>
<translation>%1/offline</translation>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1/onbevestigd</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>%1 bevestigingen</translation>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation>Status</translation>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation><numerusform>, uitgezonden naar %n node</numerusform><numerusform>, uitgezonden naar %n nodes</numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>Datum</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation>Bron</translation>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation>Gegenereerd</translation>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation>Van</translation>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation>Aan</translation>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation>eigen adres</translation>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation>label</translation>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation>Credit</translation>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation><numerusform>komt tot wasdom na %n nieuw blok</numerusform><numerusform>komt tot wasdom na %n nieuwe blokken</numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation>niet geaccepteerd</translation>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation>Debet</translation>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation>Transactiekosten</translation>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation>Netto bedrag</translation>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation>Bericht</translation>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation>Opmerking</translation>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation>Transactie-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>Gegeneerde munten moeten 120 blokken wachten voordat ze tot wasdom komen en kunnen worden uitgegeven. Uw net gegenereerde blok is uitgezonden aan het netwerk om te worden toegevoegd aan de blokketen. Als het niet wordt geaccepteerd in de keten, zal het blok als "niet geaccepteerd" worden aangemerkt en kan het niet worden uitgegeven. Dit kan soms gebeuren als een andere node net iets sneller een blok heeft gegenereerd; een paar seconden voor het uwe.</translation>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation>Debug-informatie</translation>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation>Transactie</translation>
</message>
<message>
<location line="+3"/>
<source>Inputs</source>
<translation>Inputs</translation>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation>Bedrag</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation>waar</translation>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation>onwaar</translation>
</message>
<message>
<location line="-209"/>
<source>, has not been successfully broadcast yet</source>
<translation>, is nog niet met succes uitgezonden</translation>
</message>
<message numerus="yes">
<location line="-35"/>
<source>Open for %n more block(s)</source>
<translation><numerusform>Open voor nog %n blok</numerusform><numerusform>Open voor nog %n blokken</numerusform></translation>
</message>
<message>
<location line="+70"/>
<source>unknown</source>
<translation>onbekend</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>Transactiedetails</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>Dit venster laat een uitgebreide beschrijving van de transactie zien</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+225"/>
<source>Date</source>
<translation>Datum</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>Type</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Adres</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>Bedrag</translation>
</message>
<message numerus="yes">
<location line="+57"/>
<source>Open for %n more block(s)</source>
<translation><numerusform>Open voor nog %n blok</numerusform><numerusform>Open voor nog %n blokken</numerusform></translation>
</message>
<message>
<location line="+3"/>
<source>Open until %1</source>
<translation>Open tot %1</translation>
</message>
<message>
<location line="+3"/>
<source>Offline (%1 confirmations)</source>
<translation>Niet verbonden (%1 bevestigingen)</translation>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed (%1 of %2 confirmations)</source>
<translation>Onbevestigd (%1 van %2 bevestigd)</translation>
</message>
<message>
<location line="+3"/>
<source>Confirmed (%1 confirmations)</source>
<translation>Bevestigd (%1 bevestigingen)</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>Gedolven saldo zal beschikbaar komen als het tot wasdom komt na %n blok</numerusform><numerusform>Gedolven saldo zal beschikbaar komen als het tot wasdom komt na %n blokken</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>Dit blok is niet ontvangen bij andere nodes en zal waarschijnlijk niet worden geaccepteerd!</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>Gegenereerd maar niet geaccepteerd</translation>
</message>
<message>
<location line="+43"/>
<source>Received with</source>
<translation>Ontvangen met</translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation>Ontvangen van</translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>Verzonden aan</translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation>Betaling aan uzelf</translation>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation>Gedolven</translation>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation>(nvt)</translation>
</message>
<message>
<location line="+199"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>Transactiestatus. Houd de muiscursor boven dit veld om het aantal bevestigingen te laten zien.</translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>Datum en tijd waarop deze transactie is ontvangen.</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>Type transactie.</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>Ontvangend adres van transactie.</translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>Bedrag verwijderd van of toegevoegd aan saldo</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+52"/>
<location line="+16"/>
<source>All</source>
<translation>Alles</translation>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation>Vandaag</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation>Deze week</translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation>Deze maand</translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation>Vorige maand</translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation>Dit jaar</translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation>Bereik...</translation>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation>Ontvangen met</translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>Verzonden aan</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>Aan uzelf</translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation>Gedolven</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation>Anders</translation>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation>Vul adres of label in om te zoeken</translation>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation>Min. bedrag</translation>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation>Kopieer adres</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Kopieer label</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Kopieer bedrag</translation>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation>Kopieer transactie-ID</translation>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation>Bewerk label</translation>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation>Toon transactiedetails</translation>
</message>
<message>
<location line="+139"/>
<source>Export Transaction Data</source>
<translation>Exporteer transactiegegevens</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Kommagescheiden bestand (*.csv)</translation>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation>Bevestigd</translation>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>Datum</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>Type</translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>Label</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>Adres</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation>Bedrag</translation>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation>ID</translation>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation>Fout bij exporteren</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Kon niet schrijven naar bestand %1.</translation>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation>Bereik:</translation>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation>naar</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+193"/>
<source>Send Coins</source>
<translation>Verstuur munten</translation>
</message>
</context>
<context>
<name>WalletView</name>
<message>
<location filename="../walletview.cpp" line="+42"/>
<source>&Export</source>
<translation>&Exporteer</translation>
</message>
<message>
<location line="+1"/>
<source>Export the data in the current tab to a file</source>
<translation>Exporteer de data in de huidige tab naar een bestand</translation>
</message>
<message>
<location line="+193"/>
<source>Backup Wallet</source>
<translation>Portomonnee backuppen</translation>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation>Portemonnee-data (*.dat)</translation>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation>Backup Mislukt</translation>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation>Er is een fout opgetreden bij het wegschrijven van de portemonnee-data naar de nieuwe locatie.</translation>
</message>
<message>
<location line="+4"/>
<source>Backup Successful</source>
<translation>Backup Succesvol</translation>
</message>
<message>
<location line="+0"/>
<source>The wallet data was successfully saved to the new location.</source>
<translation>De portemonneedata is succesvol opgeslagen op de nieuwe locatie.</translation>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+94"/>
<source>TPPcoin version</source>
<translation>TPPcoinversie</translation>
</message>
<message>
<location line="+102"/>
<source>Usage:</source>
<translation>Gebruik:</translation>
</message>
<message>
<location line="-29"/>
<source>Send command to -server or tppcoind</source>
<translation>Stuur commando naar -server of tppcoind</translation>
</message>
<message>
<location line="-23"/>
<source>List commands</source>
<translation>Lijst van commando's</translation>
</message>
<message>
<location line="-12"/>
<source>Get help for a command</source>
<translation>Toon hulp voor een commando</translation>
</message>
<message>
<location line="+24"/>
<source>Options:</source>
<translation>Opties:</translation>
</message>
<message>
<location line="+24"/>
<source>Specify configuration file (default: tppcoin.conf)</source>
<translation>Specificeer configuratiebestand (standaard: tppcoin.conf)
</translation>
</message>
<message>
<location line="+3"/>
<source>Specify pid file (default: tppcoind.pid)</source>
<translation>Specificeer pid-bestand (standaard: tppcoind.pid)
</translation>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation>Stel datamap in</translation>
</message>
<message>
<location line="-9"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation>Stel databankcachegrootte in in megabytes (standaard: 25)</translation>
</message>
<message>
<location line="-28"/>
<source>Listen for connections on <port> (default: 9333 or testnet: 19333)</source>
<translation>Luister voor verbindingen op <poort> (standaard: 9333 of testnet: 19333)</translation>
</message>
<message>
<location line="+5"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>Onderhoud maximaal <n> verbindingen naar peers (standaard: 125)</translation>
</message>
<message>
<location line="-48"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation>Verbind naar een node om adressen van anderen op te halen, en verbreek vervolgens de verbinding</translation>
</message>
<message>
<location line="+82"/>
<source>Specify your own public address</source>
<translation>Specificeer uw eigen publieke adres</translation>
</message>
<message>
<location line="+3"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation>Drempel om verbinding te verbreken naar zich misdragende peers (standaard: 100)</translation>
</message>
<message>
<location line="-134"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation>Aantal seconden dat zich misdragende peers niet opnieuw mogen verbinden (standaard: 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>Er is een fout opgetreden tijdens het instellen van de inkomende RPC-poort %u op IPv4: %s</translation>
</message>
<message>
<location line="+27"/>
<source>Listen for JSON-RPC connections on <port> (default: 9332 or testnet: 19332)</source>
<translation>Wacht op JSON-RPC-connecties op poort <port> (standaard: 9332 of testnet: 19332)</translation>
</message>
<message>
<location line="+37"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>Aanvaard commandoregel- en JSON-RPC-commando's</translation>
</message>
<message>
<location line="+76"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>Draai in de achtergrond als daemon en aanvaard commando's</translation>
</message>
<message>
<location line="+37"/>
<source>Use the test network</source>
<translation>Gebruik het testnetwerk</translation>
</message>
<message>
<location line="-112"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation>Accepteer verbindingen van buitenaf (standaard: 1 als geen -proxy of -connect is opgegeven)</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=tppcoinrpc
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 "TPPcoin Alert" admin@foo.com
</source>
<translation>%s, u moet een RPC-wachtwoord instellen in het configuratiebestand: %s
U wordt aangeraden het volgende willekeurige wachtwoord te gebruiken:
rpcuser=tppcoinrpc
rpcpassword=%s
(u hoeft dit wachtwoord niet te onthouden)
De gebruikersnaam en wachtwoord mogen niet hetzelfde zijn.
Als het bestand niet bestaat, make hem dan aan met leesrechten voor enkel de eigenaar.
Het is ook aan te bevelen "alertnotify" in te stellen zodat u op de hoogte gesteld wordt van problemen;
for example: alertnotify=echo %%s | mail -s "TPPcoin 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>Er is een fout opgetreden tijdens het instellen van de inkomende RPC-poort %u op IPv6, terugval naar 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>Bind aan opgegeven adres en luister er altijd op. Gebruik [host]:port notatie voor IPv6</translation>
</message>
<message>
<location line="+3"/>
<source>Cannot obtain a lock on data directory %s. TPPcoin is probably already running.</source>
<translation>Kan geen lock op de datamap %s verkrijgen. TPPcoin draait vermoedelijk reeds.</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>Fout: De transactie was afgewezen! Dit kan gebeuren als sommige munten in uw portemonnee al eerder uitgegeven zijn, zoals wanneer u een kopie van uw wallet.dat heeft gebruikt en in de kopie deze munten zijn uitgegeven, maar in deze portemonnee die munten nog niet als zodanig zijn gemarkeerd.</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>Fout: Deze transactie vereist transactiekosten van tenminste %s, vanwege zijn grootte, complexiteit, of het gebruik van onlangs ontvangen munten!</translation>
</message>
<message>
<location line="+3"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation>Voer opdracht uit zodra een relevante melding ontvangen is (%s wordt in cmd vervangen door het bericht)</translation>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation>Voer opdracht uit zodra een portemonneetransactie verandert (%s in cmd wordt vervangen door TxID)</translation>
</message>
<message>
<location line="+11"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation>Stel maximumgrootte in in bytes voor hoge-prioriteits-/lage-transactiekosten-transacties (standaard: 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>Dit is een pre-release testversie - gebruik op eigen risico! Gebruik deze niet voor het delven van munten of handelsdoeleinden</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>Waarschuwing: -paytxfee is zeer hoog ingesteld. Dit zijn de transactiekosten die u betaalt bij het versturen van een transactie.</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>Waarschuwing: Weergegeven transacties zijn mogelijk niet correct! Mogelijk dient u te upgraden, of andere nodes dienen te upgraden.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong TPPcoin will not work properly.</source>
<translation>Waarschuwing: Controleer dat de datum en tijd op uw computer correct zijn ingesteld. Als uw klok fout staat zal TPPcoin niet correct werken.</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>Waarschuwing: Fout bij het lezen van wallet.dat! Alle sleutels zijn in goede orde uitgelezen, maar transactiedata of adresboeklemma's zouden kunnen ontbreken of fouten bevatten.</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>Waarschuwing: wallet.dat is corrupt, data is veiliggesteld! Originele wallet.dat is opgeslagen als wallet.{tijdstip}.bak in %s; als uw balans of transacties incorrect zijn dient u een backup terug te zetten.</translation>
</message>
<message>
<location line="+14"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation>Poog de geheime sleutels uit een corrupt wallet.dat bestand terug te halen</translation>
</message>
<message>
<location line="+2"/>
<source>Block creation options:</source>
<translation>Blokcreatie-opties:</translation>
</message>
<message>
<location line="+5"/>
<source>Connect only to the specified node(s)</source>
<translation>Verbind alleen naar de gespecificeerde node(s)</translation>
</message>
<message>
<location line="+3"/>
<source>Corrupted block database detected</source>
<translation>Corrupte blokkendatabase gedetecteerd</translation>
</message>
<message>
<location line="+1"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation>Ontdek eigen IP-adres (standaard: 1 als er wordt geluisterd en geen -externalip is opgegeven)</translation>
</message>
<message>
<location line="+1"/>
<source>Do you want to rebuild the block database now?</source>
<translation>Wilt u de blokkendatabase nu herbouwen?</translation>
</message>
<message>
<location line="+2"/>
<source>Error initializing block database</source>
<translation>Fout bij intialisatie blokkendatabase</translation>
</message>
<message>
<location line="+1"/>
<source>Error initializing wallet database environment %s!</source>
<translation>Probleem met initializeren van de database-omgeving %s!</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading block database</source>
<translation>Fout bij het laden van blokkendatabase</translation>
</message>
<message>
<location line="+4"/>
<source>Error opening block database</source>
<translation>Fout bij openen blokkendatabase</translation>
</message>
<message>
<location line="+2"/>
<source>Error: Disk space is low!</source>
<translation>Fout: Weinig vrije diskruimte!</translation>
</message>
<message>
<location line="+1"/>
<source>Error: Wallet locked, unable to create transaction!</source>
<translation>Fout: Portemonnee vergrendeld, aanmaak transactie niet mogelijk!</translation>
</message>
<message>
<location line="+1"/>
<source>Error: system error: </source>
<translation>Fout: Systeemfout:</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation>Mislukt om op welke poort dan ook te luisteren. Gebruik -listen=0 as u dit wilt.</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to read block info</source>
<translation>Lezen van blokinformatie mislukt</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to read block</source>
<translation>Lezen van blok mislukt</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to sync block index</source>
<translation>Synchroniseren van blokindex mislukt</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write block index</source>
<translation>Schrijven van blokindex mislukt</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write block info</source>
<translation>Schrijven van blokinformatie mislukt</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write block</source>
<translation>Schrijven van blok mislukt</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write file info</source>
<translation>Schrijven van bestandsinformatie mislukt</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write to coin database</source>
<translation>Schrijven naar coindatabase mislukt</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write transaction index</source>
<translation>Schrijven van transactieindex mislukt</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write undo data</source>
<translation>Schrijven van undo-data mislukt</translation>
</message>
<message>
<location line="+2"/>
<source>Find peers using DNS lookup (default: 1 unless -connect)</source>
<translation>Vind andere nodes d.m.v. DNS-naslag (standaard: 1 tenzij -connect)</translation>
</message>
<message>
<location line="+1"/>
<source>Generate coins (default: 0)</source>
<translation>Genereer munten (standaard: 0)</translation>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 288, 0 = all)</source>
<translation>Aantal te checken blokken bij het opstarten (standaard: 288, 0 = allemaal)</translation>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-4, default: 3)</source>
<translation>Hoe grondig de blokverificatie is (0-4, standaard: 3)</translation>
</message>
<message>
<location line="+19"/>
<source>Not enough file descriptors available.</source>
<translation>Niet genoeg file descriptors beschikbaar.</translation>
</message>
<message>
<location line="+8"/>
<source>Rebuild block chain index from current blk000??.dat files</source>
<translation>Blokketen opnieuw opbouwen van huidige blk000??.dat-bestanden</translation>
</message>
<message>
<location line="+16"/>
<source>Set the number of threads to service RPC calls (default: 4)</source>
<translation>Stel het aantal threads in om RPC-aanvragen mee te bedienen (standaard: 4)</translation>
</message>
<message>
<location line="+26"/>
<source>Verifying blocks...</source>
<translation>Blokken aan het controleren...</translation>
</message>
<message>
<location line="+1"/>
<source>Verifying wallet...</source>
<translation>Portomonnee aan het controleren...</translation>
</message>
<message>
<location line="-69"/>
<source>Imports blocks from external blk000??.dat file</source>
<translation>Importeert blokken van extern blk000??.dat bestand</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>Stel het aantal threads voor scriptverificatie in (max 16, 0 = auto, <0 = laat zoveel cores vrij, standaard: 0)</translation>
</message>
<message>
<location line="+77"/>
<source>Information</source>
<translation>Informatie</translation>
</message>
<message>
<location line="+3"/>
<source>Invalid -tor address: '%s'</source>
<translation>Ongeldig -tor adres: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -minrelaytxfee=<amount>: '%s'</source>
<translation>Ongeldig bedrag voor -minrelaytxfee=<bedrag>: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -mintxfee=<amount>: '%s'</source>
<translation>Ongeldig bedrag voor -mintxfee=<bedrag>: '%s'</translation>
</message>
<message>
<location line="+8"/>
<source>Maintain a full transaction index (default: 0)</source>
<translation>Onderhoud een volledige transactieindex (standaard: 0)</translation>
</message>
<message>
<location line="+2"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation>Maximum per-connectie ontvangstbuffer, <n>*1000 bytes (standaard: 5000)</translation>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation>Maximum per-connectie zendbuffer, <n>*1000 bytes (standaard: 1000)</translation>
</message>
<message>
<location line="+2"/>
<source>Only accept block chain matching built-in checkpoints (default: 1)</source>
<translation>Accepteer alleen blokketen die overeenkomt met de ingebouwde checkpoints (standaard: 1)</translation>
</message>
<message>
<location line="+1"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation>Verbind alleen naar nodes in netwerk <net> (IPv4, IPv6 of Tor)</translation>
</message>
<message>
<location line="+2"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation>Output extra debugginginformatie. Impliceert alle andere -debug* opties</translation>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation>Output extra netwerk-debugginginformatie</translation>
</message>
<message>
<location line="+2"/>
<source>Prepend debug output with timestamp</source>
<translation>Voorzie de debuggingsuitvoer van een tijdsaanduiding</translation>
</message>
<message>
<location line="+5"/>
<source>SSL options: (see the TPPcoin Wiki for SSL setup instructions)</source>
<translation>SSL-opties: (zie de TPPcoin wiki voor SSL-instructies)</translation>
</message>
<message>
<location line="+1"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation>Selecteer de versie van de SOCKS-proxy om te gebruiken (4 of 5, standaard is 5)</translation>
</message>
<message>
<location line="+3"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>Stuur trace/debug-info naar de console in plaats van het debug.log bestand</translation>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation>Stuur trace/debug-info naar debugger</translation>
</message>
<message>
<location line="+5"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation>Stel maximum blokgrootte in in bytes (standaard: 250000)</translation>
</message>
<message>
<location line="+1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation>Stel minimum blokgrootte in in bytes (standaard: 0)</translation>
</message>
<message>
<location line="+2"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation>Verklein debug.log-bestand bij het opstarten van de client (standaard: 1 als geen -debug)</translation>
</message>
<message>
<location line="+1"/>
<source>Signing transaction failed</source>
<translation>Ondertekenen van transactie mislukt</translation>
</message>
<message>
<location line="+2"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation>Specificeer de time-outtijd in milliseconden (standaard: 5000)</translation>
</message>
<message>
<location line="+4"/>
<source>System error: </source>
<translation>Systeemfout:</translation>
</message>
<message>
<location line="+4"/>
<source>Transaction amount too small</source>
<translation>Transactiebedrag te klein</translation>
</message>
<message>
<location line="+1"/>
<source>Transaction amounts must be positive</source>
<translation>Transactiebedragen moeten positief zijn</translation>
</message>
<message>
<location line="+1"/>
<source>Transaction too large</source>
<translation>Transactie te groot</translation>
</message>
<message>
<location line="+7"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation>Gebruik UPnP om de luisterende poort te mappen (standaard: 0)</translation>
</message>
<message>
<location line="+1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation>Gebruik UPnP om de luisterende poort te mappen (standaard: 1 als er wordt geluisterd)</translation>
</message>
<message>
<location line="+1"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation>Gebruik proxy om 'tor hidden services' te bereiken (standaard: hetzelfde als -proxy)</translation>
</message>
<message>
<location line="+2"/>
<source>Username for JSON-RPC connections</source>
<translation>Gebruikersnaam voor JSON-RPC-verbindingen</translation>
</message>
<message>
<location line="+4"/>
<source>Warning</source>
<translation>Waarschuwing</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation>Waarschuwing: Deze versie is verouderd, een upgrade is vereist!</translation>
</message>
<message>
<location line="+1"/>
<source>You need to rebuild the databases using -reindex to change -txindex</source>
<translation>U moet de databases herbouwen met behulp van -reindex om -txindex te kunnen veranderen</translation>
</message>
<message>
<location line="+1"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation>wallet.dat corrupt, veiligstellen mislukt</translation>
</message>
<message>
<location line="-50"/>
<source>Password for JSON-RPC connections</source>
<translation>Wachtwoord voor JSON-RPC-verbindingen</translation>
</message>
<message>
<location line="-67"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>Sta JSON-RPC verbindingen van opgegeven IP-adres toe</translation>
</message>
<message>
<location line="+76"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>Verstuur commando's naar proces dat op <ip> draait (standaard: 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>Voer commando uit zodra het beste blok verandert (%s in cmd wordt vervangen door blockhash)</translation>
</message>
<message>
<location line="+147"/>
<source>Upgrade wallet to latest format</source>
<translation>Vernieuw portemonnee naar nieuwste versie</translation>
</message>
<message>
<location line="-21"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>Stel sleutelpoelgrootte in op <n> (standaard: 100)</translation>
</message>
<message>
<location line="-12"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>Doorzoek de blokketen op ontbrekende portemonnee-transacties</translation>
</message>
<message>
<location line="+35"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>Gebruik OpenSSL (https) voor JSON-RPC-verbindingen</translation>
</message>
<message>
<location line="-26"/>
<source>Server certificate file (default: server.cert)</source>
<translation>Certificaat-bestand voor server (standaard: server.cert)</translation>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation>Geheime sleutel voor server (standaard: server.pem)</translation>
</message>
<message>
<location line="-151"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation>Aanvaardbare ciphers (standaard: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation>
</message>
<message>
<location line="+165"/>
<source>This help message</source>
<translation>Dit helpbericht</translation>
</message>
<message>
<location line="+6"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation>Niet in staat om aan %s te binden op deze computer (bind gaf error %d, %s)</translation>
</message>
<message>
<location line="-91"/>
<source>Connect through socks proxy</source>
<translation>Verbind via een socks-proxy</translation>
</message>
<message>
<location line="-10"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation>Sta DNS-naslag toe voor -addnode, -seednode en -connect</translation>
</message>
<message>
<location line="+55"/>
<source>Loading addresses...</source>
<translation>Adressen aan het laden...</translation>
</message>
<message>
<location line="-35"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>Fout bij laden wallet.dat: Portemonnee corrupt</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat: Wallet requires newer version of TPPcoin</source>
<translation>Fout bij laden wallet.dat: Portemonnee vereist een nieuwere versie van TPPcoin</translation>
</message>
<message>
<location line="+93"/>
<source>Wallet needed to be rewritten: restart TPPcoin to complete</source>
<translation>Portemonnee moest herschreven worden: Herstart TPPcoin om te voltooien</translation>
</message>
<message>
<location line="-95"/>
<source>Error loading wallet.dat</source>
<translation>Fout bij laden wallet.dat</translation>
</message>
<message>
<location line="+28"/>
<source>Invalid -proxy address: '%s'</source>
<translation>Ongeldig -proxy adres: '%s'</translation>
</message>
<message>
<location line="+56"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation>Onbekend netwerk gespecificeerd in -onlynet: '%s'</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation>Onbekende -socks proxyversie aangegeven: %i</translation>
</message>
<message>
<location line="-96"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation>Kan -bind adres niet herleiden: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation>Kan -externlip adres niet herleiden: '%s'</translation>
</message>
<message>
<location line="+44"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation>Ongeldig bedrag voor -paytxfee=<bedrag>: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount</source>
<translation>Ongeldig bedrag</translation>
</message>
<message>
<location line="-6"/>
<source>Insufficient funds</source>
<translation>Ontoereikend saldo</translation>
</message>
<message>
<location line="+10"/>
<source>Loading block index...</source>
<translation>Blokindex aan het laden...</translation>
</message>
<message>
<location line="-57"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>Voeg een node om naar te verbinden toe en probeer de verbinding open te houden</translation>
</message>
<message>
<location line="-25"/>
<source>Unable to bind to %s on this computer. TPPcoin is probably already running.</source>
<translation>Niet in staat om aan %s te binden op deze computer. TPPcoin draait vermoedelijk reeds.</translation>
</message>
<message>
<location line="+64"/>
<source>Fee per KB to add to transactions you send</source>
<translation>Kosten per KB om aan transacties toe te voegen die u verstuurt</translation>
</message>
<message>
<location line="+19"/>
<source>Loading wallet...</source>
<translation>Portemonnee aan het laden...</translation>
</message>
<message>
<location line="-52"/>
<source>Cannot downgrade wallet</source>
<translation>Kan portemonnee niet downgraden</translation>
</message>
<message>
<location line="+3"/>
<source>Cannot write default address</source>
<translation>Kan standaardadres niet schrijven</translation>
</message>
<message>
<location line="+64"/>
<source>Rescanning...</source>
<translation>Blokketen aan het doorzoeken...</translation>
</message>
<message>
<location line="-57"/>
<source>Done loading</source>
<translation>Klaar met laden</translation>
</message>
<message>
<location line="+82"/>
<source>To use the %s option</source>
<translation>Om de %s optie te gebruiken</translation>
</message>
<message>
<location line="-74"/>
<source>Error</source>
<translation>Fout</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>U dient rpcpassword=<wachtwoord> in te stellen in het configuratiebestand:
%s
Als het bestand niet bestaat, maak het dan aan, met een alleen-lezen-permissie.</translation>
</message>
</context>
</TS> | tppcoin/tppcoin | src/qt/locale/bitcoin_nl.ts | TypeScript | mit | 118,342 |
"""
Django settings for ProgrammerCompetencyMatrix project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '^k(h30rq(chrdd0y2)327we@uh@nat3d*^8f1l--4t0bxo9_nm'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'survey',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'ProgrammerCompetencyMatrix.urls'
WSGI_APPLICATION = 'ProgrammerCompetencyMatrix.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static').replace(os.sep, '/'),
)
# BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))
#logging.warning(TEMPLATE_DIR)
TEMPLATE_DIRS = (
# os.path.join(BASE_DIR, '../../templates/'),
os.path.join(BASE_DIR, 'templates').replace(os.sep, '/'),
# 'D:/Java/Project/GettingStartBlog/templates/'
)
| FiaDot/programmer-competency-matrix | ProgrammerCompetencyMatrix/settings.py | Python | mit | 2,486 |
require 'test_helper'
module Cms
class CategoriesHelperTest < ActionView::TestCase
end
end
| dreamyourweb/dyw-cms | test/unit/helpers/cms/categories_helper_test.rb | Ruby | mit | 96 |
angular.module('backAnd.services')
.constant('CONSTANTS', {
URL: "https://api.backand.com",
DEFAULT_APP: null,
VERSION : '0.1'
}); | backand/angularbknd | app/backand/js/services/constants.js | JavaScript | mit | 162 |
class CommentsController < ApplicationController
before_action :set_comment, only: [:show, :update, :destroy]
def index
render json: { comments: Comment.all }, methods: :post_id
end
def show
render json: { comment: @comment }, methods: :post_id
end
def create
@comment = Comment.new(comment_params)
if @comment.save
render json: { comment: @comment }, methods: :post_id, status: :created, location: @comment
else
render json: @comment.errors, status: :unprocessable_entity
end
end
def destroy
@comment.destroy
head :no_content
end
private
def set_comment
@comment = Comment.find(params[:id])
end
def comment_params
params.require(:comment).permit(:author, :body, :post_id)
end
end
| brunoocasali/ember-n-rails | blog-backend/app/controllers/comments_controller.rb | Ruby | mit | 769 |
const JSUnit = imports.jsUnit;
const Cairo = imports.cairo;
const Everything = imports.gi.Regress;
function _ts(obj) {
return obj.toString().slice(8, -1);
}
function _createSurface() {
return new Cairo.ImageSurface(Cairo.Format.ARGB32, 1, 1);
}
function _createContext() {
return new Cairo.Context(_createSurface());
}
function testContext() {
let cr = _createContext();
JSUnit.assertTrue(cr instanceof Cairo.Context);
}
function testContextMethods() {
let cr = _createContext();
JSUnit.assertTrue(cr instanceof Cairo.Context);
cr.save();
cr.restore();
let surface = _createSurface();
JSUnit.assertEquals(_ts(cr.getTarget()), "CairoImageSurface");
let pattern = Cairo.SolidPattern.createRGB(1, 2, 3);
cr.setSource(pattern);
JSUnit.assertEquals(_ts(cr.getSource()), "CairoSolidPattern");
cr.setSourceSurface(surface, 0, 0);
cr.pushGroup();
cr.popGroup();
cr.pushGroupWithContent(Cairo.Content.COLOR);
cr.popGroupToSource();
cr.setSourceRGB(1, 2, 3);
cr.setSourceRGBA(1, 2, 3, 4);
cr.setAntialias(Cairo.Antialias.NONE);
JSUnit.assertEquals("antialias", cr.getAntialias(), Cairo.Antialias.NONE);
cr.setFillRule(Cairo.FillRule.EVEN_ODD);
JSUnit.assertEquals("fillRule", cr.getFillRule(), Cairo.FillRule.EVEN_ODD);
cr.setLineCap(Cairo.LineCap.ROUND);
JSUnit.assertEquals("lineCap", cr.getLineCap(), Cairo.LineCap.ROUND);
cr.setLineJoin(Cairo.LineJoin.ROUND);
JSUnit.assertEquals("lineJoin", cr.getLineJoin(), Cairo.LineJoin.ROUND);
cr.setLineWidth(1138);
JSUnit.assertEquals("lineWidth", cr.getLineWidth(), 1138);
cr.setMiterLimit(42);
JSUnit.assertEquals("miterLimit", cr.getMiterLimit(), 42);
cr.setOperator(Cairo.Operator.IN);
JSUnit.assertEquals("operator", cr.getOperator(), Cairo.Operator.IN);
cr.setTolerance(144);
JSUnit.assertEquals("tolerance", cr.getTolerance(), 144);
cr.clip();
cr.clipPreserve();
let rv = cr.clipExtents();
JSUnit.assertEquals("clipExtents", rv.length, 4);
cr.fill();
cr.fillPreserve();
let rv = cr.fillExtents();
JSUnit.assertEquals("fillExtents", rv.length, 4);
cr.mask(pattern);
cr.maskSurface(surface, 0, 0);
cr.paint();
cr.paintWithAlpha(1);
cr.stroke();
cr.strokePreserve();
let rv = cr.strokeExtents();
JSUnit.assertEquals("strokeExtents", rv.length, 4);
cr.inFill(0, 0);
cr.inStroke(0, 0);
cr.copyPage();
cr.showPage();
let dc = cr.getDashCount();
JSUnit.assertEquals("dashCount", dc, 0);
cr.translate(10, 10);
cr.scale(10, 10);
cr.rotate(180);
cr.identityMatrix();
let rv = cr.userToDevice(0, 0);
JSUnit.assertEquals("userToDevice", rv.length, 2);
let rv = cr.userToDeviceDistance(0, 0);
JSUnit.assertEquals("userToDeviceDistance", rv.length, 2);
let rv = cr.deviceToUser(0, 0);
JSUnit.assertEquals("deviceToUser", rv.length, 2);
let rv = cr.deviceToUserDistance(0, 0);
JSUnit.assertEquals("deviceToUserDistance", rv.length, 2);
cr.showText("foobar");
cr.moveTo(0, 0);
cr.setDash([1, 0.5], 1);
cr.lineTo(1, 0);
cr.lineTo(1, 1);
cr.lineTo(0, 1);
cr.closePath();
let path = cr.copyPath();
cr.fill();
cr.appendPath(path);
cr.stroke();
}
function testSolidPattern() {
let cr = _createContext();
let p1 = Cairo.SolidPattern.createRGB(1, 2, 3);
JSUnit.assertEquals(_ts(p1), "CairoSolidPattern");
cr.setSource(p1);
JSUnit.assertEquals(_ts(cr.getSource()), "CairoSolidPattern");
let p2 = Cairo.SolidPattern.createRGBA(1, 2, 3, 4);
JSUnit.assertEquals(_ts(p2), "CairoSolidPattern");
cr.setSource(p2);
JSUnit.assertEquals(_ts(cr.getSource()), "CairoSolidPattern");
}
function testSurfacePattern() {
let cr = _createContext();
let surface = _createSurface();
let p1 = new Cairo.SurfacePattern(surface);
JSUnit.assertEquals(_ts(p1), "CairoSurfacePattern");
cr.setSource(p1);
JSUnit.assertEquals(_ts(cr.getSource()), "CairoSurfacePattern");
}
function testLinearGradient() {
let cr = _createContext();
let surface = _createSurface();
let p1 = new Cairo.LinearGradient(1, 2, 3, 4);
JSUnit.assertEquals(_ts(p1), "CairoLinearGradient");
cr.setSource(p1);
JSUnit.assertEquals(_ts(cr.getSource()), "CairoLinearGradient");
}
function testRadialGradient() {
let cr = _createContext();
let surface = _createSurface();
let p1 = new Cairo.RadialGradient(1, 2, 3, 4, 5, 6);
JSUnit.assertEquals(_ts(p1), "CairoRadialGradient");
cr.setSource(p1);
JSUnit.assertEquals(_ts(cr.getSource()), "CairoRadialGradient");
}
function testCairoSignal() {
let o = new Everything.TestObj();
let called = false;
o.connect('sig-with-foreign-struct', function(o, cr) {
called = true;
JSUnit.assertEquals(_ts(cr), "CairoContext");
});
o.emit_sig_with_foreign_struct();
JSUnit.assertTrue(called);
}
JSUnit.gwkjstestRun(this, JSUnit.setUp, JSUnit.tearDown);
| danilocesar/gwkjs | installed-tests/js/testCairo.js | JavaScript | mit | 5,061 |
package org.testcontainers.dockerclient;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.core.DockerClientBuilder;
import com.github.dockerjava.core.DockerClientConfig;
import com.github.dockerjava.netty.NettyDockerCmdExecFactory;
import com.google.common.base.Throwables;
import org.apache.commons.io.IOUtils;
import org.jetbrains.annotations.Nullable;
import org.rnorth.ducttape.TimeoutException;
import org.rnorth.ducttape.ratelimits.RateLimiter;
import org.rnorth.ducttape.ratelimits.RateLimiterBuilder;
import org.rnorth.ducttape.unreliables.Unreliables;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testcontainers.utility.TestcontainersConfiguration;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Stream;
/**
* Mechanism to find a viable Docker client configuration according to the host system environment.
*/
public abstract class DockerClientProviderStrategy {
protected DockerClient client;
protected DockerClientConfig config;
private static final RateLimiter PING_RATE_LIMITER = RateLimiterBuilder.newBuilder()
.withRate(2, TimeUnit.SECONDS)
.withConstantThroughput()
.build();
private static final AtomicBoolean FAIL_FAST_ALWAYS = new AtomicBoolean(false);
/**
* @throws InvalidConfigurationException if this strategy fails
*/
public abstract void test() throws InvalidConfigurationException;
/**
* @return a short textual description of the strategy
*/
public abstract String getDescription();
protected boolean isApplicable() {
return true;
}
protected boolean isPersistable() {
return true;
}
/**
* @return highest to lowest priority value
*/
protected int getPriority() {
return 0;
}
protected static final Logger LOGGER = LoggerFactory.getLogger(DockerClientProviderStrategy.class);
/**
* Determine the right DockerClientConfig to use for building clients by trial-and-error.
*
* @return a working DockerClientConfig, as determined by successful execution of a ping command
*/
public static DockerClientProviderStrategy getFirstValidStrategy(List<DockerClientProviderStrategy> strategies) {
if (FAIL_FAST_ALWAYS.get()) {
throw new IllegalStateException("Previous attempts to find a Docker environment failed. Will not retry. Please see logs and check configuration");
}
List<String> configurationFailures = new ArrayList<>();
return Stream
.concat(
Stream
.of(TestcontainersConfiguration.getInstance().getDockerClientStrategyClassName())
.filter(Objects::nonNull)
.flatMap(it -> {
try {
Class<? extends DockerClientProviderStrategy> strategyClass = (Class) Thread.currentThread().getContextClassLoader().loadClass(it);
return Stream.of(strategyClass.newInstance());
} catch (ClassNotFoundException e) {
LOGGER.warn("Can't instantiate a strategy from {} (ClassNotFoundException). " +
"This probably means that cached configuration refers to a client provider " +
"class that is not available in this version of Testcontainers. Other " +
"strategies will be tried instead.", it);
return Stream.empty();
} catch (InstantiationException | IllegalAccessException e) {
LOGGER.warn("Can't instantiate a strategy from {}", it, e);
return Stream.empty();
}
})
// Ignore persisted strategy if it's not persistable anymore
.filter(DockerClientProviderStrategy::isPersistable)
.peek(strategy -> LOGGER.info("Loaded {} from ~/.testcontainers.properties, will try it first", strategy.getClass().getName())),
strategies
.stream()
.filter(DockerClientProviderStrategy::isApplicable)
.sorted(Comparator.comparing(DockerClientProviderStrategy::getPriority).reversed())
)
.flatMap(strategy -> {
try {
strategy.test();
LOGGER.info("Found Docker environment with {}", strategy.getDescription());
if (strategy.isPersistable()) {
TestcontainersConfiguration.getInstance().updateGlobalConfig("docker.client.strategy", strategy.getClass().getName());
}
return Stream.of(strategy);
} catch (Exception | ExceptionInInitializerError | NoClassDefFoundError e) {
@Nullable String throwableMessage = e.getMessage();
@SuppressWarnings("ThrowableResultOfMethodCallIgnored")
Throwable rootCause = Throwables.getRootCause(e);
@Nullable String rootCauseMessage = rootCause.getMessage();
String failureDescription;
if (throwableMessage != null && throwableMessage.equals(rootCauseMessage)) {
failureDescription = String.format("%s: failed with exception %s (%s)",
strategy.getClass().getSimpleName(),
e.getClass().getSimpleName(),
throwableMessage);
} else {
failureDescription = String.format("%s: failed with exception %s (%s). Root cause %s (%s)",
strategy.getClass().getSimpleName(),
e.getClass().getSimpleName(),
throwableMessage,
rootCause.getClass().getSimpleName(),
rootCauseMessage
);
}
configurationFailures.add(failureDescription);
LOGGER.debug(failureDescription);
return Stream.empty();
}
})
.findAny()
.orElseThrow(() -> {
LOGGER.error("Could not find a valid Docker environment. Please check configuration. Attempted configurations were:");
for (String failureMessage : configurationFailures) {
LOGGER.error(" " + failureMessage);
}
LOGGER.error("As no valid configuration was found, execution cannot continue");
FAIL_FAST_ALWAYS.set(true);
return new IllegalStateException("Could not find a valid Docker environment. Please see logs and check configuration");
});
}
/**
* @return a usable, tested, Docker client configuration for the host system environment
*/
public DockerClient getClient() {
return new AuditLoggingDockerClient(client);
}
protected DockerClient getClientForConfig(DockerClientConfig config) {
return DockerClientBuilder
.getInstance(config)
.withDockerCmdExecFactory(new NettyDockerCmdExecFactory())
.build();
}
protected void ping(DockerClient client, int timeoutInSeconds) {
try {
Unreliables.retryUntilSuccess(timeoutInSeconds, TimeUnit.SECONDS, () -> {
return PING_RATE_LIMITER.getWhenReady(() -> {
LOGGER.debug("Pinging docker daemon...");
client.pingCmd().exec();
return true;
});
});
} catch (TimeoutException e) {
IOUtils.closeQuietly(client);
throw e;
}
}
public String getDockerHostIpAddress() {
return DockerClientConfigUtils.getDockerHostIpAddress(this.config);
}
}
| barrycommins/testcontainers-java | core/src/main/java/org/testcontainers/dockerclient/DockerClientProviderStrategy.java | Java | mit | 8,768 |
package pass.core.scheduling.distributed;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
import pass.core.scheduling.TaskSpecification;
public class Job implements Serializable
{
private static final Logger LOGGER = Logger.getLogger(Job.class.getName());
private final UUID taskId;
private final TaskSpecification taskSpec;
public Job(UUID taskId, TaskSpecification taskSpec)
{
this.taskId = taskId;
this.taskSpec = taskSpec;
}
public UUID getTaskId()
{
return taskId;
}
public TaskSpecification getTaskSpec()
{
return taskSpec;
}
public byte[] serialize()
{
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(this);
oos.flush();
return bos.toByteArray();
}
catch (IOException ex) {
LOGGER.log(Level.SEVERE, null, ex);
return null;
}
}
public static Job deserialize(byte[] input)
{
try {
ByteArrayInputStream bis = new ByteArrayInputStream(input);
ObjectInputStream ois = new ObjectInputStream(bis);
return (Job) ois.readObject();
}
catch (IOException | ClassNotFoundException ex) {
LOGGER.log(Level.SEVERE, null, ex);
return null;
}
}
}
| mzohreva/PASS | pass-core/src/main/java/pass/core/scheduling/distributed/Job.java | Java | mit | 1,683 |
<?php
/*
* This file is part of KoolKode Security Database.
*
* (c) Martin Schröder <m.schroeder2007@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace KoolKode\Security\Database;
use KoolKode\Database\ConnectionInterface;
use KoolKode\Security\Authentication\NonceTrackerInterface;
use KoolKode\Security\SecurityContextInterface;
use KoolKode\Util\RandomGeneratorInterface;
/**
* Keeps track of nonces being used by clients in HTTP digest auth.
*
* @author Martin Schröder
*/
class DatabaseNonceTracker implements NonceTrackerInterface
{
protected $context;
protected $conn;
protected $nonceByteCount = 16;
protected $nonceStrength = RandomGeneratorInterface::STRENGTH_MEDIUM;
protected $lifetime = 900;
protected $maxLifetime = 3600;
protected $delta = 15;
protected $invalidState = self::NONCE_INVALID;
protected $initialized = false;
protected $table = '#__security_nonce_tracker';
protected $columnNonce = 'nonce';
protected $columnCount = 'count';
protected $columnCreated = 'created';
public function __construct(SecurityContextInterface $context, ConnectionInterface $conn)
{
$this->context = $context;
$this->conn = $conn;
}
/**
* Set the number of random bytes being used to create a nonce.
*
* @param integer $byteCount
*/
public function setNonceByteCount($byteCount)
{
$this->nonceByteCount = max(4, (int)$byteCount);
}
/**
* Set the strength of randomness being used to create nonces.
*
* Defaults to MEDIUM strength.
*
* @param integer $strength
*/
public function setNonceStrength($strength)
{
$this->nonceStrength = max(RandomGeneratorInterface::STRENGTH_LOW, (int)$strength);
}
/**
* Set the nonce lifetime before it becomes stale.
*
* Defaults to 900 seconds.
*
* @param integer $lifetime Lifetime in seconds.
*/
public function setLifetime($lifetime)
{
$this->lifetime = (int)$lifetime;
}
/**
* Set the maximum lifetime before a nonce is deleted.
*
* Defaults to 3600 seconds.
*
* @param integer $maxLifetime Maximum lifetime in seconds.
*/
public function setMaxLifetime($maxLifetime)
{
$this->maxLifetime = (int)$maxLifetime;
}
/**
* Set the client nonce delta (that is half the size of the interval being used when
* checking for a valid client nonce count).
*
* Defaults to 15.
*
* @param integer $delta
*/
public function setDelta($delta)
{
$this->delta = (int)$delta;
}
/**
* Set the name of the table being used for nonce tracking.
*
* Defaults to "nonce_tracker".
*
* @param string $tableName
*/
public function setTableName($tableName)
{
$this->table = $this->conn->quoteIdentifier($tableName);
}
/**
* Set the name of the column holding the nonce value.
*
* Defaults to "nonce".
*
* @param string $column
*/
public function setNonceColumn($column)
{
$this->columnNonce = $this->conn->quoteIdentifier($column);
}
/**
* Set the name of the column tracking the nonce usage count.
*
* Defaults to "count".
*
* @param string $column
*/
public function setCountColumn($column)
{
$this->columnCount = $this->conn->quoteIdentifier($column);
}
/**
* Set the name of the column holding the nonce creation timestamp.
*
* Defaults to "created".
*
* @param string $column
*/
public function setCreatedColumn($column)
{
$this->columnCreated = $this->conn->quoteIdentifier($column);
}
/**
* Set the state to be returned when the checked nonce is invalid.
*
* Some clients (MS WebDAV client for example) may require returning STALE instead of INVALID in such a situation.
*
* @param integer $state One of NONCE_INVALID or NONCE_STALE.
*
* @throws \InvalidArgumentException
*/
public function setInvalidState($state)
{
switch($state)
{
case self::NONCE_INVALID:
case self::NONCE_STALE:
$this->invalidState = (int)$state;
break;
default:
throw new \InvalidArgumentException(sprintf('State not supported for invalid nonce: %s', $state));
}
}
/**
* {@inheritdoc}
*/
public function initializeTracker()
{
if($this->initialized)
{
return;
}
$sql = " DELETE FROM {$this->table}
WHERE {$this->columnCreated} < :max
OR {$this->columnCount} < 2 AND {$this->columnCreated} < :lifetime
";
$stmt = $this->conn->prepare($sql);
$stmt->bindValue('mac', time() - $this->maxLifetime);
$stmt->bindValue('lifetime', time() - $this->lifetime);
$stmt->execute();
$this->initialized = true;
}
/**
* {@inheritdoc}
*/
public function createNonce()
{
$nonce = $this->context->getRandomGenerator()->generateHexString($this->nonceByteCount, $this->nonceStrength);
// Create fresh nonce:
$sql = " INSERT INTO {$this->table}
({$this->columnNonce}, {$this->columnCount}, {$this->columnCreated})
VALUES
(:nonce, :count, :created)
";
$stmt = $this->conn->prepare($sql);
$stmt->bindValue('nonce', $nonce);
$stmt->bindValue('count', 0);
$stmt->bindValue('created', time());
$stmt->execute();
return $nonce;
}
/**
* {@inheritdoc}
*/
public function checkNonce($nonce, $count)
{
$nonce = (string)$nonce;
$count = (int)$count;
$sql = " SELECT {$this->columnCount} AS nonce_count, {$this->columnCreated} AS nonce_created
FROM {$this->table}
WHERE {$this->columnNonce} = :nonce
";
$stmt = $this->conn->prepare($sql);
$stmt->bindValue('nonce', $nonce);
$stmt->execute();
$row = $stmt->fetchNextRow();
if($row === false)
{
return $this->invalidState;
}
$nonceCount = (int)$row['nonce_count'];
$nonceCreated = (int)$row['nonce_created'];
// Update nonce count:
$sql = " UPDATE {$this->table}
SET {$this->columnCount} = {$this->columnCount} + 1
WHERE {$this->columnNonce} = :nonce
";
$stmt = $this->conn->prepare($sql);
$stmt->bindValue('nonce', $nonce);
$stmt->execute();
// Check client nonce counter including delta range (useful when processing requests in parallel).
if($count < ($nonceCount - $this->delta) || $count > ($nonceCount + $this->delta))
{
return $this->invalidState;
}
// Check if nonce has staled out.
if(($nonceCreated + $this->lifetime) < time())
{
return self::NONCE_STALE;
}
return self::NONCE_OK;
}
}
| koolkode/security-database | src/DatabaseNonceTracker.php | PHP | mit | 6,412 |
Ember.Fuel.Grid.View.Toolbar = Ember.Fuel.Grid.View.ContainerBase.extend({
classNames: ['table-toolbar'],
classNameBindings: ['childViews.length::hide'],
childViewsBinding: 'controller.toolbar'
}); | redfire1539/ember-fuel | Libraries/Grid/Views/Toolbar.js | JavaScript | mit | 203 |
<?php
/*
* This file is part of PHPExifTool.
*
* (c) 2012 Romain Neutron <imprec@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPExiftool\Driver\Tag\Flash;
use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;
/**
* @ExclusionPolicy("all")
*/
class Message extends AbstractTag
{
protected $Id = 'pmsg';
protected $Name = 'Message';
protected $FullName = 'Flash::Meta';
protected $GroupName = 'Flash';
protected $g0 = 'Flash';
protected $g1 = 'Flash';
protected $g2 = 'Video';
protected $Type = '?';
protected $Writable = false;
protected $Description = 'Message';
}
| romainneutron/PHPExiftool | lib/PHPExiftool/Driver/Tag/Flash/Message.php | PHP | mit | 764 |
angular.module('DashboardModule', ['ui.router', 'toastr', 'ngResource', 'angular-js-xlsx', 'angularFileUpload','ngAnimate'])
//.config(function ($routeProvider, $locationProvider) {
// $routeProvider
//
// .when('/', {
// templateUrl: '/js/private/dashboard/tpl/dashboard.tpl.html',
// controller: 'DashboardController'
// })
//
// .when('/account', {
// templateUrl: '/js/private/dashboard/account/tpl/account.tpl.html',
// controller: 'AccountController'
// })
// ;
// $locationProvider.html5Mode({enabled: true, requireBase: false});
//})
.config(['$sceDelegateProvider', function($sceDelegateProvider) {
// We must whitelist the JSONP endpoint that we are using to show that we trust it
$sceDelegateProvider.resourceUrlWhitelist([
'self',
'http://localhost:1339/**'
]);
}])
.config(function ($stateProvider, $urlRouterProvider, $locationProvider) {
$stateProvider
.state('home', {
url: '/',
views: {
//'sidebar@': {templateUrl: '/js/private/tpl/sidebar.tpl.html'},
'@': {
templateUrl: '/js/public/dashboard/tpl/dashboard.html',
controller: 'DashboardController'
}
}
})
.state('home.upload', {
url: 'upload',
views: {
'@': {
templateUrl: '/js/public/dashboard/tpl/upload.html',
controller: 'DashboardController'
}
}
})
.state('home.file.upload', {
url: 'upload',
views: {
'@': {
templateUrl: '/js/public/dashboard/tpl/upload.html',
controller: 'DashboardController'
}
}
})
//.state('home.profile.edit', {
// url: '/edit',
// views: {
// '@': {
// templateUrl: '/js/private/dashboard/tpl/edit-profile.html',
// controller: 'EditProfileController'
// }
// }
//})
// .state('home.profile.restore', {
// url: 'restore',
// views: {
// '@': {
// templateUrl: '/js/private/dashboard/tpl/restore-profile.html',
// controller: 'RestoreProfileController'
// }
// }
// })
// .state('account', {
// url: '/account',
// templateUrl: '/js/private/dashboard/account/tpl/account.tpl.html'
// })
// .state('contact', {
// url: '/contact',
// // Будет автоматически вложен в безымянный ui-view
// // родительского шаблона. Начиная с состояния верхнего уровня,
// // шаблоном этого родительского состояния является index.html.
// templateUrl: '/js/private/contacts.html'
// })
//
// .state('contact.detail', {
// views: {
// /////////////////////////////////////////////////////
// // Относительное позиционирование //
// // позиционируется родительское состояние в ui-view//
// /////////////////////////////////////////////////////
//
// // Относительное позиционирование вида 'detail' в родительском
// // состоянии 'contacts'.
// // <div ui-view='detail'/> внутри contacts.html
// // "detail": {},
//
// // Относительное поциционирование безымянного вида в родительском
// // состояния 'contacts'.
// // <div ui-view/> внутри contacts.html
// // "": {}
//
// ////////////////////////////////////////////////////////////////////////////
// // Абсолютное позиционирование '@' //
// // Позиционирование любых видов внутри этого состояния илипредшествующего //
// ////////////////////////////////////////////////////////////////////////////
//
// // Абсолютное позиционирование вида 'info' в состоянии 'contacts.detail'.
// // <div ui-view='info'/> внутри contacts.detail.html
// //"info@contacts.detail" : { }
//
// // Абсолютное позиционирование вида 'detail' в состоянии 'contacts'.
// // <div ui-view='detail'/> внутри contacts.html
// "detail@contact": {templateUrl: '/js/private/contact.detail.tpl.html'}
//
// // Абсолютное позиционирование безымянного вида в родительском
// // состоянии 'contacts'.
// // <div ui-view/> внутри contacts.html
// // "@contacts" : { }
//
// // Абсолютное позиционирование вида 'status' в корневом безымянном состоянии.
// // <div ui-view='status'/> внутри index.html
// // "status@" : { }
//
// // Абсолютное позиционирование безымянного вида в корневом безымянном состоянии.
// // <div ui-view/> внутри index.html
// // "@" : { }
// }
// // .state('route1.viewC', {
// // url: "/route1",
// // views: {
// // "viewC": { template: "route1.viewA" }
// // }
// // })
// // .state('route2', {
// // url: "/route2",
// // views: {
// // "viewA": { template: "route2.viewA" },
// // "viewB": { template: "route2.viewB" }
// // }
// // })
// })
;
})
.directive('file', function () {
return {
scope: {
file: '='
},
link: function (scope, el, attrs) {
el.bind('change', function (event) {
var file = event.target.files[0];
scope.file = file ? file : undefined;
scope.$apply();
});
}
};
});
//.constant('CONF_MODULE', {baseUrl: '/price/:priceId'})
//.factory('Prices', function ($resource, $state, CONF_MODULE) {
// var Prices = $resource(
// CONF_MODULE.baseUrl,
// {priceId: '@id'},
// // Определяем собственный метод update на обоих уровнях, класса и экземпляра
// {
// update: {
// method: 'PUT'
// }
// }
// );
//})
; | SETTER2000/price | assets/js/public/dashboard/DashboardModule.js | JavaScript | mit | 8,259 |
<!--
Safe sample
input : execute a ls command using the function system, and put the last result in $tainted
sanitize : cast via + = 0.0
File : unsafe, use of untrusted data in a comment
-->
<!--Copyright 2015 Bertrand STIVALET
Permission is hereby granted, without written agreement or royalty fee, to
use, copy, modify, and distribute this software and its documentation for
any purpose, provided that the above copyright notice and the following
three paragraphs appear in all copies of this software.
IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT,
INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE
BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT
LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO
OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
MODIFICATIONS.-->
<!DOCTYPE html>
<html>
<head>
<!--
<?php
$tainted = system('ls', $retval);
$tainted += 0.0 ;
echo $tainted ;
?>
-->
</head>
<body>
<h1>Hello World!</h1>
</body>
</html> | stivalet/PHP-Vulnerability-test-suite | XSS/CWE_79/safe/CWE_79__system__CAST-cast_float_sort_of__Unsafe_use_untrusted_data-comment.php | PHP | mit | 1,275 |
# describe 'Users feature', type: :feature do
# let!(:first_user) { create :user, name: 'Admin' }
# let!(:second_user) { create :user, name: 'User' }
# before do
# visit root_path
# click_link 'All users'
# end
# describe '#index' do
# it 'shows page title' do
# expect(page).to have_content('All users')
# end
# it 'shows all registered users' do
# expect(page).to have_content(first_user.name)
# expect(page).to have_content(first_user.email)
# expect(page).to have_content(second_user.name)
# expect(page).to have_content(second_user.email)
# end
# end
# describe '#show' do
# before do
# click_link "Show profile of #{first_user.name}"
# end
# it 'redirects to user posts url' do
# expect(page).to have_current_path(user_posts_path(first_user))
# end
# end
# end
| vrtsev/LifeLog | spec/features/publications/users_feature_spec.rb | Ruby | mit | 872 |
module App {
/**
* Наследуйте все директивы не имеющие html-темплейта от этого класса.
* Стили будут загружаться относительно папки URL.DIRECTIVES_ROOT/<имя-директивы>.
* Скоуп, элемент и атрибуты директивы доступны через св-ва $scope, $element, $attrs.
* По умолчанию доступны сервисы $parse, $compile, $sce
*/
export class Directive extends LionSoftAngular.Directive {
promiseFromResult<T>(res: T): IPromise<T> {
return <any>super.promiseFromResult(res);
}
/**
* Do not override this method. Use methods this.PreLink, this.Link, this.Compile instead.
*/
compile = (element, attrs, transclude) => {
this.ngName = this.name || this.ngName;
this.rootFolder = URL.DIRECTIVES_ROOT + this.getName(false) + "/";
this.Compile(element, attrs, transclude);
return {
pre: (scope, element, attrs, controller, transclude) => {
this.PreLink(scope, element, attrs, controller, transclude);
},
post: (scope, element, attrs, controller, transclude) => this.Link(scope, element, attrs, controller, transclude)
}
};
}
} | lionsoft/SampleSPA | Sam/app/common/Directive.ts | TypeScript | mit | 1,419 |
(function() {
function ce(p, n, id, c, html)
{
var e = document.createElement(n);
p.appendChild(e);
if (id) e.id = id;
if (c) e.className = c;
if (html) e.innerHTML = html;
return e;
}
demoModeGameboard = gameboard.extend
({
init : function(isActive, gameData, generateState, elapsedTime)
{
arguments.callee.$.init.call(this);
this.maxTime = 120.0;
var that = this;
this.elapsedTime = 0;
this.pastMoves = Array();
setTimeout(function()
{
that.startGame();
}, 100);
return this.encodeBoard();
},
uninit : function()
{
arguments.callee.$.uninit.call(this);
_('#demoModeContainer').innerHTML = '';
_('#demoModeContainer').style.display = 'none';
clearInterval(this.startInterval);
clearInterval(this.confirmInterval);
},
encodeBoard : function()
{
var boardData = arguments.callee.$.encodeBoard.call(this);
return boardData;
},
startRound : function()
{
var that = this;
},
endRound : function(success)
{
this.elapsedTime = 0;
clearInterval(this.startInterval);
var target = this.captureTile.target;
this.captureTile.target = null;
var token = this.createToken(target.id, target.color);
this.targetTile = null;
this.activeTile = null;
this.isActive = false;
this.activeBidder = null;
for (var i = 0; i < this.moveOptions.length; ++i)
{
this.moveOptions[i] = null;
}
this.render();
this.init();
},
showPossible : function()
{
return;
},
startGame : function()
{
var that = this;
this.isActive = false;
this.captureTileIndex = Math.floor(Math.random()*this.targets.length);
this.activeTarget = this.targets[this.captureTileIndex];
this.targets.splice(this.captureTileIndex, 1);
var t = this.activeTarget;
for (var j = 0; j < this.tiles.length; ++j)
{
var ti = this.tiles[j];
if (ti.targetId === t.id)
{
ti.target = t;
this.captureTile = ti;
break;
}
}
this.render();
this.solution = null;
this.simulateMove();
this.speed = 500;
},
simulateMove : function()
{
var that = this;
if (!that.solution)
{
that.solution = that.solve();
}
var from = null;
var to = null;
var mover = null;
if (that.solution)
{
if (that.solution.length == 0)
{
return;
}
var move = that.solution.splice(0, 1)[0];
from = that.tiles[move.f];
to = that.tiles[move.t];
mover = move.m;
this.activeTile = from;
that.showPossible();
this.pastMoves.push(move);
this.speed = 500;
}
else
{
// Move pieces at random...
var pieceIndex = Math.floor(Math.random()*4);
var moveOption = null;
that.activeTile = that.tiles[that.movers[pieceIndex].tileIndex];
that.showPossible();
do
{
var moveIndex = Math.floor(Math.random()*4);
moveOption = that.moveOptions[moveIndex];
} while (!moveOption);
from = that.activeTile;
to = moveOption.endTile;
mover = that.movers[pieceIndex];
this.speed = 50;
}
this.render();
if (from.piece != mover)
{
_alert('wtf');
from.piece = mover;
that.render();
that.simulateMove();
return;
}
this.moveMover(mover, from, to, this.speed, function() { that.simulateMove();} );
}
});
window['demoModeGameboard'] = demoModeGameboard;
})(); | nbclark/bounding-bandits | bb.demomode.js | JavaScript | mit | 4,865 |
/*global describe, beforeEach, it*/
'use strict';
var path = require('path');
var helpers = require('yeoman-generator').test;
describe('statik generator', function () {
beforeEach(function (done) {
helpers.testDirectory(path.join(__dirname, 'temp'), function (err) {
if (err) {
return done(err);
}
this.app = helpers.createGenerator('statik:app', [
'../../app'
]);
done();
}.bind(this));
});
it('creates expected files', function (done) {
var expected = [
// add files you expect to exist here.
'.jshintrc',
'.editorconfig'
];
helpers.mockPrompt(this.app, {
'someOption': true
});
this.app.options['skip-install'] = true;
this.app.run({}, function () {
helpers.assertFiles(expected);
done();
});
});
});
| balintgaspar/generator-statik | test/test-creation.js | JavaScript | mit | 965 |
<?php
namespace AppBundle\Repository;
/**
* MsvTConsecutivoRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class MsvTConsecutivoRepository extends \Doctrine\ORM\EntityRepository
{
//Obtiene el maximo consecutivo disponible según la sede operativa
public function getLastBySede($idOrganismoTransito)
{
$em = $this->getEntityManager();
$dql = "SELECT MAX(c.consecutivo) AS consecutivo, c.id
FROM AppBundle:MsvTConsecutivo c
WHERE c.organismoTransito = :idOrganismoTransito
AND c.estado = :estado
GROUP BY c.organismoTransito";
$consulta = $em->createQuery($dql);
$consulta->setParameters(array(
'idOrganismoTransito' => $idOrganismoTransito,
'estado' => 'DISPONIBLE',
));
return $consulta->getOneOrNullResult();
}
public function getBySede($identificacionUsuario)
{
$em = $this->getEntityManager();
$dql = "SELECT msc
FROM AppBundle:MsvTConsecutivo msc, UsuarioBundle:Usuario u, AppBundle:MpersonalFuncionario mpf
WHERE u.identificacion = :identificacionUsuario
AND u.ciudadano = mpf.ciudadano
AND mpf.sedeOperativa = msc.sedeOperativa
AND msc.activo = true";
$consulta = $em->createQuery($dql);
$consulta->setParameters(array(
'identificacionUsuario' => $identificacionUsuario,
));
return $consulta->getResult();
}
}
/*
SELECT consecutivo FROM msv_t_consecutivo, usuario, mpersonal_funcionario
WHERE usuario.identificacion=2222
AND usuario.ciudadano_id = mpersonal_funcionario.ciudadano_id
AND mpersonal_funcionario.sede_operativa_id = msv_t_consecutivo.sede_operativa_id
AND msv_t_consecutivo.consecutivo = 12312300000000000000
*/ | edosgn/colossus-sit | src/AppBundle/Repository/MsvTConsecutivoRepository.php | PHP | mit | 1,887 |
var gulp = require('gulp'),
nodemon = require('gulp-nodemon'),
plumber = require('gulp-plumber'),
livereload = require('gulp-livereload'),
sass = require('gulp-sass');
gulp.task('sass', function () {
gulp.src('./public/stylesheets/*.scss')
.pipe(plumber())
.pipe(sass())
.pipe(gulp.dest('./public/stylesheets'))
.pipe(livereload());
});
gulp.task('watch', function() {
gulp.watch('./public/stylesheets/*.scss', ['sass']);
});
gulp.task('develop', function () {
livereload.listen();
nodemon({
script: 'bin/www',
ext: 'js coffee jade',
stdout: false
}).on('readable', function () {
this.stdout.on('data', function (chunk) {
if(/^Express server listening on port/.test(chunk)){
livereload.changed(__dirname);
}
});
this.stdout.pipe(process.stdout);
this.stderr.pipe(process.stderr);
});
});
gulp.task('default', [
'sass',
'develop',
'watch'
]);
| draptik/rpi-temperature-website | gulpfile.js | JavaScript | mit | 936 |
"""Common settings and globals."""
from os.path import abspath, basename, dirname, join, normpath
from sys import path
from os import environ
# Normally you should not import ANYTHING from Django directly
# into your settings, but ImproperlyConfigured is an exception.
from django.core.exceptions import ImproperlyConfigured
def get_env_setting(setting):
""" Get the environment setting or return exception """
try:
return environ[setting]
except KeyError:
error_msg = "Set the %s env variable" % setting
raise ImproperlyConfigured(error_msg)
########## PATH CONFIGURATION
# Absolute filesystem path to the Django project directory:
DJANGO_ROOT = dirname(dirname(dirname(abspath(__file__))))
# Absolute filesystem path to the top-level project folder:
SITE_ROOT = dirname(DJANGO_ROOT)
# Site name:
SITE_NAME = basename(DJANGO_ROOT)
# Add our project to our pythonpath, this way we don't need to type our project
# name in our dotted import paths:
path.append(DJANGO_ROOT)
########## END PATH CONFIGURATION
########## DEBUG CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#debug
DEBUG = False
########## END DEBUG CONFIGURATION
########## MANAGER CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#admins
ADMINS = (
('Gregory Favre', 'info@gregoryfavre.ch'),
)
# See: https://docs.djangoproject.com/en/dev/ref/settings/#managers
MANAGERS = ADMINS
########## END MANAGER CONFIGURATION
########## DATABASE CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.',
'NAME': '',
'USER': '',
'PASSWORD': '',
'HOST': '',
'PORT': '',
}
}
########## END DATABASE CONFIGURATION
########## GENERAL CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#time-zone
TIME_ZONE = 'Europe/Zurich'
# See: https://docs.djangoproject.com/en/dev/ref/settings/#language-code
LANGUAGE_CODE = 'fr-CH'
# See: https://docs.djangoproject.com/en/dev/ref/settings/#site-id
SITE_ID = 1
# See: https://docs.djangoproject.com/en/dev/ref/settings/#use-i18n
USE_I18N = True
# See: https://docs.djangoproject.com/en/dev/ref/settings/#use-l10n
USE_L10N = True
# See: https://docs.djangoproject.com/en/dev/ref/settings/#use-tz
USE_TZ = True
########## END GENERAL CONFIGURATION
########## MEDIA CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#media-root
MEDIA_ROOT = normpath(join(SITE_ROOT, 'media'))
# See: https://docs.djangoproject.com/en/dev/ref/settings/#media-url
MEDIA_URL = '/media/'
########## END MEDIA CONFIGURATION
########## STATIC FILE CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#static-root
STATIC_ROOT = normpath(join(SITE_ROOT, 'staticfiles'))
# See: https://docs.djangoproject.com/en/dev/ref/settings/#static-url
STATIC_URL = '/static/'
# See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#staticfiles-finders
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
'compressor.finders.CompressorFinder',
)
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
STATICFILES_DIRS = [
join(DJANGO_ROOT, "static"),
]
########## END STATIC FILE CONFIGURATION
########## SECRET CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#secret-key
# Note: This key should only be used for development and testing.
SECRET_KEY = get_env_setting('SECRET_KEY')
########## END SECRET CONFIGURATION
########## SITE CONFIGURATION
# Hosts/domain names that are valid for this site
# See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts
ALLOWED_HOSTS = []
########## END SITE CONFIGURATION
########## FIXTURE CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-FIXTURE_DIRS
FIXTURE_DIRS = (
normpath(join(SITE_ROOT, 'fixtures')),
)
########## END FIXTURE CONFIGURATION
########## TEMPLATE CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#template-context-processors
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'APP_DIRS': True,
'DIRS': [
normpath(join(DJANGO_ROOT, 'templates')),
],
'OPTIONS': {
'context_processors': (
'django.contrib.auth.context_processors.auth',
'django.template.context_processors.debug',
'django.template.context_processors.i18n',
'django.template.context_processors.media',
'django.template.context_processors.static',
'django.template.context_processors.tz',
'django.contrib.messages.context_processors.messages',
'django.template.context_processors.request',
'sekizai.context_processors.sekizai',
)
}
},
]
########## END TEMPLATE CONFIGURATION
########## MIDDLEWARE CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#middleware-classes
MIDDLEWARE_CLASSES = (
# Default Django middleware.
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
)
########## END MIDDLEWARE CONFIGURATION
########## URL CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#root-urlconf
ROOT_URLCONF = '%s.urls' % SITE_NAME
########## END URL CONFIGURATION
########## APP CONFIGURATION
DJANGO_APPS = [
# Default Django apps:
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
# Useful template tags:
# 'django.contrib.humanize',
# Admin panel and documentation:
'django.contrib.admin',
# 'django.contrib.admindocs',
]
THIRD_PARTY_APPS = [
'captcha', # recaptcha
'compressor',
'sekizai',
]
# Apps specific for this project go here.
LOCAL_APPS = [
'contact',
]
# See: https://docs.djangoproject.com/en/dev/ref/settings/#installed-apps
INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS
########## END APP CONFIGURATION
########## LOGGING CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#logging
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
########## END LOGGING CONFIGURATION
########## WSGI CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#wsgi-application
WSGI_APPLICATION = '%s.wsgi.application' % SITE_NAME
########## END WSGI CONFIGURATION
RECAPTCHA_PUBLIC_KEY = get_env_setting('RECAPTCHA_PUBLIC_KEY')
RECAPTCHA_PRIVATE_KEY = get_env_setting('RECAPTCHA_PRIVATE_KEY') | gfavre/beyondthewall.ch | beyondthewall/beyondthewall/settings/base.py | Python | mit | 7,931 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Routing;
namespace SpecFlowHelper.SampleWebApi
{
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
}
}
}
| giacomelli/SpecFlowHelper | SpecFlowHelper.SampleWebApi/Global.asax.cs | C# | mit | 402 |
<?php
/**
* aPage filter form base class.
*
* @package symfony
* @subpackage filter
* @author Your name here
* @version SVN: $Id: sfDoctrineFormFilterGeneratedTemplate.php 29570 2010-05-21 14:49:47Z Kris.Wallsmith $
*/
abstract class BaseaPageFormFilter extends BaseFormFilterDoctrine
{
public function setup()
{
$this->setWidgets(array(
'slug' => new sfWidgetFormFilterInput(),
'template' => new sfWidgetFormFilterInput(),
'view_is_secure' => new sfWidgetFormChoice(array('choices' => array('' => 'yes or no', 1 => 'yes', 0 => 'no'))),
'view_guest' => new sfWidgetFormChoice(array('choices' => array('' => 'yes or no', 1 => 'yes', 0 => 'no'))),
'edit_admin_lock' => new sfWidgetFormChoice(array('choices' => array('' => 'yes or no', 1 => 'yes', 0 => 'no'))),
'view_admin_lock' => new sfWidgetFormChoice(array('choices' => array('' => 'yes or no', 1 => 'yes', 0 => 'no'))),
'published_at' => new sfWidgetFormFilterDate(array('from_date' => new sfWidgetFormDate(), 'to_date' => new sfWidgetFormDate())),
'archived' => new sfWidgetFormChoice(array('choices' => array('' => 'yes or no', 1 => 'yes', 0 => 'no'))),
'admin' => new sfWidgetFormChoice(array('choices' => array('' => 'yes or no', 1 => 'yes', 0 => 'no'))),
'author_id' => new sfWidgetFormDoctrineChoice(array('model' => $this->getRelatedModelName('Author'), 'add_empty' => true)),
'deleter_id' => new sfWidgetFormDoctrineChoice(array('model' => $this->getRelatedModelName('Deleter'), 'add_empty' => true)),
'engine' => new sfWidgetFormFilterInput(),
'created_at' => new sfWidgetFormFilterDate(array('from_date' => new sfWidgetFormDate(), 'to_date' => new sfWidgetFormDate(), 'with_empty' => false)),
'updated_at' => new sfWidgetFormFilterDate(array('from_date' => new sfWidgetFormDate(), 'to_date' => new sfWidgetFormDate(), 'with_empty' => false)),
'lft' => new sfWidgetFormFilterInput(),
'rgt' => new sfWidgetFormFilterInput(),
'level' => new sfWidgetFormFilterInput(),
'a_search_documents_list' => new sfWidgetFormDoctrineChoice(array('multiple' => true, 'model' => 'aSearchDocument')),
'categories_list' => new sfWidgetFormDoctrineChoice(array('multiple' => true, 'model' => 'aCategory')),
));
$this->setValidators(array(
'slug' => new sfValidatorPass(array('required' => false)),
'template' => new sfValidatorPass(array('required' => false)),
'view_is_secure' => new sfValidatorChoice(array('required' => false, 'choices' => array('', 1, 0))),
'view_guest' => new sfValidatorChoice(array('required' => false, 'choices' => array('', 1, 0))),
'edit_admin_lock' => new sfValidatorChoice(array('required' => false, 'choices' => array('', 1, 0))),
'view_admin_lock' => new sfValidatorChoice(array('required' => false, 'choices' => array('', 1, 0))),
'published_at' => new sfValidatorDateRange(array('required' => false, 'from_date' => new sfValidatorDateTime(array('required' => false, 'datetime_output' => 'Y-m-d 00:00:00')), 'to_date' => new sfValidatorDateTime(array('required' => false, 'datetime_output' => 'Y-m-d 23:59:59')))),
'archived' => new sfValidatorChoice(array('required' => false, 'choices' => array('', 1, 0))),
'admin' => new sfValidatorChoice(array('required' => false, 'choices' => array('', 1, 0))),
'author_id' => new sfValidatorDoctrineChoice(array('required' => false, 'model' => $this->getRelatedModelName('Author'), 'column' => 'id')),
'deleter_id' => new sfValidatorDoctrineChoice(array('required' => false, 'model' => $this->getRelatedModelName('Deleter'), 'column' => 'id')),
'engine' => new sfValidatorPass(array('required' => false)),
'created_at' => new sfValidatorDateRange(array('required' => false, 'from_date' => new sfValidatorDateTime(array('required' => false, 'datetime_output' => 'Y-m-d 00:00:00')), 'to_date' => new sfValidatorDateTime(array('required' => false, 'datetime_output' => 'Y-m-d 23:59:59')))),
'updated_at' => new sfValidatorDateRange(array('required' => false, 'from_date' => new sfValidatorDateTime(array('required' => false, 'datetime_output' => 'Y-m-d 00:00:00')), 'to_date' => new sfValidatorDateTime(array('required' => false, 'datetime_output' => 'Y-m-d 23:59:59')))),
'lft' => new sfValidatorSchemaFilter('text', new sfValidatorInteger(array('required' => false))),
'rgt' => new sfValidatorSchemaFilter('text', new sfValidatorInteger(array('required' => false))),
'level' => new sfValidatorSchemaFilter('text', new sfValidatorInteger(array('required' => false))),
'a_search_documents_list' => new sfValidatorDoctrineChoice(array('multiple' => true, 'model' => 'aSearchDocument', 'required' => false)),
'categories_list' => new sfValidatorDoctrineChoice(array('multiple' => true, 'model' => 'aCategory', 'required' => false)),
));
$this->widgetSchema->setNameFormat('a_page_filters[%s]');
$this->errorSchema = new sfValidatorErrorSchema($this->validatorSchema);
$this->setupInheritance();
parent::setup();
}
public function addASearchDocumentsListColumnQuery(Doctrine_Query $query, $field, $values)
{
if (!is_array($values))
{
$values = array($values);
}
if (!count($values))
{
return;
}
$query
->leftJoin($query->getRootAlias().'.aPageToASearchDocument aPageToASearchDocument')
->andWhereIn('aPageToASearchDocument.a_search_document_id', $values)
;
}
public function addCategoriesListColumnQuery(Doctrine_Query $query, $field, $values)
{
if (!is_array($values))
{
$values = array($values);
}
if (!count($values))
{
return;
}
$query
->leftJoin($query->getRootAlias().'.aPageToCategory aPageToCategory')
->andWhereIn('aPageToCategory.category_id', $values)
;
}
public function getModelName()
{
return 'aPage';
}
public function getFields()
{
return array(
'id' => 'Number',
'slug' => 'Text',
'template' => 'Text',
'view_is_secure' => 'Boolean',
'view_guest' => 'Boolean',
'edit_admin_lock' => 'Boolean',
'view_admin_lock' => 'Boolean',
'published_at' => 'Date',
'archived' => 'Boolean',
'admin' => 'Boolean',
'author_id' => 'ForeignKey',
'deleter_id' => 'ForeignKey',
'engine' => 'Text',
'created_at' => 'Date',
'updated_at' => 'Date',
'lft' => 'Number',
'rgt' => 'Number',
'level' => 'Number',
'a_search_documents_list' => 'ManyKey',
'categories_list' => 'ManyKey',
);
}
}
| samura/asandbox | lib/filter/doctrine/apostrophePlugin/base/BaseaPageFormFilter.class.php | PHP | mit | 7,433 |
package com.charmyin.cmstudio.basic.authorize.service;
import java.util.List;
import org.springframework.stereotype.Service;
import com.charmyin.cmstudio.basic.authorize.vo.TreeItem;
@Service
public interface TreeItemService {
List<TreeItem> getOrganizationWithUsers(int organizationId);
}
| Feolive/EmploymentWebsite | src/main/java/com/charmyin/cmstudio/basic/authorize/service/TreeItemService.java | Java | mit | 300 |
'use strict';
const loadRule = require('../utils/load-rule');
const ContextBuilder = require('../utils/contextBuilder');
const RequestBuilder = require('../utils/requestBuilder');
const AuthenticationBuilder = require('../utils/authenticationBuilder');
const ruleName = 'require-mfa-once-per-session';
describe(ruleName, () => {
let context;
let rule;
let user;
describe('With only a login prompt completed', () => {
beforeEach(() => {
rule = loadRule(ruleName);
const request = new RequestBuilder().build();
const authentication = new AuthenticationBuilder().build();
context = new ContextBuilder()
.withRequest(request)
.withAuthentication(authentication)
.build();
});
it('should set a multifactor provider', (done) => {
rule(user, context, (err, u, c) => {
expect(c.multifactor.provider).toBe('any');
expect(c.multifactor.allowRememberBrowser).toBe(false);
done();
});
});
});
describe('With a login and MFA prompt completed', () => {
beforeEach(() => {
rule = loadRule(ruleName);
const request = new RequestBuilder().build();
const authentication = new AuthenticationBuilder()
.withMethods([
{
name: 'pwd',
timestamp: 1434454643024
},
{
name: 'mfa',
timestamp: 1534454643881
}
])
.build();
context = new ContextBuilder()
.withRequest(request)
.withAuthentication(authentication)
.build();
});
it('should not set a multifactor provider', (done) => {
rule(user, context, (err, u, c) => {
expect(c.multifactor).toBe(undefined);
done();
});
});
});
});
| auth0/rules | test/rules/require-mfa-once-per-session.test.js | JavaScript | mit | 1,787 |
# frozen_string_literal: true
require 'numbers_and_words/strategies/figures_converter/languages'
require 'numbers_and_words/strategies/figures_converter/options'
require 'numbers_and_words/strategies/figures_converter/decorators'
module NumbersAndWords
module Strategies
module FiguresConverter
class Base
attr_accessor :options, :figures, :translations, :language, :decorator
def initialize(figures, options = {})
@figures = figures.reverse
@decorator = Decorators.factory(self, options)
@options = Options::Proxy.new(self, options)
@translations = Translations.factory
@language = Languages.factory(self)
end
def run
around { language.words }
end
private
def around(&block)
decorator.run(&block)
end
end
end
end
end
| kslazarev/numbers_and_words | lib/numbers_and_words/strategies/figures_converter.rb | Ruby | mit | 883 |
using WebPlatform.Core.Data;
namespace WebPlatform.Tests.Core
{
/// <summary>
/// Defines the test entity.
/// </summary>
public class TestEntity : Entity
{
/// <summary>
/// Gets or sets the caption.
/// </summary>
public string Caption
{
get;
set;
}
}
}
| urahnung/webplatform | src/Tests/Core/TestEntity.cs | C# | mit | 336 |
let base_x = {}
let dictionaries = {}
/// @name Encode
/// @description Takes a large number and converts it to a shorter encoded string style string i.e. 1TigYx
/// @arg {number} input The number to be encoded to a string
/// @arg {number, string} dictionary ['DICTIONARY_52'] - The dictionary to use for the encoding
/// @arg {number} padding [0] - The padding (minimum length of the generated string)
base_x.encodeNumber = (input, padding, dictionary) => {
let result = []
dictionary = base_x.getDictionary(dictionary)
let base = dictionary.length
let exponent = 1
let remaining = parseInt(input)
let a, b, c, d
a = b = c = d = 0
padding = padding || 0
// check if padding is being used
if (padding) {
remaining += Math.pow(base, padding)
}
// generate the encoded string
while (true) {
a = Math.pow(base, exponent) // 16^1 = 16
b = remaining % a // 119 % 16 = 7 | 112 % 256 = 112
c = Math.pow(base, exponent - 1)
d = b / c
result.push(dictionary[parseInt(d)])
remaining -= b // 119 - 7 = 112 | 112 - 112 = 0
if (remaining === 0) {
break
}
exponent++
}
return result.reverse().join('')
}
/// @name Encode
/// @description Decodes a shortened encoded string back into a number
/// @arg {number} input - The encoded string to be decoded
/// @arg {number, string} dictionary ['DICTIONARY_52'] - The dictionary to use for the encoding
/// @arg {number} padding [0] - The padding (minimum length of the generated string) to use
base_x.decodeNumber = (input, padding, dictionary) => {
let chars = input.split('').reverse()
dictionary = base_x.getDictionary(dictionary)
let base = dictionary.length
let result = 0
let map = {}
let exponent = 0
padding = padding || 0
// create a map lookup
for (let i = 0; i < base; i++) {
map[dictionary[i]] = i
}
// generate the number
for (let i = 0; i < input.length; i++) {
result += Math.pow(base, exponent) * map[chars[i]]
exponent++
}
// check if padding is being used
if (padding) {
result -= Math.pow(base, padding)
}
return result
}
/// @name getDictionary
/// @description Gets a dictionary or returns the default dictionary of 'DICTIONARY_52'
/// @arg {number, string} dictionary ['DICTIONARY_52'] - The dictionary to get
/// @returns {array}
base_x.getDictionary = (dictionary) => {
return dictionaries[dictionary] || dictionaries['DICTIONARY_' + dictionary] || dictionaries.DICTIONARY_52
}
/// @name addDictionaries
/// @description Adds a new dictionary
/// @arg {string} name - The name of the dictionary to add
/// @arg {string, array} dictionary - The dictionary to use as an array of characters
base_x.addDictionary = (name, dictionary) => {
if (typeof dictionary === 'string') {
dictionary = dictionary.split('')
}
dictionaries[name] = dictionary
return
}
let numbers = '0123456789'
let lower = 'abcdefghijklmnopqrstuvwxyz'
let upper = lower.toUpperCase()
// add default dictionarys
// numbers and A-F only
base_x.addDictionary('DICTIONARY_16',
numbers + upper.slice(0, 7)
)
// numbers and uppercase letters A-Z
base_x.addDictionary('DICTIONARY_32',
(numbers + upper).replace(/[0ilo]/gi, '')
)
base_x.addDictionary('letters', upper + lower)
// numbers, uppercase and lowercase B-Z minus vowels
base_x.addDictionary('DICTIONARY_52',
(numbers + upper).replace(/[aeiou]/gi, '')
)
// numbers, uppercase and lowercase A-Z
base_x.addDictionary('DICTIONARY_62',
numbers + upper + lower
)
// numbers, uppercase and lowercase A-Z and ~!@#$%^& (minus 0,o,O,1,i,I,l,L useful to generate passwords)
base_x.addDictionary('DICTIONARY_PASS',
(numbers + upper + lower + '~!@#$%^&').replace(/[01oil]/gi, '')
)
// numbers, uppercase and lowercase A-Z and ~!@#$%^& (useful to generate passwords)
base_x.addDictionary('DICTIONARY_70',
numbers + upper + lower + '~!@#$%^&'
)
// numbers, uppercase and lowercase A-Z and +"~!@#$%&*/|()=?'[]{}-_:.,;
base_x.addDictionary('DICTIONARY_89',
numbers + upper + lower + '+"@*#%&/|()=?~[]{}$-_.:,;<>'
)
import crypto from 'crypto'
base_x.encode = (data, padding = 4, dictionary = 'letters') => {
let hash = crypto
.createHash('md5')
.update(JSON.stringify(data), 'utf8')
.digest('hex')
.split('')
.reduce((prev, next) => prev + next.charCodeAt(), 0)
return base_x.encodeNumber(hash, padding, dictionary)
}
let base = global.base_x = global.base_x || base_x
export default base
| tjbenton/docs | packages/docs-theme-default/src/base-x.js | JavaScript | mit | 4,443 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Qoollo.PerformanceCounters
{
/// <summary>
/// Контейнер стандартных счётчиков
/// </summary>
public static class PerfCountersDefault
{
private static CounterFactory _default;
private static SingleInstanceCategory _defaultCategory;
private static readonly object _syncObj = new object();
/// <summary>
/// Фабрика для NullCounters
/// </summary>
public static NullCounters.NullCounterFactory NullCounterFactory
{
get { return NullCounters.NullCounterFactory.Instance; }
}
/// <summary>
/// Creates DefaultFactory singleton
/// </summary>
private static void CreateDefaultFactory()
{
if (_default == null)
{
lock (_syncObj)
{
if (_default == null)
_default = new InternalCounters.InternalCounterFactory();
}
}
}
/// <summary>
/// Creates DefaultCategory from DefaultFactory
/// </summary>
private static void CreateDefaultCategory()
{
if (_defaultCategory == null)
{
lock (_syncObj)
{
if (_default == null)
_default = new InternalCounters.InternalCounterFactory();
if (_defaultCategory == null)
_defaultCategory = _default.CreateSingleInstanceCategory("DefaultCategory", "Default category");
}
}
}
/// <summary>
/// Инстанс фабрики счётчиков.
/// По умолчанию тут InternalCounterFactory
/// </summary>
public static CounterFactory DefaultFactory
{
get
{
if (_default == null)
CreateDefaultFactory();
return _default;
}
}
/// <summary>
/// Default category to create counters in place.
/// Be careful: some CounterFactories are not support this approach.
/// </summary>
public static SingleInstanceCategory DefaultCategory
{
get
{
if (_defaultCategory == null)
CreateDefaultCategory();
return _defaultCategory;
}
}
/// <summary>
/// Задать новое значение инстанса фабрики счётчиков
/// </summary>
/// <param name="factory">Фабрика счётчиков</param>
public static void SetDefaultFactory(CounterFactory factory)
{
if (factory == null)
factory = new InternalCounters.InternalCounterFactory();
CounterFactory oldVal = null;
lock (_syncObj)
{
oldVal = System.Threading.Interlocked.Exchange(ref _default, factory);
System.Threading.Interlocked.Exchange(ref _defaultCategory, null);
}
if (oldVal != null)
oldVal.Dispose();
}
/// <summary>
/// Сбросить значение фабрики счётчиков.
/// Возвращает InternalCounterFactory.
/// </summary>
public static void ResetDefaultFactory()
{
SetDefaultFactory(new InternalCounters.InternalCounterFactory());
}
/// <summary>
/// Загрузить фабрику счётчиков из файла конфигурации
/// </summary>
/// <param name="sectionName">Имя секции в файле конфигурации</param>
public static void LoadDefaultFactoryFromAppConfig(string sectionName = "PerfCountersConfigurationSection")
{
if (sectionName == null)
throw new ArgumentNullException("sectionName");
var counters = PerfCountersInstantiationFactory.CreateCounterFactoryFromAppConfig(sectionName);
SetDefaultFactory(counters);
}
}
}
| qoollo/performance-counters | src/Qoollo.PerformanceCounters/PerfCountersDefault.cs | C# | mit | 4,487 |
<?php
/*
* This file is part of the Fidry\AliceDataFixtures package.
*
* (c) Théo FIDRY <theo.fidry@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Fidry\AliceDataFixtures\Bridge\Doctrine\PhpCrDocument;
use Doctrine\ODM\PHPCR\Mapping\Annotations\Document;
use Doctrine\ODM\PHPCR\Mapping\Annotations\Id;
/**
* @Document()
*
* @author Théo FIDRY <theo.fidry@gmail.com>
*/
class Dummy
{
/**
* @Id()
*/
public $id;
}
| furtadodiegos/projeto_cv | vendor/theofidry/alice-data-fixtures/fixtures/Bridge/Doctrine/PhpCrDocument/Dummy.php | PHP | mit | 577 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sneaking
{
class Sneaking
{
static void Main()
{
var roomSize = int.Parse(Console.ReadLine());
char[][] room = new char[roomSize][];
for (int row = 0; row < roomSize; row++)
{
room[row] = Console.ReadLine().ToCharArray();
}
var commands = Console.ReadLine().ToCharArray();
//initial positions
int samCurrentRow = 0;
int samCurrentCol = 0;
int nikoCurrentRow = 0;
int nikoCurrentCol = 0;
for (int row = 0; row < room.Length; row++)
{
if (room[row].Contains('S'))
{
samCurrentRow = row;
samCurrentCol = Array.IndexOf(room[row], 'S');
}
if (room[row].Contains('N'))
{
nikoCurrentRow = row;
nikoCurrentCol = Array.IndexOf(room[row], 'N');
}
}
for (int move = 0; move < commands.Length; move++)
{
var samCommand = commands[move];
EnemyMove(room);
if (IsSamKilled(room, samCurrentRow, samCurrentCol))
{
Console.WriteLine($"Sam died at {samCurrentRow}, {samCurrentCol}");
PrintCuurentRoomState(room);
break;
}
//sam moves
switch (samCommand)
{
case 'U':
room[samCurrentRow][samCurrentCol] = '.';
room[samCurrentRow - 1][samCurrentCol] = 'S';
samCurrentRow--;
break;
case 'D':
room[samCurrentRow][samCurrentCol] = '.';
room[samCurrentRow + 1][samCurrentCol] = 'S';
samCurrentRow++;
break;
case 'L':
room[samCurrentRow][samCurrentCol] = '.';
room[samCurrentRow][samCurrentCol - 1] = 'S';
samCurrentCol--;
break;
case 'R':
room[samCurrentRow][samCurrentCol] = '.';
room[samCurrentRow][samCurrentCol + 1] = 'S';
samCurrentCol++;
break;
}
//check if sam kills
if (samCurrentRow == nikoCurrentRow)
{
Console.WriteLine($"Nikoladze killed!");
room[nikoCurrentRow][nikoCurrentCol] = 'X';
PrintCuurentRoomState(room);
break;
}
}
}
private static void PrintCuurentRoomState(char[][] room)
{
for (int row = 0; row < room.Length; row++)
{
Console.WriteLine(string.Join("", room[row]));
}
}
private static bool IsSamKilled(char[][] room, int samCurrentRow, int samCurrentCol)
{
bool isKilled = false;
if (room[samCurrentRow].Contains('b'))
{
var enemyCol = Array.IndexOf(room[samCurrentRow], 'b');
if (samCurrentCol >= enemyCol)
{
room[samCurrentRow][samCurrentCol] = 'X';
isKilled = true;
}
}
else if (room[samCurrentRow].Contains('d'))
{
var enemyCol = Array.IndexOf(room[samCurrentRow], 'd');
if (samCurrentCol <= enemyCol)
{
room[samCurrentRow][samCurrentCol] = 'X';
isKilled = true;
}
}
return isKilled;
}
private static void EnemyMove(char[][] room)
{
for (int row = 0; row < room.Length; row++)
{
for (int col = 0; col < room[row].Length; col++)
{
var currentValue = room[row][col];
if (currentValue == 'b')
{
if (col < room[row].Length - 1)
{
room[row][col] = '.';
room[row][col + 1] = 'b';
}
else
{
room[row][col] = 'd';
}
break;
}
else if (currentValue == 'd')
{
if (col > 0)
{
room[row][col] = '.';
room[row][col - 1] = 'd';
}
else
{
room[row][col] = 'b';
}
break;
}
}
}
}
}
}
| radoikoff/SoftUni | C Sharp Advanced/Adv 9 The Exam/Task2/Sneaking.cs | C# | mit | 5,315 |
from wodcraft.api import resources
# Routing
def map_routes(api):
api.add_resource(resources.Activity,
'/api/v1.0/activities/<int:id>',
endpoint='activity')
api.add_resource(resources.Activities,
'/api/v1.0/activities',
endpoint='activities')
api.add_resource(resources.Score,
'/api/v1.0/scores/<int:id>',
endpoint='score')
api.add_resource(resources.Scores,
'/api/v1.0/scores',
endpoint='scores')
api.add_resource(resources.Tag,
'/api/v1.0/tags/<int:id>',
endpoint='tag')
api.add_resource(resources.Tags,
'/api/v1.0/tags',
endpoint='tags')
api.add_resource(resources.User,
'/api/v1.0/users/<int:id>',
endpoint='user')
api.add_resource(resources.Users,
'/api/v1.0/users',
endpoint='users')
| the-gigi/wod-craft-server | wodcraft/api/routes.py | Python | mit | 1,064 |
package html
import "fmt"
const (
NodeError NodeType = "error"
NodeText NodeType = "text"
NodeElement NodeType = "element"
NodeComment NodeType = "comment"
)
type NodeType string
type Node struct {
Parent *Node
FirstChild *Node
LastChild *Node
PrevSibling *Node
NextSibling *Node
Type NodeType
Tag string
Attributes map[string]string
TextContent string
}
func (n *Node) String() string {
return fmt.Sprintf(
"{Tag:%q, Parent:%p, FirstChild:%p, LastChild:%p, PrevSibling:%p, NextSibling:%p}",
n.Tag,
n.Parent,
n.FirstChild,
n.LastChild,
n.PrevSibling,
n.NextSibling,
)
}
func (n *Node) AddChild(c *Node) {
c.Parent = c
if n.FirstChild == nil {
n.FirstChild = c
n.LastChild = c
return
}
n.LastChild.NextSibling = c
c.PrevSibling = n.LastChild
n.LastChild = c
}
| lysrt/bro | html/node.go | GO | mit | 829 |
Pony.options = {
via: :smtp,
from: 'HUD Notifier <no-reply@hud-notifier.herokuapp.com>',
via_options: {
address: 'smtp.sendgrid.net',
port: '587',
domain: 'heroku.com',
user_name: ENV['SENDGRID_USERNAME'],
password: ENV['SENDGRID_PASSWORD'],
authentication: :plain,
enable_starttls_auto: true
}
}
| ancorcruz/hud_notifier | lib/hud_notifier/mailer_config.rb | Ruby | mit | 333 |
/*
* The MIT License (MIT)
*
* Copyright (c) 2016-2020, Hamdi Douss
*
* 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.aljebra.scalar.mock;
import com.aljebra.field.Field;
import com.aljebra.scalar.Scalar;
import java.util.Optional;
/**
* Scalar decorator with spying capabilities on the value method calls.
* It holds the last {@link Field} passed when calling value method as an optional. The optional
* is empty if the method was never called.
* @param <T> scalar types
* @since 0.3
*/
public final class SpyScalar<T> implements Scalar<T> {
/**
* An optional holding the last field passed as parameter when calling value method.
* The optional is empty if the method was never called.
*/
private Optional<Field<T>> fld;
/**
* Decorated scalar.
*/
private final Scalar<T> org;
/**
* Ctor.
* @param origin The scalar to decorate.
*/
public SpyScalar(final Scalar<T> origin) {
this.org = origin;
this.fld = Optional.empty();
}
@Override
public T value(final Field<T> field) {
this.fld = Optional.of(field);
return this.org.value(field);
}
/**
* Accessor for the last field passed when calling value method.
* @return Optional containing the field passed when last called value method.
* If the optional is empty, that means the method was never called.
*/
public Optional<Field<T>> field() {
return this.fld;
}
}
| HDouss/jeometry | aljebra/src/test/java/com/aljebra/scalar/mock/SpyScalar.java | Java | mit | 2,523 |
package jeliot.mcode;
/**
* Currently this class is not used in Jeliot 3.
*
* @author Niko Myller
*/
public class Command {
// DOC: document!
/**
*
*/
private int expressionReference = 0;
/**
*
*/
private int type = 0;
/**
*
*/
protected Command() { }
/**
* @param t
* @param er
*/
public Command(int t, int er) {
this.type = t;
this.expressionReference = er;
}
/**
* @param er
*/
public void setExpressionReference(int er) {
this.expressionReference = er;
}
/**
* @param t
*/
public void setType(int t) {
this.type = t;
}
/**
* @return
*/
public int getExpressionReference() {
return this.expressionReference;
}
/**
* @return
*/
public int getType() {
return this.type;
}
} | moegyver/mJeliot | Jeliot/src/jeliot/mcode/Command.java | Java | mit | 899 |
/*
* Copyright 2007 ZXing authors
*
* 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 com.google.zxing.common.reedsolomon;
/**
* <p>Implements Reed-Solomon decoding, as the name implies.</p>
* <p/>
* <p>The algorithm will not be explained here, but the following references were helpful
* in creating this implementation:</p>
* <p/>
* <ul>
* <li>Bruce Maggs.
* <a href="http://www.cs.cmu.edu/afs/cs.cmu.edu/project/pscico-guyb/realworld/www/rs_decode.ps">
* "Decoding Reed-Solomon Codes"</a> (see discussion of Forney's Formula)</li>
* <li>J.I. Hall. <a href="www.mth.msu.edu/~jhall/classes/codenotes/GRS.pdf">
* "Chapter 5. Generalized Reed-Solomon Codes"</a>
* (see discussion of Euclidean algorithm)</li>
* </ul>
* <p/>
* <p>Much credit is due to William Rucklidge since portions of this code are an indirect
* port of his C++ Reed-Solomon implementation.</p>
*
* @author Sean Owen
* @author William Rucklidge
* @author sanfordsquires
*/
public final class ReedSolomonDecoder {
private final GenericGF field;
public ReedSolomonDecoder(GenericGF field) {
this.field = field;
}
/**
* <p>Decodes given set of received codewords, which include both data and error-correction
* codewords. Really, this means it uses Reed-Solomon to detect and correct errors, in-place,
* in the input.</p>
*
* @param received data and error-correction codewords
* @param twoS number of error-correction codewords available
* @throws ReedSolomonException if decoding fails for any reason
*/
public void decode(int[] received, int twoS) throws ReedSolomonException {
GenericGFPoly poly = new GenericGFPoly(field, received);
int[] syndromeCoefficients = new int[twoS];
boolean noError = true;
for (int i = 0; i < twoS; i++) {
int eval = poly.evaluateAt(field.exp(i + field.getGeneratorBase()));
syndromeCoefficients[syndromeCoefficients.length - 1 - i] = eval;
if (eval != 0) {
noError = false;
}
}
if (noError) {
return;
}
GenericGFPoly syndrome = new GenericGFPoly(field, syndromeCoefficients);
GenericGFPoly[] sigmaOmega =
runEuclideanAlgorithm(field.buildMonomial(twoS, 1), syndrome, twoS);
GenericGFPoly sigma = sigmaOmega[0];
GenericGFPoly omega = sigmaOmega[1];
int[] errorLocations = findErrorLocations(sigma);
int[] errorMagnitudes = findErrorMagnitudes(omega, errorLocations);
for (int i = 0; i < errorLocations.length; i++) {
int position = received.length - 1 - field.log(errorLocations[i]);
if (position < 0) {
throw new ReedSolomonException("Bad error location");
}
received[position] = GenericGF.addOrSubtract(received[position], errorMagnitudes[i]);
}
}
public GenericGFPoly[] runEuclideanAlgorithm(GenericGFPoly a, GenericGFPoly b, int R)
throws ReedSolomonException {
// Assume a's degree is >= b's
if (a.getDegree() < b.getDegree()) {
GenericGFPoly temp = a;
a = b;
b = temp;
}
GenericGFPoly rLast = a;
GenericGFPoly r = b;
GenericGFPoly tLast = field.getZero();
GenericGFPoly t = field.getOne();
// Run Euclidean algorithm until r's degree is less than R/2
while (r.getDegree() >= R / 2) {
GenericGFPoly rLastLast = rLast;
GenericGFPoly tLastLast = tLast;
rLast = r;
tLast = t;
// Divide rLastLast by rLast, with quotient in q and remainder in r
if (rLast.isZero()) {
// Oops, Euclidean algorithm already terminated?
throw new ReedSolomonException("r_{i-1} was zero");
}
r = rLastLast;
GenericGFPoly q = field.getZero();
int denominatorLeadingTerm = rLast.getCoefficient(rLast.getDegree());
int dltInverse = field.inverse(denominatorLeadingTerm);
while (r.getDegree() >= rLast.getDegree() && !r.isZero()) {
int degreeDiff = r.getDegree() - rLast.getDegree();
int scale = field.multiply(r.getCoefficient(r.getDegree()), dltInverse);
q = q.addOrSubtract(field.buildMonomial(degreeDiff, scale));
r = r.addOrSubtract(rLast.multiplyByMonomial(degreeDiff, scale));
}
t = q.multiply(tLast).addOrSubtract(tLastLast);
if (r.getDegree() >= rLast.getDegree()) {
throw new IllegalStateException("Division algorithm failed to reduce polynomial?");
}
}
int sigmaTildeAtZero = t.getCoefficient(0);
if (sigmaTildeAtZero == 0) {
throw new ReedSolomonException("sigmaTilde(0) was zero");
}
int inverse = field.inverse(sigmaTildeAtZero);
GenericGFPoly sigma = t.multiply(inverse);
GenericGFPoly omega = r.multiply(inverse);
return new GenericGFPoly[]{sigma, omega};
}
private int[] findErrorLocations(GenericGFPoly errorLocator) throws ReedSolomonException {
// This is a direct application of Chien's search
int numErrors = errorLocator.getDegree();
if (numErrors == 1) { // shortcut
return new int[]{errorLocator.getCoefficient(1)};
}
int[] result = new int[numErrors];
int e = 0;
for (int i = 1; i < field.getSize() && e < numErrors; i++) {
if (errorLocator.evaluateAt(i) == 0) {
result[e] = field.inverse(i);
e++;
}
}
if (e != numErrors) {
throw new ReedSolomonException("Error locator degree does not match number of roots");
}
return result;
}
private int[] findErrorMagnitudes(GenericGFPoly errorEvaluator, int[] errorLocations) {
// This is directly applying Forney's Formula
int s = errorLocations.length;
int[] result = new int[s];
for (int i = 0; i < s; i++) {
int xiInverse = field.inverse(errorLocations[i]);
int denominator = 1;
for (int j = 0; j < s; j++) {
if (i != j) {
//denominator = field.multiply(denominator,
// GenericGF.addOrSubtract(1, field.multiply(errorLocations[j], xiInverse)));
// Above should work but fails on some Apple and Linux JDKs due to a Hotspot bug.
// Below is a funny-looking workaround from Steven Parkes
int term = field.multiply(errorLocations[j], xiInverse);
int termPlus1 = (term & 0x1) == 0 ? term | 1 : term & ~1;
denominator = field.multiply(denominator, termPlus1);
}
}
result[i] = field.multiply(errorEvaluator.evaluateAt(xiInverse),
field.inverse(denominator));
if (field.getGeneratorBase() != 0) {
result[i] = field.multiply(result[i], xiInverse);
}
}
return result;
}
}
| yakovenkodenis/Discounty | src/main/java/com/google/zxing/common/reedsolomon/ReedSolomonDecoder.java | Java | mit | 7,749 |
<?php
$passEnc = '$2y$06$wRkrmRT6gm8g0CqcKnrWYOrLke6waZva11sqfv4RkjuCXCjG0qI56';
$user = 'admin';
?>
| jplsek/Basic-CMS-Project | cms/key.php | PHP | mit | 103 |
package us.corenetwork.tradecraft;
import net.minecraft.server.v1_10_R1.Item;
import net.minecraft.server.v1_10_R1.ItemStack;
import net.minecraft.server.v1_10_R1.MerchantRecipe;
import net.minecraft.server.v1_10_R1.NBTTagCompound;
/**
* Created by Matej on 5.3.2014.
*/
public class CustomRecipe extends MerchantRecipe
{
private int tradeID = 0; //trade id per villager
private boolean locked = false;
private int tier = 0;
private int tradesLeft = 0;
private int tradesPerformed = 0;
private boolean isNew = false;
private boolean needsSaving = false;
public CustomRecipe(ItemStack itemStack, ItemStack itemStack2, ItemStack itemStack3) {
super(itemStack, itemStack2, itemStack3);
}
public CustomRecipe(ItemStack itemStack, ItemStack itemStack2) {
super(itemStack, itemStack2);
}
public CustomRecipe(ItemStack itemStack, Item item) {
super(itemStack, item);
}
/**
* Returns if trade is locked (cannot be traded)
*/
@Override
public boolean h() {
return locked || tradesLeft <= 0;
}
public void lockManually()
{
locked = true;
}
public void removeManualLock()
{
locked = false;
}
public int getTier() {
return tier;
}
public void setTier(int tier) {
this.tier = tier;
}
public int getTradesLeft() {
return tradesLeft;
}
public void setTradesLeft(int tradesLeft) {
this.tradesLeft = tradesLeft;
}
public int getTradesPerformed()
{
return tradesPerformed;
}
public void setTradesPerformed(int tradesPerformed)
{
this.tradesPerformed = tradesPerformed;
}
public CustomRecipe(NBTTagCompound nbtTagCompound) {
super(nbtTagCompound);
}
public int getTradeID()
{
return tradeID;
}
public void setTradeID(int id)
{
tradeID = id;
}
public void useTrade()
{
setTradesLeft(this.getTradesLeft() - 1);
setTradesPerformed(this.getTradesPerformed() + 1);
needsSaving = true;
}
public void restock()
{
setTradesLeft(Villagers.getDefaultNumberOfTrades());
needsSaving = true;
}
public void setShouldSave(boolean b)
{
needsSaving = false;
}
public boolean shouldSave()
{
return needsSaving;
}
public boolean getIsNew()
{
return isNew;
}
public void setIsNew(boolean value)
{
isNew = value;
}
}
| Kongolan/TradeCraft | src/us/corenetwork/tradecraft/CustomRecipe.java | Java | mit | 2,230 |
package com.tom.util;
import java.util.List;
import net.minecraft.block.Block;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.IRecipe;
import net.minecraftforge.fluids.FluidStack;
import com.tom.api.research.Research;
import com.tom.recipes.handler.AdvancedCraftingHandler.CraftingLevel;
public class RecipeData {
public RecipeData(FluidStack f1, FluidStack f2, FluidStack f3, FluidStack f4, int energy, int inputAmount) {
this.f1 = f1;
this.f2 = f2;
this.f3 = f3;
this.f4 = f4;
this.energy = energy;
this.inputAmount = inputAmount;
this.processTime = 1;
}
public RecipeData(Block block2, Block output) {
this.output = output;
this.block2 = block2;
this.processTime = 1;
}
public RecipeData(Block block2, Block output, Item invItem1) {
this.output = output;
this.block2 = block2;
this.invItem1 = invItem1;
this.hasInv = true;
this.processTime = 1;
}
public RecipeData(FluidStack f, int energy, int amount) {
this.f1 = f;
this.energy = energy;
this.inputAmount = amount;
this.processTime = 1;
}
public RecipeData(FluidStack f, int energy, int amount, int processTime) {
this.f1 = f;
this.energy = energy;
this.inputAmount = amount;
this.processTime = processTime;
}
public RecipeData(ItemStack i, int energy, int amount, int processTime) {
this.itemstack1 = i;
this.energy = energy;
this.inputAmount = amount;
this.processTime = processTime;
}
public RecipeData(ItemStack is, int time, ItemStack[] isIn, List<Research> researchList, boolean shaped, ItemStack isExtra, CraftingLevel level) {
this.processTime = time;
this.requiredResearches = researchList;
this.itemstack1 = isIn[0];
this.itemstack2 = isIn[1];
this.itemstack3 = isIn[2];
this.itemstack4 = isIn[3];
this.itemstack5 = isIn[4];
this.itemstack6 = isIn[5];
this.itemstack7 = isIn[6];
this.itemstack8 = isIn[7];
this.itemstack9 = isIn[8];
this.itemstack0 = is;
this.itemstack10 = isExtra;
this.shaped = shaped;
this.level = level;
}
public RecipeData(ItemStack itemstack0, ItemStack itemstack1) {
this.itemstack0 = itemstack0;
this.itemstack1 = itemstack1;
}
public RecipeData(int energy, ItemStack itemstack0, ItemStack itemstack1) {
this.energy = energy;
this.itemstack0 = itemstack0;
this.itemstack1 = itemstack1;
}
public RecipeData(ItemStack itemstack0, ItemStack itemstack1, ItemStack itemstack2) {
this.itemstack0 = itemstack0;
this.itemstack1 = itemstack1;
this.itemstack2 = itemstack2;
}
public RecipeData(ItemStack itemstack0, ItemStack itemstack1, ItemStack itemstack2, boolean mode) {
this.itemstack0 = itemstack0;
this.itemstack1 = itemstack1;
this.itemstack2 = itemstack2;
this.hasInv = mode;
}
public RecipeData(IRecipe recipe, int time, List<Research> researchList, ItemStack extra, CraftingLevel level, int extraD, String rid) {
this.processTime = time;
this.requiredResearches = researchList;
this.recipe = recipe;
this.itemstack10 = extra;
this.level = level;
this.energy = extraD;
this.id = rid;
}
public RecipeData(FluidStack f1, FluidStack f2, int energy, int inputAmount) {
this.f1 = f1;
this.f2 = f2;
this.energy = energy;
this.inputAmount = inputAmount;
this.processTime = 1;
}
public FluidStack f1;
public FluidStack f2;
public FluidStack f3;
public FluidStack f4;
public int energy;
public int inputAmount;
public Block block2;
public Block output;
public Item invItem1;
public Item invItem2;
public Item invItem3;
public Item invItem4;
public Item invReturn1;
public Item invReturn2;
public boolean hasInv;
public int processTime;
public ItemStack itemstack0;
public ItemStack itemstack1;
public ItemStack itemstack2;
public ItemStack itemstack3;
public ItemStack itemstack4;
public ItemStack itemstack5;
public ItemStack itemstack6;
public ItemStack itemstack7;
public ItemStack itemstack8;
public ItemStack itemstack9;
public ItemStack itemstack10;
public List<Research> requiredResearches;
public boolean shaped;
public CraftingLevel level;
public IRecipe recipe;
public String id;
public RecipeData setId(String id) {
this.id = id;
return this;
}
}
| tom5454/Toms-Mod | src/main/java/com/tom/util/RecipeData.java | Java | mit | 4,212 |
using ShopifySharp.Filters;
using System;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
namespace ShopifySharp.Tests
{
[Trait("Category", "InventoryLevel")]
public class InventoryLevel_Tests : IClassFixture<InventoryLevel_Tests_Fixture>
{
private InventoryLevel_Tests_Fixture Fixture { get; }
public InventoryLevel_Tests(InventoryLevel_Tests_Fixture fixture)
{
this.Fixture = fixture;
}
[Fact]
public async Task Lists_Items()
{
var list = await Fixture.Service.ListAsync(new InventoryLevelFilter { InventoryItemIds = new[] { Fixture.InventoryItemId } });
Assert.True(list.Count() > 0);
}
[Fact]
public async Task Creates_InventoryLevel()
{
var created = await Fixture.Create();
Assert.NotNull(created);
}
[Fact]
public async Task Updates_InventoryLevel()
{
var invLevel = (await Fixture.Service.ListAsync(new InventoryLevelFilter
{
InventoryItemIds = new long[] { Fixture.InventoryItemId }
})).First();
Random newRandom = new Random();
int newQty, currQty;
newQty = currQty = invLevel.Available ?? 0;
while (newQty == currQty)
{
invLevel.Available = newQty = newRandom.Next(5, 55);
}
var updated = await Fixture.Service.SetAsync(invLevel, true);
Assert.Equal(newQty, updated.Available);
Assert.NotEqual(currQty, updated.Available);
}
[Fact]
public async Task Adjust_InventoryLevel()
{
var availableAdjustment = 1;
var invLevel = (await Fixture.Service.ListAsync(new InventoryLevelFilter
{
InventoryItemIds = new long[] { Fixture.InventoryItemId }
})).First();
var adjustInventoryLevel = new InventoryLevelAdjust()
{
AvailableAdjustment = availableAdjustment,
InventoryItemId = invLevel.InventoryItemId,
LocationId = invLevel.LocationId
};
int newQty, currQty;
currQty = invLevel.Available ?? 0;
newQty = currQty + availableAdjustment;
var updated = await Fixture.Service.AdjustAsync(adjustInventoryLevel);
Assert.Equal(newQty, updated.Available);
Assert.NotEqual(currQty, updated.Available);
}
[Fact(Skip = "Test appears to be broken in mysterious ways, with Shopify returning a 500 internal server error")]
public async Task Deletes_InventoryLevel()
{
var currentInvLevel = (await Fixture.Service.ListAsync(new InventoryLevelFilter { InventoryItemIds = new[] { Fixture.InventoryItemId } })).First();
//When switching from the default location to a Fulfillment location, the default InventoryLevel is deleted
var created = await Fixture.Create();
//Set inventory back to original location because a location is required
await Fixture.Service.SetAsync(currentInvLevel, true);
bool threw = false;
try
{
await Fixture.Service.DeleteAsync(created.InventoryItemId.Value, created.LocationId.Value);
}
catch (ShopifyException ex)
{
Console.WriteLine($"{nameof(Deletes_InventoryLevel)} failed. {ex.Message}");
threw = true;
}
Assert.False(threw);
//Delete will not throw an error but still will not delete if there isn't another location available for the product.
Assert.Equal(0, (await Fixture.Service.ListAsync(new InventoryLevelFilter { InventoryItemIds = new[] { created.InventoryItemId.Value }, LocationIds = new[] { created.LocationId.Value } })).Count());
}
}
public class InventoryLevel_Tests_Fixture : IAsyncLifetime
{
public InventoryLevelService Service { get; } = new InventoryLevelService(Utils.MyShopifyUrl, Utils.AccessToken);
public Product_Tests_Fixture ProductTest { get; } = new Product_Tests_Fixture();
public ProductVariant_Tests_Fixture VariantTest { get; } = new ProductVariant_Tests_Fixture();
public FulfillmentService_Tests_Fixture FulfillmentServiceServTest { get; } = new FulfillmentService_Tests_Fixture();
public long InventoryItemId { get; set; }
public async Task InitializeAsync()
{
// Get a product id to use with these tests.
var prod = await ProductTest.Create();
VariantTest.ProductId = prod.Id.Value;
var variant = prod.Variants.First();
InventoryItemId = variant.InventoryItemId.Value;
variant.SKU = "TestSKU";//To change fulfillment, SKU is required
variant.InventoryManagement = "Shopify";//To set inventory, InventoryManagement must be Shopify
await VariantTest.Service.UpdateAsync(variant.Id.Value, variant);
}
public async Task DisposeAsync()
{
await VariantTest.DisposeAsync();
await ProductTest.DisposeAsync();
await FulfillmentServiceServTest.DisposeAsync();
}
/// <summary>
/// Convenience function for running tests. Creates an object and automatically adds it to the queue for deleting after tests finish.
/// </summary>
public async Task<InventoryLevel> Create(bool skipAddToCreateList = false)
{
var locId = (await FulfillmentServiceServTest.Create(skipAddToCreateList)).LocationId.Value;
return await Service.ConnectAsync(InventoryItemId, locId, true);
}
}
} | addsb/ShopifySharp | ShopifySharp.Tests/InventoryLevel_Tests.cs | C# | mit | 5,840 |
//This file makes it easier to import everything from the common folder
export * from './Button';
export * from './Card';
export * from './CardSection';
export * from './Header';
export * from './Input';
export * from './Spinner';
export * from './Confirm';
| srserx/react-native-ui-common | index.js | JavaScript | mit | 259 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Filename : video.py
# Author : Kim K
# Created : Fri, 29 Jan 2016
# Last Modified : Sun, 31 Jan 2016
from sys import exit as Die
try:
import sys
import cv2
from colordetection import ColorDetector
except ImportError as err:
Die(err)
class Webcam:
def __init__(self):
self.cam = cv2.VideoCapture(0)
self.stickers = self.get_sticker_coordinates('main')
self.current_stickers = self.get_sticker_coordinates('current')
self.preview_stickers = self.get_sticker_coordinates('preview')
def get_sticker_coordinates(self, name):
"""
Every array has 2 values: x and y.
Grouped per 3 since on the cam will be
3 rows of 3 stickers.
:param name: the requested color type
:returns: list
"""
stickers = {
'main': [
[200, 120], [300, 120], [400, 120],
[200, 220], [300, 220], [400, 220],
[200, 320], [300, 320], [400, 320]
],
'current': [
[20, 20], [54, 20], [88, 20],
[20, 54], [54, 54], [88, 54],
[20, 88], [54, 88], [88, 88]
],
'preview': [
[20, 130], [54, 130], [88, 130],
[20, 164], [54, 164], [88, 164],
[20, 198], [54, 198], [88, 198]
]
}
return stickers[name]
def draw_main_stickers(self, frame):
"""Draws the 9 stickers in the frame."""
for x,y in self.stickers:
cv2.rectangle(frame, (x,y), (x+30, y+30), (255,255,255), 2)
def draw_current_stickers(self, frame, state):
"""Draws the 9 current stickers in the frame."""
for index,(x,y) in enumerate(self.current_stickers):
cv2.rectangle(frame, (x,y), (x+32, y+32), ColorDetector.name_to_rgb(state[index]), -1)
def draw_preview_stickers(self, frame, state):
"""Draws the 9 preview stickers in the frame."""
for index,(x,y) in enumerate(self.preview_stickers):
cv2.rectangle(frame, (x,y), (x+32, y+32), ColorDetector.name_to_rgb(state[index]), -1)
def color_to_notation(self, color):
"""
Return the notation from a specific color.
We want a user to have green in front, white on top,
which is the usual.
:param color: the requested color
"""
notation = {
'green' : 'F',
'white' : 'U',
'blue' : 'B',
'red' : 'R',
'orange' : 'L',
'yellow' : 'D'
}
return notation[color]
def scan(self):
"""
Open up the webcam and scans the 9 regions in the center
and show a preview in the left upper corner.
After hitting the space bar to confirm, the block below the
current stickers shows the current state that you have.
This is show every user can see what the computer toke as input.
:returns: dictionary
"""
sides = {}
preview = ['white','white','white',
'white','white','white',
'white','white','white']
state = [0,0,0,
0,0,0,
0,0,0]
while True:
_, frame = self.cam.read()
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
key = cv2.waitKey(10) & 0xff
# init certain stickers.
self.draw_main_stickers(frame)
self.draw_preview_stickers(frame, preview)
for index,(x,y) in enumerate(self.stickers):
roi = hsv[y:y+32, x:x+32]
avg_hsv = ColorDetector.average_hsv(roi)
color_name = ColorDetector.get_color_name(avg_hsv)
state[index] = color_name
# update when space bar is pressed.
if key == 32:
preview = list(state)
self.draw_preview_stickers(frame, state)
face = self.color_to_notation(state[4])
notation = [self.color_to_notation(color) for color in state]
sides[face] = notation
# show the new stickers
self.draw_current_stickers(frame, state)
# append amount of scanned sides
text = 'scanned sides: {}/6'.format(len(sides))
cv2.putText(frame, text, (20, 460), cv2.FONT_HERSHEY_TRIPLEX, 0.5, (255,255,255), 1, cv2.LINE_AA)
# quit on escape.
if key == 27:
break
# show result
cv2.imshow("default", frame)
self.cam.release()
cv2.destroyAllWindows()
return sides if len(sides) == 6 else False
webcam = Webcam()
| muts/qbr | src/video.py | Python | mit | 4,872 |
import React from 'react';
import Example from './Example';
import Icon from '../../src/Icon';
import Button from '../../src/Button';
import IconButton from '../../src/IconButton';
import FABButton from '../../src/FABButton';
export default ( props ) => (
<section { ...props }>
<h3>Buttons</h3>
<Example>
<FABButton colored>
<Icon name="add" />
</FABButton>
<FABButton colored ripple>
<Icon name="add" />
</FABButton>
</Example>
<Example>
<FABButton>
<Icon name="add" />
</FABButton>
<FABButton ripple>
<Icon name="add" />
</FABButton>
<FABButton disabled>
<Icon name="add" />
</FABButton>
</Example>
<Example>
<Button raised>Button</Button>
<Button raised ripple>Button</Button>
<Button raised disabled>Button</Button>
</Example>
<Example>
<Button raised colored>Button</Button>
<Button raised accent>Button</Button>
<Button raised accent ripple>Button</Button>
</Example>
<Example>
<Button>Button</Button>
<Button ripple>Button</Button>
<Button disabled>Button</Button>
</Example>
<Example>
<Button primary colored>Button</Button>
<Button accent>Button</Button>
</Example>
<Example>
<IconButton name="mood" />
<IconButton colored name="mood" />
</Example>
<Example>
<FABButton mini>
<Icon name="add" />
</FABButton>
<FABButton colored mini>
<Icon name="add" />
</FABButton>
</Example>
</section>
);
| joshq00/react-mdl | demo/sections/Buttons.js | JavaScript | mit | 1,885 |
using System.Collections;
namespace System.ComponentModel.DataAnnotations
{
public class EnsureMinimumElementsAttribute : ValidationAttribute
{
private readonly int _minElements;
public EnsureMinimumElementsAttribute(int minElements)
{
_minElements = minElements;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
return (((IList)value).Count >= _minElements) ? ValidationResult.Success : new ValidationResult(base.ErrorMessage);
}
}
}
| orbital7/orbital7.extensions | src/Orbital7.Extensions.Attributes/EnsureMinimumElementsAttribute.cs | C# | mit | 583 |
//
// Copyright (c) 2017 Advanced Micro Devices, Inc. All rights reserved.
//
// 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.
//
/*
* File manipulation helper functions.
*/
#include "misc/debug.h"
#include "misc/io.h"
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#ifdef _WIN32
#include <Windows.h>
#else
#include <dirent.h>
#include <unistd.h>
#endif
/** Creates a new sub-directory in the process' working directory.
*
* @param name Name of the folder to create.
*
* @return true if the operation succeeded, false otherwise.
**/
bool Anvil::IO::create_directory(std::string name)
{
#ifdef _WIN32
wchar_t buffer[32767]; /* as per MSDN documentation */
std::wstring buffer_string;
std::wstring full_path_wide;
std::wstring name_wide = std::wstring(name.begin(), name.end() );
std::string prefix = std::string ("\x5C\x5C?\x5C");
std::wstring prefix_wide = std::wstring(prefix.begin(), prefix.end() );
/* CreateDirectory*() require us to pass the full path to the directory
* we want to create. Form a string that contains this data. */
memset(buffer,
0,
sizeof(buffer) );
GetCurrentDirectoryW(sizeof(buffer),
buffer);
buffer_string = std::wstring(buffer);
full_path_wide = prefix_wide + buffer + std::wstring(L"\\") + name_wide;
return (CreateDirectoryW(full_path_wide.c_str(),
nullptr /* lpSecurityAttributes */) != 0);
#else
std::string absolute_path;
{
const int max_size = 1000;
char buffer[max_size];
/* mkdir() require us to pass the full path to the directory
* we want to create. Form a string that contains this data. */
memset(buffer, 0, max_size);
if (nullptr == getcwd(buffer, max_size))
{
anvil_assert(false);
}
absolute_path = std::string(buffer);
if (*absolute_path.rbegin() != '/')
absolute_path.append("/");
absolute_path += name;
}
struct stat st;
bool status = true;
if (stat(absolute_path.c_str(), &st) != 0)
{
if(mkdir(absolute_path.c_str(), 0777) != 0)
{
status = false;
}
}
else if (!S_ISDIR(st.st_mode))
{
status = false;
}
if (status == false)
{
anvil_assert(false);
}
return status;
#endif
}
/** Deletes a file in the working directory.
*
* @param filename Name of the file to remove.
**/
void Anvil::IO::delete_file(std::string filename)
{
remove(filename.c_str());
}
/* Please see header for specification */
bool Anvil::IO::enumerate_files_in_directory(const std::string& path,
std::vector<std::string>* out_result_ptr)
{
bool result = false;
#ifdef _WIN32
{
HANDLE file_finder(INVALID_HANDLE_VALUE);
WIN32_FIND_DATAW find_data;
const std::string path_expanded (path + "//*");
const std::wstring path_expanded_wide(path_expanded.begin(), path_expanded.end() );
if ( (file_finder = ::FindFirstFileW(path_expanded_wide.c_str(),
&find_data)) == INVALID_HANDLE_VALUE)
{
goto end;
}
do
{
if (find_data.dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE)
{
std::wstring file_name_wide(find_data.cFileName);
std::string file_name (file_name_wide.begin(), file_name_wide.end() );
out_result_ptr->push_back(file_name);
}
}
while (::FindNextFileW(file_finder,
&find_data) );
if (file_finder != INVALID_HANDLE_VALUE)
{
::FindClose(file_finder);
result = true;
}
}
#else
{
struct dirent* dir_ptr = nullptr;
DIR* file_finder = nullptr;
file_finder = opendir(path.c_str() );
if (file_finder != nullptr)
{
while ( (dir_ptr = readdir(file_finder) ) != nullptr)
{
out_result_ptr->push_back(dir_ptr->d_name);
}
closedir(file_finder);
result = true;
}
}
#endif
#ifdef _WIN32
end:
#endif
return result;
}
/* Please see header for specification */
bool Anvil::IO::is_directory(const std::string& path)
{
bool result = false;
struct stat stat_data = {0};
if ((stat(path.c_str(),
&stat_data) == 0) &&
(stat_data.st_mode & S_IFMT) == S_IFDIR)
{
result = true;
}
return result;
}
/** Reads contents of a file with user-specified name and returns it to the caller.
*
* @param filename Name of the file to use for the operation.
* @param is_text_file true if the file should be treated as a text file; false
* if it should be considered a binary file.
* @param out_result_ptr Deref will be set to an array, holding the read file contents.
* The array must be deleted with a delete[] operator when no
* longer needed. Must not be nullptr.
* @param out_opt_size_ptr Deref will be set to the number of bytes allocated for @param out_result_ptr.
* May be nullptr.
**/
void Anvil::IO::read_file(std::string filename,
bool is_text_file,
char** out_result_ptr,
size_t* out_opt_size_ptr)
{
FILE* file_handle = nullptr;
size_t file_size = 0;
char* result = nullptr;
file_handle = fopen(filename.c_str(),
(is_text_file) ? "rt" : "rb");
anvil_assert(file_handle != 0);
fseek(file_handle,
0,
SEEK_END);
file_size = static_cast<size_t>(ftell(file_handle) );
anvil_assert(file_size != -1 &&
file_size != 0);
fseek(file_handle,
0,
SEEK_SET);
result = new char[file_size + 1];
anvil_assert(result != nullptr);
memset(result,
0,
file_size + 1);
size_t n_bytes_read = fread(result,
1,
file_size,
file_handle);
fclose(file_handle);
result[n_bytes_read] = 0;
/* Set the output variables */
*out_result_ptr = result;
if (out_opt_size_ptr != nullptr)
{
*out_opt_size_ptr = file_size;
}
}
/** Please see header for specification */
void Anvil::IO::write_binary_file(std::string filename,
const void* data,
unsigned int data_size,
bool should_append)
{
FILE* file_handle = nullptr;
file_handle = fopen(filename.c_str(),
(should_append) ? "ab" : "wb");
anvil_assert(file_handle != 0);
if (fwrite(data,
data_size,
1, /* count */
file_handle) != 1)
{
anvil_assert(false);
}
fclose(file_handle);
}
/** Please see header for specification */
void Anvil::IO::write_text_file(std::string filename,
std::string contents,
bool should_append)
{
FILE* file_handle = nullptr;
file_handle = fopen(filename.c_str(),
(should_append) ? "a" : "wt");
anvil_assert(file_handle != 0);
if (fwrite(contents.c_str(),
strlen(contents.c_str() ),
1, /* count */
file_handle) != 1)
{
anvil_assert(false);
}
fclose(file_handle);
}
| baxtea/Anvil | src/misc/io.cpp | C++ | mit | 8,936 |
var async = require('async');
function _hasher() {
return "_";
}
function accessor(idx) {
return (this.memo._ || [])[idx];
};
module.exports = function mymoize(fn) {
var memoized = async.memoize(fn, _hasher);
memoized.getErr = accessor.bind(memoized, 0);
memoized.getRes = accessor.bind(memoized, 1);
return memoized;
}
| adrienjoly/npm-mymoize | index.js | JavaScript | mit | 335 |
module Sinkhole
module Commands
class Help < Command
def do_process
Responses::HelpMessage.new(":(... y u no smtp?")
end
end
end
end | andrewstucki/sinkhole | lib/sinkhole/commands/help.rb | Ruby | mit | 164 |
using System;
namespace _03.Mankind
{
public abstract class Human
{
private string firstName;
private string lastName;
protected Human(string firstName, string lastName)
{
this.FirstName = firstName;
this.LastName = lastName;
}
public string FirstName
{
get { return this.firstName; }
set
{
var firstLetter = char.Parse(value.Substring(0, 1));
if (!char.IsUpper(firstLetter))
{
throw new ArgumentException("Expected upper case letter! Argument: firstName");
}
if (value.Length < 4)
{
throw new ArgumentException("Expected length at least 4 symbols! Argument: firstName");
}
this.firstName = value;
}
}
public string LastName
{
get { return this.lastName; }
set
{
var firstLetter = char.Parse(value.Substring(0, 1));
if (!char.IsUpper(firstLetter))
{
throw new ArgumentException("Expected upper case letter! Argument: lastName");
}
if (value.Length < 3)
{
throw new ArgumentException("Expected length at least 3 symbols! Argument: lastName");
}
this.lastName = value;
}
}
}
}
| George221b/SoftUni-Tasks | C#OOP-Basics/03.Inheritance-Exercise/03.Mankind/Human.cs | C# | mit | 1,540 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// La información general sobre un ensamblado se controla mediante el siguiente
// conjunto de atributos. Cambie estos atributos para modificar la información
// asociada con un ensamblado.
[assembly: AssemblyTitle("Slack.ServiceLibrary")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Slack.ServiceLibrary")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Si establece ComVisible como false, los tipos de este ensamblado no estarán visibles
// para los componentes COM. Si necesita obtener acceso a un tipo de este ensamblado desde
// COM, establezca el atributo ComVisible como true en este tipo.
[assembly: ComVisible(false)]
// El siguiente GUID sirve como identificador de typelib si este proyecto se expone a COM
[assembly: Guid("ea97ed70-cfb4-4bb0-8619-0061c5d33b11")]
// La información de versión de un ensamblado consta de los cuatro valores siguientes:
//
// Versión principal
// Versión secundaria
// Número de compilación
// Revisión
//
// Puede especificar todos los valores o establecer como predeterminados los números de compilación y de revisión
// mediante el carácter '*', como se muestra a continuación:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| nikeyes/SlackClient | Slack.ServiceLibrary/Properties/AssemblyInfo.cs | C# | mit | 1,558 |
// Karma configuration
// Generated on Fri Jul 05 2013 01:57:57 GMT-0400 (EDT)
/*global basePath:true, exclude:true, reporters:true, files:true*/
/*global coverageReporter:true, junitReporter:true, reporters:true,
preprocessors:true, frameworks:true*/
/*global port:true, runnerPort:true, colors:true, logLevel:true*/
/*global autoWatch:true, browsers:true, captureTimeout:true, singleRun:true*/
/*global JASMINE:true, JASMINE_ADAPTER:true, REQUIRE:true, REQUIRE_ADAPTER:true*/
/*global LOG_INFO:true*/
module.exports = function(config) {
config.set({
// base path, that will be used to resolve files and exclude
// basePath: 'tmp/public',
basePath: '',
// list of files / patterns to load in the browser
files: [
{pattern: 'libs/jquery/jquery.js', included: false},
{pattern: 'libs/requirejs/require.js', included: false},
{pattern: 'src/*.js', included: false},
{pattern: 'test/spec/*-spec.js', included: false},
// helpers & fixtures for jasmine-jquery
{ pattern: 'test/helpers/*.js', included: true },
'test/test-main.js',
],
frameworks: ['jasmine', 'requirejs'],
plugins: [
'karma-jasmine',
'karma-requirejs',
'karma-coverage',
'karma-phantomjs-launcher',
'karma-chrome-launcher',
'karma-firefox-launcher',
'karma-safari-launcher'
],
preprocessors: {
'**/src/*.js': 'coverage'
},
// list of files to exclude
exclude: [],
// test results reporter to use
// possible values: 'dots', 'progress', 'junit'
reporters: 'coverage',
coverageReporter: {
type : ['text'],
dir : '.coverage/'
// type: 'cobertura',
// dir: 'coverage/',
// file: 'coverage.xml'
},
// web server port
port: 9871,
// cli runner port
runnerPort: 9130,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
logLevel: config.LOG_DEBUG,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
browsers: ['Chrome'],
// If browser does not capture in given timeout [ms], kill it
captureTimeout: 60000,
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: false
});
}; | goliatone/gmodule | karma.conf.js | JavaScript | mit | 2,909 |
var Promise = require('ia-promise');
var XHRPromise = require('./XHRPromise');
var CommandPromise = require('./CommandPromise');
var ProfilePromise = require('./ProfilePromise');
var ViewPromise = require('./ViewPromise');
var FutureViewPromise = require('./FutureViewPromise');
var RoomPromise = require('./RoomPromise');
function RoomsPromise(app, name) {
// Calling parent constructor
ViewPromise.call(this, app, name);
// Registering UI elements
this.tbody = document.querySelector('tbody'),
this.trTpl = this.tbody.firstChild;
this.tbody.removeChild(this.trTpl);
}
RoomsPromise.prototype = Object.create(ViewPromise.prototype);
RoomsPromise.prototype.reset = function () {
while(this.tbody.firstChild) {
this.tbody.removeChild(this.tbody.firstChild);
}
};
RoomsPromise.prototype.hide = function () {
this.reset();
this.tbody.appendChild(this.trTpl);
};
RoomsPromise.prototype.loop = function (timeout) {
var _this = this;
// roooms update
function getRoomsUpdatePromise() {
return new XHRPromise('GET', '/rooms.json', true).then(function(xhr){
_this.reset();
var rooms = JSON.parse(xhr.responseText);
rooms.forEach(function(room) {
var tr = _this.trTpl.cloneNode(true);
tr.firstChild.firstChild.setAttribute('href',
_this.trTpl.firstChild.firstChild.getAttribute('href') + room.id);
if(room.state)
tr.firstChild.firstChild.setAttribute('disabled','disabled');
tr.firstChild.firstChild.firstChild.textContent = room.name;
tr.childNodes[1].firstChild.textContent = room.players + '/6';
tr.childNodes[2].firstChild.textContent = room.mode;
_this.tbody.appendChild(tr);
});
});
}
return Promise.all(
_this.app.user && _this.app.user.name ?
Promise.sure() :
new ProfilePromise(_this.app, 'Profile', true),
getRoomsUpdatePromise()
).then(function() {
_this.display();
return Promise.any(
// Handling channel join
new CommandPromise(_this.app.cmdMgr, 'join', _this.name).then(function(data) {
return new RoomPromise(_this.app, 'Room', data.params.room);
}),
// Handling channel list refresh
new CommandPromise(_this.app.cmdMgr, 'refresh', _this.name),
// Handling the back button
new CommandPromise(_this.app.cmdMgr, 'back', _this.name).then(function() {
_this.end=true;
}),
// Handling menu
new CommandPromise(_this.app.cmdMgr, 'menu', _this.name).then(function(data) {
// Loading the selected view
return _this.app.loadView(data.params.view);
})
)
});
};
module.exports = RoomsPromise;
| nfroidure/Liar | src/RoomsPromise.js | JavaScript | mit | 2,568 |
/**
* ionNavBar
*
* ionNavBar and _ionNavBar are created to overcome Meteor's templating limitations. By utilizing Template.dynamic
* in blaze, we can force ionNavBar to destroy _ionNavBar, enabling css transitions and none of that javascript
* animation.
*/
let _ionNavBar_Destroyed = new ReactiveVar(false);
Template.ionNavBar.onCreated(function() {
this.data = this.data || {};
if (Platform.isAndroid()) {
this.transition = 'android';
} else {
this.transition = 'ios';
}
this.ionNavBarTemplate = new ReactiveVar('_ionNavBar');
$(window).on('statechange', e => this.ionNavBarTemplate.set(''));
this.autorun(() => {
if (_ionNavBar_Destroyed.get()) { this.ionNavBarTemplate.set('_ionNavBar'); }
});
});
Template.ionNavBar.onRendered(function() {
let container = this.$('.nav-bar-container');
container.attr('nav-bar-direction', 'forward');
let navBarContainer = this.find('.nav-bar-container');
navBarContainer._uihooks = {
// Override onDestroyed so that's children won't remove themselves immediately.
removeElement: function(node) {
// Worst case scenario. Remove if exceeded maximum transition duration.
Meteor.setTimeout(() => {
node.remove();
}, METEORIC.maximum_transition_duration);
}
};
});
Template.ionNavBar.helpers({
ionNavBarTemplate: function() {
return Template.instance().ionNavBarTemplate.get();
},
transition: function () {
return Template.instance().transition;
}
});
Template._ionNavBar.onCreated(function () {
this.entering = false;
this.leaving = false;
this.activate_view_timeout_id = null;
this.deactivate_view_timeout_id = null;
_ionNavBar_Destroyed.set(false);
});
Template._ionNavBar.onRendered(function () {
// Reset nav-bar-direction.
let navBarBlock = this.find('.nav-bar-block');
navBarBlock._uihooks = {
// Override onDestroyed so that's children won't remove themselves immediately.
removeElement: function(node) {
// Worst case scenario. Remove if exceeded maximum transition duration.
Meteor.setTimeout(() => {
node.remove();
}, METEORIC.maximum_transition_duration);
}
};
let $navBarBlock = this.$('.nav-bar-block').first();
let activate_view = () => {
this.entering = false;
let activate_timer_active = !!this.activate_view_timeout_id;
if (activate_timer_active) {
Meteor.clearTimeout(this.activate_view_timeout_id);
this.activate_view_timeout_id = null;
}
$navBarBlock.attr('nav-bar', 'active');
$('[data-navbar-container]').attr('nav-bar-direction', 'forward');
};
$navBarBlock.attr('nav-bar', 'stage');
let $headerBar = this.$('.nav-bar-block *');
Meteor.setTimeout(() => {
this.entering = true;
$navBarBlock.attr('nav-bar', 'entering');
$headerBar.one(METEORIC.UTILITY.transitionend_events.join(' '), activate_view);
}, 0);
// Worst case scenario, transitionend did not occur. Just place view in.
this.activate_view_timeout_id = Meteor.setTimeout(activate_view, METEORIC.maximum_transition_duration);
});
Template._ionNavBar.onDestroyed(function () {
_ionNavBar_Destroyed.set(true);
let $navBarBlock = this.$('.nav-bar-block');
let deactivate_view = () => {
this.leaving = false;
// If the user have trigger fingers, in which he/she can click back buttons
// really fast, activate view timer might still be going. Kill it.
let activate_timer_active = !!this.activate_view_timeout_id;
if (activate_timer_active) {
Meteor.clearTimeout(this.activate_view_timeout_id);
this.activate_view_timeout_id = null;
}
let deactivate_timer_active = !!this.deactivate_view_timeout_id;
if (deactivate_timer_active) {
Meteor.clearTimeout(this.deactivate_view_timeout_id);
this.deactivate_view_timeout_id = null;
}
this.deactivate_view_timeout_id = null;
$navBarBlock.remove();
};
let $headerBar = this.$('.nav-bar-block *');
Meteor.setTimeout(() => {
this.leaving = true;
$navBarBlock.attr('nav-bar', 'leaving');
$headerBar.one(METEORIC.UTILITY.transitionend_events.join(' '), deactivate_view);
}, 0);
// Worst case scenario, transitionend did not occur. Just remove the view.
this.deactivate_view_timeout_id = Meteor.setTimeout(deactivate_view, METEORIC.maximum_transition_duration);
});
| JoeyAndres/meteor-ionic | components/ionNavBar/ionNavBar.js | JavaScript | mit | 4,669 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("mko.Testdata")]
[assembly: AssemblyDescription("Testdatengeneratoren")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("mk-prg-net")]
[assembly: AssemblyProduct("mko.Testdata")]
[assembly: AssemblyCopyright("Copyright Martin Korneffel © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("ea115078-b90f-446e-881f-8a2ddc578d7c")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mk-prg-net/mk-prg-net.lib | mko.Testdata/Properties/AssemblyInfo.cs | C# | mit | 1,447 |
using System;
using System.Collections.Generic;
using System.Reflection;
using WSDL.Models;
using WSDL.Models.Schema;
namespace WSDL.TypeManagement
{
/// <summary>
/// This provides a stateful context for managing the types required to define
/// a web service. It includes all the types, both static and instance related
/// </summary>
public interface ITypeContext : IDisposable
{
/// <summary>
/// It transforms the parameter types and return types into complex types for both
/// input and output
/// </summary>
/// <param name="methodInfo">The method to transform</param>
/// <param name="contractNamespace">The namespace of the contract to which this method belongs to</param>
/// <returns>Method description with input and output types</returns>
MethodDescription GetDescriptionForMethod(MethodInfo methodInfo, string contractNamespace);
/// <summary>
/// Returns the schemas for the types built during the last execution
/// </summary>
/// <returns>The schemas containing all the types built</returns>
IEnumerable<Schema> GetSchemas();
}
}
| carlos-vicente/Nancy.Soap | src/WSDL/TypeManagement/ITypeContext.cs | C# | mit | 1,193 |
/*
* jobshopConstants.java
*
* Created on February 3, 2001, 12:48 PM
*/
package hugs.apps.jobshop;
import java.lang.*;
import java.util.*;
/**
* This class holds all the constants used in the jobshop project
*
* @author Guy T. Schafer
* @version 1.0
*/
public class jobshopConstants
{
// Window titles:
public final static String TITLE = "Jobshop Optimizer";
public final static String TITLE2 = " v1.0 by Guy T. Schafer";
public final static String STBTITLE = "Algorithm Server Process ";
public final static String HISTTITLE= "Solution History";
public final static String GRPTITLE = "Group Solutions";
public final static String NAMTITLE = "Group Identifier";
// Top level menus:
public final static String FILE = "File";
public final static String VIEW = "View";
public final static String HIST = "History";
public final static String SERVER = "Servers";
public final static String MOBIL = "Mobilities";
public final static String HELP = "Help";
// Tools and Menu Items:
public final static String OPEN = "Open";
public final static String SAVE = "Save";
public final static String SAVEAS = "Save As";
public final static String EXIT = "Exit";
// public final static String TOOLBAR = "Toolbar";
public final static String ATTRIB = "Attributes";
// public final static String PRIOR = "Mobility";
public final static String SHOW = "Show ";
public final static String JOBCOL = "Job Colors";
public final static String JOBID = "Job IDs";
public final static String CHANGE = "Changes";
public final static String CRIT = "Critical Path";
// The first L here is actually an I so the L in Low
// is underlined for the menu shortcut:
public final static String LOW = "Set seIected to Low Mobility";
public final static String MED = "Set selected to Medium Mobility";
public final static String HIGH = "Set selected to High Mobility";
public final static String LOWALL = "Set all to Low Mobility";
public final static String MEDALL = "Set all to Medium Mobility";
public final static String HIGHALL = "Set all to High Mobility";
public final static String DOUBLE = " (double-click to set all)";
public final static String SCALE = "Scale";
public final static String FIT = "Fit on page";
public final static String ZOOMINH = "Stretch Horizontally";
public final static String ZOOMOUTH = "Shrink Horizontally";
public final static String ZOOMINV = "Stretch Vertically";
public final static String ZOOMOUTV = "Shrink Vertically";
public final static String GO = "Go";
public final static String STOP = "Stop";
public final static String LOOK = "Display solution / Add solution to history";
public final static String REL = "Kill this server process";
public final static String SPAN = "Spansize - improving any of these machines is an improvement";
public final static String PLY = "Minimum ply - no fewer than this many swaps";
public final static String UNDO = "Earlier Solution";
public final static String REDO = "Later Solution";
public final static String PROC = "Request server process";
public final static String CONTENTS = "Contents";
public final static String ABOUT = "About";
public final static String CHOOSE = "Choose search algorithm";
public final static String SHARE = "Share this solution with group";
// Labels for controls:
public final static String SPANLBL = "Span ";
public final static String PLYLBL = "min ply ";
public final static String SOLHIST = " History ";
public final static String GRPHIST = " Shared solutions ";
public final static String GRPID = " Group ";
public final static String GRPNAME = " Name ";
public final static String GETNAME = "Enter your name";
// Some labels are in menus (with dots) and tooltips (without dots):
public final static String DOTS = "...";
// Accelerators:
public final static char FACC = 'f';
public final static char VACC = 'v';
public final static char SACC = 's';
public final static char HACC = 'h';
public final static char OACC = 'o';
public final static char AACC = 'a';
public final static char XACC = 'x';
public final static char IACC = 'i';
public final static char GACC = 'g';
public final static char TACC = 't';
public final static char UACC = 'u';
public final static char CACC = 'c';
public final static char PACC = 'p';
public final static char RACC = 'r';
public final static char MACC = 'm';
public final static char LACC = 'l';
public final static char WACC = 'w';
public final static char DACC = 'd';
public final static char EACC = 'e';
public final static char JACC = 'j';
// Status bar has solution history:
public final static String NOHIST = "No solutions";
// Status bar messages:
public final static String GOSTATUS = "Start server process...";
public final static String STOPSTATUS = "Stop server process";
public final static String ENOPROC = "Server cannot supply more power";
public final static String FILEOPEN = "File opened";
public final static String ALERT = "Better solution found";
public final static String GRPSTATUS= "New schedule from group";
public final static String ALGSTATUS= "New schedule from server";
public final static String SHOWING = "Showing ";
public final static String HIDING = "Hiding ";
// Group info:
// The max number of members in each group
// (Also the max number of groups before the numbers
// wrap - hopefully, by the time the 10,000th group
// is created, group 0 is gone. But if it isn't
// unpredictable--but bad--behavior will result.)
public final static int MAXMEMBERS = 10000;
// Algorithm names (and count):
public final static int ALGOCNT = 3;
public final static String[] ALGO = { "Local Greedy",
"Local Deep",
"Tabu Search"
};
// File Dialog strings:
public final static String FILTER = "Jobshop files (*.jsp)";
public final static String EXT = ".jobshop";
// Group Name Input Dialog:
public final static String CANCEL = "Cancel";
// About Dialog strings:
public final static String COPYRIGHT= " (c) 2001 Mitsubishi Electric Research Lab";
public final static String OK = "OK";
// Client status messages:
public final static String CONNORB = " Connecting to ORB...";
public final static String OKORB = " Connected to ORB.";
public final static String ENOORB = " ERROR: Failed to acquire ORB. Check tnameserv is running.";
public final static String CONNALGO = " Finding Algorithm Server...";
public final static String OKALGO = " Found Algorithm Server.";
public final static String ENOALGO = " ERROR: Failed to find Algorithm Server. Cannot continue.";
public final static String CONNGROUP= " Finding Group Server...";
public final static String OKGROUP = " Found Group Server.";
public final static String MONITOR = " Group Monitor Mode ON.";
public final static String ENOGROUP = " ERROR: Failed to find Group Server. Cannot be Monitor.";
public final static String WNOGROUP = " WARNING: Failed to find Group Server. Working alone...";
public final static String ENOPACK = "Invalid move. Cannot pack schedule.";
// Output file comments:
public final static String DEFCOM1 = "// MachineCount JobCount:";
public final static String DEFCOM2 = "// Each line is a job, data format: {machine# jobDuration}";
public final static String HISTCOM1 = "// History of solutions:";
public final static String HISTCOM2 = "// Each line is a job, data format: {machine# jobDuration startTime}";
public final static String SLBLCOM = "// Maxspan = "; // Schedule label comment
// Critical path (it is either critcal because of job
// or machine or both so make the flags OR-able):
public final static int NOTCR = 0;
public final static int CRJOB = 1;
public final static int CRMACH = 2;
// Mobilites:
public final static int LOWMOB = 4;
public final static int MEDMOB = 2;
public final static int HIGHMOB = 1;
// Flags for menu to tell client to move in history:
public final static int NEXT = -2;
public final static int PREV = -4;
}
| guwek/HuGS | hugs/apps/jobshop/jobshopConstants.java | Java | mit | 9,091 |
<?php
/**
* This file is loaded automatically by the app/webroot/index.php file after core.php
*
* This file should load/create any application wide configuration settings, such as
* Caching, Logging, loading additional configuration files.
*
* You should also use this file to include any files that provide global functions/constants
* that your application uses.
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package app.Config
* @since CakePHP(tm) v 0.10.8.2117
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
/**
* Cache Engine Configuration
* Default settings provided below
*
* File storage engine.
*
* Cache::config('default', array(
* 'engine' => 'File', //[required]
* 'duration'=> 3600, //[optional]
* 'probability'=> 100, //[optional]
* 'path' => CACHE, //[optional] use system tmp directory - remember to use absolute path
* 'prefix' => 'cake_', //[optional] prefix every cache file with this string
* 'lock' => false, //[optional] use file locking
* 'serialize' => true, // [optional]
* 'mask' => 0666, // [optional] permission mask to use when creating cache files
* ));
*
* APC (http://pecl.php.net/package/APC)
*
* Cache::config('default', array(
* 'engine' => 'Apc', //[required]
* 'duration'=> 3600, //[optional]
* 'probability'=> 100, //[optional]
* 'prefix' => Inflector::slug(APP_DIR) . '_', //[optional] prefix every cache file with this string
* ));
*
* Xcache (http://xcache.lighttpd.net/)
*
* Cache::config('default', array(
* 'engine' => 'Xcache', //[required]
* 'duration'=> 3600, //[optional]
* 'probability'=> 100, //[optional]
* 'prefix' => Inflector::slug(APP_DIR) . '_', //[optional] prefix every cache file with this string
* 'user' => 'user', //user from xcache.admin.user settings
* 'password' => 'password', //plaintext password (xcache.admin.pass)
* ));
*
* Memcache (http://memcached.org/)
*
* Cache::config('default', array(
* 'engine' => 'Memcache', //[required]
* 'duration'=> 3600, //[optional]
* 'probability'=> 100, //[optional]
* 'prefix' => Inflector::slug(APP_DIR) . '_', //[optional] prefix every cache file with this string
* 'servers' => array(
* '127.0.0.1:11211' // localhost, default port 11211
* ), //[optional]
* 'persistent' => true, // [optional] set this to false for non-persistent connections
* 'compress' => false, // [optional] compress data in Memcache (slower, but uses less memory)
* ));
*
* Wincache (http://php.net/wincache)
*
* Cache::config('default', array(
* 'engine' => 'Wincache', //[required]
* 'duration'=> 3600, //[optional]
* 'probability'=> 100, //[optional]
* 'prefix' => Inflector::slug(APP_DIR) . '_', //[optional] prefix every cache file with this string
* ));
*
* Redis (http://http://redis.io/)
*
* Cache::config('default', array(
* 'engine' => 'Redis', //[required]
* 'duration'=> 3600, //[optional]
* 'probability'=> 100, //[optional]
* 'prefix' => Inflector::slug(APP_DIR) . '_', //[optional] prefix every cache file with this string
* 'server' => '127.0.0.1' // localhost
* 'port' => 6379 // default port 6379
* 'timeout' => 0 // timeout in seconds, 0 = unlimited
* 'persistent' => true, // [optional] set this to false for non-persistent connections
* ));
*/
Cache::config('default', array('engine' => 'File'));
/**
* The settings below can be used to set additional paths to models, views and controllers.
*
* App::build(array(
* 'Model' => array('/path/to/models', '/next/path/to/models'),
* 'Model/Behavior' => array('/path/to/behaviors', '/next/path/to/behaviors'),
* 'Model/Datasource' => array('/path/to/datasources', '/next/path/to/datasources'),
* 'Model/Datasource/Database' => array('/path/to/databases', '/next/path/to/database'),
* 'Model/Datasource/Session' => array('/path/to/sessions', '/next/path/to/sessions'),
* 'Controller' => array('/path/to/controllers', '/next/path/to/controllers'),
* 'Controller/Component' => array('/path/to/components', '/next/path/to/components'),
* 'Controller/Component/Auth' => array('/path/to/auths', '/next/path/to/auths'),
* 'Controller/Component/Acl' => array('/path/to/acls', '/next/path/to/acls'),
* 'View' => array('/path/to/views', '/next/path/to/views'),
* 'View/Helper' => array('/path/to/helpers', '/next/path/to/helpers'),
* 'Console' => array('/path/to/consoles', '/next/path/to/consoles'),
* 'Console/Command' => array('/path/to/commands', '/next/path/to/commands'),
* 'Console/Command/Task' => array('/path/to/tasks', '/next/path/to/tasks'),
* 'Lib' => array('/path/to/libs', '/next/path/to/libs'),
* 'Locale' => array('/path/to/locales', '/next/path/to/locales'),
* 'Vendor' => array('/path/to/vendors', '/next/path/to/vendors'),
* 'Plugin' => array('/path/to/plugins', '/next/path/to/plugins'),
* ));
*
*/
/**
* Custom Inflector rules, can be set to correctly pluralize or singularize table, model, controller names or whatever other
* string is passed to the inflection functions
*
* Inflector::rules('singular', array('rules' => array(), 'irregular' => array(), 'uninflected' => array()));
* Inflector::rules('plural', array('rules' => array(), 'irregular' => array(), 'uninflected' => array()));
*
*/
/**
* Plugins need to be loaded manually, you can either load them one by one or all of them in a single call
* Uncomment one of the lines below, as you need. make sure you read the documentation on CakePlugin to use more
* advanced ways of loading plugins
*
* CakePlugin::loadAll(); // Loads all plugins at once
* CakePlugin::load('DebugKit'); //Loads a single plugin named DebugKit
*
*/
/**
* Your application configuration starts here
*/
Configure::write(
'Application', array(
'name' => 'NTrack',
'from_email' => 'from@your_app_domain.com',
'contact_mail' => 'contact@your_app_domain.com'
)
);
/**
* Choose your application theme
* The list of supported themes are:
* -> default
* -> amelia
* -> cerulean
* -> cyborg
* -> journal
* -> readable
* -> simplex
* -> slate
* -> spacelab
* -> spruce
* -> superhero
* -> united
*/
Configure::write(
'Layout', array(
'theme' => 'default'
)
);
App::uses('CakeEmail', 'Network/Email');
/**
* You can attach event listeners to the request lifecyle as Dispatcher Filter . By Default CakePHP bundles two filters:
*
* - AssetDispatcher filter will serve your asset files (css, images, js, etc) from your themes and plugins
* - CacheDispatcher filter will read the Cache.check configure variable and try to serve cached content generated from controllers
*
* Feel free to remove or add filters as you see fit for your application. A few examples:
*
* Configure::write('Dispatcher.filters', array(
* 'MyCacheFilter', // will use MyCacheFilter class from the Routing/Filter package in your app.
* 'MyPlugin.MyFilter', // will use MyFilter class from the Routing/Filter package in MyPlugin plugin.
* array('callable' => $aFunction, 'on' => 'before', 'priority' => 9), // A valid PHP callback type to be called on beforeDispatch
* array('callable' => $anotherMethod, 'on' => 'after'), // A valid PHP callback type to be called on afterDispatch
*
* ));
*/
Configure::write('Dispatcher.filters', array(
'AssetDispatcher',
'CacheDispatcher'
));
/**
* Configures default file logging options
*/
App::uses('CakeLog', 'Log');
CakeLog::config('debug', array(
'engine' => 'FileLog',
'types' => array('notice', 'info', 'debug'),
'file' => 'debug',
));
CakeLog::config('error', array(
'engine' => 'FileLog',
'types' => array('warning', 'error', 'critical', 'alert', 'emergency'),
'file' => 'error',
));
define('BLOCK_TEMP', 'Temporary Block');
define('BLOCK_PERMANENT', 'Permanent Block');
define('BLOCK_NO', 'No Block');
//CakePlugin::load('Upload');
| Shahlal47/nits | app/Config/bootstrap.php | PHP | mit | 8,502 |
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports.
config.consider_all_requests_local = true
# Enable/disable caching. By default caching is disabled.
if Rails.root.join('tmp/caching-dev.txt').exist?
config.action_controller.perform_caching = true
config.action_mailer.perform_caching = false
config.cache_store = :memory_store
config.public_file_server.headers = {
'Cache-Control' => 'public, max-age=172800'
}
else
config.action_controller.perform_caching = false
config.action_mailer.perform_caching = false
config.cache_store = :null_store
end
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations.
config.active_record.migration_error = :page_load
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true
# Asset digests allow you to set far-future HTTP expiration dates on all assets,
# yet still be able to expire them through the digest params.
config.assets.digest = true
# Adds additional error checking when serving assets at runtime.
# Checks for improperly declared sprockets dependencies.
# Raises helpful error messages.
config.assets.raise_runtime_errors = true
# Raises error for missing translations
# config.action_view.raise_on_missing_translations = true
# Use an evented file watcher to asynchronously detect changes in source code,
# routes, locales, etc. This feature depends on the listen gem.
config.file_watcher = ActiveSupport::EventedFileUpdateChecker
config.action_mailer.default_url_options = { host: 'localhost:3000' }
config.action_mailer.delivery_method = :letter_opener
end
| yannvery/ratatime | config/environments/development.rb | Ruby | mit | 2,371 |
/* eslint no-unused-expressions: "off" */
import { expect } from 'chai';
import { Session } from '../utils';
import * as ModelUtils from '../../../src/utils/model-utils';
const session = new Session();
const Vehicle = session.model('Vehicle', {});
const Car = session.model('Car', {}, {
'extends': Vehicle
});
const Sedan = session.model('Sedan', {
'numDoors': {
'type': Number
}
}, {
'extends': Car
});
describe('Model Utilities tests', () => {
describe('getModel()', () => {
it('Fails when no argument given', () => {
const result = ModelUtils.getModel();
expect(result).to.be.null;
});
it('Fails when given non-model', () => {
const result = ModelUtils.getModel({});
expect(result).to.be.null;
});
it('Returns model class given', () => {
const result = ModelUtils.getModel(Car);
expect(result).to.equal(Car);
});
it('Returns model class for instance', () => {
const car = new Car();
const result = ModelUtils.getModel(car);
expect(result).to.not.equal(car);
expect(result).to.equal(Car);
});
});
describe('getName()', () => {
it('Returns name for model class', () => {
const result = ModelUtils.getName(Car);
expect(result).to.equal('Car');
});
it('Returns name for model instance', () => {
const result = ModelUtils.getName(new Car());
expect(result).to.equal('Car');
});
});
describe('getParent()', () => {
it('Returns parent for model class', () => {
const result = ModelUtils.getParent(Sedan);
expect(result).to.equal(Car);
});
it('Returns parent for model instance', () => {
const result = ModelUtils.getParent(new Sedan());
expect(result).to.equal(Car);
});
it('Returns null if given model is root', () => {
const result = ModelUtils.getParent(Vehicle);
expect(result).to.be.null;
});
it('Returns null if argument missing', () => {
const result = ModelUtils.getParent();
expect(result).to.be.null;
});
});
describe('getAncestors()', () => {
it('Returns ancestors for model class', () => {
const result = ModelUtils.getAncestors(Sedan, session);
expect(result).to.deep.equal([Car, Vehicle]);
});
it('Returns ancestors for model instance', () => {
const result = ModelUtils.getAncestors(new Sedan(), session);
expect(result).to.deep.equal([Car, Vehicle]);
});
});
describe('getField()', () => {
it('Returns field for model class', () => {
const result = ModelUtils.getField(Sedan, 'numDoors');
expect(result).to.deep.equal({
'column': 'numDoors',
'name': 'numDoors',
'type': Number,
'owningModel': Sedan
});
});
it('Returns field for model instance', () => {
const result = ModelUtils.getField(new Sedan(), 'numDoors');
expect(result).to.deep.equal({
'column': 'numDoors',
'name': 'numDoors',
'type': Number,
'owningModel': Sedan
});
});
});
describe('getFields()', () => {
it('Returns fields for model class', () => {
const result = ModelUtils.getFields(Sedan);
expect(result).to.deep.equal({
'numDoors': {
'column': 'numDoors',
'name': 'numDoors',
'owningModel': Sedan,
'type': Number
}
});
});
it('Returns fields for model instance', () => {
const result = ModelUtils.getFields(new Sedan());
expect(result).to.deep.equal({
'numDoors': {
'column': 'numDoors',
'name': 'numDoors',
'owningModel': Sedan,
'type': Number
}
});
});
});
describe('getAllFields()', () => {
it('Returns fields for model class', () => {
const result = ModelUtils.getAllFields(Sedan, session);
expect(result).to.deep.equal({
'numDoors': {
'column': 'numDoors',
'name': 'numDoors',
'owningModel': Sedan,
'type': Number
}
});
});
it('Returns fields for model instance', () => {
const result = ModelUtils.getAllFields(new Sedan(), session);
expect(result).to.deep.equal({
'numDoors': {
'column': 'numDoors',
'name': 'numDoors',
'owningModel': Sedan,
'type': Number
}
});
});
});
describe('getChangedFields', () => {
it('Returns array of field names for model instance', () => {
const sedan = new Sedan({
'numDoors': 4,
'numWheels': 4,
'numWindows': 6
});
const result = ModelUtils.getChangedFields(sedan, session);
expect(result).to.deep.equal(['numDoors']);
});
});
}); | one-orm/core | test/unit/utils/model-utils-test.js | JavaScript | mit | 5,551 |
#!/usr/bin/python
"""
Author: Mohamed K. Eid (mohamedkeid@gmail.com)
Description: stylizes an image using a generative model trained on a particular style
Args:
--input: path to the input image you'd like to apply a style to
--style: name of style (found in 'lib/generators') to apply to the input
--out: path to where the stylized image will be created
--styles: lists trained models available
"""
import argparse
import os
import time
import tensorflow as tf
import generator
import helpers
# Loss term weights
CONTENT_WEIGHT = 1.
STYLE_WEIGHT = 3.
TV_WEIGHT = .1
# Default image paths
DIR_PATH = os.path.dirname(os.path.realpath(__file__))
TRAINED_MODELS_PATH = DIR_PATH + '/../lib/generators/'
INPUT_PATH, STYLE = None, None
OUT_PATH = DIR_PATH + '/../output/out_%.0f.jpg' % time.time()
if not os.path.isdir(DIR_PATH + '/../output'):
os.makedirs(DIR_PATH + '/../output')
# Parse arguments and assign them to their respective global variables
def parse_args():
global INPUT_PATH, STYLE, OUT_PATH
# Create flags
parser = argparse.ArgumentParser()
parser.add_argument('--input', help="path to the input image you'd like to apply a style to")
parser.add_argument('--style', help="name of style (found in 'lib/generators') to apply to the input")
parser.add_argument('--out', default=OUT_PATH, help="path to where the stylized image will be created")
parser.add_argument('--styles', action="store_true", help="list available styles")
args = parser.parse_args()
# Assign image paths from the arg parsing
if args.input and args.style:
INPUT_PATH = os.path.abspath(args.input)
STYLE = args.style
OUT_PATH = args.out
else:
if args.styles:
list_styles()
exit(0)
else:
parser.print_usage()
exit(1)
# Lists trained models
def list_styles():
print("Available styles:")
files = os.listdir(TRAINED_MODELS_PATH)
for file in files:
if os.path.isdir(TRAINED_MODELS_PATH + file):
print(file)
parse_args()
with tf.Session() as sess:
# Check if there is a model trained on the given style
if not os.path.isdir(TRAINED_MODELS_PATH + STYLE):
print("No trained model with the style '%s' was found." % STYLE)
list_styles()
exit(1)
# Load and initialize the image to be stlylized
input_img, _ = helpers.load_img(INPUT_PATH)
input_img = tf.convert_to_tensor(input_img, dtype=tf.float32)
input_img = tf.expand_dims(input_img, axis=0)
# Initialize new generative net
with tf.variable_scope('generator'):
gen = generator.Generator()
gen.build(tf.convert_to_tensor(input_img))
sess.run(tf.global_variables_initializer())
# Restore previously trained model
ckpt_dir = TRAINED_MODELS_PATH + STYLE
saved_path = ckpt_dir + "/{}".format(STYLE)
saver = tf.train.Saver()
saver.restore(sess, saved_path)
# Generate stylized image
img = sess.run(gen.output)
# Save the generated image and close the tf session
helpers.render(img, path_out=OUT_PATH)
sess.close()
| mohamedkeid/Feed-Forward-Style-Transfer | src/test.py | Python | mit | 3,177 |
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res) {
res.render('index', { title: 'Express',reqCsrf:req.csrfToken()});
});
router.post('/regist',function(req,res){
res.send('OK')
});
router.post('/registXhr',function(req,res){
if(req.xhr){
res.send('xhr Access');
}else{
res.send('not xhr Access');
}
});
module.exports = router
| CM-Kajiwara/csurfSample | routes/index.js | JavaScript | mit | 439 |
using Diabhelp.Core.Api;
using Diabhelp.Core.Api.ResponseModels;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace Diabhelp.Core
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class InscriptionScreen : Page
{
public InscriptionScreen()
{
this.InitializeComponent();
}
private void inscription_confirm_button_Click(object sender, RoutedEventArgs e)
{
if (inscriptionPanel.Children.OfType<TextBox>().Any(t => string.IsNullOrWhiteSpace(t.Text)) ||
inscriptionPanel.Children.OfType<PasswordBox>().Any(t => string.IsNullOrWhiteSpace(t.Password)) ||
!role_panel.Children.OfType<RadioButton>().Any(b => b.IsChecked == true))
{
error_lbl.Text = "Veuillez remplir tout les champs";
}
else if (!password_input.Password.Equals(password_confirm_input.Password))
error_lbl.Text = "Les mots de passe doivent correspondre";
else if (login_input.Text.Length < 6)
error_lbl.Text = "Le login doit faire au moins 6 caractères";
else if (password_input.Password.Length < 6)
error_lbl.Text = "Le mot de passe doit faire au moins 6 caractères";
else
{
string role = "";
if (patient_radio_btn.IsChecked == true)
role = "ROLE_PATIENT";
else if (medecin_radio_btn.IsChecked == true)
role = "ROLE_DOCTOR";
else
role = "ROLE_PROCHE";
new ApiClient().doInscription(login_input.Text, email_input.Text, password_input.Password, role, firstname_input.Text, lastname_input.Text, inscription_button_callback);
}
}
public async void inscription_button_callback(InscriptionResponseBody response)
{
if (response.success)
{
error_lbl.Text = "";
await new ApiClient().doLoginPost(login_input.Text, password_input.Password, connect_after_inscription_button_callback);
}
else
{
String errortext = "Erreur lors de l'inscription : ";
if (response.errors.Count >= 1)
errortext += response.errors[0];
else
errortext += "Erreur Inconnue";
error_lbl.Text = errortext;
}
}
public void connect_after_inscription_button_callback(LoginResponseBody response)
{
if (response.success)
{
this.Frame.Navigate(typeof(MainScreen), response);
}
else
{
this.Frame.Navigate(typeof(LoginScreen));
}
}
}
} | DiabHelp/DiabHelp-App-WP | Diabhelp/Core/InscriptionScreen.xaml.cs | C# | mit | 3,398 |
var React = require('react');
var AWSMixin = require('../mixins/aws.mixin');
var AWSActions = require('../actions/AWSActions');
var EC2Item = React.createClass({
render: function() {
return (
<a href="#" onClick={this._onSSHClick} className="col one-fourth ec2-instance">{this.props.instance.Name}</a>
);
},
_onSSHClick: function() {
AWSActions.sshInto(this.props.instance);
}
});
var EC2Section = React.createClass({
mixins:[AWSMixin],
render: function() {
instances = this.state['ec2-instances'];
var ec2items = [];
instances.forEach(function(i) {
ec2items.push(<EC2Item instance={i} />);
});
return (
<div>
<h4 class="section-title" id="grid">EC2 Instances</h4>
<div className="container" id="ec2-instances">{ec2items}</div>
</div>
);
}
});
module.exports = EC2Section;
| sunils34/visualize-aws | www/js/components/EC2.react.js | JavaScript | mit | 865 |
package com.ipacc;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
*
* @author PateL
*
*/
@SpringBootApplication
public class SpringAopPermgenLeakApplication {
} | lucaspate/bugs | SpringAopPermGenLeak/src/main/java/com/ipacc/SpringAopPermgenLeakApplication.java | Java | mit | 194 |
describe('jQuery Plugin', function () {
it('jQuery.fn.plugin should exist', function () {
expect(jQuery.fn.plugin).toBeDefined();
});
}); | angryobject/jquery-plugin-starter | app/jquery.plugin.spec.js | JavaScript | mit | 149 |
using HtmlAgilityPack;
using MagicNewCardsBot.Helpers;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace MagicNewCardsBot
{
public class MTGPicsTasker : Tasker
{
#region Definitions
protected new string _websiteUrl = "https://www.mtgpics.com/";
#endregion
protected string ValidateAndFixUrl(string url)
{
if (!url.Contains(_websiteUrl))
{
url = _websiteUrl + url;
}
return url;
}
#region Overrided Methods
async override protected IAsyncEnumerable<Card> GetAvaliableCardsInWebSiteAsync()
{
List<Set> setsToCrawl = await Database.GetAllCrawlableSetsAsync();
foreach (Set set in setsToCrawl)
{
//loads the website
HtmlDocument doc = new();
//crawl the webpage to get this information
using (Stream stream = await Utils.GetStreamFromUrlAsync(set.URL))
{
doc.Load(stream);
}
//all the cards are a a href so we get all of that
HtmlNodeCollection nodesCards = doc.DocumentNode.SelectNodes("//td[@valign='middle']");
if (nodesCards != null)
{
int crawlsFromThisSite = 0;
foreach (HtmlNode node in nodesCards)
{
var nodeImageCard = node.SelectSingleNode(".//img");
//also the cards have a special class called 'card', so we use it to get the right ones
if (nodeImageCard != null &&
nodeImageCard.Attributes.Contains("src") &&
nodeImageCard.Attributes["src"].Value.ToString().EndsWith(".jpg"))
{
string cardUrl = nodeImageCard.ParentNode.Attributes["href"].Value.ToString();
cardUrl = ValidateAndFixUrl(cardUrl);
string imageUrl = nodeImageCard.Attributes["src"].Value.ToString();
imageUrl = ValidateAndFixUrl(imageUrl);
var card = new Card
{
FullUrlWebSite = cardUrl,
ImageUrl = imageUrl
};
yield return card;
crawlsFromThisSite++;
}
//only get the lastest
if (crawlsFromThisSite == Database.MAX_CARDS)
break;
}
}
}
}
private static void ProcessFieldByType(IList<HtmlNode> nodes, Card mainCard, CardFields field)
{
for (int i = 0; i < nodes.Count; i++)
{
try
{
var node = nodes[i];
Card card;
if (i == 0)
card = mainCard;
else
card = mainCard.ExtraSides[i - 1];
switch (field)
{
case CardFields.Name:
card.Name = node.InnerText.Trim();
break;
case CardFields.ManaCost:
string totalCost = String.Empty;
foreach (var childNode in node.ChildNodes)
{
string imgUrl = childNode.Attributes["src"].Value;
if (imgUrl.EndsWith(".png"))
{
int lastIndex = imgUrl.LastIndexOf('/');
string cost = imgUrl[(lastIndex + 1)..];
cost = cost.Replace(".png", String.Empty);
totalCost += cost.Trim().ToUpper();
}
}
if (!String.IsNullOrEmpty(totalCost))
{
card.ManaCost = totalCost;
}
break;
case CardFields.Type:
string type = node.InnerText;
type = type.Replace("\u0097", "-");
type = System.Net.WebUtility.HtmlDecode(type);
type = type.Trim();
if (!String.IsNullOrEmpty(type))
card.Type = type;
break;
case CardFields.Text:
StringBuilder sb = new();
foreach (var childNode in node.ChildNodes)
{
if (childNode.Attributes != null)
{
if (childNode.Attributes["alt"] != null)
{
string symbol = childNode.Attributes["alt"].Value;
symbol = symbol.Replace("%", "");
sb.Append(symbol.ToUpper());
continue;
}
else if (childNode.Attributes["onclick"] != null && childNode.Attributes["onclick"].Value.Contains("LoadGlo"))
{
continue;
}
}
string text = childNode.InnerText.Replace("\u0095", "");
text = text.Replace("\u0097", "-");
text = text.Replace("\n\t\t\t", String.Empty);
text = text.Replace(" ", " ");
text = WebUtility.HtmlDecode(text);
sb.Append(text);
}
string sbString = sb.ToString();
if (!String.IsNullOrEmpty(sbString))
card.Text = sbString;
break;
case CardFields.PT:
foreach (var childNodes in node.ChildNodes)
{
var text = childNodes.InnerText.Trim();
text = text.Replace("\n", String.Empty);
if (text.Contains("/"))
{
String[] arrPt = text.Split('/');
if (arrPt.Length == 2)
{
card.Power = arrPt[0];
card.Toughness = arrPt[1];
break;
}
}
else if (text.Contains("Loyalty:") || text.Contains("Loyalty :"))
{
string numbersOnly = Regex.Replace(text, "[^0-9]", "");
card.Loyalty = Convert.ToInt32(numbersOnly);
}
}
break;
case CardFields.Rarity:
string rarityValue = node.Attributes?["src"].Value;
Rarity? rarity = null;
rarityValue = rarityValue.Replace("graph/rarity/", string.Empty).Trim();
switch (rarityValue)
{
case "carte30.png":
rarity = Rarity.Common;
break;
case "carte20.png":
rarity = Rarity.Uncommon;
break;
case "carte10.png":
rarity = Rarity.Rare;
break;
case "carte4.png":
rarity = Rarity.Mythic;
break;
}
if(rarity.HasValue)
{
card.Rarity = rarity;
}
break;
default:
break;
}
}
catch { }
}
}
private string GetImageUrlFromHtmlDoc(HtmlDocument html)
{
try
{
var nodeParent = html.DocumentNode.SelectSingleNode(".//div[@id='CardScan']");
var nodeImage = nodeParent.SelectSingleNode(".//img");
string urlNewImage = nodeImage.Attributes["src"].Value.ToString();
urlNewImage = ValidateAndFixUrl(urlNewImage);
return urlNewImage;
}
catch
{ }
return null;
}
private static void GetDetails(Card card, HtmlDocument html)
{
//NAME
var nodes = html.DocumentNode.SelectNodes(".//div[@class='Card20']");
if (nodes != null)
ProcessFieldByType(nodes, card, CardFields.Name);
//MANA COST
nodes = html.DocumentNode.SelectNodes(".//div[@style='height:25px;float:right;']");
if (nodes != null)
ProcessFieldByType(nodes, card, CardFields.ManaCost);
//TEXT
nodes = html.DocumentNode.SelectNodes(".//div[@id='EngShort']");
if (nodes != null)
ProcessFieldByType(nodes, card, CardFields.Text);
var g16nodes = html.DocumentNode.SelectNodes(".//div[@class='CardG16']");
//TYPE
var nodesType = g16nodes.Where(x => x.Attributes["style"] != null &&
x.Attributes["style"].Value.Trim().Equals("padding:5px 0px 5px 0px;")
).ToList();
if (nodesType != null)
ProcessFieldByType(nodesType, card, CardFields.Type);
//POWER AND TOUGHNESS AND LOYALTY
var nodesPT = g16nodes.Where(x => x.Attributes["align"] != null &&
!String.IsNullOrEmpty(x.InnerText.Trim()) &&
x.Attributes["align"].Value.Trim().Equals("right")).ToList();
if (nodesPT != null)
ProcessFieldByType(nodesPT, card, CardFields.PT);
var nodesRarity = html.DocumentNode.SelectNodes("//img[contains(@src,'graph/rarity/')]");
if (nodesRarity != null)
ProcessFieldByType(nodesRarity,card, CardFields.Rarity);
}
private void GetExtraSides(Card card, HtmlDocument html)
{
//SEE IF IT HAS EXTRA IMAGES
try
{
var nodeParent = html.DocumentNode.SelectSingleNode(".//div[@id='CardScanBack']");
if (nodeParent != null)
{
var nodeImage = nodeParent.SelectSingleNode(".//img");
string urlNewImage = nodeImage?.Attributes["src"].Value.ToString();
urlNewImage = ValidateAndFixUrl(urlNewImage);
if (!string.IsNullOrEmpty(urlNewImage))
{
card.AddExtraSide(new Card() { ImageUrl = urlNewImage });
}
}
}
catch
{ }
}
async override protected Task GetAdditionalInfoAsync(Card card)
{
//we do all of this in empty try catches because it is not mandatory information
try
{
HtmlDocument html = await GetHtmlDocumentFromUrlAsync(card.FullUrlWebSite);
//IMAGE
card.ImageUrl = GetImageUrlFromHtmlDoc(html);
GetExtraSides(card, html);
GetDetails(card, html);
//SEE IF IT HAS ALTERNATIVE ARTS/STYLE CARDS
try
{
for (int i = 1; i < 10; i++)
{
var resultNodes = html.DocumentNode.SelectNodes($"//text()[. = '{i}']");
if (resultNodes != null)
{
foreach (HtmlNode node in resultNodes)
{
var nodeParent = node.ParentNode;
if (nodeParent != null && nodeParent.Attributes.Count > 0 && nodeParent.Attributes["href"] != null)
{
var hrefAlternative = nodeParent.Attributes["href"].Value;
hrefAlternative = ValidateAndFixUrl(hrefAlternative);
var alternativeHtmlDoc = await GetHtmlDocumentFromUrlAsync(hrefAlternative);
var alernativeImage = GetImageUrlFromHtmlDoc(alternativeHtmlDoc);
if (!String.IsNullOrEmpty(alernativeImage))
{
Card alternativeCard = new() { FullUrlWebSite = hrefAlternative, ImageUrl = alernativeImage };
GetExtraSides(alternativeCard, alternativeHtmlDoc);
GetDetails(alternativeCard, alternativeHtmlDoc);
//small workarround to not cascade extra sides
card.AddExtraSide(alternativeCard);
for (int j = 0; j < alternativeCard.ExtraSides.Count; j++)
{
Card extraSideAlternative = alternativeCard.ExtraSides[j];
card.AddExtraSide(extraSideAlternative);
alternativeCard.ExtraSides.RemoveAt(j);
}
}
}
}
}
}
}
catch
{ }
}
catch
{ }
}
#endregion
}
} | vinimk/MagicNewCardsBotForTelegram | TaskersAndControllers/MTGPicsTasker.cs | C# | mit | 15,297 |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace Pickin.Models
{
public class PickinUser : IComparable
{
[Key]
public int PickinUserId { get; set; }
[Required]
public virtual ApplicationUser RealUser { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
// ICollection, IEnumerable, IQueryable
public List<Tune> Tunes { get; set; }
public List<PickinUser> AllPickinUsers { get; set; }
public int CompareTo(object obj)
{
// sort user based on email because email is string AND...
// .NET knows how to compare strings already. ha!
// first need to explicitly cast from boject type to PickinUser type
PickinUser other_user = obj as PickinUser;
int answer = this.RealUser.Email.CompareTo(other_user.RealUser.Email);
return answer;
}
}
}
| jbrooks036/Pickin | Pickin/Models/PickinUser.cs | C# | mit | 1,050 |
/* --------------------------------------------------------------------------
*
* File MainScene.cpp
* Description
* Ported By Young-Hwan Mun
* Contact xmsoft77@gmail.com
*
* --------------------------------------------------------------------------
*
* Copyright (c) 2010-2013 XMSoft.
* Copyright (c) 2012 喆 肖 (12/08/10). All rights reserved.
*
* --------------------------------------------------------------------------
*
* This library 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 of the License, or (at your option) 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library in the file COPYING.LIB;
* if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*
* -------------------------------------------------------------------------- */
#include "Precompiled.h"
#include "MainScene.h"
#include "Controllers/InputLayer.h"
enum
{
eTagLife = 1000 ,
eTagLevel ,
};
CCScene* MainScene::scene ( KDint nLevel, KDint nStatus, KDint nLife )
{
CCScene* pScene = CCScene::create ( );
MainScene* pLayer = new MainScene ( );
if ( pScene && pLayer && pLayer->initWithMapInformation ( nLevel, nStatus, nLife ) )
{
pLayer->autorelease ( );
pScene->addChild ( pLayer );
}
else
{
CC_SAFE_DELETE ( pScene );
CC_SAFE_DELETE ( pLayer );
}
return pScene;
}
MainScene::MainScene ( KDvoid )
{
m_pIconArray = KD_NULL;
}
MainScene::~MainScene ( KDvoid )
{
CC_SAFE_RELEASE ( m_pIconArray );
}
KDbool MainScene::initWithMapInformation ( KDint nLevel, KDint nStatus, KDint nLife )
{
if ( !CCLayer::initWithVisibleViewport ( ) )
{
return KD_FALSE;
}
const CCSize& tLyrSize = this->getContentSize ( );
SimpleAudioEngine::sharedEngine ( )->playEffect ( "Sounds/02 start.wav" );
CCLayerColor* pBackColor = CCLayerColor::create ( ccc4 ( 192, 192, 192, 255 ), tLyrSize );
this->addChild ( pBackColor );
CCSpriteFrameCache::sharedSpriteFrameCache ( )->addSpriteFramesWithFile ( "Images/images.plist" );
m_pIconArray = CCArray::create ( );
m_pIconArray->retain ( );
this->iconTank ( );
CCSprite* pLife = CCSprite::createWithSpriteFrameName ( "IP.png" );
pLife->setPosition ( ccp ( 30, tLyrSize.cy - 50 ) );
this->addChild ( pLife );
CCSprite* pLifeIcon = CCSprite::createWithSpriteFrameName ( "p1.png" );
pLifeIcon->setPosition ( ccp ( 20, tLyrSize.cy - 70 ) );
pLifeIcon->setScale ( 0.5f );
this->addChild ( pLifeIcon );
this->showLife ( nLife );
CCSprite* pFlag = CCSprite::createWithSpriteFrameName ( "flag.png" );
pFlag->setPosition ( ccp ( tLyrSize.cx - 50 , tLyrSize.cy - 200 ) );
this->addChild ( pFlag );
this->showLevel ( nLevel );
MapLayer* pMapLayer = MapLayer::create ( nLevel, nStatus, nLife );
pMapLayer->setDelegate ( this );
this->addChild ( pMapLayer );
InputLayer* pInputLayer = InputLayer::create ( );
pInputLayer->setMapLayer ( pMapLayer );
this->addChild ( pInputLayer );
return KD_TRUE;
}
//
// PrivateMethods
//
KDvoid MainScene::iconTank ( KDvoid )
{
const CCSize& tLyrSize = this->getContentSize ( );
CCSpriteFrame* pIconFrame = CCSpriteFrameCache::sharedSpriteFrameCache ( )->spriteFrameByName ( "enemy.png" );
KDint nWidth = 55;
KDint nHeight = 15;
for ( KDint i = 0; i < 10; i++ )
{
nHeight += 15;
CCSprite* pIconA = CCSprite::createWithSpriteFrame ( pIconFrame );
pIconA->setPosition ( ccp ( tLyrSize.cx - nWidth, tLyrSize.cy - nHeight ) );
this->addChild ( pIconA );
m_pIconArray->addObject ( pIconA );
CCSprite* pIconB = CCSprite::createWithSpriteFrame ( pIconFrame );
pIconB->setPosition ( ccp ( tLyrSize.cx - nWidth + 18, tLyrSize.cy - nHeight ) );
this->addChild ( pIconB );
m_pIconArray->addObject ( pIconB );
}
}
KDvoid MainScene::showLife ( KDint nLife )
{
const CCSize& tLyrSize = this->getContentSize ( );
this->removeChildByTag ( eTagLife );
CCLabelTTF* pLabel = CCLabelTTF::create ( ccszf ( "%d", nLife ), "Font/CourierBold.ttf", 20 );
pLabel->setColor ( ccc3 ( 0, 0, 0 ) );
pLabel->setPosition ( ccp ( 45, tLyrSize.cy - 70 ) );
this->addChild ( pLabel, 0, eTagLife );
}
KDvoid MainScene::showLevel ( KDint nLevel )
{
const CCSize& tLyrSize = this->getContentSize ( );
this->removeChildByTag ( eTagLevel );
CCLabelTTF* pLabel = CCLabelTTF::create ( ccszf ( "%d", nLevel ), "Font/CourierBold.ttf", 20 );
pLabel->setColor ( ccc3 ( 0, 0, 0 ) );
pLabel->setPosition ( ccp ( tLyrSize.cx - 40, tLyrSize.cy - 230 ) );
this->addChild ( pLabel, 0, eTagLevel );
}
//
// MapLayerDelegate methods
//
KDvoid MainScene::gameOver ( KDvoid )
{
}
KDvoid MainScene::bornEnmey ( KDvoid )
{
if ( m_pIconArray->count ( ) > 0 )
{
CCSprite* pIcon = (CCSprite*) m_pIconArray->lastObject ( );
pIcon->removeFromParent ( );
m_pIconArray->removeLastObject ( );
}
}
KDvoid MainScene::changeTankLife ( KDint nLife )
{
this->showLife ( nLife );
}
| mcodegeeks/OpenKODE-Framework | 04_Sample/BattleCity/Source/Views/MainScene.cpp | C++ | mit | 5,528 |
<?php
/**
* Класс User - предназначен для работы с учетными записями пользователей системы.
* Доступен из любой точки программы.
* Реализован в виде синглтона, что исключает его дублирование.
*
* @author Авдеев Марк <mark-avdeev@mail.ru>
* @package moguta.cms
* @subpackage Libraries
*/
class User {
static private $_instance = null;
private $auth = array();
static $accessStatus = array(0 => 'Разрешен', 1 => 'Заблокирован');
static $groupName = array(1 => 'Администратор', 2 => 'Пользователь', 3 => 'Менеджер', 4 => 'Модератор');
private function __construct() {
// Если пользователь был авторизован, то присваиваем сохраненные данные.
if (isset($_SESSION['user'])) {
if ($_SESSION['userAuthDomain'] == $_SERVER['SERVER_NAME']) {
$this->auth = $_SESSION['user'];
}
}
}
private function __clone() {
}
private function __wakeup() {
}
/**
* Возвращет единственный экземпляр данного класса.
* @return object - объект класса URL.
*/
static public function getInstance() {
if (is_null(self::$_instance)) {
self::$_instance = new self;
}
return self::$_instance;
}
/**
* Инициализирует объект данного класса User.
* @return void
*/
public static function init() {
self::getInstance();
}
/**
* Возвращает авторизированнго пользователя.
* @return void
*/
public static function getThis() {
return self::$_instance->auth;
}
/**
* Добавляет новую учетную запись пользователя в базу сайта.
* @param $userInfo - массив значений для вставки в БД [Поле => Значение].
* @return bool
*/
public static function add($userInfo) {
$result = false;
// Если пользователя с таким емайлом еще нет.
if (!self::getUserInfoByEmail($userInfo['email'])) {
$userInfo['pass'] = crypt($userInfo['pass']);
foreach ($array as $k => $v) {
if($k!=='pass'){
$array[$k] = htmlspecialchars_decode($v);
$array[$k] = htmlspecialchars($v);
}
}
if (DB::buildQuery('INSERT INTO `'.PREFIX.'user` SET ', $userInfo)) {
$id = DB::insertId();
$result = $id;
}
} else {
$result = false;
}
$args = func_get_args();
return MG::createHook(__CLASS__."_".__FUNCTION__, $result, $args);
}
/**
* Удаляет учетную запись пользователя из базы.
* @param $id id пользовате, чью запись следует удалить.
* @return void
*/
public static function delete($id) {
$res = DB::query('SELECT `role` FROM `'.PREFIX.'user` WHERE id = '.DB::quote($id));
$role = DB::fetchArray($res);
// Нельзя удалить первого пользователя, поскольку он является админом
if ($role['role'] == 1 ) {
$res = DB::query('SELECT `id` FROM `'.PREFIX.'user` WHERE `role` = 1');
if (DB::numRows($res) == 1 || $_SESSION['user']->id == $id) {
return false;
}
}
DB::query('DELETE FROM `'.PREFIX.'user` WHERE id = '.DB::quote($id));
return true;
}
/**
* Обновляет пользователя учетную запись пользователя.
* @param $id - id пользователя.
* @param $data - массив значений для вставки в БД [Поле => Значение].
* @param $authRewrite - false = перезапишет данные в сессии детущего пользователя, на полученные у $data.
* @return void
*/
public static function update($id, $data, $authRewrite = false) {
$userInfo = USER::getUserById($id);
foreach ($data as $k => $v) {
if($k!=='pass'){
$v = htmlspecialchars_decode($v);
$data[$k] = htmlspecialchars($v);
}
}
//только если пытаемся разжаловать админа, проверяем,
// не является ли он последним админом
// Без админов никак незя!
if ($userInfo->role == '1' && $data['role'] != '1') {
$countAdmin = DB::query('
SELECT count(id) as "count"
FROM `'.PREFIX.'user`
WHERE role = 1
');
if ($row = DB::fetchAssoc($countAdmin)) {
if ($row['count'] == 1) {// остался один админ
$data['role'] = 1; // не даем разжаловать админа, уж лучше плохой чем никакого :-)
}
}
}
DB::query('
UPDATE `'.PREFIX.'user`
SET '.DB::buildPartQuery($data).'
WHERE id = '.DB::quote($id));
if (!$authRewrite) {
foreach ($data as $k => $v) {
self::$_instance->auth->$k = $v;
}
$_SESSION['user'] = self::$_instance->auth;
}
return true;
}
/**
* Разлогинивает авторизованного пользователя.
* @param $id - id пользователя.
* @return void
*/
public static function logout() {
self::getInstance()->auth = null;
unset($_SESSION['user']);
unset($_SESSION['cart']);
unset($_SESSION['loginAttempt']);
unset($_SESSION['blockTimeStart']);
//Удаляем данные о корзине.
SetCookie('cart', '', time());
MG::redirect('/enter');
}
/**
* Аутентифицирует данные, с помощью криптографического алгоритма
* @param $email - емайл.
* @param $pass - пароль.
* @return bool
*/
public static function auth($email, $pass, $cap) {
// проверка заблокирована ли авторизация,
if (isset($_SESSION['blockTimeStart'])) {
$period = time() - $_SESSION['blockTimeStart'];
if ($period < 15 * 60) {
return false;
} else {
unset($_SESSION['loginAttempt']);
unset($_SESSION['blockTimeStart']);
}
}
$result = DB::query('
SELECT *
FROM `'.PREFIX.'user`
WHERE email = "%s"
', $email, $pass);
// если был введен код капчи,
if ($cap && (($cap == '') || (strtolower($cap) != strtolower($_SESSION['capcha'])))) {
$_SESSION['loginAttempt'] += 1;
return false;
}
if ($row = DB::fetchObject($result)) {
if ($row->pass == crypt($pass, $row->pass)) {
self::$_instance->auth = $row;
$_SESSION['userAuthDomain'] = $_SERVER['SERVER_NAME'];
$_SESSION['user'] = self::$_instance->auth;
$_SESSION['loginAttempt']='';
return true;
}
}
// если в настройках блокировка отменена, то количество попыток не суммируется.
$lockAuth = MG::getOption('lockAuthorization') == 'false' ? false : true;
if ($lockAuth) {
if (!isset($_SESSION['loginAttempt'])) {
$_SESSION['loginAttempt'] = 0;
}
$_SESSION['loginAttempt'] += 1;
}
return false;
}
/**
* Получает все данные пользователя из БД по ID.
* @param $id - пользователя.
* @return void
*/
public static function getUserById($id) {
$result = false;
$res = DB::query('
SELECT *
FROM `'.PREFIX.'user`
WHERE id = "%s"
', $id);
if ($row = DB::fetchObject($res)) {
$result = $row;
}
$args = func_get_args();
return MG::createHook(__CLASS__."_".__FUNCTION__, $result, $args);
}
/**
* Получает все данные пользователя из БД по email.
* @param $email - пользователя.
* @return void
*/
public static function getUserInfoByEmail($email) {
$result = false;
$res = DB::query('
SELECT *
FROM `'.PREFIX.'user`
WHERE email = "%s"
', $email);
if ($row = DB::fetchObject($res)) {
$result = $row;
}
$args = func_get_args();
return MG::createHook(__CLASS__."_".__FUNCTION__, $result, $args);
}
/**
* Проверяет, авторизован ли текущий пользователь.
* @return void
*/
public static function isAuth() {
if (self::getThis()) {
return true;
}
return false;
}
/**
* Получает список пользователей.
* @param $id - пользователя.
* @return void
*/
public static function getListUser() {
$result = false;
$res = DB::query('
SELECT *
FROM `'.PREFIX.'user`
', $id);
while ($row = DB::fetchObject($res)) {
$result[] = $row;
}
$args = func_get_args();
return MG::createHook(__CLASS__."_".__FUNCTION__, $result, $args);
}
/**
* Проверяет права пользователя на выполнение ajax запроса.
* @param string $roleMask - строка с перечисленными ролями, которые имеют доступ,
* если параметр не передается, то доступ открыт для всех.
* 1 - администратор,
* 2 - пользователь,
* 3 - менеджер,
* 4 - модератор
* @return bool or exit;
*/
public static function AccessOnly($roleMask="1,2,3,4",$exit=null) {
$thisRole = empty(self::getThis()->role)?'2':self::getThis()->role;
if(strpos($roleMask,(string)$thisRole)!==false){
return true;
}
// мод для аяксовых запросов.
if($exit){
exit();
}
return false;
}
/**
* Возвращает дату последней регистрации пользователя
* @return array
*/
public function getMaxDate() {
$res = DB::query('
SELECT MAX(date_add) as res
FROM `'.PREFIX.'user`');
if ($row = DB::fetchObject($res)) {
$result = $row->res;
}
return $result;
}
/**
* Возвращает дату первой регистрации пользователя.
* @return array
*/
public function getMinDate() {
$res = DB::query('
SELECT MIN(date_add) as res
FROM `'.PREFIX.'user`'
);
if ($row = DB::fetchObject($res)) {
$result = $row->res;
}
return $result;
}
/**
* Получает все email пользователя из БД
*
*/
public static function searchEmail($email) {
$result = false;
$res = DB::query('
SELECT `email`
FROM `'.PREFIX.'user`
WHERE email LIKE '.$email.'%');
if ($row = DB::fetchObject($res)) {
$result = $row;
}
return $result;
}
} | hlogeon/autoryad | mg-core/lib/user.php | PHP | mit | 11,648 |