repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
trustify/oroplatform | src/Oro/Component/Layout/Tests/Unit/Loader/Driver/YamlDriverTest.php | 6880 | <?php
namespace Oro\Component\Layout\Tests\Unit\Loader\Driver;
use Symfony\Component\Filesystem\Filesystem;
use Oro\Component\Layout\Exception\SyntaxException;
use Oro\Component\Layout\Loader\Driver\YamlDriver;
use Oro\Component\Layout\Loader\Generator\GeneratorData;
use Oro\Component\Layout\Loader\Generator\LayoutUpdateGeneratorInterface;
use Oro\Component\Layout\Loader\Visitor\VisitorCollection;
class YamlDriverTest extends \PHPUnit_Framework_TestCase
{
protected $cacheDir;
public function setUp()
{
parent::setUp();
$this->cacheDir = rtrim(sys_get_temp_dir(), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . 'layouts';
$fs = new Filesystem();
$fs->remove($this->cacheDir);
}
public function tearDown()
{
parent::tearDown();
$fs = new Filesystem();
$fs->remove($this->cacheDir);
}
/**
* @expectedException \InvalidArgumentException
*/
public function testEmptyCacheDirException()
{
$generator = $this->getMock('Oro\Component\Layout\Loader\Generator\LayoutUpdateGeneratorInterface');
$this->getLoader($generator);
}
public function testLoadInDebugMode()
{
$generator = $this->getMock('Oro\Component\Layout\Loader\Generator\LayoutUpdateGeneratorInterface');
$loader = $this->getLoader($generator, false, $this->cacheDir);
$generator->expects($this->once())->method('generate')->willReturnCallback([$this, 'buildClass']);
$path = rtrim(__DIR__, DIRECTORY_SEPARATOR) . '/../Stubs/Updates/layout_update.yml';
$path = str_replace('/', DIRECTORY_SEPARATOR, $path);
$update = $loader->load($path);
$this->assertInstanceOf('Oro\Component\Layout\LayoutUpdateInterface', $update);
}
public function testLoadInProductionMode()
{
$generator = $this->getMock('Oro\Component\Layout\Loader\Generator\LayoutUpdateGeneratorInterface');
$loader = $this->getLoader($generator, false, $this->cacheDir);
$generator->expects($this->once())->method('generate')->willReturnCallback([$this, 'buildClass']);
$path = rtrim(__DIR__, DIRECTORY_SEPARATOR) . '/../Stubs/Updates/layout_update2.yml';
$path = str_replace('/', DIRECTORY_SEPARATOR, $path);
$update = $loader->load($path);
$this->assertInstanceOf('Oro\Component\Layout\LayoutUpdateInterface', $update);
$this->assertCount(1, $files = iterator_to_array(new \FilesystemIterator($this->cacheDir)));
}
public function testPassElementVisitor()
{
$generator = $this->getMock('Oro\Component\Layout\Loader\Generator\LayoutUpdateGeneratorInterface');
$loader = $this->getLoader($generator, false, $this->cacheDir);
$path = rtrim(__DIR__, DIRECTORY_SEPARATOR) . '/../Stubs/Updates/_header.yml';
$path = str_replace('/', DIRECTORY_SEPARATOR, $path);
$resource = $path;
$generator->expects($this->once())->method('generate')
->willReturnCallback(
function ($className, $data, VisitorCollection $collection) use ($resource) {
$this->assertContainsOnlyInstancesOf(
'Oro\Component\Layout\Loader\Visitor\ElementDependentVisitor',
$collection
);
return $this->buildClass($className, $data);
}
);
$loader->load($resource);
}
public function testPassesParsedYamlContentToGenerator()
{
$generator = $this->getMock('Oro\Component\Layout\Loader\Generator\LayoutUpdateGeneratorInterface');
$loader = $this->getLoader($generator, false, $this->cacheDir);
$path = rtrim(__DIR__, DIRECTORY_SEPARATOR) . '/../Stubs/Updates/layout_update4.yml';
$path = str_replace('/', DIRECTORY_SEPARATOR, $path);
$generator->expects($this->once())->method('generate')
->willReturnCallback(
function ($className, GeneratorData $data) use ($path) {
$this->assertNotEmpty($data);
$this->assertSame(
['actions' => [['@add' => ['id' => 'root', 'parent' => null]]]],
$data->getSource()
);
$this->assertSame($path, $data->getFilename());
return $this->buildClass($className);
}
);
$loader->load($path);
}
public function testProcessSyntaxExceptions()
{
$path = rtrim(__DIR__, DIRECTORY_SEPARATOR) . '/../Stubs/Updates/layout_update5.yml';
$path = str_replace('/', DIRECTORY_SEPARATOR, $path);
$generator = $this->getMock('Oro\Component\Layout\Loader\Generator\LayoutUpdateGeneratorInterface');
$loader = $this->getLoader($generator, false, $this->cacheDir);
$exception = new SyntaxException(
'action name should start with "@" symbol, current name "add"',
['add' => ['id' => 'myId', 'parentId' => 'myParentId']],
'actions.0'
);
$generator->expects($this->once())->method('generate')->willThrowException($exception);
$message = <<<MESSAGE
Syntax error: action name should start with "@" symbol, current name "add" at "actions.0"
add:
id: myId
parentId: myParentId
Filename: $path
MESSAGE;
$this->setExpectedException('\RuntimeException', $message);
$update = $loader->load($path);
$this->assertInstanceOf('Oro\Component\Layout\LayoutUpdateInterface', $update);
}
public function testGetUpdateFilenamePattern()
{
$loader = $this->getLoader(null, false, $this->cacheDir);
$this->assertEquals('/\.yml$/', $loader->getUpdateFilenamePattern('yml'));
}
/**
* @param string $className
*
* @return string
*/
public function buildClass($className)
{
return <<<CLASS
<?php
use \Oro\Component\Layout\LayoutManipulatorInterface;
use \Oro\Component\Layout\LayoutItemInterface;
class $className implements \Oro\Component\Layout\LayoutUpdateInterface
{
public function updateLayout(LayoutManipulatorInterface \$layoutManipulator, LayoutItemInterface \$item)
{
}
}
CLASS;
}
/**
* @param null|LayoutUpdateGeneratorInterface $generator
* @param bool $debug
* @param bool $cache
*
* @return YamlDriver
*/
protected function getLoader($generator = null, $debug = false, $cache = false)
{
$generator = null === $generator
? $this->getMock('Oro\Component\Layout\Loader\Generator\LayoutUpdateGeneratorInterface')
: $generator;
return new YamlDriver($generator, $debug, $cache);
}
}
| mit |
NCSU-Libraries/circa | app/models/concerns/ref_integrity.rb | 2404 | require 'active_support/concern'
module RefIntegrity
extend ActiveSupport::Concern
included do
include CircaExceptions
before_destroy :check_deletable, prepend: true
# before_destroy :delete_from_index
def deletable?
deletable = true
case self
when User
if self.orders.length > 0
deletable = false
end
when Order
if (self.items.length > 0) || self.state_reached?(:confirmed)
deletable = false
end
when Item
if (self.item_orders.length > 0) || (self.access_sessions.length > 0)
deletable = false
end
when Location
if self.permanent_items.length > 0 || self.current_items.length > 0
deletable = false
elsif self.orders.length > 0
self.orders.each do |o|
if !o.deletable?
deletable = false
break
end
end
end
when UserRole
deletable = users.length == 0
end
deletable
end
protected
def delete_associations
case self
when Item
self.item_archivesspace_records.each { |iar| iar.destroy }
if self.item_catalog_record
self.item_catalog_record.destroy
end
end
end
def check_deletable
if deletable?
if respond_to?(:delete_from_index)
delete_from_index
delete_associations
end
else
error_messages = lambda do |type|
case type
when :user
return "The user cannot be deleted because it is currently associated with one or more orders."
when :order
return "Confirmed orders cannot be deleted."
when :item
return "This item cannot be deleted because it associated with one or more orders or has an access history that must be maintained."
when :location
return "This location cannot be deleted because it is associated with one or more items or orders."
when :user_role
return "This user role cannot be deleted because it has associated users."
end
end
puts error_messages.call(self.class.to_s.underscore.to_sym)
raise CircaExceptions::ReferentialIntegrityConflict, error_messages.call(self.class.to_s.downcase.to_sym)
false
end
end
end
end
| mit |
Xadera/Software-University | Programming Fundamentals Jan 2017/homework/Files, Direct., Exceptions - Lab/04. Max Sequence of Equal Elements/Properties/AssemblyInfo.cs | 1444 | 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("04. Max Sequence of Equal Elements")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("04. Max Sequence of Equal Elements")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("8415b42e-87dc-4535-b589-7c0f4d361705")]
// 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")]
| mit |
ramswaroop/Algorithms-and-Data-Structures-in-Java | src/main/java/com/rampatra/linkedlists/DeleteAlternateNodes.java | 1039 | package com.rampatra.linkedlists;
import com.rampatra.base.SingleLinkedList;
import com.rampatra.base.SingleLinkedNode;
/**
* Delete alternate nodes in a single linked list.
*
* @author rampatra
* @since 6/27/15
*/
public class DeleteAlternateNodes {
public static <E extends Comparable<E>> void deleteAlternateNodes(SingleLinkedList<E> list) {
deleteAlternateNodes(list.head);
}
public static <E extends Comparable<E>> void deleteAlternateNodes(SingleLinkedNode<E> node) {
if (node == null || node.next == null) return;
node.next = node.next.next;
deleteAlternateNodes(node.next);
}
public static void main(String[] args) {
SingleLinkedList<Integer> linkedList = new SingleLinkedList<>();
linkedList.add(0);
linkedList.add(1);
linkedList.add(2);
linkedList.add(3);
linkedList.add(4);
linkedList.add(5);
linkedList.printList();
deleteAlternateNodes(linkedList);
linkedList.printList();
}
}
| mit |
DecibelTechnology/decibel-framework | rpc/debug/DInvalidRemoteProcedureCallException.php | 3410 | <?php
//
// Copyright (c) 2008-2016 Decibel Technology Limited.
//
namespace app\decibel\rpc\debug;
use app\decibel\utility\DJson;
use stdClass;
/**
* Handles an exception occurring when execution of a remote procedure
* against an non-Decibel server is attempted, or when the remote server
* cannot be contacted.
*
* @section why Why Would I Use It?
*
* This exception is thrown by the {@link DRemoteProcedureCall} class when
* attempting execution of a remote procedure on a non-Decibel server or when
* the remote server cannot be contacted.
*
* @section how How Do I Use It?
*
* This exception should be caught using a <code>try ... catch</code> block
* around any execution of {@link DRemoteProcedureCall::create()}.
*
* @subsection example Examples
*
* The following example handles a {@link DInvalidRemoteProcedureCallException}.
*
* @code
* use app\decibel\rpc\DRemoteProcedureCall;
* use app\decibel\rpc\debug\DInvalidRemoteProcedureCallException;
*
* try {
* $result = DRemoteProcedureCall::create('app\\MyApp\\MyRemoteProcedure')
* ->setServer('myremoteserver.com')
* ->execute();
* } catch (DInvalidRemoteProcedureCallException $e) {
* debug('Not a Decibel server!');
* }
* @endcode
*
* @section versioning Version Control
*
* @author Timothy de Paris
* @ingroup rpc_exceptions
*/
class DInvalidRemoteProcedureCallException extends DRpcException
{
/**
* 'HTTP Code' information field name.
*
* @var string
*/
const INFORMATION_HTTP_CODE = 'httpCode';
/**
* 'Location' information field name.
*
* @var string
*/
const INFORMATION_LOCATION = 'location';
/**
* 'Result' information field name.
*
* @var string
*/
const INFORMATION_RESULT = 'result';
/**
* Creates a new {@link DInvalidRemoteProcedureCallException}.
*
* @param string $location Location from which the remote procedure was called.
* @param mixed $httpCode The HTTP status code returned by the remote server.
* @param mixed $result Content returned by the remote procedure.
*
* @return static
*/
public function __construct($location,
$httpCode = null, $result = null)
{
parent::__construct(array(
self::INFORMATION_LOCATION => $location,
self::INFORMATION_HTTP_CODE => $httpCode,
self::INFORMATION_RESULT => $result,
));
}
/**
* Returns the HTTP code returned by the remote server, if known.
*
* @return int
*/
public function getHttpCode()
{
return $this->information[ self::INFORMATION_HTTP_CODE ];
}
/**
* Returns the content returned by the remote server.
*
* @return string
*/
public function getResult()
{
return $this->information[ self::INFORMATION_RESULT ];
}
/**
* Returns a stdClass object ready for encoding into json format.
*
* @return stdClass
*/
public function jsonSerialize()
{
$jsonObject = parent::jsonSerialize();
$jsonObject->result = $this->information[ self::INFORMATION_RESULT ];
return $jsonObject;
}
}
| mit |
OblivionNW/Nucleus | src/main/java/io/github/nucleuspowered/nucleus/modules/mute/events/MuteEvent.java | 2041 | /*
* This file is part of Nucleus, licensed under the MIT License (MIT). See the LICENSE.txt file
* at the root of this project for more details.
*/
package io.github.nucleuspowered.nucleus.modules.mute.events;
import io.github.nucleuspowered.nucleus.api.events.NucleusMuteEvent;
import org.spongepowered.api.entity.living.player.User;
import org.spongepowered.api.event.cause.Cause;
import org.spongepowered.api.event.impl.AbstractEvent;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.util.annotation.NonnullByDefault;
import java.time.Duration;
import java.util.Optional;
import javax.annotation.Nullable;
@NonnullByDefault
public abstract class MuteEvent extends AbstractEvent implements NucleusMuteEvent {
private final Cause cause;
private final User target;
public MuteEvent(Cause cause, User target) {
this.cause = cause;
this.target = target;
}
@Override public User getTargetUser() {
return this.target;
}
@Override public Cause getCause() {
return this.cause;
}
public static class Muted extends MuteEvent implements NucleusMuteEvent.Muted {
@Nullable public final Duration duration;
public final Text reason;
public Muted(Cause cause, User target, @Nullable Duration duration, Text reason) {
super(cause, target);
this.duration = duration;
this.reason = reason;
}
@Override public Optional<Duration> getDuration() {
return Optional.ofNullable(this.duration);
}
@Override public Text getReason() {
return this.reason;
}
}
public static class Unmuted extends MuteEvent implements NucleusMuteEvent.Unmuted {
private final boolean expired;
public Unmuted(Cause cause, User target, boolean expired) {
super(cause, target);
this.expired = expired;
}
@Override public boolean expired() {
return this.expired;
}
}
}
| mit |
versioneye/versioneye-core | lib/versioneye/models/license.rb | 4651 | class License < Versioneye::Model
include Mongoid::Document
include Mongoid::Timestamps
require 'versioneye/models/traits/license_normalizer'
include VersionEye::LicenseNormalizer
# This license belongs to the product with this attributes
field :language , type: String
field :prod_key , type: String
field :version , type: String
field :name , type: String # For example MIT
field :url , type: String # URL to the license text
field :comments , type: String # Maven specific
field :distributions , type: String # Maven specific
field :spdx_id , type: String # For example AGPL-1.0. See http://spdx.org/licenses/
field :source , type: String # Where it was crawled
field :update_version , type: String
field :crowdsourced , type: Boolean, default: false
# TODO This is causing a too large index. For Python some names are containnign the license text. This need to be fixest! See -> License.where(:name => /\n/).count
index({ language: 1, prod_key: 1, version: 1 }, { name: "language_prod_key_version_index", background: true })
index({ language: 1, prod_key: 1} , { name: "language_prod_key_index" , background: true })
index({ update_version: 1} , { name: "update_version_index" , background: true })
validates_presence_of :language, :message => 'language is mandatory!'
validates_presence_of :prod_key, :message => 'prod_key is mandatory!'
validates_presence_of :name, :message => 'name is mandatory!'
def product
Product.fetch_product(self.language, self.prod_key)
end
def label
name = license_for_url
return name if !name.to_s.empty?
return spdx_id if !spdx_id.to_s.empty?
name_substitute
end
def self.for_product( product, ignore_version = false )
licenses = []
if ignore_version
licenses = License.where(:language => product.language, :prod_key => product.prod_key)
else
licenses = License.where(:language => product.language, :prod_key => product.prod_key, :version => product.version)
if licenses.empty? && product.version.to_s.scan(/\./).count == 1
licenses = License.where(:language => product.language, :prod_key => product.prod_key, :version => "#{product.version}.0")
end
end
licenses
end
# Returns the licenses with nil version!
def self.for_product_global product
return License.where(:language => product.language, :prod_key => product.prod_key, :version => nil)
end
def self.find_or_create language, prod_key, version, name, url = nil, comments = nil, distributions = nil
license = License.where(:language => language, :prod_key => prod_key, :version => version, :name => name).first
return license if license
license = License.new({ :language => language, :prod_key => prod_key, :version => version, :name => name, :url => url, :comments => comments, :distributions => distributions })
if license.save
log.info "new license (#{name}) for #{language}:#{prod_key}:#{version}"
else
log.error "Can't save license (#{name}) for #{language}:#{prod_key}:#{version} because #{license.errors.full_messages.to_json}"
end
license
end
def to_s
if url
return "[License for (#{language}/#{prod_key}/#{version}) : #{name}/#{url}]"
else
return "[License for (#{language}/#{prod_key}/#{version}) : #{name}]"
end
end
def license_for_url
return 'LGPL-2.1' if url.to_s.eql?('https://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt')
return 'LGPL-2.1' if url.to_s.eql?('https://www.gnu.org/licenses/old-licenses/lgpl-2.1.html')
return 'LGPL-2.1' if url.to_s.eql?('http://www.gnu.org/licenses/lgpl-2.1.html')
return 'LGPL-2.1' if url.to_s.eql?('http://www.gnu.org/licenses/lgpl-2.1.txt')
return 'LGPL-2.1' if url.to_s.eql?('http://www.gnu.org/licenses/lgpl-2.1.en.html')
return 'LGPL-2.1' if url.to_s.eql?('http://creativecommons.org/licenses/LGPL/2.1/')
return 'LGPL-2.1' if url.to_s.eql?('http://www.opensource.org/licenses/LGPL-2.1')
return 'LGPL-3.0' if url.to_s.eql?('http://www.gnu.org/licenses/lgpl.html')
return 'CDDL-1.0' if url.to_s.eql?('http://repository.jboss.org/licenses/cddl.txt')
return 'CDDL-1.0' if url.to_s.eql?('https://opensource.org/licenses/cddl1.php')
return 'CC0-1.0' if url.to_s.eql?('http://repository.jboss.org/licenses/cc0-1.0.txt')
return 'CC0-1.0' if url.to_s.eql?('http://repository.jboss.org/licenses/cc0-1.0.html')
return 'EPL-1.0' if url.to_s.eql?('http://www.eclipse.org/legal/epl-v10.html')
return nil
end
end
| mit |
chrisdew/barricane-server | www/vendor/knockout.mapping-latest.js | 5941 | // Knockout Mapping plugin v0.5
// (c) 2010 Steven Sanderson, Roy Jacobs - http://knockoutjs.com/
// License: Ms-Pl (http://www.opensource.org/licenses/ms-pl.html)
ko.exportSymbol=function(n,s){for(var j=n.split("."),t=window,o=0;o<j.length-1;o++)t=t[j[o]];t[j[j.length-1]]=s};ko.exportProperty=function(n,s,j){n[s]=j};
(function(){function n(a){if(a&&typeof a==="object"&&a.constructor==(new Date).constructor)return"date";return typeof a}function s(a,c,b){w||(z=[]);w++;a=j(a,c,b);w--;return a}function j(a,c,b,d,f,p){var h=ko.utils.unwrapObservable(c)instanceof Array;if(ko.mapping.isMapped(a))b=ko.utils.unwrapObservable(a)[q];d=d||new A;if(d.get(c))return a;f=f||"";if(h){p=[];var g=function(e){return e};if(b[f]&&b[f].key)g=b[f].key;if(!ko.isObservable(a)){a=ko.observableArray([]);a.mappedRemove=function(e){var i=
typeof e=="function"?e:function(k){return k===g(e)};return a.remove(function(k){return i(g(k))})};a.mappedRemoveAll=function(e){var i=v(e,g);return a.remove(function(k){return ko.utils.arrayIndexOf(i,g(k))!=-1})};a.mappedDestroy=function(e){var i=typeof e=="function"?e:function(k){return k===g(e)};return a.destroy(function(k){return i(g(k))})};a.mappedDestroyAll=function(e){var i=v(e,g);return a.destroy(function(k){return ko.utils.arrayIndexOf(i,g(k))!=-1})};a.mappedIndexOf=function(e){var i=v(a(),
g);e=g(e);return ko.utils.arrayIndexOf(i,e)}}h=v(ko.utils.unwrapObservable(a),g).sort();var r=v(c,g).sort();h=ko.utils.compareArrays(h,r);r=[];for(var x=0,C=h.length;x<C;x++){var u=h[x];switch(u.status){case "added":var l=o(ko.utils.unwrapObservable(c),u.value,g),m=ko.utils.unwrapObservable(j(undefined,l,b,d,f,a));l=ko.utils.arrayIndexOf(ko.utils.unwrapObservable(c),l);r[l]=m;break;case "retained":l=o(ko.utils.unwrapObservable(c),u.value,g);m=o(a,u.value,g);j(m,l,b,d,f,a);l=ko.utils.arrayIndexOf(ko.utils.unwrapObservable(c),
l);r[l]=m;break;case "deleted":m=o(a,u.value,g);a.remove(m)}p.push({event:u.status,item:m})}a(r);b[f]&&b[f].arrayChanged&&ko.utils.arrayForEach(p,function(e){b[f].arrayChanged(e.event,e.item)})}else if(n(c)=="object"&&c!==null&&c!==undefined){if(!a)if(b[f]&&b[f].create instanceof Function){D();m=b[f].create({data:c,parent:p});ko.dependentObservable=y;return m}else a={};d.save(c,a);B(c,function(e){var i=d.get(c[e]);a[e]=i?i:j(a[e],c[e],b,d,e,a)})}else switch(n(c)){case "function":a=c;break;default:if(ko.isWriteableObservable(a))a(ko.utils.unwrapObservable(c));
else a=ko.observable(ko.utils.unwrapObservable(c))}return a}function t(a,c){var b;if(c)b=c(a);b||(b=a);return ko.utils.unwrapObservable(b)}function o(a,c,b){a=ko.utils.arrayFilter(ko.utils.unwrapObservable(a),function(d){return t(d,b)==c});if(a.length!=1)throw Error("When calling ko.update*, the key '"+c+"' was not found or not unique!");return a[0]}function v(a,c){return ko.utils.arrayMap(ko.utils.unwrapObservable(a),function(b){return c?t(b,c):b})}function B(a,c){if(a instanceof Array)for(var b=
0;b<a.length;b++)c(b);else for(b in a)c(b)}function A(){var a=[],c=[];this.save=function(b,d){var f=ko.utils.arrayIndexOf(a,b);if(f>=0)c[f]=d;else{a.push(b);c.push(d)}};this.get=function(b){b=ko.utils.arrayIndexOf(a,b);return b>=0?c[b]:undefined}}ko.mapping={};var q="__ko_mapping__",w=0,y=ko.dependentObservable,z;ko.mapping.fromJS=function(a,c,b){if(arguments.length==0)throw Error("When calling ko.fromJS, pass the object you want to convert.");var d=c;d=d||{};if(d.create instanceof Function||d.key instanceof
Function||d.arrayChanged instanceof Function)d={"":d};c=d;d=s(b,a,c);d[q]=d[q]||{};d[q]=c;return d};ko.mapping.fromJSON=function(a,c){var b=ko.utils.parseJson(a);return ko.mapping.fromJS(b,c)};ko.mapping.isMapped=function(a){return(a=ko.utils.unwrapObservable(a))&&a[q]};ko.mapping.updateFromJS=function(a,c){if(arguments.length<2)throw Error("When calling ko.updateFromJS, pass: the object to update and the object you want to update from.");if(!a)throw Error("The object is undefined.");if(!a[q])throw Error("The object you are trying to update was not created by a 'fromJS' or 'fromJSON' mapping.");
return s(a,c,a[q])};ko.mapping.updateFromJSON=function(a,c,b){c=ko.utils.parseJson(c);return ko.mapping.updateFromJS(a,c,b)};ko.mapping.toJS=function(a,c){if(arguments.length==0)throw Error("When calling ko.mapping.toJS, pass the object you want to convert.");c=c||{};c.ignore=c.ignore||[];if(!(c.ignore instanceof Array))c.ignore=[c.ignore];c.ignore.push(q);return ko.mapping.visitModel(a,function(b){return ko.utils.unwrapObservable(b)},c)};ko.mapping.toJSON=function(a,c){var b=ko.mapping.toJS(a);return ko.utils.stringifyJson(b,
c)};var D=function(){ko.dependentObservable=function(a,c,b){b=b||{};b.deferEvaluation=true;a=new y(a,c,b);a.__ko_proto__=y;z.push(a);return a}};ko.mapping.visitModel=function(a,c,b){b=b||{};b.visitedObjects=b.visitedObjects||new A;var d,f=ko.utils.unwrapObservable(a);if(n(f)=="object"&&f!==null&&f!==undefined){c(a,b.parentName);d=f instanceof Array?[]:{}}else return c(a,b.parentName);b.visitedObjects.save(a,d);var p=b.parentName;B(f,function(h){if(!(b.ignore&&ko.utils.arrayIndexOf(b.ignore,h)!=-1)){var g=
f[h];b.parentName=p||"";if(f instanceof Array){if(p)b.parentName+="["+h+"]"}else{if(p)b.parentName+=".";b.parentName+=h}switch(n(ko.utils.unwrapObservable(g))){case "object":case "undefined":var r=b.visitedObjects.get(g);d[h]=r!==undefined?r:ko.mapping.visitModel(g,c,b);break;default:d[h]=c(g,b.parentName)}}});return d};ko.exportSymbol("ko.mapping",ko.mapping);ko.exportSymbol("ko.mapping.fromJS",ko.mapping.fromJS);ko.exportSymbol("ko.mapping.fromJSON",ko.mapping.fromJSON);ko.exportSymbol("ko.mapping.isMapped",
ko.mapping.isMapped);ko.exportSymbol("ko.mapping.toJS",ko.mapping.toJS);ko.exportSymbol("ko.mapping.toJSON",ko.mapping.toJSON);ko.exportSymbol("ko.mapping.updateFromJS",ko.mapping.updateFromJS);ko.exportSymbol("ko.mapping.updateFromJSON",ko.mapping.updateFromJSON);ko.exportSymbol("ko.mapping.visitModel",ko.mapping.visitModel)})();
| mit |
MOJOv3/mojocoin | src/util.cpp | 35861 | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "util.h"
#include "chainparams.h"
#include "sync.h"
#include "ui_interface.h"
#include "uint256.h"
#include "version.h"
#include <algorithm>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/algorithm/string/case_conv.hpp> // for to_lower()
#include <boost/algorithm/string/join.hpp>
#include <boost/algorithm/string/predicate.hpp> // for startswith() and endswith()
// Work around clang compilation problem in Boost 1.46:
// /usr/include/boost/program_options/detail/config_file.hpp:163:17: error: call to function 'to_internal' that is neither visible in the template definition nor found by argument-dependent lookup
// See also: http://stackoverflow.com/questions/10020179/compilation-fail-in-boost-librairies-program-options
// http://clang.debian.net/status.php?version=3.0&key=CANNOT_FIND_FUNCTION
namespace boost {
namespace program_options {
std::string to_internal(const std::string&);
}
}
#include <boost/program_options/detail/config_file.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/foreach.hpp>
#include <boost/thread.hpp>
#include <openssl/crypto.h>
#include <openssl/rand.h>
#include <stdarg.h>
#ifdef WIN32
#ifdef _MSC_VER
#pragma warning(disable:4786)
#pragma warning(disable:4804)
#pragma warning(disable:4805)
#pragma warning(disable:4717)
#endif
#ifdef _WIN32_WINNT
#undef _WIN32_WINNT
#endif
#define _WIN32_WINNT 0x0501
#ifdef _WIN32_IE
#undef _WIN32_IE
#endif
#define _WIN32_IE 0x0501
#define WIN32_LEAN_AND_MEAN 1
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <io.h> /* for _commit */
#include "shlobj.h"
#elif defined(__linux__)
# include <sys/prctl.h>
#endif
using namespace std;
map<string, string> mapArgs;
map<string, vector<string> > mapMultiArgs;
bool fDebug = false;
bool fPrintToConsole = false;
bool fPrintToDebugLog = true;
bool fDaemon = false;
bool fServer = false;
bool fCommandLine = false;
string strMiscWarning;
bool fNoListen = false;
bool fLogTimestamps = false;
volatile bool fReopenDebugLog = false;
// Init OpenSSL library multithreading support
static CCriticalSection** ppmutexOpenSSL;
void locking_callback(int mode, int i, const char* file, int line)
{
if (mode & CRYPTO_LOCK) {
ENTER_CRITICAL_SECTION(*ppmutexOpenSSL[i]);
} else {
LEAVE_CRITICAL_SECTION(*ppmutexOpenSSL[i]);
}
}
LockedPageManager LockedPageManager::instance;
// Init
class CInit
{
public:
CInit()
{
// Init OpenSSL library multithreading support
ppmutexOpenSSL = (CCriticalSection**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(CCriticalSection*));
for (int i = 0; i < CRYPTO_num_locks(); i++)
ppmutexOpenSSL[i] = new CCriticalSection();
CRYPTO_set_locking_callback(locking_callback);
#ifdef WIN32
// Seed OpenSSL PRNG with current contents of the screen
RAND_screen();
#endif
// Seed OpenSSL PRNG with performance counter
RandAddSeed();
}
~CInit()
{
// Securely erase the memory used by the PRNG
RAND_cleanup();
// Shutdown OpenSSL library multithreading support
CRYPTO_set_locking_callback(NULL);
for (int i = 0; i < CRYPTO_num_locks(); i++)
delete ppmutexOpenSSL[i];
OPENSSL_free(ppmutexOpenSSL);
}
}
instance_of_cinit;
void RandAddSeed()
{
// Seed with CPU performance counter
int64_t nCounter = GetPerformanceCounter();
RAND_add(&nCounter, sizeof(nCounter), 1.5);
memset(&nCounter, 0, sizeof(nCounter));
}
void RandAddSeedPerfmon()
{
RandAddSeed();
// This can take up to 2 seconds, so only do it every 10 minutes
static int64_t nLastPerfmon;
if (GetTime() < nLastPerfmon + 10 * 60)
return;
nLastPerfmon = GetTime();
#ifdef WIN32
// Don't need this on Linux, OpenSSL automatically uses /dev/urandom
// Seed with the entire set of perfmon data
unsigned char pdata[250000];
memset(pdata, 0, sizeof(pdata));
unsigned long nSize = sizeof(pdata);
long ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, pdata, &nSize);
RegCloseKey(HKEY_PERFORMANCE_DATA);
if (ret == ERROR_SUCCESS)
{
RAND_add(pdata, nSize, nSize/100.0);
OPENSSL_cleanse(pdata, nSize);
LogPrint("rand", "RandAddSeed() %lu bytes\n", nSize);
}
#endif
}
uint64_t GetRand(uint64_t nMax)
{
if (nMax == 0)
return 0;
// The range of the random source must be a multiple of the modulus
// to give every possible output value an equal possibility
uint64_t nRange = (std::numeric_limits<uint64_t>::max() / nMax) * nMax;
uint64_t nRand = 0;
do
RAND_bytes((unsigned char*)&nRand, sizeof(nRand));
while (nRand >= nRange);
return (nRand % nMax);
}
int GetRandInt(int nMax)
{
return GetRand(nMax);
}
uint256 GetRandHash()
{
uint256 hash;
RAND_bytes((unsigned char*)&hash, sizeof(hash));
return hash;
}
// LogPrintf() has been broken a couple of times now
// by well-meaning people adding mutexes in the most straightforward way.
// It breaks because it may be called by global destructors during shutdown.
// Since the order of destruction of static/global objects is undefined,
// defining a mutex as a global object doesn't work (the mutex gets
// destroyed, and then some later destructor calls OutputDebugStringF,
// maybe indirectly, and you get a core dump at shutdown trying to lock
// the mutex).
static boost::once_flag debugPrintInitFlag = BOOST_ONCE_INIT;
// We use boost::call_once() to make sure these are initialized in
// in a thread-safe manner the first time it is called:
static FILE* fileout = NULL;
static boost::mutex* mutexDebugLog = NULL;
static void DebugPrintInit()
{
assert(fileout == NULL);
assert(mutexDebugLog == NULL);
boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
fileout = fopen(pathDebug.string().c_str(), "a");
if (fileout) setbuf(fileout, NULL); // unbuffered
mutexDebugLog = new boost::mutex();
}
bool LogAcceptCategory(const char* category)
{
if (category != NULL)
{
if (!fDebug)
return false;
// Give each thread quick access to -debug settings.
// This helps prevent issues debugging global destructors,
// where mapMultiArgs might be deleted before another
// global destructor calls LogPrint()
static boost::thread_specific_ptr<set<string> > ptrCategory;
if (ptrCategory.get() == NULL)
{
const vector<string>& categories = mapMultiArgs["-debug"];
ptrCategory.reset(new set<string>(categories.begin(), categories.end()));
// thread_specific_ptr automatically deletes the set when the thread ends.
}
const set<string>& setCategories = *ptrCategory.get();
// if not debugging everything and not debugging specific category, LogPrint does nothing.
if (setCategories.count(string("")) == 0 &&
setCategories.count(string(category)) == 0)
return false;
}
return true;
}
int LogPrintStr(const std::string &str)
{
int ret = 0; // Returns total number of characters written
if (fPrintToConsole)
{
// print to console
ret = fwrite(str.data(), 1, str.size(), stdout);
}
else if (fPrintToDebugLog)
{
static bool fStartedNewLine = true;
boost::call_once(&DebugPrintInit, debugPrintInitFlag);
if (fileout == NULL)
return ret;
boost::mutex::scoped_lock scoped_lock(*mutexDebugLog);
// reopen the log file, if requested
if (fReopenDebugLog) {
fReopenDebugLog = false;
boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
if (freopen(pathDebug.string().c_str(),"a",fileout) != NULL)
setbuf(fileout, NULL); // unbuffered
}
// Debug print useful for profiling
if (fLogTimestamps && fStartedNewLine)
ret += fprintf(fileout, "%s ", DateTimeStrFormat("%Y-%m-%d %H:%M:%S", GetTime()).c_str());
if (!str.empty() && str[str.size()-1] == '\n')
fStartedNewLine = true;
else
fStartedNewLine = false;
ret = fwrite(str.data(), 1, str.size(), fileout);
}
return ret;
}
void ParseString(const string& str, char c, vector<string>& v)
{
if (str.empty())
return;
string::size_type i1 = 0;
string::size_type i2;
while (true)
{
i2 = str.find(c, i1);
if (i2 == str.npos)
{
v.push_back(str.substr(i1));
return;
}
v.push_back(str.substr(i1, i2-i1));
i1 = i2+1;
}
}
string FormatMoney(int64_t n, bool fPlus)
{
// Note: not using straight sprintf here because we do NOT want
// localized number formatting.
int64_t n_abs = (n > 0 ? n : -n);
int64_t quotient = n_abs/COIN;
int64_t remainder = n_abs%COIN;
string str = strprintf("%d.%08d", quotient, remainder);
// Right-trim excess zeros before the decimal point:
int nTrim = 0;
for (int i = str.size()-1; (str[i] == '0' && isdigit(str[i-2])); --i)
++nTrim;
if (nTrim)
str.erase(str.size()-nTrim, nTrim);
if (n < 0)
str.insert((unsigned int)0, 1, '-');
else if (fPlus && n > 0)
str.insert((unsigned int)0, 1, '+');
return str;
}
bool ParseMoney(const string& str, int64_t& nRet)
{
return ParseMoney(str.c_str(), nRet);
}
bool ParseMoney(const char* pszIn, int64_t& nRet)
{
string strWhole;
int64_t nUnits = 0;
const char* p = pszIn;
while (isspace(*p))
p++;
for (; *p; p++)
{
if (*p == '.')
{
p++;
int64_t nMult = CENT*10;
while (isdigit(*p) && (nMult > 0))
{
nUnits += nMult * (*p++ - '0');
nMult /= 10;
}
break;
}
if (isspace(*p))
break;
if (!isdigit(*p))
return false;
strWhole.insert(strWhole.end(), *p);
}
for (; *p; p++)
if (!isspace(*p))
return false;
if (strWhole.size() > 10) // guard against 63 bit overflow
return false;
if (nUnits < 0 || nUnits > COIN)
return false;
int64_t nWhole = atoi64(strWhole);
int64_t nValue = nWhole*COIN + nUnits;
nRet = nValue;
return true;
}
// safeChars chosen to allow simple messages/URLs/email addresses, but avoid anything
// even possibly remotely dangerous like & or >
static string safeChars("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890 .,;_/:?@");
string SanitizeString(const string& str)
{
string strResult;
for (std::string::size_type i = 0; i < str.size(); i++)
{
if (safeChars.find(str[i]) != std::string::npos)
strResult.push_back(str[i]);
}
return strResult;
}
static const signed char phexdigit[256] =
{ -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,
-1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, };
bool IsHex(const string& str)
{
BOOST_FOREACH(unsigned char c, str)
{
if (phexdigit[c] < 0)
return false;
}
return (str.size() > 0) && (str.size()%2 == 0);
}
vector<unsigned char> ParseHex(const char* psz)
{
// convert hex dump to vector
vector<unsigned char> vch;
while (true)
{
while (isspace(*psz))
psz++;
signed char c = phexdigit[(unsigned char)*psz++];
if (c == (signed char)-1)
break;
unsigned char n = (c << 4);
c = phexdigit[(unsigned char)*psz++];
if (c == (signed char)-1)
break;
n |= c;
vch.push_back(n);
}
return vch;
}
vector<unsigned char> ParseHex(const string& str)
{
return ParseHex(str.c_str());
}
static void InterpretNegativeSetting(string name, map<string, string>& mapSettingsRet)
{
// interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
if (name.find("-no") == 0)
{
std::string positive("-");
positive.append(name.begin()+3, name.end());
if (mapSettingsRet.count(positive) == 0)
{
bool value = !GetBoolArg(name, false);
mapSettingsRet[positive] = (value ? "1" : "0");
}
}
}
void ParseParameters(int argc, const char* const argv[])
{
mapArgs.clear();
mapMultiArgs.clear();
for (int i = 1; i < argc; i++)
{
std::string str(argv[i]);
std::string strValue;
size_t is_index = str.find('=');
if (is_index != std::string::npos)
{
strValue = str.substr(is_index+1);
str = str.substr(0, is_index);
}
#ifdef WIN32
boost::to_lower(str);
if (boost::algorithm::starts_with(str, "/"))
str = "-" + str.substr(1);
#endif
if (str[0] != '-')
break;
mapArgs[str] = strValue;
mapMultiArgs[str].push_back(strValue);
}
// New 0.6 features:
BOOST_FOREACH(const PAIRTYPE(string,string)& entry, mapArgs)
{
string name = entry.first;
// interpret --foo as -foo (as long as both are not set)
if (name.find("--") == 0)
{
std::string singleDash(name.begin()+1, name.end());
if (mapArgs.count(singleDash) == 0)
mapArgs[singleDash] = entry.second;
name = singleDash;
}
// interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
InterpretNegativeSetting(name, mapArgs);
}
}
std::string GetArg(const std::string& strArg, const std::string& strDefault)
{
if (mapArgs.count(strArg))
return mapArgs[strArg];
return strDefault;
}
int64_t GetArg(const std::string& strArg, int64_t nDefault)
{
if (mapArgs.count(strArg))
return atoi64(mapArgs[strArg]);
return nDefault;
}
bool GetBoolArg(const std::string& strArg, bool fDefault)
{
if (mapArgs.count(strArg))
{
if (mapArgs[strArg].empty())
return true;
return (atoi(mapArgs[strArg]) != 0);
}
return fDefault;
}
bool SoftSetArg(const std::string& strArg, const std::string& strValue)
{
if (mapArgs.count(strArg))
return false;
mapArgs[strArg] = strValue;
return true;
}
bool SoftSetBoolArg(const std::string& strArg, bool fValue)
{
if (fValue)
return SoftSetArg(strArg, std::string("1"));
else
return SoftSetArg(strArg, std::string("0"));
}
string EncodeBase64(const unsigned char* pch, size_t len)
{
static const char *pbase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
string strRet="";
strRet.reserve((len+2)/3*4);
int mode=0, left=0;
const unsigned char *pchEnd = pch+len;
while (pch<pchEnd)
{
int enc = *(pch++);
switch (mode)
{
case 0: // we have no bits
strRet += pbase64[enc >> 2];
left = (enc & 3) << 4;
mode = 1;
break;
case 1: // we have two bits
strRet += pbase64[left | (enc >> 4)];
left = (enc & 15) << 2;
mode = 2;
break;
case 2: // we have four bits
strRet += pbase64[left | (enc >> 6)];
strRet += pbase64[enc & 63];
mode = 0;
break;
}
}
if (mode)
{
strRet += pbase64[left];
strRet += '=';
if (mode == 1)
strRet += '=';
}
return strRet;
}
string EncodeBase64(const string& str)
{
return EncodeBase64((const unsigned char*)str.c_str(), str.size());
}
vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid)
{
static const int decode64_table[256] =
{
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1,
-1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28,
29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
};
if (pfInvalid)
*pfInvalid = false;
vector<unsigned char> vchRet;
vchRet.reserve(strlen(p)*3/4);
int mode = 0;
int left = 0;
while (1)
{
int dec = decode64_table[(unsigned char)*p];
if (dec == -1) break;
p++;
switch (mode)
{
case 0: // we have no bits and get 6
left = dec;
mode = 1;
break;
case 1: // we have 6 bits and keep 4
vchRet.push_back((left<<2) | (dec>>4));
left = dec & 15;
mode = 2;
break;
case 2: // we have 4 bits and get 6, we keep 2
vchRet.push_back((left<<4) | (dec>>2));
left = dec & 3;
mode = 3;
break;
case 3: // we have 2 bits and get 6
vchRet.push_back((left<<6) | dec);
mode = 0;
break;
}
}
if (pfInvalid)
switch (mode)
{
case 0: // 4n base64 characters processed: ok
break;
case 1: // 4n+1 base64 character processed: impossible
*pfInvalid = true;
break;
case 2: // 4n+2 base64 characters processed: require '=='
if (left || p[0] != '=' || p[1] != '=' || decode64_table[(unsigned char)p[2]] != -1)
*pfInvalid = true;
break;
case 3: // 4n+3 base64 characters processed: require '='
if (left || p[0] != '=' || decode64_table[(unsigned char)p[1]] != -1)
*pfInvalid = true;
break;
}
return vchRet;
}
string DecodeBase64(const string& str)
{
vector<unsigned char> vchRet = DecodeBase64(str.c_str());
return string((const char*)&vchRet[0], vchRet.size());
}
string EncodeBase32(const unsigned char* pch, size_t len)
{
static const char *pbase32 = "abcdefghijklmnopqrstuvwxyz234567";
string strRet="";
strRet.reserve((len+4)/5*8);
int mode=0, left=0;
const unsigned char *pchEnd = pch+len;
while (pch<pchEnd)
{
int enc = *(pch++);
switch (mode)
{
case 0: // we have no bits
strRet += pbase32[enc >> 3];
left = (enc & 7) << 2;
mode = 1;
break;
case 1: // we have three bits
strRet += pbase32[left | (enc >> 6)];
strRet += pbase32[(enc >> 1) & 31];
left = (enc & 1) << 4;
mode = 2;
break;
case 2: // we have one bit
strRet += pbase32[left | (enc >> 4)];
left = (enc & 15) << 1;
mode = 3;
break;
case 3: // we have four bits
strRet += pbase32[left | (enc >> 7)];
strRet += pbase32[(enc >> 2) & 31];
left = (enc & 3) << 3;
mode = 4;
break;
case 4: // we have two bits
strRet += pbase32[left | (enc >> 5)];
strRet += pbase32[enc & 31];
mode = 0;
}
}
static const int nPadding[5] = {0, 6, 4, 3, 1};
if (mode)
{
strRet += pbase32[left];
for (int n=0; n<nPadding[mode]; n++)
strRet += '=';
}
return strRet;
}
string EncodeBase32(const string& str)
{
return EncodeBase32((const unsigned char*)str.c_str(), str.size());
}
vector<unsigned char> DecodeBase32(const char* p, bool* pfInvalid)
{
static const int decode32_table[256] =
{
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, -1, -1, -1, -1,
-1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 0, 1, 2,
3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
23, 24, 25, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
};
if (pfInvalid)
*pfInvalid = false;
vector<unsigned char> vchRet;
vchRet.reserve((strlen(p))*5/8);
int mode = 0;
int left = 0;
while (1)
{
int dec = decode32_table[(unsigned char)*p];
if (dec == -1) break;
p++;
switch (mode)
{
case 0: // we have no bits and get 5
left = dec;
mode = 1;
break;
case 1: // we have 5 bits and keep 2
vchRet.push_back((left<<3) | (dec>>2));
left = dec & 3;
mode = 2;
break;
case 2: // we have 2 bits and keep 7
left = left << 5 | dec;
mode = 3;
break;
case 3: // we have 7 bits and keep 4
vchRet.push_back((left<<1) | (dec>>4));
left = dec & 15;
mode = 4;
break;
case 4: // we have 4 bits, and keep 1
vchRet.push_back((left<<4) | (dec>>1));
left = dec & 1;
mode = 5;
break;
case 5: // we have 1 bit, and keep 6
left = left << 5 | dec;
mode = 6;
break;
case 6: // we have 6 bits, and keep 3
vchRet.push_back((left<<2) | (dec>>3));
left = dec & 7;
mode = 7;
break;
case 7: // we have 3 bits, and keep 0
vchRet.push_back((left<<5) | dec);
mode = 0;
break;
}
}
if (pfInvalid)
switch (mode)
{
case 0: // 8n base32 characters processed: ok
break;
case 1: // 8n+1 base32 characters processed: impossible
case 3: // +3
case 6: // +6
*pfInvalid = true;
break;
case 2: // 8n+2 base32 characters processed: require '======'
if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || p[4] != '=' || p[5] != '=' || decode32_table[(unsigned char)p[6]] != -1)
*pfInvalid = true;
break;
case 4: // 8n+4 base32 characters processed: require '===='
if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || decode32_table[(unsigned char)p[4]] != -1)
*pfInvalid = true;
break;
case 5: // 8n+5 base32 characters processed: require '==='
if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || decode32_table[(unsigned char)p[3]] != -1)
*pfInvalid = true;
break;
case 7: // 8n+7 base32 characters processed: require '='
if (left || p[0] != '=' || decode32_table[(unsigned char)p[1]] != -1)
*pfInvalid = true;
break;
}
return vchRet;
}
string DecodeBase32(const string& str)
{
vector<unsigned char> vchRet = DecodeBase32(str.c_str());
return string((const char*)&vchRet[0], vchRet.size());
}
bool WildcardMatch(const char* psz, const char* mask)
{
while (true)
{
switch (*mask)
{
case '\0':
return (*psz == '\0');
case '*':
return WildcardMatch(psz, mask+1) || (*psz && WildcardMatch(psz+1, mask));
case '?':
if (*psz == '\0')
return false;
break;
default:
if (*psz != *mask)
return false;
break;
}
psz++;
mask++;
}
}
bool WildcardMatch(const string& str, const string& mask)
{
return WildcardMatch(str.c_str(), mask.c_str());
}
static std::string FormatException(std::exception* pex, const char* pszThread)
{
#ifdef WIN32
char pszModule[MAX_PATH] = "";
GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
#else
const char* pszModule = "mojocoin";
#endif
if (pex)
return strprintf(
"EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
else
return strprintf(
"UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
}
void PrintException(std::exception* pex, const char* pszThread)
{
std::string message = FormatException(pex, pszThread);
LogPrintf("\n\n************************\n%s\n", message);
fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
strMiscWarning = message;
throw;
}
void PrintExceptionContinue(std::exception* pex, const char* pszThread)
{
std::string message = FormatException(pex, pszThread);
LogPrintf("\n\n************************\n%s\n", message);
fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
strMiscWarning = message;
}
boost::filesystem::path GetDefaultDataDir()
{
namespace fs = boost::filesystem;
// Windows < Vista: C:\Documents and Settings\Username\Application Data\mojocoinV3
// Windows >= Vista: C:\Users\Username\AppData\Roaming\mojocoinV3
// Mac: ~/Library/Application Support/mojocoinV3
// Unix: ~/.mojocoinV3
#ifdef WIN32
// Windows
return GetSpecialFolderPath(CSIDL_APPDATA) / "mojocoinV3";
#else
fs::path pathRet;
char* pszHome = getenv("HOME");
if (pszHome == NULL || strlen(pszHome) == 0)
pathRet = fs::path("/");
else
pathRet = fs::path(pszHome);
#ifdef MAC_OSX
// Mac
pathRet /= "Library/Application Support";
fs::create_directory(pathRet);
return pathRet / "mojocoinV3";
#else
// Unix
return pathRet / ".mojocoinV3";
#endif
#endif
}
static boost::filesystem::path pathCached[CChainParams::MAX_NETWORK_TYPES+1];
static CCriticalSection csPathCached;
const boost::filesystem::path &GetDataDir(bool fNetSpecific)
{
namespace fs = boost::filesystem;
LOCK(csPathCached);
int nNet = CChainParams::MAX_NETWORK_TYPES;
if (fNetSpecific) nNet = Params().NetworkID();
fs::path &path = pathCached[nNet];
// This can be called during exceptions by LogPrintf(), so we cache the
// value so we don't have to do memory allocations after that.
if (!path.empty())
return path;
if (mapArgs.count("-datadir")) {
path = fs::system_complete(mapArgs["-datadir"]);
if (!fs::is_directory(path)) {
path = "";
return path;
}
} else {
path = GetDefaultDataDir();
}
if (fNetSpecific)
path /= Params().DataDir();
fs::create_directory(path);
return path;
}
void ClearDatadirCache()
{
std::fill(&pathCached[0], &pathCached[CChainParams::MAX_NETWORK_TYPES+1],
boost::filesystem::path());
}
boost::filesystem::path GetConfigFile()
{
boost::filesystem::path pathConfigFile(GetArg("-conf", "mojocoin.conf"));
if (!pathConfigFile.is_complete()) pathConfigFile = GetDataDir(false) / pathConfigFile;
return pathConfigFile;
}
void ReadConfigFile(map<string, string>& mapSettingsRet,
map<string, vector<string> >& mapMultiSettingsRet)
{
boost::filesystem::ifstream streamConfig(GetConfigFile());
if (!streamConfig.good())
return; // No bitcoin.conf file is OK
set<string> setOptions;
setOptions.insert("*");
for (boost::program_options::detail::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
{
// Don't overwrite existing settings so command line settings override bitcoin.conf
string strKey = string("-") + it->string_key;
if (mapSettingsRet.count(strKey) == 0)
{
mapSettingsRet[strKey] = it->value[0];
// interpret nofoo=1 as foo=0 (and nofoo=0 as foo=1) as long as foo not set)
InterpretNegativeSetting(strKey, mapSettingsRet);
}
mapMultiSettingsRet[strKey].push_back(it->value[0]);
}
// If datadir is changed in .conf file:
ClearDatadirCache();
}
boost::filesystem::path GetPidFile()
{
boost::filesystem::path pathPidFile(GetArg("-pid", "mojocoind.pid"));
if (!pathPidFile.is_complete()) pathPidFile = GetDataDir() / pathPidFile;
return pathPidFile;
}
#ifndef WIN32
void CreatePidFile(const boost::filesystem::path &path, pid_t pid)
{
FILE* file = fopen(path.string().c_str(), "w");
if (file)
{
fprintf(file, "%d\n", pid);
fclose(file);
}
}
#endif
bool RenameOver(boost::filesystem::path src, boost::filesystem::path dest)
{
#ifdef WIN32
return MoveFileExA(src.string().c_str(), dest.string().c_str(),
MOVEFILE_REPLACE_EXISTING);
#else
int rc = std::rename(src.string().c_str(), dest.string().c_str());
return (rc == 0);
#endif /* WIN32 */
}
void FileCommit(FILE *fileout)
{
fflush(fileout); // harmless if redundantly called
#ifdef WIN32
_commit(_fileno(fileout));
#else
fsync(fileno(fileout));
#endif
}
void ShrinkDebugFile()
{
// Scroll debug.log if it's getting too big
boost::filesystem::path pathLog = GetDataDir() / "debug.log";
FILE* file = fopen(pathLog.string().c_str(), "r");
if (file && boost::filesystem::file_size(pathLog) > 10 * 1000000)
{
// Restart the file with some of the end
char pch[200000];
fseek(file, -sizeof(pch), SEEK_END);
int nBytes = fread(pch, 1, sizeof(pch), file);
fclose(file);
file = fopen(pathLog.string().c_str(), "w");
if (file)
{
fwrite(pch, 1, nBytes, file);
fclose(file);
}
}
}
static int64_t nMockTime = 0; // For unit testing
int64_t GetTime()
{
if (nMockTime) return nMockTime;
return time(NULL);
}
void SetMockTime(int64_t nMockTimeIn)
{
nMockTime = nMockTimeIn;
}
uint32_t insecure_rand_Rz = 11;
uint32_t insecure_rand_Rw = 11;
void seed_insecure_rand(bool fDeterministic)
{
//The seed values have some unlikely fixed points which we avoid.
if(fDeterministic)
{
insecure_rand_Rz = insecure_rand_Rw = 11;
} else {
uint32_t tmp;
do{
RAND_bytes((unsigned char*)&tmp,4);
}while(tmp==0 || tmp==0x9068ffffU);
insecure_rand_Rz=tmp;
do{
RAND_bytes((unsigned char*)&tmp,4);
}while(tmp==0 || tmp==0x464fffffU);
insecure_rand_Rw=tmp;
}
}
string FormatVersion(int nVersion)
{
if (nVersion%100 == 0)
return strprintf("%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100);
else
return strprintf("%d.%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100, nVersion%100);
}
string FormatFullVersion()
{
return CLIENT_BUILD;
}
// Format the subversion field according to BIP 14 spec (https://en.bitcoin.it/wiki/BIP_0014)
std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments)
{
std::ostringstream ss;
ss << "/";
ss << name << ":" << FormatVersion(nClientVersion);
if (!comments.empty())
ss << "(" << boost::algorithm::join(comments, "; ") << ")";
ss << "/";
return ss.str();
}
#ifdef WIN32
boost::filesystem::path GetSpecialFolderPath(int nFolder, bool fCreate)
{
namespace fs = boost::filesystem;
char pszPath[MAX_PATH] = "";
if(SHGetSpecialFolderPathA(NULL, pszPath, nFolder, fCreate))
{
return fs::path(pszPath);
}
LogPrintf("SHGetSpecialFolderPathA() failed, could not obtain requested path.\n");
return fs::path("");
}
#endif
void runCommand(std::string strCommand)
{
int nErr = ::system(strCommand.c_str());
if (nErr)
LogPrintf("runCommand error: system(%s) returned %d\n", strCommand, nErr);
}
void RenameThread(const char* name)
{
#if defined(PR_SET_NAME)
// Only the first 15 characters are used (16 - NUL terminator)
::prctl(PR_SET_NAME, name, 0, 0, 0);
#elif 0 && (defined(__FreeBSD__) || defined(__OpenBSD__))
// TODO: This is currently disabled because it needs to be verified to work
// on FreeBSD or OpenBSD first. When verified the '0 &&' part can be
// removed.
pthread_set_name_np(pthread_self(), name);
#elif defined(MAC_OSX) && defined(__MAC_OS_X_VERSION_MAX_ALLOWED)
// pthread_setname_np is XCode 10.6-and-later
#if __MAC_OS_X_VERSION_MAX_ALLOWED >= 1060
pthread_setname_np(name);
#endif
#else
// Prevent warnings for unused parameters...
(void)name;
#endif
}
std::string DateTimeStrFormat(const char* pszFormat, int64_t nTime)
{
// std::locale takes ownership of the pointer
std::locale loc(std::locale::classic(), new boost::posix_time::time_facet(pszFormat));
std::stringstream ss;
ss.imbue(loc);
ss << boost::posix_time::from_time_t(nTime);
return ss.str();
}
| mit |
oprema/ResQ-Pi | fileutil.py | 423 | import os, errno
class FileUtil(object):
def __init__(self, path):
self.path = os.path.join(os.getcwd(), path)
try:
os.makedirs(self.path, 0750)
except OSError as exc:
if exc.errno == errno.EEXIST and os.path.isdir(self.path):
pass
else:
raise
def path(self):
return self.path
if __name__ == "__main__":
fu = FileUtil(".progdir")
print "Path is: %s" % fu.path
| mit |
kalibao/magesko | kalibao/backend/modules/cms/components/cmsLayout/crud/ListGridRowEdit.php | 2663 | <?php
/**
* @copyright Copyright (c) 2015 Kévin Walter <walkev13@gmail.com> - Kalibao
* @license https://github.com/kalibao/magesko/blob/master/LICENSE
*/
namespace kalibao\backend\modules\cms\components\cmsLayout\crud;
use Yii;
use yii\helpers\Url;
use kalibao\common\components\crud\SimpleValueField;
use kalibao\common\components\crud\InputField;
use kalibao\common\components\i18n\I18N;
/**
* Class ListGridRowEdit
*
* @package kalibao\backend\modules\cms\components\cmsLayout\crud
* @version 1.0
* @author Kevin Walter <walkev13@gmail.com>
*/
class ListGridRowEdit extends \kalibao\common\components\crud\ListGridRowEdit
{
/**
* @inheritdoc
*/
public function init()
{
parent::init();
// models
$models = $this->getModels();
// language
$language = $this->getLanguage();
// get drop down list methods
$dropDownList = $this->getDropDownList();
// upload config
$uploadConfig['main'] = $this->uploadConfig[(new \ReflectionClass($models['main']))->getName()];
// set items
$items = [];
$items[] = new InputField([
'model' => $models['i18n'],
'attribute' => 'name',
'type' => 'activeTextInput',
'options' => [
'class' => 'form-control input-sm',
'maxlength' => true,
'placeholder' => $models['main']->getAttributeLabel('name'),
]
]);
$items[] = new InputField([
'model' => $models['main'],
'attribute' => 'max_container',
'type' => 'activeTextInput',
'options' => [
'class' => 'form-control input-sm',
'maxlength' => true,
'placeholder' => $models['main']->getAttributeLabel('max_container'),
]
]);
$items[] = new InputField([
'model' => $models['main'],
'attribute' => 'path',
'type' => 'activeTextInput',
'options' => [
'class' => 'form-control input-sm',
'maxlength' => true,
'placeholder' => $models['main']->getAttributeLabel('path'),
]
]);
$items[] = new InputField([
'model' => $models['main'],
'attribute' => 'view',
'type' => 'activeTextInput',
'options' => [
'class' => 'form-control input-sm',
'maxlength' => true,
'placeholder' => $models['main']->getAttributeLabel('view'),
]
]);
$this->setItems($items);
}
} | mit |
nano-byte/common | src/Common/INamed.cs | 747 | // Copyright Bastian Eicher
// Licensed under the MIT License
namespace NanoByte.Common;
/// <summary>
/// An entity that has a unique name that can be used for identification in lists and trees.
/// </summary>
/// <see cref="Collections.NamedCollection{T}"/>
public interface INamed
{
/// <summary>
/// A unique name for the object.
/// </summary>
[Description("A unique name for the object.")]
string Name { get; set; }
}
/// <summary>
/// Static companion for <see cref="INamed"/>.
/// </summary>
public static class Named
{
/// <summary>
/// The default separator to use in <see cref="INamed.Name"/> for tree hierarchies.
/// </summary>
public const char TreeSeparator = '|';
} | mit |
jmptable/semanter | SemanterApp/semanter/src/main/java/graphics/epi/PlaceholderFragment.java | 1303 | package graphics.epi;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.concurrent.Executor;
import java.util.concurrent.RunnableFuture;
import graphics.epi.vision.VisionExecutor;
import graphics.epi.vision.VisionListener;
import graphics.epi.vision.operations.OpDummyLong;
/**
* A placeholder fragment containing a simple view.
*/
public class PlaceholderFragment extends Fragment {
private View rootView;
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
return fragment;
}
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_overview, container, false);
return rootView;
}
}
| mit |
kevinschmidt/tvillion | config/environments/test.rb | 1528 | TVillion::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# The test environment is used exclusively to run your application's
# test suite. You never need to work with it otherwise. Remember that
# your test database is "scratch space" for the test suite and is wiped
# and recreated between test runs. Don't rely on the data there!
config.cache_classes = true
# Configure static asset server for tests with Cache-Control for performance
config.serve_static_assets = true
config.static_cache_control = "public, max-age=3600"
# Log error messages when you accidentally call methods on nil
config.whiny_nils = true
# Show full error reports and disable caching
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Raise exceptions instead of rendering exception templates
config.action_dispatch.show_exceptions = false
# Disable request forgery protection in test environment
config.action_controller.allow_forgery_protection = false
# Tell Action Mailer not to deliver emails to the real world.
# The :test delivery method accumulates sent emails in the
# ActionMailer::Base.deliveries array.
config.action_mailer.delivery_method = :test
# Raise exception on mass assignment protection for Active Record models
config.active_record.mass_assignment_sanitizer = :strict
# Print deprecation notices to the stderr
config.active_support.deprecation = :stderr
end
| mit |
kihira/Tails | src/main/java/uk/kihira/tails/client/toast/ToastManager.java | 2428 | package uk.kihira.tails.client.toast;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.profiler.IProfiler;
import net.minecraft.util.IReorderingProcessor;
import net.minecraft.util.text.StringTextComponent;
import net.minecraftforge.client.event.GuiScreenEvent;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.TickEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public final class ToastManager
{
public static final ToastManager INSTANCE = new ToastManager();
private final ArrayList<Toast> toasts = new ArrayList<>();
private ToastManager()
{
MinecraftForge.EVENT_BUS.register(this);
}
public void createToast(int x, int y, String text)
{
FontRenderer fontRenderer = Minecraft.getInstance().fontRenderer;
int stringWidth = fontRenderer.getStringWidth(text);
this.toasts.add(new Toast(x, y, stringWidth + 10, stringWidth * 3, text));
}
public void createCenteredToast(int x, int y, int maxWidth, String text)
{
FontRenderer fontRenderer = Minecraft.getInstance().fontRenderer;
int stringWidth = fontRenderer.getStringWidth(text);
if (stringWidth > maxWidth)
{
List<IReorderingProcessor> strings = fontRenderer.trimStringToWidth(new StringTextComponent(text), maxWidth);
// TODO toasts.add(new Toast(x - (maxWidth / 2) - 5, y, maxWidth + 10, text.length() * 3, strings.toArray(new IReorderingProcessor[0])));
}
else
{
this.toasts.add(new Toast(x - (stringWidth / 2) - 5, y, stringWidth + 10, text.length() * 3, text));
}
}
@SubscribeEvent
public void onClientTickPost(TickEvent.ClientTickEvent event)
{
if (event.phase == TickEvent.Phase.END)
{
this.toasts.removeIf(toast -> toast.time-- <= 0);
}
}
@SubscribeEvent
public void onDrawScreenPost(GuiScreenEvent.DrawScreenEvent.Post event)
{
IProfiler profiler = Minecraft.getInstance().getProfiler();
profiler.startSection("toastNotification");
for (Toast toast : toasts)
{
toast.drawToast(event.getMatrixStack(), event.getMouseX(), event.getMouseY());
}
profiler.endSection();
}
}
| mit |
Zonama/ZonamaDev | server/emuyoda/html/js/config.js | 177 | /**
* defines constants for application
*/
"use strict";
define(["angular"], function (angular) {
return angular.module("app.constants", []).constant("CONFIG", {});
});
| mit |
moegyver/mJeliot | Jeliot/src/avinteraction/InteractionInterface.java | 2174 | package avinteraction;
import java.awt.event.ActionListener;
import java.awt.event.WindowListener;
import avinteraction.backend.BackendInterface;
import avinteraction.parser.LanguageParserInterface;
/**
* Represents the interface for communicating with the
* AVInteraction module. Version 0.1, backend components
* missing
*
* @author Gina Haeussge, huge(at)rbg.informatik.tu-darmstadt.de
*/
public interface InteractionInterface extends ActionListener
{
//~ Methods -------------------------------------------------
/**
* called one time, loads the interaction file and sends it
* to the given parser object
*/
public void interactionDefinition(String definitionFile,
LanguageParserInterface parserObj);
/**
* called one time, loads the interaction file and sends it
* to a new animalparser object
*/
public void interactionDefinition(String definitionFile);
/**
* called one time, loads the interaction file and sends it
* to the given parser object defined by the parserType
* given in the string.
*/
public void interactionDefinition(String definitionFile,
String parserType) throws UnknownParserException;
/**
* called each time a interaction should take place,
*/
public void interaction(String interactionID) throws UnknownInteractionException;
/**
* used backend object is set to backendObj
*/
public void setBackend(BackendInterface backendObj);
/**
* gets the JFrame used for displaying the interactions
*
* @return the JFrame object used to display the
* interactions
*/
//public JFrame getFrame();
/**
* Adds a window listener. The list of window listeners
* maintained by the InteractionModule is given to
* every interaction-frame. This allows extern components
* to react to closing and opening of interaction windows.
*
* @param listener The listener to be added.
*/
public void addWindowListener (WindowListener listener);
/**
* Removes a window listener.
*
* @param listener The listener to be removed.
*/
public void removeWindowListener (WindowListener listener);
}
| mit |
yuesir/HTML5-Canvas | ch03/example-3.9/example.js | 4545 | /*
* Copyright (C) 2012 David Geary. This code is from the book
* Core HTML5 Canvas, published by Prentice-Hall in 2012.
*
* License:
*
* 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 may not be used to create training material of any sort,
* including courses, books, instructional videos, presentations, etc.
* without the express written consent of David Geary.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d'),
CENTROID_RADIUS = 10,
CENTROID_STROKE_STYLE = 'rgba(0, 0, 0, 0.5)',
CENTROID_FILL_STYLE ='rgba(80, 190, 240, 0.6)',
GUIDEWIRE_STROKE_STYLE = 'goldenrod',
GUIDEWIRE_FILL_STYLE = 'rgba(85, 190, 240, 0.6)',
TEXT_FILL_STYLE = 'rgba(100, 130, 240, 0.5)',
TEXT_STROKE_STYLE = 'rgba(200, 0, 0, 0.7)',
TEXT_SIZE = 64,
GUIDEWIRE_STROKE_STYLE = 'goldenrod',
GUIDEWIRE_FILL_STYLE = 'rgba(85, 190, 240, 0.6)',
circle = { x: canvas.width/2,
y: canvas.height/2,
radius: 200
};
// Functions.....................................................
function drawGrid(color, stepx, stepy) {
context.save()
context.shadowColor = undefined;
context.shadowOffsetX = 0;
context.shadowOffsetY = 0;
context.strokeStyle = color;
context.fillStyle = '#ffffff';
context.lineWidth = 0.5;
context.fillRect(0, 0, context.canvas.width, context.canvas.height);
for (var i = stepx + 0.5; i < context.canvas.width; i += stepx) {
context.beginPath();
context.moveTo(i, 0);
context.lineTo(i, context.canvas.height);
context.stroke();
}
for (var i = stepy + 0.5; i < context.canvas.height; i += stepy) {
context.beginPath();
context.moveTo(0, i);
context.lineTo(context.canvas.width, i);
context.stroke();
}
context.restore();
}
// Drawing functions.............................................
function drawCentroid() {
context.beginPath();
context.save();
context.strokeStyle = CENTROID_STROKE_STYLE;
context.fillStyle = CENTROID_FILL_STYLE;
context.arc(circle.x, circle.y, CENTROID_RADIUS, 0, Math.PI*2, false);
context.stroke();
context.fill();
context.restore();
}
function drawCircularText(string, startAngle, endAngle) {
var radius = circle.radius,
angleDecrement = (startAngle - endAngle)/(string.length-1),
angle = parseFloat(startAngle),
index = 0,
character;
context.save();
context.fillStyle = TEXT_FILL_STYLE;
context.strokeStyle = TEXT_STROKE_STYLE;
context.font = TEXT_SIZE + 'px Lucida Sans';
while (index < string.length) {
character = string.charAt(index);
context.save();
context.beginPath();
context.translate(
circle.x + Math.cos(angle) * radius,
circle.y - Math.sin(angle) * radius);
context.rotate(Math.PI/2 - angle);
context.fillText(character, 0, 0);
context.strokeText(character, 0, 0);
angle -= angleDecrement;
index++;
context.restore();
}
context.restore();
}
// Initialization................................................
if (navigator.userAgent.indexOf('Opera') === -1)
context.shadowColor = 'rgba(0, 0, 0, 0.4)';
context.shadowOffsetX = 2;
context.shadowOffsetY = 2;
context.shadowBlur = 5;
context.textAlign = 'center';
context.textBaseline = 'middle';
drawGrid('lightgray', 10, 10);
drawCentroid();
drawCircularText("Clockwise around the circle", Math.PI*2, Math.PI/8);
| mit |
ashutoshrishi/slate | packages/slate/test/changes/at-current-range/delete-forward/start-text-middle-inline.js | 523 | /** @jsx h */
import h from '../../../helpers/h'
export default function(change) {
change.deleteForward()
}
export const input = (
<value>
<document>
<paragraph>
<anchor />one<link>
t<focus />wo
</link>
</paragraph>
</document>
</value>
)
// TODO: this output selection seems bad
export const output = (
<value>
<document>
<paragraph>
<anchor />
<link>
<focus />wo
</link>
</paragraph>
</document>
</value>
)
| mit |
tokenhouse/solhint | lib/rules/order/separate-top-level-by-two-lines.js | 1550 | const BaseChecker = require('./../base-checker');
const BlankLineCounter = require('./../../common/blank-line-counter');
const { typeOf } = require('./../../common/tree-traversing');
class SeparateTopLevelByTwoLinesChecker extends BaseChecker {
constructor(reporter) {
super(reporter);
this.lineCounter = new BlankLineCounter();
}
enterSourceUnit(ctx) {
const lineCounter = this.lineCounter;
lineCounter.calcTokenLines(ctx);
for (let i = 0; ctx.children && i < ctx.children.length; i += 1) {
const prevItemIndex = i - 1;
const prevItem = (prevItemIndex >= 0) && ctx.children[prevItemIndex];
const curItem = ctx.children[i];
const nextItemIndex = i + 1;
const nextItem = (nextItemIndex < ctx.children.length) && ctx.children[nextItemIndex];
if (typeOf(curItem) === 'contractDefinition') {
if (prevItem.stop && lineCounter.countOfEmptyLinesBetween(prevItem, curItem) !== 2) {
this.makeReport(curItem);
continue;
}
if (nextItem.start && lineCounter.countOfEmptyLinesBetween(curItem, nextItem) !== 2) {
this.makeReport(curItem);
}
}
}
}
makeReport(ctx) {
const message = 'Definition must be surrounded with two blank line indent';
this.error(ctx, 'two-lines-top-level-separator', message);
}
}
module.exports = SeparateTopLevelByTwoLinesChecker; | mit |
ricardopereyra/SysTur | src/IM/SysTurBundle/Entity/Seguimiento.php | 4208 | <?php
namespace IM\SysTurBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Seguimiento
*
* @ORM\Table()
* @ORM\Entity(repositoryClass="IM\SysTurBundle\Entity\SeguimientoRepository")
*/
class Seguimiento
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\ManyToOne(targetEntity="File", inversedBy="seguimientos")
* @ORM\JoinColumn(name="file", referencedColumnName="id")
*/
private $file;
/**
* @ORM\ManyToOne(targetEntity="TipoSeguimiento", inversedBy="seguimientos")
* @ORM\JoinColumn(name="tipo", referencedColumnName="id")
*/
private $tipo;
/**
* @var string
*
* @ORM\Column(name="descripcion", type="text")
*/
private $descripcion;
/**
* @ORM\ManyToOne(targetEntity="Empleado", inversedBy="seguimientos")
* @ORM\JoinColumn(name="empleado", referencedColumnName="id")
*/
private $empleado;
/**
* @var \DateTime
*
* @ORM\Column(name="fechaAlta", type="datetime", nullable=true)
*/
private $fechaAlta;
/**
* @var \DateTime
*
* @ORM\Column(name="fechaBaja", type="datetime", nullable=true)
*/
private $fechaBaja;
/**
* @var \DateTime
*
* @ORM\Column(name="fechaModificacion", type="datetime", nullable=true)
*/
private $fechaModificacion;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set file
*
* @param integer $file
* @return Seguimiento
*/
public function setFile($file)
{
$this->file = $file;
return $this;
}
/**
* Get file
*
* @return integer
*/
public function getFile()
{
return $this->file;
}
/**
* Set tipo
*
* @param integer $tipo
* @return Seguimiento
*/
public function setTipo($tipo)
{
$this->tipo = $tipo;
return $this;
}
/**
* Get tipo
*
* @return integer
*/
public function getTipo()
{
return $this->tipo;
}
/**
* Set descripcion
*
* @param string $descripcion
* @return Seguimiento
*/
public function setDescripcion($descripcion)
{
$this->descripcion = $descripcion;
return $this;
}
/**
* Get descripcion
*
* @return string
*/
public function getDescripcion()
{
return $this->descripcion;
}
/**
* Set empleado
*
* @param integer $empleado
* @return Seguimiento
*/
public function setEmpleado($empleado)
{
$this->empleado = $empleado;
return $this;
}
/**
* Get empleado
*
* @return integer
*/
public function getEmpleado()
{
return $this->empleado;
}
/**
* Set fechaAlta
*
* @param \DateTime $fechaAlta
* @return Seguimiento
*/
public function setFechaAlta($fechaAlta)
{
$this->fechaAlta = $fechaAlta;
return $this;
}
/**
* Get fechaAlta
*
* @return \DateTime
*/
public function getFechaAlta()
{
return $this->fechaAlta;
}
/**
* Set fechaBaja
*
* @param \DateTime $fechaBaja
* @return Seguimiento
*/
public function setFechaBaja($fechaBaja)
{
$this->fechaBaja = $fechaBaja;
return $this;
}
/**
* Get fechaBaja
*
* @return \DateTime
*/
public function getFechaBaja()
{
return $this->fechaBaja;
}
/**
* Set fechaModificacion
*
* @param \DateTime $fechaModificacion
* @return Seguimiento
*/
public function setFechaModificacion($fechaModificacion)
{
$this->fechaModificacion = $fechaModificacion;
return $this;
}
/**
* Get fechaModificacion
*
* @return \DateTime
*/
public function getFechaModificacion()
{
return $this->fechaModificacion;
}
}
| mit |
obeattie/sqlalchemy | test/base/test_except.py | 5046 | """Tests exceptions and DB-API exception wrapping."""
from sqlalchemy import exc as sa_exceptions
from sqlalchemy.test import TestBase
# Py3K
#StandardError = BaseException
# Py2K
from exceptions import StandardError, KeyboardInterrupt, SystemExit
# end Py2K
class Error(StandardError):
"""This class will be old-style on <= 2.4 and new-style on >= 2.5."""
class DatabaseError(Error):
pass
class OperationalError(DatabaseError):
pass
class ProgrammingError(DatabaseError):
def __str__(self):
return "<%s>" % self.bogus
class OutOfSpec(DatabaseError):
pass
class WrapTest(TestBase):
def test_db_error_normal(self):
try:
raise sa_exceptions.DBAPIError.instance(
'', [], OperationalError())
except sa_exceptions.DBAPIError:
self.assert_(True)
def test_tostring(self):
try:
raise sa_exceptions.DBAPIError.instance(
'this is a message', None, OperationalError())
except sa_exceptions.DBAPIError, exc:
assert str(exc) == "(OperationalError) 'this is a message' None"
def test_tostring_large_dict(self):
try:
raise sa_exceptions.DBAPIError.instance(
'this is a message', {'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6, 'g':7, 'h':8, 'i':9, 'j':10, 'k':11}, OperationalError())
except sa_exceptions.DBAPIError, exc:
assert str(exc).startswith("(OperationalError) 'this is a message' {")
def test_tostring_large_list(self):
try:
raise sa_exceptions.DBAPIError.instance(
'this is a message', [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], OperationalError())
except sa_exceptions.DBAPIError, exc:
assert str(exc).startswith("(OperationalError) 'this is a message' [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]")
def test_tostring_large_executemany(self):
try:
raise sa_exceptions.DBAPIError.instance(
'this is a message', [{1:1},{1:1},{1:1},{1:1},{1:1},{1:1},{1:1},{1:1},{1:1},{1:1},], OperationalError())
except sa_exceptions.DBAPIError, exc:
assert str(exc) == "(OperationalError) 'this is a message' [{1: 1}, {1: 1}, {1: 1}, {1: 1}, {1: 1}, {1: 1}, {1: 1}, {1: 1}, {1: 1}, {1: 1}]", str(exc)
try:
raise sa_exceptions.DBAPIError.instance(
'this is a message', [{1:1},{1:1},{1:1},{1:1},{1:1},{1:1},{1:1},{1:1},{1:1},{1:1},{1:1},], OperationalError())
except sa_exceptions.DBAPIError, exc:
assert str(exc) == "(OperationalError) 'this is a message' [{1: 1}, {1: 1}] ... and a total of 11 bound parameter sets"
try:
raise sa_exceptions.DBAPIError.instance(
'this is a message', [(1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,)], OperationalError())
except sa_exceptions.DBAPIError, exc:
assert str(exc) == "(OperationalError) 'this is a message' [(1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,)]"
try:
raise sa_exceptions.DBAPIError.instance(
'this is a message', [(1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), ], OperationalError())
except sa_exceptions.DBAPIError, exc:
assert str(exc) == "(OperationalError) 'this is a message' [(1,), (1,)] ... and a total of 11 bound parameter sets"
def test_db_error_busted_dbapi(self):
try:
raise sa_exceptions.DBAPIError.instance(
'', [], ProgrammingError())
except sa_exceptions.DBAPIError, e:
self.assert_(True)
self.assert_('Error in str() of DB-API' in e.args[0])
def test_db_error_noncompliant_dbapi(self):
try:
raise sa_exceptions.DBAPIError.instance(
'', [], OutOfSpec())
except sa_exceptions.DBAPIError, e:
self.assert_(e.__class__ is sa_exceptions.DBAPIError)
except OutOfSpec:
self.assert_(False)
# Make sure the DatabaseError recognition logic is limited to
# subclasses of sqlalchemy.exceptions.DBAPIError
try:
raise sa_exceptions.DBAPIError.instance(
'', [], sa_exceptions.ArgumentError())
except sa_exceptions.DBAPIError, e:
self.assert_(e.__class__ is sa_exceptions.DBAPIError)
except sa_exceptions.ArgumentError:
self.assert_(False)
def test_db_error_keyboard_interrupt(self):
try:
raise sa_exceptions.DBAPIError.instance(
'', [], KeyboardInterrupt())
except sa_exceptions.DBAPIError:
self.assert_(False)
except KeyboardInterrupt:
self.assert_(True)
def test_db_error_system_exit(self):
try:
raise sa_exceptions.DBAPIError.instance(
'', [], SystemExit())
except sa_exceptions.DBAPIError:
self.assert_(False)
except SystemExit:
self.assert_(True)
| mit |
Dashron/roads | types/core/road.d.ts | 5550 | /**
* road.ts
* Copyright(c) 2021 Aaron Hedges <aaron@dashron.com>
* MIT Licensed
*
* Exposes the core Road class
*/
import Response from './response';
export interface IncomingHeaders {
[x: string]: string | Array<string> | undefined;
}
export interface Middleware<MiddlewareContext extends Context> {
(this: MiddlewareContext, method: string, path: string, body: string, headers: IncomingHeaders, next: NextCallback): Promise<Response | string> | Response | string;
}
export interface NextCallback {
(): Promise<Response | string>;
}
export interface Context {
[x: string]: unknown;
}
/**
* See roadsjs.com for full docs.
*
* @name Road
*/
export default class Road {
protected _request_chain: Middleware<Context>[];
/**
* Road Constructor
*
* Creates a new Road object
*/
constructor();
/**
* The use function can be called one or more times. Each time it is called, the function provided via the `fn` parameter will be added to the end of the *request chain* which is executed when you call `request`.
*
* | name | type | required | description |
* | ---- | ---------------------------------------------------------------------------------------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
* | fn | Function(method: *string*, url: *string*, body: *string*, headers: *object*, next: *function*) | yes | This is the function that will be added to the end of the *request chain*. See the [Middleware](#middleware) below for more details on the function parameters. |
*
* *Middleware*
* Each function in the request chain is called middleware. Each middleware function must match the following function signature.
*
* **function (method: *string*, url: *string*, body: *string*, headers: *object*, next: *next*): Promise<Response | string>**
*
* Parameters
* | name | type | description |
* | ------- | ---------------------------- | ------------------------------------------------------------------------------------------------ |
* | method | string | The request's HTTP method |
* | url | string | The request's URL. The `SimpleRouter` is included to help run different code for different URLs. |
* | body | string | The request's body (as a string). To parse this check out the `parseBodyMiddleware` |
* | headers | object | The request's headers. This is an object of strings or arrays of strings. |
* | next | function(): Promise<Response | String> | The next step of the *request chain*. If there are no more steps in the *request chain* this does nothing. This method will always return a promise, which resolves to a `Response` object, or a string. |
*
* Each middleware function must return a promise that resolves to a [Response](#response) object or a string. If you return a string it will be transformed into a response object using the default status code (200) and no headers.
*
* *See the readme for more information*
*
* @param {Function} fn - A callback (function or async function) that will be executed every time a request is made.
* @returns {Road} this road object. Useful for chaining use statements.
*/
use<ContextType extends Context>(fn: Middleware<ContextType>): Road;
/**
*
* Execute the resource method associated with the request parameters.
*
* This function will execute the *request chain* in the order they were assigned via
* [use](#roadusefunction-fn) and return a Promise that resolves to a [Response](#response)
*
* Make sure to catch any errors in the promise!
*
* @param {string} method - HTTP request method
* @param {string} url - HTTP request url
* @param {string} [body] - HTTP request body
* @param {object} [headers] - HTTP request headers
* @returns {Promise} this promise will resolve to a Response object
*/
request(method: string, url: string, body?: string, headers?: IncomingHeaders): Promise<Response>;
/**
* Turn an HTTP request into an executable function with a useful request context. Will also incorporate the entire
* request handler chain
*
* @param {string} request_method - HTTP request method
* @param {string} path - HTTP request path
* @param {string} request_body - HTTP request body
* @param {object} request_headers - HTTP request headers
* @param {Context} context - Request context
* @returns {NextMiddleware} A function that will start (or continue) the request chain
*/
protected _buildNext(request_method: string, path: string, request_body: string | undefined, request_headers: IncomingHeaders | undefined, context: Context): NextCallback;
}
| mit |
osser/ionic2-sample | ionic-preview-app/app/pages/buttons/block/pages.ts | 142 | import {Component} from '@angular/core';
@Component({
templateUrl: './build/pages/buttons/block/block.html'
})
export class BlockPage { }
| mit |
sdl/Testy | src/main/java/com/sdl/selenium/web/utils/RetryUtils.java | 14241 | package com.sdl.selenium.web.utils;
import com.google.common.base.Strings;
import org.slf4j.Logger;
import java.time.Duration;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.Callable;
public class RetryUtils {
private static final Logger log = org.slf4j.LoggerFactory.getLogger(RetryUtils.class);
public static <V> V retry(int maxRetries, Callable<V> call) {
return retry(maxRetries, null, call, false);
}
/**
* @param duration example 20 seconds
* @param call button.click()
* @param <V> type of method
* @return true or false, throw RuntimeException()
* <pre>{@code
* RetryUtils.retry(Duration.ofSeconds(10), ()-> button.click());
* }</pre>
*/
public static <V> V retry(Duration duration, Callable<V> call) {
return retry(duration, null, call, false);
}
public static <V> V retry(int maxRetries, String prefixLog, Callable<V> call) {
return retry(maxRetries, prefixLog, call, false);
}
/**
* @param duration example 20 seconds
* @param prefixLog class name
* @param call button.click()
* @param <V> type of method
* @return true or false, throw RuntimeException()
* <pre>{@code
* RetryUtils.retry(Duration.ofSeconds(10), "LoginButton", ()-> button.click());
* }</pre>
*/
public static <V> V retry(Duration duration, String prefixLog, Callable<V> call) {
return retry(duration, prefixLog, call, false);
}
public static boolean retryRunnable(int maxRetries, Runnable r) {
return retryRunnable(maxRetries, null, r, false);
}
public static boolean retryRunnable(int maxRetries, String prefixLog, Runnable r) {
return retryRunnable(maxRetries, prefixLog, r, false);
}
public static boolean retryRunnableSafe(int maxRetries, Runnable r) {
return retryRunnable(maxRetries, null, r, true);
}
public static boolean retryRunnableSafe(int maxRetries, String prefixLog, Runnable r) {
return retryRunnable(maxRetries, prefixLog, r, true);
}
private static boolean retryRunnable(int maxRetries, String prefixLog, Runnable r, boolean safe) {
int count = 0;
int wait = 0;
Fib fib = new Fib();
long startMs = System.currentTimeMillis();
do {
count++;
// wait = wait == 0 ? 5 : count < 9 ? wait * 2 : wait;
wait = count < 9 ? fibonacci(wait, fib).getResult() : wait;
Utils.sleep(wait);
try {
r.run();
return true;
} catch (Exception | AssertionError e) {
if (safe) {
return false;
} else {
if (count >= maxRetries) {
long duringMs = getDuringMillis(startMs);
log.error((Strings.isNullOrEmpty(prefixLog) ? "" : prefixLog + ":") + "Retry {} and wait {} milliseconds ->{}", count, duringMs, e);
throw new RuntimeException(e.getMessage(), e);
}
}
}
} while (count < maxRetries);
if (count > 1) {
long duringMs = getDuringMillis(startMs);
log.info((Strings.isNullOrEmpty(prefixLog) ? "" : prefixLog + ":") + "Retry {} and wait {} milliseconds", count, duringMs);
}
return true;
}
private static <V> V retry(int maxRetries, String prefixLog, Callable<V> call, boolean safe) {
int count = 0;
int wait = 0;
Fib fib = new Fib();
long startMs = System.currentTimeMillis();
V execute = null;
do {
count++;
// wait = wait == 0 ? 5 : count < 9 ? wait * 2 : wait;
wait = count < 9 ? fibonacci(wait, fib).getResult() : wait;
Utils.sleep(wait);
// log.info("Retry {} and wait {} ->!!!", count, wait);
try {
execute = call.call();
} catch (Exception | AssertionError e) {
if (!safe) {
if (count >= maxRetries) {
long duringMs = getDuringMillis(startMs);
log.error((Strings.isNullOrEmpty(prefixLog) ? "" : prefixLog + ":") + "Retry {} and wait {} milliseconds ->{}", count, duringMs, e);
throw new RuntimeException(e.getMessage(), e);
}
}
}
} while ((execute == null || isNotExpected(execute)) && count < maxRetries);
if (count > 1) {
long duringMs = getDuringMillis(startMs);
log.info((Strings.isNullOrEmpty(prefixLog) ? "" : prefixLog + ":") + "Retry {} and wait {} milliseconds", count, duringMs);
}
return execute;
}
private static <V> V retry(Duration duration, String prefixLog, Callable<V> call, boolean safe) {
int count = 0;
int wait = 0;
int limit = (int) duration.getSeconds() / 5;
Fib fib = new Fib(limit);
long startMillis = System.currentTimeMillis();
V execute = null;
do {
count++;
wait = fibonacciSinusoidal(wait, fib).getResult();
Utils.sleep(wait * 1000);
try {
execute = call.call();
} catch (Exception | AssertionError e) {
if (!safe) {
if (timeIsOver(startMillis, duration)) {
long duringMillis = getDuringMillis(startMillis);
log.error((Strings.isNullOrEmpty(prefixLog) ? "" : prefixLog + ":") + "Retry {} and wait {} milliseconds ->{}", count, duringMillis, e);
throw new RuntimeException(e.getMessage(), e);
}
}
}
} while ((execute == null || isNotExpected(execute)) && !timeIsOver(startMillis, duration));
if (count > 1) {
long duringMillis = getDuringMillis(startMillis);
log.info((Strings.isNullOrEmpty(prefixLog) ? "" : prefixLog + ":") + "Retry {} and wait {} milliseconds", count, duringMillis);
}
return execute;
}
private static boolean timeIsOver(long startMillis, Duration duration) {
long duringMillis = getDuringMillis(startMillis);
long toMillis = duration.toMillis();
return toMillis <= duringMillis;
}
private static long getDuringMillis(long startMillis) {
long endMillis = System.currentTimeMillis();
return endMillis - startMillis;
}
@Deprecated
public static <V> V retryWithSuccess(int maxRetries, Callable<V> call) {
return retry(maxRetries, call);
}
public static <V> V retrySafe(int maxRetries, Callable<V> call) {
return retry(maxRetries, null, call, true);
}
public static <V> V retrySafe(Duration duration, Callable<V> call) {
return retry(duration, null, call, true);
}
public static <V> V retrySafe(int maxRetries, String prefixLog, Callable<V> call) {
return retry(maxRetries, prefixLog, call, true);
}
public static <V> V retrySafe(Duration duration, String prefixLog, Callable<V> call) {
return retry(duration, prefixLog, call, true);
}
private static <V> boolean isNotExpected(V execute) {
if (execute instanceof Boolean) {
return !(Boolean) execute;
} else if (execute instanceof String) {
return Strings.isNullOrEmpty((String) execute);
} else if (execute instanceof List) {
List<?> list = (List<?>) execute;
return list.isEmpty() || list.stream().allMatch(Objects::isNull);
}
return execute == null;
}
/**
*
* @param duration Duration.ofSeconds(2)
* @param expected accept only: <pre>{@code Integer, String, Boolean, List<String> and List<List<String>> }</pre>
* @param call getCount();
* @param <V> expected Type
* @return expected value
*/
public static <V> V retryIfNotSame(Duration duration, V expected, Callable<V> call) {
V result = retry(duration, () -> doRetryIfNotSame(expected, call));
return result == null ? retry(0, call) : result;
}
private static <V> V doRetryIfNotSame(V expected, Callable<V> call) throws Exception {
V text = call.call();
if (text instanceof Integer && expected instanceof Integer) {
return expected == text ? text : null;
} else if (text instanceof List && expected instanceof List) {
List<?> currentList = (List<?>) text;
List<?> expectedList = (List<?>) expected;
if (currentList.get(0) instanceof List && expectedList.get(0) instanceof List) {
List<List<?>> currentListOfList = (List<List<?>>) text;
List<List<?>> expectedListOfList = (List<List<?>>) expected;
Boolean compare = null;
if (currentListOfList.size() == expectedListOfList.size()) {
for (int i = 0; i < currentListOfList.size(); i++) {
boolean match = currentListOfList.get(i).containsAll(expectedListOfList.get(i));
compare = compare == null ? match : compare && match;
}
return compare ? text : null;
} else {
return null;
}
} else {
boolean allMatch = expectedList.containsAll(currentList);
return allMatch ? text : null;
}
} else if (text instanceof String && expected instanceof String) {
return expected.equals(text) ? text : null;
} else if (text instanceof Boolean && expected instanceof Boolean) {
Boolean bolActual = (Boolean) text;
Boolean bolExpected = (Boolean) expected;
return bolExpected.equals(bolActual) ? text : null;
} else {
log.error("Expected and actual objects aren't the some type!");
return null;
}
}
/**
*
* @param maxRetries e.g 3
* @param expected accept only: <pre>{@code Integer, String, Boolean, List<String> and List<List<String>> }</pre>
* @param call getCount();
* @param <V> expected Type
* @return expected value
*/
public static <V> V retryIfNotSame(int maxRetries, V expected, Callable<V> call) {
V result = retry(maxRetries, () -> doRetryIfNotSame(expected, call));
return result == null ? retry(0, call) : result;
}
public static <V> V retryIfNotContains(Duration duration, String expected, Callable<V> call) {
V result = retry(duration, () -> {
V text = call.call();
return text instanceof String && ((String) text).contains(expected) ? text : null;
});
return result == null ? retry(0, call) : result;
}
public static <V> V retryIfNotContains(int maxRetries, String expected, Callable<V> call) {
V result = retry(maxRetries, () -> {
V text = call.call();
return text instanceof String && ((String) text).contains(expected) ? text : null;
});
return result == null ? retry(0, call) : result;
}
private static Fib fibonacci(int time, Fib fib) {
int sum = time + fib.getLast();
fib.setLast(fib.getStart());
fib.setStart(sum);
fib.setResult(sum);
// log.info((Strings.isNullOrEmpty(prefixLog) ? "" : prefixLog + ":") + "time is {}", sum);
return fib;
}
private static Fib fibonacciSinusoidal(int time, Fib fib) {
int sum = 0;
if (fib.isPositive() && time >= fib.getLimit()) {
sum = fib.getLast();
fib.setStart(fib.getStart() - fib.getLast());
fib.setLast(sum);
fib.setPositive(false);
} else if (!fib.isPositive() && time < fib.getLimit()) {
sum = fib.getStart();
fib.setStart(fib.getLast() - fib.getStart());
fib.setLast(sum);
} else if (fib.isPositive() && time >= 0) {
sum = time + fib.getLast();
fib.setLast(fib.getStart());
fib.setStart(sum);
} else {
log.info("This value is not covered!");
Utils.sleep(1);
}
if (sum <= 0) {
fib.setPositive(true);
}
fib.setResult(sum);
// log.info("result is: {}", sum);
return fib;
}
public static void main(String[] args) {
int t = 0;
for (int i = 0; i < 10; i++) {
t = RetryUtils.fibonacci(t, new Fib()).getResult();
// log.info("time is {}", t);
Utils.sleep(t);
}
}
private static class Fib {
private int start = 0;
private int last = 1;
private int result;
private int limit = 60;
private boolean positive = true;
public Fib() {
}
public Fib(int limit) {
this.limit = limit;
}
public void setStart(int start) {
this.start = start;
}
public int getStart() {
return start;
}
public void setLast(int last) {
this.last = last;
}
public int getLast() {
return last;
}
public void setResult(int result) {
this.result = result;
}
public int getResult() {
return result;
}
public int getLimit() {
return limit;
}
public void setLimit(int limit) {
this.limit = limit;
}
public boolean isPositive() {
return positive;
}
public void setPositive(boolean positive) {
this.positive = positive;
}
@Override
public String toString() {
return "Fib{" +
"start=" + start +
", last=" + last +
", result=" + result +
", limit=" + limit +
", positive=" + positive +
'}';
}
}
} | mit |
Yeasayer/YoutubeVideoPage | ytdownload/settings.py | 4708 | """
Django settings for ytdownload project.
Generated by 'django-admin startproject' using Django 1.10.4.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
import os
from django.conf import global_settings
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'jzg=tgoz086kckovf%e(5p8nnd)eu&_pa_-b2f%&xd!sp$es%+'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = [u'192.168.33.10',u'reen.co.de',u'www.reen.co.de',u'enco.dev']
# Redis/Celery Stuff goes right here
# This is for task management for things like checking subscriptions and whatnot.
CELERY_BROKER_URL = 'redis://localhost:6379'
CELERY_RESULT_BACKEND = 'redis://localhost:6379'
CELERY_ACCEPT_CONTENT = ['application/json']
CELERY_IMPORTS = ('downloadz.tasks',)
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_TIMEZONE = 'America/Chicago'
#Data upload size
DATA_UPLOAD_MAX_MEMORY_SIZE = 40000000
# Application definition
INSTALLED_APPS = [
'downloadz.apps.DownloadzConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django_ajax',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'ytdownload.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, "templates")],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'ytdownload.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'ytdownload',
'USER': 'root',
'PASSWORD': 'SafetyFirst',
'HOST': '127.0.0.1',
'OPTIONS':{
'init_command': "SET sql_mode='STRICT_TRANS_TABLES'"
}
}
}
# Password validation
# https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Memcached settings
FILE_UPLOAD_HANDLERS = ('uploadprogresscachedhandler.UploadProgressCachedHandler', )
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
# Internationalization
# https://docs.djangoproject.com/en/1.10/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/
STATIC_ROOT = os.path.join(BASE_DIR, "staticfinal/")
STATIC_URL = '/staticfinal/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static/"),
os.path.join(BASE_DIR, "downloadz/static/"),
]
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
},
'logfile': {
'level':'DEBUG',
'class':'logging.FileHandler',
'filename': BASE_DIR + "/coollogfile.log",
},
},
'root': {
'level': 'INFO',
'handlers': ['console', 'logfile']
},
} | mit |
prajesh-ananthan/java_mastery | src/main/java/com/java/mastery/lambda_expression/functional_interface/ConsumerVsSupplier.java | 1241 | package com.java.mastery.lambda_expression.functional_interface;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Supplier;
/**
* Created by ANAN011 on 18/4/2017.
*
* @author Prajesh Ananthan, arvato Systems Malaysia Sdn Bhd
* <p>
* A supplier does not take in any input
*/
public class ConsumerVsSupplier {
public static void main(String[] args) {
Supplier s = () -> Names.getNames();
displayStringWithConsumer("Hello Consumer!");
}
static void printNames(Supplier supplier) {
System.out.println(supplier.get());
}
private static void displayStringWithConsumer(String value) {
Consumer<String> supplier = System.out::println;
supplier.accept(value);
}
private ArrayList<String> getArrayListConstructor() {
Supplier<ArrayList<String>> supplier = ArrayList<String>::new;
return supplier.get();
}
}
class Names {
public static String getNames() {
List<String> names = new ArrayList<String>();
names.add("Person1");
names.add("Person2");
names.add("Person3");
String s = new String();
for (String name : names) {
s += name;
}
return s;
}
}
class SupplierTest {
}
| mit |
AlexLibs/ScriptsLoader | js/scripts_loader.js | 2261 | function ScriptsLoader(dependencyForest, callback) {
var head = document.getElementsByTagName("head")[0] || document.documentElement;
var processed = 0;
var toBeProcessed = 0;
var scriptsLoaded = {}; // to check uniqueness
function loadOne(src, innerCallback) {
toBeProcessed++;
if(scriptsLoaded[src]){
onDone();
return;
}
scriptsLoaded[src] = true;
// console.log('Loading - ' + src);
var done = false;
var script = document.createElement('script');
script.onload = script.onreadystatechange = function() {
if (!done && (!this.readyState || this.readyState === "loaded" || this.readyState === "complete")) {
done = true;
// console.log('Loaded - ' + src);
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
if (head && script.parentNode) {
head.removeChild(script);
}
onDone();
}
};
script.src = src;
script.type = 'text/javascript';
head.appendChild(script);
function onDone() {
if (typeof(innerCallback) == 'function') {
innerCallback();
};
processed++;
if ((typeof(callback) == 'function') && (processed == toBeProcessed)) {
callback(scriptsLoaded);
}
}
}
var processors = {
'[object String]': loadOne,
'[object Array]': function(array) {
for (var key in array) {
load(array[key]);
}
},
'[object Object]': function(object) {
for (var key in object) {
(function(child) {
loadOne(key, function() {
load(child);
});
})(object[key]);
}
}
};
function load(subForest) {
var processor = processors[toString.call(subForest)];
if (!processor) {
throw 'Malformated dependencyForest'
}
else {
processor(subForest);
}
}
load(dependencyForest);
};
| mit |
zavyrylin/m | lib/m/all.rb | 64 | # Make all accessible in global namespace
require "m"
include M
| mit |
chikara-chan/full-stack-javascript | manager/server/server.prod.js | 651 | import 'babel-polyfill'
import serve from 'koa-static'
import path from 'path'
import views from 'koa-views'
import app from './app'
import router from './routes'
import clientRoute from './middlewares/clientRoute'
const port = process.env.port || 3002
app.use(views(path.resolve(__dirname, '../views/prod'), {map: {html: 'ejs'}}))
app.use(serve(path.resolve(__dirname, '../dist/client')))
app.use(serve(path.resolve(__dirname, '../../public')))
app.use(clientRoute)
app.use(router.routes())
app.use(router.allowedMethods())
app.listen(port)
console.log(`\n==> 🌎 Listening on port ${port}. Open up http://localhost:${port}/ in your browser.\n`)
| mit |
f0rki/cb-multios | original-challenges/Multi_Arena_Pursuit_Simulator/poller/for-release/machine.py | 15599 | #!/usr/bin/env python
#
# Copyright (C) 2015 Narf Industries <info@narfindustries.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 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.
#
from generator.actions import Actions, Variable
import string
import random
import itertools
import math
from struct import *
class TemplateGenerator(Actions):
harborMap = [
# -10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13
[100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 13, 100, 100, 100, 100, 100], # 10
[100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 7, 6, 7, 9, 100, 100, 100], # 9
[100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 7, 5, 6, 7, 100, 100, 100, 100], # 8
[100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 5, 5, 5, 6, 7, 8, 9, 100, 100], # 7
[100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 4, 4, 5, 6, 7, 9, 9, 100, 100], # 6
[100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 3, 3, 4, 5, 6, 7, 8, 8, 100, 100], # 5
[100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 2, 2, 2, 3, 4, 5, 6, 8, 9, 9, 100, 100], # 4
[100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 1, 1, 1, 1, 2, 3, 4, 5, 6, 6, 7, 100, 100, 100], # 3
[100, 100, 100, 100, 100, 100, 100, 100, 100, 1, 1, 1, 1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 100], # 2
[100, 100, 100, 100, 100, 100, 100, 100, 100, 1, 0, 0, 1, 1, 2, 3, 4, 5, 6, 8, 9, 9, 10, 100], # 1
[100, 100, 100, 100, 100, 100, 100, 100, 100, 0, 0, 0, 1, 1, 2, 3, 4, 5, 6, 7, 8, 13, 100, 100], # 0
[100, 100, 100, 100, 100, 100, 100, 100, 13, 0, 0, 1, 1, 2, 3, 4, 5, 6, 7, 8, 8, 100, 100, 100], # -1
[100, 100, 100, 100, 100, 100, 9, 12, 13, 13, 13, 13, 2, 3, 4, 5, 6, 7, 8, 9, 100, 100, 100, 100], # -2
[100, 100, 100, 100, 100, 10, 11, 12, 12, 12, 12, 13, 3, 4, 5, 6, 7, 8, 10, 9, 100, 100, 100, 100], # -3
[100, 100, 100, 100, 100, 9, 11, 11, 11, 11, 11, 4, 4, 5, 6, 7, 8, 9, 11, 100, 100, 100, 100, 100], # -4
[100, 100, 100, 9, 100, 9, 9, 10, 10, 9, 5, 5, 5, 6, 7, 8, 10, 10, 100, 100, 100, 100, 100, 100], # -5
[100, 100, 100, 10, 10, 9, 8, 7, 6, 6, 6, 6, 6, 7, 8, 10, 9, 11, 100, 100, 100, 100, 100, 100], # -6
[100, 100, 11, 11, 10, 9, 8, 7, 7, 7, 7, 7, 7, 8, 9, 9, 100, 12, 100, 100, 100, 100, 100, 100], # -7
[100, 12, 12, 11, 10, 9, 8, 8, 8, 8, 8, 8, 8, 9, 9, 100, 100, 100, 100, 100, 100, 100, 100, 100], # -8
[100, 13, 12, 11, 10, 9, 9, 9, 9, 9, 9, 9, 9, 8, 10, 100, 100, 100, 100, 100, 100, 100, 100, 100], # -9
[100, 100, 12, 100, 10, 10, 10, 10, 10, 11, 10, 100, 12, 11, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100], # -10
[100, 100, 100, 11, 11, 11, 9, 12, 11, 12, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100], # -11
[100, 100, 100, 13, 11, 10, 12, 10, 11, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100], # -12
[100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100], # -13
[100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100] # -14
]
cityMap = [
# -2, -1, 0, 1, 2, 3, 4, 5, 6, 7
[100, 100, 100, 8, 11, 100, 100, 100, 100, 100], # 7
[100, 100, 100, 5, 8, 100, 100, 100, 100, 100], # 6
[100, 100, 3, 4, 7, 10, 100, 100, 100, 100], # 5
[100, 100, 2, 3, 4, 7, 100, 100, 100, 100], # 4
[100, 1, 1, 1, 3, 6, 9, 100, 100, 100], # 3
[100, 1, 1, 1, 2, 3, 6, 100, 100, 100], # 2
[100, 0, 0, 0, 1, 1, 5, 8, 100, 100], # 1
[100, 0, 0, 0, 1, 1, 2, 3, 100, 100], # 0
[ 9, 0, 0, 0, 1, 1, 3, 4, 5, 8], # -1
[100, 7, 4, 3, 2, 3, 4, 7, 8, 11], # -2
[100, 10, 7, 4, 3, 6, 7, 10, 100, 100], # -3
[100, 100, 8, 5, 6, 9, 100, 100, 100, 100], # -4
[100, 100, 11, 8, 100, 100, 100, 100, 100, 100] # -5
]
def _getRandomNumber(self, minN, maxN):
diff = maxN - minN + 1
num = ord(self.magic_page[self.flag_idx: self.flag_idx+1])
self.flag_idx += 1
if(self.flag_idx) == 200:
self.flag_idx = 0
num = num % diff
num += minN
return num
def _getXInBoat(self):
self.x = self._getRandomNumber(-9, 9)
def _getYInBoat(self):
if self.x == -9:
self.y = self._getRandomNumber(-9, -8)
elif self.x == -8:
self.x = -9
self.y = self._getRandomNumber(-9, -8)
elif self.x == -7:
self.y = self._getRandomNumber(-7, -5)
elif self.x == -6:
self.y = self._getRandomNumber(-10, -5)
elif self.x == -5:
self.y = self._getRandomNumber(-10, -3)
elif self.x == -4:
self.y = self._getRandomNumber(-8, -3)
elif self.x == -3:
self.y = self._getRandomNumber(-10, -2)
elif self.x == -2:
self.y = self._getRandomNumber(-10, 0)
elif self.x == -1:
self.y = self._getRandomNumber(-9, 0)
if(self.y == -1):
self.y = -2
if(self.y == 0):
self.y = -2
elif self.x == 0:
self.y = self._getRandomNumber(-9, 0)
if(self.y < 0 and self.y > -2):
self.y = -2
if(self.y >= 0 and self.y < 2):
self.y = -2
elif self.x == 1:
self.y = self._getRandomNumber(-9, 0)
if(self.y == 0):
self.y = -3
if(self.y == 1):
self.y = -3
elif self.x == 2:
self.y = self._getRandomNumber(-9, 4)
elif self.x == 3:
self.y = self._getRandomNumber(-8, 4)
elif self.x == 4:
self.y = self._getRandomNumber(-7, 5)
elif self.x == 5:
self.y = self._getRandomNumber(-5, 6)
elif self.x == 6:
self.y = self._getRandomNumber(-4, 6)
elif self.x == 7:
self.y = self._getRandomNumber(-5, 6)
elif self.x == 8:
self.y = self._getRandomNumber(0, 1)
elif self.x == 9:
self.y = self._getRandomNumber(0, 1)
def _getXInCar(self):
self.x = self._getRandomNumber(-2, 7)
def _getYInCar(self):
if self.x == -2:
self.y = -1
elif self.x == -1:
self.y = self._getRandomNumber(-3, 3)
if(self.y < 0 and self.y > -2):
self.y = -2
if(self.y > 0 and self.y < 2):
self.y = 2
elif self.x == 0:
self.y = self._getRandomNumber(-5,5)
if(self.y < 0 and self.y > -2):
self.y = -2
if(self.y >= 0 and self.y < 2):
self.y = 2
elif self.x == 1:
self.y = self._getRandomNumber(-5,7)
if(self.y < 0 and self.y > -2):
self.y = -2
if(self.y > 0 and self.y < 2):
self.y = 2
elif self.x == 2:
self.y = self._getRandomNumber(-4,7)
elif self.x == 3:
self.y = self._getRandomNumber(-4,5)
elif self.x == 4:
self.y = self._getRandomNumber(-3,3)
elif self.x == 5:
self.y = self._getRandomNumber(-3,1)
elif self.x == 6:
self.y = self._getRandomNumber(-2,-1)
elif self.x == 7:
self.y = self._getRandomNumber(-2,-1)
def _bestCriminalMove(self, x, y):
value = 0
tmp = self.harborMap[23 - y - 13][x + 10 - 1]
if tmp > value:
value = tmp
tmp = self.harborMap[23 - y - 13][x + 10 + 1]
if tmp > value:
value = tmp
tmp = self.harborMap[23 - y - 13 + 1][x + 10]
if tmp > value:
value = tmp
tmp = self.harborMap[23 - y - 13 - 1][x + 10]
if tmp > value:
value = tmp
tmp = self.harborMap[23 - y - 13 + 1][x + 10 - 1]
if tmp > value:
value = tmp
tmp = self.harborMap[23 - y - 13 - 1][x + 10 + 1]
if tmp > value:
value = tmp
return value
def _moveCriminalInBoat(self):
value = 0
bestX = self.x
bestY = self.y
x = self.x
y = self.y
if x > -11 and x < 14 and y > -14 and y < 11:
tmp = self.harborMap[23 - y - 13][x + 10]
if tmp > value:
value = tmp
bestX = self.x
bestY = self.y
x = self.x + 1
y = self.y
if x > -11 and x < 14 and y > -14 and y < 11:
tmp = self.harborMap[23 - y - 13][x + 10]
if tmp > value:
value = tmp
bestX = self.x + 1
bestY = self.y
x = self.x
y = self.y + 1
if x > -11 and x < 14 and y > -14 and y < 11:
tmp = self.harborMap[23 - y - 13][x + 10]
if tmp > value:
value = tmp
bestX = self.x
bestY = self.y + 1
x = self.x - 1
y = self.y
if x > -11 and x < 14 and y > -14 and y < 11:
tmp = self.harborMap[23 - y - 13][x + 10]
if tmp > value:
value = tmp
bestX = self.x - 1
bestY = self.y
x = self.x
y = self.y - 1
if x > -11 and x < 14 and y > -14 and y < 11:
tmp = self.harborMap[23 - y - 13][x + 10]
if tmp > value:
value = tmp
bestX = self.x
bestY = self.y - 1
x = self.x + 1
y = self.y + 1
if x > -11 and x < 14 and y > -14 and y < 11:
tmp = self.harborMap[23 - y - 13][x + 10]
if tmp > value:
value = tmp
bestX = self.x + 1
bestY = self.y + 1
x = self.x - 1
y = self.y - 1
if x > -11 and x < 14 and y > -14 and y < 11:
tmp = self.harborMap[23 - y - 13][x + 10]
if tmp > value:
value = tmp
bestX = self.x - 1
bestY = self.y - 1
self.x = bestX
self.y = bestY
#print "Criminal moves. Criminal at (" + str(self.x) + ", " + str(self.y) + ")"
def _moveCriminal(self):
value=0
bestX=self.x
bestY=self.y
tmp = self.cityMap[12-self.y-5][self.x + 2]
if tmp > value:
value = tmp
bestX = self.x
bestY = self.y
tmp = self.cityMap[12-self.y-5][self.x + 2 + 1]
if tmp > value:
value = tmp
bestX = self.x+1
bestY = self.y
tmp = self.cityMap[12-self.y-5-1][self.x + 2]
if tmp > value:
value = tmp
bestX = self.x
bestY = self.y+1
tmp = self.cityMap[12-self.y-5][self.x + 2 - 1]
if tmp > value:
value = tmp
bestX = self.x-1
bestY = self.y
tmp = self.cityMap[12-self.y-5+1][self.x + 2]
if tmp > value:
value = tmp
bestX = self.x
bestY = self.y-1
self.x = bestX
self.y = bestY
def _moveLeftInBoat(self):
newX = self.y
newY = self.y - self.x
self.x = newX - 2
self.y = newY - 2
#print "Move Left. Criminal at (" + str(self.x) + ", " + str(self.y) + ")"
return 'L'
def _moveForwardInBoat(self):
self.x = self.x - 2
self.y = self.y - 2
#print "Move Forward. Criminal at (" + str(self.x) + ", " + str(self.y) + ")"
return 'F'
def _moveRightInBoat(self):
newX = self.x - self.y
newY = self.x
self.x = newX - 2
self.y = newY - 2
#print "Move Right. Criminal at (" + str(self.x) + ", " + str(self.y) + ")"
return 'R'
def _moveForward(self):
self.y = self.y - 2
return 'F'
def _moveRight(self):
newX = self.y * -1
newY = self.x - 2
self.x = newX;
self.y = newY;
return 'R'
def _makeMoveInBoat(self):
value=100
move = ''
y = self.y - self.x - 2
x = self.y - 2
if x > -11 and x < 14 and y > -14 and y < 11:
tmp = self.harborMap[23 - y - 13][x + 10]
if tmp < 100:
tmp = self._bestCriminalMove(x, y)
if tmp < value:
value = tmp
move = 'L'
y = self.y - 2
x = self.x - 2
if x > -11 and x < 14 and y > -14 and y < 11:
tmp = self.harborMap[23 - y - 13][x + 10]
if tmp < 100:
tmp = self._bestCriminalMove(x, y)
if tmp < value:
value = tmp
move = 'F'
y = self.x - 2
x = self.x - self.y - 2
if x > -11 and x < 14 and y > -14 and y < 11:
tmp = self.harborMap[23 - y - 13][x + 10]
if tmp < 100:
tmp = self._bestCriminalMove(x, y)
if tmp < value:
value = tmp
move = 'R'
if(move == 'L'):
return self._moveLeftInBoat()
elif(move == 'F'):
return self._moveForwardInBoat()
else:
return self._moveRightInBoat()
def _makeMoveInCar(self):
if self.y < 1 or self.x < -1:
return self._moveRight()
else:
return self._moveForward()
def start(self):
#self.delay(100)
self.flag_idx = 0
def catchCriminalInCar(self):
for i in range(100):
self._getXInCar()
self._getYInCar()
#self.x = 4
#self.y = -1
criminal_str = "Criminal at (" + str(self.x) + ", " + str(self.y) + ")\n"
self.read(delim="\n", expect=criminal_str)
move_str = self._makeMoveInCar() + "#"
while not (self.x > -2 and self.x < 2 and self.y > -2 and self.y < 2):
self._moveCriminal()
move_str += self._makeMoveInCar() + "#"
self.write(move_str)
caught_str = 'Criminal caught in ([0-9]*) moves\n'
self.read(delim="\n", expect=caught_str, expect_format='pcre')
def catchCriminalInBoat(self):
for i in range(100):
self._getXInBoat()
self._getYInBoat()
criminal_str = "Criminal at (" + str(self.x) + ", " + str(self.y) + ")\n"
self.read(delim="\n", expect=criminal_str)
move_str = self._makeMoveInBoat() + "#"
while not self.harborMap[23 - self.y - 13][self.x + 10] == 0:
self._moveCriminalInBoat()
move_str += self._makeMoveInBoat() + "#"
self.write(move_str)
caught_str = 'Criminal caught in ([0-9]*) moves\n'
self.read(delim="\n", expect=caught_str, expect_format='pcre')
def attack1(self):
self.catchCriminalInCar()
self._getXInBoat()
self._getYInBoat()
self.x = 4
self.y = -1
moves = 0
criminalX_re = r'Criminal at \((-?\d+),'
criminalY_re = r' (-?\d+)\)\n'
criminalX = Variable('criminalX')
criminalY = Variable('criminalY')
criminalX.set_re(criminalX_re, group=1)
criminalY.set_re(criminalY_re, group=1)
#criminal_str = "Criminal at (" + str(self.x) + ", " + str(self.y) + ")\n"
#self.read(delim="\n", expect=criminal_str)
self.read(delim=",", assign=criminalX)
self.read(delim="\n", assign=criminalY)
move_str = self._makeMoveInBoat() + "#"
moves += 1
while moves < 100000:
while not self.harborMap[23 - self.y - 13][self.x + 10] == 1:
self._moveCriminalInBoat()
move_str += self._makeMoveInBoat() + "#"
moves += 1
self._moveCriminalInBoat()
move_str += self._moveLeftInBoat() + "#"
moves += 1
while not self.harborMap[23 - self.y - 13][self.x + 10] == 0:
self._moveCriminalInBoat()
move_str += self._makeMoveInBoat() + "#"
self.write(move_str)
caught_str = 'Criminal caught in ([0-9]*) moves\n'
self.read(delim="\n", expect=caught_str, expect_format='pcre')
flag_re = r'(.*)'
flag = Variable('flag')
flag.set_re(flag_re, group=1)
self.read(length=40, assign=flag)
def quit(self):
return -1
| mit |
lftzzzzfeng/myaolin | application/views/main/food/index.php | 7139 | <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<title><?php echo $pageTitle; ?></title>
<link rel="stylesheet" href="<?php echo base_url() ?>ui/css/mobile/bootstrap.css"/>
<link rel="stylesheet" type="text/css" href="<?php echo base_url() ?>ui/css/mobile/normalize.css" />
<link rel="stylesheet" type="text/css" href="<?php echo base_url() ?>ui/css/mobile/demo.css">
<link href="http://cdn.bootcss.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet">
<link rel="stylesheet" href="<?php echo base_url() ?>ui/css/mobile/style.css">
<link href="<?php echo base_url() ?>ui/css/mobile/css.css" rel="stylesheet"/>
<link rel="stylesheet" href="<?php echo base_url() ?>ui/css/mobile/essentials.css"/>
<link rel="stylesheet" href="<?php echo base_url() ?>ui/css/mobile/photoswipe.css"/>
<link rel="stylesheet" href="<?php echo base_url() ?>ui/css/mobile/default-skin.css"/>
<link rel="stylesheet" href="<?php echo base_url() ?>ui/css/mobile/jd.css"/>
<script src="<?php echo base_url() ?>ui/js/mobile/jquery-2.1.4.min.js"></script>
<script src="<?php echo base_url() ?>ui/js/mobile/bootstrap.min.js"></script>
<script src='<?php echo base_url() ?>ui/js/mobile/jquery-2.1.4.min.js'></script>
<script src='<?php echo base_url() ?>ui/js/mobile/velocity.min.js'></script>
<script src='<?php echo base_url() ?>ui/js/mobile/sideToggleExtended.js'></script>
<script src="<?php echo base_url() ?>ui/js/mobile/ss.js"></script>
<script src="<?php echo base_url() ?>ui/js/mobile/photoswipe.min.js"></script>
<script src="<?php echo base_url() ?>ui/js/mobile/photoswipe-ui-default.min.js"></script>
<script type="text/javascript">
document.addEventListener('plusready', function(){
//console.log("所有plus api都应该在此事件发生后调用,否则会出现plus is undefined。"
});
</script>
</head>
<body style="background: #e5e5e5;">
<a id="a"><div class="top"></div></a>
<!--banner-->
<div class="relative">
<img src="<?php echo base_url() ?>ui/img/mobile/chi_banner.jpg" width="100%" alt=""/>
<div class="banner_txt_food col-xs-6 col-sm-4 col-xs-offset-3 col-sm-offset-4 tex-white text-center">
<p class="p1 size-10 margin-bottom-5">
<span class="block margin-bottom-6"><img src="<?php echo base_url() ?>ui/img/mobile/icon_yuan_03.png" alt=""/></span>
<span class="">YAOLIN</span><br/><span>INTO NATURE</span>
</p>
<p class="size-25 weight-800 margin-bottom-5 ipad_size">吃在瑶琳</p>
<p class="p3 size-12 color_blue margin-bottom-5"><span>NICE TRIP</span><br/><span>TRAVEL SERVICE</span></p>
</div>
<div class="you_fh" onclick="window.history.go(-1);"><a><img src="<?php echo base_url() ?>ui/img/mobile/fanhui.png" style="height:80%;width: 70%"/></a></div>
</div>
<div class="chi_con">
<div class="chi_top">
<p class="chi_p">瑶琳美食 (DELICIOUS FOODS)</p>
<p class="chi_pa">特色小吃是中国饮食不可缺少的一部分,并成为中国饮食生活的主要内容之一。在中国的每个地区都有着其独特的小吃,被称为当地的特色小吃。这种小吃,已经是一种在当地的饮食文化,绝非只是在三餐之间填饱肚子,追求不饿肚子的层次。<br />
瑶琳特色美食将瑶琳文化展现的淋漓尽致,那我们就来看看瑶琳美食吧。</p>
<img src="<?php echo base_url() ?>ui/img/mobile/chi_1.jpg" />
</div>
<div class="chi_meau">
<p class="meau_p">菜单(MENU)</p>
<div class="meau_con" style="width:100%; padding: 15px 1%;">
<ul class="meau_ul" id="foods">
<?php foreach ($food['food'] as $k => $v){ ?>
<li>
<img src="<?php echo $v['coverImage'] ?>" style="height:115px;"/>
<p class="mli_p"><a href="#"><?php echo $v['title'] ?></a></p>
<p class="mli_pa"><?php echo $v['description'] ?></p>
</li>
<?php } ?>
</ul>
</div>
<?php if($num == 1){ ?>
<div class="look_more text-center margin-bottom-10 clearfix" style="background:#f8f8f8;">
<input id="food" value="1" type="hidden">
<button class="flex_box margin-0-auto btn radius-0 size-16" onclick="food()" id="jzgds"><span id="jzgd">加载更多 </span> <img src="<?php echo base_url() ?>ui/img/mobile/icon_btn_03.png" width="13%" alt=""/></button>
</div>
<?php } ?>
</div>
<div class="chi_zs">
<div id="myCarousel" class="carousel slide">
<!-- 轮播(Carousel)指标 -->
<ol class="carousel-indicators" style="bottom: 0;">
<li data-target="#myCarousel" data-slide-to="0" class="active"></li>
<li data-target="#myCarousel" data-slide-to="1"></li>
<li data-target="#myCarousel" data-slide-to="2"></li>
</ol>
<!-- 轮播(Carousel)项目 -->
<div class="carousel-inner">
<div class="item active">
<img src="<?php echo base_url() ?>ui/img/mobile/chi_4.jpg" alt="First slide">
</div>
<div class="item">
<img src="<?php echo base_url() ?>ui/img/mobile/chi_4.jpg" alt="Second slide">
</div>
<div class="item">
<img src="<?php echo base_url() ?>ui/img/mobile/chi_4.jpg" alt="Third slide">
</div>
</div>
</div>
</div>
<div class="chi_dc">
<div class="chi_dcl"><img src="<?php echo base_url() ?>ui/img/mobile/chi_dc.jpg" /></div>
<div class="chi_dcr">
<p class="dc_p">瑶琳大厨</p>
<p class="dc_pa">董华建</p>
<p class="dc_pb"> 2000年1月——2017年任职瑶琳国家森林公园行政总厨,期间成功策划过湖南穗满圆大酒店,昆明湘水人家,大连鱼鹅港大饭店等等,并在此间多次参加全国烹饪大赛。</p>
</div>
</div>
</div>
<script type="text/javascript">
var url = "<?php echo base_url(); ?>";
function food() {
var p = $('#food').val();
var ps = parseInt(p)+1
$('#food').val(ps);
$.post(url+'food/ajaxFood?p='+ps,function(data){
$('#foods').append(data.html);
if(data.num == 2){
$('#jzgd').html('没有更多了');
$('#jzgds').css('background-color','#808080');
$("#jzgds").attr("onclick","");
}
},'json');
}
</script> | mit |
jakobabesser/pymus | pymus/tools.py | 7333 | # try to import libsoundfile for audio import, alternatively try loading audio via scipy or wave
try:
import soundfile
soundfile_found = True
except ImportError:
from scipy.io.wavfile import read
import wave
soundfile_found = False
import numpy as np
import os
__author__ = 'Jakob Abesser'
class Tools:
""" Class provides several tools for audio analysis
"""
def __init__(self):
pass
@staticmethod
def set_missing_values(options,
**default_frame_wise_values):
""" Add default frame_wise_values & keys to dictionary if frame_wise_values are not set
Args:
options (dict): Arbitrary dictionary (e.g. containing processing options)
default_frame_wise_values (dict): Keyword list with default frame_wise_values to be set if corresponding
keys are not set in options dict
Returns:
options (dict): Arbitrary dictionary with added default frame_wise_values if required
"""
for param in default_frame_wise_values.keys():
if param not in options:
options[param] = default_frame_wise_values[param]
return options
@staticmethod
def load_wav(fn_wav,
mono=False):
""" Function loads samples from WAV file. Both implementations (wave / scipy package) fail for some WAV files
hence we combine them.
Args:
fn_wav (string): WAV file name
mono (bool): Switch if samples shall be converted to mono
Returns:
samples (np array): Audio samples (between [-1,1]
> if stereo: (2D ndarray with DIM numSamples x numChannels),
> if mono: (1D ndarray with DIM numSamples)
sample_rate (float): Sampling frequency [Hz]
"""
if soundfile_found:
samples, sample_rate = soundfile.read(fn_wav)
else:
try:
samples, sample_rate = Tools._load_wav_file_via_scipy(fn_wav)
except:
try:
samples, sample_rate = Tools._load_wav_file_via_wave(fn_wav)
except:
raise Exception("WAV file could neither be opened using Scipy nor Wave!")
# mono conversion
if mono:
if samples.ndim == 2:
if samples.shape[1] > 1:
samples = np.mean(samples, axis=1)
else:
samples = np.squeeze(samples)
# scaling
if np.max(np.abs(samples)) > 1:
samples = samples.astype(float) / 32768.0
return samples, sample_rate
@staticmethod
def _load_wav_file_via_wave(fn_wav):
""" Load samples & sample rate from WAV file """
fp = wave.open(fn_wav)
num_channels = fp.getnchannels()
num_frames = fp.getnframes()
frame_string = fp.readframes(num_frames*num_channels)
data = np.fromstring(frame_string, np.int16)
samples = np.reshape(data, (-1, num_channels))
sample_rate = float(fp.getframerate())
return samples, sample_rate
@staticmethod
def _load_wav_file_via_scipy(fn_wav):
""" Load samples & sample rate from WAV file """
inputData = read(fn_wav)
samples = inputData[1]
sample_rate = inputData[0]
return samples, sample_rate
@staticmethod
def aggregate_framewise_function_over_notes(frame_wise_values,
time_sec,
onset,
duration):
""" Aggregate a frame-wise function (e.g. loudness) over note durations to obtain note-wise features
:param frame_wise_values: (ndarray) Frame-wise values
:param time_sec: (ndarray) Time frame frame_wise_values in seconds
:param onset: (ndarray) Note onset times in seconds
:param duration: (ndarray) Note durations in seconds
:return: result: (dict of ndarrays) Note-wise aggregation results with keys
'max': Maximum over note duration
'median': Median over note duration
'std': Standard deviation over note duration
'temp_centroid': Temporal centroid over note duration [0,1]
'rel_peak_pos': Position of global maximum over note duration relative to note duration [0,1]
"""
dt = time_sec[1]-time_sec[0]
num_notes = len(onset)
onset_frame = (onset/dt).astype(int)
offset_frame = ((onset+duration)/dt).astype(int)
# initialize
result = dict()
result['max'] = np.zeros(num_notes)
result['median'] = np.zeros(num_notes)
result['std'] = np.zeros(num_notes)
result['temp_centroid'] = np.zeros(num_notes)
result['rel_peak_pos'] = np.zeros(num_notes)
for n in range(num_notes):
curr_frame_wise_values = frame_wise_values[onset_frame[n]:offset_frame[n]+1]
num_frames_curr = len(curr_frame_wise_values)
result['max'][n] = np.max(curr_frame_wise_values)
result['median'][n] = np.median(curr_frame_wise_values)
result['std'][n] = np.std(curr_frame_wise_values, ddof=1) # same result as in Matlab
result['temp_centroid'][n] = np.sum(np.linspace(0, 1, num_frames_curr)*curr_frame_wise_values)/np.sum(curr_frame_wise_values)
if num_frames_curr > 1:
result['rel_peak_pos'][n] = float(np.argmax(curr_frame_wise_values))/(num_frames_curr-1)
else:
result['rel_peak_pos'][n] = 0
return result
@staticmethod
def quadratic_interpolation(x):
""" Peak refinement using quadratic interpolation.
Args:
x (ndarray): 3-element numpy array. Central element was identified as local peak before
(e.g. using numpy.argmax)
Returns:
peak_pos (float): Interpolated peak position (relative to central element)
peak_val (float): Interpolated peak value
"""
peak_pos = (x[2] - x[0])/(2*(2*x[1] - x[2] - x[0]))
peak_val = x[1] - 0.25*(x[0]-x[2])*peak_pos
return peak_pos, peak_val
@staticmethod
def moving_average_filter(x,
N=5):
""" Moving average on a vector
Args:
x (ndarray): Input vector
N (int): Filter length
Returns
y (ndarry): Filtered vector
"""
return np.convolve(x, np.ones((N,))/N, mode='valid')
@staticmethod
def acf(x):
""" Autocorrelation function
Args:
x (ndarray): Input function
Returns:
acf (ndarray): Autocorrelation function
"""
result = np.correlate(x, x, mode='full')
return result[result.size/2:]
@staticmethod
def get_file_path_for_test_data(fn):
""" Get path for test data
:param fn: file name
:return: absolute path of filename in subfolder /test/data
"""
return os.path.join(os.path.abspath(os.path.dirname(__file__)), 'test', 'data', fn)
| mit |
Eernie/JMoribus | core/src/main/java/nl/eernie/jmoribus/parser/ReferringScenario.java | 344 | package nl.eernie.jmoribus.parser;
import nl.eernie.jmoribus.model.Scenario;
import nl.eernie.jmoribus.model.StepContainer;
class ReferringScenario extends Scenario
{
public ReferringScenario(String combinedStepLines, StepContainer prologueOrScenario)
{
this.setStepContainer(prologueOrScenario);
this.setTitle(combinedStepLines);
}
}
| mit |
kevholditch/Rotation | Tests/Rotation.Tests/Game1.cs | 2600 | using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace Rotation.GameObjects.sTests
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class Game1 : Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
// TODO: Add your initialization logic here
base.Initialize();
}
/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
// TODO: use this.Content to load your game content here
}
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// all content.
/// </summary>
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
// TODO: Add your update logic here
base.Update(gameTime);
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
// TODO: Add your drawing code here
base.Draw(gameTime);
}
}
}
| mit |
mscherotter/spotlists | SpotLists.WP8/SpotLists.WP8/BeatsMusic/TokenResponse.cs | 306 | using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SpotLists.WP8.BeatsMusic
{
public class TokenResponse
{
[JsonProperty("result")]
public TokenResult Result { get; set; }
}
}
| mit |
GabGab/api_ai_wrapper | lib/api_ai_wrapper/extensions/string.rb | 448 | # String Override taken from Rails
class String
def demodulize
if i = self.rindex("::")
self[(i + 2)..-1]
else
self
end
end
def underscore
return self unless /[A-Z-]|::/.match?(self)
word = self.gsub("::".freeze, "/".freeze)
word.gsub!(/([A-Z\d]+)([A-Z][a-z])/, '\1_\2'.freeze)
word.gsub!(/([a-z\d])([A-Z])/, '\1_\2'.freeze)
word.tr!("-".freeze, "_".freeze)
word.downcase!
word
end
end | mit |
oscarguindzberg/multibit-hd | mbhd-swing/src/test/java/org/multibit/hd/ui/fest/use_cases/sidebar/settings/language/ShowThenCancelLanguageUseCase.java | 1311 | package org.multibit.hd.ui.fest.use_cases.sidebar.settings.language;
import org.fest.swing.fixture.FrameFixture;
import org.multibit.hd.ui.fest.use_cases.AbstractFestUseCase;
import org.multibit.hd.ui.languages.MessageKey;
import java.util.Map;
/**
* <p>Use case to provide the following to FEST testing:</p>
* <ul>
* <li>Verify the "settings" screen languages wizard shows</li>
* </ul>
* <p>Requires the "settings" screen to be showing</p>
*
* @since 0.0.1
*
*/
public class ShowThenCancelLanguageUseCase extends AbstractFestUseCase {
public ShowThenCancelLanguageUseCase(FrameFixture window) {
super(window);
}
@Override
public void execute(Map<String, Object> parameters) {
// Click on "languages"
window
.button(MessageKey.SHOW_LANGUAGE_WIZARD.getKey())
.click();
// Verify the "language" wizard appears
assertLabelText(MessageKey.LANGUAGE_SETTINGS_TITLE);
// Verify cancel is present
window
.button(MessageKey.CANCEL.getKey())
.requireVisible()
.requireEnabled();
// Click Cancel
window
.button(MessageKey.CANCEL.getKey())
.click();
// Verify the underlying screen is back
window
.button(MessageKey.SHOW_LANGUAGE_WIZARD.getKey())
.requireVisible()
.requireEnabled();
}
}
| mit |
Snarkie/YGOProAIScript | AI/mod/AIHelperFunctions.lua | 62989 | -----------------------------------------
-- AIHelperFunctions.lua
--
-- A set of functions for use with ai.lua
--
-- Parameters (none):
-----------------------------------------
-- This file is divided into sections
-- for easier use.
-----------------------------------------
-------------------------------------------------
-- **********************************************
-- Functions to shorten names of general functions
-- for better access in future.
-- **********************************************
-------------------------------------------------
function AIMon()
local list = {}
local AIMon = AI.GetAIMonsterZones()
for i=1,#AIMon do
if AIMon[i] ~= false then
list[#list+1]=AIMon[i]
end
end
return list
end
function OppMon()
local list = {}
local OppMon = AI.GetOppMonsterZones()
for i=1,#OppMon do
if OppMon[i] ~= false then
list[#list+1]=OppMon[i]
end
end
return list
end
function AIST()
local list = {}
local AIST = AI.GetAISpellTrapZones()
for i=1,#AIST do
if AIST[i] ~= false then
list[#list+1]=AIST[i]
end
end
return list
end
function AIPendulum()
local list = {}
local AIST = AI.GetAISpellTrapZones()
for i=7,8 do
if AIST[i] ~= false then
list[#list+1]=AIST[i]
end
end
return list
end
function OppPendulum()
local list = {}
local AIST = AI.GetOppSpellTrapZones()
for i=7,8 do
if AIST[i] ~= false then
list[#list+1]=AIST[i]
end
end
return list
end
function AllPendulum()
return UseLists(AIPendulum(),OppPendulum())
end
function OppST()
local list = {}
local OppST = AI.GetOppSpellTrapZones()
for i=1,#OppST do
if OppST[i] ~= false then
list[#list+1]=OppST[i]
end
end
return list
end
function AIGrave()
local list = {}
local AIGrave = AI.GetAIGraveyard()
for i=1,#AIGrave do
if AIGrave[i] ~= false then
list[#list+1]=AIGrave[i]
end
end
return list
end
function OppGrave()
local list = {}
local OppGrave = AI.GetOppGraveyard()
for i=1,#OppGrave do
if OppGrave[i] ~= false then
list[#list+1]=OppGrave[i]
end
end
return list
end
function AIBanish()
local list = {}
local AIBanish = AI.GetAIBanished()
for i=1,#AIBanish do
if AIBanish[i] ~= false then
list[#list+1]=AIBanish[i]
end
end
return list
end
function OppBanish()
local list = {}
local OppBanish = AI.GetOppBanished()
for i=1,#OppBanish do
if OppBanish[i] ~= false then
list[#list+1]=OppBanish[i]
end
end
return list
end
function AIHand()
local list = {}
local AIHand = AI.GetAIHand()
for i=1,#AIHand do
if AIHand[i] ~= false then
list[#list+1]=AIHand[i]
end
end
return list
end
function OppHand()
local list = {}
local OppHand = AI.GetOppHand()
for i=1,#OppHand do
if OppHand[i] ~= false then
list[#list+1]=OppHand[i]
end
end
return list
end
function AIDeck()
local list = {}
local AIDeck = AI.GetAIMainDeck()
for i=1,#AIDeck do
if AIDeck[i] ~= false then
list[#list+1]=AIDeck[i]
end
end
return list
end
function OppDeck()
local list = {}
local OppDeck = AI.GetOppMainDeck()
for i=1,#OppDeck do
if OppDeck[i] ~= false then
list[#list+1]=OppDeck[i]
end
end
return list
end
function AIExtra()
local list = {}
local AIExtra = AI.GetAIExtraDeck()
for i=1,#AIExtra do
if AIExtra[i] ~= false then
list[#list+1]=AIExtra[i]
end
end
return list
end
function OppExtra()
local list = {}
local OppExtra = AI.GetOppExtraDeck()
for i=1,#OppExtra do
if OppExtra[i] ~= false then
list[#list+1]=OppExtra[i]
end
end
return list
end
function Merge(lists,opt,opt2)
local cards
local Result={}
if lists then
if type(lists)~="table" then
print("Warning: Merge invalid type")
PrintCallingFunction()
return Result
end
if opt and type(opt)~="table" then
print("Warning: Merge invalid type")
PrintCallingFunction()
return Result
end
if opt2 and type(opt2)~="table" then
print("Warning: Merge invalid type")
PrintCallingFunction()
return Result
end
if opt then
for i=1,#lists do
Result[#Result+1]=lists[i]
end
for i=1,#opt do
Result[#Result+1]=opt[i]
end
if opt2 then
for i=1,#opt2 do
Result[#Result+1]=opt2[i]
end
end
else
for i=1,#lists do
cards = lists[i]
if cards then
for j=1,#cards do
Result[#Result+1]=cards[j]
end
end
end
end
end
return Result
end
function UseLists(lists,opt,opt2)
return Merge(lists,opt,opt2)
end
function AIField()
return UseLists({AIMon(),AIST()})
end
function OppField()
return UseLists({OppMon(),OppST()})
end
function AICards()
return UseLists(AIField(),AIHand())
end
function OppCards()
return UseLists(OppField(),OppHand())
end
function AIAll()
return UseLists({AIHand(),AIField(),AIGrave(),AIDeck(),AIBanish(),AIExtra()})
end
function OppAll()
return UseLists({OppHand(),OppField(),OppGrave(),OppDeck(),OppBanish(),OppExtra()})
end
function Field()
return UseLists(AIField(),OppField())
end
function All()
return UseLists(AIAll(),OppAll())
end
function AllMon()
return UseLists(AIMon(),OppMon())
end
function AllST()
return UseLists(AIST(),OppST())
end
function AIMaterials()
local result = {}
for i=1,#AIMon() do
local cards = AIMon()[i].xyz_materials
if cards and #cards>0 then
result = UseLists(result,cards)
end
end
return result
end
function OppMaterials()
local result = {}
for i=1,#OppMon() do
local cards = OppMon()[i].xyz_materials
if cards and #cards>0 then
result = UseLists(result,cards)
end
end
return result
end
-------------------------------------------------
-- **********************************************
-- Functions related to monster count returning,
-- using specified parameters.
-- **********************************************
-------------------------------------------------
---------------------------------------
-- Returns the total number of cards in
-- specified location
--
-- Parameters (1):
-- Cards = array of cards for search
---------------------------------------
function Get_Card_Count(Cards)
local Result = 0
for i=1,#Cards do
if Cards[i] ~= false then
Result = Result + 1
end
end
return Result
end
---------------------------------------
-- Returns the total number of cards in
-- specified location who are in
-- specified position
--
-- Parameters (2):
-- Cards = array of cards for search
-- Position = Specified position of the card
---------------------------------------
function Get_Card_Count_Pos(Cards, Position)
local Result = 0
for i=1,#Cards do
if bit32.band(Cards[i].position,Position) > 0 then
Result = Result + 1
end
end
return Result
end
---------------------------------------
-- Returns the total number of cards in
-- specified location who are of
-- specified ID
--
-- Parameters (3):
-- Cards = first array of cards for search
-- CardID = Specified id of the card
-- Position = Card's position
---------------------------------------
function Get_Card_Count_ID(Cards, CardID, Position)
local Result = 0
for i=1,#Cards do
if (Position == nil or bit32.band(Cards[i].position,Position) > 0) and
(CardID == nil or Cards[i].id == CardID) then
Result = Result + 1
end
end
return Result
end
---------------------------------------
-- Returns the total number of cards in
-- specified location who are of
-- specified attribute
--
-- Parameters (3):
-- Cards = first array of cards for search
-- Oper = operation used (>, >=, == etc.)
-- Attribute = Specified attribute of the card
-- Position = Card's position
---------------------------------------
function Get_Card_Count_ATT(Cards, Oper, Attribute, Position)
local Result = 0
for i=1,#Cards do
if (Position == nil or bit32.band(Cards[i].position,Position) > 0) and
(Oper == "==" or Cards[i].attribute == Attribute) or
(Oper == "~=" or Cards[i].attribute ~= Attribute) then
Result = Result + 1
end
end
return Result
end
---------------------------------------
-- Returns the total number of cards in
-- specified location who are of
-- specified ID
--
-- Parameters (4):
-- Cards = first array of cards for search
-- Oper = operation used (>, >=, == etc.)
-- Race = Specified race of the card
-- Position = Card's position
---------------------------------------
function Get_Card_Count_Race(Cards, Oper, Race, Position)
local Result = 0
for i=1,#Cards do
if (Position == nil or bit32.band(Cards[i].position,Position) > 0) and
(Oper == "==" and Cards[i].race == Race) or
(Oper == "~=" and Cards[i].race ~= Race) then
Result = Result + 1
end
end
return Result
end
---------------------------------------
-- Returns the total number of cards in
-- specified location who are of
-- specified rank
--
-- Parameters (2):
-- Cards = array of cards for search
-- Rank = Specified rank of the card
-- Oper = operation used (>, >=, == etc.)
-- Position = Card's position
---------------------------------------
function Get_Card_Count_Rank(Cards, Rank, Oper, Position)
local Result = 0
for i=1,#Cards do
if (Position == nil or bit32.band(Cards[i].position,Position) > 0) and
(Oper == ">" and Cards[i].rank > Rank) or
(Oper == "<" and Cards[i].rank < Rank) or
(Oper == "==" and Cards[i].rank == Rank) or
(Oper == ">=" and Cards[i].rank >= Rank) or
(Oper == "<=" and Cards[i].rank <= Rank) then
Result = Result + 1
end
end
return Result
end
---------------------------------------
-- Returns the total number of cards in
-- specified location who are of
-- specified rank
--
-- Parameters (2):
-- Cards = array of cards for search
-- Level = Specified level of the card
-- Oper = operation used (>, >=, == etc.)
-- Position = Card's position
---------------------------------------
function Get_Card_Count_Level(Cards, Level, Oper, Position)
local Result = 0
for i=1,#Cards do
if (Position == nil or bit32.band(Cards[i].position,Position) > 0) and
(Oper == ">" and Cards[i].level > Level) or
(Oper == "<" and Cards[i].level < Level) or
(Oper == "==" and Cards[i].level == Level) or
(Oper == ">=" and Cards[i].level >= Level) or
(Oper == "<=" and Cards[i].level <= Level) then
Result = Result + 1
end
end
return Result
end
---------------------------------------
-- Returns the total number of cards in
-- specified location who are of
-- specified type
--
-- Parameters (2):
-- Cards = array of cards for search
-- Type = Specified type of the card
-- Oper = operation used (>, >=, == etc.)
-- Position = Card's position
---------------------------------------
function Get_Card_Count_Type(Cards, Type, Oper, Position)
local Result = 0
for i=1,#Cards do
if (Position == nil or bit32.band(Cards[i].position,Position) > 0) and
(Oper == ">" and bit32.band(Cards[i].type,Type) > 0) or
(Oper == "==" and bit32.band(Cards[i].type,Type) == Type) and
Cards[i].id ~= 72892473 then
Result = Result + 1
end
end
return Result
end
---------------------------------------
-- Returns the total number of cards in
-- specified location who have specified
-- amount of Attack or/and Defense
-- compared with specified operation
-- and who are in specified position
--
-- Parameters (5):
-- Cards = array of cards for search
-- Oper = operation used (>, >=, == etc.)
-- Attack = Compared attack value
-- Defense = Compared defense value
-- Position = Card's position
---------------------------------------
function Get_Card_Count_Att_Def(Cards, Oper, Attack, Defense, Position)
local Result = 0
for i=1,#Cards do
if bit32.band(Cards[i].type,TYPE_MONSTER)>0 and
(Position == nil or bit32.band(Cards[i].position,Position) > 0) and
(Attack == nil or
Oper == ">" and Cards[i].attack > Attack or
Oper == "<" and Cards[i].attack < Attack or
Oper == "==" and Cards[i].attack == Attack or
Oper == ">=" and Cards[i].attack >= Attack or
Oper == "<=" and Cards[i].attack <= Attack ) and
(Defense == nil or
Oper == ">" and Cards[i].defense > Defense or
Oper == "<" and Cards[i].defense < Defense or
Oper == "==" and Cards[i].defense == Defense or
Oper == ">=" and Cards[i].defense >= Defense or
Oper == "<=" and Cards[i].defense <= Defense) then
Result = Result + 1
end
end
return Result
end
----------------------------------------
-- Returns the total number of cards
-- currently affected by specified effect
-- in specified card location.
--
-- Parameters (2):
-- Effect = checked effect (refer to constant.lua)
-- Cards = array of cards for search
---------------------------------------
function Card_Count_Affected_By(Effect,Cards)
local Result = 0
for i=1,#Cards do
if Cards[i]:is_affected_by(Effect) == 0 then
Result = Result + 1
end
end
return Result
end
---------------------------------------
-- Returns the total number of cards,
-- of specified archetype in specified
-- location.
--
-- Parameters (4):
-- SetCode = code of searched archetype
-- Cards = array of cards to serach
-- Pos = required position (nil if any)
---------------------------------------
function Archetype_Card_Count(Cards, SetCode, Pos)
local Result = 0
if Cards ~= nil then
for i=1,#Cards do
if Cards[i].setcode == SetCode and
(Pos == nil or bit32.band(Cards[i].position,Pos) > 0) then
Result = Result + 1
end
end
end
return Result
end
---------------------------------------
-- Returns the total number of cards,
-- who are of a specified list
-- and are in a specified location.
--
-- Parameters (2):
-- List = list of cards to compare with (refer to AICheckList.lua)
-- Cards = specified array of cards
-- Oper = used operation (~= or ==)
---------------------------------------
function Card_Count_From_List(List, Cards, Oper)
local Result = 0
for i=1,#Cards do
if (Oper == "==" and List(Cards[i].id) == 1) or
(Oper == "~=" and List(Cards[i].id) == 0) then
Result = Result + 1
end
end
return Result
end
---------------------------------------
-- Returns the total number of cards,
-- who match specified parametrs.
--
-- Parameters (9):
-- Cards = specified array of cards
-- ID = card's id
-- Type = card's type
-- Pos = card's position
-- Oper = operation used (>, >=, == etc.)
-- Level = card's level
-- Race = card's race
-- SetCode = code of card's archetype
-- MinLvl = minimal level check
-- Att = Card's attribute
-- Note: Set parametr to nil if it's not required.
---------------------------------------
function Card_Count_Specified(Cards, ID, Type, Pos, Oper, Level, Race, SetCode, MinLvl, Att)
local Result = 0
for i=1,#Cards do
if Cards[i].location ~= LOCATION_OVERLAY and
(Type == nil or bit32.band(Cards[i].type,Type) > 0) and
(Pos == nil or bit32.band(Cards[i].position,Pos) > 0) and
(ID == nil or Cards[i].id == ID) and
(Race == nil or Cards[i].race == Race) and
(SetCode == nil or Cards[i].setcode == SetCode) and
(Att == nil or Cards[i].attribute == Att) and
(MinLvl == nil or Cards[i].level > MinLvl) and
(Level == nil or
(Oper == ">" and Cards[i].level > Level) or
(Oper == "<" and Cards[i].level < Level) or
(Oper == "==" and Cards[i].level == Level) or
(Oper == ">=" and Cards[i].level >= Level) or
(Oper == "<=" and Cards[i].level <= Level)) then
Result = Result + 1
end
end
return Result
end
----------------------------------------
-- Returns the total number of monsters
-- currently controlled by the AI
-- with lower level and attack points than specified
----------------------------------------
function AIMonCountLowerLevelAndAttack(Level, Attack)
local AIMons = AI.GetAIMonsterZones()
local Result = 0
for x=1,#AIMons do
if AIMons[x] ~= false then
if AIMons[x].level <= Level and AIMons[x].attack < Attack and AIMons[x].rank == 0 and
IsTributeException(AIMons[x].id) == 0 or TributeWhitelist(AIMons[x].id) > 0 and AIMons[x]:is_affected_by(EFFECT_CANNOT_RELEASE) == 0 then
Result = Result + 1
end
end
end
return Result
end
---------------------------------------
-- Returns count of monsters of same level
-- as special summonable monsters rank
---------------------------------------
function AIMonOnFieldMatCount(Rank)
local AIMons = AI.GetAIMonsterZones()
local AIExtra = AI.GetAIExtraDeck()
local Result = 0
for i=1,#AIMons do
if AIMons[i] ~= false then
if bit32.band(AIMons[i].type,TYPE_MONSTER) > 0 and AIMons[i].level == Rank and
IsTributeException(AIMons[i].id) == 0 then
Result = Result + 1
end
end
end
return Result
end
---------------------------------------
-- Returns count of monsters of same level
-- as summonable XYZ monsters rank currently on the field.
---------------------------------------
function AIMonOnFieldMatCurrentCount()
local AIMons = AI.GetAIMonsterZones()
local Result = 0
for i=1,#AIMons do
if AIMons[i] ~= false then
if isMonLevelEqualToRank(AIMons[i].level,AIMons[i].id) == 1 then
Result = Result + 1
end
end
end
return Result
end
---------------------------------------
-- Returns the total number of XYZ materials
-- attached to monster of a specified rank
---------------------------------------
function AIXyzMonsterMatCount(Rank, MatCount)
local AIMon = AI.GetAIMonsterZones()
local Result = 0
for x=1,#AIMon do
if AIMon[x] ~= false then
if AIMon[x] and bit32.band(AIMon[x].type,TYPE_XYZ)> 0 and AIMon[x].rank == Rank and AIMon[x].xyz_material_count == MatCount then
Result = Result + 1
end
end
end
return Result
end
---------------------------------------
-- Returns required count of monsters
-- to special summon XYZ monster.
-- TODO: Add Material count depending on card's id, for every individual card
---------------------------------------
function GetXYZRequiredMatCount()
local AIExtra = AI.GetAIExtraDeck()
local MaterialCount = 0
for i=1,#AIExtra do
if AIExtra[i] ~= false and bit32.band(AIExtra[i].type,TYPE_MONSTER) > 0 then
MaterialCount = 2
end
end
return MaterialCount
end
---------------------------------------
-- Returns required tribute count of monster
-- by it's level or id
---------------------------------------
function AIMonGetTributeCountByLevel(CardLevel)
local AIHand = AI.GetAIHand()
local TributeCount = 0
for i=1,#AIHand do
if AIHand[i] ~= false and bit32.band(AIHand[i].type,TYPE_MONSTER) > 0 then
if AIHand[i].level == CardLevel then
if AIHand[i].level == 5 or AIHand[i].level == 6 then
TributeCount = 1
elseif Is3TributeMonster(AIHand[i].id) == 0 and AIHand[i].level >= 7 then
TributeCount = 2
elseif Is3TributeMonster(AIHand[i].id) == 1 then
TributeCount = 3
end
end
end
end
return TributeCount
end
---------------------------------------
-- Returns the total number of monsters,
-- of specified archetype in AI's hand
-- who aren't of specified id.
---------------------------------------
function AIArchetypeMonNotID(SetCode, CardID)
local AIHand = AI.GetAIHand()
local Result = 0
for x=1,#AIHand do
if AIHand[x] ~= false then
if AIHand[x].setcode == SetCode and AIHand[x].id ~= CardID then
Result = Result + 1
end
end
end
return Result
end
---------------------------------------
-- Returns count of attacked light monster
-- who have weaker attack
---------------------------------------
function AIAttackedLightMonCount()
local AIMon = AI.GetAIMonsterZones()
local Result = 0
for i=1,#AIMon do
if AIMon[i] ~= false then
if AIMon[i].attribute == ATTRIBUTE_LIGHT and AIMon[i].status == STATUS_ATTACKED and AIMon[i].attack >= 1900
and AIMon[i].owner == 1 then
Result = Result + 1
end
end
end
return Result
end
-------------------------------------------------
-- **********************************************
-- Functions related to returning true (1) or false (0)
-- after checking for specified conditions.
-- **********************************************
-------------------------------------------------
---------------------------------------
-- Returns if monster is controlled by AI (1) or Player (2)
-- by checking it's position on side of the field.
---------------------------------------
function CurrentMonOwner(CardId)
local cards = AIMon()
local Result = 2 -- by default it's controlled by Player
for i=1,#cards do
if cards[i] and cards[i].cardid == CardId then
Result = 1 -- if monster exists on AI's side of the field it is owned by AI (well duh)
end
end
return Result
end
---------------------------------------
-- Returns if Spell/Trap card is controlled by AI (1) or Player (2)
-- by checking it's position on side of the field.
---------------------------------------
function CurrentSTOwner(CardsID)
local AIST = AI.GetAISpellTrapZones()
local Result = 2 -- by default it's controlled by Player
for i=1,#AIST do
if AIST[i] ~= false then
if AIST[i].cardid == CardsID then
Result = 1 -- if S/T exists on AI's side of the field it is owned by AI (well duh)
end
end
end
return Result
end
function CurrentOwner(c,cards)
c=GetCardFromScript(c)
if not FilterLocation(c,LOCATION_ONFIELD) then
return c.owner
end
if cards == nil then
cards = AICards()
end
local result = 2
for i=1,#cards do
if cards[i].cardid == c.cardid then
result = 1
end
end
return result
end
----------------------------------------
-- Checks whether or not the opponent
-- controls a face-up monster with a
-- specified ATK (if in attack position)
-- or DEF (if in defense position), and
-- returns True or False as the result.
----------------------------------------
function OppHasFaceupMonster(AtkDef)
if Get_Card_Count_Att_Def(OppMon(),">=",AtkDef,nil,POS_FACEUP_ATTACK) > 0 then
return 1
end
if Get_Card_Count_Att_Def(OppMon(),">=",AtkDef,nil,POS_FACEUP_DEFENSE) > 0 then
return 1
end
return 0
end
---------------------------------------
-- Compares level of specified card with
-- monsters rank in AI's extra deck
-- and returns true or false
---------------------------------------
function isMonLevelEqualToRank(Level,ID)
local AIExtra = AI.GetAIExtraDeck()
local Result = 0
for i=1,#AIExtra do
if AIExtra[i] ~= false then
if bit32.band(AIExtra[i].type,TYPE_MONSTER) > 0 and AIExtra[i].rank == Level and
IsTributeException(ID) == 0 then
Result = 1
end
end
end
return Result
end
--------------------------------------------------
-- Checks if card is a "Toon" monster, and AI
-- controls face up "Toon Kingdom"
--------------------------------------------------
function isToonUndestroyable(Cards)
local Result = 0
for i=1,#Cards do
if Cards[i] ~= false then
if (Cards[i].setcode == 98 and Get_Card_Count_ID(UseLists({AIMon(),AIST()}), 15259703, POS_FACEUP) > 0) or
(Cards[i].setcode == 4522082 and Get_Card_Count_ID(UseLists({AIMon(),AIST()}), 15259703, POS_FACEUP) > 0) then
return 1
end
end
end
return 0
end
-----------------------------------------------------
-- Check if any face up card is from unchain-able card list
-----------------------------------------------------
function AIControlsFaceupUnchainable(CardId)
local AIST = AIST()
for i=1,#AIST do
if isUnchainableTogether(AIST[i].id) == 1 and bit32.band(AIST[i].position,POS_FACEUP) > 0 then
return 1
end
end
return 0
end
-------------------------------------------------
-- **********************************************
-- Functions related to returning value of specified
-- parameter, usually attack or defense.
-- **********************************************
-------------------------------------------------
---------------------------------------
-- Returns highest or lowest attack or
-- defense in specified array of cards
--
-- Parameters (4):
-- Cards = array of cards for search
-- AttDef = attack or defense value of card
-- Oper = operation to check for (> or <)
-- Position = card's position
-- Return = value to return (attack or defense)
---------------------------------------
function Get_Card_Att_Def(Cards, AttDef, Oper, Position, Return)
local Result = 0
local Highest = 0
local Lowest = 99999999
if Oper == ">" and AttDef == "attack" then
for i=1,#Cards do
if(Position == nil or bit32.band(Cards[i].position,Position) > 0) then
if Cards[i].attack > Highest and Return == "attack" then
Highest = Cards[i].attack
Result = Cards[i].attack
elseif Cards[i].attack > Highest and Return == "defense" then
Highest = Cards[i].attack
Result = Cards[i].defense
end
end
end
end
if Oper == ">" and AttDef == "defense" then
for i=1,#Cards do
if(Position == nil or bit32.band(Cards[i].position,Position) > 0) then
if Cards[i].defense > Highest and Return == "attack" then
Highest = Cards[i].defense
Result = Cards[i].attack
elseif Cards[i].defense > Highest and Return == "defense" then
Highest = Cards[i].defense
Result = Cards[i].defense
end
end
end
end
if Oper == "<" and AttDef == "attack" then
for i=1,#Cards do
if(Position == nil or bit32.band(Cards[i].position,Position) > 0) then
if Cards[i].attack < Lowest and Return == "attack" then
Lowest = Cards[i].attack
Result = Cards[i].attack
elseif Cards[i].attack < Lowest and Return == "defense" then
Lowest = Cards[i].attack
Result = Cards[i].defense
end
end
end
end
if Oper == "<" and AttDef == "defense" then
for i=1,#Cards do
if(Position == nil or bit32.band(Cards[i].position,Position) > 0) then
if Cards[i].defense < Lowest and Return == "attack" then
Lowest = Cards[i].defense
Result = Cards[i].attack
elseif Cards[i].defense < Lowest and Return == "defense" then
Lowest = Cards[i].defense
Result = Cards[i].defense
end
end
end
end
return Result
end
---------------------------------------------------------------
-- Returns the highest ATK or DEF (depending on position) in
-- specified index of cards
--
-- Parameters (1):
-- Cards = array of cards for search
----------------------------------------------------------------
function Get_Card_Att_Def_Pos(Cards)
local Result = 0
for i=1,#Cards do
if Cards[i].position == POS_FACEUP_ATTACK then
if Cards[i].attack > Result then
Result = Cards[i].attack
end
end
if Cards[i].position == POS_FACEUP_DEFENSE then
if Cards[i].defense > Result then
Result = Cards[i].defense
end
end
end
return Result
end
---------------------------------------
-- Returns the attack points of card by it's id
--
-- Parameters (1):
-- CardId = ID of the card
---------------------------------------
function AIMonGetAttackById(CardId)
local Result = -1
local AllCards = UseLists({AIMon(),AIDeck(),AIHand(),AIGrave(),AIExtra(),AIBanish(),OppMon(),OppDeck(),OppHand(),OppGrave(),OppExtra(),OppBanish()})
for i=1,#AllCards do
if AllCards[i] ~= false then
if AllCards[i].id == CardId then
Result = AllCards[i].attack
end
end
end
return Result
end
---------------------------------------
-- Returns the race of card by it's id
--
-- Parameters (1):
-- CardId = ID of the card
---------------------------------------
function AIMonGetRaceById(CardId)
local Result = -1
local AllCards = UseLists({AIMon(),AIDeck(),AIHand(),AIGrave(),AIExtra(),AIBanish(),OppMon(),OppDeck(),OppHand(),OppGrave(),OppExtra(),OppBanish()})
for i=1,#AllCards do
if AllCards[i] ~= false then
if AllCards[i].id == CardId then
Result = AllCards[i].race
end
end
end
return Result
end
---------------------------------------
-- Checks, if a specific level/rank is
-- available in specified index of cards
--
-- Parameters (3):
-- Cards = array of cards for search
-- Type = card's type
-- level = card's level
---------------------------------------
function Cards_Available(Cards, Type, level)
local cards=Sort_List_By(Cards,nil,nil,nil,">",Type)
local result={}
for i=1,#cards do
if math.max(cards[i].level,cards[i].rank) == level then
return 1
end
end
return 0
end
---------------------------------------
-- Returns table of xyz materials
-- attached to a specified card
--
-- Parameters (1):
-- CardId = id of the card
---------------------------------------
function Get_Mat_Table(CardId)
local AIMon = AI.GetAIMonsterZones()
local Result = {}
for i=1,#AIMon do
if AIMon[i] ~= false then
if AIMon[i].id == CardId then
Result = AIMon[i].xyz_materials
end
end
end
return Result
end
-------------------------------------------------
-- **********************************************
-- Functions related to returning index of card
-- that is matching specified parameters.
-- **********************************************
-------------------------------------------------
------------------------------------------------
-- Returns index of random spell or trap card on field
--
-- Parameters (2):
-- Cards = array of cards for search
-- Owner = card's current owner
------------------------------------------------
function getRandomSTIndex(Cards, Owner)
local targets = {}
local Index = -1
if #Cards > 0 then
for i=1,#Cards do
if Cards[i] ~= false then
if (bit32.band(Cards[i].type,TYPE_TRAP) == TYPE_TRAP
or bit32.band(Cards[i].type,TYPE_SPELL) == TYPE_SPELL)
and CurrentSTOwner(Cards[i].cardid) == Owner then
targets[#targets+1]=i
Index = targets[math.random(#targets)]
end
end
end
end
return {Index}
end
---------------------------------------
-- Returns index of lowest or highest
-- attack monster of specified parameters in
-- specified array of cards
--
-- Parameters (5):
-- Cards = array of cards for search
-- Owner = card's current owner
-- Oper = search of Highest or Lowest attack monster
-- Type = card's type
-- Position = card's current position
---------------------------------------
function Get_Card_Index(Cards, Owner, Oper, Type, Position)
local Index = 1
local Highest = 0
local Lowest = 99999999
if Oper == "Highest" then
for i=1,#Cards do
if Cards[i] ~= false then
if(Type == nil or bit32.band(Cards[i].type,Type) >= Type) and (Owner == nil or CurrentMonOwner(Cards[i].cardid) == Owner) and
(Position == nil or bit32.band(Cards[i].position,Position) > 0) and
Cards[i].attack > Highest then
Highest = Cards[i].attack
Index = i
end
end
end
end
if Oper == "Lowest" then
for i=1,#Cards do
if Cards[i] ~= false then
if (Type == nil or bit32.band(Cards[i].type,Type) >= Type) and (Owner == nil or CurrentMonOwner(Cards[i].cardid) == Owner) and
(Position == nil or bit32.band(Cards[i].position,Position) > 0) and
Cards[i].attack < Lowest then
Lowest = Cards[i].attack
Index = i
end
end
end
end
return {Index}
end
---------------------------------------
-- Returns index of lowest or highest
-- attack monster of specified parameters in
-- specified array of cards
--
-- Parameters (7):
-- Cards = array of cards for search
-- Owner = card's current owner
-- Oper = search of Highest or Lowest attack monster
-- Type = card's type
-- Position = card's current position
-- Oper2 = operation used (>, >=, == etc.)
-- Race = card's race
---------------------------------------
function Index_By_Race(Cards, Owner, Oper, Type, Position, Oper2, Race)
local Index = 1
local Highest = 0
local Lowest = 99999999
if Oper == "Highest" then
for i=1,#Cards do
if Cards[i] ~= false then
if(Type == nil or bit32.band(Cards[i].type,Type) >= Type) and (Owner == nil or CurrentMonOwner(Cards[i].cardid) == Owner) and
(Position == nil or bit32.band(Cards[i].position,Position) > 0) and (Oper2 == "==" and Cards[i].race == Race) or
(Oper2 == "~=" and Cards[i].race ~= Race) and
Cards[i].attack > Highest then
Highest = Cards[i].attack
Index = i
end
end
end
end
if Oper == "Lowest" then
for i=1,#Cards do
if Cards[i] ~= false then
if(Type == nil or bit32.band(Cards[i].type,Type) >= Type) and (Owner == nil or CurrentMonOwner(Cards[i].cardid) == Owner) and
(Position == nil or bit32.band(Cards[i].position,Position) > 0) and (Oper2 == "==" and Cards[i].race == Race) or
(Oper2 == "~=" and Cards[i].race ~= Race) and
Cards[i].attack < Lowest then
Lowest = Cards[i].attack
Index = i
end
end
end
end
return {Index}
end
---------------------------------------
-- Returns index of lowest or highest
-- attack monster of specified parameters in
-- specified array of cards
--
-- Parameters (7):
-- Cards = array of cards for search
-- Owner = card's current owner
-- Oper = search of Highest or Lowest attack monster
-- Type = card's type
-- Position = card's current position
-- Oper2 = operation used (>, >=, == etc.)
-- Attribute = card's attribute
---------------------------------------
function Index_By_ATT(Cards, Owner, Oper, Type, Position, Oper2, Attribute)
local Index = 1
local Highest = 0
local Lowest = 99999999
if Oper == "Highest" then
for i=1,#Cards do
if Cards[i] ~= false then
if(Type == nil or bit32.band(Cards[i].type,Type) >= Type) and (Owner == nil or CurrentMonOwner(Cards[i].cardid) == Owner) and
(Position == nil or bit32.band(Cards[i].position,Position) > 0) and (Oper2 == "==" and Cards[i].attribute == Attribute) or
(Oper2 == "~=" and Cards[i].attribute ~= Attribute) and
Cards[i].attack > Highest then
Highest = Cards[i].attack
Index = i
end
end
end
end
if Oper == "Lowest" then
for i=1,#Cards do
if Cards[i] ~= false then
if(Type == nil or bit32.band(Cards[i].type,Type) >= Type) and (Owner == nil or CurrentMonOwner(Cards[i].cardid) == Owner) and
(Position == nil or bit32.band(Cards[i].position,Position) > 0) and (Oper2 == "==" and Cards[i].attribute == Attribute) or
(Oper2 == "~=" and Cards[i].attribute ~= Attribute) and
Cards[i].attack < Lowest then
Lowest = Cards[i].attack
Index = i
end
end
end
end
return {Index}
end
---------------------------------------
-- Returns index of lowest or highest
-- attack monster of specified parameters in
-- specified array of cards
--
-- Parameters (7):
-- Cards = array of cards for search
-- Owner = card's current owner
-- Oper = search of Highest or Lowest attack monster
-- Type = card's type
-- Position = card's current position
-- Oper2 = operation used (>, >=, == etc.)
-- ID = card's ID
---------------------------------------
function Index_By_ID(Cards, Owner, Oper, Type, Position, Oper2, ID)
local Index = 1
local Highest = 0
local Lowest = 99999999
if Oper == "Highest" then
for i=1,#Cards do
if Cards[i] ~= false then
if(Type == nil or bit32.band(Cards[i].type,Type) >= Type) and (Owner == nil or CurrentMonOwner(Cards[i].cardid) == Owner) and
(Position == nil or bit32.band(Cards[i].position,Position) > 0) and (Oper2 == "==" and Cards[i].id == ID) or
(Oper2 == "~=" and Cards[i].id ~= ID) and
(Cards[i].attack > Highest or bit32.band(Cards[i].type,TYPE_MONSTER) == 0) then
Highest = Cards[i].attack
Index = i
end
end
end
end
if Oper == "Lowest" then
for i=1,#Cards do
if Cards[i] ~= false then
if(Type == nil or bit32.band(Cards[i].type,Type) >= Type) and (Owner == nil or CurrentMonOwner(Cards[i].cardid) == Owner) and
(Position == nil or bit32.band(Cards[i].position,Position) > 0) and (Oper2 == "==" and Cards[i].id == ID) or
(Oper2 == "~=" and Cards[i].id ~= ID) and
(Cards[i].attack < Lowest or bit32.band(Cards[i].type,TYPE_MONSTER) == 0)then
Lowest = Cards[i].attack
Index = i
end
end
end
end
return {Index}
end
---------------------------------------
-- Returns index of lowest or highest
-- attack monster of specified parameters in
-- specified array of cards
--
-- Parameters (7):
-- Cards = array of cards for search
-- Owner = card's current owner
-- Oper = search of Highest or Lowest attack monster
-- Type = card's type
-- Position = card's current position
-- Oper2 = operation used (>, >=, == etc.)
-- SetCode = card's setcode
---------------------------------------
function Index_By_SetCode(Cards, Owner, Oper, Type, Position, Oper2, Setcode)
local Index = 1
local Highest = 0
local Lowest = 99999999
if Oper == "Highest" then
for i=1,#Cards do
if Cards[i] ~= false then
if(Type == nil or bit32.band(Cards[i].type,Type) >= Type) and (Owner == nil or CurrentMonOwner(Cards[i].cardid) == Owner) and
(Position == nil or bit32.band(Cards[i].position,Position) > 0) and (Oper2 == "==" and Cards[i].setcode == Setcode) or
(Oper2 == "~=" and Cards[i].setcode ~= Setcode) and
Cards[i].attack > Highest then
Highest = Cards[i].attack
Index = i
end
end
end
end
if Oper == "Lowest" then
for i=1,#Cards do
if Cards[i] ~= false then
if(Type == nil or bit32.band(Cards[i].type,Type) >= Type) and (Owner == nil or CurrentMonOwner(Cards[i].cardid) == Owner) and
(Position == nil or bit32.band(Cards[i].position,Position) > 0) and (Oper2 == "==" and Cards[i].setcode == Setcode) or
(Oper2 == "~=" and Cards[i].setcode ~= Setcode) and
Cards[i].attack < Lowest then
Lowest = Cards[i].attack
Index = i
end
end
end
end
return {Index}
end
---------------------------------------
-- Returns index of lowest or highest
-- attack monster of specified parameters in
-- specified array of cards
--
-- Parameters (7):
-- Cards = array of cards for search
-- Owner = card's current owner
-- Oper = search of Highest or Lowest attack monster
-- Type = card's type
-- Position = card's current position
-- Oper2 = operation used (>, >=, == etc.)
-- Location = card's location
---------------------------------------
function Index_By_Loc(Cards, Owner, Oper, Type, Position, Oper2, Location)
local Index = 1
local Highest = 0
local Lowest = 99999999
if Oper == "Highest" then
for i=1,#Cards do
if Cards[i] ~= false then
if (Type == nil or bit32.band(Cards[i].type,Type) >= Type)
and (Owner == nil or CurrentMonOwner(Cards[i].cardid) == Owner)
and (Position == nil or bit32.band(Cards[i].position,Position) > 0)
and (Oper2 == "==" and Cards[i].location == Location or Oper2 == "~=" and Cards[i].location ~= Location)
and Cards[i].attack > Highest then
Highest = Cards[i].attack
Index = i
end
end
end
end
if Oper == "Lowest" then
for i=1,#Cards do
if Cards[i] ~= false then
if(Type == nil or bit32.band(Cards[i].type,Type) >= Type)
and (Owner == nil or CurrentMonOwner(Cards[i].cardid) == Owner)
and (Position == nil or bit32.band(Cards[i].position,Position) > 0)
and (Oper2 == "==" and Cards[i].location == Location or Oper2 == "~=" and Cards[i].location ~= Location)
and Cards[i].attack < Lowest then
Lowest = Cards[i].attack
Index = i
end
end
end
end
return {Index}
end
---------------------------------------
-- Returns index of lowest or highest
-- attack monster of specified parameters in
-- specified array of cards
--
-- Parameters (7):
-- Cards = array of cards for search
-- Owner = card's current owner
-- Oper = search of Highest or Lowest attack monster
-- Type = card's type
-- Position = card's current position
-- Oper2 = operation used (>, >=, == etc.)
-- Level = card's level
---------------------------------------
function Index_By_Level(Cards, Owner, Oper, Type, Position, Oper2, Level)
local Index = 1
local Highest = 0
local Lowest = 99999999
if Oper == "Highest" then
for i=1,#Cards do
if Cards[i] ~= false then
if(Type == nil or bit32.band(Cards[i].type,Type) >= Type) and (Owner == nil or CurrentMonOwner(Cards[i].cardid) == Owner) and
(Position == nil or bit32.band(Cards[i].position,Position) > 0) and
(Oper2 == ">" and Cards[i].level > Level) or
(Oper2 == "<" and Cards[i].level < Level) or
(Oper2 == "==" and Cards[i].level == Level) or
(Oper2 == ">=" and Cards[i].level >= Level) or
(Oper2 == "<=" and Cards[i].level <= Level) and
Cards[i].attack > Highest then
Highest = Cards[i].attack
Index = i
end
end
end
end
if Oper == "Lowest" then
for i=1,#Cards do
if Cards[i] ~= false then
if(Type == nil or bit32.band(Cards[i].type,Type) >= Type) and (Owner == nil or CurrentMonOwner(Cards[i].cardid) == Owner) and
(Position == nil or bit32.band(Cards[i].position,Position) > 0) and
(Oper2 == ">" and Cards[i].level > Level) or
(Oper2 == "<" and Cards[i].level < Level) or
(Oper2 == "==" and Cards[i].level == Level) or
(Oper2 == ">=" and Cards[i].level >= Level) or
(Oper2 == "<=" and Cards[i].level <= Level) and
Cards[i].attack < Lowest then
Lowest = Cards[i].attack
Index = i
end
end
end
end
return {Index}
end
---------------------------------------
-- Returns index of lowest or highest
-- attack monster of specified parameters in
-- specified array of cards
--
-- Parameters (7):
-- Cards = array of cards for search
-- Owner = card's current owner
-- Oper = search of Highest or Lowest attack monster
-- Type = card's type
-- Position = card's current position
-- Oper2 = operation used (>, >=, == etc.)
-- Attack = card's attack
---------------------------------------
function Index_By_Attack(Cards, Owner, Oper, Type, Position, Oper2, Attack)
local Index = 1
local Highest = 0
local Lowest = 99999999
if Oper == "Highest" then
for i=1,#Cards do
if Cards[i] ~= false then
if(Type == nil or bit32.band(Cards[i].type,Type) >= Type) and (Owner == nil or CurrentMonOwner(Cards[i].cardid) == Owner) and
(Position == nil or bit32.band(Cards[i].position,Position) > 0) and
(Oper2 == ">" and Cards[i].attack > Attack) or
(Oper2 == "<" and Cards[i].attack < Attack) or
(Oper2 == "==" and Cards[i].attack == Attack) or
(Oper2 == ">=" and Cards[i].attack >= Attack) or
(Oper2 == "<=" and Cards[i].attack <= Attack) and
Cards[i].attack > Highest then
Highest = Cards[i].attack
Index = i
end
end
end
end
if Oper == "Lowest" then
for i=1,#Cards do
if Cards[i] ~= false then
if(Type == nil or bit32.band(Cards[i].type,Type) >= Type) and (Owner == nil or CurrentMonOwner(Cards[i].cardid) == Owner) and
(Position == nil or bit32.band(Cards[i].position,Position) > 0) and
(Oper2 == ">" and Cards[i].attack > Attack) or
(Oper2 == "<" and Cards[i].attack < Attack) or
(Oper2 == "==" and Cards[i].attack == Attack) or
(Oper2 == ">=" and Cards[i].attack >= Attack) or
(Oper2 == "<=" and Cards[i].attack <= Attack) and
Cards[i].attack < Lowest then
Lowest = Cards[i].attack
Index = i
end
end
end
end
return {Index}
end
------------------------------------------
-- Returns the location of the highest ATK
-- monster who is of a specified type or
-- higher or equal of a specified level,
-- which is controlled by AI - 1 or Player -2,
-- in a specified index of cards.
------------------------------------------
function GetHighestATKMonByLevelOrSS(Cards,Type, Level, Position, Owner)
local HighestATK = 0
local HighestIndex = 1
if #Cards > 0 then
for i=1,#Cards do
if Cards[i] ~= false then
if bit32.band(Cards[i].type,Type) == Type and Cards[i].owner == Owner or Cards[i].rank > 0 and Cards[i].owner == Owner and
Cards[i].attack > HighestATK then
HighestATK = Cards[i].attack
HighestIndex = i
elseif bit32.band(Cards[i].type,TYPE_MONSTER) > 0 and (Cards[i].owner == Owner or CurrentMonOwner(Cards[i].cardid) == Owner) and
Cards[i].attack > HighestATK and Cards[i].level >= Level and Cards[i].position == Position then
HighestATK = Cards[i].attack
HighestIndex = i
end
end
end
end
return {HighestIndex}
end
------------------------------------------
-- Returns the location of the highest ATK
-- monster with same ID's,
-- which is controlled by AI - 1 or Player -2,
-- in a specified index of cards.
------------------------------------------
function GetHighestATKMonBySameID(Cards, Position, Owner)
local HighestATK = 0
local HighestIndex = 1
if #Cards > 0 then
for i=1,#Cards do
if Cards[i] ~= false then
if bit32.band(Cards[i].type,TYPE_MONSTER) == TYPE_MONSTER and
Cards[i].attack > HighestATK and Cards[i].id == Cards[i].id and Cards[i].position == Position then
if (Cards[i].owner == Owner or CurrentMonOwner(Cards[i].cardid) == Owner) then
HighestATK = Cards[i].attack
HighestIndex = i
end
end
end
end
end
return {HighestIndex}
end
-------------------------------------------------
-- **********************************************
-- Functions to calculate attack, or defense of cards
-- before preforming certain actions.
-- **********************************************
-------------------------------------------------
-------------------------------------------------
-- Function to calculate possible attack or defense
-- increase for certain cards
-- when they are about to be summoned.
-------------------------------------------------
function CalculatePossibleSummonAttack(SummonableCards)
for i=1,#SummonableCards do
if SummonableCards[i] ~= false then
if SummonableCards[i].id == 10000020 then -- Slifer the Sky Dragon
SummonableCards[i].attack = SummonableCards[i].attack + 1000 * (Get_Card_Count(AIHand()) -1)
end
end
end
for i=1,#SummonableCards do
if SummonableCards[i] ~= false then
if SummonableCards[i].id == 10000010 then -- The Winged Dragon of Ra
SummonableCards[i].attack = SummonableCards[i].attack + (AI.GetPlayerLP(1) - 100)
end
end
end
for i=1,#SummonableCards do
if SummonableCards[i] ~= false then
if SummonableCards[i].id == 12014404 then -- Gagaga gunman
SummonableCards[i].attack = SummonableCards[i].attack + 1500
end
end
end
end
-------------------------------------------------
-- This temporarily applies ATK boosts to certain
-- cards, either built-in or from a field spell.
-------------------------------------------------
function ApplyATKBoosts(Cards)
for i=1,#Cards do
Cards[i].bonus = 0 -- bonus is used, if the ATK boost needs to use up a card to apply
-- (Honest, Crane, Lance...), to make sure they are not used on indestructible targets
end
------------------------------------------------------
-- Apply Jain, Lightsworn Paladin's, X-Saber Galahad's
-- and Cyber Dragon Zwei's +300 ATK boost.
------------------------------------------------------
if #Cards > 0 then
for i=1,#Cards do
if Cards[i] ~= false then
if Cards[i].id == 50604950 or -- XSG
Cards[i].id == 05373478 then -- Zwei
Cards[i].attack = Cards[i].attack + 300
end
end
end
end
---------------------------------------------------------
-- Apply Max Warrior's, Black Veloci's, T.G. Rush Rhino's
-- and Crystal Beast Topaz Tiger's +400 ATK boost.
---------------------------------------------------------
if #Cards > 0 then
for i=1,#Cards do
if Cards[i] ~= false then
if Cards[i].id == 94538053 or Cards[i].id == 52319752 or -- Max,BV
Cards[i].id == 36687247 or Cards[i].id == 95600067 then -- RR,CBTT
Cards[i].attack = Cards[i].attack + 400
end
end
end
end
-------------------------------------------------------
-- Apply Steamroid's and Etoile Cyber's +500 ATK boost.
-------------------------------------------------------
if #Cards > 0 then
for i=1,#Cards do
if Cards[i] ~= false then
if Cards[i].id == 96235275 or
Cards[i].id == 11460577 then
Cards[i].attack = Cards[i].attack + 500
end
end
end
end
----------------------------------------
-- Apply Dash Warrior's +1200 ATK boost.
----------------------------------------
if #Cards > 0 then
for i=1,#Cards do
if Cards[i] ~= false then
if Cards[i].id == 342570017 then
Cards[i].attack = Cards[i].attack + 1200
end
end
end
end
-------------------------------------------
-- Apply Skyscraper's 1000 ATK boost to any
-- Elemental HERO monsters the AI controls.
-------------------------------------------
if Get_Card_Count_ID(UseLists({AIMon(),AIST(),OppMon(),OppST()}), 63035430, POS_FACEUP) > 0 then
if #Cards > 0 then
for i=1,#Cards do
if Cards[i] ~= false then
if IsEHeroMonster(Cards[i].id) == 1 then
Cards[i].attack = Cards[i].attack + 1000
end
end
end
end
end
-------------------------------------------
-- Gagaga Gunman's 1500 ATK boost if his
-- attacking opponents monster.
-------------------------------------------
if #Cards > 0 then
for i=1,#Cards do
if Cards[i] ~= false then
if Cards[i].id == 12014404 then
if Global1PTGunman == 1 then
Cards[i].attack = Cards[i].attack + 1500
end
end
end
end
end
------------------------------------------
-- Apply Dark City's 1000 ATK boost to any
-- Destiny HERO monsters the AI controls.
------------------------------------------
if Get_Card_Count_ID(UseLists({AIMon(),AIST(),OppMon(),OppST()}), 53527835, POS_FACEUP) > 0 then
if #Cards > 0 then
for i=1,#Cards do
if Cards[i] ~= false then
if IsDHeroMonster(Cards[i].id) == 1 then
Cards[i].attack = Cards[i].attack + 1000
end
end
end
end
end
------------------------------------------
-- Apply Tensen's 1000 ATK boost to Beast-
-- Warrior monsters
------------------------------------------
if #Cards > 0 then
local ST = AIST()
local check = false
for i=1,#ST do
if ST[i].id == 44920699 and bit32.band(ST[i].position,POS_FACEDOWN)>0
and bit32.band(ST[i].status,STATUS_SET_TURN)==0 then
check = true
end
end
if check then
for i=1,#Cards do
if Cards[i].race==RACE_BEASTWARRIOR and CurrentOwner(Cards[i])==1 then
Cards[i].attack = Cards[i].attack + 1000
Cards[i].bonus = 1000
end
end
end
end
------------------------------------------
-- Apply Forbidden Lance's 800 ATK reduction
------------------------------------------
if #Cards > 0 then
local ST = AIST()
local check = false
if HasIDNotNegated(AIST(),27243130,true) then
check = true
end
if HasIDNotNegated(AIHand(),27243130,true)
and Duel.GetLocationCount(player_ai,LOCATION_SZONE)>0
then
check = true
end
if check then
for i=1,#Cards do
local c = Cards[i]
if CurrentOwner(c)==2
and Affected(c,TYPE_SPELL)
and Targetable(c,TYPE_SPELL)
and not ArmadesCheck(c)
then
Cards[i].attack = Cards[i].attack -800
Cards[i].bonus = -800
end
end
end
end
------------------------------------------
-- Apply Forbidden Chalice 400 ATK boost
------------------------------------------
if #Cards > 0 then
local ST = AIST()
local check = false
for i=1,#ST do
if ST[i].id == 25789292 and bit32.band(ST[i].status,STATUS_SET_TURN)==0 then
check = true
end
end
if HasID(AIHand(),25789292,true) and Duel.GetLocationCount(player_ai,LOCATION_SZONE)>0 then
check = true
end
if check then
for i=1,#Cards do
if CurrentOwner(Cards[i])==1
and (Cards[i]:is_affected_by(EFFECT_IMMUNE_EFFECT)==0
or QliphortFilter(Cards[i],27279764))
and Cards[i]:is_affected_by(EFFECT_CANNOT_BE_EFFECT_TARGET)==0
then
Cards[i].attack = Cards[i].attack+400+QliphortAttackBonus(Cards[i].id,Cards[i].level)
Cards[i].bonus = 400+QliphortAttackBonus(Cards[i].id,Cards[i].level)
end
end
end
end
------------------------------------------
-- Apply attack bonuses monster get for Skill Drain
------------------------------------------
if #Cards > 0 then
local ST = AIST()
local check = false
for i=1,#ST do
if ST[i].id == 82732705 and bit32.band(ST[i].status,STATUS_SET_TURN)==0
and AI.GetPlayerLP(1)>1000 and not SkillDrainCheck()
then
check = true
end
end
if check then
for i=1,#Cards do
if CurrentOwner(Cards[i])==1
and (Cards[i]:is_affected_by(EFFECT_IMMUNE_EFFECT)==0
or QliphortFilter(Cards[i],27279764))
and NotNegated(Cards[i])
then
Cards[i].attack = Cards[i].attack+QliphortAttackBonus(Cards[i].id,Cards[i].level)
end
end
end
end
------------------------------------------
-- Apply Vampire Empire's Attack Boost
------------------------------------------
if HasID(UseLists({AIST(),OppST()}),62188962,true) then
for i=1,#Cards do
if bit32.band(Cards[i].race,RACE_ZOMBIE)>0 then
Cards[i].attack = Cards[i].attack +500
end
end
end
------------------------------------------
-- Apply Bujingi Crane's Attack Doubling
------------------------------------------
for i=1,#Cards do
if HasID(AIHand(),68601507,true) and bit32.band(Cards[i].setcode,0x88)>0
and bit32.band(Cards[i].race,RACE_BEASTWARRIOR)>0 and Cards[i].owner==1
and MacroCheck()
then
Cards[i].bonus = Cards[i].base_attack * 2 - Cards[i].attack
Cards[i].attack = Cards[i].base_attack * 2
end
end
------------------------------------------
-- Apply Bujingi Sinyou's Attack Bonus
------------------------------------------
for i=1,#Cards do
if HasID(AIGrave(),56574543,true) and bit32.band(Cards[i].setcode,0x88)>0
and bit32.band(Cards[i].race,RACE_BEASTWARRIOR)>0 and CurrentOwner(Cards[i])==1
then
local OppAtt = Get_Card_Att_Def(OppMon(),"attack",">",nil,"attack")
Cards[i].attack = Cards[i].attack + OppAtt
Cards[i].bonus = OppAtt
end
end
------------------------------------------
-- Apply Honest's Attack Bonus
------------------------------------------
for i=1,#Cards do
if HasID(AIHand(),37742478,true) and CurrentOwner(Cards[i])==1
and bit32.band(Cards[i].attribute,ATTRIBUTE_LIGHT)>0
and MacroCheck()
then
local OppAtt = Get_Card_Att_Def(OppMon(),"attack",">",nil,"attack")
Cards[i].attack = Cards[i].attack + OppAtt
Cards[i].bonus = OppAtt
end
end
-- Nekroz Decisive Armor
for i=1,#Cards do
if HasID(AIHand(),88240999,true) and NekrozMonsterFilter(Cards[i])
and CurrentOwner(Cards[i])==1 and not FilterAffected(Cards[i],EFFECT_CANNOT_BE_EFFECT_TARGET)
then
Cards[i].bonus = Cards[i].bonus + 1000
Cards[i].attack = Cards[i].attack + 1000
end
end
-- Nekroz Clausolas
for i=1,#Cards do
if HasIDNotNegated(AIMon(),99185129,true) and OPTCheck(991851291) then
for i=1,#Cards do
if ClausFilter2(Cards[i]) then
Cards[i].attack = 0
end
end
end
end
-- Utopia Lightning
for i=1,#Cards do
local c = Cards[i]
if c.id == 56832966
and c.xyz_material_count>1
and CardsMatchingFilter(c.xyz_materials,FilterSet,0x7f)>0
and NotNegated(c)
and #OppMon()>0
then
c.bonus = 5000-c.attack
c.attack = 5000
end
end
-- Kalut
for i=1,CardsMatchingFilter(AIHand(),FilterID,85215458) do
for j=1,#Cards do
local c = Cards[j]
if BlackwingFilter(c)
and CurrentOwner(c)==1
and MacroCheck()
then
c.attack=c.attack+1400
if c.bonus==nil then
c.bonus=0
end
c.bonus=c.bonus+1400
end
end
end
-- Shrink
if HasIDNotNegated(AICards(),55713623,true) then
for i=1,#Cards do
local c = Cards[i]
if Targetable(c,TYPE_SPELL)
and Affected(c,TYPE_SPELL)
and CurrentOwner(c)==2
then
c.attack=c.attack-c.base_attack*.5
c.bonus=c.base_attack*-.5
end
end
end
-- Masked HERO Koga
if HasIDNotNegated(AICards(),50608164,true) then
local atk = 0
local Heroes = SubGroup(AIGrave(),HEROFilter)
if Heroes and #Heroes>0 then
SortByATK(Heroes,true)
atk = math.min(atk,Heroes[1].attack)
end
for i=1,#Cards do
local c = Cards[i]
if Targetable(c,TYPE_MONSTER)
and Affected(c,TYPE_MONSTER,8)
and CurrentOwner(c)==2
then
local temp=c.attack
c.attack=math.max(0,c.attack-atk)
c.bonus=c.attack-temp
end
end
end
local d = DeckCheck()
if d and d.AttackBoost then
d.AttackBoost(Cards)
end
-- Moon Mirror Shield
for i=1,#Cards do
local c = Cards[i]
local equips = c:get_equipped_cards()
if HasIDNotNegated(equips,19508728,true) then
local list = OppMon()
if CurrentOwner(c)==2 then
list = AIMon()
end
c.attack=GetHighestAttDef(list)+100
end
end
-- Crystal Wing
for i,c in pairs(Cards) do
if c.id == 50954680 -- Crystal Wing
and NotNegated(c)
then
local targets = FilterController(c,1) and OppMon() or AIMon()
if CardsMatchingFilter(targets,CrystalWingFilter,c)>0
then
SortByATK(targets,true)
c.attack=(c.attack or 0)+targets[1].attack
end
end
end
-- unknown face-down monsters
for i=1,#Cards do
local c = Cards[i]
if FilterPosition(c,POS_FACEDOWN_DEFENSE)
and FilterPrivate(c)
and CurrentOwner(c)==2
then
c.defense=1499
end
end
-- fix cards with attack < 0 after attack boosts
for i=1,#Cards do
Cards[i].attack=math.max(Cards[i].attack,0)
end
end
function CatastorFilter(c)
return bit32.band(c.attribute,ATTRIBUTE_DARK)==0
and bit32.band(c.position,POS_FACEUP)>0
and c:is_affected_by(EFFECT_CANNOT_BE_BATTLE_TARGET)==0
and c:is_affected_by(EFFECT_INDESTRUCTABLE_EFFECT)==0
end
-------------------------------------------------
-- **********************************************
-- Set of global functions to serve general purposes
-- **********************************************
-------------------------------------------------
--------------------------------------------------------
-- Certain effects and other things should only be used
-- by the AI once per turn to prevent infinite loops.
-- This will help allow them to be used once every turn.
--------------------------------------------------------
GlobalTurn = 0
function ResetOncePerTurnGlobals()
if GlobalTurn == Duel.GetTurnCount() then
return
end
GlobalSummonRestriction = nil
GlobalTurn = Duel.GetTurnCount()
Global1PTLylaST = nil
Global1PTGenome = nil
Global1PTHonest = nil
Global1PTFormula = nil
Global1PTWaboku = nil
GlobalNoBattle = nil
Global1PTVariable = nil
Global1PTGunman = nil
Global1PTSparSSed = nil
Global1PTAArchers = nil
Global1PTPollux = nil
GlobalAttackerID = 0
GlobalKaustActivated = nil
GlobalAdditionalTributeCount = 0
GlobalKaustActivationCount = 0
GlobalPosChangedByControllerUseTime = 0
GlobalPosChangedByController = nil
GlobalPosChangedByController2 = nil
GlobalSummonedThisTurn = 0
GlobalSoulExchangeActivated = 0
GlobalCostDownActivated = 0
GlobalInfiniteLoopCheck = {}
end
function Globals()
GlobalCocoonTurnCount = 0
GlobalEffectNum = 0
end
---------------------------------------
-- Sorts selected array of cards by
-- cards of only specified parameters
--
-- Parameters (6):
-- Cards = array of cards for search
-- Level = card's level
-- Attribute = card's attribute
-- Race = card's race
-- Oper = operation used (> or ==)
-- Type = card's type
---------------------------------------
function Sort_List_By(Cards, Level, Attribute, Race, Oper, Type)
local result = {}
for i=1,#Cards do
if (Level == nil or Cards[i].level == level) and
(Attribute == nil or bit32.band(Cards[i].attribute,Attribute) > 0) and
(Race == nil or bit32.band(Cards[i].race,Race) > 0) and
(Oper == nil or Oper == ">" and bit32.band(Cards[i].type,Type) > 0 or
(Oper == "==" and bit32.band(Cards[i].type,Type) == Type)) then
result[#result+1]=Cards[i]
end
end
return result
end
----------------------------------------------------------
-- Compares each field of 2 specified cards. Returns True
-- if both are equal, and False if any field is different.
----------------------------------------------------------
function CardsEqual(Card1, Card2)
if not (Card1 and Card2) then
print("Warning: CardsEqual null cards")
PrintCallingFunction()
return false
end
local type1=type(Card1)
local type2=type(Card2)
if type1~="table" and type1~="userdata"
or type2~="table" and type2~="userdata"
then
print("Warning: CardsEqual invalid cards")
PrintCallingFunction()
return false
end
if Card1.GetCode then
Card1=GetCardFromScript(Card1)
end
if Card2.GetCode then
Card2=GetCardFromScript(Card2)
end
return Card1 and Card2 and Card1.cardid==Card2.cardid
end
function CardsNotEqual(c1,c2)
return not CardsEqual(c1,c2)
end
function ListHasCard(cards,c)
if cards and c then
for i=1,#cards do
if CardsEqual(cards[i],c) then
return true
end
end
end
return false
end
function ListRemoveCards(cards,rem)
if rem == nil then
return cards
end
if rem.GetCode then
rem = GetCardFromScript(rem)
end
if type(rem) == "table" and rem.id then
rem = {rem}
end
for i=1,#cards do
for j=1,#rem do
if cards[i] and rem[j] and CardsEqual(cards[i],rem[j]) then
table.remove(cards,i)
end
end
end
end
| mit |
dynamicreflectance/core | math/source/Converters.hpp | 457 | #pragma once
/* Converters.hpp
*
* Copyright (C) 2017 Dynamic Reflectance
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace core {
namespace math {
float toDegrees(float in_radians)
{
return in_radians * 180.0f / 3.14f;
}
float toRadians(float in_degrees)
{
return in_degrees * 3.14f / 180.0f;
}
} // namespace math
} // namespace core | mit |
voku/swiftmailer | lib/classes/Swift/Encoder/Rfc2231Encoder.php | 2439 | <?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Handles RFC 2231 specified Encoding in Swift Mailer.
*
* @author Chris Corbyn
*/
class Swift_Encoder_Rfc2231Encoder implements Swift_Encoder
{
/**
* A character stream to use when reading a string as characters instead of bytes.
*
* @var Swift_CharacterStream
*/
private $_charStream;
/**
* Creates a new Rfc2231Encoder using the given character stream instance.
*
* @param Swift_CharacterStream
*/
public function __construct(Swift_CharacterStream $charStream)
{
$this->_charStream = $charStream;
}
/**
* Takes an unencoded string and produces a string encoded according to
* RFC 2231 from it.
*
* @param string $string
* @param int $firstLineOffset
* @param int $maxLineLength optional, 0 indicates the default of 75 bytes
*
* @return string
*/
public function encodeString(string $string, int $firstLineOffset = 0, int $maxLineLength = 0)
{
$lines = array();
$lineCount = 0;
$lines[] = '';
$currentLine = &$lines[$lineCount++];
if (0 >= $maxLineLength) {
$maxLineLength = 75;
}
$this->_charStream->flushContents();
$this->_charStream->importString($string);
$thisLineLength = $maxLineLength - $firstLineOffset;
while (false !== $char = $this->_charStream->read(4)) {
$encodedChar = \rawurlencode($char);
if (
$currentLine !== ''
&&
\strlen($currentLine . $encodedChar) > $thisLineLength
) {
$lines[] = '';
$currentLine = &$lines[$lineCount++];
$thisLineLength = $maxLineLength;
}
$currentLine .= $encodedChar;
}
return \implode("\r\n", $lines);
}
/**
* Updates the charset used.
*
* @param string|null $charset
*/
public function charsetChanged($charset)
{
$this->_charStream->setCharacterSet($charset);
}
/**
* Make a deep copy of object.
*/
public function __clone()
{
$this->_charStream = clone $this->_charStream;
}
}
| mit |
rdqw/sscoin | contrib/devtools/update-translations.py | 7660 | #!/usr/bin/python
# Copyright (c) 2014 Wladimir J. van der Laan
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
'''
Run this script from the root of the repository to update all translations from
transifex.
It will do the following automatically:
- fetch all translations using the tx tool
- post-process them into valid and committable format
- remove invalid control characters
- remove location tags (makes diffs less noisy)
TODO:
- auto-add new translations to the build system according to the translation process
'''
from __future__ import division, print_function
import subprocess
import re
import sys
import os
import io
import xml.etree.ElementTree as ET
# Name of transifex tool
TX = 'tx'
# Name of source language file
SOURCE_LANG = 'sscoin_en.ts'
# Directory with locale files
LOCALE_DIR = 'src/qt/locale'
# Minimum number of messages for translation to be considered at all
MIN_NUM_MESSAGES = 10
def check_at_repository_root():
if not os.path.exists('.git'):
print('No .git directory found')
print('Execute this script at the root of the repository', file=sys.stderr)
exit(1)
def fetch_all_translations():
if subprocess.call([TX, 'pull', '-f', '-a']):
print('Error while fetching translations', file=sys.stderr)
exit(1)
def find_format_specifiers(s):
'''Find all format specifiers in a string.'''
pos = 0
specifiers = []
while True:
percent = s.find('%', pos)
if percent < 0:
break
try:
specifiers.append(s[percent+1])
except:
print('Failed to get specifier')
pos = percent+2
return specifiers
def split_format_specifiers(specifiers):
'''Split format specifiers between numeric (Qt) and others (strprintf)'''
numeric = []
other = []
for s in specifiers:
if s in {'1','2','3','4','5','6','7','8','9'}:
numeric.append(s)
else:
other.append(s)
# numeric (Qt) can be present in any order, others (strprintf) must be in specified order
return set(numeric),other
def sanitize_string(s):
'''Sanitize string for printing'''
return s.replace('\n',' ')
def check_format_specifiers(source, translation, errors, numerus):
source_f = split_format_specifiers(find_format_specifiers(source))
# assert that no source messages contain both Qt and strprintf format specifiers
# if this fails, go change the source as this is hacky and confusing!
#assert(not(source_f[0] and source_f[1]))
try:
translation_f = split_format_specifiers(find_format_specifiers(translation))
except IndexError:
errors.append("Parse error in translation for '%s': '%s'" % (sanitize_string(source), sanitize_string(translation)))
return False
else:
if source_f != translation_f:
if numerus and source_f == (set(), ['n']) and translation_f == (set(), []) and translation.find('%') == -1:
# Allow numerus translations to omit %n specifier (usually when it only has one possible value)
return True
errors.append("Mismatch between '%s' and '%s'" % (sanitize_string(source), sanitize_string(translation)))
return False
return True
def all_ts_files(suffix=''):
for filename in os.listdir(LOCALE_DIR):
# process only language files, and do not process source language
if not filename.endswith('.ts'+suffix) or filename == SOURCE_LANG+suffix:
continue
if suffix: # remove provided suffix
filename = filename[0:-len(suffix)]
filepath = os.path.join(LOCALE_DIR, filename)
yield(filename, filepath)
FIX_RE = re.compile(b'[\x00-\x09\x0b\x0c\x0e-\x1f]')
def remove_invalid_characters(s):
'''Remove invalid characters from translation string'''
return FIX_RE.sub(b'', s)
# Override cdata escape function to make our output match Qt's (optional, just for cleaner diffs for
# comparison, disable by default)
_orig_escape_cdata = None
def escape_cdata(text):
text = _orig_escape_cdata(text)
text = text.replace("'", ''')
text = text.replace('"', '"')
return text
def postprocess_translations(reduce_diff_hacks=False):
print('Checking and postprocessing...')
if reduce_diff_hacks:
global _orig_escape_cdata
_orig_escape_cdata = ET._escape_cdata
ET._escape_cdata = escape_cdata
for (filename,filepath) in all_ts_files():
os.rename(filepath, filepath+'.orig')
have_errors = False
for (filename,filepath) in all_ts_files('.orig'):
# pre-fixups to cope with transifex output
parser = ET.XMLParser(encoding='utf-8') # need to override encoding because 'utf8' is not understood only 'utf-8'
with open(filepath + '.orig', 'rb') as f:
data = f.read()
# remove control characters; this must be done over the entire file otherwise the XML parser will fail
data = remove_invalid_characters(data)
tree = ET.parse(io.BytesIO(data), parser=parser)
# iterate over all messages in file
root = tree.getroot()
for context in root.findall('context'):
for message in context.findall('message'):
numerus = message.get('numerus') == 'yes'
source = message.find('source').text
translation_node = message.find('translation')
# pick all numerusforms
if numerus:
translations = [i.text for i in translation_node.findall('numerusform')]
else:
translations = [translation_node.text]
for translation in translations:
if translation is None:
continue
errors = []
valid = check_format_specifiers(source, translation, errors, numerus)
for error in errors:
print('%s: %s' % (filename, error))
if not valid: # set type to unfinished and clear string if invalid
translation_node.clear()
translation_node.set('type', 'unfinished')
have_errors = True
# Remove location tags
for location in message.findall('location'):
message.remove(location)
# Remove entire message if it is an unfinished translation
if translation_node.get('type') == 'unfinished':
context.remove(message)
# check if document is (virtually) empty, and remove it if so
num_messages = 0
for context in root.findall('context'):
for message in context.findall('message'):
num_messages += 1
if num_messages < MIN_NUM_MESSAGES:
print('Removing %s, as it contains only %i messages' % (filepath, num_messages))
continue
# write fixed-up tree
# if diff reduction requested, replace some XML to 'sanitize' to qt formatting
if reduce_diff_hacks:
out = io.BytesIO()
tree.write(out, encoding='utf-8')
out = out.getvalue()
out = out.replace(b' />', b'/>')
with open(filepath, 'wb') as f:
f.write(out)
else:
tree.write(filepath, encoding='utf-8')
return have_errors
if __name__ == '__main__':
check_at_repository_root()
# fetch_all_translations()
postprocess_translations()
| mit |
elennick/retry4j | src/main/java/com/evanlennick/retry4j/CallExecutor.java | 11095 | package com.evanlennick.retry4j;
import com.evanlennick.retry4j.config.RetryConfig;
import com.evanlennick.retry4j.exception.RetriesExhaustedException;
import com.evanlennick.retry4j.exception.UnexpectedException;
import com.evanlennick.retry4j.listener.RetryListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
/**
* Default implementation that does a single, synchronous retry in the same thread that it is called from.
*
* @param <T> The type that is returned by the Callable (eg: Boolean, Void, Object, etc)
*/
public class CallExecutor<T> implements RetryExecutor<T, Status<T>> {
private Logger logger = LoggerFactory.getLogger(CallExecutor.class);
private RetryConfig config;
private RetryListener<T> afterFailedTryListener;
private RetryListener<T> beforeNextTryListener;
private RetryListener<T> onFailureListener;
private RetryListener<T> onSuccessListener;
private RetryListener<T> onCompletionListener;
private Exception lastKnownExceptionThatCausedRetry;
private Status<T> status = new Status<>();
/**
* Use {@link CallExecutorBuilder} to build {@link CallExecutor}
*/
CallExecutor(RetryConfig config, RetryListener<T> afterFailedTryListener,
RetryListener<T> beforeNextTryListener, RetryListener<T> onFailureListener,
RetryListener<T> onSuccessListener, RetryListener<T> onCompletionListener) {
this.config = config;
this.afterFailedTryListener = afterFailedTryListener;
this.beforeNextTryListener = beforeNextTryListener;
this.onFailureListener = onFailureListener;
this.onSuccessListener = onSuccessListener;
this.onCompletionListener = onCompletionListener;
this.status.setId(UUID.randomUUID().toString());
}
@Override
public Status<T> execute(Callable<T> callable) {
return execute(callable, null);
}
@Override
public Status<T> execute(Callable<T> callable, String callName) {
logger.trace("Starting retry4j execution with callable {}", config, callable);
logger.debug("Starting retry4j execution with executor state {}", this);
long start = System.currentTimeMillis();
status.setStartTime(start);
int maxTries = config.getMaxNumberOfTries();
long millisBetweenTries = config.getDelayBetweenRetries() != null
? config.getDelayBetweenRetries().toMillis() : 0L;
this.status.setCallName(callName);
AttemptStatus<T> attemptStatus = new AttemptStatus<>();
attemptStatus.setSuccessful(false);
int tries;
try {
for (tries = 0; tries < maxTries && !attemptStatus.wasSuccessful(); tries++) {
if (tries > 0) {
handleBeforeNextTry(millisBetweenTries, tries);
logger.trace("Retry4j retrying for time number {}", tries);
}
logger.trace("Retry4j executing callable {}", callable);
attemptStatus = tryCall(callable);
if (!attemptStatus.wasSuccessful()) {
handleFailedTry(tries + 1);
}
}
refreshRetryStatus(attemptStatus.wasSuccessful(), tries);
status.setEndTime(System.currentTimeMillis());
postExecutionCleanup(callable, maxTries, attemptStatus);
logger.debug("Finished retry4j execution in {} ms", status.getTotalElapsedDuration().toMillis());
logger.trace("Finished retry4j execution with executor state {}", this);
} finally {
if (null != onCompletionListener) {
onCompletionListener.onEvent(status);
}
}
return status;
}
private void postExecutionCleanup(Callable<T> callable, int maxTries, AttemptStatus<T> attemptStatus) {
if (!attemptStatus.wasSuccessful()) {
String failureMsg = String.format("Call '%s' failed after %d tries!", callable.toString(), maxTries);
if (null != onFailureListener) {
onFailureListener.onEvent(status);
} else {
logger.trace("Throwing retries exhausted exception");
throw new RetriesExhaustedException(failureMsg, lastKnownExceptionThatCausedRetry, status);
}
} else {
status.setResult(attemptStatus.getResult());
if (null != onSuccessListener) {
onSuccessListener.onEvent(status);
}
}
}
private AttemptStatus<T> tryCall(Callable<T> callable) throws UnexpectedException {
AttemptStatus attemptStatus = new AttemptStatus();
try {
T callResult = callable.call();
boolean shouldRetryOnThisResult = config.shouldRetryOnValue() && (
(config.getValuesToExpect() != null && !isOneOfValuesToExpect(callResult))
|| isOneOfValuesToRetryOn(callResult));
if (shouldRetryOnThisResult) {
attemptStatus.setSuccessful(false);
} else {
attemptStatus.setResult(callResult);
attemptStatus.setSuccessful(true);
}
} catch (Exception e) {
if (shouldThrowException(e)) {
logger.trace("Throwing expected exception {}", e);
throw new UnexpectedException("Unexpected exception thrown during retry execution!", e);
} else {
lastKnownExceptionThatCausedRetry = e;
attemptStatus.setSuccessful(false);
}
}
return attemptStatus;
}
private boolean isOneOfValuesToExpect(T callResult) {
Collection<Object> valuesToExpect = config.getValuesToExpect();
if (valuesToExpect != null) {
for (Object o : valuesToExpect) {
if (o.equals(callResult)) {
return true;
}
}
}
return false;
}
private boolean isOneOfValuesToRetryOn(T callResult) {
Collection<Object> valuesToRetryOn = config.getValuesToRetryOn();
if (valuesToRetryOn != null) {
for (Object o : valuesToRetryOn) {
if (o.equals(callResult)) {
return true;
}
}
}
return false;
}
private void handleBeforeNextTry(final long millisBetweenTries, final int tries) {
sleep(millisBetweenTries, tries);
if (null != beforeNextTryListener) {
beforeNextTryListener.onEvent(status);
}
}
private void handleFailedTry(int tries) {
refreshRetryStatus(false, tries);
if (null != afterFailedTryListener) {
afterFailedTryListener.onEvent(status);
}
}
private void refreshRetryStatus(boolean success, int tries) {
long currentTime = System.currentTimeMillis();
long elapsed = currentTime - status.getStartTime();
status.setTotalTries(tries);
status.setTotalElapsedDuration(Duration.of(elapsed, ChronoUnit.MILLIS));
status.setSuccessful(success);
status.setLastExceptionThatCausedRetry(lastKnownExceptionThatCausedRetry);
}
private void sleep(long millis, int tries) {
Duration duration = Duration.of(millis, ChronoUnit.MILLIS);
long millisToSleep = config.getBackoffStrategy().getDurationToWait(tries, duration).toMillis();
logger.trace("Retry4j executor sleeping for {} ms", millisToSleep);
try {
TimeUnit.MILLISECONDS.sleep(millisToSleep);
} catch (InterruptedException ignored) {
}
}
private boolean shouldThrowException(Exception e) {
if (this.config.getCustomRetryOnLogic() != null) {
//custom retry logic
return !this.config.getCustomRetryOnLogic().apply(e);
} else {
//config says to always retry
if (this.config.isRetryOnAnyException()) {
return false;
}
Set<Class<?>> exceptionsToMatch = new HashSet<>();
exceptionsToMatch.add(e.getClass());
if (this.config.shouldRetryOnCausedBy()) {
exceptionsToMatch.clear();
exceptionsToMatch.addAll(getExceptionCauses(e));
}
return !exceptionsToMatch.stream().anyMatch(ex -> matchesException(ex));
}
}
private boolean matchesException(Class<?> thrownExceptionClass) {
//config says to retry only on specific exceptions
for (Class<? extends Exception> exceptionToRetryOn : this.config.getRetryOnSpecificExceptions()) {
if (exceptionToRetryOn.isAssignableFrom(thrownExceptionClass)) {
return true;
}
}
//config says to retry on all except specific exceptions
if (!this.config.getRetryOnAnyExceptionExcluding().isEmpty()) {
for (Class<? extends Exception> exceptionToNotRetryOn : this.config.getRetryOnAnyExceptionExcluding()) {
if (exceptionToNotRetryOn.isAssignableFrom(thrownExceptionClass)) {
return false;
}
}
return true;
}
return false;
}
private Set<Class<?>> getExceptionCauses(Exception exception) {
Throwable parent = exception;
Set<Class<?>> causes = new HashSet<>();
while (parent.getCause() != null) {
causes.add(parent.getCause().getClass());
parent = parent.getCause();
}
return causes;
}
public RetryConfig getConfig() {
return config;
}
public RetryListener<T> getAfterFailedTryListener() {
return afterFailedTryListener;
}
public RetryListener<T> getBeforeNextTryListener() {
return beforeNextTryListener;
}
public RetryListener<T> getOnFailureListener() {
return onFailureListener;
}
public RetryListener<T> getOnSuccessListener() {
return onSuccessListener;
}
public RetryListener<T> getOnCompletionListener() {
return onCompletionListener;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("CallExecutor{");
sb.append("config=").append(config);
sb.append(", afterFailedTryListener=").append(afterFailedTryListener);
sb.append(", beforeNextTryListener=").append(beforeNextTryListener);
sb.append(", onFailureListener=").append(onFailureListener);
sb.append(", onSuccessListener=").append(onSuccessListener);
sb.append(", lastKnownExceptionThatCausedRetry=").append(lastKnownExceptionThatCausedRetry);
sb.append(", status=").append(status);
sb.append('}');
return sb.toString();
}
}
| mit |
lucasp90/learnyounode | lesson12.js | 360 | var http = require('http');
var fs = require('fs');
var map = require('through2-map');
var port = process.argv[2];
var path = process.argv[3];
var toUpper = map(function(result){
return result.toString().toUpperCase()
});
var server = http.createServer(function(req,res){
if(req.method == 'POST')
req.pipe(toUpper).pipe(res);
});
server.listen(port); | mit |
NikolaiMishev/OneHourSport | OneHourSport/OneHourSport.Web/Models/Account/LoginViewModel.cs | 471 | namespace OneHourSport.Web.Models.Account
{
using System.ComponentModel.DataAnnotations;
public class LoginViewModel
{
[Required]
[Display(Name = "Username")]
public string UserName { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[Display(Name = "Remember me?")]
public bool RememberMe { get; set; }
}
} | mit |
pixelpicosean/phaser | plugins/fbinstant/src/Product.js | 814 | /**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2018 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
var GetFastValue = require('../utils/object/GetFastValue');
/**
* @classdesc
* [description]
*
* @class FacebookInstantGamesPlugin
* @memberOf Phaser
* @constructor
* @since 3.12.0
*/
var Product = function (data)
{
return {
title: GetFastValue(data, 'title', ''),
productID: GetFastValue(data, 'productID', ''),
description: GetFastValue(data, 'description', ''),
imageURI: GetFastValue(data, 'imageURI', ''),
price: GetFastValue(data, 'price', ''),
priceCurrencyCode: GetFastValue(data, 'priceCurrencyCode', '')
};
};
module.exports = Product;
| mit |
frxstrem/fys3150 | project5/code/transactions.cc | 4741 | #include <iostream>
#include <cstdio>
#include <random>
#include <algorithm>
#include <iterator>
#include "transactions.hh"
using namespace std;
// pseudorandom number generator
default_random_engine G;
// seed PRNG with true random number
unsigned int seed_simulation() {
random_device source;
unsigned int seed = source();
G.seed(seed);
return seed;
}
/**
* Simulate transactions.
*
* Arguments:
* size_t N - Number of agents
* size_t K - Number of transactions
* double m0 - Initial amount of money for each agent
* double l - Saving fraction λ (default: 0.0)
* double S - Higher number gives more accurate simulations but slower (required if α or γ is given)
* double a - Neighbor preference parameter α (default: 0.0)
* double g - Previous interaction preference parameter γ (default: 0.0)
*
* Returns:
* Vector with the amount of money each agent has after all transactions
**/
// 5a)
vector<double> simulate_transactions(size_t N, size_t K, double m0) {
// uniform distributions
uniform_int_distribution<> idist(0, N-1); // discrete distribution on [0,N)
uniform_real_distribution<> rdist(0, 1); // real distribution on [0,1)
// list of agents' money
vector<double> m(N, m0);
// do switches
for(size_t k = 0; k < K; k++) {
// pick two random, different agents
int i = idist(G), j = idist(G);
while(i == j) j = idist(G);
// calculate total money of the two agents
double mtot = m[i] + m[j];
// redistribute money between the two agents
double e = rdist(G);
m[i] = e * mtot;
m[j] = (1 - e) * mtot;
}
return m;
}
// 5c)
vector<double> simulate_transactions(size_t N, size_t K, double m0, double l) {
// uniform distributions
uniform_int_distribution<> idist(0, N-1); // discrete distribution on [0,N)
uniform_real_distribution<> rdist(0, 1); // real distribution on [0,1)
// list of agents' money
vector<double> m(N, m0);
// do switches
for(size_t k = 0; k < K; k++) {
// pick two random, different agents
int i = idist(G), j = idist(G);
while(i == j) j = idist(G);
// redistribute money between the two agents
double e = rdist(G);
double rm = (1 - l) * (e * m[j] - (1 - e) * m[i]);
m[i] += rm;
m[j] -= rm;
}
return m;
}
// 5d)
vector<double> simulate_transactions(size_t N, size_t K, double m0, double l, double S, double a) {
// uniform distributions
uniform_int_distribution<> idist(0, N-1); // discrete distribution on [0,N)
uniform_real_distribution<> rdist(0, 1); // real distribution on [0,1)
// list of agents' money
vector<double> m(N, m0);
// count total tests vs. accepted tests
int total_tests = 0, accepted_tests = 0;
// do switches
for(size_t k = 0; k < K; k++) {
// pick two random, different agents
int i, j;
double r, dm, M;
do {
i = idist(G);
j = idist(G);
r = S * rdist(G);
dm = m[i] - m[j];
M = pow(dm * dm, - a);
total_tests++; // DEBUGGING
accepted_tests += (M < S * S);
} while(i == j || (dm != 0 && r * r > M));
// redistribute money between the two agents
double e = rdist(G);
double rm = (1 - l) * (e * m[j] - (1 - e) * m[i]);
m[i] += rm;
m[j] -= rm;
}
fprintf(stderr, "accepted tests: %6.2f%% (%6.2fx)\n", 100.0 * accepted_tests / total_tests, 1.0 * total_tests / K);
return m;
}
// // 5e)
vector<double> simulate_transactions(size_t N, size_t K, double m0, double l, double S, double a, double g) {
// uniform distributions
uniform_int_distribution<> idist(0, N-1); // discrete distribution on [0,N)
uniform_real_distribution<> rdist(0, 1); // real distribution on [0,1)
// list of agents' money
vector<double> m(N, m0);
// number of previous interactions between pairs of agents
vector<vector<int>> c(N, vector<int>(N, 0));
// count total tests vs. accepted tests
int total_tests = 0, accepted_tests = 0;
// do switches
for(size_t k = 0; k < K; k++) {
// pick two random, different agents
int i, j;
double r, dm, C, M;
do {
i = idist(G);
j = idist(G);
r = S * rdist(G);
dm = m[i] - m[j];
C = c[i][j] + 1;
M = pow(dm * dm, - a) * pow(C * C, g);
// DEBUGGING
total_tests++;
accepted_tests += (M < S * S);
} while(i == j || (dm != 0 && r * r > M));
// redistribute money between the two agents
double e = rdist(G);
double rm = (1 - l) * (e * m[j] - (1 - e) * m[i]);
m[i] += rm;
m[j] -= rm;
// count transaction
c[i][j]++;
c[j][i]++;
}
fprintf(stderr, "accepted tests: %6.2f%% (%6.2fx)\n", 100.0 * accepted_tests / total_tests, 1.0 * total_tests / K);
return m;
}
| mit |
peteward44/WebNES | project/js/db/A48AD4C24648F0996CC5C06B5CBD1F284F04D40F.js | 1161 | this.NesDb = this.NesDb || {};
NesDb[ 'A48AD4C24648F0996CC5C06B5CBD1F284F04D40F' ] = {
"$": {
"name": "Marusa no Onna",
"altname": "マルサの女",
"class": "Licensed",
"catalog": "CAP-FM",
"publisher": "Capcom",
"developer": "Capcom",
"region": "Japan",
"players": "1",
"date": "1989-09-19"
},
"cartridge": [
{
"$": {
"system": "Famicom",
"crc": "E2281986",
"sha1": "A48AD4C24648F0996CC5C06B5CBD1F284F04D40F",
"dump": "ok",
"dumper": "bootgod",
"datedumped": "2007-04-28"
},
"board": [
{
"$": {
"type": "HVC-SLROM",
"pcb": "HVC-SLROM-03",
"mapper": "1"
},
"prg": [
{
"$": {
"name": "CAP-FM-0 PRG",
"size": "128k",
"crc": "37BF04D7",
"sha1": "68FA0D57A868269B6090D9FE5E9F1BBD3754591B"
}
}
],
"chr": [
{
"$": {
"name": "CAP-FM-0 CHR",
"size": "128k",
"crc": "8A586745",
"sha1": "4E29B3622B2FBBA0E4D6E5B9BD26B445DD9BDE22"
}
}
],
"chip": [
{
"$": {
"type": "MMC1B2"
}
}
]
}
]
}
]
};
| mit |
sclark39/UE-VR-Code-Sample | Source/VRCode/VRCodeGameModeBase.cpp | 155 | /*
* Author: Skyler Clark (@sclark39)
* Website: http://skylerclark.com
* License: MIT License
*/
#include "VRCode.h"
#include "VRCodeGameModeBase.h"
| mit |
binidini/mstock | admin/rights_managed/step_add.php | 452 | <? include("../function/db.php");?>
<? include("../function/upload.php");?>
<?
//Check access
admin_panel_access("settings_rightsmanaged");
$sql="insert into rights_managed_structure (id_parent,types,title,adjust,price,price_id,group_id,option_id,conditions,collapse) values (0,0,'".result($_POST["title"])."','',0,".(int)$_GET["id"].",0,0,'',0)";
$db->execute($sql);
$db->close();
header("location:content.php?id=".$_GET["id"]);
?> | mit |
wilfreddenton/react-motion | src/components.js | 10118 | import mapTree from './mapTree';
import noVelocity from './noVelocity';
import compareTrees from './compareTrees';
import mergeDiff from './mergeDiff';
import configAnimation from './animationLoop';
import zero from './zero';
import {interpolateValue, updateCurrValue, updateCurrVelocity} from './updateTree';
import presets from './presets';
import stepper from './stepper';
const startAnimation = configAnimation();
function animationStep(shouldMerge, stopAnimation, getProps, timestep, state) {
let {currValue, currVelocity} = state;
let {willEnter, willLeave, endValue} = getProps();
if (typeof endValue === 'function') {
endValue = endValue(currValue);
}
let mergedValue = endValue; // set mergedValue to endValue as the default
let hasNewKey = false;
if (shouldMerge) {
mergedValue = mergeDiff(
currValue,
endValue,
// TODO: stop allocating like crazy in this whole code path
key => {
const res = willLeave(key, currValue[key], endValue, currValue, currVelocity);
if (res == null) {
// For legacy reason. We won't allow returning null soon
// TODO: remove, after next release
return null;
}
if (noVelocity(currVelocity[key]) && compareTrees(currValue[key], res)) {
return null;
}
return res;
}
);
Object.keys(mergedValue)
.filter(key => !currValue.hasOwnProperty(key))
.forEach(key => {
hasNewKey = true;
const enterValue = willEnter(key, mergedValue[key], endValue, currValue, currVelocity);
// We can mutate this here because mergeDiff returns a new Obj
mergedValue[key] = enterValue;
currValue = {
...currValue,
[key]: enterValue,
};
currVelocity = {
...currVelocity,
[key]: mapTree(zero, enterValue),
};
});
}
const newCurrValue = updateCurrValue(timestep, currValue, currVelocity, mergedValue);
const newCurrVelocity = updateCurrVelocity(timestep, currValue, currVelocity, mergedValue);
if (!hasNewKey && noVelocity(currVelocity) && noVelocity(newCurrVelocity)) {
// check explanation in `Spring.animationRender`
stopAnimation(); // Nasty side effects....
}
return {
currValue: newCurrValue,
currVelocity: newCurrVelocity,
};
}
// temporary forks of updateCurrVal, updateCurrVelocity and animationStep
// don't be scared by the amount of code! It's mostly duplicate for now
function updateCurrentStyle(frameRate, currentStyle, currentVelocity, style) {
let ret = {};
for (let key in style) {
if (!style.hasOwnProperty(key)) {
continue;
}
if (!style[key].config) {
ret[key] = style[key];
// not a spring config, not something we want to interpolate
continue;
}
const [k, b] = style[key].config;
const val = stepper(
frameRate,
currentStyle[key].val,
currentVelocity[key],
style[key].val,
k,
b,
)[0];
ret[key] = {
val: val,
config: style[key].config,
};
}
return ret;
}
function updateCurrentVelocity(frameRate, currentStyle, currentVelocity, style) {
let ret = {};
for (let key in style) {
if (!style.hasOwnProperty(key)) {
continue;
}
if (!style[key].config) {
// not a spring config, not something we want to interpolate
ret[key] = style[key];
continue;
}
const [k, b] = style[key].config;
const val = stepper(
frameRate,
currentStyle[key].val,
currentVelocity[key],
style[key].val,
k,
b,
)[1];
ret[key] = val;
}
return ret;
}
// Temporary new loop for the Motion component
function animationStepMotion(shouldMerge, stopAnimation, getProps, timestep, state) {
let {currentStyle, currentVelocity} = state;
let {style} = getProps();
const newCurrentStyle =
updateCurrentStyle(timestep, currentStyle, currentVelocity, style);
const newCurrentVelocity =
updateCurrentVelocity(timestep, currentStyle, currentVelocity, style);
if (noVelocity(currentVelocity) && noVelocity(newCurrentVelocity)) {
// check explanation in `Motion.animationRender`
stopAnimation(); // Nasty side effects....
}
return {
currentStyle: newCurrentStyle,
currentVelocity: newCurrentVelocity,
};
}
function mapObject(f, obj) {
let ret = {};
for (let key in obj) {
if (!obj.hasOwnProperty(key)) {
continue;
}
ret[key] = f(obj[key], key);
}
return ret;
}
// instead of exposing {val: bla, config: bla}, use a helper
function spring(val, config = presets.noWobble) {
return {val, config};
}
let hasWarnedForSpring = false;
// let hasWarnedForTransitionSpring = false;
export default function components(React) {
const {PropTypes} = React;
const Spring = React.createClass({
propTypes: {
defaultValue: PropTypes.oneOfType([
PropTypes.object,
PropTypes.array,
PropTypes.number,
]),
endValue: PropTypes.oneOfType([
PropTypes.func,
PropTypes.object,
PropTypes.array,
PropTypes.number,
]).isRequired,
children: PropTypes.func.isRequired,
},
componentWillMount() {
if (process.env.NODE_ENV === 'development') {
if (!hasWarnedForSpring) {
hasWarnedForSpring = true;
// TODO: check props, provide more descriptive warning.
console.error(
`Spring has now been renamed to Motion. Please see the release note
for the upgrade path. Thank you!`
);
}
}
},
render() {
return null;
},
});
// this is mostly the same code as SPring, again, temporary!
const Motion = React.createClass({
propTypes: {
defaultStyle: PropTypes.object,
style: PropTypes.object,
children: PropTypes.func,
},
getInitialState() {
const {defaultStyle, style} = this.props;
const currentStyle = defaultStyle || style;
return {
currentStyle: currentStyle,
currentVelocity: mapObject(zero, currentStyle),
};
},
componentDidMount() {
this.animationStep = animationStepMotion.bind(
null,
false,
() => this.stopAnimation(),
() => this.props,
);
this.startAnimating();
},
componentWillReceiveProps() {
this.startAnimating();
},
stopAnimation: null,
// used in animationRender
hasUnmounted: false,
animationStep: null,
componentWillUnmount() {
this.stopAnimation();
this.hasUnmounted = true;
},
startAnimating() {
// Is smart enough to not start it twice
this.stopAnimation = startAnimation(
this.state,
this.animationStep,
this.animationRender,
);
},
animationRender(alpha, nextState, prevState) {
// `this.hasUnmounted` might be true in the following condition:
// user does some checks in `style` and calls an owner handler
// owner sets state in the callback, triggering a re-render
// re-render unmounts the Spring
if (!this.hasUnmounted) {
this.setState({
currentStyle: interpolateValue(
alpha,
nextState.currentStyle,
prevState.currentStyle,
),
currentVelocity: nextState.currentVelocity,
});
}
},
render() {
const renderedChildren = this.props.children(this.state.currentStyle);
return renderedChildren && React.Children.only(renderedChildren);
},
});
// TODO: warn when obj uses numerical keys
// TODO: warn when endValue doesn't contain a val
const TransitionSpring = React.createClass({
propTypes: {
defaultValue: PropTypes.objectOf(PropTypes.any),
endValue: PropTypes.oneOfType([
PropTypes.func,
PropTypes.objectOf(PropTypes.any.isRequired),
// PropTypes.arrayOf(PropTypes.shape({
// key: PropTypes.any.isRequired,
// })),
// PropTypes.arrayOf(PropTypes.element),
]).isRequired,
willLeave: PropTypes.oneOfType([
PropTypes.func,
// PropTypes.object,
// PropTypes.array,
]),
willEnter: PropTypes.oneOfType([
PropTypes.func,
// PropTypes.object,
// PropTypes.array,
]),
children: PropTypes.func.isRequired,
},
getDefaultProps() {
return {
willEnter: (key, value) => value,
willLeave: () => null,
};
},
getInitialState() {
const {endValue, defaultValue} = this.props;
let currValue;
if (defaultValue == null) {
if (typeof endValue === 'function') {
currValue = endValue();
} else {
currValue = endValue;
}
} else {
currValue = defaultValue;
}
return {
currValue: currValue,
currVelocity: mapTree(zero, currValue),
};
},
componentDidMount() {
this.animationStep = animationStep.bind(null, true, () => this.stopAnimation(), () => this.props);
this.startAnimating();
},
componentWillReceiveProps() {
this.startAnimating();
},
stopAnimation: null,
// used in animationRender
hasUnmounted: false,
animationStep: null,
componentWillUnmount() {
this.stopAnimation();
this.hasUnmounted = true;
},
startAnimating() {
this.stopAnimation = startAnimation(
this.state,
this.animationStep,
this.animationRender,
);
},
animationRender(alpha, nextState, prevState) {
// See comment in Spring.
if (!this.hasUnmounted) {
this.setState({
currValue: interpolateValue(alpha, nextState.currValue, prevState.currValue),
currVelocity: nextState.currVelocity,
});
}
},
render() {
const renderedChildren = this.props.children(this.state.currValue);
return renderedChildren && React.Children.only(renderedChildren);
},
});
return {Spring, TransitionSpring, Motion, spring};
}
| mit |
Kenwhite23/Unamed | src/qt/locale/bitcoin_el_GR.ts | 138189 | <?xml version="1.0" ?><!DOCTYPE TS><TS language="el_GR" version="2.0">
<defaultcodec>UTF-8</defaultcodec>
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About Shiacoin</source>
<translation>Σχετικά με το Shiacoin</translation>
</message>
<message>
<location line="+39"/>
<source><b>Shiacoin</b> version</source>
<translation>Έκδοση Shiacoin</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>
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.</translation>
</message>
<message>
<location filename="../aboutdialog.cpp" line="+14"/>
<source>Copyright</source>
<translation>Πνευματική ιδιοκτησία </translation>
</message>
<message>
<location line="+0"/>
<source>The Shiacoin developers</source>
<translation>Οι Shiacoin προγραμματιστές </translation>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation>Βιβλίο Διευθύνσεων</translation>
</message>
<message>
<location line="+19"/>
<source>Double-click to edit address or label</source>
<translation>Διπλό-κλικ για επεξεργασία της διεύθυνσης ή της ετικέτας</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>Δημιούργησε νέα διεύθυνση</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Αντέγραψε την επιλεγμένη διεύθυνση στο πρόχειρο του συστήματος</translation>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation>&Νέα διεύθυνση</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+63"/>
<source>These are your Shiacoin 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>Αυτές είναι οι Shiacoin διευθύνσεις σας για να λαμβάνετε πληρωμές. Δίνοντας μία ξεχωριστή διεύθυνση σε κάθε αποστολέα, θα μπορείτε να ελέγχετε ποιος σας πληρώνει.</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>&Copy Address</source>
<translation>&Αντιγραφή διεύθυνσης</translation>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation>Δείξε &QR κωδικα</translation>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a Shiacoin address</source>
<translation>Υπογράψτε ένα μήνυμα για ν' αποδείξετε πως σας ανήκει μια συγκεκριμένη διεύθυνση Shiacoin</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>&Υπέγραψε το μήνυμα</translation>
</message>
<message>
<location line="+25"/>
<source>Delete the currently selected address from the list</source>
<translation>Αντιγραφη της επιλεγμενης διεύθυνσης στο πρόχειρο του συστηματος</translation>
</message>
<message>
<location line="+27"/>
<source>Export the data in the current tab to a file</source>
<translation>Εξαγωγή δεδομένων καρτέλας σε αρχείο</translation>
</message>
<message>
<location line="+3"/>
<source>&Export</source>
<translation>&Εξαγωγή</translation>
</message>
<message>
<location line="-44"/>
<source>Verify a message to ensure it was signed with a specified Shiacoin address</source>
<translation>Υπογράψτε ένα μήνυμα για ν' αποδείξετε πως ανήκει μια συγκεκριμένη διεύθυνση Shiacoin</translation>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation>&Επιβεβαίωση μηνύματος</translation>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>&Διαγραφή</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="-5"/>
<source>These are your Shiacoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source>
<translation>Αυτές είναι οι Shiacoin διευθύνσεις σας για να λαμβάνετε πληρωμές. Δίνοντας μία ξεχωριστή διεύθυνση σε κάθε αποστολέα, θα μπορείτε να ελέγχετε ποιος σας πληρώνει.</translation>
</message>
<message>
<location line="+13"/>
<source>Copy &Label</source>
<translation>Αντιγραφή &επιγραφής</translation>
</message>
<message>
<location line="+1"/>
<source>&Edit</source>
<translation>&Επεξεργασία</translation>
</message>
<message>
<location line="+1"/>
<source>Send &Coins</source>
<translation>Αποστολή νομισμάτων</translation>
</message>
<message>
<location line="+260"/>
<source>Export Address Book Data</source>
<translation>Εξαγωγή Δεδομενων Βιβλίου Διευθύνσεων</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Αρχείο οριοθετημένο με κόμματα (*.csv)</translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation>Εξαγωγή λαθών</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Αδυναμία εγγραφής στο αρχείο %1.</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation>Ετικέτα</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Διεύθυνση</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(χωρίς ετικέτα)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation>Φράση πρόσβασης </translation>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>Βάλτε κωδικό πρόσβασης</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>Νέος κωδικός πρόσβασης</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>Επανέλαβε τον νέο κωδικό πρόσβασης</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+33"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.</source>
<translation>Εισάγετε τον νέο κωδικό πρόσβασης στον πορτοφόλι <br/> Παρακαλώ χρησιμοποιείστε ένα κωδικό με <b> 10 ή περισσότερους τυχαίους χαρακτήρες</b> ή <b> οχτώ ή παραπάνω λέξεις</b>.</translation>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation>Κρυπτογράφησε το πορτοφόλι</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>Αυτη η ενεργεία χρειάζεται τον κωδικό του πορτοφολιού για να ξεκλειδώσει το πορτοφόλι.</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>Ξεκλειδωσε το πορτοφολι</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>Αυτη η ενεργεια χρειάζεται τον κωδικο του πορτοφολιου για να αποκρυπτογραφησειι το πορτοφολι.</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>Αποκρυπτογράφησε το πορτοφολι</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>Άλλαξε κωδικο πρόσβασης</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Εισάγετε τον παλιό και τον νεο κωδικο στο πορτοφολι.</translation>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation>Επιβεβαίωσε την κρυπτογραφηση του πορτοφολιού</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR LITECOINS</b>!</source>
<translation>Προσοχη: Εαν κρυπτογραφησεις το πορτοφολι σου και χάσεις τον κωδικο σου θα χάσεις <b> ΟΛΑ ΣΟΥ ΤΑ LITECOINS</b>!
Είσαι σίγουρος ότι θέλεις να κρυπτογραφησεις το πορτοφολι;</translation>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>Είστε σίγουροι ότι θέλετε να κρυπτογραφήσετε το πορτοφόλι σας;</translation>
</message>
<message>
<location line="+15"/>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation>ΣΗΜΑΝΤΙΚΟ: Τα προηγούμενα αντίγραφα ασφαλείας που έχετε κάνει από το αρχείο του πορτοφόλιου σας θα πρέπει να αντικατασταθουν με το νέο που δημιουργείται, κρυπτογραφημένο αρχείο πορτοφόλιου. Για λόγους ασφαλείας, τα προηγούμενα αντίγραφα ασφαλείας του μη κρυπτογραφημένου αρχείου πορτοφόλιου θα καταστουν άχρηστα μόλις αρχίσετε να χρησιμοποιείτε το νέο κρυπτογραφημένο πορτοφόλι. </translation>
</message>
<message>
<location line="+100"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation>Προσοχη: το πλήκτρο Caps Lock είναι ενεργο.</translation>
</message>
<message>
<location line="-130"/>
<location line="+58"/>
<source>Wallet encrypted</source>
<translation>Κρυπτογραφημενο πορτοφολι</translation>
</message>
<message>
<location line="-56"/>
<source>Shiacoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your fastcoins from being stolen by malware infecting your computer.</source>
<translation>Το Shiacoin θα κλεισει τώρα για να τελειώσει την διαδικασία κρυπτογραφησης. Θυμησου ότι κρυπτογραφώντας το πορτοφολι σου δεν μπορείς να προστατέψεις πλήρως τα fastcoins σου από κλοπή στην περίπτωση όπου μολυνθεί ο υπολογιστής σου με κακόβουλο λογισμικο.</translation>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+42"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>Η κρυπτογραφηση του πορτοφολιού απέτυχε</translation>
</message>
<message>
<location line="-54"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Η κρυπτογράφηση του πορτοφολιού απέτυχε λογω εσωτερικού σφάλματος. Το πορτοφολι δεν κρυπτογραφηθηκε.</translation>
</message>
<message>
<location line="+7"/>
<location line="+48"/>
<source>The supplied passphrases do not match.</source>
<translation>Οι εισαχθέντες κωδικοί δεν ταιριάζουν.</translation>
</message>
<message>
<location line="-37"/>
<source>Wallet unlock failed</source>
<translation>το ξεκλείδωμα του πορτοφολιού απέτυχε</translation>
</message>
<message>
<location line="+1"/>
<location line="+11"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>Ο κωδικος που εισήχθη για την αποκρυπτογραφηση του πορτοφολιού ήταν λαθος.</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>Η αποκρυπτογραφηση του πορτοφολιού απέτυχε</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation>Ο κωδικος του πορτοφολιού άλλαξε με επιτυχία.</translation>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+233"/>
<source>Sign &message...</source>
<translation>Υπογραφή &Μηνύματος...</translation>
</message>
<message>
<location line="+280"/>
<source>Synchronizing with network...</source>
<translation>Συγχρονισμός με το δίκτυο...</translation>
</message>
<message>
<location line="-349"/>
<source>&Overview</source>
<translation>&Επισκόπηση</translation>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation>Εμφάνισε γενική εικονα του πορτοφολιού</translation>
</message>
<message>
<location line="+20"/>
<source>&Transactions</source>
<translation>&Συναλλαγές</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>Περιήγηση στο ιστορικο συνναλαγων</translation>
</message>
<message>
<location line="+7"/>
<source>Edit the list of stored addresses and labels</source>
<translation>Εξεργασια της λιστας των αποθηκευμενων διευθύνσεων και ετικετων</translation>
</message>
<message>
<location line="-14"/>
<source>Show the list of addresses for receiving payments</source>
<translation>Εμφάνισε την λίστα των διευθύνσεων για την παραλαβή πληρωμων</translation>
</message>
<message>
<location line="+31"/>
<source>E&xit</source>
<translation>Έ&ξοδος</translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>Εξοδος από την εφαρμογή</translation>
</message>
<message>
<location line="+4"/>
<source>Show information about Shiacoin</source>
<translation>Εμφάνισε πληροφορίες σχετικά με το Shiacoin</translation>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation>Σχετικά με &Qt</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation>Εμφάνισε πληροφορίες σχετικά με Qt</translation>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>&Επιλογές...</translation>
</message>
<message>
<location line="+6"/>
<source>&Encrypt Wallet...</source>
<translation>&Κρυπτογράφησε το πορτοφόλι</translation>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation>&Αντίγραφο ασφαλείας του πορτοφολιού</translation>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation>&Άλλαξε κωδικο πρόσβασης</translation>
</message>
<message>
<location line="+285"/>
<source>Importing blocks from disk...</source>
<translation>Εισαγωγή μπλοκ από τον σκληρο δίσκο ... </translation>
</message>
<message>
<location line="+3"/>
<source>Reindexing blocks on disk...</source>
<translation>Φόρτωση ευρετηρίου μπλοκ στον σκληρο δισκο...</translation>
</message>
<message>
<location line="-347"/>
<source>Send coins to a Shiacoin address</source>
<translation>Στείλε νομισματα σε μια διεύθυνση Shiacoin</translation>
</message>
<message>
<location line="+49"/>
<source>Modify configuration options for Shiacoin</source>
<translation>Επεργασία ρυθμισεων επιλογών για το Shiacoin</translation>
</message>
<message>
<location line="+9"/>
<source>Backup wallet to another location</source>
<translation>Δημιουργία αντιγράφου ασφαλείας πορτοφολιού σε άλλη τοποθεσία</translation>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>Αλλαγή του κωδικού κρυπτογράφησης του πορτοφολιού</translation>
</message>
<message>
<location line="+6"/>
<source>&Debug window</source>
<translation>&Παράθυρο αποσφαλμάτωσης</translation>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation>Άνοιγμα κονσόλας αποσφαλμάτωσης και διαγνωστικών</translation>
</message>
<message>
<location line="-4"/>
<source>&Verify message...</source>
<translation>&Επιβεβαίωση μηνύματος</translation>
</message>
<message>
<location line="-165"/>
<location line="+530"/>
<source>Shiacoin</source>
<translation>Shiacoin</translation>
</message>
<message>
<location line="-530"/>
<source>Wallet</source>
<translation>Πορτοφόλι</translation>
</message>
<message>
<location line="+101"/>
<source>&Send</source>
<translation>&Αποστολή</translation>
</message>
<message>
<location line="+7"/>
<source>&Receive</source>
<translation>&Παραλαβή </translation>
</message>
<message>
<location line="+14"/>
<source>&Addresses</source>
<translation>&Διεύθυνσεις</translation>
</message>
<message>
<location line="+22"/>
<source>&About Shiacoin</source>
<translation>&Σχετικα:Shiacoin</translation>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation>&Εμφάνισε/Κρύψε</translation>
</message>
<message>
<location line="+1"/>
<source>Show or hide the main Window</source>
<translation>Εμφάνιση ή αποκρύψη του κεντρικου παράθυρου </translation>
</message>
<message>
<location line="+3"/>
<source>Encrypt the private keys that belong to your wallet</source>
<translation>Κρυπτογραφήστε τα ιδιωτικά κλειδιά που ανήκουν στο πορτοφόλι σας </translation>
</message>
<message>
<location line="+7"/>
<source>Sign messages with your Shiacoin addresses to prove you own them</source>
<translation>Υπογράψτε ένα μήνυμα για να βεβαιώσετε πως είστε ο κάτοχος αυτής της διεύθυνσης</translation>
</message>
<message>
<location line="+2"/>
<source>Verify messages to ensure they were signed with specified Shiacoin addresses</source>
<translation>Υπογράψτε ένα μήνυμα για ν' αποδείξετε πως ανήκει μια συγκεκριμένη διεύθυνση Shiacoin</translation>
</message>
<message>
<location line="+28"/>
<source>&File</source>
<translation>&Αρχείο</translation>
</message>
<message>
<location line="+7"/>
<source>&Settings</source>
<translation>&Ρυθμίσεις</translation>
</message>
<message>
<location line="+6"/>
<source>&Help</source>
<translation>&Βοήθεια</translation>
</message>
<message>
<location line="+9"/>
<source>Tabs toolbar</source>
<translation>Εργαλειοθήκη καρτελών</translation>
</message>
<message>
<location line="+17"/>
<location line="+10"/>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
<message>
<location line="+47"/>
<source>Shiacoin client</source>
<translation>Πελάτης Shiacoin</translation>
</message>
<message numerus="yes">
<location line="+141"/>
<source>%n active connection(s) to Shiacoin network</source>
<translation><numerusform>%n ενεργή σύνδεση στο δίκτυο Shiacoin</numerusform><numerusform>%n ενεργές συνδέσεις στο δίκτυο Βitcoin</numerusform></translation>
</message>
<message>
<location line="+22"/>
<source>No block source available...</source>
<translation>Η πηγή του μπλοκ δεν ειναι διαθέσιμη... </translation>
</message>
<message>
<location line="+12"/>
<source>Processed %1 of %2 (estimated) blocks of transaction history.</source>
<translation>Μεταποιημένα %1 απο % 2 (κατ 'εκτίμηση) μπλοκ της ιστορίας της συναλλαγής. </translation>
</message>
<message>
<location line="+4"/>
<source>Processed %1 blocks of transaction history.</source>
<translation>Έγινε λήψη %1 μπλοκ ιστορικού συναλλαγών</translation>
</message>
<message numerus="yes">
<location line="+20"/>
<source>%n hour(s)</source>
<translation><numerusform>%n ώρες </numerusform><numerusform>%n ώρες </numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation><numerusform>%n ημέρες </numerusform><numerusform>%n ημέρες </numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n week(s)</source>
<translation><numerusform>%n εβδομαδες</numerusform><numerusform>%n εβδομαδες</numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>%1 behind</source>
<translation>%1 πίσω</translation>
</message>
<message>
<location line="+14"/>
<source>Last received block was generated %1 ago.</source>
<translation>Το τελευταίο μπλοκ που ελήφθη δημιουργήθηκε %1 πριν.</translation>
</message>
<message>
<location line="+2"/>
<source>Transactions after this will not yet be visible.</source>
<translation>Οι συναλλαγές μετά από αυτό δεν θα είναι ακόμη ορατες.</translation>
</message>
<message>
<location line="+22"/>
<source>Error</source>
<translation>Σφάλμα</translation>
</message>
<message>
<location line="+3"/>
<source>Warning</source>
<translation>Προειδοποίηση</translation>
</message>
<message>
<location line="+3"/>
<source>Information</source>
<translation>Πληροφορία</translation>
</message>
<message>
<location line="+70"/>
<source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source>
<translation>Η συναλλαγή ξεπερνάει το όριο.
Μπορεί να ολοκληρωθεί με μια αμοιβή των %1, η οποία αποδίδεται στους κόμβους που επεξεργάζονται τις συναλλαγές και βοηθούν στην υποστήριξη του δικτύου.
Θέλετε να συνεχίσετε;</translation>
</message>
<message>
<location line="-140"/>
<source>Up to date</source>
<translation>Ενημερωμένο</translation>
</message>
<message>
<location line="+31"/>
<source>Catching up...</source>
<translation>Ενημέρωση...</translation>
</message>
<message>
<location line="+113"/>
<source>Confirm transaction fee</source>
<translation>Επιβεβαίωση αμοιβής συναλλαγής</translation>
</message>
<message>
<location line="+8"/>
<source>Sent transaction</source>
<translation>Η συναλλαγή απεστάλη</translation>
</message>
<message>
<location line="+0"/>
<source>Incoming transaction</source>
<translation>Εισερχόμενη συναλλαγή</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>Ημερομηνία: %1
Ποσό: %2
Τύπος: %3
Διεύθυνση: %4
</translation>
</message>
<message>
<location line="+33"/>
<location line="+23"/>
<source>URI handling</source>
<translation>Χειρισμός URI</translation>
</message>
<message>
<location line="-23"/>
<location line="+23"/>
<source>URI can not be parsed! This can be caused by an invalid Shiacoin address or malformed URI parameters.</source>
<translation>Το URI δεν μπορεί να αναλυθεί! Αυτό μπορεί να προκληθεί από μια μη έγκυρη διεύθυνση Shiacoin ή ακατάλληλη παραμέτρο URI.</translation>
</message>
<message>
<location line="+17"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>Το πορτοφόλι είναι <b>κρυπτογραφημένο</b> και <b>ξεκλείδωτο</b></translation>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>Το πορτοφόλι είναι <b>κρυπτογραφημένο</b> και <b>κλειδωμένο</b></translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="+111"/>
<source>A fatal error occurred. Shiacoin can no longer continue safely and will quit.</source>
<translation>Παρουσιάστηκε ανεπανόρθωτο σφάλμα. Το Shiacoin δεν μπορεί πλέον να συνεχίσει με ασφάλεια και θα τερματισθει.</translation>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+104"/>
<source>Network Alert</source>
<translation>Ειδοποίηση Δικτύου</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>Επεξεργασία Διεύθυνσης</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation>&Επιγραφή</translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation>Η επιγραφή που σχετίζεται με αυτή την καταχώρηση του βιβλίου διευθύνσεων</translation>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>&Διεύθυνση</translation>
</message>
<message>
<location line="+10"/>
<source>The address associated with this address book entry. This can only be modified for sending addresses.</source>
<translation>Η διεύθυνση που σχετίζεται με αυτή την καταχώρηση του βιβλίου διευθύνσεων. Μπορεί να τροποποιηθεί μόνο για τις διευθύνσεις αποστολής.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+21"/>
<source>New receiving address</source>
<translation>Νέα διεύθυνση λήψης</translation>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation>Νέα διεύθυνση αποστολής</translation>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation>Επεξεργασία διεύθυνσης λήψης</translation>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation>Επεξεργασία διεύθυνσης αποστολής</translation>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>Η διεύθυνση "%1" βρίσκεται ήδη στο βιβλίο διευθύνσεων.</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid Shiacoin address.</source>
<translation>Η διεύθυνση "%1" δεν είναι έγκυρη Shiacoin διεύθυνση.</translation>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation>Δεν είναι δυνατό το ξεκλείδωμα του πορτοφολιού.</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>Η δημιουργία νέου κλειδιού απέτυχε.</translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+424"/>
<location line="+12"/>
<source>Shiacoin-Qt</source>
<translation>Shiacoin-qt</translation>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation>έκδοση</translation>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation>Χρήση:</translation>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation>επιλογής γραμμής εντολών</translation>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation>επιλογές UI</translation>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation>Όρισε γλώσσα, για παράδειγμα "de_DE"(προεπιλογή:τοπικές ρυθμίσεις)</translation>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation>Έναρξη ελαχιστοποιημένο</translation>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation>Εμφάνισε την οθόνη εκκίνησης κατά την εκκίνηση(προεπιλογή:1)</translation>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation>Ρυθμίσεις</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation>&Κύριο</translation>
</message>
<message>
<location line="+6"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source>
<translation>Η προαιρετική αμοιβή για κάθε kB επισπεύδει την επεξεργασία των συναλλαγών σας. Οι περισσότερες συναλλαγές είναι 1 kB. </translation>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation>Αμοιβή &συναλλαγής</translation>
</message>
<message>
<location line="+31"/>
<source>Automatically start Shiacoin after logging in to the system.</source>
<translation>Αυτόματη εκκίνηση του Shiacoin μετά την εισαγωγή στο σύστημα</translation>
</message>
<message>
<location line="+3"/>
<source>&Start Shiacoin on system login</source>
<translation>&Έναρξη του Βιtcoin κατά την εκκίνηση του συστήματος</translation>
</message>
<message>
<location line="+35"/>
<source>Reset all client options to default.</source>
<translation>Επαναφορα όλων των επιλογων του πελάτη σε default.</translation>
</message>
<message>
<location line="+3"/>
<source>&Reset Options</source>
<translation>Επαναφορα ρυθμίσεων</translation>
</message>
<message>
<location line="+13"/>
<source>&Network</source>
<translation>&Δίκτυο</translation>
</message>
<message>
<location line="+6"/>
<source>Automatically open the Shiacoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation>Αυτόματο άνοιγμα των θυρών Shiacoin στον δρομολογητή. Λειτουργεί μόνο αν ο δρομολογητής σας υποστηρίζει τη λειτουργία UPnP.</translation>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation>Απόδοση θυρών με χρήστη &UPnP</translation>
</message>
<message>
<location line="+7"/>
<source>Connect to the Shiacoin network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation>Σύνδεση στο Shiacoin δίκτυο μέσω διαμεσολαβητή SOCKS4 (π.χ. για σύνδεση μέσω Tor)</translation>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation>&Σύνδεση μέσω διαμεσολαβητή SOCKS</translation>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation>&IP διαμεσολαβητή:</translation>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation>Διεύθυνση IP του διαμεσολαβητή (π.χ. 127.0.0.1)</translation>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation>&Θύρα:</translation>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation>Θύρα διαμεσολαβητή</translation>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation>SOCKS &Έκδοση:</translation>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation>SOCKS εκδοση του διαμεσολαβητη (e.g. 5)</translation>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation>&Παράθυρο</translation>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation>Εμφάνιση μόνο εικονιδίου στην περιοχή ειδοποιήσεων κατά την ελαχιστοποίηση</translation>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>&Ελαχιστοποίηση στην περιοχή ειδοποιήσεων αντί της γραμμής εργασιών</translation>
</message>
<message>
<location line="+7"/>
<source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source>
<translation>Ελαχιστοποίηση αντί για έξοδο κατά το κλείσιμο του παραθύρου</translation>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation>Ε&λαχιστοποίηση κατά το κλείσιμο</translation>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation>%Απεικόνιση</translation>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation>Γλώσσα περιβάλλοντος εργασίας: </translation>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting Shiacoin.</source>
<translation>Εδώ μπορεί να ρυθμιστεί η γλώσσα διεπαφής χρήστη. Αυτή η ρύθμιση θα ισχύσει μετά την επανεκκίνηση του Shiacoin.</translation>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation>&Μονάδα μέτρησης:</translation>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation>Διαλέξτε την προεπιλεγμένη υποδιαίρεση που θα εμφανίζεται όταν στέλνετε νομίσματα.</translation>
</message>
<message>
<location line="+9"/>
<source>Whether to show Shiacoin addresses in the transaction list or not.</source>
<translation>Επιλέξτε αν θέλετε να εμφανίζονται οι διευθύνσεις Shiacoin στη λίστα συναλλαγών.</translation>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation>Εμφάνιση διευθύνσεων στη λίστα συναλλαγών</translation>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation>&ΟΚ</translation>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation>&Ακύρωση</translation>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation>&Εφαρμογή</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+53"/>
<source>default</source>
<translation>προεπιλογή</translation>
</message>
<message>
<location line="+130"/>
<source>Confirm options reset</source>
<translation>Επιβεβαιώση των επιλογων επαναφοράς </translation>
</message>
<message>
<location line="+1"/>
<source>Some settings may require a client restart to take effect.</source>
<translation>Για ορισμένες ρυθμίσεις πρεπει η επανεκκίνηση να τεθεί σε ισχύ.</translation>
</message>
<message>
<location line="+0"/>
<source>Do you want to proceed?</source>
<translation>Θέλετε να προχωρήσετε;</translation>
</message>
<message>
<location line="+42"/>
<location line="+9"/>
<source>Warning</source>
<translation>Προειδοποίηση</translation>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting Shiacoin.</source>
<translation>Αυτή η ρύθμιση θα ισχύσει μετά την επανεκκίνηση του Shiacoin.</translation>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation>Δεν είναι έγκυρη η διεύθυνση διαμεσολαβητή</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation>Φόρμα</translation>
</message>
<message>
<location line="+50"/>
<location line="+166"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the Shiacoin network after a connection is established, but this process has not completed yet.</source>
<translation>Οι πληροφορίες που εμφανίζονται μπορεί να είναι ξεπερασμένες. Το πορτοφόλι σας συγχρονίζεται αυτόματα με το δίκτυο Shiacoin μετά από μια σύνδεση, αλλά αυτή η διαδικασία δεν έχει ακόμη ολοκληρωθεί. </translation>
</message>
<message>
<location line="-124"/>
<source>Balance:</source>
<translation>Υπόλοιπο</translation>
</message>
<message>
<location line="+29"/>
<source>Unconfirmed:</source>
<translation>Ανεπιβεβαίωτες</translation>
</message>
<message>
<location line="-78"/>
<source>Wallet</source>
<translation>Πορτοφόλι</translation>
</message>
<message>
<location line="+107"/>
<source>Immature:</source>
<translation>Ανώριμος</translation>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation>Εξορυγμενο υπόλοιπο που δεν έχει ακόμα ωριμάσει </translation>
</message>
<message>
<location line="+46"/>
<source><b>Recent transactions</b></source>
<translation><b>Πρόσφατες συναλλαγές</b></translation>
</message>
<message>
<location line="-101"/>
<source>Your current balance</source>
<translation>Το τρέχον υπόλοιπο</translation>
</message>
<message>
<location line="+29"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation>Το άθροισμα των συναλλαγών που δεν έχουν ακόμα επιβεβαιωθεί και δεν προσμετρώνται στο τρέχον υπόλοιπό σας</translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="+116"/>
<location line="+1"/>
<source>out of sync</source>
<translation>εκτός συγχρονισμού</translation>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<location filename="../paymentserver.cpp" line="+107"/>
<source>Cannot start Shiacoin: click-to-pay handler</source>
<translation>Δεν είναι δυνατή η εκκίνηση του Shiacoin: 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</translation>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation>Αίτηση πληρωμής</translation>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation>Ποσό:</translation>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation>Επιγραφή:</translation>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation>Μήνυμα:</translation>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation>&Αποθήκευση ως...</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation>Σφάλμα κατά την κωδικοποίηση του URI σε κώδικα QR</translation>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation>Το αναγραφόμενο ποσό δεν είναι έγκυρο, παρακαλούμε να το ελέγξετε.</translation>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation>Το αποτέλεσμα της διεύθυνσης είναι πολύ μεγάλο. Μειώστε το μέγεθος για το κείμενο της ετικέτας/ μηνύματος.</translation>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation>Αποθήκευση κώδικα QR</translation>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation>Εικόνες PNG (*.png)</translation>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation>Όνομα Πελάτη</translation>
</message>
<message>
<location line="+10"/>
<location line="+23"/>
<location line="+26"/>
<location line="+23"/>
<location line="+23"/>
<location line="+36"/>
<location line="+53"/>
<location line="+23"/>
<location line="+23"/>
<location filename="../rpcconsole.cpp" line="+339"/>
<source>N/A</source>
<translation>Μη διαθέσιμο</translation>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation>Έκδοση Πελάτη</translation>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation>&Πληροφορία</translation>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation>Χρησιμοποιηση της OpenSSL εκδοσης</translation>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation>Χρόνος εκκίνησης</translation>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation>Δίκτυο</translation>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation>Αριθμός συνδέσεων</translation>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation>Στο testnet</translation>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation>αλυσίδα εμποδισμού</translation>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation>Τρέχον αριθμός μπλοκ</translation>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation>Κατ' εκτίμηση συνολικά μπλοκς</translation>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation>Χρόνος τελευταίου μπλοκ</translation>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation>&Άνοιγμα</translation>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation>επιλογής γραμμής εντολών</translation>
</message>
<message>
<location line="+7"/>
<source>Show the Shiacoin-Qt help message to get a list with possible Shiacoin command-line options.</source>
<translation>Εμφανιση του Shiacoin-Qt μήνυματος βοήθειας για να πάρετε μια λίστα με τις πιθανές επιλογές Shiacoin γραμμής εντολών.</translation>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation>&Εμφάνιση</translation>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation>&Κονσόλα</translation>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation>Ημερομηνία κατασκευής</translation>
</message>
<message>
<location line="-104"/>
<source>Shiacoin - Debug window</source>
<translation>Shiacoin - Παράθυρο αποσφαλμάτωσης</translation>
</message>
<message>
<location line="+25"/>
<source>Shiacoin Core</source>
<translation>Shiacoin Core</translation>
</message>
<message>
<location line="+279"/>
<source>Debug log file</source>
<translation>Αρχείο καταγραφής εντοπισμού σφαλμάτων </translation>
</message>
<message>
<location line="+7"/>
<source>Open the Shiacoin debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation>Ανοίξτε το αρχείο καταγραφής εντοπισμού σφαλμάτων από τον τρέχοντα κατάλογο δεδομένων. Αυτό μπορεί να πάρει μερικά δευτερόλεπτα για τα μεγάλα αρχεία καταγραφής. </translation>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation>Καθαρισμός κονσόλας</translation>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-30"/>
<source>Welcome to the Shiacoin RPC console.</source>
<translation>Καλώς ήρθατε στην Shiacoin RPC κονσόλα.</translation>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation>Χρησιμοποιήστε το πάνω και κάτω βέλος για να περιηγηθείτε στο ιστορικο, και <b>Ctrl-L</b> για εκκαθαριση οθονης.</translation>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation>Γράψτε <b>βοήθεια</b> για μια επισκόπηση των διαθέσιμων εντολών</translation>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+14"/>
<location filename="../sendcoinsdialog.cpp" line="+124"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation>Αποστολή νομισμάτων</translation>
</message>
<message>
<location line="+50"/>
<source>Send to multiple recipients at once</source>
<translation>Αποστολή σε πολλούς αποδέκτες ταυτόχρονα</translation>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation>&Προσθήκη αποδέκτη</translation>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation>Διαγραφή όλων των πεδίων συναλλαγής</translation>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation>Καθαρισμός &Όλων</translation>
</message>
<message>
<location line="+22"/>
<source>Balance:</source>
<translation>Υπόλοιπο:</translation>
</message>
<message>
<location line="+10"/>
<source>123.456 BTC</source>
<translation>123,456 BTC</translation>
</message>
<message>
<location line="+31"/>
<source>Confirm the send action</source>
<translation>Επιβεβαίωση αποστολής</translation>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation>Αποστολη</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-59"/>
<source><b>%1</b> to %2 (%3)</source>
<translation><b>%1</b> σε %2 (%3)</translation>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation>Επιβεβαίωση αποστολής νομισμάτων</translation>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation>Είστε βέβαιοι για την αποστολή %1;</translation>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation>και</translation>
</message>
<message>
<location line="+23"/>
<source>The recipient address is not valid, please recheck.</source>
<translation>Η διεύθυνση του αποδέκτη δεν είναι σωστή. Παρακαλώ ελέγξτε ξανά.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation>Το ποσό πληρωμής πρέπει να είναι μεγαλύτερο από 0.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation>Το ποσό ξεπερνάει το διαθέσιμο υπόλοιπο</translation>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation>Το σύνολο υπερβαίνει το υπόλοιπό σας όταν συμπεριληφθεί και η αμοιβή %1</translation>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation>Βρέθηκε η ίδια διεύθυνση δύο φορές. Επιτρέπεται μία μόνο εγγραφή για κάθε διεύθυνση, σε κάθε διαδικασία αποστολής.</translation>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed!</source>
<translation>Σφάλμα: Η δημιουργία της συναλλαγής απέτυχε</translation>
</message>
<message>
<location line="+5"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation>Σφάλμα: Η συναλλαγή απερρίφθη. Αυτό ενδέχεται να συμβαίνει αν κάποια από τα νομίσματα έχουν ήδη ξοδευθεί, όπως αν χρησιμοποιήσατε αντίγραφο του wallet.dat και τα νομίσματα ξοδεύθηκαν εκεί.</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation>Φόρμα</translation>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation>&Ποσό:</translation>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation>Πληρωμή &σε:</translation>
</message>
<message>
<location line="+34"/>
<source>The address to send the payment to (e.g. sYKUBXhcTMCi8PNGsDEjFXtx5DpEftok3W)</source>
<translation>Διεύθυνση αποστολής της πληρωμής (e.g. sYKUBXhcTMCi8PNGsDEjFXtx5DpEftok3W)</translation>
</message>
<message>
<location line="+60"/>
<location filename="../sendcoinsentry.cpp" line="+26"/>
<source>Enter a label for this address to add it to your address book</source>
<translation>Εισάγετε μια επιγραφή για αυτή τη διεύθυνση ώστε να καταχωρηθεί στο βιβλίο διευθύνσεων</translation>
</message>
<message>
<location line="-78"/>
<source>&Label:</source>
<translation>&Επιγραφή</translation>
</message>
<message>
<location line="+28"/>
<source>Choose address from address book</source>
<translation>Επιλογή διεύθυνσης από το βιβλίο διευθύνσεων</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="+7"/>
<source>Paste address from clipboard</source>
<translation>Επικόλληση διεύθυνσης από το πρόχειρο</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+7"/>
<source>Remove this recipient</source>
<translation>Αφαίρεση αποδέκτη</translation>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a Shiacoin address (e.g. sYKUBXhcTMCi8PNGsDEjFXtx5DpEftok3W)</source>
<translation>Εισάγετε μια διεύθυνση Shiacoin (π.χ. sYKUBXhcTMCi8PNGsDEjFXtx5DpEftok3W)</translation>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation>Υπογραφές - Είσοδος / Επαλήθευση μήνυματος </translation>
</message>
<message>
<location line="+13"/>
<source>&Sign Message</source>
<translation>&Υπογραφή Μηνύματος</translation>
</message>
<message>
<location line="+6"/>
<source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation>Μπορείτε να υπογράφετε μηνύματα με τις διευθύνσεις σας, ώστε ν' αποδεικνύετε πως αυτές σας ανήκουν. Αποφεύγετε να υπογράφετε κάτι αόριστο καθώς ενδέχεται να εξαπατηθείτε. Υπογράφετε μόνο πλήρης δηλώσεις με τις οποίες συμφωνείτε.</translation>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. sYKUBXhcTMCi8PNGsDEjFXtx5DpEftok3W)</source>
<translation>Εισάγετε μια διεύθυνση Shiacoin (π.χ. sYKUBXhcTMCi8PNGsDEjFXtx5DpEftok3W)</translation>
</message>
<message>
<location line="+10"/>
<location line="+213"/>
<source>Choose an address from the address book</source>
<translation>Επιλογή διεύθυνσης από το βιβλίο διευθύνσεων</translation>
</message>
<message>
<location line="-203"/>
<location line="+213"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="-203"/>
<source>Paste address from clipboard</source>
<translation>Επικόλληση διεύθυνσης από το βιβλίο διευθύνσεων</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+12"/>
<source>Enter the message you want to sign here</source>
<translation>Εισάγετε εδώ το μήνυμα που θέλετε να υπογράψετε</translation>
</message>
<message>
<location line="+7"/>
<source>Signature</source>
<translation>Υπογραφή</translation>
</message>
<message>
<location line="+27"/>
<source>Copy the current signature to the system clipboard</source>
<translation>Αντέγραφη της επιλεγμενης διεύθυνσης στο πρόχειρο του συστηματος</translation>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this Shiacoin address</source>
<translation>Υπογράψτε ένα μήνυμα για ν' αποδείξετε πως σας ανήκει μια συγκεκριμένη διεύθυνση Shiacoin</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>Υπογραφη μήνυματος</translation>
</message>
<message>
<location line="+14"/>
<source>Reset all sign message fields</source>
<translation>Επαναφορά όλων των πεδίων μήνυματος</translation>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation>Καθαρισμός &Όλων</translation>
</message>
<message>
<location line="-87"/>
<source>&Verify Message</source>
<translation>&Επιβεβαίωση μηνύματος</translation>
</message>
<message>
<location line="+6"/>
<source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source>
<translation>Πληκτρολογήστε την υπογραφή διεύθυνσης, μήνυμα (βεβαιωθείτε ότι έχετε αντιγράψει τις αλλαγές γραμμής, κενά, tabs, κ.λπ. ακριβώς) και την υπογραφή παρακάτω, για να ελέγξει το μήνυμα. Να είστε προσεκτικοί για να μην διαβάσετε περισσότερα στην υπογραφή ό, τι είναι στην υπογραφή ίδιο το μήνυμα , για να μην εξαπατηθούν από έναν άνθρωπο -in - the-middle επίθεση.</translation>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. sYKUBXhcTMCi8PNGsDEjFXtx5DpEftok3W)</source>
<translation>Εισάγετε μια διεύθυνση Shiacoin (π.χ. sYKUBXhcTMCi8PNGsDEjFXtx5DpEftok3W)</translation>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified Shiacoin address</source>
<translation>Υπογράψτε ένα μήνυμα για ν' αποδείξετε πως υπογραφθηκε απο μια συγκεκριμένη διεύθυνση Shiacoin</translation>
</message>
<message>
<location line="+3"/>
<source>Verify &Message</source>
<translation>Επιβεβαίωση μηνύματος</translation>
</message>
<message>
<location line="+14"/>
<source>Reset all verify message fields</source>
<translation>Επαναφορά όλων επαλήθευμενων πεδίων μήνυματος </translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a Shiacoin address (e.g. sYKUBXhcTMCi8PNGsDEjFXtx5DpEftok3W)</source>
<translation>Εισάγετε μια διεύθυνση Shiacoin (π.χ. sYKUBXhcTMCi8PNGsDEjFXtx5DpEftok3W)</translation>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation>Κάντε κλικ στο "Υπογραφή Μηνύματος" για να λάβετε την υπογραφή</translation>
</message>
<message>
<location line="+3"/>
<source>Enter Shiacoin signature</source>
<translation>Εισαγωγή υπογραφής Shiacoin</translation>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation>Η διεύθυνση που εισήχθη είναι λάθος.</translation>
</message>
<message>
<location line="-81"/>
<location line="+8"/>
<location line="+73"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation>Παρακαλούμε ελέγξτε την διεύθυνση και δοκιμάστε ξανά.</translation>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation>Η διεύθυνση που έχει εισαχθεί δεν αναφέρεται σε ένα πλήκτρο.</translation>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation>το ξεκλείδωμα του πορτοφολιού απέτυχε</translation>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation>Το προσωπικό κλειδί εισαγμενης διευθυνσης δεν είναι διαθέσιμο.</translation>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation>Η υπογραφή του μηνύματος απέτυχε.</translation>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation>Μήνυμα υπεγράφη.</translation>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation>Η υπογραφή δεν μπόρεσε να αποκρυπτογραφηθεί.</translation>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation>Παρακαλούμε ελέγξτε την υπογραφή και δοκιμάστε ξανά.</translation>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation>Η υπογραφή δεν ταιριάζει με το μήνυμα. </translation>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation>Η επιβεβαίωση του μηνύματος απέτυχε</translation>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation>Μήνυμα επιβεβαιώθηκε.</translation>
</message>
</context>
<context>
<name>SplashScreen</name>
<message>
<location filename="../splashscreen.cpp" line="+22"/>
<source>The Shiacoin developers</source>
<translation>Οι Shiacoin προγραμματιστές </translation>
</message>
<message>
<location line="+1"/>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+20"/>
<source>Open until %1</source>
<translation>Ανοιχτό μέχρι %1</translation>
</message>
<message>
<location line="+6"/>
<source>%1/offline</source>
<translation>%1/χωρίς σύνδεση;</translation>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1/χωρίς επιβεβαίωση</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>%1 επιβεβαιώσεις</translation>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation>Κατάσταση</translation>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation><numerusform>, έχει μεταδοθεί μέσω %n κόμβων</numerusform><numerusform>, έχει μεταδοθεί μέσω %n κόμβων</numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>Ημερομηνία</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation>Πηγή</translation>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation>Δημιουργία </translation>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation>Από</translation>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation>Προς</translation>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation> δική σας διεύθυνση </translation>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation>eπιγραφή</translation>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation>Πίστωση </translation>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation><numerusform>ωρίμανση σε %n επιπλέον μπλοκ</numerusform><numerusform>ωρίμανση σε %n επιπλέον μπλοκ</numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation>μη αποδεκτό</translation>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation>Debit</translation>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation>Τέλος συναλλαγής </translation>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation>Καθαρό ποσό</translation>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation>Μήνυμα</translation>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation>Σχόλιο:</translation>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation>ID Συναλλαγής:</translation>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation>Πρέπει να περιμένετε 120 μπλοκ πριν μπορέσετε να χρησιμοποιήσετε τα νομίσματα που έχετε δημιουργήσει. Το μπλοκ που δημιουργήσατε μεταδόθηκε στο δίκτυο για να συμπεριληφθεί στην αλυσίδα των μπλοκ. Αν δεν μπει σε αυτή θα μετατραπεί σε "μη αποδεκτό" και δε θα μπορεί να καταναλωθεί. Αυτό συμβαίνει σπάνια όταν κάποιος άλλος κόμβος δημιουργήσει ένα μπλοκ λίγα δευτερόλεπτα πριν από εσάς.</translation>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation>Πληροφορίες αποσφαλμάτωσης</translation>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation>Συναλλαγή</translation>
</message>
<message>
<location line="+3"/>
<source>Inputs</source>
<translation>εισροές </translation>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation>Ποσό</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation>αληθής</translation>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation>αναληθής </translation>
</message>
<message>
<location line="-209"/>
<source>, has not been successfully broadcast yet</source>
<translation>, δεν έχει ακόμα μεταδοθεί μ' επιτυχία</translation>
</message>
<message numerus="yes">
<location line="-35"/>
<source>Open for %n more block(s)</source>
<translation><numerusform>Ανοιχτό για %n μπλοκ</numerusform><numerusform>Ανοιχτό για %n μπλοκ</numerusform></translation>
</message>
<message>
<location line="+70"/>
<source>unknown</source>
<translation>άγνωστο</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>Λεπτομέρειες συναλλαγής</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>Αυτό το παράθυρο δείχνει μια λεπτομερή περιγραφή της συναλλαγής</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+225"/>
<source>Date</source>
<translation>Ημερομηνία</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>Τύπος</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Διεύθυνση</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>Ποσό</translation>
</message>
<message numerus="yes">
<location line="+57"/>
<source>Open for %n more block(s)</source>
<translation><numerusform>Ανοιχτό για %n μπλοκ</numerusform><numerusform>Ανοιχτό για %n μπλοκ</numerusform></translation>
</message>
<message>
<location line="+3"/>
<source>Open until %1</source>
<translation>Ανοιχτό μέχρι %1</translation>
</message>
<message>
<location line="+3"/>
<source>Offline (%1 confirmations)</source>
<translation>Χωρίς σύνδεση (%1 επικυρώσεις)</translation>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed (%1 of %2 confirmations)</source>
<translation>Χωρίς επιβεβαίωση (%1 από %2 επικυρώσεις)</translation>
</message>
<message>
<location line="+3"/>
<source>Confirmed (%1 confirmations)</source>
<translation>Επικυρωμένη (%1 επικυρώσεις)</translation>
</message>
<message numerus="yes">
<location line="+8"/>
<source>Mined balance will be available when it matures in %n more block(s)</source>
<translation><numerusform>Το υπόλοιπο από την εξόρυξη θα είναι διαθέσιμο μετά από %n μπλοκ</numerusform><numerusform>Το υπόλοιπο από την εξόρυξη θα είναι διαθέσιμο μετά από %n μπλοκ</numerusform></translation>
</message>
<message>
<location line="+5"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>Αυτό το μπλοκ δεν έχει παραληφθεί από κανέναν άλλο κόμβο και κατά πάσα πιθανότητα θα απορριφθεί!</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>Δημιουργήθηκε αλλά απορρίφθηκε</translation>
</message>
<message>
<location line="+43"/>
<source>Received with</source>
<translation>Παραλαβή με</translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation>Ελήφθη από</translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>Αποστολή προς</translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation>Πληρωμή προς εσάς</translation>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation>Εξόρυξη</translation>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation>(δ/α)</translation>
</message>
<message>
<location line="+199"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>Κατάσταση συναλλαγής. Πηγαίνετε το ποντίκι πάνω από αυτό το πεδίο για να δείτε τον αριθμό των επικυρώσεων</translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>Ημερομηνία κι ώρα λήψης της συναλλαγής.</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>Είδος συναλλαγής.</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>Διεύθυνση αποστολής της συναλλαγής.</translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>Ποσό που αφαιρέθηκε ή προστέθηκε στο υπόλοιπο.</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+52"/>
<location line="+16"/>
<source>All</source>
<translation>Όλα</translation>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation>Σήμερα</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation>Αυτή την εβδομάδα</translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation>Αυτόν τον μήνα</translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation>Τον προηγούμενο μήνα</translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation>Αυτό το έτος</translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation>Έκταση...</translation>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation>Ελήφθη με</translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>Απεστάλη προς</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>Προς εσάς</translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation>Εξόρυξη</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation>Άλλο</translation>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation>Αναζήτηση με βάση τη διεύθυνση ή την επιγραφή</translation>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation>Ελάχιστο ποσό</translation>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation>Αντιγραφή διεύθυνσης</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Αντιγραφή επιγραφής</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Αντιγραφή ποσού</translation>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation>Αντιγραφη του ID Συναλλαγής</translation>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation>Επεξεργασία επιγραφής</translation>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation>Εμφάνιση λεπτομερειών συναλλαγής</translation>
</message>
<message>
<location line="+139"/>
<source>Export Transaction Data</source>
<translation>Εξαγωγή Στοιχείων Συναλλαγών</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Αρχείο οριοθετημένο με κόμματα (*.csv)</translation>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation>Επικυρωμένες</translation>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>Ημερομηνία</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>Τύπος</translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>Επιγραφή</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>Διεύθυνση</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation>Ποσό</translation>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation>ID</translation>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation>Σφάλμα εξαγωγής</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Αδυναμία εγγραφής στο αρχείο %1.</translation>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation>Έκταση:</translation>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation>έως</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+193"/>
<source>Send Coins</source>
<translation>Αποστολή νομισμάτων</translation>
</message>
</context>
<context>
<name>WalletView</name>
<message>
<location filename="../walletview.cpp" line="+42"/>
<source>&Export</source>
<translation>&Εξαγωγή</translation>
</message>
<message>
<location line="+1"/>
<source>Export the data in the current tab to a file</source>
<translation>Εξαγωγή δεδομένων καρτέλας σε αρχείο</translation>
</message>
<message>
<location line="+193"/>
<source>Backup Wallet</source>
<translation>Αντίγραφο ασφαλείας του πορτοφολιού</translation>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation>Αρχεία δεδομένων πορτοφολιού (*.dat)</translation>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation>Αποτυχία κατά τη δημιουργία αντιγράφου</translation>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation>Παρουσιάστηκε σφάλμα κατά την αποθήκευση των δεδομένων πορτοφολιού στη νέα τοποθεσία.</translation>
</message>
<message>
<location line="+4"/>
<source>Backup Successful</source>
<translation>Η δημιουργια αντιγραφου ασφαλειας πετυχε</translation>
</message>
<message>
<location line="+0"/>
<source>The wallet data was successfully saved to the new location.</source>
<translation>Τα δεδομένα πορτοφόλιου αποθηκεύτηκαν με επιτυχία στη νέα θέση. </translation>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+94"/>
<source>Shiacoin version</source>
<translation>Έκδοση Shiacoin</translation>
</message>
<message>
<location line="+102"/>
<source>Usage:</source>
<translation>Χρήση:</translation>
</message>
<message>
<location line="-29"/>
<source>Send command to -server or fastcoind</source>
<translation>Αποστολή εντολής στον εξυπηρετητή ή στο fastcoind</translation>
</message>
<message>
<location line="-23"/>
<source>List commands</source>
<translation>Λίστα εντολών</translation>
</message>
<message>
<location line="-12"/>
<source>Get help for a command</source>
<translation>Επεξήγηση εντολής</translation>
</message>
<message>
<location line="+24"/>
<source>Options:</source>
<translation>Επιλογές:</translation>
</message>
<message>
<location line="+24"/>
<source>Specify configuration file (default: Shiacoin.conf)</source>
<translation>Ορίστε αρχείο ρυθμίσεων (προεπιλογή: Shiacoin.conf)</translation>
</message>
<message>
<location line="+3"/>
<source>Specify pid file (default: fastcoind.pid)</source>
<translation>Ορίστε αρχείο pid (προεπιλογή: fastcoind.pid)</translation>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation>Ορισμός φακέλου δεδομένων</translation>
</message>
<message>
<location line="-9"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation>Όρισε το μέγεθος της βάσης προσωρινής αποθήκευσης σε megabytes(προεπιλογή:25)</translation>
</message>
<message>
<location line="-28"/>
<source>Listen for connections on <port> (default: 9333 or testnet: 19333)</source>
<translation>Εισερχόμενες συνδέσεις στη θύρα <port> (προεπιλογή: 9333 ή στο testnet: 19333)</translation>
</message>
<message>
<location line="+5"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>Μέγιστες αριθμός συνδέσεων με τους peers <n> (προεπιλογή: 125)</translation>
</message>
<message>
<location line="-48"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation>Σύνδεση σε έναν κόμβο για την ανάκτηση διευθύνσεων από ομοτίμους, και αποσυνδέσh</translation>
</message>
<message>
<location line="+82"/>
<source>Specify your own public address</source>
<translation>Διευκρινίστε τη δικιά σας δημόσια διεύθυνση.</translation>
</message>
<message>
<location line="+3"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation>Όριο αποσύνδεσης προβληματικών peers (προεπιλογή: 100)</translation>
</message>
<message>
<location line="-134"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation>Δευτερόλεπτα πριν επιτραπεί ξανά η σύνδεση των προβληματικών peers (προεπιλογή: 86400)</translation>
</message>
<message>
<location line="-29"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation>Ένα σφάλμα συνέβη καθώς προετοιμαζόταν η πόρτα RPC %u για αναμονή IPv4: %s</translation>
</message>
<message>
<location line="+27"/>
<source>Listen for JSON-RPC connections on <port> (default: 9332 or testnet: 19332)</source>
<translation>Εισερχόμενες συνδέσεις JSON-RPC στη θύρα <port> (προεπιλογή: 9332 or testnet: 19332)</translation>
</message>
<message>
<location line="+37"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>Αποδοχή εντολών κονσόλας και JSON-RPC</translation>
</message>
<message>
<location line="+76"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>Εκτέλεση στο παρασκήνιο κι αποδοχή εντολών</translation>
</message>
<message>
<location line="+37"/>
<source>Use the test network</source>
<translation>Χρήση του δοκιμαστικού δικτύου</translation>
</message>
<message>
<location line="-112"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation>Να δέχεσαι συνδέσεις από έξω(προεπιλογή:1)</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=fastcoinrpc
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 "Shiacoin Alert" admin@foo.com
</source>
<translation>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=fastcoinrpc
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 "Shiacoin 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>Ένα σφάλμα συνέβη καθώς προετοιμαζόταν η υποδοχη RPC %u για αναμονη του IPv6, επεσε πισω στο 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>Αποθηκευση σε συγκεκριμένη διεύθυνση. Χρησιμοποιήστε τα πλήκτρα [Host] : συμβολισμός θύρα για IPv6</translation>
</message>
<message>
<location line="+3"/>
<source>Cannot obtain a lock on data directory %s. Shiacoin is probably already running.</source>
<translation>Αδυναμία κλειδώματος του φακέλου δεδομένων %s. Πιθανώς το Shiacoin να είναι ήδη ενεργό.</translation>
</message>
<message>
<location line="+3"/>
<source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation>Σφάλμα: Η συναλλαγή απορρίφθηκε.
Αυτό ίσως οφείλεται στο ότι τα νομίσματά σας έχουν ήδη ξοδευτεί, π.χ. με την αντιγραφή του wallet.dat σε άλλο σύστημα και την χρήση τους εκεί, χωρίς η συναλλαγή να έχει καταγραφεί στο παρόν σύστημα.</translation>
</message>
<message>
<location line="+4"/>
<source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source>
<translation>Σφάλμα: Αυτή η συναλλαγή απαιτεί αμοιβή συναλλαγής τουλάχιστον %s λόγω του μεγέθους, πολυπλοκότητας ή της χρήσης πρόσφατης παραλαβής κεφαλαίου</translation>
</message>
<message>
<location line="+3"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation>Εκτέλεση της εντολής όταν το καλύτερο μπλοκ αλλάξει(%s στην εντολή αντικαθίσταται από το hash του μπλοκ)</translation>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation>Εκτέλεσε την εντολή όταν το καλύτερο μπλοκ αλλάξει(%s στην εντολή αντικαθίσταται από το hash του μπλοκ)</translation>
</message>
<message>
<location line="+11"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation>Ορίστε το μέγιστο μέγεθος των high-priority/low-fee συναλλαγων σε bytes (προεπιλογή: 27000)</translation>
</message>
<message>
<location line="+6"/>
<source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source>
<translation>Αυτό είναι ένα προ-τεστ κυκλοφορίας - χρησιμοποιήστε το με δική σας ευθύνη - δεν χρησιμοποιείτε για εξόρυξη ή για αλλες εφαρμογές</translation>
</message>
<message>
<location line="+5"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation>Προειδοποίηση: Η παράμετρος -paytxfee είναι πολύ υψηλή. Πρόκειται για την αμοιβή που θα πληρώνετε για κάθε συναλλαγή που θα στέλνετε.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source>
<translation>Προειδοποίηση: Εμφανίσεις συναλλαγων δεν μπορεί να είναι σωστες! Μπορεί να χρειαστεί να αναβαθμίσετε, ή άλλοι κόμβοι μπορεί να χρειαστεί να αναβαθμίστουν. </translation>
</message>
<message>
<location line="+3"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong Shiacoin will not work properly.</source>
<translation>Προειδοποίηση: Παρακαλώ βεβαιωθείτε πως η ημερομηνία κι ώρα του συστήματός σας είναι σωστές. Αν το ρολόι του υπολογιστή σας πάει λάθος, ενδέχεται να μη λειτουργεί σωστά το Shiacoin.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation>Προειδοποίηση : Σφάλμα wallet.dat κατα την ανάγνωση ! Όλα τα κλειδιά αναγνωρισθηκαν σωστά, αλλά τα δεδομένα των συναλλαγών ή καταχωρήσεις στο βιβλίο διευθύνσεων μπορεί να είναι ελλιπείς ή λανθασμένα. </translation>
</message>
<message>
<location line="+3"/>
<source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source>
<translation>Προειδοποίηση : το αρχειο wallet.dat ειναι διεφθαρμένο, τα δεδομένα σώζονται ! Original wallet.dat αποθηκεύονται ως πορτοφόλι { timestamp } bak στο % s ? . . Αν το υπόλοιπο του ή τις συναλλαγές σας, είναι λάθος θα πρέπει να επαναφέρετε από ένα αντίγραφο ασφαλείας</translation>
</message>
<message>
<location line="+14"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation>Προσπάθεια για ανακτησει ιδιωτικων κλειδιων από ενα διεφθαρμένο αρχειο wallet.dat </translation>
</message>
<message>
<location line="+2"/>
<source>Block creation options:</source>
<translation>Αποκλεισμός επιλογων δημιουργίας: </translation>
</message>
<message>
<location line="+5"/>
<source>Connect only to the specified node(s)</source>
<translation>Σύνδεση μόνο με ορισμένους κόμβους</translation>
</message>
<message>
<location line="+3"/>
<source>Corrupted block database detected</source>
<translation>Εντοπισθηκε διεφθαρμενη βαση δεδομενων των μπλοκ</translation>
</message>
<message>
<location line="+1"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation>Ανακαλύψτε την δικη σας IP διεύθυνση (προεπιλογή: 1 όταν ακούει και δεν - externalip) </translation>
</message>
<message>
<location line="+1"/>
<source>Do you want to rebuild the block database now?</source>
<translation>Θελετε να δημιουργηθει τωρα η βαση δεδομενων του μπλοκ? </translation>
</message>
<message>
<location line="+2"/>
<source>Error initializing block database</source>
<translation>Σφάλμα κατά την ενεργοποίηση της βάσης δεδομένων μπλοκ</translation>
</message>
<message>
<location line="+1"/>
<source>Error initializing wallet database environment %s!</source>
<translation>Σφάλμα κατά την ενεργοποίηση της βάσης δεδομένων πορτοφόλιου %s!</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading block database</source>
<translation>Σφάλμα φορτωσης της βασης δεδομενων των μπλοκ</translation>
</message>
<message>
<location line="+4"/>
<source>Error opening block database</source>
<translation>Σφάλμα φορτωσης της βασης δεδομενων των μπλοκ</translation>
</message>
<message>
<location line="+2"/>
<source>Error: Disk space is low!</source>
<translation>Προειδοποίηση: Χαμηλός χώρος στο δίσκο </translation>
</message>
<message>
<location line="+1"/>
<source>Error: Wallet locked, unable to create transaction!</source>
<translation>Σφάλμα: το πορτοφόλι είναι κλειδωμένο, δεν μπορεί να δημιουργηθεί συναλλαγή</translation>
</message>
<message>
<location line="+1"/>
<source>Error: system error: </source>
<translation>Λάθος: λάθος συστήματος:</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation>ταλαιπωρηθειτε για να ακούσετε σε οποιαδήποτε θύρα. Χρήση - ακούστε = 0 , αν θέλετε αυτό.</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to read block info</source>
<translation>Αποτυχία αναγνωσης των block πληροφοριων</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to read block</source>
<translation>Η αναγνωση του μπλοκ απετυχε</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to sync block index</source>
<translation>Ο συγχρονισμος του μπλοκ ευρετηριου απετυχε</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write block index</source>
<translation>Η δημιουργια του μπλοκ ευρετηριου απετυχε</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write block info</source>
<translation>Η δημιουργια των μπλοκ πληροφοριων απετυχε</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write block</source>
<translation>Η δημιουργια του μπλοκ απετυχε</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write file info</source>
<translation>Αδυναμία εγγραφής πληροφοριων αρχειου</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write to coin database</source>
<translation>Αποτυχία εγγραφής στη βάση δεδομένων νομίσματος</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write transaction index</source>
<translation>Αποτυχία εγγραφής δείκτη συναλλαγών </translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write undo data</source>
<translation>Αποτυχία εγγραφής αναίρεσης δεδομένων </translation>
</message>
<message>
<location line="+2"/>
<source>Find peers using DNS lookup (default: 1 unless -connect)</source>
<translation>Βρες ομότιμους υπολογιστές χρησιμοποιώντας αναζήτηση DNS(προεπιλογή:1)</translation>
</message>
<message>
<location line="+1"/>
<source>Generate coins (default: 0)</source>
<translation>Δημιουργία νομισμάτων (προκαθορισμος: 0)</translation>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 288, 0 = all)</source>
<translation>Πόσα μπλοκ να ελέγχθουν κατά την εκκίνηση (προεπιλογή:288,0=όλα)</translation>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-4, default: 3)</source>
<translation>Πόσο εξονυχιστική να είναι η επιβεβαίωση του μπλοκ(0-4, προεπιλογή:3)</translation>
</message>
<message>
<location line="+19"/>
<source>Not enough file descriptors available.</source>
<translation>Δεν ειναι αρκετες περιγραφες αρχείων διαθέσιμες.</translation>
</message>
<message>
<location line="+8"/>
<source>Rebuild block chain index from current blk000??.dat files</source>
<translation>Εισαγωγή μπλοκ από εξωτερικό αρχείο blk000?.dat</translation>
</message>
<message>
<location line="+16"/>
<source>Set the number of threads to service RPC calls (default: 4)</source>
<translation>Ορίσμος του αριθμόυ θεματων στην υπηρεσία κλήσεων RPC (προεπιλογή: 4) </translation>
</message>
<message>
<location line="+26"/>
<source>Verifying blocks...</source>
<translation>Επαλήθευση των μπλοκ... </translation>
</message>
<message>
<location line="+1"/>
<source>Verifying wallet...</source>
<translation>Επαλήθευση πορτοφολιου... </translation>
</message>
<message>
<location line="-69"/>
<source>Imports blocks from external blk000??.dat file</source>
<translation>Εισαγωγή μπλοκ από εξωτερικό αρχείο blk000?.dat</translation>
</message>
<message>
<location line="-76"/>
<source>Set the number of script verification threads (up to 16, 0 = auto, <0 = leave that many cores free, default: 0)</source>
<translation>Ορίσμος του αριθμό των νημάτων ελέγχου σεναρίου (μέχρι 16, 0 = auto, <0 = αφήνουν τους πολλους πυρήνες δωρεάν, default: 0)</translation>
</message>
<message>
<location line="+77"/>
<source>Information</source>
<translation>Πληροφορία</translation>
</message>
<message>
<location line="+3"/>
<source>Invalid -tor address: '%s'</source>
<translation>Δεν είναι έγκυρη η διεύθυνση διαμεσολαβητή: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -minrelaytxfee=<amount>: '%s'</source>
<translation>Μη έγκυρο ποσό για την παράμετρο -paytxfee=<amount>: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -mintxfee=<amount>: '%s'</source>
<translation>Μη έγκυρο ποσό για την παράμετρο -paytxfee=<amount>: '%s'</translation>
</message>
<message>
<location line="+8"/>
<source>Maintain a full transaction index (default: 0)</source>
<translation>Διατηρήση ένος πλήρες ευρετήριου συναλλαγών (προεπιλογή: 0) </translation>
</message>
<message>
<location line="+2"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation>Μέγιστος buffer λήψης ανά σύνδεση, <n>*1000 bytes (προεπιλογή: 5000)</translation>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation>Μέγιστος buffer αποστολής ανά σύνδεση, <n>*1000 bytes (προεπιλογή: 1000)</translation>
</message>
<message>
<location line="+2"/>
<source>Only accept block chain matching built-in checkpoints (default: 1)</source>
<translation>Μονο αποδοχη αλυσίδας μπλοκ που ταιριάζει με τα ενσωματωμένα σημεία ελέγχου (προεπιλογή: 1) </translation>
</message>
<message>
<location line="+1"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation> Συνδέση μόνο σε κόμβους του δικτύου <net> (IPv4, IPv6 ή Tor) </translation>
</message>
<message>
<location line="+2"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation>Έξοδος επιπλέον πληροφοριών εντοπισμού σφαλμάτων</translation>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation>Έξοδος επιπλέον πληροφοριών εντοπισμού σφαλμάτων</translation>
</message>
<message>
<location line="+2"/>
<source>Prepend debug output with timestamp</source>
<translation>Χρονοσφραγίδα πληροφοριών εντοπισμού σφαλμάτων</translation>
</message>
<message>
<location line="+5"/>
<source>SSL options: (see the Shiacoin Wiki for SSL setup instructions)</source>
<translation>Ρυθμίσεις SSL: (ανατρέξτε στο Shiacoin Wiki για οδηγίες ρυθμίσεων SSL)</translation>
</message>
<message>
<location line="+1"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation>Επιλέξτε την έκδοση του διαμεσολαβητη για να χρησιμοποιήσετε (4-5 , προεπιλογή: 5)</translation>
</message>
<message>
<location line="+3"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>Αποστολή πληροφοριών εντοπισμού σφαλμάτων στην κονσόλα αντί του αρχείου debug.log</translation>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation>Αποστολή πληροφοριών εντοπισμού σφαλμάτων στον debugger</translation>
</message>
<message>
<location line="+5"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation>Ορίσμος του μέγιστου μέγεθος block σε bytes (προεπιλογή: 250000)</translation>
</message>
<message>
<location line="+1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation>Ορίστε το μέγιστο μέγεθος block σε bytes (προεπιλογή: 0)</translation>
</message>
<message>
<location line="+2"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation>Συρρίκνωση του αρχείο debug.log κατα την εκκίνηση του πελάτη (προεπιλογή: 1 όταν δεν-debug)</translation>
</message>
<message>
<location line="+1"/>
<source>Signing transaction failed</source>
<translation>Η υπογραφή συναλλαγής απέτυχε </translation>
</message>
<message>
<location line="+2"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation>Ορισμός λήξης χρονικού ορίου σε χιλιοστά του δευτερολέπτου(προεπιλογή:5000)</translation>
</message>
<message>
<location line="+4"/>
<source>System error: </source>
<translation>Λάθος Συστήματος:</translation>
</message>
<message>
<location line="+4"/>
<source>Transaction amount too small</source>
<translation>Το ποσό της συναλλαγής είναι πολύ μικρο </translation>
</message>
<message>
<location line="+1"/>
<source>Transaction amounts must be positive</source>
<translation>Τα ποσά των συναλλαγών πρέπει να είναι θετικα</translation>
</message>
<message>
<location line="+1"/>
<source>Transaction too large</source>
<translation>Η συναλλαγή ειναι πολύ μεγάλη </translation>
</message>
<message>
<location line="+7"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation>Χρησιμοποίηση του UPnP για την χρήση της πόρτας αναμονής (προεπιλογή:0)</translation>
</message>
<message>
<location line="+1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation>Χρησιμοποίηση του UPnP για την χρήση της πόρτας αναμονής (προεπιλογή:1)</translation>
</message>
<message>
<location line="+1"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation>Χρήση διακομιστή μεσολάβησης για την επίτευξη των Tor κρυμμένων υπηρεσιων (προεπιλογή: ίδιο με το-proxy) </translation>
</message>
<message>
<location line="+2"/>
<source>Username for JSON-RPC connections</source>
<translation>Όνομα χρήστη για τις συνδέσεις JSON-RPC</translation>
</message>
<message>
<location line="+4"/>
<source>Warning</source>
<translation>Προειδοποίηση</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation>Προειδοποίηση: Αυτή η έκδοση είναι ξεπερασμένη, απαιτείται αναβάθμιση </translation>
</message>
<message>
<location line="+1"/>
<source>You need to rebuild the databases using -reindex to change -txindex</source>
<translation>Θα πρέπει να ξαναχτίστουν οι βάσεις δεδομένων που χρησιμοποιούντε-Αναδημιουργία αλλάγων-txindex </translation>
</message>
<message>
<location line="+1"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation>Το αρχειο wallet.dat ειναι διεφθαρμένο, η διάσωση απέτυχε</translation>
</message>
<message>
<location line="-50"/>
<source>Password for JSON-RPC connections</source>
<translation>Κωδικός για τις συνδέσεις JSON-RPC</translation>
</message>
<message>
<location line="-67"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>Αποδοχή συνδέσεων JSON-RPC από συγκεκριμένη διεύθυνση IP</translation>
</message>
<message>
<location line="+76"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>Αποστολή εντολών στον κόμβο <ip> (προεπιλογή: 127.0.0.1)</translation>
</message>
<message>
<location line="-120"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation>Εκτέλεσε την εντολή όταν το καλύτερο μπλοκ αλλάξει(%s στην εντολή αντικαθίσταται από το hash του μπλοκ)</translation>
</message>
<message>
<location line="+147"/>
<source>Upgrade wallet to latest format</source>
<translation>Αναβάθμισε το πορτοφόλι στην τελευταία έκδοση</translation>
</message>
<message>
<location line="-21"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>Όριο πλήθους κλειδιών pool <n> (προεπιλογή: 100)</translation>
</message>
<message>
<location line="-12"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>Επανέλεγχος της αλυσίδας μπλοκ για απούσες συναλλαγές</translation>
</message>
<message>
<location line="+35"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>Χρήση του OpenSSL (https) για συνδέσεις JSON-RPC</translation>
</message>
<message>
<location line="-26"/>
<source>Server certificate file (default: server.cert)</source>
<translation>Αρχείο πιστοποιητικού του διακομιστή (προεπιλογή: server.cert)</translation>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation>Προσωπικό κλειδί του διακομιστή (προεπιλογή: server.pem)</translation>
</message>
<message>
<location line="-151"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation>Αποδεκτά κρυπτογραφήματα (προεπιλογή: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation>
</message>
<message>
<location line="+165"/>
<source>This help message</source>
<translation>Αυτό το κείμενο βοήθειας</translation>
</message>
<message>
<location line="+6"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation>Αδύνατη η σύνδεση με τη θύρα %s αυτού του υπολογιστή (bind returned error %d, %s) </translation>
</message>
<message>
<location line="-91"/>
<source>Connect through socks proxy</source>
<translation>Σύνδεση μέσω διαμεσολαβητή socks</translation>
</message>
<message>
<location line="-10"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation>Να επιτρέπονται οι έλεγχοι DNS για προσθήκη και σύνδεση κόμβων</translation>
</message>
<message>
<location line="+55"/>
<source>Loading addresses...</source>
<translation>Φόρτωση διευθύνσεων...</translation>
</message>
<message>
<location line="-35"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>Σφάλμα φόρτωσης wallet.dat: Κατεστραμμένο Πορτοφόλι</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat: Wallet requires newer version of Shiacoin</source>
<translation>Σφάλμα φόρτωσης wallet.dat: Το Πορτοφόλι απαιτεί μια νεότερη έκδοση του Shiacoin</translation>
</message>
<message>
<location line="+93"/>
<source>Wallet needed to be rewritten: restart Shiacoin to complete</source>
<translation>Απαιτείται η επανεγγραφή του Πορτοφολιού, η οποία θα ολοκληρωθεί στην επανεκκίνηση του Shiacoin</translation>
</message>
<message>
<location line="-95"/>
<source>Error loading wallet.dat</source>
<translation>Σφάλμα φόρτωσης αρχείου wallet.dat</translation>
</message>
<message>
<location line="+28"/>
<source>Invalid -proxy address: '%s'</source>
<translation>Δεν είναι έγκυρη η διεύθυνση διαμεσολαβητή: '%s'</translation>
</message>
<message>
<location line="+56"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation>Άγνωστo δίκτυο ορίζεται σε onlynet: '%s'</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation>Άγνωστo δίκτυο ορίζεται: %i</translation>
</message>
<message>
<location line="-96"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation>Δεν μπορώ να γράψω την προεπιλεγμένη διεύθυνση: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation>Δεν μπορώ να γράψω την προεπιλεγμένη διεύθυνση: '%s'</translation>
</message>
<message>
<location line="+44"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation>Μη έγκυρο ποσό για την παράμετρο -paytxfee=<amount>: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount</source>
<translation>Λάθος ποσότητα</translation>
</message>
<message>
<location line="-6"/>
<source>Insufficient funds</source>
<translation>Ανεπαρκές κεφάλαιο</translation>
</message>
<message>
<location line="+10"/>
<source>Loading block index...</source>
<translation>Φόρτωση ευρετηρίου μπλοκ...</translation>
</message>
<message>
<location line="-57"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>Προσέθεσε ένα κόμβο για σύνδεση και προσπάθησε να κρατήσεις την σύνδεση ανοιχτή</translation>
</message>
<message>
<location line="-25"/>
<source>Unable to bind to %s on this computer. Shiacoin is probably already running.</source>
<translation>Αδύνατη η σύνδεση με τη θύρα %s αυτού του υπολογιστή. Το Shiacoin είναι πιθανώς ήδη ενεργό.</translation>
</message>
<message>
<location line="+64"/>
<source>Fee per KB to add to transactions you send</source>
<translation>Αμοιβή ανά KB που θα προστίθεται στις συναλλαγές που στέλνεις</translation>
</message>
<message>
<location line="+19"/>
<source>Loading wallet...</source>
<translation>Φόρτωση πορτοφολιού...</translation>
</message>
<message>
<location line="-52"/>
<source>Cannot downgrade wallet</source>
<translation>Δεν μπορώ να υποβαθμίσω το πορτοφόλι</translation>
</message>
<message>
<location line="+3"/>
<source>Cannot write default address</source>
<translation>Δεν μπορώ να γράψω την προεπιλεγμένη διεύθυνση</translation>
</message>
<message>
<location line="+64"/>
<source>Rescanning...</source>
<translation>Ανίχνευση...</translation>
</message>
<message>
<location line="-57"/>
<source>Done loading</source>
<translation>Η φόρτωση ολοκληρώθηκε</translation>
</message>
<message>
<location line="+82"/>
<source>To use the %s option</source>
<translation>Χρήση της %s επιλογής</translation>
</message>
<message>
<location line="-74"/>
<source>Error</source>
<translation>Σφάλμα</translation>
</message>
<message>
<location line="-31"/>
<source>You must set rpcpassword=<password> in the configuration file:
%s
If the file does not exist, create it with owner-readable-only file permissions.</source>
<translation>Πρέπει να βάλεις ένα κωδικό στο αρχείο παραμέτρων: %s
Εάν το αρχείο δεν υπάρχει, δημιούργησε το με δικαιώματα μόνο για ανάγνωση από τον δημιουργό</translation>
</message>
</context>
</TS>
| mit |
eumes/ber-tlv-annotations | gulpfile.js | 1744 | var del = require('del');
var gulp = require('gulp');
var mocha = require('gulp-mocha');
var ts = require('gulp-typescript');
var merge = require('merge2');
gulp.task('typescript.clean', function () {
del.sync(['./release'], { force: true });
});
gulp.task('typescript.build', ['typescript.clean'], function() {
var tsProject = ts.createProject('tsconfig.json', { rootDir: './src' });
var tsResult = tsProject.src()
.pipe(ts(tsProject));
gulp.src(['./annotations/**/*']).pipe(gulp.dest('./release/annotations'));
return merge([
tsResult.dts.pipe(gulp.dest('./release/definitions')),
tsResult.js.pipe(gulp.dest('./release/js'))
]);
});
gulp.task('build', ['typescript.build']);
gulp.task('mocha.test', ['typescript.build'], function() {
return gulp.src('./release/**/*-Specs.js', { read: false })
.pipe(mocha({ reporter: 'spec' }));
});
gulp.task('test', ['mocha.test']);
gulp.task('test-standalone', function() {
return gulp.src('./release/**/*-Specs.js', { read: false })
.pipe(mocha({ reporter: 'spec' }));
});
/*
gulp.task('typescript:lint', function(){
return gulp.src([env.paths.source.main, env.paths.source.test])
.pipe(tslint())
.pipe(tslint.report('prose'));
});
gulp.task("typescript:documentation", function() {
return gulp
.src(env.paths.source.main)
.pipe(typedoc({
module: env.typescript.compiler.module,
out: env.paths.release.documentation,
name: "iso-7816",
target: env.typescript.compiler.target,
readme: "none",
includeDeclarations: env.typescript.compiler.declarations
}))
;
});
*/
//gulp.task('default', ['watch', 'build', 'test']);
| mit |
peterwilletts24/Monsoon-Python-Scripts | geopotential/temps_etc_on_p_levels_8km.py | 4343 | """
Find heights oftemperature etc. on pressure levels from models and save
Takes calculate pressure level heights from geopotential_interpolate_multiple.py
"""
import os,sys
import iris
import iris.coords as coords
import iris.unit as unit
#from tempfile import mkdtemp
import numpy as np
import os.path as path
import datetime
import time
import h5py
#from scipy.interpolate import interp1d
from scipy.interpolate import InterpolatedUnivariateSpline
def main():
#experiment_ids = ['djzny', 'djznq', 'djznw', 'djzns', 'dkbhu', 'dkjxq', 'dklyu', 'dkmbq', 'dklwu', 'dklzq' ]
experiment_ids = ['dklyu', 'dkmbq']
for experiment_id in experiment_ids:
print "======================================"
print 'Start of interpolate script for temp/specific humidity'
print experiment_id
sys.stdout.flush()
start_time = time.clock()
try:
p_levels = [1000, 950, 925, 850, 700, 500, 400, 300, 250, 200, 150, 100, 70, 50, 30, 20, 10]
expmin1 = experiment_id[:-1]
fname_heights = '/projects/cascade/pwille/moose_retrievals/%s/%s/15101.pp'% (expmin1, experiment_id)
fname_temp = '/projects/cascade/pwille/moose_retrievals/%s/%s/4.pp' % (expmin1, experiment_id)
fname_sp_hum= '/projects/cascade/pwille/moose_retrievals/%s/%s/10.pp' % (expmin1, experiment_id)
path_tempfile='/projects/cascade/pwille/temp/'
load_name_i='/408_pressure_levels_interp_pressure_%s' % experiment_id
save_name_temp='/temp_pressure_levels_interp_%s' % experiment_id
save_name_sp_hum='/sp_hum_pressure_levels_interp_%s' % experiment_id
temp_p_heights_file = path.join("%s%s" % (path_tempfile, save_name_temp))
sp_hum_p_heights_file = path.join("%s%s" % (path_tempfile, save_name_sp_hum))
p_heights_file = path.join("%s%s" % (path_tempfile, load_name_i))
hl = iris.load_cube(fname_heights)
temp_cube = iris.load_cube(fname_temp)
sp_hum_cube = iris.load_cube(fname_sp_hum)
no_of_times = temp_cube.coord('time').points.size
lat_len = temp_cube.coord('grid_latitude').points.size
lon_len = temp_cube.coord('grid_longitude').points.size
shape_alltime = (no_of_times,lat_len,lon_len, len(p_levels))
shape_1time = (lat_len,lon_len, len(p_levels))
print shape_alltime
te = np.empty((shape_1time), dtype=float)
sh = np.empty((shape_1time), dtype=float)
sys.stdout.flush()
heights = hl.slices(['model_level_number', 'grid_latitude', 'grid_longitude']).next().data
with h5py.File(p_heights_file, 'r') as i:
p_hsf = i['interps']
with h5py.File(temp_p_heights_file, 'w') as tf:
temps = tf.create_dataset('t_on_p', dtype='float32', shape=shape_alltime)
for t, time_cube in enumerate(temp_cube.slices(['model_level_number', 'grid_latitude', 'grid_longitude'])):
p_hs=p_hsf[t,:,:,:]
tc = time_cube.data
for f in range(lat_len):
for y in range(lon_len):
i_func_t = InterpolatedUnivariateSpline(heights[:,f,y], tc[:,f,y])
te[f,y,:] = i_func_t(p_hs[f,y,:])
temps[t,:,:,:] = te
with h5py.File(sp_hum_p_heights_file, 'w') as s:
sphums = s.create_dataset('sh_on_p', dtype='float32', shape=shape_alltime)
for t, time_cube in enumerate(sp_hum_cube.slices(['model_level_number', 'grid_latitude', 'grid_longitude'])):
p_hs=p_hsf[t,:,:,:]
sphc = time_cube.data
for f in range(lat_len):
for y in range(lon_len):
i_func_sh = InterpolatedUnivariateSpline(heights[:,f,y], sphc[:,f,y])
sh[f,y,:] = i_func_sh(p_hs[f,y,:])
sphums[t,:,:,:] = sh
end_time=time.clock()
print(('%s time elapsed: {0}' % experiment_id).format(end_time - start_time))
# End of try for experiment_id loop
except Exception,e:
print e
print sys.exc_traceback.tb_lineno
print 'Failed to run interpolate script for %s' % experiment_id
sys.stdout.flush()
#pass
if __name__ == '__main__':
main()
| mit |
gmunro/another-auth | another-auth/Interfaces/IAuthDb.cs | 378 | using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
namespace another_auth.Interfaces
{
public interface IAuthDb
{
void Save();
Task SaveAsync();
void Add<T>(T entity) where T : class;
IQueryable<T> Query<T>() where T : class;
bool ModelPresent<T>() where T : class;
}
} | mit |
yeojz/data-calendar | src/helpers/classNames.js | 950 | /*
* className
*
* Takes in an object or string option,
* passes it into `cx` and concats with
* optional additional classNames
*
* Depends on `cx` modules
*
* @param string|object className to modularize, or an object of key/values.
* In the object case, the values are conditions that
* determine if the className keys should be included.
* @param string|array className in string case or an Array of classNames
* @return string Renderable space-separated CSS className.
*/
import cx from './cx';
export default function(options, classNames){
var classNameArray = [];
if (options instanceof Object){
classNameArray.push(cx(options));
}
if (typeof classNames === 'string' &&
classNames.trim() !== ''){
classNameArray.push(classNames);
} else if (Array.isArray(classNames)){
classNameArray.concat(classNames);
}
return classNameArray.join(' ');
}
| mit |
leisureq/study | 28_ArrayBuffer/new-1.js | 226 | "use strict";
debugger;
let obj1 = new ArrayBuffer(20);
console.log(obj1.byteLength);
let obj2 = new ArrayBuffer();
console.log(obj2.byteLength);
let obj3 = new ArrayBuffer("12");
console.log(obj3.byteLength);
let dummy;
| mit |
musicglue/sidekiq-isochronal | lib/sidekiq-isochronal/version.rb | 67 | module Sidekiq
module Isochronal
VERSION = "0.0.1"
end
end
| mit |
jcondor/SpringORM | src/main/java/app/model/Socio.java | 1437 | package app.model;
import java.util.List;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.OneToOne;
@Entity
@Table(name = "socio")
public class Socio implements Serializable {
@Id
@GeneratedValue
@Column(name = "id")
private Long id;
@OneToOne(mappedBy = "socio", fetch = FetchType.LAZY)
@JoinColumn(name = "id_persona")
private Persona persona;
@OneToMany(mappedBy = "socio", fetch = FetchType.LAZY)
private List<SolicitudAlquiler> solicitudAlquiler;
public Socio() {}
public Socio(Long id) {
this.id = id;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Persona getPersona() {
return persona;
}
public void setPersona(Persona persona) {
this.persona = persona;
}
public List<SolicitudAlquiler> getSolicitudAlquiler() {
return solicitudAlquiler;
}
public void setSolicitudAlquiler(List<SolicitudAlquiler> solicitudAlquiler) {
this.solicitudAlquiler = solicitudAlquiler;
}
} | mit |
mike-robertson/doctor_finder | client/app/main/main.controller.js | 2034 | 'use strict';
angular.module('mrWebdesignApp')
.controller('MainCtrl', ['$timeout', '$http', 'GoogleMapApi'.ns(),
function ($timeout, $http, GoogleMapApi) {
var ctrl = this;
// In case there is a delay, display loading gif for map.
ctrl.loading = true;
// Set our map to San Antonio center coords, zoom 13.
ctrl.map = {
center: {latitude: 40.1451, longitude: -29.4167 },
zoom: 13,
bounds: {},
control: {}
};
ctrl.options = {scrollwheel: false};
ctrl.doctors = [];
// If this were an actual api call, we would use a get, so this is simulating getting the json in our local file.
$http.get('././assets/search.json')
.success(function(data, status, headers, config) {
// Turn off loading gif.
ctrl.loading = false;
// Set our doctors array to the data in the json.
ctrl.doctors = data.professionals;
// This is the latLong object which contains the current location's latitude and longitude.
ctrl.currentLocation = {
longitude: ctrl.doctors[0].locations[0].address.longitude,
latitude: ctrl.doctors[0].locations[0].address.latitude
};
// On the next $digest, we want to update the center to the first doctor's location.
$timeout(function() {
ctrl.map.control.refresh(ctrl.currentLocation);
});
console.log(ctrl.doctors);
})
.error(function(data, status, headers, config) {
alert('The data failed to load');
ctrl.loading = false;
});
GoogleMapApi.then(function() {
// Turn off the loading gif.
ctrl.loading = false;
});
// When this is called from ng-click on the doctor names, it will update the center of the map to their location.
ctrl.centerMap = function(lon, lat) {
ctrl.currentLocation = {
longitude: lon,
latitude: lat
};
$timeout(function() {
ctrl.map.control.refresh(ctrl.currentLocation);
});
};
}]);
| mit |
bitcoin-s/bitcoin-s | core/src/main/scala/org/bitcoins/core/gcs/FilterHeader.scala | 1394 | package org.bitcoins.core.gcs
import org.bitcoins.crypto.{
CryptoUtil,
DoubleSha256Digest,
DoubleSha256DigestBE
}
/** Bip 157 Block Filter Headers which commit to a chain of block filters,
* much in the same way that block headers commit to a block chain
* @see [[https://github.com/bitcoin/bips/blob/master/bip-0157.mediawiki#filter-headers]]
*/
case class FilterHeader(
filterHash: DoubleSha256Digest,
prevHeaderHash: DoubleSha256Digest) {
val hash: DoubleSha256Digest = {
CryptoUtil.doubleSHA256(filterHash.bytes ++ prevHeaderHash.bytes)
}
/** Given the next Block Filter, constructs the next Block Filter Header */
def nextHeader(nextFilter: GolombFilter): FilterHeader = {
FilterHeader(filterHash = nextFilter.hash, prevHeaderHash = this.hash)
}
/** Given the next Block Filter hash, constructs the next Block Filter Header */
def nextHeader(nextFilterHash: DoubleSha256Digest): FilterHeader = {
FilterHeader(filterHash = nextFilterHash, prevHeaderHash = this.hash)
}
override def toString: String = {
s"FilterHeader(hashBE=${hash.flip},filterHashBE=${filterHash.flip.hex},prevHeaderHashBE=${prevHeaderHash.flip.hex})"
}
}
object FilterHeader {
def apply(
filterHash: DoubleSha256DigestBE,
prevHeaderHash: DoubleSha256DigestBE): FilterHeader = {
new FilterHeader(filterHash.flip, prevHeaderHash.flip)
}
}
| mit |
skinny-framework/skinny-splash | src/test/scala/simple/SimpleExampleDispatcher.scala | 291 | package simple
import skinny.splash._
trait SimpleExampleDispatcher extends SprayDispatcher {
val controller = new SimpleExampleController
override def routes = Seq(
getRoute("ok")(req => SprayResponse(body = "ok")),
postRoute("echo")(implicit req => controller.echo)
)
}
| mit |
xinge/gcm_helper | lib/gcm_helper/result.rb | 548 | module GcmHelper
class Result
attr_accessor :message_id, :canonical_registration_id, :error_code
def initialize(args)
[:message_id, :canonical_registration_id, :error_code].each do |attr|
instance_variable_set("@#{attr}", args[attr]) if (args.key?(attr))
end
end
def inspect
[:message_id, :canonical_registration_id, :error_code].inject({ }) do |h, attr|
h[attr] = instance_variable_get("@#{attr}")
h
end
end
def to_s
"Result #{self.inspect.to_s}"
end
end
end | mit |
patricksrobertson/simple-mde | addon/utils/default-toolbar.js | 149 | export default ["bold", "italic", "|", "heading-1", "heading-2", "heading-3", "|", "unordered-list", "ordered-list", "|", "link", "horizontal-rule"]; | mit |
abhishekkr/j | minified/j_httpget.js | 127 | function getUrlVars(){var e={};var t=window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,function(t,n,r){e[n]=r});return e}
| mit |
Zokerus/Tameran | Tameran/Hydro/Graphics/2D/Texture.cpp | 6470 | #include "Texture.h"
#include <exception>
Hydro::Texture::Texture(ID3D11Device* _device, ID3D11DeviceContext* _deviceContext, std::string _fileName, Rectangle& _srcRect)
: pTargaData(nullptr), width(0), height(0), pTexture(nullptr), pTextureView(nullptr)
{
//Load the targa image data into memory
if (!LoadTarga(_fileName, width, height, _srcRect))
{
throw std::exception(("Failed to load texture data: " + _fileName).c_str());
}
if (!Initialize(_device, _deviceContext, _fileName))
{
throw std::exception(("Failed to create Texture2D: " + _fileName).c_str());
}
}
Hydro::Texture::Texture(ID3D11Device* _device, ID3D11DeviceContext* _deviceContext, std::string _fileName)
: pTargaData(nullptr), width(0), height(0), pTexture(nullptr), pTextureView(nullptr)
{
//Load the targa image data into memory
if (!LoadTarga(_fileName, width, height, Rectangle()))
{
throw std::exception(("Failed to load texture data: " + _fileName).c_str());
}
if (!Initialize(_device, _deviceContext, _fileName))
{
throw std::exception(("Failed to create Texture2D: " + _fileName).c_str());
}
}
Hydro::Texture::~Texture()
{
// Release the texture view resource.
if (pTextureView)
{
pTextureView->Release();
pTextureView = nullptr;
}
// Release the texture.
if (pTexture)
{
pTexture->Release();
pTexture = nullptr;
}
// Release the targa data.
if (pTargaData)
{
delete[] pTargaData;
pTargaData = nullptr;
}
}
ID3D11ShaderResourceView* Hydro::Texture::GetTexture()
{
return pTextureView;
}
int Hydro::Texture::GetTextureWidth() const
{
return width;
}
int Hydro::Texture::GetTextureHeight() const
{
return height;
}
bool Hydro::Texture::Initialize(ID3D11Device * _device, ID3D11DeviceContext * _deviceContext, std::string _fileName)
{
D3D11_TEXTURE2D_DESC textureDesc;
HRESULT hResult;
unsigned int rowPitch;
D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
// Setup the description of the texture.
textureDesc.Height = height;
textureDesc.Width = width;
textureDesc.MipLevels = 3;
textureDesc.ArraySize = 4;
textureDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
textureDesc.SampleDesc.Count = 1;
textureDesc.SampleDesc.Quality = 0;
textureDesc.Usage = D3D11_USAGE_DEFAULT;
textureDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET;
textureDesc.CPUAccessFlags = 0;
textureDesc.MiscFlags = D3D11_RESOURCE_MISC_GENERATE_MIPS;
// Create the empty texture.
hResult = _device->CreateTexture2D(&textureDesc, NULL, &pTexture);
if (FAILED(hResult))
{
return false;
}
// Set the row pitch of the targa image data.
rowPitch = (width * 4) * sizeof(unsigned char);
// Copy the targa image data into the texture.
_deviceContext->UpdateSubresource(pTexture, 0, NULL, pTargaData, rowPitch, 0);
// Setup the shader resource view description.
srvDesc.Format = textureDesc.Format;
srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
srvDesc.Texture2D.MostDetailedMip = 0;
srvDesc.Texture2D.MipLevels = -1;
// Create the shader resource view for the texture.
hResult = _device->CreateShaderResourceView(pTexture, &srvDesc, &pTextureView);
if (FAILED(hResult))
{
return false;
}
// Generate mipmaps for this texture.
_deviceContext->GenerateMips(pTextureView);
// Release the targa image data now that the image data has been loaded into the texture.
delete[] pTargaData;
pTargaData = nullptr;
return true;
}
bool Hydro::Texture::LoadTarga(std::string fileName, int& width, int& height, Rectangle& _srcRect)
{
int error, bpp, srcImageSize, dstImageSize, index, i, j, k;
FILE *filePtr;
unsigned int count;
TargaHeader targaHeader;
unsigned char* targaImage;
int _height, _width;
//Open the targa file for reading in binary
error = fopen_s(&filePtr, fileName.c_str(), "rb");
if (error != 0)
return false;
//Read in the file header
count = (unsigned int)fread(&targaHeader, sizeof(TargaHeader), 1, filePtr);
if (count != 1)
return false;
//temporary storage for loops
_height = (int)targaHeader.height;
_width = (int)targaHeader.width;
if (_srcRect.GetWidth() <= 0 || _srcRect.GetHeight() <= 0)
{
//Get the important information from the header
height = (int)targaHeader.height;
width = (int)targaHeader.width;
bpp = (int)targaHeader.bpp;
}
else if (_srcRect.GetWidth() > 0 && _srcRect.GetHeight() > 0)
{
//Get the important information from the header
height = _srcRect.GetHeight();
width = _srcRect.GetWidth();
bpp = (int)targaHeader.bpp;
if ((int)targaHeader.height < height || (int)targaHeader.width < width)
{
return false;
}
if (_srcRect.GetXPos() < 0 && _srcRect.GetXPos() >= _width && _srcRect.GetYPos() < 0 && _srcRect.GetYPos() >= height)
{
//Rectangle is out og boundaries
return false;
}
}
//Check that it is 32 bit and not 24 bit
if (bpp != 32)
{
return false;
}
//Calculate the size of the 32 bit image data
srcImageSize = _width * _height * 4;
dstImageSize = width * height * 4;
//Allocate memomry for the targa image data
targaImage = new unsigned char[srcImageSize];
if (!targaImage)
{
return false;
}
//Read in the targa image
count = (unsigned int)fread(targaImage, 1, srcImageSize, filePtr);
if (count != srcImageSize)
{
return false;
}
//Close the file
error = fclose(filePtr);
if (error != 0)
{
return false;
}
//Allocate memory for the targa destination data
pTargaData = new unsigned char[dstImageSize];
if (!pTargaData)
return false;
//Initialize the index into the targa destination data array
index = 0;
// Initialize the index into the targa image data.
k = ((_height - _srcRect.GetYPos() - 1) * _width * 4) + _srcRect.GetXPos() * 4;
// Now copy the targa image data into the targa destination array in the correct order since the targa format is stored upside down.
for (j = 0; j < height; j++)
{
for (i = 0; i < width; i++)
{
pTargaData[index + 0] = targaImage[k + 2]; // Red.
pTargaData[index + 1] = targaImage[k + 1]; // Green.
pTargaData[index + 2] = targaImage[k + 0]; // Blue
pTargaData[index + 3] = targaImage[k + 3]; // Alpha
// Increment the indexes into the targa data.
k += 4;
index += 4;
}
// Set the targa image data index back to the preceding row at the beginning of the column since its reading it in upside down.
k -= (_width + width) * 4;
}
// Release the targa image data now that it was copied into the destination array.
delete[] targaImage;
targaImage = nullptr;
return true;
}
| mit |
aditigoel23/React-Car-App | app/containers/HomePage/index.js | 903 | /*
* HomePage
*
* This is the first thing users see of our App, at the '/' route
* For now this will just render the needed 2 columns with the nav and the content areas.
* Eventually main content would be where diff contents get loaded based on routes.
*
* NOTE: while this component should technically be a stateless functional
* component (SFC), hot reloading does not currently support SFCs. If hot
* reloading is not a necessity for you then you can refactor it and remove
* the linting exception.
*/
import React from 'react';
import ColumnLayout from './ColumnLayout';
import SideNav from './sideNav';
import MainContent from './mainContent';
export default class HomePage extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function
render() {
return (
<ColumnLayout>
<SideNav />
<MainContent />
</ColumnLayout>
);
}
}
| mit |
asiboro/asiboro.github.io | vsdoc/toc--/topic_00000000000009B5.html.js | 389 | var breadcrumbs=[['-1',"",""],['2',"SOLUTION-WIDE PROPERTIES Reference","topic_0000000000000C16.html"],['2851',"Tlece.Recruitment.Models.Subscriptions Namespace","topic_00000000000009A3.html"],['2866',"SubscriptionsDto Class","topic_00000000000009B1.html"],['2867',"Properties","topic_00000000000009B1_props--.html"],['2873',"PurchasedDescription Property","topic_00000000000009B5.html"]]; | mit |
jdt/EID.Wrapper | Source/EID.Wrapper/Pkcs11/Delegates/C_DigestFinal.cs | 313 |
using System;
using Net.Sf.Pkcs11.Wrapper;
namespace Net.Sf.Pkcs11.Delegates
{
[System.Runtime.InteropServices.UnmanagedFunctionPointerAttribute(System.Runtime.InteropServices.CallingConvention.Cdecl)]
internal delegate CKR C_DigestFinal(
uint hSession,
byte[] pDigest,
ref uint pulDigestLen
);
}
| mit |
lholota/LH.TestObjects | LH.TestObjects.Tests/Compare/WhenComparingPrimitiveTypes.cs | 1817 | namespace LH.TestObjects.Tests.Compare
{
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Linq.Expressions;
using FluentAssertions;
using Microsoft.CSharp.RuntimeBinder;
using NUnit.Framework;
using TestObjects.Compare;
[TestFixture]
public class WhenComparingPrimitiveTypes
{
[Test]
public void ThenShouldPassWhenComparingTwoEqualStrings()
{
var comparator = Extensions.CreateComparator<string>();
var result = comparator.Compare("AAA", "AAA");
result.AreSame.Should().BeTrue();
}
[Test]
public void ThenShouldFailWhenComparingTwoDifferentStrings()
{
var comparator = Extensions.CreateComparator<string>();
var result = comparator.Compare("AAA", "BBB");
result.AreSame.Should().BeFalse();
result.Differences.Single().PropertyPath.Should().BeNullOrEmpty();
}
[Test]
public void ThenShouldSucceedIfCollectionsAreEqual()
{
var objA = new[] {"AAA", "BBB"};
var objB = new[] {"AAA", "BBB"};
var comparator = new ObjectComparator<string[]>();
var result = comparator.Compare(objA, objB);
result.AreSame.Should().BeTrue();
}
[Test]
public void ThenShouldSucceedIfCollectionsDiffer()
{
var objA = new[] { "AAA", "BBB" };
var objB = new[] { "AAA", "CCC" };
var comparator = new ObjectComparator<string[]>();
var result = comparator.Compare(objA, objB);
result.AreSame.Should().BeFalse();
result.Differences.Single().PropertyPath.Should().Be("[1]");
}
}
}
| mit |
GordonSmith/dagre | test/order/initOrder-test.js | 1459 | var assert = require('../assert'),
initOrder = require('../../lib/order/initOrder'),
CDigraph = require('graphlib').CDigraph;
describe('initOrder', function() {
var g;
beforeEach(function() {
g = new CDigraph();
g.graph({});
});
it('sets order to 0 for the node in a singleton graph', function() {
g.addNode(1, { rank: 0 });
initOrder(g);
assert.equal(g.node(1).order, 0);
});
it('sets order to 0 to nodes on multiple single-node layers', function() {
g.addNode(1, { rank: 0 });
g.addNode(2, { rank: 1 });
g.addNode(3, { rank: 2 });
initOrder(g);
assert.equal(g.node(1).order, 0);
assert.equal(g.node(2).order, 0);
assert.equal(g.node(3).order, 0);
});
it('incrementally sets the order position for nodes on the same rank', function() {
g.addNode(1, { rank: 0 });
g.addNode(2, { rank: 0 });
g.addNode(3, { rank: 0 });
initOrder(g);
// There is no guarantee about what order gets assigned to what node, but
// we can assert that the order values 0, 1, 2 were assigned.
assert.sameMembers(g.nodes().map(function(u) { return g.node(u).order; }),
[0, 1, 2]);
});
it('does not assign order to subgraphs', function() {
g.addNode(1, { rank: 0 });
g.addNode(2, { rank: 0 });
g.addNode('sg1', {});
g.parent(1, 'sg1');
g.parent(2, 'sg1');
initOrder(g);
assert.notProperty(g.node('sg1'), 'order');
});
});
| mit |
KJSCE-C12/VDOC | Source/Cloud/VDOC/Depends/Models/Resources/CloudletServer.py | 1734 | from google.appengine.ext import db
from ApplicationServer import ApplicationServer
class CloudletServer(db.Model):
DomainName = db.StringProperty(required=True)
IPAddress = db.StringProperty(required=True)
secretKey = db.ByteStringProperty(required=True)
serverIV = db.ByteStringProperty(required=True)
def getApplicationServers(self):
lst = []
q =db.Query(ApplicationServer).filter("parentCloudlet =",self.key())
for p in q.run():
lst.append(p)
return lst
def getBestApplicationServerCandidate(self):
#TODO: Better Algorithm
return self.getApplicationServers()[0]
def getDiskImageFromCloudlet(self, cloudletServer):
#TODO: Command Cloudlet to shift disk image
print "Empty Method"
def validateAndStore(self):
q = db.Query(CloudletServer)
q.filter("IPAddress =", self.IPAddress)
if q.count() != 0:
return False
self.put()
return True
@classmethod
def createCloudlet(cls,DomainName, IPAddress, secretKey, serverIV):
cloudlet = CloudletServer(DomainName=DomainName, IPAddress=IPAddress,secretKey=secretKey,serverIV=serverIV)
print 'Hello {0}'.format(cloudlet.DomainName)
if not cloudlet.validateAndStore():
return None
return cloudlet
@classmethod
def getCloudletServerByDomainName(cls,name):
return db.Query(CloudletServer).filter("DomainName =",name).get()
@classmethod
def getBestCloudletServerCandidate(cls):
#TODO: Better Algorithm
return db.Query(CloudletServer).get()
@classmethod
def isAllocationPossible(cls,cloudletServer):
return True
@classmethod
def shiftDiskImageToCloudletServer(cls,diskImage, cloudletServer):
cloudletServer.getDiskImageFromCloudlet(diskImage.locations[0])
diskImage.addLocation(cloudletServer)
return True | mit |
romanoide/tumblrwave | utils/colors.js | 886 | var fs = require('fs');
var request = require('request');
var color = require('dominant-color')
// Or with cookies
// var request = require('request').defaults({jar: true});
module.exports= function(yyz, next){
var url = yyz["miniature_link"];
var filename =url.substring(url.lastIndexOf('/')+1)
var imagepath ="./public/tmp/"+filename;
request.get({url: url, encoding: 'binary'}, function (err, response, body) {
fs.writeFile(imagepath, body, 'binary', function(err) {
if(err)
console.log(err);
else{
//console.log(filename)
color(imagepath, function(err, color){
// hex color by default
if(err){
console.log(err)
}
else{
//console.log(color) // '5b6c6e'
//yyz["color"]= color;
next(color);
}
})
}
});
});
console.log('fin de proceso de colores');
}; | mit |
simon-wh/PAYDAY-2-BeardLib-Editor | mods/BeardLib-Editor/Classes/Map/PortalLayerEditor.lua | 11752 | PortalLayerEditor = PortalLayerEditor or class(LayerEditor)
local PortalLayer = PortalLayerEditor
function PortalLayer:init(parent)
self:init_basic(parent, "PortalLayerEditor")
self._menu = parent._holder
MenuUtils:new(self)
self._created_units = {}
self._portal_shape_unit = "core/units/portal_shape/portal_shape"
end
function PortalLayer:loaded_continents()
PortalLayer.super.loaded_continents(self)
for _, portal in pairs(clone(managers.portal:unit_groups())) do
for _, shape in pairs(portal._shapes) do
self:do_spawn_unit(self._portal_shape_unit, {position = shape:position(), rotation = shape:rotation(), shape = shape, portal = portal})
end
end
end
function PortalLayer:reset()
self._selected_portal = nil
self._selected_shape = nil
self:select_shape()
end
function PortalLayer:selected_portal()
return self._selected_portal
end
function PortalLayer:set_selected_unit()
local unit = self:selected_unit()
if not alive(unit) or unit:name() ~= self._portal_shape_unit:id() then
self._selected_shape = nil
self:select_shape()
end
for k, unit in ipairs(clone(self._created_units)) do
if not alive(unit) then
table.remove(self._created_units, k)
end
end
end
function PortalLayer:save()
local data = self._parent:data()
if data then
data.portal.unit_groups = managers.portal:save_level_data()
end
end
function PortalLayer:do_spawn_unit(unit_path, ud)
local unit = World:spawn_unit(unit_path:id(), ud.position or Vector3(), ud.rotation or Rotation())
table.merge(unit:unit_data(), ud)
ud = unit:unit_data()
ud.name = unit_path
ud.portal_shape_unit = true
ud.position = unit:position()
ud.rotation = unit:rotation()
table.insert(self._created_units, unit)
if alive(unit) then
if unit:name() == self._portal_shape_unit:id() then
local shape = ud.shape or ud.portal:add_shape({})
shape:set_unit(unit)
ud.shape = shape
end
end
end
function PortalLayer:is_my_unit(unit)
if unit == self._portal_shape_unit:id() then
return true
end
return false
end
function PortalLayer:delete_unit(unit)
local ud = unit:unit_data()
table.delete(self._created_units, unit)
if ud then
if unit:name() == self._portal_shape_unit:id() then
ud.portal:remove_shape(ud.shape)
self:load_portal_shapes()
self:save()
end
end
self:save()
end
function PortalLayer:build_menu()
self:Group("Portals")
self:Group("Shapes")
self:Group("Units")
self:load_portals()
self:save()
end
function PortalLayer:build_unit_menu()
local S = self:GetPart("static")
S._built_multi = false
S.super.build_default_menu(S)
local unit = self:selected_unit()
if alive(unit) then
S:build_positions_items(true)
S:update_positions()
S:Button("CreatePrefab", ClassClbk(S, "add_selection_to_prefabs"), {group = S:GetItem("QuickButtons")})
S:SetTitle("Portal Shape Selection")
if unit:name() == self._portal_shape_unit:id() then
unit:unit_data().shape:create_panel(S)
end
for i, shape in pairs(self._selected_portal._shapes) do
if shape == unit:unit_data().shape then
self:GetItem("shape_"..tostring(i)):RunCallback()
break
end
end
end
end
function PortalLayer:update(t, dt)
local portal = self._selected_portal
if portal then
local r, g, b = portal._r, portal._g, portal._b
self._brush:set_color(Color(0.25, r, g, b))
for unit_id in pairs(portal._ids) do
local unit = managers.worlddefinition:get_unit(unit_id)
if alive(unit) then
self._brush:unit(unit)
end
end
for _, shape in pairs(portal._shapes) do
shape:draw(t, dt, 1, self._selected_shape == shape and 0 or 1,1)
end
end
for _, unit in pairs(self._created_units) do
if alive(unit) then
unit:set_enabled(unit:unit_data().portal == portal)
else
table.remove(self._created_units, unit)
break
end
end
end
function PortalLayer:select_shape(item)
if self._selected_portal then
for i=1, #self._selected_portal._shapes do
self._menu:GetItem("shape_" .. tostring(i)):SetBorder({left = false})
end
self._selected_shape = item and self._selected_portal._shapes[tonumber(item.id)]
end
if self._selected_shape and self:selected_unit() ~= self._selected_shape:unit() then
self:GetPart("static"):set_selected_unit(self._selected_shape:unit())
end
if item then
item:SetBorder({left = true})
end
self:save()
end
function PortalLayer:load_portal_units()
local units = self._menu:GetItem("Units")
units:ClearItems()
if self._selected_portal then
for unit_id, _ in pairs(self._selected_portal._ids) do
local unit = managers.worlddefinition:get_unit(unit_id)
if unit then
local btn = self:Button(unit_id, function() managers.editor:select_unit(unit) end, {text = string.format("%s[%s]", unit:unit_data().name_id, unit_id), group = units})
btn:ImgButton("Remove", ClassClbk(self, "remove_unit_from_portal"), nil, {184, 2, 48, 48}, {highlight_color = Color.red})
end
end
end
end
function PortalLayer:remove_unit_from_portal(unit, no_refresh)
self._selected_portal:add_unit_id(unit)
if not no_refresh then
self:load_portal_units()
end
end
function PortalLayer:rename_portal(item)
BeardLibEditor.InputDialog:Show({title = "Rename portal to", text = item.parent.text, callback = function(name)
if name == "" then
BeardLibEditor.Dialog:Show({title = "ERROR!", message = "Portal name cannot be empty!", callback = function()
self:rename_portal(item)
end})
return
elseif string.begins(name, " ") then
BeardLibEditor.Dialog:Show({title = "ERROR!", message = "Invalid name", callback = function()
self:rename_portal(item)
end})
return
elseif managers.portal:unit_groups()[name] then
BeardLibEditor.Dialog:Show({title = "ERROR!", message = "Portal with that name already exists!", callback = function()
self:add_portal(name)
end})
return
end
managers.portal:rename_unit_group(item.parent.text, name)
self:load_portals()
self:save()
end})
end
function PortalLayer:remove_portal(item)
BeardLibEditor.Utils:YesNoQuestion("This will remove the portal", function()
managers.portal:remove_unit_group(item.parent.text)
self:load_portals()
self:save()
end)
end
function PortalLayer:remove_shape(item)
BeardLibEditor.Utils:YesNoQuestion("This will remove the portal shape", function()
if self._selected_shape == self._selected_portal._shapes[tonumber(item.parent.id)] then
self._selected_shape = nil
end
self._selected_portal:remove_shape(self._selected_portal._shapes[tonumber(item.parent.id)])
self:load_portal_shapes()
self:save()
end)
end
function PortalLayer:add_portal(name)
BeardLibEditor.InputDialog:Show({title = "Portal name", text = type(name) == "string" and name or "group", callback = function(name)
if name == "" then
BeardLibEditor.Dialog:Show({title = "ERROR!", message = "Portal name cannot be empty!", callback = function()
self:add_portal(name)
end})
return
elseif string.begins(name, " ") then
BeardLibEditor.Dialog:Show({title = "ERROR!", message = "Invalid name", callback = function()
self:add_portal(name)
end})
return
elseif managers.portal:unit_groups()[name] then
BeardLibEditor.Dialog:Show({title = "ERROR!", message = "Portal with that name already exists!", callback = function()
self:add_portal(name)
end})
return
end
managers.portal:add_unit_group(name)
self:load_portals()
end})
self:save()
end
function PortalLayer:refresh()
if self._parent._current_layer == "portal" and self._selected_portal then
self:load_portal_shapes()
self:load_portal_units()
self:select_shape()
end
end
function PortalLayer:select_portal(name, nounselect, noswitch)
if noswitch ~= true then
self._parent:Switch()
end
if self._parent._current_layer ~= "portal" then
self._parent:build_menu("portal", self) --TODO: change to less dumb
end
self._selected_shape = nil
self._menu:GetItem("Shapes"):ClearItems()
self._menu:GetItem("Units"):ClearItems()
if self._selected_portal then
self._menu:GetItem("portal_"..self._selected_portal._name):SetBorder({left = false})
end
if self._selected_portal and self._selected_portal._name == name and nounselect ~= true then
self._selected_portal = nil
else
self._menu:GetItem("portal_"..name):SetBorder({left = true})
self._selected_portal = managers.portal:unit_groups()[name]
self:load_portal_shapes()
self:load_portal_units()
end
self:select_shape()
self:save()
end
function PortalLayer:clbk_select_portal(item)
self:select_portal(item.text)
end
function PortalLayer:load_portal_shapes()
local group = self._menu:GetItem("Shapes")
if group then
group:ClearItems()
self:Button("NewShape", ClassClbk(self, "add_shape"), {group = group, label = "Shapes"})
for i=1, #self._selected_portal._shapes do
local btn = self:Button("shape_" .. tostring(i), ClassClbk(self, "select_shape"), {group = group})
btn.id = i
btn:ImgButton("Remove", ClassClbk(self, "remove_shape"), nil, {184, 2, 48, 48}, {highlight_color = Color.red})
end
end
end
function PortalLayer:add_shape()
self:do_spawn_unit(self._portal_shape_unit, {position = managers.editor:GetSpawnPosition(), portal = self._selected_portal})
self:load_portal_shapes()
self:save()
end
function PortalLayer:load_portals()
local portals = self:GetItem("Portals")
if portals then
portals:ClearItems()
self:Button("NewPortal", ClassClbk(self, "add_portal"), {group = portals})
for name, portal in pairs(managers.portal:unit_groups()) do
local prtl = self:Button("portal_"..portal._name, ClassClbk(self, "clbk_select_portal"), {group = portals, text = portal._name})
prtl:ImgButton("Remove", ClassClbk(self, "remove_portal"), nil, {184, 2, 48, 48}, {highlight_color = Color.red})
prtl:ImgButton("Rename", ClassClbk(self, "rename_portal"), nil, {66, 1, 48, 48})
prtl:ImgButton("AutoFillUnits", ClassClbk(self, "auto_fill_portal"), nil, {122, 1, 48, 48})
end
end
end
function PortalLayer:auto_fill_portal(item)
local portal = managers.portal:unit_groups()[item.parent.text]
BeardLibEditor.Utils:YesNoQuestion("This will automatically fill the portal with units", function()
for _, unit in pairs(managers.worlddefinition._all_units) do
if alive(unit) and unit:visible() and not unit:unit_data().only_visible_in_editor and not unit:unit_data().only_exists_in_editor and not portal:unit_in_group(unit) and portal:inside(unit:position()) then
portal:add_unit_id(unit)
end
end
self:load_portal_units()
self:save()
end)
end | mit |
huseyinozyilmaz/automated-acceptance-tests-quickstart | src/test/java/org/huseyin/bdd/config/webdriver/WebDriverFactory.java | 3789 | package org.huseyin.bdd.config.webdriver;
import static java.lang.String.format;
import static java.lang.System.getProperty;
import static java.util.Arrays.stream;
import static java.util.stream.Collectors.toList;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import java.io.File;
final class WebDriverFactory {
private static String OS = System.getProperty("os.name").toLowerCase();
private WebDriverFactory() {
}
static WebDriver create() {
String chromeDriver = getProperty("webdriver.chrome.driver");
String webDriverProperty = getProperty("webdriver");
if (webDriverProperty == null || webDriverProperty.isEmpty()) {
webDriverProperty = "CHROME";
}
if (chromeDriver == null || chromeDriver.isEmpty()) {
File driverDirectory = new File("node_modules/chromedriver/lib/chromedriver/chromedriver");
//chromeDriver = String.join(File.separator, resourcesDirectory.getAbsolutePath(), "chromedriver");
chromeDriver = driverDirectory.getAbsolutePath();
if (isWindows()) {
chromeDriver = String.join(".", chromeDriver, "exe");
}
System.setProperty("webdriver.chrome.driver", chromeDriver);
}
try {
return Drivers.valueOf(webDriverProperty.toUpperCase()).newDriver();
} catch (IllegalArgumentException e) {
String msg = format("The webdriver system property '%s' did not match any " +
"existing browser or the browser was not supported on your operating system. " +
"Valid values are %s",
webDriverProperty, stream(Drivers
.values())
.map(Enum::name)
.map(String::toLowerCase)
.collect(toList()));
throw new IllegalStateException(msg, e);
}
}
static boolean isWindows() {
return (OS.contains("win"));
}
static boolean isMac() {
return (OS.contains("mac"));
}
private enum Drivers {
FIREFOX {
@Override
public WebDriver newDriver() {
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
return new FirefoxDriver(capabilities);
}
}, CHROME {
@Override
public WebDriver newDriver() {
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
ChromeOptions options = new ChromeOptions();
options.addArguments("disable-infobars");
options.addArguments("start-maximized");
options.addArguments("disable-extensions");
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
return new ChromeDriver(capabilities);
}
}, IE {
@Override
public WebDriver newDriver() {
DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
return new InternetExplorerDriver(capabilities);
}
}, EDGE {
@Override
public WebDriver newDriver() {
DesiredCapabilities capabilities = DesiredCapabilities.edge();
return new EdgeDriver(capabilities);
}
};
public abstract org.openqa.selenium.WebDriver newDriver();
}
}
| mit |
Supertext/SuperScript.JavaScript | Configuration/Classes/CallElement.cs | 1078 | using System;
using System.Configuration;
namespace SuperScript.JavaScript.Configuration
{
public class CallElement : DeclarationElement
{
private static readonly ConfigurationProperty ParametersElement = new ConfigurationProperty("parameters", typeof (ParametersCollection), null, ConfigurationPropertyOptions.None);
[ConfigurationProperty("comment", IsRequired = false)]
public string Comment
{
get { return (String) this["comment"]; }
}
[ConfigurationProperty("emitterKey", IsRequired = false)]
public string EmitterKey
{
get { return (string) this["emitterKey"]; }
}
[ConfigurationProperty("functionName", IsRequired = true)]
public string FunctionName
{
get { return (string) this["functionName"]; }
}
[ConfigurationProperty("parameters", IsRequired = false)]
public ParametersCollection Parameters
{
get { return (ParametersCollection) this[ParametersElement]; }
}
}
} | mit |
jjenki11/blaze-chem-rendering | qca_designer/lib/pnetlib-0.8.0/runtime/System/Security/Permissions/UrlIdentityPermissionAttribute.cs | 2131 | /*
* UrlIdentityPermissionAttribute.cs - Implementation of the
* "System.Security.Permissions.UrlIdentityPermissionAttribute" class.
*
* Copyright (C) 2003 Southern Storm Software, Pty Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace System.Security.Permissions
{
#if CONFIG_POLICY_OBJECTS && CONFIG_PERMISSIONS && !ECMA_COMPAT
using System;
using System.Security;
[AttributeUsage(AttributeTargets.Assembly |
AttributeTargets.Class |
AttributeTargets.Struct |
AttributeTargets.Constructor |
AttributeTargets.Method,
AllowMultiple=true, Inherited=false)]
public sealed class UrlIdentityPermissionAttribute
: CodeAccessSecurityAttribute
{
// Internal state.
private String url;
// Constructors.
public UrlIdentityPermissionAttribute(SecurityAction action)
: base(action)
{
// Nothing to do here.
}
// Get or set the site value.
public String Url
{
get
{
return url;
}
set
{
url = value;
}
}
// Create a permission object that corresponds to this attribute.
public override IPermission CreatePermission()
{
if(Unrestricted || url == null)
{
throw new ArgumentException(_("Arg_PermissionState"));
}
else
{
return new UrlIdentityPermission(url);
}
}
}; // class UrlIdentityPermissionAttribute
#endif // CONFIG_POLICY_OBJECTS && CONFIG_PERMISSIONS && !ECMA_COMPAT
}; // namespace System.Security.Permissions
| mit |
mattmilburn/wp-bootstrap | theme/category.php | 2232 | <?php get_header(); ?>
<div class="page-main">
<div class="page-title">
<div class="container">
<h1>Categories</h1>
</div>
</div>
<div class="inner">
<div class="container">
<?php if (have_posts()): ?>
<div class="posts">
<?php while (have_posts()): the_post(); ?>
<div class="post">
<div class="post-inner">
<div class="post-thumbnail">
<a href="<?php the_permalink(); ?>" title="Read More">
<?php the_post_thumbnail('medium'); ?>
</a>
</div>
<h3 class="post-title">
<a href="<?php the_permalink(); ?>" title="Read More">
<?php the_title(); ?>
</a>
</h3>
<div class="post-author">By <?php the_author(); ?></div>
<div class="post-date">On <?php the_time('F jS, Y'); ?></div>
<div class="post-excerpt"><?php the_excerpt(); ?></div>
<div class="post-links">
<a href="<?php the_permalink(); ?>" class="btn btn-default post-permalink" title="Read More">Read More</a>
<a href="<?php comments_link(); ?>" class="post-comments-link" title="View Comments">
<?php comments_number(); ?>
</a>
</div>
</div>
</div>
<?php endwhile; ?>
</div>
<nav class="pager">
<?php pagination_bar(); ?>
</nav>
<?php else: ?>
<p><em>Sorry, no posts were found.</em></p>
<?php endif; ?>
</div>
</div>
</div>
<?php get_footer(); ?>
| mit |
Department-for-Work-and-Pensions/ClaimCapture | c3/test/views/OnHandlerNotFoundSpec.scala | 358 | package views
import org.specs2.mutable._
import utils.WithBrowser
class OnHandlerNotFoundSpec extends Specification {
section("unit")
"OnHandlerNotFound" should {
"show 404 page when user navigates to a bad URL" in new WithBrowser {
browser.goTo("/404")
browser.title mustEqual "This page can't be found"
}
}
section("unit")
}
| mit |
saulmadi/Encomiendas | src/Encomiendas.Web/Api/Modules/UserAccountModule.cs | 3597 | using System;
using System.Collections.Generic;
using System.Linq;
using AcklenAvenue.Commands;
using AutoMapper;
using Encomiendas.Domain.Application.Commands;
using Encomiendas.Domain.Entities;
using Encomiendas.Domain.Services;
using Nancy;
using Nancy.ModelBinding;
using Encomiendas.Web.Api.Infrastructure;
using Encomiendas.Web.Api.Requests;
using Encomiendas.Web.Api.Requests.Facebook;
using Encomiendas.Web.Api.Requests.Google;
namespace Encomiendas.Web.Api.Modules
{
public class UserAccountModule : NancyModule
{
public UserAccountModule(IReadOnlyRepository readOnlyRepository,ICommandDispatcher commandDispatcher, IPasswordEncryptor passwordEncryptor, IMappingEngine mappingEngine)
{
Post["/register"] =
_ =>
{
var req = this.Bind<NewUserRequest>();
var abilities = mappingEngine.Map<IEnumerable<UserAbilityRequest>, IEnumerable<UserAbility>>(req.Abilities);
commandDispatcher.Dispatch(this.UserSession(),
new CreateEmailLoginUser(req.Email, passwordEncryptor.Encrypt(req.Password), req.Name, req.PhoneNumber, abilities));
return null;
};
Post["/register/facebook"] =
_ =>
{
var req = this.Bind<FacebookRegisterRequest>();
commandDispatcher.Dispatch(this.UserSession(), new CreateFacebookLoginUser(req.id,req.email, req.first_name, req.last_name,req.link,req.name,req.url_image));
return null;
};
Post["/register/google"] =
_ =>
{
var req = this.Bind<GoogleRegisterRequest>();
commandDispatcher.Dispatch(this.UserSession(), new CreateGoogleLoginUser(req.id,req.email,req.name.givenName,req.name.familyName,req.url,req.displayName,req.image.url));
return null;
};
Post["/password/requestReset"] =
_ =>
{
var req = this.Bind<ResetPasswordRequest>();
commandDispatcher.Dispatch(this.UserSession(),
new CreatePasswordResetToken(req.Email) );
return null;
};
Put["/password/reset/{token}"] =
p =>
{
var newPasswordRequest = this.Bind<NewPasswordRequest>();
var token = Guid.Parse((string)p.token);
commandDispatcher.Dispatch(this.UserSession(),
new ResetPassword(token, passwordEncryptor.Encrypt(newPasswordRequest.Password)));
return null;
};
Post["/user/abilites"] = p =>
{
var requestAbilites = this.Bind<UserAbilitiesRequest>();
commandDispatcher.Dispatch(this.UserSession(), new AddAbilitiesToUser(requestAbilites.UserId, requestAbilites.Abilities.Select(x => x.Id)));
return null;
};
Get["/abilities"] = _ =>
{
var abilites = readOnlyRepository.GetAll<UserAbility>();
var mappedAbilites = mappingEngine.Map<IEnumerable<UserAbility>, IEnumerable<UserAbilityRequest>>(abilites);
return mappedAbilites;
};
}
}
} | mit |
silmunc1916/LEDcontrol-Android | app/src/main/java/wb/ledcontrol/OnFragReplaceListener.java | 1127 | package wb.ledcontrol;
import android.os.Bundle;
public interface OnFragReplaceListener {
public void OnFragReplace(int fragmentID, boolean toBackStack, Bundle data);
}
/*
Callback für's Wechseln der Fragments
int fragmentID: ID, welches Fragment gestartet werden soll. Die IDs sind in FAct_control definiert.
boolean toBackStack: wenn true: "fragmentTransaction.addToBackStack(null);" wird ausgeführt
man kann danach mit der BACK-Taste zum alten Fragment zurückspringen.
Ist das nicht gewünscht, muß false übergeben werden, dannn wird kein
.addToBackStack() ausgeführt.
Bundle data: Im Bundle können Daten übergeben werden, wenn zB. ein startActivityForResult() ersetzt werden soll.
Das Bundle muß dann in der FragmentActivity ausgewertet werden.
NICHT MEHR BENÖTIGT:
int containerID: ID des containers, in dem das alte Fragment enthalten ist, das durch das neue (fragmentID) ersetzt werden soll.
Die containerID kann im fragment folgendermaßen ermittelt werden:
int containerID = ((ViewGroup)getView().getParent()).getId();
oder einfach fcontainer.getId(), wenn bekannt
*/ | mit |
Phybbit/kinect-data-transmitter | DataConverter/Properties/AssemblyInfo.cs | 1402 | 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("DataConverter")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DataConverter")]
[assembly: AssemblyCopyright("Copyright © 2012")]
[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("33774843-291e-455d-9cb1-140b27ad7f53")]
// 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")]
| mit |
HerrB92/obp | OpenBeaconPackage/libraries/hibernate-release-4.2.7.SP1/project/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/RelatedAuditExpression.java | 2689 | /*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.envers.query.criteria;
import org.hibernate.envers.configuration.AuditConfiguration;
import org.hibernate.envers.entities.RelationDescription;
import org.hibernate.envers.exception.AuditException;
import org.hibernate.envers.query.property.PropertyNameGetter;
import org.hibernate.envers.reader.AuditReaderImplementor;
import org.hibernate.envers.tools.query.Parameters;
import org.hibernate.envers.tools.query.QueryBuilder;
/**
* @author Adam Warski (adam at warski dot org)
*/
public class RelatedAuditExpression implements AuditCriterion {
private final PropertyNameGetter propertyNameGetter;
private final Object id;
private final boolean equals;
public RelatedAuditExpression(PropertyNameGetter propertyNameGetter, Object id, boolean equals) {
this.propertyNameGetter = propertyNameGetter;
this.id = id;
this.equals = equals;
}
public void addToQuery(AuditConfiguration auditCfg, AuditReaderImplementor versionsReader, String entityName,
QueryBuilder qb, Parameters parameters) {
String propertyName = CriteriaTools.determinePropertyName( auditCfg, versionsReader, entityName, propertyNameGetter );
RelationDescription relatedEntity = CriteriaTools.getRelatedEntity(auditCfg, entityName, propertyName);
if (relatedEntity == null) {
throw new AuditException("This criterion can only be used on a property that is " +
"a relation to another property.");
} else {
relatedEntity.getIdMapper().addIdEqualsToQuery(parameters, id, null, equals);
}
}
} | mit |
XenonApp/xenon | js/fs/static.js | 2426 | 'use strict';
/**
* This module implements the read-only file system, essentially a simple
* way to serve files from folders from within the Zed application
*/
const fs = require('fs');
var http_cache = require("../lib/http_cache");
var fsUtil = require("./util");
module.exports = function(options) {
var root = options.url;
var readOnlyFn = options.readOnlyFn;
var api = {
listFiles: function() {
return http_cache.fetchUrl(root + "/all", {}).then(function(res) {
var items = res.split("\n");
for (var i = 0; i < items.length; i++) {
if (!items[i]) {
items.splice(i, 1);
i--;
}
}
return items;
});
},
readFile: function(path, binary) {
return new Promise(function(resolve, reject) {
fs.readFile(root + path, (err, data) => {
if (err) {
return reject(err);
}
if (!window.readOnlyFiles) {
window.readOnlyFiles = {};
}
if (readOnlyFn && readOnlyFn(path)) {
window.readOnlyFiles[path] = true;
}
let res;
if (binary) {
res = fsUtil.uint8ArrayToBinaryString(new Uint8Array(res));
} else {
res = data.toString();
}
resolve(res);
});
});
},
writeFile: function(path, content, binary) {
return Promise.reject(405); // Method not allowed
},
deleteFile: function(path) {
return Promise.reject(405); // Method not allowed
},
watchFile: function() {
// Nop
},
unwatchFile: function() {
// Nop
},
getCacheTag: function(path) {
return http_cache.fetchUrl(root + path, {}).then(function() {
return "unchanged";
}, function(err) {
console.log("Doesn't exist", path);
return Promise.reject(404);
});
},
getCapabilities: function() {
return {};
}
};
return api;
}
| mit |
MarcTowler/blog | includes/functions.php | 1484 | <?php
function slug($text){
// replace non letter or digits by -
$text = preg_replace('~[^\\pL\d]+~u', '-', $text);
// trim
$text = trim($text, '-');
// transliterate
$text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
// lowercase
$text = strtolower($text);
// remove unwanted characters
$text = preg_replace('~[^-\w]+~', '', $text);
if (empty($text))
{
return 'n-a';
}
return $text;
}
/**
* This function just checks referring sites/pages aka the visitors last page before coming to ours
*
* @param $current string URL of current page (the calling link)
* @param $title string the page's title for ease of viewing
* @return void
*/
function whereFrom($current, $title) {
global $db;
$referer = '';
//check that both are string before we go ahead
if(!is_string($current) || !is_string($title)) {
return;
}
//check referrer
if(!isset($_SERVER['HTTP_REFERER']) || !is_string($_SERVER['HTTP_REFERER']) || $_SERVER['HTTP_REFERER'] == '') {
$referer = 'Unknown - Referer not set';
} else {
$referer = $_SERVER['HTTP_REFERER'];
}
//prep query
$whe = $db->prepare("INSERT INTO blog_referer (page_title, page_url, referer_url, date_added) VALUES (:title, :cur, :referer, :dates)");
$whe->execute(array(
':title' => $title,
':cur' => $current,
':referer' => $referer,
':dates' => date("Y-m-d H:i:s")
));
}
?> | mit |
daviian/sd_googlemaps | Tests/Unit/Domain/Model/StyleTest.php | 3651 | <?php
namespace SD\SdGooglemaps\Tests\Unit\Domain\Model;
/**
* Test case.
*
* @author David Schneiderbauer <david.schneiderbauer@dschneiderbauer.me>
*/
class StyleTest extends \TYPO3\CMS\Core\Tests\UnitTestCase
{
/**
* @var \SD\SdGooglemaps\Domain\Model\Style
*/
protected $subject = null;
protected function setUp()
{
parent::setUp();
$this->subject = new \SD\SdGooglemaps\Domain\Model\Style();
}
protected function tearDown()
{
parent::tearDown();
}
/**
* @test
*/
public function getFeatureTypeReturnsInitialValueForString()
{
self::assertSame(
'',
$this->subject->getFeatureType()
);
}
/**
* @test
*/
public function setFeatureTypeForStringSetsFeatureType()
{
$this->subject->setFeatureType('Conceived at T3CON10');
self::assertAttributeEquals(
'Conceived at T3CON10',
'featureType',
$this->subject
);
}
/**
* @test
*/
public function getElementTypeReturnsInitialValueForString()
{
self::assertSame(
'',
$this->subject->getElementType()
);
}
/**
* @test
*/
public function setElementTypeForStringSetsElementType()
{
$this->subject->setElementType('Conceived at T3CON10');
self::assertAttributeEquals(
'Conceived at T3CON10',
'elementType',
$this->subject
);
}
/**
* @test
*/
public function getStylersReturnsInitialValueForStyler()
{
$newObjectStorage = new \TYPO3\CMS\Extbase\Persistence\ObjectStorage();
self::assertEquals(
$newObjectStorage,
$this->subject->getStylers()
);
}
/**
* @test
*/
public function setStylersForObjectStorageContainingStylerSetsStylers()
{
$styler = new \SD\SdGooglemaps\Domain\Model\Styler();
$objectStorageHoldingExactlyOneStylers = new \TYPO3\CMS\Extbase\Persistence\ObjectStorage();
$objectStorageHoldingExactlyOneStylers->attach($styler);
$this->subject->setStylers($objectStorageHoldingExactlyOneStylers);
self::assertAttributeEquals(
$objectStorageHoldingExactlyOneStylers,
'stylers',
$this->subject
);
}
/**
* @test
*/
public function addStylerToObjectStorageHoldingStylers()
{
$styler = new \SD\SdGooglemaps\Domain\Model\Styler();
$stylersObjectStorageMock = $this->getMockBuilder(\TYPO3\CMS\Extbase\Persistence\ObjectStorage::class)
->setMethods(['attach'])
->disableOriginalConstructor()
->getMock();
$stylersObjectStorageMock->expects(self::once())->method('attach')->with(self::equalTo($styler));
$this->inject($this->subject, 'stylers', $stylersObjectStorageMock);
$this->subject->addStyler($styler);
}
/**
* @test
*/
public function removeStylerFromObjectStorageHoldingStylers()
{
$styler = new \SD\SdGooglemaps\Domain\Model\Styler();
$stylersObjectStorageMock = $this->getMockBuilder(\TYPO3\CMS\Extbase\Persistence\ObjectStorage::class)
->setMethods(['detach'])
->disableOriginalConstructor()
->getMock();
$stylersObjectStorageMock->expects(self::once())->method('detach')->with(self::equalTo($styler));
$this->inject($this->subject, 'stylers', $stylersObjectStorageMock);
$this->subject->removeStyler($styler);
}
}
| mit |
california-civic-data-coalition/django-calaccess-processed-data | calaccess_processed_elections/managers/opencivicdata/elections/candidatecontests.py | 1856 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Custom managers for the OCD CandidateContest models.
"""
from __future__ import unicode_literals
from django.db.models import Q
from django.db import models
from postgres_copy import CopyQuerySet
class OCDCandidateContestQuerySet(CopyQuerySet):
"""
Custom helpers for the OCD CandidateContest model that limit it to runoffs.
"""
def set_parents(self):
"""
Connect and save parent contests for all runoffs.
"""
for obj in self.runoffs():
# Carve out for the duplicate 2010 Assembly 43 runoffs until
# I can figure out what I broke.
obj.runoff_for_contest = obj.get_parent()
obj.save()
def assembly(self):
"""
Filter to state assembly contests.
"""
return self.filter(division__subtype2='sldl')
def executive(self):
"""
Filter to executive contests.
"""
return self.filter(
Q(posts__post__organization__name='California State Executive Branch')
| Q(posts__post__organization__parent__name='California State Executive Branch')
)
def regular(self):
"""
Filter to "regular" contests.
"""
return self.filter(previous_term_unexpired=False)
def runoffs(self):
"""
Filter down to runoff CandidateContest instances.
"""
return self.filter(name__contains='RUNOFF')
def senate(self):
"""
Filter to state senate contests.
"""
return self.filter(division__subtype2='sldu')
def special(self):
"""
Filter to "special" contests.
"""
return self.filter(previous_term_unexpired=True)
OCDCandidateContestManager = models.Manager.from_queryset(OCDCandidateContestQuerySet)
| mit |
savageboy74/SavageCore | src/main/java/tv/savageboy74/savagecore/common/proxy/CommonProxy.java | 1380 | package tv.savageboy74.savagecore.common.proxy;
/*
* CommonProxy.java
* Copyright (C) 2014 - 2015 Savage - github.com/savageboy74
*
* 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.
*/
import net.minecraft.block.Block;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraftforge.fml.common.registry.GameRegistry;
public class CommonProxy
{
}
| mit |
mathewgrabau/shmotg | node_modules/d3/node_modules/jsdom/node_modules/cssstyle/lib/properties/pitchRange.js | 263 | 'use strict';
module.exports.definition = {
set: function (v) {
this.setProperty('pitch-range', v);
},
get: function () {
return this.getPropertyValue('pitch-range');
},
enumerable: true,
configurable: true
};
| mit |
jakewendt/phonify_string | test/phonify_string_test.rb | 2692 | require 'test/unit'
require 'rubygems'
require 'active_record'
$:.unshift "#{File.dirname(__FILE__)}/../lib"
require 'phonify_string'
ActiveRecord::Base.send(:extend, PhonifyString )
ActiveRecord::Base.establish_connection(:adapter => "sqlite3", :database => ":memory:")
def setup_db
ActiveRecord::Schema.define(:version => 1) do
create_table :users do |t|
t.string :name
t.string :phone
t.string :optional_phone
t.timestamps
end
user = User.create({:name => "Jake", :phone_number => '1234567890'})
end
end
def teardown_db
ActiveRecord::Base.connection.tables.each do |table|
ActiveRecord::Base.connection.drop_table(table)
end
end
class User < ActiveRecord::Base
phonify_string :phone, :required => true
phonify_string :optional_phone, :required => false
end
class PhonifyStringTest < Test::Unit::TestCase
def setup
setup_db
end
def teardown
teardown_db
end
def test_invalid_phone_1
u = User.first
u.update_attributes(:phone_number => "123")
assert u.errors.on(:phone_number)
assert u.changed?
assert u.phone == "123"
u = User.first
assert u.reload.phone == "(123)456-7890"
end
def test_invalid_phone_2
u = User.first
u.update_attributes(:phone_number => "")
assert u.errors.on(:phone_number)
assert u.changed?
assert u.reload.phone == "(123)456-7890"
end
def test_invalid_phone_3
u = User.first
u.update_attributes(:phone_number => "123 456 789")
assert u.errors.on(:phone_number)
assert u.changed?
assert u.reload.phone == "(123)456-7890"
end
def test_valid_phone_1
u = User.first
u.update_attributes(:phone_number => "0987654321")
assert !u.errors.on(:phone_number)
assert u.reload.phone == "(098)765-4321"
end
def test_valid_phone_2
u = User.create(:name => "Jakeb", :phone => "fakephone") # nothing to stop straight access
assert u.phone == "fakephone"
assert !u.errors.on(:phone_number)
assert !u.errors.on(:optional_phone_number)
u.update_attributes(:phone_number => "0987654321")
assert !u.errors.on(:phone_number)
assert u.reload.phone == "(098)765-4321"
end
def test_valid_phone_3
u = User.create(:name => "Jakeb", :phone => "fakephone") # nothing to stop straight access
assert u.phone == "fakephone"
assert !u.errors.on(:phone_number)
assert !u.errors.on(:optional_phone_number)
u.update_attributes(:optional_phone_number => "")
assert !u.errors.on(:optional_phone_number)
assert u.reload.optional_phone == ""
end
def test_valid_phone_4
u = User.create(:name => "Jakeb", :optional_phone_number => "fakephone")
assert u.optional_phone == "fakephone"
assert !u.errors.on(:phone_number)
assert u.errors.on(:optional_phone_number)
end
end
| mit |
inCodeSystemsNsk/frontend-boilerplate | shared/reducers/user.js | 258 | import { LOGIN, LOGOUT } from '../actions/user'
export default function user(state = null, action) {
switch (action.type) {
case LOGIN:
return { ...state, ...action.user }
case LOGOUT:
return null
default:
return state
}
}
| mit |
ebothmann/heppyplotlib | examples/ratioplot.py | 720 | #!/usr/bin/env python2
import heppyplotlib as hpl
import matplotlib.pyplot as plt
basenames = ["central", "up", "down"]
filepaths = [b + ".yoda" for b in basenames]
rivet_path = "/ANALYSIS/OBSERVABLE"
# plot envelope
combined = hpl.combine(filepaths, rivet_path, hpl.envelope_error)
axes_list = hpl.ratioplot([combined], rivet_path,
use_errorrects_for_legend=True,
labels=[r"envelope"])[0]
# plot central histogram again for statistical errors
hpl.ratioplot(filepaths[0], rivet_path,
axes_list=axes_list,
hatch=r"//",
use_errorrects_for_legend=True,
labels=["statistiscal errors"])
plt.savefig("plot.pdf")
| mit |
warren5236/OperationSyncTheDatabase | Tests/Bootstrap.php | 157 | <?php
require_once(getcwd() . '/OSTD/Autoloader/Autoloader.php');
use OSTD\Autoloader\Autoloader;
$autoloader = new Autoloader();
$autoloader->register(); | mit |
SolidEdgeCommunity/docs | docfx_project/snippets/SolidEdgePart.Split.Edit.cs | 1946 | using System.IO;
using System.Runtime.InteropServices;
internal static class Example
{
[STAThread()]
public static void Main()
{
SolidEdgeFramework.Application objApplication = null;
SolidEdgePart.PartDocument objPartDocument = null;
SolidEdgePart.Models objModels = null;
SolidEdgePart.Model objModel = null;
SolidEdgePart.Splits objSplits = null;
SolidEdgePart.Split objSplit = null;
object[] objTargetBodySplit = new object[6];
object[] objToolBodySplit = new object[6];
try
{
OleMessageFilter.Register();
objApplication = (SolidEdgeFramework.Application)Marshal.GetActiveObject("SolidEdge.Application");
objPartDocument = objApplication.ActiveDocument;
objModels = objPartDocument.Models;
objTargetBodySplit[0] = objModels.Item(1).Body;
objToolBodySplit[0] = objModels.Item(2).Body;
objModel = objModels.Item(1);
objSplits = objModel.Splits;
objSplit = objSplits.Add(1, objTargetBodySplit, 1, objToolBodySplit, SolidEdgePart.SETargetDesignBodyOption.igCreateMultipleDesignBodiesOnNonManifoldOption, SolidEdgePart.SETargetConstructionBodyOption.igCreateMultipleConstructionBodiesOnNonManifoldOption);
objModel.ExtrudedProtrusions.Item(2).RollToFeature();
objTargetBodySplit[0] = objModels.Item(1).Body;
objToolBodySplit[0] = objModels.Item(2).Body;
objSplit.Edit(1, objTargetBodySplit, 1, objToolBodySplit, SolidEdgePart.SETargetDesignBodyOption.igCreateMultipleDesignBodiesOnNonManifoldOption, SolidEdgePart.SETargetConstructionBodyOption.igCreateMultipleConstructionBodiesOnNonManifoldOption);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
OleMessageFilter.Revoke();
}
}
} | mit |
rockabox/rbx_ui_components | src/rb-canvas/index.js | 347 | define([
'./rb-canvas-directive',
'./rb-canvas.css'
], function (rbCanvasDirective, css) {
/**
* @ngdoc module
* @name rb-canvas
* @description
*
* rbCanvas
*
*/
var rbCanvas = angular
.module('rb-canvas', [])
.directive('rbCanvas', rbCanvasDirective);
return rbCanvas;
});
| mit |
bojanrajkovic/pingu | src/Pingu/Chunks/IhdrChunk.cs | 3836 | using System;
using System.Threading.Tasks;
using Pingu.Colors;
namespace Pingu.Chunks
{
public class IhdrChunk : Chunk
{
public override string Name => "IHDR";
public override int Length => 13;
public int Width { get; }
public int Height { get; }
public int BitDepth { get; }
// ColorType 6 is true color, with alpha, in RGBA order. 2 is true color, w/o alpha, RGB order.
public ColorType ColorType { get; }
// 0 is the only allowed method, meaning DEFLATE with a sliding window of no more than 32768 bytes
public byte CompressionMethod => 0;
// 0 is the only allowed filter method, adaptive filtering with 5 basic filter types.
public byte FilterMethod => 0;
// 0 and 1 are the only allowed interlace methods. 0 means no interlacing, 1 means Adam7
// interlacing.
public byte InterlaceMethod => 0;
// Our IHDR chunk will only have 3 fungible values, the rest are going to be hard-coded.
public IhdrChunk(int width, int height, int bitDepth, ColorType colorType)
{
if (width <= 0)
throw new ArgumentOutOfRangeException(nameof(width), "Width must be within the range of 1 to 2^31-1.");
if (height <= 0)
throw new ArgumentOutOfRangeException(nameof(height), "Height must be within the range of 1 to 2^31-1.");
if (!Enum.IsDefined (typeof (ColorType), colorType))
throw new ArgumentOutOfRangeException(nameof(colorType), $"Undefined color type {colorType}.");
if (bitDepth != 1 && bitDepth != 2 && bitDepth != 4 && bitDepth != 8 && bitDepth != 16)
throw new ArgumentException("Bit depth must be one of 1, 2, 4, 8, or 16.", nameof (bitDepth));
// Not all color types and bit depths can be combined.
switch (colorType) {
case ColorType.Indexed:
if (bitDepth != 1 && bitDepth != 2 && bitDepth != 4 && bitDepth != 8)
throw new Exception($"Bit depth {bitDepth} is not compatible with indexed color. " +
"Only bit depths of 1, 2, 4, and 8 are allowed.");
break;
case ColorType.GrayscaleAlpha:
if (bitDepth != 8 && bitDepth != 16)
throw new Exception($"Bit depth {bitDepth} is not compatible with grayscale color with alpha.");
break;
case ColorType.Truecolor:
if (bitDepth != 8 && bitDepth != 16)
throw new Exception($"Bit depth {bitDepth} is not compatible with true color.");
break;
case ColorType.TruecolorAlpha:
if (bitDepth != 8 && bitDepth != 16)
throw new Exception($"Bit depth {bitDepth} is not compatible with true color with alpha.");
break;
}
Width = width;
Height = height;
BitDepth = bitDepth;
ColorType = colorType;
}
protected override Task<byte[]> GetChunkDataAsync()
{
byte[] chunkData = new byte[13],
widthBytes = GetBytesForInteger(Width),
heightBytes = GetBytesForInteger(Height);
Buffer.BlockCopy(widthBytes, 0, chunkData, 0, widthBytes.Length);
Buffer.BlockCopy(heightBytes, 0, chunkData, 4, heightBytes.Length);
chunkData[8] = (byte) BitDepth;
chunkData[9] = (byte) ColorType;
chunkData[10] = CompressionMethod;
chunkData[11] = FilterMethod;
chunkData[12] = InterlaceMethod;
return Task.FromResult(chunkData);
}
}
}
| mit |
garethj-msft/msgraph-sdk-dotnet | src/Microsoft.Graph/Requests/Generated/WorkbookFunctionsGcdRequest.cs | 2945 | // ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
/// <summary>
/// The type WorkbookFunctionsGcdRequest.
/// </summary>
public partial class WorkbookFunctionsGcdRequest : BaseRequest, IWorkbookFunctionsGcdRequest
{
/// <summary>
/// Constructs a new WorkbookFunctionsGcdRequest.
/// </summary>
public WorkbookFunctionsGcdRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
this.ContentType = "application/json";
this.RequestBody = new WorkbookFunctionsGcdRequestBody();
}
/// <summary>
/// Gets the request body.
/// </summary>
public WorkbookFunctionsGcdRequestBody RequestBody { get; private set; }
/// <summary>
/// Issues the POST request.
/// </summary>
public System.Threading.Tasks.Task<WorkbookFunctionResult> PostAsync()
{
return this.PostAsync(CancellationToken.None);
}
/// <summary>
/// Issues the POST request.
/// </summary>
/// <param name=""cancellationToken"">The <see cref=""CancellationToken""/> for the request.</param>
/// <returns>The task to await for async call.</returns>
public System.Threading.Tasks.Task<WorkbookFunctionResult> PostAsync(
CancellationToken cancellationToken)
{
this.Method = "POST";
return this.SendAsync<WorkbookFunctionResult>(this.RequestBody, cancellationToken);
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookFunctionsGcdRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookFunctionsGcdRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
}
}
| mit |
jimlindstrom/xbrlware-extras | lib/xbrlware-extras/item.rb | 2355 | module Xbrlware
class ValueMapping
attr_accessor :policy
def initialize
@unknown_classifier = nil
@policy = { :credit => :no_action,
:debit => :no_action,
:unknown => :no_action } # FIXME: a classifier could be used here....
end
def value(name, defn, val)
# we ignore 'name' in this implementation
case @policy[defn]
when :no_action then val
when :flip then -val
end
end
end
class Item
def pretty_name
self.name.gsub(/([a-z])([A-Z])/, '\1 \2')
end
def write_constructor(file, item_name)
item_context_name = item_name + "_context"
if @context.nil?
file.puts "#{item_context_name} = nil"
else
@context.write_constructor(file, item_context_name)
end
file.puts "#{item_name} = Xbrlware::Factory.Item(:name => \"#{@name}\"," +
" :decimals => \"#{@decimals}\"," +
" :context => #{item_context_name}," +
" :value => \"#{@value}\")"
if !@def.nil? and !@def["xbrli:balance"].nil?
file.puts "#{item_name}.def = { } if #{item_name}.def.nil?"
file.puts "#{item_name}.def[\"xbrli:balance\"] = \"#{@def['xbrli:balance']}\""
end
end
def print_tree(indent_count=0)
output = "#{indent} #{@label}"
@items.each do |item|
period=item.context.period
period_str = period.is_duration? ? "#{period.value["start_date"]} to #{period.value["end_date"]}" : "#{period.value}"
output += " [#{item.def["xbrli:balance"]}]" unless item.def.nil?
output += " (#{period_str}) = #{item.value}" unless item.nil?
end
puts indent + output
@children.each { |child| child.print_tree(indent_count+1) }
end
def is_sub_leaf?
@context.entity.segment
end
def value(mapping=nil)
definition = case
when @def.nil? then :unknown
when @def["xbrli:balance"].nil? then :unknown
else @def["xbrli:balance"].to_sym
end
mapping = mapping || ValueMapping.new
return mapping.value(pretty_name, definition, @value.to_f)
end
end
end
| mit |
gehnster/nerdbot | Nerdbot/Utilities/Fortuna/Accumulator/Sources/CryptoServiceProvider.cs | 1999 | /* Fortuna
* By: smithc
* GitHub: https://github.com/smithc/Fortuna
* LICENSE:
* MIT License
Copyright (c) 2016 smithc
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using System;
using System.Security.Cryptography;
namespace Nerdbot.Utilities.Fortuna.Accumulator.Sources
{
public class CryptoServiceProvider : EntropyProviderBase, IDisposable
{
private readonly RandomNumberGenerator _cryptoService = RandomNumberGenerator.Create();
public override string SourceName => ".NET RNGCryptoServiceProvider";
protected override TimeSpan ScheduledPeriod => TimeSpan.FromMilliseconds(100);
protected override byte[] GetEntropy()
{
var randomData = new byte[32];
_cryptoService.GetBytes(randomData);
return randomData;
}
private bool _isDisposed;
public void Dispose()
{
if (_isDisposed) return;
_cryptoService?.Dispose();
_isDisposed = true;
}
}
}
| mit |
Symfony-Plugins/sfSympalPlugin | lib/plugins/sfSympalAdminPlugin/modules/sympal_content_menu_item/lib/Basesympal_content_menu_itemActions.class.php | 2039 | <?php
/**
* Base actions for the sfSympalPlugin sympal_content_menu_item module.
*
* @package sfSympalPlugin
* @subpackage sympal_content_menu_item
* @author Your name here
* @version SVN: $Id: BaseActions.class.php 12534 2008-11-01 13:38:27Z Kris.Wallsmith $
*/
abstract class Basesympal_content_menu_itemActions extends sfActions
{
public function preExecute()
{
parent::preExecute();
$this->getContext()->getEventDispatcher()->connect('admin.save_object', array($this, 'listenToAdminSaveObject'));
}
public function listenToAdminSaveObject(sfEvent $event)
{
$this->resetSympalRoutesCache();
}
public function executeIndex(sfWebRequest $request)
{
$this->content = $this->getRoute()->getObject();
$this->menuItem = $this->content->getMenuItem();
$this->menuItem->Site = $this->content->Site;
$this->getResponse()->setTitle(sprintf('Sympal Admin / Editing the "%s" Page Menu Item', (string) $this->content));
$this->form = new sfSympalMenuItemForm($this->menuItem);
$widgetSchema = $this->form->getWidgetSchema();
$widgetSchema['parent_id']->setOption('add_empty', '');
unset(
$this->form['id'],
$this->form['content_id'],
$this->form['groups_list'],
$this->form['permissions_list'],
$this->form['slug'],
$this->form['custom_path'],
$this->form['requires_auth'],
$this->form['requires_no_auth']
);
if ($this->menuItem->isNew())
{
$this->form->setDefault('name', $this->content->getTitle());
$this->form->setDefault('label', $this->content->getTitle());
}
if ($request->isMethod('post'))
{
$this->form->bind($request->getParameter($this->form->getName()));
if ($this->form->isValid())
{
$this->form->save();
// TODO redirect to the frontend when coming from there
$this->getUser()->setFlash('notice', 'Menu saved successfully!');
$this->redirect('@sympal_content_edit?id='.$this->content->id);
}
}
}
} | mit |